Skip to content

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

Implement file upload in messages

Hakan Shehu73a161d68648
diff --git a/desktop/index.html b/desktop/index.html
index ad89e1b2..bd976de6 100644
--- a/desktop/index.html
+++ b/desktop/index.html
@@ -5,7 +5,7 @@
<title>Neuron</title>
<meta
http-equiv="Content-Security-Policy"
- content="default-src 'self' 'unsafe-inline' data: avatar: local-file: asset:;"
+ content="default-src 'self' 'unsafe-inline' data: avatar: local-file: local-file-preview: asset:;"
/>
</head>
<body>
diff --git a/desktop/src/lib/constants.ts b/desktop/src/lib/constants.ts
index a8cd0e5d..d46003b7 100644
--- a/desktop/src/lib/constants.ts
+++ b/desktop/src/lib/constants.ts
@@ -32,6 +32,9 @@ export const EditorNodeTypes = {
TaskItem: 'taskItem',
HorizontalRule: 'horizontalRule',
Page: 'page',
+ File: 'file',
+ Folder: 'folder',
+ FilePlaceholder: 'filePlaceholder',
};
export const ViewNodeTypes: string[] = [
diff --git a/desktop/src/lib/files.ts b/desktop/src/lib/files.ts
index e7c4eb2b..7c5335aa 100644
--- a/desktop/src/lib/files.ts
+++ b/desktop/src/lib/files.ts
@@ -32,6 +32,10 @@ export const getFileUrl = (
return `local-file://${userId}/${fileId}${extension}`;
};
+export const getFilePlaceholderUrl = (path: string) => {
+ return `local-file-preview://${path}`;
+};
+
const friendlyNameMapping: Record<string, string> = {
// Application types
'application/msword': 'Word Document',
diff --git a/desktop/src/lib/id.ts b/desktop/src/lib/id.ts
index f803ad62..ae59ce3b 100644
--- a/desktop/src/lib/id.ts
+++ b/desktop/src/lib/id.ts
@@ -44,6 +44,7 @@ export enum IdType {
Avatar = 'av',
Icon = 'ic',
File = 'fi',
+ FilePlaceholder = 'fp',
}
export const generateId = (type: IdType): string => {
diff --git a/desktop/src/main.ts b/desktop/src/main.ts
index 4f1481f7..078f173b 100644
--- a/desktop/src/main.ts
+++ b/desktop/src/main.ts
@@ -9,6 +9,7 @@ import { socketManager } from '@/main/sockets/socket-manager';
import { synchronizer } from '@/main/synchronizer';
import { avatarManager } from '@/main/avatar-manager';
import { fileManager } from '@/main/file-manager';
+import { FileMetadata } from '@/types/files';
let subscriptionId: string | null = null;
@@ -62,6 +63,12 @@ const createWindow = async () => {
});
}
+ if (!protocol.isProtocolHandled('local-file-preview')) {
+ protocol.handle('local-file-preview', (request) => {
+ return fileManager.handleFilePreviewRequest(request);
+ });
+ }
+
if (!protocol.isProtocolHandled('asset')) {
protocol.handle('asset', (request) => {
const url = request.url.replace('asset://', '');
@@ -148,6 +155,13 @@ ipcMain.handle(
},
);
+ipcMain.handle(
+ 'get-file-metadata',
+ (_: unknown, path: string): FileMetadata | null => {
+ return fileManager.getFileMetadata(path);
+ },
+);
+
ipcMain.handle(
'open-file',
async (
diff --git a/desktop/src/main/file-manager.ts b/desktop/src/main/file-manager.ts
index 14ade384..3f5ed781 100644
--- a/desktop/src/main/file-manager.ts
+++ b/desktop/src/main/file-manager.ts
@@ -2,7 +2,9 @@ import { net, shell } from 'electron';
import path from 'path';
import fs from 'fs';
import axios from 'axios';
+import mime from 'mime-types';
import {
+ FileMetadata,
ServerFileDownloadResponse,
ServerFileUploadResponse,
} from '@/types/files';
@@ -28,6 +30,11 @@ class FileManager {
return new Response(null, { status: 404 });
}
+ public async handleFilePreviewRequest(request: Request): Promise<Response> {
+ const url = request.url.replace('local-file-preview://', 'file://');
+ return net.fetch(url);
+ }
+
public copyFileToWorkspace(
filePath: string,
fileId: string,
@@ -59,6 +66,27 @@ class FileManager {
fs.rmSync(filePath, { force: true });
}
+ public getFileMetadata(filePath: string): FileMetadata | null {
+ if (!fs.existsSync(filePath)) {
+ return null;
+ }
+
+ const mimeType = mime.lookup(filePath);
+ if (mimeType === false) {
+ return null;
+ }
+
+ const stats = fs.statSync(filePath);
+
+ return {
+ path: filePath,
+ mimeType,
+ extension: path.extname(filePath),
+ name: path.basename(filePath),
+ size: stats.size,
+ };
+ }
+
public async checkForUploads(
credentials: WorkspaceCredentials,
): Promise<void> {
diff --git a/desktop/src/main/handlers/mutations/file-create.ts b/desktop/src/main/handlers/mutations/file-create.ts
index edb7c642..73d9fdf5 100644
--- a/desktop/src/main/handlers/mutations/file-create.ts
+++ b/desktop/src/main/handlers/mutations/file-create.ts
@@ -1,6 +1,3 @@
-import fs from 'fs';
-import mime from 'mime-types';
-import path from 'path';
import * as Y from 'yjs';
import { databaseManager } from '@/main/data/database-manager';
import { MutationHandler, MutationResult } from '@/operations/mutations';
@@ -20,22 +17,21 @@ export class FileCreateMutationHandler
input.userId,
);
- const filePath = input.filePath;
- const fileName = path.basename(filePath);
- const extension = path.extname(filePath);
- const stats = fs.statSync(filePath);
-
- const size = stats.size;
- const mimeType = mime.lookup(filePath);
- if (mimeType === false) {
- throw new Error('Invalid file type');
+ const metadata = fileManager.getFileMetadata(input.filePath);
+ if (!metadata) {
+ throw new Error('Invalid file');
}
const id = generateId(IdType.File);
const versionId = generateId(IdType.Version);
const createdAt = new Date().toISOString();
- fileManager.copyFileToWorkspace(filePath, id, extension, input.userId);
+ fileManager.copyFileToWorkspace(
+ input.filePath,
+ id,
+ metadata.extension,
+ input.userId,
+ );
const doc = new Y.Doc({
guid: id,
@@ -45,11 +41,11 @@ export class FileCreateMutationHandler
doc.transact(() => {
attributesMap.set('type', NodeTypes.File);
attributesMap.set('parentId', input.parentId);
- attributesMap.set('name', fileName);
- attributesMap.set('fileName', fileName);
- attributesMap.set('extension', extension);
- attributesMap.set('size', size);
- attributesMap.set('mimeType', mimeType);
+ attributesMap.set('name', metadata.name);
+ attributesMap.set('fileName', metadata.name);
+ attributesMap.set('extension', metadata.extension);
+ attributesMap.set('size', metadata.size);
+ attributesMap.set('mimeType', metadata.mimeType);
});
const attributes = JSON.stringify(attributesMap.toJSON());
diff --git a/desktop/src/main/handlers/mutations/message-create.ts b/desktop/src/main/handlers/mutations/message-create.ts
index f8916a6a..faea509a 100644
--- a/desktop/src/main/handlers/mutations/message-create.ts
+++ b/desktop/src/main/handlers/mutations/message-create.ts
@@ -1,12 +1,23 @@
import * as Y from 'yjs';
import { databaseManager } from '@/main/data/database-manager';
-import { NodeTypes } from '@/lib/constants';
+import { EditorNodeTypes, NodeTypes } from '@/lib/constants';
import { generateId, IdType } from '@/lib/id';
-import { MutationHandler, MutationResult } from '@/operations/mutations';
+import {
+ MutationChange,
+ MutationHandler,
+ MutationResult,
+} from '@/operations/mutations';
import { MessageCreateMutationInput } from '@/operations/mutations/message-create';
import { fromUint8Array } from 'js-base64';
import { LocalCreateNodeChangeData } from '@/types/sync';
import { applyChangeToAttributesMap, mapContentsToBlocks } from '@/lib/editor';
+import { fileManager } from '@/main/file-manager';
+import {
+ CreateChange,
+ CreateDownload,
+ CreateNode,
+ CreateUpload,
+} from '@/main/data/workspace/schema';
export class MessageCreateMutationHandler
implements MutationHandler<MessageCreateMutationInput>
@@ -18,73 +29,174 @@ export class MessageCreateMutationHandler
input.userId,
);
- const id = generateId(IdType.Message);
- const versionId = generateId(IdType.Version);
+ const nodesToCreate: CreateNode[] = [];
+ const downloadsToCreate: CreateDownload[] = [];
+ const uploadsToCreate: CreateUpload[] = [];
+ const changesToCreate: CreateChange[] = [];
+
+ const messageId = generateId(IdType.Message);
+ const messageVersionId = generateId(IdType.Version);
const createdAt = new Date().toISOString();
+ const blocks = mapContentsToBlocks(
+ messageId,
+ input.content.content,
+ new Map(),
+ );
- const blocks = mapContentsToBlocks(id, input.content.content, new Map());
+ // check if there are nested nodes (files, pages, folders etc.)
+ for (const block of blocks) {
+ if (block.type === EditorNodeTypes.FilePlaceholder) {
+ const path = block.attrs.path;
+ const metadata = fileManager.getFileMetadata(path);
+ if (!metadata) {
+ throw new Error('Invalid file');
+ }
- const doc = new Y.Doc({
- guid: id,
- });
+ const fileId = generateId(IdType.File);
+ const fileVersionId = generateId(IdType.Version);
- const attributesMap = doc.getMap('attributes');
- doc.transact(() => {
- attributesMap.set('type', NodeTypes.Message);
- attributesMap.set('parentId', input.conversationId);
- applyChangeToAttributesMap(attributesMap, blocks);
- });
+ block.id = fileId;
+ block.type = NodeTypes.File;
+ block.attrs = null;
- const attributes = JSON.stringify(attributesMap.toJSON());
- const encodedState = fromUint8Array(Y.encodeStateAsUpdate(doc));
+ fileManager.copyFileToWorkspace(
+ path,
+ fileId,
+ metadata.extension,
+ input.userId,
+ );
- const changeData: LocalCreateNodeChangeData = {
- type: 'node_create',
- id: id,
- state: encodedState,
- createdAt: createdAt,
- createdBy: input.userId,
- versionId: versionId,
- };
+ const fileDoc = new Y.Doc({
+ guid: fileId,
+ });
- await workspaceDatabase.transaction().execute(async (trx) => {
- await trx
- .insertInto('nodes')
- .values({
- id: id,
- attributes: attributes,
- state: encodedState,
+ const fileAttributesMap = fileDoc.getMap('attributes');
+ fileDoc.transact(() => {
+ fileAttributesMap.set('type', NodeTypes.File);
+ fileAttributesMap.set('parentId', messageId);
+ fileAttributesMap.set('name', metadata.name);
+ fileAttributesMap.set('fileName', metadata.name);
+ fileAttributesMap.set('extension', metadata.extension);
+ fileAttributesMap.set('size', metadata.size);
+ fileAttributesMap.set('mimeType', metadata.mimeType);
+ });
+
+ const fileAttributes = JSON.stringify(fileAttributesMap.toJSON());
+ const encodedFileState = fromUint8Array(Y.encodeStateAsUpdate(fileDoc));
+
+ nodesToCreate.push({
+ id: fileId,
+ attributes: fileAttributes,
+ state: encodedFileState,
created_at: createdAt,
created_by: input.userId,
- version_id: versionId,
- })
- .execute();
-
- await trx
- .insertInto('changes')
- .values({
- data: JSON.stringify(changeData),
+ version_id: fileVersionId,
+ });
+
+ downloadsToCreate.push({
+ node_id: fileId,
+ created_at: createdAt,
+ progress: 100,
+ retry_count: 0,
+ });
+
+ uploadsToCreate.push({
+ node_id: fileId,
created_at: createdAt,
- })
- .execute();
+ progress: 0,
+ retry_count: 0,
+ });
+ }
+ }
+
+ const messageDoc = new Y.Doc({
+ guid: messageId,
+ });
+
+ const messageAttributesMap = messageDoc.getMap('attributes');
+ messageDoc.transact(() => {
+ messageAttributesMap.set('type', NodeTypes.Message);
+ messageAttributesMap.set('parentId', input.conversationId);
+ applyChangeToAttributesMap(messageAttributesMap, blocks);
+ });
+
+ const messageAttributes = JSON.stringify(messageAttributesMap.toJSON());
+ const encodedMessageState = fromUint8Array(
+ Y.encodeStateAsUpdate(messageDoc),
+ );
+
+ nodesToCreate.unshift({
+ id: messageId,
+ attributes: messageAttributes,
+ state: encodedMessageState,
+ created_at: createdAt,
+ created_by: input.userId,
+ version_id: messageVersionId,
});
+ for (const nodeToCreate of nodesToCreate) {
+ const changeData: LocalCreateNodeChangeData = {
+ type: 'node_create',
+ id: nodeToCreate.id,
+ state: nodeToCreate.state,
+ createdAt: nodeToCreate.created_at,
+ createdBy: nodeToCreate.created_by,
+ versionId: nodeToCreate.version_id,
+ };
+
+ changesToCreate.push({
+ data: JSON.stringify(changeData),
+ created_at: createdAt,
+ });
+ }
+
+ await workspaceDatabase.transaction().execute(async (trx) => {
+ await trx.insertInto('nodes').values(nodesToCreate).execute();
+ await trx.insertInto('changes').values(changesToCreate).execute();
+
+ if (uploadsToCreate.length > 0) {
+ await trx.insertInto('uploads').values(uploadsToCreate).execute();
+ }
+
+ if (downloadsToCreate.length > 0) {
+ await trx.insertInto('downloads').values(downloadsToCreate).execute();
+ }
+ });
+
+ const mutationChanges: MutationChange[] = [
+ {
+ type: 'workspace',
+ table: 'nodes',
+ userId: input.userId,
+ },
+ {
+ type: 'workspace',
+ table: 'changes',
+ userId: input.userId,
+ },
+ ];
+
+ if (downloadsToCreate.length > 0) {
+ mutationChanges.push({
+ type: 'workspace',
+ table: 'downloads',
+ userId: input.userId,
+ });
+ }
+
+ if (uploadsToCreate.length > 0) {
+ mutationChanges.push({
+ type: 'workspace',
+ table: 'uploads',
+ userId: input.userId,
+ });
+ }
+
return {
output: {
- id: id,
+ id: messageId,
},
- changes: [
- {
- type: 'workspace',
- table: 'nodes',
- userId: input.userId,
- },
- {
- type: 'workspace',
- table: 'changes',
- userId: input.userId,
- },
- ],
+ changes: mutationChanges,
};
}
}
diff --git a/desktop/src/preload.ts b/desktop/src/preload.ts
index 38c61b51..30c581df 100644
--- a/desktop/src/preload.ts
+++ b/desktop/src/preload.ts
@@ -37,6 +37,10 @@ contextBridge.exposeInMainWorld('neuron', {
openFile: (userId: string, id: string, extension: string) => {
return ipcRenderer.invoke('open-file', userId, id, extension);
},
+
+ getFileMetadata: (path: string) => {
+ return ipcRenderer.invoke('get-file-metadata', path);
+ },
});
contextBridge.exposeInMainWorld('eventBus', {
diff --git a/desktop/src/renderer/components/files/file-block.tsx b/desktop/src/renderer/components/files/file-block.tsx
new file mode 100644
index 00000000..cfc62c9d
--- /dev/null
+++ b/desktop/src/renderer/components/files/file-block.tsx
@@ -0,0 +1,40 @@
+import React from 'react';
+import { getFileUrl } from '@/lib/files';
+import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useQuery } from '@/renderer/hooks/use-query';
+import { FilePreview } from '@/renderer/components/files/file-preview';
+import { FileDownload } from '@/renderer/components/files/file-download';
+
+interface FileBlockProps {
+ id: string;
+}
+
+export const FileBlock = ({ id }: FileBlockProps) => {
+ const workspace = useWorkspace();
+
+ const { data } = useQuery({
+ type: 'file_get',
+ fileId: id,
+ userId: workspace.userId,
+ });
+
+ if (!data) {
+ return null;
+ }
+
+ const url = getFileUrl(workspace.userId, data.id, data.extension);
+ return (
+ <div
+ className="flex h-72 max-h-72 w-full cursor-pointer overflow-hidden rounded-md p-2 hover:bg-gray-100"
+ onClick={() => {
+ workspace.openModal(id);
+ }}
+ >
+ {data.downloadProgress !== 100 ? (
+ <FileDownload id={data.id} downloadProgress={data.downloadProgress} />
+ ) : (
+ <FilePreview url={url} name={data.name} mimeType={data.mimeType} />
+ )}
+ </div>
+ );
+};
diff --git a/desktop/src/renderer/components/files/file-container.tsx b/desktop/src/renderer/components/files/file-container.tsx
index 9c77ca39..17252568 100644
--- a/desktop/src/renderer/components/files/file-container.tsx
+++ b/desktop/src/renderer/components/files/file-container.tsx
@@ -5,6 +5,8 @@ import { FilePreview } from '@/renderer/components/files/file-preview';
import { FileSidebar } from '@/renderer/components/files/file-sidebar';
import { Button } from '@/renderer/components/ui/button';
import { SquareArrowOutUpRight } from 'lucide-react';
+import { FileDownload } from '@/renderer/components/files/file-download';
+import { getFileUrl } from '@/lib/files';
interface FileContainerProps {
nodeId: string;
@@ -22,6 +24,7 @@ export const FileContainer = ({ nodeId }: FileContainerProps) => {
return null;
}
+ const url = getFileUrl(workspace.userId, data.id, data.extension);
return (
<div className="flex h-full max-h-full w-full flex-row items-center gap-2">
<div className="flex h-full max-h-full w-full max-w-full flex-grow flex-col items-center justify-center overflow-hidden">
@@ -37,7 +40,14 @@ export const FileContainer = ({ nodeId }: FileContainerProps) => {
</Button>
</div>
<div className="flex w-full max-w-full flex-grow items-center justify-center overflow-hidden">
- <FilePreview file={data} />
+ {data.downloadProgress !== 100 ? (
+ <FileDownload
+ id={data.id}
+ downloadProgress={data.downloadProgress}
+ />
+ ) : (
+ <FilePreview url={url} name={data.name} mimeType={data.mimeType} />
+ )}
</div>
</div>
<div className="h-full w-72 min-w-72 overflow-hidden border-l border-gray-100 p-2 pl-3">
diff --git a/desktop/src/renderer/components/files/file-preview.tsx b/desktop/src/renderer/components/files/file-preview.tsx
index 949b7a1a..a6f8131c 100644
--- a/desktop/src/renderer/components/files/file-preview.tsx
+++ b/desktop/src/renderer/components/files/file-preview.tsx
@@ -1,46 +1,21 @@
import React from 'react';
import { match } from 'ts-pattern';
-import { FileDetails } from '@/types/files';
import { getFilePreviewType } from '@/lib/files';
-import { FileDownload } from '@/renderer/components/files/file-download';
import { FilePreviewImage } from '@/renderer/components/files/previews/file-preview-image';
import { FilePreviewVideo } from '@/renderer/components/files/previews/file-preview-video';
import { FilePreviewOther } from '@/renderer/components/files/previews/file-preview-other';
interface FilePreviewProps {
- file: FileDetails;
+ url: string;
+ name: string;
+ mimeType: string;
}
-export const FilePreview = ({ file }: FilePreviewProps) => {
- if (file.downloadProgress !== 100) {
- return (
- <FileDownload id={file.id} downloadProgress={file.downloadProgress} />
- );
- }
-
- const previewType = getFilePreviewType(file.mimeType);
+export const FilePreview = ({ url, name, mimeType }: FilePreviewProps) => {
+ const previewType = getFilePreviewType(mimeType);
return match(previewType)
- .with('image', () => (
- <FilePreviewImage
- id={file.id}
- name={file.name}
- extension={file.extension}
- />
- ))
- .with('video', () => (
- <FilePreviewVideo
- id={file.id}
- name={file.name}
- extension={file.extension}
- />
- ))
- .with('other', () => (
- <FilePreviewOther
- id={file.id}
- name={file.name}
- extension={file.extension}
- mimeType={file.mimeType}
- />
- ))
+ .with('image', () => <FilePreviewImage url={url} name={name} />)
+ .with('video', () => <FilePreviewVideo url={url} />)
+ .with('other', () => <FilePreviewOther mimeType={mimeType} />)
.otherwise(() => null);
};
diff --git a/desktop/src/renderer/components/files/previews/file-preview-image.tsx b/desktop/src/renderer/components/files/previews/file-preview-image.tsx
index c94399b2..09dadec9 100644
--- a/desktop/src/renderer/components/files/previews/file-preview-image.tsx
+++ b/desktop/src/renderer/components/files/previews/file-preview-image.tsx
@@ -1,21 +1,11 @@
import React from 'react';
-import { useWorkspace } from '@/renderer/contexts/workspace';
-import { getFileUrl } from '@/lib/files';
interface FilePreviewImageProps {
- id: string;
+ url: string;
name: string;
- extension: string;
}
-export const FilePreviewImage = ({
- id,
- name,
- extension,
-}: FilePreviewImageProps) => {
- const workspace = useWorkspace();
- const url = getFileUrl(workspace.userId, id, extension);
-
+export const FilePreviewImage = ({ url, name }: FilePreviewImageProps) => {
return (
<img
src={url}
diff --git a/desktop/src/renderer/components/files/previews/file-preview-other.tsx b/desktop/src/renderer/components/files/previews/file-preview-other.tsx
index 7420580f..e756c2f0 100644
--- a/desktop/src/renderer/components/files/previews/file-preview-other.tsx
+++ b/desktop/src/renderer/components/files/previews/file-preview-other.tsx
@@ -3,18 +3,10 @@ import { getFriendlyNameFromMimeType } from '@/lib/files';
import { FileIcon } from '@/renderer/components/files/file-icon';
interface FilePreviewOtherProps {
- id: string;
- name: string;
- extension: string;
mimeType: string;
}
-export const FilePreviewOther = ({
- id,
- name,
- extension,
- mimeType,
-}: FilePreviewOtherProps) => {
+export const FilePreviewOther = ({ mimeType }: FilePreviewOtherProps) => {
const friendlyName = getFriendlyNameFromMimeType(mimeType);
return (
diff --git a/desktop/src/renderer/components/files/previews/file-preview-video.tsx b/desktop/src/renderer/components/files/previews/file-preview-video.tsx
index 7d30234c..68546cf3 100644
--- a/desktop/src/renderer/components/files/previews/file-preview-video.tsx
+++ b/desktop/src/renderer/components/files/previews/file-preview-video.tsx
@@ -1,20 +1,9 @@
import React from 'react';
-import { getFileUrl } from '@/lib/files';
-import { useWorkspace } from '@/renderer/contexts/workspace';
interface FilePreviewVideoProps {
- id: string;
- name: string;
- extension: string;
+ url: string;
}
-export const FilePreviewVideo = ({
- id,
- name,
- extension,
-}: FilePreviewVideoProps) => {
- const workspace = useWorkspace();
- const url = getFileUrl(workspace.userId, id, extension);
-
+export const FilePreviewVideo = ({ url }: FilePreviewVideoProps) => {
return <video controls src={url} className="h-full w-full object-contain" />;
};
diff --git a/desktop/src/renderer/components/messages/message-editor.tsx b/desktop/src/renderer/components/messages/message-editor.tsx
index 9c12f4b5..99c319f8 100644
--- a/desktop/src/renderer/components/messages/message-editor.tsx
+++ b/desktop/src/renderer/components/messages/message-editor.tsx
@@ -28,9 +28,12 @@ import {
LinkMark,
IdExtension,
DropcursorExtension,
+ FilePlaceholderNode,
+ FileNode,
} from '@/renderer/editor/extensions';
import { EditorBubbleMenu } from '@/renderer/editor/menu/bubble-menu';
import { Plus, Search, Send, Upload } from 'lucide-react';
+import { toast } from '@/renderer/hooks/use-toast';
interface MessageEditorProps {
conversationId: string;
@@ -73,6 +76,8 @@ export const MessageEditor = React.forwardRef<
HighlightMark,
LinkMark,
DropcursorExtension,
+ FilePlaceholderNode,
+ FileNode,
],
editorProps: {
attributes: {
@@ -115,6 +120,36 @@ export const MessageEditor = React.forwardRef<
},
}));
+ const handleUploadClick = React.useCallback(async () => {
+ if (editor == null) {
+ return;
+ }
+
+ const result = await window.neuron.openFileDialog({
+ properties: ['openFile'],
+ buttonLabel: 'Upload',
+ title: 'Upload files to message',
+ });
+
+ if (result.canceled) {
+ return;
+ }
+
+ const filePath = result.filePaths[0];
+ const fileMetadata = await window.neuron.getFileMetadata(filePath);
+
+ if (fileMetadata === null) {
+ toast({
+ title: 'Failed to add file',
+ description:
+ 'Something went wrong adding file to the message. Please try again!',
+ variant: 'destructive',
+ });
+ }
+
+ editor.chain().focus().addFilePlaceholder(fileMetadata).run();
+ }, [editor]);
+
return (
<div className="flex min-h-0 flex-row items-center rounded bg-gray-100 p-2 pl-0">
<div className="flex w-10 items-center justify-center">
@@ -131,7 +166,7 @@ export const MessageEditor = React.forwardRef<
<span>Browse</span>
</div>
</DropdownMenuItem>
- <DropdownMenuItem disabled={true}>
+ <DropdownMenuItem onClick={handleUploadClick}>
<div className="flex cursor-pointer flex-row items-center gap-2 text-sm">
<Upload className="size-4" />
<span>Upload</span>
diff --git a/desktop/src/renderer/components/messages/message.tsx b/desktop/src/renderer/components/messages/message.tsx
index 437894e0..504c08ba 100644
--- a/desktop/src/renderer/components/messages/message.tsx
+++ b/desktop/src/renderer/components/messages/message.tsx
@@ -48,10 +48,6 @@ export const Message = ({
const workspace = useWorkspace();
const { mutate, isPending } = useMutation();
- if (!message.content || message.content.length === 0) {
- return null;
- }
-
const canEdit = true;
const canDelete = true;
const canReplyInThread = false;
diff --git a/desktop/src/renderer/components/workspaces/containers/breadcrumb-item.tsx b/desktop/src/renderer/components/workspaces/containers/breadcrumb-item.tsx
index f51856f8..71620828 100644
--- a/desktop/src/renderer/components/workspaces/containers/breadcrumb-item.tsx
+++ b/desktop/src/renderer/components/workspaces/containers/breadcrumb-item.tsx
@@ -2,6 +2,7 @@ import React from 'react';
import { cn } from '@/lib/utils';
import { Avatar } from '@/renderer/components/avatars/avatar';
import { BreadcrumbNode } from '@/types/workspaces';
+import { NodeTypes } from '@/lib/constants';
interface BreadcrumbNodeProps {
node: BreadcrumbNode;
@@ -9,6 +10,11 @@ interface BreadcrumbNodeProps {
}
export const BreadcrumbItem = ({ node, className }: BreadcrumbNodeProps) => {
+ let name = node.name ?? 'Unnamed';
+ if (node.type === NodeTypes.Message) {
+ name = 'Message';
+ }
+
return (
<div className={cn('flex items-center space-x-2', className)}>
{node.avatar && (
@@ -19,7 +25,7 @@ export const BreadcrumbItem = ({ node, className }: BreadcrumbNodeProps) => {
avatar={node.avatar}
/>
)}
- <span>{node.name ?? 'Unnamed'}</span>
+ <span>{name}</span>
</div>
);
};
diff --git a/desktop/src/renderer/components/workspaces/containers/breadcrumb.tsx b/desktop/src/renderer/components/workspaces/containers/breadcrumb.tsx
index b9e34d5b..3cbc5b3b 100644
--- a/desktop/src/renderer/components/workspaces/containers/breadcrumb.tsx
+++ b/desktop/src/renderer/components/workspaces/containers/breadcrumb.tsx
@@ -38,7 +38,8 @@ export const Breadcrumb = ({ nodeId }: BreadcrumbProps) => {
const visibleNodes = showEllipsis ? [data[0], data[data.length - 1]] : data;
const ellipsisNodes = showEllipsis ? data.slice(1, -1) : [];
- const isClickable = (type: string) => type !== NodeTypes.Space;
+ const isClickable = (type: string) =>
+ type !== NodeTypes.Space && type !== NodeTypes.Message;
return (
<BreadcrumbWrapper>
@@ -85,6 +86,7 @@ export const Breadcrumb = ({ nodeId }: BreadcrumbProps) => {
workspace.navigateToNode(ellipsisNode.id);
}
}}
+ disabled={!isClickable(ellipsisNode.type)}
>
<BreadcrumbItem
node={ellipsisNode}
diff --git a/desktop/src/renderer/editor/extensions/file-placeholder.tsx b/desktop/src/renderer/editor/extensions/file-placeholder.tsx
new file mode 100644
index 00000000..0d8f57b2
--- /dev/null
+++ b/desktop/src/renderer/editor/extensions/file-placeholder.tsx
@@ -0,0 +1,66 @@
+import { mergeAttributes, Node, CommandProps } from '@tiptap/core';
+import { ReactNodeViewRenderer } from '@tiptap/react';
+import { FilePlaceholderNodeView } from '@/renderer/editor/views';
+import { FileMetadata } from '@/types/files';
+import { generateId, IdType } from '@/lib/id';
+
+declare module '@tiptap/core' {
+ interface Commands<ReturnType> {
+ filePlaceholder: {
+ addFilePlaceholder: (metadata: FileMetadata) => ReturnType;
+ };
+ }
+}
+
+export const FilePlaceholderNode = Node.create({
+ name: 'filePlaceholder',
+ group: 'block',
+ atom: true,
+ defining: true,
+ draggable: true,
+ addAttributes() {
+ return {
+ id: {
+ default: null,
+ },
+ path: {
+ default: null,
+ },
+ extension: {
+ default: null,
+ },
+ mimeType: {
+ default: null,
+ },
+ };
+ },
+ renderHTML({ HTMLAttributes }) {
+ return ['filePlaceholder', mergeAttributes(HTMLAttributes)];
+ },
+ addNodeView() {
+ return ReactNodeViewRenderer(FilePlaceholderNodeView, {
+ as: 'filePlaceholder',
+ });
+ },
+ addCommands() {
+ return {
+ addFilePlaceholder:
+ (metadata: FileMetadata) =>
+ ({ chain }: CommandProps) => {
+ return chain()
+ .focus()
+ .insertContent({
+ type: 'filePlaceholder',
+ attrs: {
+ id: generateId(IdType.FilePlaceholder),
+ path: metadata.path,
+ extension: metadata.extension,
+ mimeType: metadata.mimeType,
+ name: metadata.name,
+ },
+ })
+ .run();
+ },
+ };
+ },
+});
diff --git a/desktop/src/renderer/editor/extensions/index.tsx b/desktop/src/renderer/editor/extensions/index.tsx
index 9c917bcd..814b349d 100644
--- a/desktop/src/renderer/editor/extensions/index.tsx
+++ b/desktop/src/renderer/editor/extensions/index.tsx
@@ -33,6 +33,7 @@ import { TrailingNode } from '@/renderer/editor/extensions/trailing-node';
import { PageNode } from '@/renderer/editor/extensions/page';
import { FolderNode } from '@/renderer/editor/extensions/folder';
import { FileNode } from '@/renderer/editor/extensions/file';
+import { FilePlaceholderNode } from '@/renderer/editor/extensions/file-placeholder';
export {
IdExtension,
@@ -69,4 +70,5 @@ export {
PageNode,
FolderNode,
FileNode,
+ FilePlaceholderNode,
};
diff --git a/desktop/src/renderer/editor/renderers/file.tsx b/desktop/src/renderer/editor/renderers/file.tsx
new file mode 100644
index 00000000..4c8404f1
--- /dev/null
+++ b/desktop/src/renderer/editor/renderers/file.tsx
@@ -0,0 +1,17 @@
+import React from 'react';
+import { JSONContent } from '@tiptap/core';
+import { FileBlock } from '@/renderer/components/files/file-block';
+
+interface FileRendererProps {
+ node: JSONContent;
+ keyPrefix: string | null;
+}
+
+export const FileRenderer = ({ node }: FileRendererProps) => {
+ const id = node.attrs.id;
+ if (!id) {
+ return null;
+ }
+
+ return <FileBlock id={id} />;
+};
diff --git a/desktop/src/renderer/editor/renderers/node.tsx b/desktop/src/renderer/editor/renderers/node.tsx
index 93e1b8a6..e43e000b 100644
--- a/desktop/src/renderer/editor/renderers/node.tsx
+++ b/desktop/src/renderer/editor/renderers/node.tsx
@@ -14,9 +14,10 @@ import { TaskItemRenderer } from '@/renderer/editor/renderers/task-item';
import { TaskListRenderer } from '@/renderer/editor/renderers/task-list';
import { TextRenderer } from '@/renderer/editor/renderers/text';
import { MessageReferenceRenderer } from '@/renderer/editor/renderers/message-reference';
+import { MarkRenderer } from '@/renderer/editor/renderers/mark';
+import { FileRenderer } from '@/renderer/editor/renderers/file';
import { match } from 'ts-pattern';
import { JSONContent } from '@tiptap/core';
-import { MarkRenderer } from '@/renderer/editor/renderers/mark';
interface NodeRendererProps {
node: JSONContent;
@@ -73,6 +74,7 @@ export const NodeRenderer = ({
.with('messageReference', () => (
<MessageReferenceRenderer node={node} keyPrefix={keyPrefix} />
))
+ .with('file', () => <FileRenderer node={node} keyPrefix={keyPrefix} />)
.otherwise(null)}
</MarkRenderer>
);
diff --git a/desktop/src/renderer/editor/views/file-placeholder.tsx b/desktop/src/renderer/editor/views/file-placeholder.tsx
new file mode 100644
index 00000000..769d919f
--- /dev/null
+++ b/desktop/src/renderer/editor/views/file-placeholder.tsx
@@ -0,0 +1,37 @@
+import React from 'react';
+import { type NodeViewProps } from '@tiptap/core';
+import { NodeViewWrapper } from '@tiptap/react';
+import { FilePreview } from '@/renderer/components/files/file-preview';
+import { getFilePlaceholderUrl } from '@/lib/files';
+import { X } from 'lucide-react';
+
+export const FilePlaceholderNodeView = ({
+ node,
+ deleteNode,
+}: NodeViewProps) => {
+ const path = node.attrs.path;
+ const mimeType = node.attrs.mimeType;
+ const name = node.attrs.name;
+
+ if (!path || !mimeType) {
+ return null;
+ }
+
+ const url = getFilePlaceholderUrl(path);
+ return (
+ <NodeViewWrapper
+ data-id={node.attrs.id}
+ className="flex h-72 max-h-72 w-full cursor-pointer overflow-hidden rounded-md p-2 hover:bg-gray-100"
+ >
+ <div className="group/file-placeholder relative">
+ <button
+ className="absolute right-2 top-2 flex h-4 w-4 items-center justify-center rounded-full bg-white opacity-0 shadow-md transition-opacity group-hover/file-placeholder:opacity-100"
+ onClick={deleteNode}
+ >
+ <X className="size-4" />
+ </button>
+ <FilePreview url={url} name={name} mimeType={mimeType} />
+ </div>
+ </NodeViewWrapper>
+ );
+};
diff --git a/desktop/src/renderer/editor/views/file.tsx b/desktop/src/renderer/editor/views/file.tsx
index dfe2bf62..81957ce1 100644
--- a/desktop/src/renderer/editor/views/file.tsx
+++ b/desktop/src/renderer/editor/views/file.tsx
@@ -1,37 +1,17 @@
import React from 'react';
import { type NodeViewProps } from '@tiptap/core';
import { NodeViewWrapper } from '@tiptap/react';
-import { useWorkspace } from '@/renderer/contexts/workspace';
-import { useQuery } from '@/renderer/hooks/use-query';
-import { FilePreview } from '@/renderer/components/files/file-preview';
+import { FileBlock } from '@/renderer/components/files/file-block';
export const FileNodeView = ({ node }: NodeViewProps) => {
- const workspace = useWorkspace();
-
const id = node.attrs.id;
- const { data } = useQuery({
- type: 'file_get',
- fileId: id,
- userId: workspace.userId,
- });
-
if (!id) {
return null;
}
- if (!data) {
- return null;
- }
-
return (
- <NodeViewWrapper
- data-id={node.attrs.id}
- className="flex h-72 max-h-72 w-full cursor-pointer overflow-hidden rounded-md p-2 hover:bg-gray-100"
- onClick={() => {
- workspace.openModal(id);
- }}
- >
- <FilePreview file={data} />
+ <NodeViewWrapper>
+ <FileBlock id={id} />
</NodeViewWrapper>
);
};
diff --git a/desktop/src/renderer/editor/views/index.tsx b/desktop/src/renderer/editor/views/index.tsx
index 697a59d0..4dedfb32 100644
--- a/desktop/src/renderer/editor/views/index.tsx
+++ b/desktop/src/renderer/editor/views/index.tsx
@@ -2,5 +2,12 @@ import { CodeBlockNodeView } from '@/renderer/editor/views/code-block';
import { PageNodeView } from '@/renderer/editor/views/page';
import { FolderNodeView } from '@/renderer/editor/views/folder';
import { FileNodeView } from '@/renderer/editor/views/file';
+import { FilePlaceholderNodeView } from '@/renderer/editor/views/file-placeholder';
-export { CodeBlockNodeView, PageNodeView, FolderNodeView, FileNodeView };
+export {
+ CodeBlockNodeView,
+ PageNodeView,
+ FolderNodeView,
+ FileNodeView,
+ FilePlaceholderNodeView,
+};
diff --git a/desktop/src/types/files.ts b/desktop/src/types/files.ts
index 13e8111c..f16c493c 100644
--- a/desktop/src/types/files.ts
+++ b/desktop/src/types/files.ts
@@ -34,3 +34,11 @@ export type FileDetails = {
};
export type FilePreviewType = 'image' | 'video' | 'other';
+
+export type FileMetadata = {
+ path: string;
+ mimeType: string;
+ extension: string;
+ name: string;
+ size: number;
+};
diff --git a/desktop/src/types/window.d.ts b/desktop/src/types/window.d.ts
index 96428bba..f01d5aaf 100644
--- a/desktop/src/types/window.d.ts
+++ b/desktop/src/types/window.d.ts
@@ -1,6 +1,7 @@
import { EventBus } from '@/lib/event-bus';
import { MutationMap, MutationInput } from '@/operations/mutations';
import { QueryMap, QueryInput } from '@/operations/queries';
+import { FileMetadata } from '@/types/files';
interface NeuronApi {
init: () => Promise<void>;
@@ -26,6 +27,7 @@ interface NeuronApi {
) => Promise<Electron.OpenDialogReturnValue>;
openFile: (userId: string, id: string, extension: string) => Promise<void>;
+ getFileMetadata: (path: string) => Promise<FileMetadata | null>;
}
declare global {