Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat: drag/drop entities + move/copy + fix canvas mention nodes (#1002)

gbirman885937081fed
diff --git a/js/app/packages/app/component/EntityModal/MoveToProjectView.tsx b/js/app/packages/app/component/EntityModal/MoveToProjectView.tsx
index 34e7e55e81..ec6a62cd1a 100644
--- a/js/app/packages/app/component/EntityModal/MoveToProjectView.tsx
+++ b/js/app/packages/app/component/EntityModal/MoveToProjectView.tsx
@@ -356,12 +356,9 @@ export const MoveToProjectView = (props: {
props.entity.type === 'chat' ||
props.entity.type === 'project'
) {
- // Find the project name for the toast message
- const projectName = selectedProject()?.name || 'Unknown Project';
-
await moveToProjectMutation.mutateAsync({
entity: props.entity,
- project: { id: projectId, name: projectName },
+ project: { id: projectId },
});
}
}
diff --git a/js/app/packages/app/component/ItemDragAndDrop.tsx b/js/app/packages/app/component/ItemDragAndDrop.tsx
index c9dc5a3d83..043c0c6ffe 100644
--- a/js/app/packages/app/component/ItemDragAndDrop.tsx
+++ b/js/app/packages/app/component/ItemDragAndDrop.tsx
@@ -1,10 +1,5 @@
-import type { FileListSize } from '@core/component/FileList/constants';
-import type { DragEventWithData } from '@core/component/FileList/DraggableItem';
import { TruncatedText } from '@core/component/FileList/TruncatedText';
-import { useItemOperations } from '@core/component/FileList/useItemOperations';
import { fileTypeToBlockName } from '@core/constant/allBlocks';
-import { useHistoryTree } from '@service-storage/history';
-import { useProjects } from '@service-storage/projects';
import {
DragDropProvider,
DragDropSensors,
@@ -13,15 +8,35 @@ import {
useDragDropContext,
} from '@thisbeyond/solid-dnd';
import { EntityIcon } from 'core/component/EntityIcon';
-import { updateItemParentOnDrop } from 'core/component/FileList/updateItemParentOnDrop';
-import { createMemo, type JSXElement } from 'solid-js';
+import {
+ createContext,
+ createMemo,
+ createSignal,
+ type JSXElement,
+ onCleanup,
+ useContext,
+ type Accessor,
+} from 'solid-js';
+
+type DragOperationContextValue = {
+ isAltKey: Accessor<boolean>;
+};
+
+const DragOperationContext = createContext<DragOperationContextValue>();
+
+export function useDragOperation() {
+ const context = useContext(DragOperationContext);
+ if (!context) {
+ throw new Error('useDragOperation must be used within ItemDndProvider');
+ }
+ return context;
+}
export function ItemDragOverlay() {
const [state] = useDragDropContext() ?? [];
const activeDraggable = createMemo(() => {
return state?.active.draggable;
});
- const size: FileListSize = activeDraggable()?.data.size;
const getEntityIconType = () => {
const data = activeDraggable()?.data;
@@ -52,12 +67,10 @@ export function ItemDragOverlay() {
return (
<div class="w-auto max-w-[300px] flex flex-col gap-2 bg-active p-2 rounded-md z-drag shadow-sm pointer-events-none">
<div class="flex flex-row items-center gap-2">
- <EntityIcon size={size ?? 'sm'} targetType={getEntityIconType()} />
- <TruncatedText size={size ?? 'sm'}>
- {activeDraggable()?.data.name}
- </TruncatedText>
+ <EntityIcon size="sm" targetType={getEntityIconType()} />
+ <TruncatedText size="sm">{activeDraggable()?.data.name}</TruncatedText>
</div>
- {/* TODO post- multiselect exists */}
+ {/* TODO: when multiselect exists */}
{/* <Show when={activeDraggable()?.data.selectedItems.length > 1}>
<div class={`${TEXT_SIZE_CLASSES[size ?? 'sm']} text-ink-muted pl-2`}>
+ {activeDraggable()?.data.selectedItems.length - 1} items
@@ -67,105 +80,38 @@ export function ItemDragOverlay() {
);
}
-export function ItemDragEndHandler() {
- const historyTree = useHistoryTree();
- const [, { onDragEnd }] = useDragDropContext() ?? [
- undefined,
- { onDragEnd: () => {} },
- ];
- const { deleteItem, bulkDelete } = useItemOperations();
-
- onDragEnd((event) => {
- const { draggable, droppable } = event as DragEventWithData;
- let parentId = '';
- let parentName = '';
-
- if (draggable.data.id === droppable?.data.id) {
- return;
- }
+export function ItemDndProvider(props: { children: JSXElement }) {
+ const [isAltPressed, setIsAltPressed] = createSignal(false);
- if (droppable && droppable.id === 'trash') {
- return deleteItem({
- itemType: draggable.data.type,
- id: draggable.data.id,
- itemName: draggable.data.name,
- });
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (e.altKey && !isAltPressed()) {
+ setIsAltPressed(true);
}
+ };
- if (droppable && droppable.data.type === 'explorer-base') {
- parentId = droppable.data.parentId ?? '';
- parentName = droppable.data.parentName ?? 'root';
-
- if (droppable.id === 'explorer-base-trash') {
- if (draggable.data.isBulkMove) {
- const items = draggable.data.selectedItems;
- if (!items) {
- return;
- }
-
- bulkDelete(items).then((result) => {
- if (result.success) {
- draggable.data.setSelectedItems?.([]);
- } else {
- draggable.data.setSelectedItems?.(result.failedItems);
- }
- });
- } else {
- // Handle single item deletion
- deleteItem({
- itemType: draggable.data.type,
- id: draggable.data.id,
- itemName: draggable.data.name,
- });
- }
- return;
- }
- } else if (droppable && droppable.data.type === 'project') {
- parentId = String(droppable.data.id);
- parentName = droppable.data.name;
- } else if (droppable && droppable.data.type !== 'project') {
- // check if droppable is in user's root list
- if (
- historyTree().rootItems.find(
- (item) => item.item.id === droppable.data.id
- )
- ) {
- parentId = '';
- parentName = 'root';
- }
- // if not, update parent to droppable parent
- else {
- const projects = useProjects();
- const parentProject = projects().find(
- (project) => project.id === droppable.data.parentId
- );
- if (!parentProject) {
- return;
- }
- parentId = parentProject.id;
- parentName = parentProject.name;
- }
+ const handleKeyUp = (e: KeyboardEvent) => {
+ if (!e.altKey && isAltPressed()) {
+ setIsAltPressed(false);
}
+ };
- updateItemParentOnDrop({
- draggable: draggable as DragEventWithData['draggable'],
- parentId,
- parentName,
- });
- });
+ window.addEventListener('keydown', handleKeyDown);
+ window.addEventListener('keyup', handleKeyUp);
- return '';
-}
+ onCleanup(() => {
+ window.removeEventListener('keydown', handleKeyDown);
+ window.removeEventListener('keyup', handleKeyUp);
+ });
-export function ItemDndProvider(props: { children: JSXElement }) {
return (
- <DragDropProvider collisionDetector={mostIntersecting}>
- <DragDropSensors />
- <ItemDragEndHandler />
- {props.children}
- <DragOverlay class="z-drag">
- <ItemDragOverlay />
- </DragOverlay>
- </DragDropProvider>
+ <DragOperationContext.Provider value={{ isAltKey: isAltPressed }}>
+ <DragDropProvider collisionDetector={mostIntersecting}>
+ <DragDropSensors />
+ {props.children}
+ <DragOverlay class="z-drag">
+ <ItemDragOverlay />
+ </DragOverlay>
+ </DragDropProvider>
+ </DragOperationContext.Provider>
);
}
diff --git a/js/app/packages/app/component/Soup.tsx b/js/app/packages/app/component/Soup.tsx
index c2e8f56ada..5e5d32dd6c 100644
--- a/js/app/packages/app/component/Soup.tsx
+++ b/js/app/packages/app/component/Soup.tsx
@@ -37,7 +37,6 @@ import { storageServiceClient } from '@service-storage/client';
import { createElementSize } from '@solid-primitives/resize-observer';
import { Navigate } from '@solidjs/router';
import { useMutation, useQueryClient } from '@tanstack/solid-query';
-import { createDroppable, useDragDropContext } from '@thisbeyond/solid-dnd';
import { registerHotkey } from 'core/hotkey/hotkeys';
import {
batch,
@@ -657,18 +656,6 @@ export function Soup() {
const [isDragging, setIsDragging] = createSignal(false);
const [isValidDrag, setIsValidDrag] = createSignal(true);
- const droppableId = 'soup-drop-zone';
- const droppable = createDroppable(droppableId);
-
- const dragDropContext = useDragDropContext();
- if (dragDropContext) {
- dragDropContext[1].onDragEnd((event) => {
- if (!event.droppable || event.droppable.id !== droppableId) return;
-
- // TODO: moveToFolder action
- });
- }
-
const handleFileUpload = useHandleFileUpload();
const notificationSource = useGlobalNotificationSource();
@@ -717,7 +704,6 @@ export function Soup() {
return (
<div
class="relative flex flex-col bg-panel size-full"
- use:droppable
use:fileFolderDrop={{
onDrop: (fileEntries, folderEntries) => {
handleFileFolderDrop(fileEntries, folderEntries, handleFileUpload);
@@ -729,14 +715,12 @@ export function Soup() {
onDragEnd: () => setIsDragging(false),
}}
>
- <Show when={isDragging() || droppable.isActiveDroppable}>
+ <Show when={isDragging()}>
<FileDropOverlay valid={isValidDrag()}>
<Show when={!isValidDrag()}>
- <div class="font-mono text-failure">[!] Invalid file type</div>
+ <div class="text-failure">[!] Invalid file type</div>
</Show>
- <div class="font-mono">
- Drop any file here to add it to your workspace
- </div>
+ <div>Drop any file here to add it to your workspace</div>
</FileDropOverlay>
</Show>
diff --git a/js/app/packages/app/component/UnifiedListView.tsx b/js/app/packages/app/component/UnifiedListView.tsx
index 7376297a3e..2315b8cfcf 100644
--- a/js/app/packages/app/component/UnifiedListView.tsx
+++ b/js/app/packages/app/component/UnifiedListView.tsx
@@ -1864,6 +1864,9 @@ export function UnifiedListView(props: UnifiedListViewProps) {
searchText={searchText()}
hasRefinementsFromBase={isViewConfigChanged()}
entityMinHeight={ENTITY_HEIGHT}
+ viewType={view()?.viewType}
+ name={view()?.view}
+ splitId={splitContext.handle.id}
>
{(innerProps) => {
const displayDoneButton = () => {
@@ -1914,6 +1917,7 @@ export function UnifiedListView(props: UnifiedListViewProps) {
}}
entity={innerProps.entity}
properties={properties()}
+ splitId={splitContext.handle.id}
timestamp={timestamp()}
onClick={entityClickHandler}
onDblClick={entityDblClickHandler}
diff --git a/js/app/packages/block-canvas/component/BaseRenderer.tsx b/js/app/packages/block-canvas/component/BaseRenderer.tsx
index 144a5707d1..15a4d51c07 100644
--- a/js/app/packages/block-canvas/component/BaseRenderer.tsx
+++ b/js/app/packages/block-canvas/component/BaseRenderer.tsx
@@ -4,9 +4,9 @@ import type { RenderMode } from '../constants';
import {
type CanvasEdge,
type CanvasNode,
- type FileNode,
+ type EntityMentionNode,
type ImageNode,
- isFileNode,
+ isEntityMentionNode,
isImageNode,
isPencilNode,
isShapeNode,
@@ -18,7 +18,7 @@ import {
type VideoNode,
} from '../model/CanvasModel';
import { Line } from './edges/Line';
-import { File } from './nodes/DSSFile';
+import { File } from './nodes/EntityMention';
import { DSSMedia } from './nodes/DSSMedia';
import { Pencil } from './nodes/Pencil';
import { Shape } from './nodes/Shape';
@@ -47,8 +47,8 @@ export function NodeRenderer(props: { node: CanvasNode; mode: RenderMode }) {
<Match when={isTextNode(props.node)}>
<TextBox node={props.node as TextNode} mode={props.mode} />
</Match>
- <Match when={isFileNode(props.node)}>
- <File node={props.node as FileNode} mode={props.mode} />
+ <Match when={isEntityMentionNode(props.node)}>
+ <File node={props.node as EntityMentionNode} mode={props.mode} />
</Match>
</Switch>
);
diff --git a/js/app/packages/block-canvas/component/Block.tsx b/js/app/packages/block-canvas/component/Block.tsx
index 256aa998be..434cf05e22 100644
--- a/js/app/packages/block-canvas/component/Block.tsx
+++ b/js/app/packages/block-canvas/component/Block.tsx
@@ -22,10 +22,15 @@ import {
createResource,
createSignal,
on,
+ onCleanup,
Show,
} from 'solid-js';
import { blockDataSignal } from '../signal/canvasBlockData';
-import { useLoadCanvasData } from '../store/canvasData';
+import {
+ pendingUpdates,
+ useLoadCanvasData,
+ useSaveCanvasDataImmediate,
+} from '../store/canvasData';
import { isAnimating, renderStateStore } from '../store/RenderState';
import { CanvasController } from './CanvasController';
import { CanvasRenderer } from './CanvasRenderer';
@@ -74,10 +79,32 @@ export default function BlockCanvas(props: BlockCanvasProps) {
const isNestedBlock = useIsNestedBlock();
const nestedContext = useBlockNestedContext<'canvas'>();
const loadCanvasData = useLoadCanvasData();
+ const saveCanvasDataImmediate = useSaveCanvasDataImmediate();
+ const [pending] = pendingUpdates;
const [, setRenderState] = renderStateStore;
const [dataState, setDataState] = createSignal<BlockDataState>('loading');
const [visible, setVisible] = createSignal(false);
+ // Flush pending saves on cleanup to prevent data loss when navigating away
+ onCleanup(() => {
+ if (pending()) {
+ saveCanvasDataImmediate();
+ }
+ });
+
+ // Also flush on page unload (refresh, close tab)
+ createEffect(() => {
+ const handleBeforeUnload = () => {
+ if (pending()) {
+ saveCanvasDataImmediate();
+ }
+ };
+ window.addEventListener('beforeunload', handleBeforeUnload);
+ onCleanup(() => {
+ window.removeEventListener('beforeunload', handleBeforeUnload);
+ });
+ });
+
createEffect(() => {
const context = nestedContext?.parentContext;
if (!context) return;
diff --git a/js/app/packages/block-canvas/component/CanvasController.tsx b/js/app/packages/block-canvas/component/CanvasController.tsx
index 131726028c..bea8def10c 100644
--- a/js/app/packages/block-canvas/component/CanvasController.tsx
+++ b/js/app/packages/block-canvas/component/CanvasController.tsx
@@ -7,7 +7,7 @@ import { useRenderMermaid } from '@block-canvas/util/mermaid';
import { withAnalytics } from '@coparse/analytics';
import { type BlockName, useBlockId, useIsNestedBlock } from '@core/block';
import { FileDropOverlay } from '@core/component/FileDropOverlay';
-import type { DragEventWithData } from '@core/component/FileList/DraggableItem';
+import type { EntityDragEvent } from '@macro-entity';
import { BasicHotkey } from '@core/component/Hotkey';
import { OldMenu, OldMenuItem } from '@core/component/OldMenu';
import {
@@ -816,7 +816,7 @@ export function CanvasController(props: ParentProps) {
},
];
- const wrapDndEvent = (event: DragEventWithData) => {
+ const wrapDndEvent = (event: EntityDragEvent) => {
const currentPos = dragDropState?.active.sensor?.coordinates?.current;
if (!currentPos) return;
const mousePos = {
@@ -834,7 +834,7 @@ export function CanvasController(props: ParentProps) {
};
};
- const attachImageOnDrag = (event: DragEventWithData) => {
+ const attachImageOnDrag = (event: EntityDragEvent) => {
if (!event.droppable) return;
track(TrackingEvents.BLOCKCANVAS.IMAGES.DSSIMAGE, {
method: 'drag from sidebar',
@@ -860,7 +860,7 @@ export function CanvasController(props: ParentProps) {
setSelectedTool(Tools.Select);
};
- const attachVideoOnDrag = (event: DragEventWithData) => {
+ const attachVideoOnDrag = (event: EntityDragEvent) => {
if (!event.droppable) return;
track(TrackingEvents.BLOCKCANVAS.VIDEOS.DSSVIDEO, {
method: 'drag from sidebar',
@@ -888,29 +888,23 @@ export function CanvasController(props: ParentProps) {
setSelectedTool(Tools.Move);
};
- const attachFileOnDrag = async (
- event: DragEventWithData,
- id: string,
- isChat = false,
- isRss = false,
- isProject = false
- ) => {
+ const attachFileOnDrag = async (event: EntityDragEvent, id: string) => {
if (!event.droppable) return;
track(TrackingEvents.BLOCKCANVAS.FILES.SIDEBARDND);
+ const entityType = event.draggable.data.type;
+
// Track document mention and get UUID
let mentionUuid: string | undefined;
- if (blockId && !isChat && !isRss) {
+ if (blockId && entityType === 'document') {
mentionUuid = await trackMention(blockId, 'document', id);
}
nodes.createNode(
{
- type: 'file',
+ type: 'entitymention',
file: id,
- isChat,
- isRss,
- isProject,
+ entityType,
mentionUuid,
x: (dragPosition()?.x ?? centerVec().x) - fileWidth / 2,
y: (dragPosition()?.y ?? centerVec().y) - fileHeight / 2,
@@ -927,7 +921,7 @@ export function CanvasController(props: ParentProps) {
setSelectedTool(Tools.Select);
};
- const dndDragMove = throttle((event: DragEventWithData) => {
+ const dndDragMove = throttle((event: EntityDragEvent) => {
if (!droppable.isActiveDroppable) {
setDragPosition();
return;
@@ -938,7 +932,7 @@ export function CanvasController(props: ParentProps) {
setDragPosition(clientToCanvas(mousePos));
}, 60);
- const dndDragEnd = (event: DragEventWithData) => {
+ const dndDragEnd = (event: EntityDragEvent) => {
if (!dragPosition()) return;
if (!canEdit()) return;
@@ -953,22 +947,18 @@ export function CanvasController(props: ParentProps) {
attachImageOnDrag(event);
} else if (res.blockName === 'video' && ENABLE_CANVAS_VIDEO) {
attachVideoOnDrag(event);
- } else if (res.blockName === 'chat') {
- attachFileOnDrag(event, res.id, true, false);
- } else if (res.blockName === 'project') {
- attachFileOnDrag(event, res.id, false, false, true);
} else {
- attachFileOnDrag(event, res.id, false, false);
+ attachFileOnDrag(event, res.id);
}
};
onDragEnd((event) => {
if (event.droppable?.id !== 'canvas-input-' + _id) return;
- dndDragEnd(event as DragEventWithData);
+ dndDragEnd(event as EntityDragEvent);
});
onDragMove((event) => {
- dndDragMove(event as DragEventWithData);
+ dndDragMove(event as EntityDragEvent);
});
const [_mouseDownPos, setMouseDownPos] = mouseDownPositionSignal;
diff --git a/js/app/packages/block-canvas/component/FloatingMenu.tsx b/js/app/packages/block-canvas/component/FloatingMenu.tsx
index 3ef710bf20..04107fe75c 100644
--- a/js/app/packages/block-canvas/component/FloatingMenu.tsx
+++ b/js/app/packages/block-canvas/component/FloatingMenu.tsx
@@ -99,7 +99,7 @@ const ValidPropsByEntity: Partial<Record<CanvasEntity, Set<string>>> = {
edge: new Set(['strokeColor', 'strokeWidth', 'opacity']),
text: new Set(['textSize', 'strokeColor']),
image: new Set(['strokeColor', 'strokeWidth', 'opacity', 'cornerRadius']),
- file: new Set([]),
+ entitymention: new Set([]),
};
export function SwatchColorPicker(props: {
@@ -458,7 +458,7 @@ export function FloatingMenu() {
const nodesLength = nodes.length;
if (
nodesLength > 1 &&
- nodes.some((node) => node.type === 'file') &&
+ nodes.some((node) => node.type === 'entitymention') &&
edges.length < 1
) {
return true;
diff --git a/js/app/packages/block-canvas/component/nodes/DSSFile.tsx b/js/app/packages/block-canvas/component/nodes/EntityMention.tsx
similarity index 78%
rename from js/app/packages/block-canvas/component/nodes/DSSFile.tsx
rename to js/app/packages/block-canvas/component/nodes/EntityMention.tsx
index 45b746916c..b9366cf8b8 100644
--- a/js/app/packages/block-canvas/component/nodes/DSSFile.tsx
+++ b/js/app/packages/block-canvas/component/nodes/EntityMention.tsx
@@ -6,18 +6,24 @@ import { CircleSpinner } from '@core/component/CircleSpinner';
import { PopupPreview } from '@core/component/DocumentPreview';
import { EntityIcon } from '@core/component/EntityIcon';
import { floatWithElement } from '@core/component/LexicalMarkdown/directive/floatWithElement';
-import { fileTypeToBlockName } from '@core/constant/allBlocks';
+import { itemToBlockName } from '@core/constant/allBlocks';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { type PreviewItemNoAccess, useItemPreview } from '@core/signal/preview';
import { matches } from '@core/util/match';
import LockKey from '@phosphor-icons/core/regular/lock-key.svg';
import Question from '@phosphor-icons/core/regular/question.svg';
-import type { FileType } from '@service-storage/generated/schemas/fileType';
import { debounce } from '@solid-primitives/scheduled';
-import { createEffect, createSignal, Match, Show, Switch } from 'solid-js';
-import { useSplitLayout } from '../../../app/component/split-layout/layout';
+import {
+ createEffect,
+ createMemo,
+ createSignal,
+ Match,
+ Show,
+ Switch,
+} from 'solid-js';
+import { useSplitLayout } from 'app/component/split-layout/layout';
import { DRAG_THRESHOLD, type RenderMode, Tools } from '../../constants';
-import type { FileNode } from '../../model/CanvasModel';
+import type { EntityMentionNode } from '../../model/CanvasModel';
import { fileWidth } from '../../operation/file';
import { type Vector2, vec2 } from '../../util/vector2';
import { BaseCanvasRectangle } from './BaseCanvasRectangle';
@@ -27,7 +33,7 @@ false && floatWithElement;
const { track, TrackingEvents } = withAnalytics();
function ErrorMessage(props: {
- node: FileNode;
+ node: EntityMentionNode;
error: 'UNAUTHORIZED' | 'MISSING' | 'INVALID' | 'LOADING' | undefined;
}) {
const { currentScale } = useRenderState();
@@ -83,16 +89,13 @@ function ErrorMessage(props: {
);
}
-export function File(props: { node: FileNode; mode: RenderMode }) {
+export function File(props: { node: EntityMentionNode; mode: RenderMode }) {
let fileRef!: HTMLDivElement;
const [error, setError] = createSignal<
'UNAUTHORIZED' | 'MISSING' | 'INVALID' | 'LOADING' | undefined
>('LOADING');
- const [fileName, setFileName] = createSignal<string>();
- const [fileType, setFileType] = createSignal<FileType | 'chat'>();
- const [blockName, setBlockName] = createSignal<string>();
const blockId = useBlockId();
const [previewOpen, setPreviewOpen] = createSignal(false);
@@ -105,11 +108,7 @@ export function File(props: { node: FileNode; mode: RenderMode }) {
const [item] = useItemPreview({
id: props.node.file,
- type: props.node.isChat
- ? 'chat'
- : props.node.isProject
- ? 'project'
- : 'document',
+ type: props.node.entityType,
});
createEffect(() => {
@@ -128,24 +127,75 @@ export function File(props: { node: FileNode; mode: RenderMode }) {
}
if (currentItem.access === 'access') {
setError();
- if (currentItem.type === 'document') {
- setFileName(currentItem.name);
- setFileType(currentItem.fileType);
- setBlockName(fileTypeToBlockName(currentItem.fileType!));
- } else if (currentItem.type === 'chat') {
- setFileName(currentItem.name);
- setFileType('chat');
- setBlockName('chat');
- setError();
- } else if (currentItem.type === 'project') {
- setFileName(currentItem.name);
- setFileType('project' as FileType);
- setBlockName('project');
- setError();
- }
}
});
+ // Get icon type using the same logic as EntityWithEverything
+ const iconType = createMemo(() => {
+ const currentItem = item();
+ if (
+ !currentItem ||
+ currentItem.loading ||
+ currentItem.access !== 'access'
+ ) {
+ return 'default';
+ }
+
+ switch (currentItem.type) {
+ case 'channel':
+ switch (currentItem.channelType) {
+ case 'direct_message':
+ return 'directMessage';
+ case 'organization':
+ return 'company';
+ default:
+ return 'channel';
+ }
+ case 'document':
+ // TODO: consolidate is task logic, see isTaskEntity
+ if (
+ currentItem.fileType === 'md' &&
+ currentItem.subType?.type === 'task'
+ ) {
+ return 'task';
+ }
+ if (currentItem.fileType) return currentItem.fileType;
+ return 'default';
+ case 'chat':
+ return 'chat';
+ case 'project':
+ return 'project';
+ case 'email':
+ return 'email';
+ default:
+ return 'default';
+ }
+ });
+
+ const fileName = createMemo(() => {
+ const currentItem = item();
+ if (
+ !currentItem ||
+ currentItem.loading ||
+ currentItem.access !== 'access'
+ ) {
+ return '';
+ }
+ return currentItem.name;
+ });
+
+ const blockName = createMemo(() => {
+ const currentItem = item();
+ if (
+ !currentItem ||
+ currentItem.loading ||
+ currentItem.access !== 'access'
+ ) {
+ return undefined;
+ }
+ return itemToBlockName(currentItem);
+ });
+
const { selectedTool, mouseIsDown, activeTool } = useToolManager();
return (
<div
@@ -210,7 +260,7 @@ export function File(props: { node: FileNode; mode: RenderMode }) {
useSimpleSelectionBox={true}
>
<Show
- when={!error() && fileType()}
+ when={!error()}
fallback={<ErrorMessage error={error()} node={props.node} />}
>
<div
@@ -233,11 +283,11 @@ export function File(props: { node: FileNode; mode: RenderMode }) {
height: 18 * (props.node.width / fileWidth) + 'px',
}}
>
- <EntityIcon targetType={fileType()} size={'fill'} />
+ <EntityIcon targetType={iconType()} size={'fill'} />
</div>
{fileName()}
</div>
- <Show when={previewOpen()}>
+ <Show when={previewOpen() && blockName()}>
<PopupPreview
item={item}
floatRef={fileRef}
diff --git a/js/app/packages/block-canvas/model/CanvasModel.ts b/js/app/packages/block-canvas/model/CanvasModel.ts
index af00944382..495efe9dfc 100644
--- a/js/app/packages/block-canvas/model/CanvasModel.ts
+++ b/js/app/packages/block-canvas/model/CanvasModel.ts
@@ -25,7 +25,7 @@ const looseNumber = z
// Node Types
export const NODE_TYPES = [
'text',
- 'file',
+ 'entitymention',
'link',
'shape',
'pencil',
@@ -139,16 +139,40 @@ export const TextNodeSchema = BaseNodeSchema.extend({
followTextWidth: z.boolean().optional(),
});
-// File node schema
-export const FileNodeSchema = BaseNodeSchema.extend({
- type: z.literal('file'),
- isChat: z.boolean().optional(),
- isRss: z.boolean().optional(),
- isProject: z.boolean().optional(),
- file: z.string(),
- subpath: z.string().optional(),
- mentionUuid: z.string().optional(),
-});
+// Entity mention node schema with backward compatibility
+export const EntityMentionSchema = z.preprocess(
+ (data: any) => {
+ // migrate old schema to new schema
+ if (data && typeof data === 'object') {
+ if (data.type === 'file') {
+ data.type = 'entitymention';
+ }
+
+ if (!data.entityType) {
+ if (data.isChat) {
+ data.entityType = 'chat';
+ } else if (data.isProject) {
+ data.entityType = 'project';
+ } else {
+ data.entityType = 'document';
+ }
+
+ // Remove old fields
+ delete data.isChat;
+ delete data.isRss;
+ delete data.isProject;
+ }
+ }
+ return data;
+ },
+ BaseNodeSchema.extend({
+ type: z.literal('entitymention'),
+ entityType: z.enum(['document', 'chat', 'project', 'channel', 'email']),
+ file: z.string(),
+ subpath: z.string().optional(),
+ mentionUuid: z.string().optional(),
+ })
+);
// Link node schema
export const LinkNodeSchema = BaseNodeSchema.extend({
@@ -187,7 +211,7 @@ export const PencilNodeSchema = BaseNodeSchema.extend({
// Union of all node types
export const NodeSchema = z.union([
TextNodeSchema,
- FileNodeSchema,
+ EntityMentionSchema,
LinkNodeSchema,
ShapeNodeSchema,
ImageNodeSchema,
@@ -243,7 +267,7 @@ export const CanvasSchema = z.object({
// Inferred Schemas Types
export type BaseNode = z.infer<typeof BaseNodeSchema>;
export type TextNode = z.infer<typeof TextNodeSchema>;
-export type FileNode = z.infer<typeof FileNodeSchema>;
+export type EntityMentionNode = z.infer<typeof EntityMentionSchema>;
export type LinkNode = z.infer<typeof LinkNodeSchema>;
export type ShapeNode = z.infer<typeof ShapeNodeSchema>;
export type ImageNode = z.infer<typeof ImageNodeSchema>;
@@ -252,7 +276,7 @@ export type PencilNode = z.infer<typeof PencilNodeSchema>;
export type CanvasNode =
| BaseNode
| TextNode
- | FileNode
+ | EntityMentionNode
| LinkNode
| ShapeNode
| ImageNode
@@ -276,8 +300,10 @@ export const isTextNode = (node: CanvasNode): node is TextNode => {
return node.type === 'text';
};
-export const isFileNode = (node: CanvasNode): node is FileNode => {
- return node.type === 'file';
+export const isEntityMentionNode = (
+ node: CanvasNode
+): node is EntityMentionNode => {
+ return node.type === 'entitymention';
};
export const isLinkNode = (node: CanvasNode): node is LinkNode => {
diff --git a/js/app/packages/block-canvas/operation/file.ts b/js/app/packages/block-canvas/operation/file.ts
index 95047c2545..fec119b49f 100644
--- a/js/app/packages/block-canvas/operation/file.ts
+++ b/js/app/packages/block-canvas/operation/file.ts
@@ -5,7 +5,7 @@ import { copiedItem } from '@core/state/clipboard';
import type { ItemType } from '@service-storage/client';
import { unwrap } from 'solid-js/store';
import { OPERATION_LOGGING, Tools } from '../constants';
-import type { FileNode } from '../model/CanvasModel';
+import type { EntityMentionNode } from '../model/CanvasModel';
import { useCanvasHistory } from '../signal/canvasHistory';
import { useToolManager } from '../signal/toolManager';
import { highestOrderSignal, useCanvasNodes } from '../store/canvasData';
@@ -33,7 +33,7 @@ function _log(message: string) {
export type FileOperation = Operation & {
type: 'file';
initialMousePos: Vector2;
- node: FileNode;
+ node: EntityMentionNode;
};
export const currentFileOperationSignal = createBlockSignal<FileOperation>();
@@ -89,9 +89,14 @@ export const useFile = sharedInstance((): Operator => {
}
const node = createNode(
{
- type: 'file',
+ type: 'entitymention',
file: id,
- isChat: type === 'chat',
+ entityType: type as
+ | 'document'
+ | 'chat'
+ | 'project'
+ | 'channel'
+ | 'email',
x: mousePos.x - fileWidth / 2,
y: mousePos.y - fileHeight / 2,
width: fileWidth,
@@ -102,7 +107,7 @@ export const useFile = sharedInstance((): Operator => {
sortOrder: highestOrder() + 1,
},
{ preview: true }
- ) as FileNode;
+ ) as EntityMentionNode;
setCurrentFileOperation({
type: 'file',
@@ -123,7 +128,7 @@ export const useFile = sharedInstance((): Operator => {
// Track document mention and store the UUID
let mentionUuid: string | undefined;
- if (blockId && op.node.file && !op.node.isChat && !op.node.isRss) {
+ if (blockId && op.node.file && op.node.entityType === 'document') {
mentionUuid = await trackMention(blockId, 'document', op.node.file);
}
diff --git a/js/app/packages/block-canvas/operation/rescale.ts b/js/app/packages/block-canvas/operation/rescale.ts
index eb0daf7d4d..6d024bdf3c 100644
--- a/js/app/packages/block-canvas/operation/rescale.ts
+++ b/js/app/packages/block-canvas/operation/rescale.ts
@@ -7,9 +7,9 @@ import {
type CanvasEdge,
type CanvasId,
type CanvasNode,
- type FileNode,
+ type EntityMentionNode,
type ImageNode,
- isFileNode,
+ isEntityMentionNode,
isImageNode,
isPencilNode,
isShapeNode,
@@ -108,7 +108,11 @@ const rescaleShape: RescaleNodeFunction<ShapeNode> = (
});
};
-const rescaleFile: RescaleNodeFunction<FileNode> = (nodes, node, innerRect) => {
+const rescaleFile: RescaleNodeFunction<EntityMentionNode> = (
+ nodes,
+ node,
+ innerRect
+) => {
const ratio = fileWidth / fileHeight;
const largerWidth = Math.abs(innerRect.w) / Math.abs(innerRect.h) > ratio;
nodes.updateNode(node.id, {
@@ -228,7 +232,7 @@ export const useRescale = sharedInstance((): Operator => {
rescaleMediaNode(nodes, node, newInnerRect, undefined, flip);
} else if (isTextNode(node)) {
rescaleText(nodes, node, newInnerRect);
- } else if (isFileNode(node)) {
+ } else if (isEntityMentionNode(node)) {
rescaleFile(nodes, node, newInnerRect);
} else if (isVideoNode(node)) {
const flip = op.initialFlip[node.id];
diff --git a/js/app/packages/block-canvas/operation/select.ts b/js/app/packages/block-canvas/operation/select.ts
index 30cca3483e..7ae71d0a93 100644
--- a/js/app/packages/block-canvas/operation/select.ts
+++ b/js/app/packages/block-canvas/operation/select.ts
@@ -59,7 +59,7 @@ export const useSelect = sharedInstance((): Operator => {
node.type === 'image' ||
node.type === 'video' ||
node.type === 'text' ||
- node.type === 'file'
+ node.type === 'entitymention'
) {
if (rect.intersects(nodeRect)) {
acc.push(node.id);
diff --git a/js/app/packages/block-canvas/store/canvasData.ts b/js/app/packages/block-canvas/store/canvasData.ts
index 7070fff638..4381365deb 100644
--- a/js/app/packages/block-canvas/store/canvasData.ts
+++ b/js/app/packages/block-canvas/store/canvasData.ts
@@ -792,40 +792,43 @@ export const useExportCanvasData = sharedInstance(() => {
};
});
-// save block-level canvas data to DSS
-export const useSaveCanvasData = sharedInstance(() => {
+// Immediate save function (not debounced)
+export const useSaveCanvasDataImmediate = sharedInstance(() => {
const exportCanvasData = useExportCanvasData();
const [, setPendingUpdates] = pendingUpdates;
const setCurrentSavedFile = currentSavedFile.set;
- return debounce(
- createCallback(async () => {
- const dssFile = blockDataSignal()?.dssFile;
- if (!dssFile) {
- console.error('no dss file');
- return;
- }
- const { documentId } = dssFile.getMetadata();
+ return createCallback(async () => {
+ const dssFile = blockDataSignal()?.dssFile;
+ if (!dssFile) {
+ console.error('no dss file');
+ return;
+ }
+ const { documentId } = dssFile.getMetadata();
- const canvas = exportCanvasData();
- const encoder = new TextEncoder();
- const buffer = encoder.encode(JSON.stringify(canvas));
+ const canvas = exportCanvasData();
+ const encoder = new TextEncoder();
+ const buffer = encoder.encode(JSON.stringify(canvas));
- const file = new Blob([buffer], { type: 'application/x-macro-canvas' });
+ const file = new Blob([buffer], { type: 'application/x-macro-canvas' });
- const saveRes = await storageServiceClient.simpleSave({
- documentId,
- file,
- });
+ const saveRes = await storageServiceClient.simpleSave({
+ documentId,
+ file,
+ });
- if (isErr(saveRes)) {
- console.error('error on canvas save');
- }
+ if (isErr(saveRes)) {
+ console.error('error on canvas save');
+ }
- setCurrentSavedFile(() => file);
+ setCurrentSavedFile(() => file);
- setPendingUpdates(false);
- }),
- 1500
- );
+ setPendingUpdates(false);
+ });
+});
+
+// save block-level canvas data to DSS (debounced)
+export const useSaveCanvasData = sharedInstance(() => {
+ const saveImmediate = useSaveCanvasDataImmediate();
+ return debounce(saveImmediate, 1500);
});
diff --git a/js/app/packages/block-canvas/util/mentions.ts b/js/app/packages/block-canvas/util/mentions.ts
index 07a7b60b9e..6c7b52355c 100644
--- a/js/app/packages/block-canvas/util/mentions.ts
+++ b/js/app/packages/block-canvas/util/mentions.ts
@@ -1,4 +1,7 @@
-import { type CanvasNode, isFileNode } from '@block-canvas/model/CanvasModel';
+import {
+ type CanvasNode,
+ isEntityMentionNode,
+} from '@block-canvas/model/CanvasModel';
import { useTextNodeEditors } from '@block-canvas/store/textNodeEditors';
import { untrackMention } from '@core/signal/mention';
import {
@@ -46,7 +49,7 @@ export async function untrackMentionsInTextNode(
nodeId: string
) {
const getTextNodeEditor = useTextNodeEditors().getEditor;
- if (isFileNode(node) && !node.isChat && !node.isRss) {
+ if (isEntityMentionNode(node) && node.entityType === 'document') {
if (node.mentionUuid) {
await untrackMention(blockId, node.mentionUuid);
}
diff --git a/js/app/packages/block-channel/component/Channel.tsx b/js/app/packages/block-channel/component/Channel.tsx
index 1d3c4ad36d..c388888012 100644
--- a/js/app/packages/block-channel/component/Channel.tsx
+++ b/js/app/packages/block-channel/component/Channel.tsx
@@ -20,7 +20,7 @@ import { handleFileUpload } from '@block-channel/utils/inputAttachments';
import { withAnalytics } from '@coparse/analytics';
import { TrackingEvents } from '@coparse/analytics/src/types/TrackingEvents';
import { useBlockId } from '@core/block';
-import type { DragEventWithData } from '@core/component/FileList/DraggableItem';
+import type { EntityDragEvent } from '@macro-entity';
import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
import { fileTypeToBlockName } from '@core/constant/allBlocks';
import { fileFolderDrop } from '@core/directive/fileFolderDrop';
@@ -181,7 +181,7 @@ export function Channel(props: {
]);
}
- onDragEnd((event: DragEventWithData) => {
+ onDragEnd((event: EntityDragEvent) => {
if (!event.droppable) return;
if (event.droppable?.id !== 'channel-input-' + channelId) return;
if (event.droppable.node === containerRef) {
diff --git a/js/app/packages/block-md/component/MarkdownEditor.tsx b/js/app/packages/block-md/component/MarkdownEditor.tsx
index 447ff0b88c..fd719f8e92 100644
--- a/js/app/packages/block-md/component/MarkdownEditor.tsx
+++ b/js/app/packages/block-md/component/MarkdownEditor.tsx
@@ -10,7 +10,7 @@ import {
useMaybeBlockAliasedName,
} from '@core/block';
import { IS_MAC } from '@core/constant/isMac';
-import type { DragEventWithData } from '@core/component/FileList/DraggableItem';
+import type { EntityDragEvent } from '@macro-entity';
import { DecoratorRenderer } from '@core/component/LexicalMarkdown/component/core/DecoratorRenderer';
import { FocusClickTarget } from '@core/component/LexicalMarkdown/component/core/FocusClickTarget';
import {
@@ -300,7 +300,7 @@ export function MarkdownEditor(props: { autoFocusOnMount?: boolean } = {}) {
];
// turn the solid dnd events into something we can use.
- const wrapDndEvent = (event: DragEventWithData) => {
+ const wrapDndEvent = (event: EntityDragEvent) => {
const currentPos = dragDropState?.active.sensor?.coordinates?.current;
if (!currentPos) return;
const mousePos = {
@@ -318,7 +318,7 @@ export function MarkdownEditor(props: { autoFocusOnMount?: boolean } = {}) {
};
};
- const dndDragEnd = async (event: DragEventWithData) => {
+ const dndDragEnd = async (event: EntityDragEvent) => {
if (!dragInsertStore.visible) return;
setDragInsertStore({ visible: false });
if (!canEdit()) return;
@@ -358,7 +358,7 @@ export function MarkdownEditor(props: { autoFocusOnMount?: boolean } = {}) {
});
};
- const dndDragMove = throttle((event: DragEventWithData) => {
+ const dndDragMove = throttle((event: EntityDragEvent) => {
if (!droppable.isActiveDroppable) {
return setDragInsertStore({ visible: false });
}
@@ -371,12 +371,12 @@ export function MarkdownEditor(props: { autoFocusOnMount?: boolean } = {}) {
}
}, 60);
- onDragEnd((event) => {
- dndDragEnd(event as DragEventWithData);
+ onDragEnd((event: EntityDragEvent) => {
+ dndDragEnd(event);
});
- onDragMove((event) => {
- dndDragMove(event as DragEventWithData);
+ onDragMove((event: EntityDragEvent) => {
+ dndDragMove(event);
});
// handler for the find and replace directive
diff --git a/js/app/packages/block-project/component/Block.tsx b/js/app/packages/block-project/component/Block.tsx
index 59f065e66a..62a45b3fe0 100644
--- a/js/app/packages/block-project/component/Block.tsx
+++ b/js/app/packages/block-project/component/Block.tsx
@@ -8,6 +8,7 @@ import { playSound } from '@app/util/sound';
import { getIsSpecialProject } from '@block-project/isSpecial';
import { useBlockId } from '@core/block';
import { DocumentBlockContainer } from '@core/component/DocumentBlockContainer';
+import { FileDropOverlay } from '@core/component/FileDropOverlay';
import { ENABLE_PROJECT_VIEW_PREVIEW } from '@core/constant/featureFlags';
import { fileFolderDrop } from '@core/directive/fileFolderDrop';
import { fileSelector } from '@core/directive/fileSelector';
@@ -22,7 +23,6 @@ import {
queryKeys,
useQueryClient as useEntityQueryClient,
} from '@macro-entity';
-import Files from '@phosphor-icons/core/duotone/files-duotone.svg?component-solid';
import { refetchResources } from '@service-storage/util/refetchResources';
import { toast } from 'core/component/Toast/Toast';
import {
@@ -155,15 +155,7 @@ const Block: Component = () => {
}}
>
<Show when={isDragging() && !isSpecialProject}>
- <div class="hidden sm:flex flex-col absolute top-0 left-0 w-full h-full backdrop-blur-sm bg-accent/10 items-center justify-center space-y-3 z-3">
- <Files class="w-[80px] h-[80px] text-ink" />
- <h3 class="text-2xl font-semibold text-ink">
- Upload to {name() ?? 'folder'}
- </h3>
- <p class="text-sm text-ink-muted">
- Drop files or folders here to upload
- </p>
- </div>
+ <FileDropOverlay>Upload to this folder</FileDropOverlay>
</Show>
<TopBar />
<Show when={ENABLE_PROJECT_VIEW_PREVIEW} fallback={<UnifiedListView />}>
diff --git a/js/app/packages/core/component/FileDropOverlay.tsx b/js/app/packages/core/component/FileDropOverlay.tsx
index 27bab7e628..730482fe76 100644
--- a/js/app/packages/core/component/FileDropOverlay.tsx
+++ b/js/app/packages/core/component/FileDropOverlay.tsx
@@ -13,7 +13,7 @@ export const FileDropOverlay = (props: ParentProps<{ valid?: boolean }>) => {
'pattern-failure-bg': !valid(),
}}
>
- <div class="bg-menu border-1 border-edge px-8 py-4 text-xs text-ink-muted shadow-md">
+ <div class="bg-menu border-1 border-edge px-8 py-4 text-xs text-ink-muted shadow-md font-mono">
{props.children}
</div>
</div>
diff --git a/js/app/packages/core/component/FileList/DragAndDropWrapper.tsx b/js/app/packages/core/component/FileList/DragAndDropWrapper.tsx
deleted file mode 100644
index 99f5f041c2..0000000000
--- a/js/app/packages/core/component/FileList/DragAndDropWrapper.tsx
+++ /dev/null
@@ -1,79 +0,0 @@
-import { DraggableItem } from '@core/component/FileList/DraggableItem';
-import { DroppableItem } from '@core/component/FileList/DroppableItem';
-import type { ItemType } from '@service-storage/client';
-import type { FileType } from '@service-storage/generated/schemas/fileType';
-import type { Item } from '@service-storage/generated/schemas/item';
-import type { Accessor, ParentProps, Setter } from 'solid-js';
-import type { FileListSize } from './constants';
-
-type DragAndDropWrapperProps = {
- itemType: ItemType;
- fileType?: FileType;
- id: string;
- name: string;
- isOwner: boolean;
- parentId?: string;
- lastEdited: string;
- depth?: number;
- context?: string;
- isEditing?: boolean;
- selectedItems: Accessor<Item[]>;
- setSelectedItems: Setter<Item[]>;
- size?: FileListSize;
- deactivated?: boolean;
-};
-
-export function DragAndDropWrapper(
- props: ParentProps<DragAndDropWrapperProps>
-) {
- if (props.id === 'trash') {
- return (
- <DroppableItem
- id={props.id}
- type={props.itemType}
- fileType={props.fileType}
- name={props.name}
- isOwner={props.isOwner}
- parentId={props.parentId}
- depth={props.depth}
- context={props.context}
- isEditing={props.isEditing}
- deactivated={props.deactivated}
- >
- {props.children}
- </DroppableItem>
- );
- }
- return (
- <DraggableItem
- type={props.itemType}
- id={props.id}
- fileType={props.fileType}
- name={props.name}
- isOwner={props.isOwner}
- parentId={props.parentId}
- lastEdited={props.lastEdited}
- context={props.context}
- isEditing={props.isEditing}
- selectedItems={props.selectedItems}
- setSelectedItems={props.setSelectedItems}
- size={props.size}
- deactivated={props.deactivated}
- >
- <DroppableItem
- id={props.id}
- type={props.itemType}
- fileType={props.fileType}
- name={props.name}
- isOwner={props.isOwner}
- parentId={props.parentId}
- depth={props.depth}
- context={props.context}
- isEditing={props.isEditing}
- deactivated={props.deactivated}
- >
- {props.children}
- </DroppableItem>
- </DraggableItem>
- );
-}
diff --git a/js/app/packages/core/component/FileList/DraggableItem.tsx b/js/app/packages/core/component/FileList/DraggableItem.tsx
deleted file mode 100644
index b665c4c933..0000000000
--- a/js/app/packages/core/component/FileList/DraggableItem.tsx
+++ /dev/null
@@ -1,119 +0,0 @@
-import type { ItemType } from '@service-storage/client';
-import type { FileType } from '@service-storage/generated/schemas/fileType';
-import type { Item } from '@service-storage/generated/schemas/item';
-import type { DragEvent } from '@thisbeyond/solid-dnd';
-import { createDraggable } from '@thisbeyond/solid-dnd';
-import {
- type Accessor,
- createEffect,
- createMemo,
- createSignal,
- type ParentProps,
- type Setter,
- Show,
-} from 'solid-js';
-import type { FileListSize } from './constants';
-
-declare module 'solid-js' {
- namespace JSX {
- interface Directives {
- draggable: any; // or a more specific type if you have one
- }
- }
-}
-
-export type DraggableItemProps = {
- type: ItemType;
- context?: string;
- isEditing?: boolean;
- id: string;
- fileType?: FileType;
- name: string;
- isOwner: boolean;
- parentId?: string;
- small?: boolean;
- lastEdited?: string | number;
- depth?: number;
- selectedItems: Accessor<Item[]>;
- setSelectedItems: Setter<Item[]>;
- size?: FileListSize;
- deactivated?: boolean;
-};
-
-export type DragEventWithData = DragEvent & {
- draggable: {
- data: DraggableData;
- };
-};
-
-export type DraggableData = {
- name: string;
- id: string;
- type: ItemType;
- fileType?: FileType;
- isOwner?: boolean;
- parentId?: string;
- lastEdited?: string | number;
- depth?: number;
- small?: boolean;
- isBulkMove?: boolean;
- selectedItems?: Item[];
- setSelectedItems?: Setter<Item[]>;
- size?: FileListSize;
-};
-
-export function DraggableItem(props: ParentProps<DraggableItemProps>) {
- const isSelected = createMemo(() => {
- return props.selectedItems().some((item) => item.id === props.id);
- });
-
- const draggableData = createMemo(
- () =>
- ({
- id: props.id,
- name: props.name,
- type: props.type,
- fileType: props.fileType,
- isOwner: props.isOwner,
- parentId: props.parentId,
- lastEdited: props.lastEdited,
- depth: props.depth,
- small: props.small,
- isBulkMove: isSelected() && props.selectedItems().length > 1,
- selectedItems: props.selectedItems(),
- setSelectedItems: props.setSelectedItems,
- size: props.size,
- }) as DraggableData
- );
-
- const draggableId = props.context ? `${props.id}-${props.context}` : props.id;
-
- let draggableRef: HTMLDivElement | undefined;
- const [draggable, setDraggable] = createSignal(
- createDraggable(draggableId, draggableData())
- );
-
- createEffect(() => {
- const data = draggableData();
- if (draggableRef) {
- const newDraggable = createDraggable(draggableId, data);
- setDraggable(() => newDraggable);
- newDraggable(draggableRef);
- }
- });
-
- return (
- <Show
- when={!props.isEditing && !props.deactivated}
- fallback={props.children}
- >
- <div
- ref={draggableRef}
- use:draggable={draggable()}
- class={`${draggable().isActiveDraggable ? 'z-side-panel-layout pointer-events-none' : ''}`}
- >
- {props.children}
- </div>
- </Show>
- );
-}
diff --git a/js/app/packages/core/component/FileList/DroppableItem.tsx b/js/app/packages/core/component/FileList/DroppableItem.tsx
deleted file mode 100644
index 38403b8a82..0000000000
--- a/js/app/packages/core/component/FileList/DroppableItem.tsx
+++ /dev/null
@@ -1,78 +0,0 @@
-import type { ItemType } from '@service-storage/client';
-import type { FileType } from '@service-storage/generated/schemas/fileType';
-import { createDroppable, useDragDropContext } from '@thisbeyond/solid-dnd';
-import { createMemo, type ParentProps, Show } from 'solid-js';
-
-export type DroppapleItemProps = {
- type: ItemType;
- context?: string;
- isEditing?: boolean;
- id: string;
- fileType?: FileType;
- name: string;
- isOwner: boolean;
- parentId?: string;
- small?: boolean;
- lastEdited?: string | number;
- depth?: number;
- deactivated?: boolean;
-};
-
-declare module 'solid-js' {
- namespace JSX {
- interface Directives {
- droppable: any; // or a more specific type if you have one
- }
- }
-}
-
-export type DroppableData = {
- type: ItemType | 'explorer-base';
- name: string;
- id: string;
- context?: string;
- isOwner?: boolean;
- parentId?: string;
- depth?: number;
-};
-
-export function DroppableItem(props: ParentProps<DroppapleItemProps>) {
- const data: DroppableData = {
- type: props.type,
- name: props.name,
- id: props.id,
- isOwner: props.isOwner,
- parentId: props.parentId ?? undefined,
- depth: props.depth,
- };
- const droppableId = props.context ? `${props.id}-${props.context}` : props.id;
- const droppable = createDroppable(droppableId, data);
- const [state] = useDragDropContext() ?? [];
-
- const draggable = createMemo(() => state?.active.draggable);
-
- const activeClass = () => {
- if (droppable.isActiveDroppable) {
- // Drag is drop, no-op
- if (draggable()?.data.id === props.id) {
- return '';
- }
- if (props.type === 'project') {
- return 'droppable rounded-lg bg-accent/20';
- } else {
- return `explorer-child-${props.depth}`;
- }
- }
- return '';
- };
- return (
- <Show
- when={!props.isEditing && !props.deactivated}
- fallback={props.children}
- >
- <div use:droppable class={`${activeClass()}`}>
- {props.children}
- </div>
- </Show>
- );
-}
diff --git a/js/app/packages/core/component/FileList/itemOperations.ts b/js/app/packages/core/component/FileList/itemOperations.ts
index efa5fc8c1b..605d92b525 100644
--- a/js/app/packages/core/component/FileList/itemOperations.ts
+++ b/js/app/packages/core/component/FileList/itemOperations.ts
@@ -317,9 +317,7 @@ export async function bulkMoveToFolder(
};
}
-/**
- * Note: Currently we do not support copying projects.
- */
+/** NOTE: Currently we do not support copying projects */
export async function copyItem(args: {
itemType: Exclude<ItemType, 'project'>;
id: string;
@@ -327,13 +325,16 @@ export async function copyItem(args: {
}): Promise<string | null> {
const { itemType, id, name } = args;
const { showPaywall } = usePaywallState();
+ const createCopyName = (originalName: string): string => {
+ return `${originalName} copy`;
+ };
let newId = '';
switch (itemType) {
case 'document': {
const result = await storageServiceClient.copyDocument({
documentId: id,
- documentName: `${name} copy`,
+ documentName: createCopyName(name),
});
if (isErr(result)) return null;
newId = result[1].documentId;
@@ -342,7 +343,7 @@ export async function copyItem(args: {
case 'chat': {
const result = await cognitionApiServiceClient.copyChat({
chat_id: id,
- name,
+ name: createCopyName(name),
});
if (isPaymentError(result)) {
showPaywall();
diff --git a/js/app/packages/core/component/FileList/updateItemParentOnDrop.ts b/js/app/packages/core/component/FileList/updateItemParentOnDrop.ts
deleted file mode 100644
index 6138090537..0000000000
--- a/js/app/packages/core/component/FileList/updateItemParentOnDrop.ts
+++ /dev/null
@@ -1,153 +0,0 @@
-import { useUserId } from '@service-gql/client';
-import type { Item } from '@service-storage/generated/schemas/item';
-import { optimisticUpdateParent } from '@service-storage/history';
-import { getAllChildProjectIds } from '@service-storage/projects';
-import { refetchResources } from '@service-storage/util/refetchResources';
-import {
- getPermissions,
- hasPermissions,
- Permissions,
-} from '../SharePermissions';
-import { toast } from '../Toast/Toast';
-import type { DragEventWithData } from './DraggableItem';
-import { useItemOperations } from './useItemOperations';
-
-export const updateItemParentOnDrop = async (args: {
- draggable: DragEventWithData['draggable'];
- parentId: string;
- parentName: string;
-}): Promise<void> => {
- const { draggable, parentId, parentName } = args;
-
- const { getItemAccessLevel } = useItemOperations();
- const accessLevel =
- parentId === ''
- ? 'owner'
- : await getItemAccessLevel({
- itemType: 'project',
- id: parentId,
- });
-
- if (!hasPermissions(getPermissions(accessLevel), Permissions.CAN_EDIT)) {
- return toast.failure(
- `You do not have permission to move items to ${parentName}`
- );
- }
-
- if (draggable.data.isBulkMove) {
- const items = draggable.data.selectedItems;
- if (!items) {
- return;
- }
- const failures: { item: Item; reason: string }[] = [];
- const userId = useUserId();
-
- await Promise.all(
- items.map(async (item) => {
- const itemParentId =
- item.type === 'project' ? item.parentId : item.projectId;
- const itemOwner =
- item.type === 'project' || item.type === 'chat'
- ? item.userId
- : item.owner;
-
- if (itemOwner !== userId()) {
- failures.push({ item, reason: 'You do not own this item' });
- return;
- }
-
- if (item.id === parentId) {
- failures.push({ item, reason: 'Cannot move item into itself' });
- return;
- }
- if (!itemParentId && !parentId) {
- failures.push({ item, reason: 'Already in root' });
- return;
- }
- if (getAllChildProjectIds(item.id).includes(parentId)) {
- failures.push({ item, reason: 'Cannot move parent into child' });
- return;
- }
- if (itemParentId === parentId) {
- failures.push({ item, reason: 'Already in destination' });
- return;
- }
-
- const success = await optimisticUpdateParent(
- item.type,
- item.id,
- parentId ?? ''
- );
-
- if (!success) {
- failures.push({ item, reason: 'Update failed' });
- }
- })
- );
-
- const successCount = items.length - failures.length;
- if (successCount > 0) {
- toast.success(`Moved ${successCount} items to ${parentName}`);
- }
-
- if (draggable.data.setSelectedItems) {
- draggable.data.setSelectedItems(() => failures.map((f) => f.item));
- }
-
- failures.forEach(({ item, reason }) => {
- const itemShortName =
- item.name.length < 30 ? item.name : item.name.slice(0, 27) + '...';
- toast.failure(`Failed to move "${itemShortName}": ${reason}`);
- });
- } else {
- // Draggable data
- const itemType = draggable.data.type;
- const itemId = draggable.data.id;
- const itemParentId = draggable.data.parentId
- ? String(draggable.data.parentId)
- : undefined;
- const itemShortName =
- draggable.data.name.length < 30
- ? draggable.data.name
- : draggable.data.name.slice(0, 27) + '...';
-
- // Droppable data
- const parentShortName =
- parentName.length < 30 ? parentName : parentName.slice(0, 27) + '...';
-
- const dragChildren = getAllChildProjectIds(itemId);
-
- if (itemId === parentId) {
- return;
- }
-
- if (!itemParentId && !parentId) {
- return;
- }
-
- if (dragChildren.includes(parentId)) {
- return toast.failure(
- `${parentShortName} is contained by ${itemShortName}. Can not move here.`
- );
- }
-
- if (itemParentId === parentId) {
- return;
- }
-
- // TODO: update this with correct permissions when we have project sharing
- if (draggable.data.isOwner !== true) {
- return toast.failure(
- `You do not own ${itemShortName}, it can not be moved`
- );
- }
-
- if (await optimisticUpdateParent(itemType, itemId, parentId ?? '')) {
- toast.success(`Moved "${itemShortName}" to ${parentShortName}`);
- } else {
- toast.failure(`Could not move "${itemShortName}"`);
- }
- }
-
- refetchResources();
-};
diff --git a/js/app/packages/core/directive/dnd.ts b/js/app/packages/core/directive/dnd.ts
new file mode 100644
index 0000000000..13274d360e
--- /dev/null
+++ b/js/app/packages/core/directive/dnd.ts
@@ -0,0 +1,11 @@
+// Type declarations for @thisbeyond/solid-dnd directives
+declare module 'solid-js' {
+ namespace JSX {
+ interface Directives {
+ draggable: any;
+ droppable: any;
+ }
+ }
+}
+
+export {};
diff --git a/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx b/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx
index e9069f2380..c3a5941aca 100644
--- a/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx
+++ b/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx
@@ -1,6 +1,7 @@
import { EntityIcon } from '@core/component/EntityIcon';
import type { Property } from '@core/component/Properties/types';
import { LabelAndHotKey, Tooltip } from '@core/component/Tooltip';
+import '@core/directive/dnd';
import { TOKENS } from '@core/hotkey/tokens';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { matches } from '@core/util/match';
@@ -9,7 +10,8 @@ import { tryToTypedNotification } from '@notifications';
import { useEmail, useUserId } from '@service-gql/client';
import { syncServiceClient } from '@service-sync/client';
import { mergeRefs } from '@solid-primitives/refs';
-import { createDraggable, createDroppable } from '@thisbeyond/solid-dnd';
+import { createDraggable } from '@thisbeyond/solid-dnd';
+import { useDragOperation } from '@app/component/ItemDragAndDrop';
import { getIconConfig } from 'core/component/EntityIcon';
import { StaticMarkdown } from 'core/component/LexicalMarkdown/component/core/StaticMarkdown';
import { unifiedListMarkdownTheme } from 'core/component/LexicalMarkdown/theme';
@@ -20,6 +22,7 @@ import {
createDeferred,
createMemo,
createSignal,
+ createUniqueId,
For,
Match,
onCleanup,
@@ -48,6 +51,7 @@ import type {
SearchLocation,
WithSearch,
} from '../types/search';
+import type { EntityDragData } from '../types/drag';
import { KeyPropertiesGrid } from './EntityPropertyValues';
export type EntityClickEvent = Parameters<
@@ -469,6 +473,7 @@ interface EntityProps<T extends WithNotification<EntityData>>
onChecked?: (checked: boolean, shiftKey?: boolean) => void;
checked?: boolean;
searchActive?: boolean;
+ splitId?: string;
}
const [hoveredComponentId, setHoveredComponentId] = createSignal<Symbol>(
@@ -868,10 +873,26 @@ export function EntityWithEverything(
);
});
- const draggable = createDraggable(props.entity.id, props.entity);
+ const { isAltKey } = useDragOperation();
+ const operation = createMemo(() => {
+ switch (props.entity.type) {
+ case 'document':
+ return isAltKey() ? 'copy' : 'move';
+ case 'chat':
+ return isAltKey() ? 'copy' : 'move';
+ default:
+ return 'move';
+ }
+ });
+ const draggableId = `${props.entity.id}-${props.splitId ?? createUniqueId()}`;
+ const dragData: EntityDragData = {
+ dragType: 'entity',
+ splitId: props.splitId,
+ ...props.entity,
+ operation,
+ };
+ const draggable = createDraggable(draggableId, dragData);
false && draggable;
- const droppable = createDroppable(props.entity.id, props.entity);
- false && droppable;
// The main click handler for the entity row should navigate to an entity
// without forcing focus back to the source split until after navigation.
@@ -913,7 +934,6 @@ export function EntityWithEverything(
return (
<div
use:draggable
- use:droppable
data-checked={props.checked}
class="everything-entity w-full relative group/entity hover:bg-hover/30 text-sm touch:mobile-width:text-base mx-[1px]"
style={{
diff --git a/js/app/packages/macro-entity/src/components/ProjectDrop.tsx b/js/app/packages/macro-entity/src/components/ProjectDrop.tsx
new file mode 100644
index 0000000000..2b1301aed2
--- /dev/null
+++ b/js/app/packages/macro-entity/src/components/ProjectDrop.tsx
@@ -0,0 +1,164 @@
+import type { EntityDragData, EntityDragEvent } from '../types/drag';
+import {
+ createCopyDssEntityMutation,
+ createMoveToProjectDssEntityMutation,
+} from '../queries/dss';
+import { createDroppable, useDragDropContext } from '@thisbeyond/solid-dnd';
+import { createMemo, Show } from 'solid-js';
+import { FileDropOverlay } from '@core/component/FileDropOverlay';
+
+export type ProjectDropData = {
+ dropType: 'project';
+ id: string;
+};
+
+export const ProjectDropOverlay = (props: {
+ projectId: string;
+ name?: string;
+ splitId?: string;
+}) => {
+ const [state, { onDragEnd }] = useDragDropContext() ?? [
+ undefined,
+ {
+ onDragEnd: () => {},
+ },
+ ];
+
+ const moveMutation = createMoveToProjectDssEntityMutation();
+ const copyMutation = createCopyDssEntityMutation();
+
+ onDragEnd((event: EntityDragEvent) => {
+ const droppable = event.droppable;
+ if (
+ !droppable ||
+ droppable.id !== props.projectId ||
+ droppable.data?.dropType !== 'project'
+ )
+ return;
+
+ const dropData = droppable.data as ProjectDropData;
+ const targetProjectId = dropData.id;
+
+ const draggable = event.draggable;
+ if (!draggable?.data) return;
+
+ const entityData = draggable.data;
+
+ // ignore drag and drop within same split
+ if (entityData.splitId === props.splitId) return;
+
+ switch (entityData.operation()) {
+ case 'copy':
+ if (entityData.type !== 'document' && entityData.type !== 'chat') {
+ console.error('copy only supported for document and chat');
+ return;
+ }
+ copyMutation.mutate(
+ {
+ entity: entityData,
+ },
+ {
+ onSuccess: (id: string) => {
+ // TODO: add project id as an argument to backend copy endpoint
+ // so we don't need multiple calls to copy and move
+ moveMutation.mutate({
+ entity: {
+ ...entityData,
+ id,
+ },
+ project: {
+ id: targetProjectId,
+ },
+ });
+ },
+ }
+ );
+ break;
+ case 'move':
+ if (
+ entityData.type !== 'document' &&
+ entityData.type !== 'chat' &&
+ entityData.type !== 'project'
+ ) {
+ console.error('move only supported for document, chat, and project');
+ return;
+ }
+ moveMutation.mutate({
+ entity: entityData,
+ project: {
+ id: targetProjectId,
+ },
+ });
+ break;
+ }
+ });
+
+ const entityDragData = createMemo(() => {
+ const draggable = state?.active.draggable;
+ if (!draggable) return;
+ const dragData = draggable.data;
+ if (!dragData || dragData.dragType !== 'entity') return;
+ return dragData as EntityDragData;
+ });
+
+ const showProjectOverlay = createMemo(() => {
+ const dragData = entityDragData();
+ if (!dragData) return false;
+
+ const entityType = dragData.type;
+ if (
+ entityType !== 'document' &&
+ entityType !== 'chat' &&
+ entityType !== 'project'
+ ) {
+ return false;
+ }
+
+ // Don't show overlay if dragging within the same split
+ if (props.splitId && dragData.splitId === props.splitId) return false;
+
+ const activeDroppable = state?.active.droppable;
+
+ if (!activeDroppable || activeDroppable.data.dropType !== 'project')
+ return false;
+
+ // Show overlay if dropping on this project or an entity within it
+ if (activeDroppable.id === props.projectId) return true;
+
+ return false;
+ });
+
+ const dropActionText = createMemo(() => {
+ switch (entityDragData()?.operation?.()) {
+ case 'copy':
+ return 'Copy to this folder';
+ case 'move':
+ return 'Move to this folder';
+ }
+ });
+
+ return (
+ <>
+ <Show when={props.projectId} keyed>
+ {(projectId) => {
+ const data: ProjectDropData = {
+ dropType: 'project',
+ id: projectId,
+ };
+ const droppable = createDroppable(props.projectId, data);
+ false && droppable;
+
+ return (
+ <div
+ use:droppable
+ class="absolute inset-0 pointer-events-none z-10"
+ />
+ );
+ }}
+ </Show>
+ <Show when={showProjectOverlay()}>
+ <FileDropOverlay>{dropActionText()}</FileDropOverlay>
+ </Show>
+ </>
+ );
+};
diff --git a/js/app/packages/macro-entity/src/components/UnifiedInfiniteList.tsx b/js/app/packages/macro-entity/src/components/UnifiedInfiniteList.tsx
index e3fabbb5ae..48929f80cc 100644
--- a/js/app/packages/macro-entity/src/components/UnifiedInfiniteList.tsx
+++ b/js/app/packages/macro-entity/src/components/UnifiedInfiniteList.tsx
@@ -2,6 +2,7 @@ import { useSuspenseContext } from '@app/component/SuspenseContext';
import { EmptyState } from '@app/component/UnifiedListEmptyState';
import { CustomScrollbar } from '@core/component/CustomScrollbar';
import { toast } from '@core/component/Toast/Toast';
+import '@core/directive/dnd';
import type { ViewId } from '@core/types/view';
import { onElementConnect } from '@solid-primitives/lifecycle';
import { debounce } from '@solid-primitives/scheduled';
@@ -42,6 +43,7 @@ import type {
} from '../types/entity';
import type { WithSearch } from '../types/search';
import { Entity } from './Entity';
+import { ProjectDropOverlay } from './ProjectDrop';
const DEBOUNCE_FETCH_MORE_MS = 50;
@@ -452,6 +454,9 @@ export function createUnifiedInfiniteList<T extends EntityData>({
viewId?: ViewId;
searchText?: string;
entityMinHeight?: number;
+ viewType?: string;
+ name?: string;
+ splitId?: string;
}) => {
const [scrollParentRef, setScrollParentRef] =
createSignal<HTMLDivElement>();
@@ -626,107 +631,118 @@ export function createUnifiedInfiniteList<T extends EntityData>({
});
return (
- <Switch>
- <Match when={showEmptyState()}>
- <EmptyState
- viewId={props.viewId}
- search={!!props.searchText}
- hasRefinementsFromBase={props.hasRefinementsFromBase}
- />
- </Match>
- <Match when={true}>
- <div class="flex size-full relative" ref={setListRef}>
- <StaticMarkdownContext>
- <div
- class="size-full relative scrollbar-hidden"
- data-unified-entity-list
- ref={(el) => {
- onElementConnect(el, () => {
- setScrollParentRef(el as HTMLDivElement);
- });
- }}
- style={{
- overflow: 'auto',
- }}
- >
+ <>
+ <Show when={props.viewType === 'project' && props.viewId}>
+ {(id) => (
+ <ProjectDropOverlay
+ projectId={id()}
+ name={props.name}
+ splitId={props.splitId}
+ />
+ )}
+ </Show>
+ <Switch>
+ <Match when={showEmptyState()}>
+ <EmptyState
+ viewId={props.viewId}
+ search={!!props.searchText}
+ hasRefinementsFromBase={props.hasRefinementsFromBase}
+ />
+ </Match>
+ <Match when={true}>
+ <div class="flex size-full relative" ref={setListRef}>
+ <StaticMarkdownContext>
<div
+ class="size-full relative scrollbar-hidden"
+ data-unified-entity-list
ref={(el) => {
onElementConnect(el, () => {
- props.entityListRef?.(el as HTMLDivElement);
+ setScrollParentRef(el as HTMLDivElement);
});
}}
style={{
- height: `${rowVirtualizer.getTotalSize()}px`,
- width: '100%',
- position: 'relative',
+ overflow: 'auto',
}}
>
<div
+ ref={(el) => {
+ onElementConnect(el, () => {
+ props.entityListRef?.(el as HTMLDivElement);
+ });
+ }}
style={{
- position: 'absolute',
- top: 0,
- left: 0,
+ height: `${rowVirtualizer.getTotalSize()}px`,
width: '100%',
- transform: `translateY(${rowVirtualizer.getVirtualItems()?.[0]?.start}px)`,
+ position: 'relative',
}}
>
- <For each={rowVirtualizer.getVirtualItems()}>
- {(virtualItem) => {
- if (
- untrack(() => virtualItem.index) >=
- Math.floor(untrack(sortedEntities).length * 0.9)
- ) {
- debouncedFetchMore();
- }
-
- return (
- <Show
- when={sortedEntitiesStore[virtualItem.index]?.id}
- keyed
- >
- {(_) => {
- const entity =
- sortedEntitiesStore[virtualItem.index];
- return (
- <Show when={entity}>
- <div
- data-index={virtualItem.index}
- ref={(el) =>
- queueMicrotask(() =>
- rowVirtualizer.measureElement(el)
- )
- }
- >
- <EntityRenderer
- entity={entity}
- index={virtualItem.index}
- />
- </div>
- </Show>
- );
- }}
- </Show>
- );
+ <div
+ style={{
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ width: '100%',
+ transform: `translateY(${rowVirtualizer.getVirtualItems()?.[0]?.start}px)`,
}}
- </For>
+ >
+ <For each={rowVirtualizer.getVirtualItems()}>
+ {(virtualItem) => {
+ if (
+ untrack(() => virtualItem.index) >=
+ Math.floor(untrack(sortedEntities).length * 0.9)
+ ) {
+ debouncedFetchMore();
+ }
+
+ return (
+ <Show
+ when={sortedEntitiesStore[virtualItem.index]?.id}
+ keyed
+ >
+ {(_) => {
+ const entity =
+ sortedEntitiesStore[virtualItem.index];
+ return (
+ <Show when={entity}>
+ <div
+ data-index={virtualItem.index}
+ ref={(el) =>
+ queueMicrotask(() =>
+ rowVirtualizer.measureElement(el)
+ )
+ }
+ >
+ <EntityRenderer
+ entity={entity}
+ index={virtualItem.index}
+ />
+ </div>
+ </Show>
+ );
+ }}
+ </Show>
+ );
+ }}
+ </For>
+ </div>
</div>
</div>
- </div>
- </StaticMarkdownContext>
- <CustomScrollbar
- scrollContainer={() => {
- // Find the actual scroll container (VList creates its own scroll container)
- const listEl = listRef();
- if (!listEl) return undefined;
- const scrollContainer = listEl.querySelector(
- '[data-unified-entity-list]'
- ) as HTMLElement;
- return scrollContainer || undefined;
- }}
- />
- </div>
- </Match>
- </Switch>
+ </StaticMarkdownContext>
+ <CustomScrollbar
+ scrollContainer={() => {
+ // Find the actual scroll container (VList creates its own scroll container)
+ const listEl = listRef();
+ if (!listEl) return undefined;
+ const scrollContainer = listEl.querySelector(
+ '[data-unified-entity-list]'
+ ) as HTMLElement;
+ return scrollContainer || undefined;
+ }}
+ />
+ </div>
+ </Match>
+ </Switch>
+ </>
);
};
diff --git a/js/app/packages/macro-entity/src/index.tsx b/js/app/packages/macro-entity/src/index.tsx
index dcbd905a32..50d6a3fa66 100644
--- a/js/app/packages/macro-entity/src/index.tsx
+++ b/js/app/packages/macro-entity/src/index.tsx
@@ -17,6 +17,8 @@ export {
createChatsInfiniteQuery,
createDeleteDssItemMutation,
createDssInfiniteQuery,
+ createMoveToProjectDssEntityMutation,
+ createCopyDssEntityMutation,
} from './queries/dss';
export { createEmailsInfiniteQuery } from './queries/email';
export type { EntityInfiniteQuery, EntityQuery } from './queries/entity';
@@ -24,6 +26,7 @@ export { queryKeys } from './queries/key';
export { enhanceWithNotifications } from './queries/notification';
export * from './queries/search';
export { createEmailSource, type EmailSource, useEmails } from './source/email';
+export type * from './types/drag';
export * from './types/entity';
export * from './types/notification';
export * from './types/search';
diff --git a/js/app/packages/macro-entity/src/queries/dss.ts b/js/app/packages/macro-entity/src/queries/dss.ts
index 40328e7f32..295938d16f 100644
--- a/js/app/packages/macro-entity/src/queries/dss.ts
+++ b/js/app/packages/macro-entity/src/queries/dss.ts
@@ -5,6 +5,7 @@ import {
renameItem,
} from '@core/component/FileList/itemOperations';
import { itemToSafeName } from '@core/constant/allBlocks';
+import { toast } from '@core/component/Toast/Toast';
import { type MutationCallbacks, withCallbacks } from '@queries/utils';
import type { UnifiedSearchResponseItem } from '@service-search/generated/models';
import type { ItemType } from '@service-storage/client';
@@ -410,11 +411,13 @@ export function createDeleteDssItemMutation() {
);
},
onSettled: (data, error, entity) => {
- if (data?.success === false || error)
+ if (data?.success === false || error) {
console.error(`Failed to delete dss item ${entity}`, data, error);
+ toast.failure('Failed to delete item');
+ }
queryClient.invalidateQueries({
- queryKey: queryKeys.dss({ infinite: true }),
+ queryKey: queryKeys.all.dss,
});
},
}));
@@ -525,6 +528,7 @@ export function createBulkDeleteDssItemsMutation() {
},
onError: (error, entities, _context) => {
console.error(`Failed to delete dss items`, entities, error);
+ toast.failure('Failed to delete items');
// Rollback on error - restore the deleted items
queryClient.invalidateQueries({
queryKey: queryKeys.all.dss,
@@ -612,11 +616,13 @@ export function createRenameDssEntityMutation(
);
},
onSettled: (data, error, { entity: { id } }) => {
- if (data?.success === false || error)
+ if (data?.success === false || error) {
console.error(`Failed to rename dss item ${id}`, data, error);
+ toast.failure('Failed to rename item');
+ }
queryClient.invalidateQueries({
- queryKey: queryKeys.dss({ infinite: true }),
+ queryKey: queryKeys.all.dss,
});
},
},
@@ -634,7 +640,7 @@ export function createBulkRenameDssEntityMutation() {
entities: (EntityData & { name: string })[];
name: (oldName: string) => string | string;
}) => {
- if (entities.every(isEntityRenameSupported)) {
+ if (!entities.every(isEntityRenameSupported)) {
throw new Error(`Unsupported entity type provided`);
}
return await Promise.all(
@@ -688,72 +694,95 @@ export function createBulkRenameDssEntityMutation() {
onSettled: (data, error, { entities }) => {
if (error) {
console.error(`Failed bulk rename`, entities, data, error);
+ toast.failure('Failed to rename items');
}
queryClient.invalidateQueries({
- queryKey: queryKeys.dss({ infinite: true }),
+ queryKey: queryKeys.all.dss,
});
},
}));
}
+function createMoveOptimisticUpdate(entityIds: string[], projectId: string) {
+ return (
+ prev: { pages: { items: EntityData[] }[] } | undefined
+ ): { pages: { items: EntityData[] }[] } | undefined => {
+ if (!prev) return prev;
+ const pages = prev.pages.map((page) => ({
+ ...page,
+ items: page.items.map((item) =>
+ entityIds.includes(item.id) ? { ...item, projectId } : item
+ ),
+ }));
+ return {
+ ...prev,
+ pages,
+ };
+ };
+}
+
+function invalidateAfterMove(hasProjects: boolean, failed?: boolean) {
+ if (failed) {
+ toast.failure('Failed to move item');
+ }
+
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.all.dss,
+ });
+ queryClient.invalidateQueries({ queryKey: ['entity'] });
+ // If moving a project, invalidate all project queries since nested projects' breadcrumbs change too
+ if (hasProjects) {
+ queryClient.invalidateQueries({
+ queryKey: ['project'],
+ });
+ }
+}
+
export function createMoveToProjectDssEntityMutation() {
return useMutation(() => ({
mutationFn: async ({
entity: { id, type },
project: { id: projectId },
}: {
- entity: EntityData & { name: string };
- project: { id: string; name: string };
+ entity: EntityData & { type: 'document' | 'chat' | 'project' };
+ project: { id: string };
}) => {
const success = await moveToFolder({
- itemType: type as 'document' | 'chat' | 'project',
- id: id,
+ itemType: type,
+ id,
folderId: projectId,
});
return { success };
},
onMutate: async ({
- entity: { id },
+ entity: { id, type },
project: { id: projectId },
}: {
- entity: EntityData & { name: string };
- project: { id: string; name: string };
+ entity: EntityData & { type: 'document' | 'chat' | 'project' };
+ project: { id: string };
}) => {
queryClient.cancelQueries({
queryKey: queryKeys.dss({ infinite: true }),
});
- function updateEntityProjectIdInQueryData(
- prev: { pages: { items: EntityData[] }[] } | undefined
- ): { pages: { items: EntityData[] }[] } | undefined {
- if (!prev) return prev;
- const pages = prev.pages.map((page) => ({
- ...page,
- items: page.items.map((item) =>
- item.id === id ? { ...item, projectId: projectId } : item
- ),
- }));
- return {
- ...prev,
- pages,
- };
+
+ // Only do optimistic updates for documents and chats
+ // Projects have complex path data that we can't compute client-side
+ if (type !== 'project') {
+ queryClient.setQueriesData(
+ { queryKey: queryKeys.all.dss },
+ createMoveOptimisticUpdate([id], projectId)
+ );
}
- queryClient.setQueriesData(
- { queryKey: queryKeys.dss({ infinite: true }) },
- (prev) =>
- updateEntityProjectIdInQueryData(
- prev as { pages: { items: EntityData[] }[] } | undefined
- )
- );
},
- onSettled: (data, error, { entity: { id } }) => {
- if (data?.success === false || error)
+ onSettled: (data, error, { entity: { id, type } }) => {
+ const failed = data?.success === false || !!error;
+ if (failed) {
console.error(`Failed to move dss item ${id}`, data, error);
+ }
- queryClient.invalidateQueries({
- queryKey: queryKeys.dss({ infinite: true }),
- });
+ invalidateAfterMove(type === 'project', failed);
},
}));
}
@@ -763,24 +792,19 @@ export function createCopyDssEntityMutation() {
mutationFn: async ({
entity: { id, type, name },
}: {
- entity: EntityData & { name: string };
+ entity: EntityData & { type: 'document' | 'chat' };
}) => {
- if (type !== 'chat' && type !== 'document')
- throw new Error(
- `Unsupported entity type: ${type} for id ${id}. Projects cannot be copied.`
- );
-
- const success = await copyItem({
- itemType: type as 'document' | 'chat',
+ const newId = await copyItem({
+ itemType: type,
id,
name,
});
- if (!success) {
+ if (!newId) {
throw new Error(`Failed to copy ${type} with id ${id}`);
}
- return { success: true };
+ return newId;
},
onMutate: async () => {
queryClient.cancelQueries({
@@ -790,11 +814,14 @@ export function createCopyDssEntityMutation() {
// The new item will be added when the mutation completes and queries are invalidated
},
onSettled: (data, error, { entity: { id } }) => {
- if (error) console.error(`Failed to copy dss item ${id}`, data, error);
-
+ if (error) {
+ console.error(`Failed to copy dss item ${id}`, data, error);
+ toast.failure('Failed to copy item');
+ }
queryClient.invalidateQueries({
- queryKey: queryKeys.dss({ infinite: true }),
+ queryKey: queryKeys.all.dss,
});
+ queryClient.invalidateQueries({ queryKey: ['entity'] });
},
}));
}
@@ -845,12 +872,14 @@ export function createBulkCopyDssEntityMutation() {
onSettled: (data, error, { entities }) => {
if (error) {
console.error(`Failed bulk copy`, entities, data, error);
+ toast.failure('Failed to copy items');
}
// Trigger refetch so new items appear
queryClient.invalidateQueries({
- queryKey: queryKeys.dss({ infinite: true }),
+ queryKey: queryKeys.all.dss,
});
+ queryClient.invalidateQueries({ queryKey: ['entity'] });
},
}));
}
@@ -901,41 +930,30 @@ export function createBulkMoveToProjectDssEntityMutation() {
queryKey: queryKeys.dss({ infinite: true }),
});
- function updateEntityProjectIdInQueryData(
- prev: { pages: { items: EntityData[] }[] } | undefined
- ): { pages: { items: EntityData[] }[] } | undefined {
- if (!prev) return prev;
- const entityIds = entities.map((e) => e.id);
- const pages = prev.pages.map((page) => ({
- ...page,
- items: page.items.map((item) =>
- entityIds.includes(item.id)
- ? { ...item, projectId: project.id }
- : item
- ),
- }));
- return {
- ...prev,
- pages,
- };
- }
+ // Only do optimistic updates for documents and chats
+ // Projects have complex path data that we can't compute client-side
+ const nonProjectIds = entities
+ .filter((e) => e.type !== 'project')
+ .map((e) => e.id);
- queryClient.setQueriesData(
- { queryKey: queryKeys.dss({ infinite: true }) },
- (prev) =>
- updateEntityProjectIdInQueryData(
- prev as { pages: { items: EntityData[] }[] } | undefined
- )
- );
+ if (nonProjectIds.length > 0) {
+ queryClient.setQueriesData(
+ { queryKey: queryKeys.dss({ infinite: true }) },
+ createMoveOptimisticUpdate(nonProjectIds, project.id)
+ );
+ }
},
onSettled: (data, error, { entities }) => {
- if (data?.success === false || error)
+ const failed = data?.success === false || !!error;
+ if (failed) {
console.error(`Failed to bulk move dss items`, entities, data, error);
+ }
- queryClient.invalidateQueries({
- queryKey: queryKeys.dss({ infinite: true }),
- });
+ invalidateAfterMove(
+ entities.some((e) => e.type === 'project'),
+ failed
+ );
},
}));
}
diff --git a/js/app/packages/macro-entity/src/types/drag.ts b/js/app/packages/macro-entity/src/types/drag.ts
new file mode 100644
index 0000000000..765ae16d4d
--- /dev/null
+++ b/js/app/packages/macro-entity/src/types/drag.ts
@@ -0,0 +1,17 @@
+import type { DragEvent } from '@thisbeyond/solid-dnd';
+import type { EntityData } from './entity';
+import type { Accessor } from 'solid-js';
+
+export type EntityDragOperation = 'move' | 'copy';
+
+export type EntityDragData = EntityData & {
+ dragType: 'entity';
+ operation: Accessor<EntityDragOperation>;
+ splitId?: string;
+};
+
+export type EntityDragEvent = DragEvent & {
+ draggable: {
+ data: EntityDragData;
+ };
+};
diff --git a/js/app/packages/service-clients/service-storage/history.ts b/js/app/packages/service-clients/service-storage/history.ts
index e5903faf6c..bbde737ffa 100644
--- a/js/app/packages/service-clients/service-storage/history.ts
+++ b/js/app/packages/service-clients/service-storage/history.ts
@@ -1,11 +1,10 @@
import { itemToSafeName } from '@core/constant/allBlocks';
import { isErr, isOk, ok } from '@core/util/maybeResult';
import type { HistoryItem } from '@queries/history/transforms';
-import { cognitionApiServiceClient } from '@service-cognition/client';
import { createSingletonRoot } from '@solid-primitives/rootless';
import { buildFileTree } from 'core/component/FileList/buildFileTree';
import { type Accessor, createMemo, createResource } from 'solid-js';
-import { type ItemType, storageServiceClient } from './client';
+import { storageServiceClient } from './client';
import type { CloudStorageItemType } from './generated/schemas/cloudStorageItemType';
import type { Item } from './generated/schemas/item';
import { useInstructionsMdIdQuery } from './instructionsMd';
@@ -185,60 +184,6 @@ export async function removeHistoryItem(
return false;
}
-export async function optimisticUpdateParent(
- itemType: ItemType,
- itemId: string,
- parentId: string
-) {
- const [resource, { mutate }] = historyResource();
- const result = resource.latest;
- if (resource.error || isErr(result)) return false;
-
- const currentHistory = result[1].data;
-
- // Create new history array with the item moved
- const newHistory = [...currentHistory].map((item) => {
- const currentId = item.id;
- if (currentId === itemId) {
- return {
- ...item,
- };
- }
- return item;
- });
-
- // Optimistically update the UI
- mutate(
- ok({
- data: newHistory,
- })
- );
-
- // And then check the Server
-
- let maybeUpdated;
- if (itemType === 'document') {
- maybeUpdated = await storageServiceClient.editDocument({
- documentId: itemId,
- projectId: parentId,
- });
- } else if (itemType === 'chat') {
- maybeUpdated = await cognitionApiServiceClient.editChatProject({
- chat_id: itemId,
- project_id: parentId,
- });
- } else {
- maybeUpdated = await storageServiceClient.projects.edit({
- id: itemId,
- projectParentId: parentId,
- });
- }
-
- refetchResources();
- if (isErr(maybeUpdated)) return false;
- return maybeUpdated[1]?.success;
-}
-
export async function postNewHistoryItem(
itemType: CloudStorageItemType,
itemId: string