Skip to content

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

Implement folder and file components and background file download

Hakan Shehucc6dc3d9407e
diff --git a/desktop/index.html b/desktop/index.html
index f0fb8b34..c18ba997 100644
--- a/desktop/index.html
+++ b/desktop/index.html
@@ -5,7 +5,7 @@
<title>Neuron</title>
<meta
http-equiv="Content-Security-Policy"
- content="script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: avatar:; "
+ content="script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: avatar: local-file:; "
/>
</head>
<body>
diff --git a/desktop/src/lib/files.ts b/desktop/src/lib/files.ts
new file mode 100644
index 00000000..3c5ef002
--- /dev/null
+++ b/desktop/src/lib/files.ts
@@ -0,0 +1,167 @@
+import { FilePreviewType } from '@/types/files';
+
+export const formatBytes = (bytes: number, decimals?: number): string => {
+ if (bytes === 0) {
+ return '0 Bytes';
+ }
+
+ const k = 1024;
+ const dm = decimals || 2;
+ const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
+ return `${parseFloat((bytes / k ** i).toFixed(dm))} ${sizes[i]}`;
+};
+
+export const getFilePreviewType = (mimeType: string): FilePreviewType => {
+ if (mimeType.startsWith('image')) {
+ return 'image';
+ }
+
+ if (mimeType.startsWith('video')) {
+ return 'video';
+ }
+
+ return 'other';
+};
+
+const fileIconMapping: Record<string, string> = {
+ 'application/json': 'braces-fill',
+ 'application/pdf': 'file-pdf-fill',
+ 'application/msword': 'file-word-fill',
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
+ 'file-word-fill',
+ 'application/vnd.ms-excel': 'file-excel-fill',
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
+ 'file-excel-fill',
+ 'application/vnd.ms-powerpoint': 'file-ppt-fill',
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
+ 'file-ppt-fill',
+
+ 'text/css': 'css3-fill',
+ 'text/html': 'html5-fill',
+ 'text/csv': 'file-text-fill',
+ 'text/plain': 'file-text-fill',
+
+ 'image/jpeg': 'image-fill',
+ 'image/png': 'image-fill',
+ 'image/gif': 'image-fill',
+ 'image/bmp': 'image-fill',
+ 'image/svg+xml': 'image-fill',
+ 'image/tiff': 'image-fill',
+ 'image/webp': 'image-fill',
+ 'image/heic': 'image-fill',
+ 'image/heif': 'image-fill',
+
+ 'video/mp4': 'video-fill',
+ 'video/quicktime': 'video-fill', // For .mov files
+ 'video/x-msvideo': 'video-fill', // For .avi files
+ 'video/x-ms-wmv': 'video-fill', // For .wmv files
+ 'video/mpeg': 'video-fill', // For .mpeg files
+ 'video/webm': 'video-fill',
+ 'video/ogg': 'video-fill',
+ 'video/x-matroska': 'video-fill', // For .mkv files
+ 'video/3gpp': 'video-fill', // For .3gp files
+ 'video/3gpp2': 'video-fill', // For .3g2 files
+
+ 'audio/mpeg': 'music-2-fill',
+ 'audio/wav': 'music-2-fill',
+ 'audio/ogg': 'music-2-fill',
+ 'audio/flac': 'music-2-fill',
+ 'audio/aac': 'music-2-fill',
+ 'audio/webm': 'music-2-fill',
+ 'audio/3gpp': 'music-2-fill',
+ 'audio/3gpp2': 'music-2-fill',
+
+ 'application/octet-stream': 'javascript-fill',
+ 'application/x-javascript': 'javascript-fill',
+ 'application/javascript': 'javascript-fill',
+ 'application/zip': 'file-zip-fill',
+ 'application/x-rar-compressed': 'file-zip-fill',
+ 'application/x-7z-compressed': 'file-zip-fill',
+};
+
+export const getFileIcon = (mimeType: string) => {
+ return fileIconMapping[mimeType] || 'file-fill';
+};
+
+export const getFileUrl = (
+ accountId: string,
+ workspaceId: string,
+ fileId: string,
+ extension: string,
+) => {
+ return `local-file://${accountId}/${workspaceId}/${fileId}${extension}`;
+};
+
+const friendlyNameMapping: Record<string, string> = {
+ // Application types
+ 'application/msword': 'Word Document',
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
+ 'Word Document',
+ 'application/pdf': 'PDF Document',
+ 'application/vnd.ms-excel': 'Excel Spreadsheet',
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
+ 'Excel Spreadsheet',
+ 'application/vnd.ms-powerpoint': 'PowerPoint Presentation',
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
+ 'PowerPoint Presentation',
+ 'application/zip': 'ZIP Archive',
+ 'application/x-rar-compressed': 'RAR Archive',
+ 'application/x-tar': 'TAR Archive',
+ 'application/x-7z-compressed': '7z Archive',
+ 'application/x-rar': 'RAR Archive',
+ 'application/x-bzip': 'BZip Archive',
+ 'application/x-bzip2': 'BZip2 Archive',
+ 'application/javascript': 'JavaScript File',
+ 'application/json': 'JSON File',
+ 'application/xml': 'XML Document',
+ 'application/x-shockwave-flash': 'Flash Movie',
+ 'application/rtf': 'RTF Document',
+ 'application/octet-stream': 'Binary File',
+ 'application/x-msdownload': 'Windows Executable',
+
+ // Text types
+ 'text/plain': 'Text File',
+ 'text/html': 'HTML Document',
+ 'text/css': 'CSS File',
+ 'text/csv': 'CSV File',
+ 'text/javascript': 'JavaScript File',
+
+ // Image types
+ 'image/jpeg': 'JPEG Image',
+ 'image/png': 'PNG Image',
+ 'image/gif': 'GIF Image',
+ 'image/webp': 'WebP Image',
+ 'image/tiff': 'TIFF Image',
+ 'image/svg+xml': 'SVG Image',
+ 'image/x-icon': 'Icon File',
+ 'image/bmp': 'Bitmap Image',
+ 'image/vnd.microsoft.icon': 'Icon File',
+
+ // Audio types
+ 'audio/midi': 'MIDI Audio',
+ 'audio/mpeg': 'MP3 Audio',
+ 'audio/webm': 'WebM Audio',
+ 'audio/ogg': 'OGG Audio',
+ 'audio/wav': 'WAV Audio',
+ 'audio/aac': 'AAC Audio',
+ 'audio/mp4': 'MP4 Audio',
+
+ // Video types
+ 'video/x-msvideo': 'AVI Video',
+ 'video/mp4': 'MP4 Video',
+ 'video/mpeg': 'MPEG Video',
+ 'video/webm': 'WebM Video',
+ 'video/ogg': 'OGG Video',
+ 'video/quicktime': 'QuickTime Video',
+ 'video/x-ms-wmv': 'WMV Video',
+ 'video/x-flv': 'FLV Video',
+ 'video/x-matroska': 'MKV Video',
+
+ // Custom types or less common
+ // Add any custom or less common file types as needed.
+};
+
+export const getFriendlyNameFromMimeType = (mimeType: string) => {
+ return friendlyNameMapping[mimeType] || 'File';
+};
diff --git a/desktop/src/main.ts b/desktop/src/main.ts
index 3123b9b2..1527ec39 100644
--- a/desktop/src/main.ts
+++ b/desktop/src/main.ts
@@ -8,6 +8,7 @@ import { databaseManager } from '@/main/data/database-manager';
import { socketManager } from '@/main/sockets/socket-manager';
import { synchronizer } from '@/main/synchronizer';
import { avatarManager } from '@/main/avatar-manager';
+import { fileManager } from '@/main/file-manager';
let subscriptionId: string | null = null;
@@ -48,6 +49,10 @@ const createWindow = async () => {
protocol.handle('avatar', (request) => {
return avatarManager.handleAvatarRequest(request);
});
+
+ protocol.handle('local-file', (request) => {
+ return fileManager.handleFileRequest(request);
+ });
};
// This method will be called when Electron has finished
diff --git a/desktop/src/main/data/workspace/migrations.ts b/desktop/src/main/data/workspace/migrations.ts
index e217eded..c0adc431 100644
--- a/desktop/src/main/data/workspace/migrations.ts
+++ b/desktop/src/main/data/workspace/migrations.ts
@@ -285,6 +285,24 @@ const createUploadsTable: Migration = {
},
};
+const createDownloadsTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('downloads')
+ .addColumn('node_id', 'text', (col) =>
+ col.notNull().primaryKey().references('nodes.id'),
+ )
+ .addColumn('created_at', 'text', (col) => col.notNull())
+ .addColumn('updated_at', 'text')
+ .addColumn('progress', 'integer', (col) => col.defaultTo(0))
+ .addColumn('retry_count', 'integer', (col) => col.defaultTo(0))
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('downloads').execute();
+ },
+};
+
export const workspaceDatabaseMigrations: Record<string, Migration> = {
'00001_create_nodes_table': createNodesTable,
'00002_create_node_names_table': createNodeNamesTable,
@@ -296,4 +314,5 @@ export const workspaceDatabaseMigrations: Record<string, Migration> = {
'00008_create_node_update_name_trigger': createNodeUpdateNameTrigger,
'00009_create_node_delete_name_trigger': createNodeDeleteNameTrigger,
'00010_create_uploads_table': createUploadsTable,
+ '00011_create_downloads_table': createDownloadsTable,
};
diff --git a/desktop/src/main/data/workspace/schema.ts b/desktop/src/main/data/workspace/schema.ts
index e5158af0..b837d300 100644
--- a/desktop/src/main/data/workspace/schema.ts
+++ b/desktop/src/main/data/workspace/schema.ts
@@ -47,8 +47,21 @@ export type SelectUpload = Selectable<UploadTable>;
export type CreateUpload = Insertable<UploadTable>;
export type UpdateUpload = Updateable<UploadTable>;
+interface DownloadTable {
+ node_id: ColumnType<string, string, never>;
+ created_at: ColumnType<string, string, never>;
+ updated_at: ColumnType<string | null, string | null, string | null>;
+ progress: ColumnType<number, number, number>;
+ retry_count: ColumnType<number, number, number>;
+}
+
+export type SelectDownload = Selectable<DownloadTable>;
+export type CreateDownload = Insertable<DownloadTable>;
+export type UpdateDownload = Updateable<DownloadTable>;
+
export interface WorkspaceDatabaseSchema {
nodes: NodeTable;
changes: ChangeTable;
uploads: UploadTable;
+ downloads: DownloadTable;
}
diff --git a/desktop/src/main/file-manager.ts b/desktop/src/main/file-manager.ts
index abf52bd1..9b3fe996 100644
--- a/desktop/src/main/file-manager.ts
+++ b/desktop/src/main/file-manager.ts
@@ -1,13 +1,16 @@
-import { app } from 'electron';
+import { app, net } from 'electron';
import path from 'path';
import fs from 'fs';
-import FormData from 'form-data';
-import { ServerFileUploadResponse } from '@/types/files';
+import axios from 'axios';
+import {
+ ServerFileDownloadResponse,
+ ServerFileUploadResponse,
+} from '@/types/files';
import { WorkspaceCredentials } from '@/types/workspaces';
import { databaseManager } from './data/database-manager';
import { httpClient } from '@/lib/http-client';
import { LocalNodeAttributes } from '@/types/nodes';
-import axios from 'axios';
+import { mediator } from '@/main/mediator';
class FileManager {
private readonly appPath: string;
@@ -16,6 +19,20 @@ class FileManager {
this.appPath = app.getPath('userData');
}
+ public async handleFileRequest(request: Request): Promise<Response> {
+ const url = request.url.replace('local-file://', '');
+ const [accountId, workspaceId, file] = url.split('/');
+ const filesDir = this.getWorkspaceFilesDir(accountId, workspaceId);
+ const filePath = path.join(filesDir, file);
+
+ if (fs.existsSync(filePath)) {
+ const fileUrl = `file://${filePath}`;
+ return net.fetch(fileUrl);
+ }
+
+ return new Response(null, { status: 404 });
+ }
+
public copyFileToWorkspace(
filePath: string,
fileId: string,
@@ -23,9 +40,7 @@ class FileManager {
accountId: string,
workspaceId: string,
): void {
- const accountDir = path.join(this.appPath, accountId);
- const workspaceDir = path.join(accountDir, 'workspaces', workspaceId);
- const filesDir = path.join(workspaceDir, 'files');
+ const filesDir = this.getWorkspaceFilesDir(accountId, workspaceId);
if (!fs.existsSync(filesDir)) {
fs.mkdirSync(filesDir, { recursive: true });
@@ -55,13 +70,10 @@ class FileManager {
return;
}
- const accountDir = path.join(this.appPath, credentials.accountId);
- const workspaceDir = path.join(
- accountDir,
- 'workspaces',
+ const filesDir = this.getWorkspaceFilesDir(
+ credentials.accountId,
credentials.workspaceId,
);
- const filesDir = path.join(workspaceDir, 'files');
for (const upload of uploads) {
if (upload.retry_count >= 5) {
@@ -136,6 +148,121 @@ class FileManager {
.execute();
}
}
+
+ await mediator.checkForQueryChanges([
+ {
+ type: 'workspace',
+ userId: credentials.userId,
+ table: 'uploads',
+ },
+ ]);
+ }
+
+ public async checkForDownloads(
+ credentials: WorkspaceCredentials,
+ ): Promise<void> {
+ const workspaceDatabase = await databaseManager.getWorkspaceDatabase(
+ credentials.userId,
+ );
+
+ const downloads = await workspaceDatabase
+ .selectFrom('downloads')
+ .selectAll()
+ .where('progress', '=', 0)
+ .execute();
+
+ if (downloads.length === 0) {
+ return;
+ }
+
+ const filesDir = this.getWorkspaceFilesDir(
+ credentials.accountId,
+ credentials.workspaceId,
+ );
+
+ for (const download of downloads) {
+ const file = await workspaceDatabase
+ .selectFrom('nodes')
+ .selectAll()
+ .where('id', '=', download.node_id)
+ .executeTakeFirst();
+
+ if (!file) {
+ await workspaceDatabase
+ .deleteFrom('downloads')
+ .where('node_id', '=', download.node_id)
+ .execute();
+
+ continue;
+ }
+
+ const attributes: LocalNodeAttributes = JSON.parse(file.attributes);
+
+ const filePath = path.join(
+ filesDir,
+ `${download.node_id}${attributes.extension}`,
+ );
+
+ if (fs.existsSync(filePath)) {
+ await workspaceDatabase
+ .updateTable('downloads')
+ .set({
+ progress: 100,
+ })
+ .where('node_id', '=', download.node_id)
+ .execute();
+
+ continue;
+ }
+
+ try {
+ const { data } = await httpClient.get<ServerFileDownloadResponse>(
+ `/v1/files/${credentials.workspaceId}/${download.node_id}`,
+ {
+ serverDomain: credentials.serverDomain,
+ serverAttributes: credentials.serverAttributes,
+ token: credentials.token,
+ },
+ );
+
+ const presignedUrl = data.url;
+ const fileStream = fs.createWriteStream(filePath);
+ await axios
+ .get(presignedUrl, { responseType: 'stream' })
+ .then((response) => {
+ response.data.pipe(fileStream);
+ });
+
+ await workspaceDatabase
+ .updateTable('downloads')
+ .set({ progress: 100 })
+ .where('node_id', '=', download.node_id)
+ .execute();
+ } catch (error) {
+ console.log('error', error);
+
+ await workspaceDatabase
+ .updateTable('downloads')
+ .set((eb) => ({ retry_count: eb('retry_count', '+', 1) }))
+ .where('node_id', '=', download.node_id)
+ .execute();
+ }
+ }
+
+ await mediator.checkForQueryChanges([
+ {
+ type: 'workspace',
+ userId: credentials.userId,
+ table: 'downloads',
+ },
+ ]);
+ }
+
+ private getWorkspaceFilesDir(accountId: string, workspaceId: string): string {
+ const accountDir = path.join(this.appPath, accountId);
+ const workspaceDir = path.join(accountDir, 'workspaces', workspaceId);
+ const filesDir = path.join(workspaceDir, 'files');
+ return filesDir;
}
}
diff --git a/desktop/src/main/handlers/mutations/file-create.ts b/desktop/src/main/handlers/mutations/file-create.ts
index 6e7260c3..31d84f7e 100644
--- a/desktop/src/main/handlers/mutations/file-create.ts
+++ b/desktop/src/main/handlers/mutations/file-create.ts
@@ -70,12 +70,39 @@ export class FileCreateMutationHandler
retry_count: 0,
})
.execute();
+
+ await tx
+ .insertInto('downloads')
+ .values({
+ node_id: id,
+ created_at: new Date().toISOString(),
+ progress: 100,
+ retry_count: 0,
+ })
+ .execute();
});
return {
output: {
id: id,
},
+ changes: [
+ {
+ type: 'workspace',
+ table: 'nodes',
+ userId: input.userId,
+ },
+ {
+ type: 'workspace',
+ table: 'downloads',
+ userId: input.userId,
+ },
+ {
+ type: 'workspace',
+ table: 'uploads',
+ userId: input.userId,
+ },
+ ],
};
}
}
diff --git a/desktop/src/main/handlers/mutations/file-download.ts b/desktop/src/main/handlers/mutations/file-download.ts
new file mode 100644
index 00000000..1a926a63
--- /dev/null
+++ b/desktop/src/main/handlers/mutations/file-download.ts
@@ -0,0 +1,66 @@
+import { databaseManager } from '@/main/data/database-manager';
+import { MutationHandler, MutationResult } from '@/operations/mutations';
+import { FileDownloadMutationInput } from '@/operations/mutations/file-download';
+
+export class FileDownloadMutationHandler
+ implements MutationHandler<FileDownloadMutationInput>
+{
+ async handleMutation(
+ input: FileDownloadMutationInput,
+ ): Promise<MutationResult<FileDownloadMutationInput>> {
+ const workspaceDatabase = await databaseManager.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ const node = await workspaceDatabase
+ .selectFrom('nodes')
+ .selectAll()
+ .where('id', '=', input.fileId)
+ .executeTakeFirst();
+
+ if (!node) {
+ return {
+ output: {
+ success: false,
+ },
+ };
+ }
+
+ const download = await workspaceDatabase
+ .selectFrom('downloads')
+ .selectAll()
+ .where('node_id', '=', input.fileId)
+ .executeTakeFirst();
+
+ if (download) {
+ return {
+ output: {
+ success: true,
+ },
+ };
+ }
+
+ await workspaceDatabase
+ .insertInto('downloads')
+ .values({
+ node_id: input.fileId,
+ created_at: new Date().toISOString(),
+ progress: 0,
+ retry_count: 0,
+ })
+ .execute();
+
+ return {
+ output: {
+ success: true,
+ },
+ changes: [
+ {
+ type: 'workspace',
+ table: 'downloads',
+ userId: input.userId,
+ },
+ ],
+ };
+ }
+}
diff --git a/desktop/src/main/handlers/mutations/index.ts b/desktop/src/main/handlers/mutations/index.ts
index 52c32ede..6b5575cf 100644
--- a/desktop/src/main/handlers/mutations/index.ts
+++ b/desktop/src/main/handlers/mutations/index.ts
@@ -35,6 +35,7 @@ import { LogoutMutationHandler } from '@/main/handlers/mutations/logout';
import { NodeSyncMutationHandler } from '@/main/handlers/mutations/node-sync';
import { FolderCreateMutationHandler } from '@/main/handlers/mutations/folder-create';
import { FileCreateMutationHandler } from '@/main/handlers/mutations/file-create';
+import { FileDownloadMutationHandler } from '@/main/handlers/mutations/file-download';
type MutationHandlerMap = {
[K in keyof MutationMap]: MutationHandler<MutationMap[K]['input']>;
@@ -77,4 +78,5 @@ export const mutationHandlerMap: MutationHandlerMap = {
node_sync: new NodeSyncMutationHandler(),
folder_create: new FolderCreateMutationHandler(),
file_create: new FileCreateMutationHandler(),
+ file_download: new FileDownloadMutationHandler(),
};
diff --git a/desktop/src/main/handlers/queries/file-get.ts b/desktop/src/main/handlers/queries/file-get.ts
new file mode 100644
index 00000000..9b8b2166
--- /dev/null
+++ b/desktop/src/main/handlers/queries/file-get.ts
@@ -0,0 +1,123 @@
+import { FileGetQueryInput } from '@/operations/queries/file-get';
+import { databaseManager } from '@/main/data/database-manager';
+import {
+ ChangeCheckResult,
+ QueryHandler,
+ QueryResult,
+} from '@/operations/queries';
+import { MutationChange } from '@/operations/mutations';
+import { isEqual } from 'lodash';
+import { FileDetails } from '@/types/files';
+
+interface FileRow {
+ id: string;
+ attributes: string;
+ parent_id: string;
+ type: string;
+ download_progress?: number | null;
+ created_at: string;
+ created_by: string;
+ created_by_attributes: string;
+}
+
+export class FileGetQueryHandler implements QueryHandler<FileGetQueryInput> {
+ public async handleQuery(
+ input: FileGetQueryInput,
+ ): Promise<QueryResult<FileGetQueryInput>> {
+ const row = await this.fetchFile(input);
+
+ return {
+ output: row ? this.buildFile(row) : null,
+ state: {
+ row,
+ },
+ };
+ }
+
+ public async checkForChanges(
+ changes: MutationChange[],
+ input: FileGetQueryInput,
+ state: Record<string, any>,
+ ): Promise<ChangeCheckResult<FileGetQueryInput>> {
+ if (
+ !changes.some(
+ (change) =>
+ change.type === 'workspace' &&
+ (change.table === 'nodes' || change.table === 'downloads') &&
+ change.userId === input.userId,
+ )
+ ) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ const row = await this.fetchFile(input);
+ if (isEqual(row, state.row)) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ return {
+ hasChanges: true,
+ result: {
+ output: row ? this.buildFile(row) : null,
+ state: {
+ row,
+ },
+ },
+ };
+ }
+
+ private async fetchFile(input: FileGetQueryInput): Promise<FileRow> {
+ const workspaceDatabase = await databaseManager.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ const row = await workspaceDatabase
+ .selectFrom('nodes as file')
+ .leftJoin('downloads as file_downloads', (join) =>
+ join.onRef('file.id', '=', 'file_downloads.node_id'),
+ )
+ .leftJoin('nodes as created_by', (join) =>
+ join.onRef('file.created_by', '=', 'created_by.id'),
+ )
+ .select([
+ 'file.id',
+ 'file.parent_id',
+ 'file.type',
+ 'file.attributes',
+ 'file_downloads.progress as download_progress',
+ 'file.created_at',
+ 'created_by.id as created_by',
+ 'created_by.attributes as created_by_attributes',
+ ])
+ .where('file.id', '=', input.fileId)
+ .executeTakeFirst();
+
+ return row;
+ }
+
+ private buildFile(row: FileRow): FileDetails {
+ const attributes = JSON.parse(row.attributes);
+ const createdByAttributes = JSON.parse(row.created_by_attributes);
+
+ return {
+ id: row.id,
+ name: attributes.name,
+ mimeType: attributes.mimeType,
+ size: attributes.size,
+ extension: attributes.extension,
+ fileName: attributes.fileName,
+ downloadProgress: row.download_progress,
+ createdAt: row.created_at,
+ createdBy: {
+ id: row.created_by,
+ name: createdByAttributes.name,
+ avatar: createdByAttributes.avatar,
+ email: createdByAttributes.email,
+ },
+ };
+ }
+}
diff --git a/desktop/src/main/handlers/queries/file-list.ts b/desktop/src/main/handlers/queries/file-list.ts
new file mode 100644
index 00000000..20e62b13
--- /dev/null
+++ b/desktop/src/main/handlers/queries/file-list.ts
@@ -0,0 +1,126 @@
+import { FileListQueryInput } from '@/operations/queries/file-list';
+import { databaseManager } from '@/main/data/database-manager';
+import {
+ ChangeCheckResult,
+ QueryHandler,
+ QueryResult,
+} from '@/operations/queries';
+import { MutationChange } from '@/operations/mutations';
+import { NodeTypes } from '@/lib/constants';
+import { compareString } from '@/lib/utils';
+import { isEqual } from 'lodash';
+import { FileNode } from '@/types/files';
+
+interface FileRow {
+ id: string;
+ attributes: string;
+ parent_id: string;
+ type: string;
+ download_progress?: number | null;
+ created_at: string;
+ created_by: string;
+}
+
+export class FileListQueryHandler implements QueryHandler<FileListQueryInput> {
+ public async handleQuery(
+ input: FileListQueryInput,
+ ): Promise<QueryResult<FileListQueryInput>> {
+ const files = await this.fetchFiles(input);
+
+ return {
+ output: this.buildFiles(files),
+ state: {
+ files,
+ },
+ };
+ }
+
+ public async checkForChanges(
+ changes: MutationChange[],
+ input: FileListQueryInput,
+ state: Record<string, any>,
+ ): Promise<ChangeCheckResult<FileListQueryInput>> {
+ if (
+ !changes.some(
+ (change) =>
+ change.type === 'workspace' &&
+ (change.table === 'nodes' || change.table === 'downloads') &&
+ change.userId === input.userId,
+ )
+ ) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ const files = await this.fetchFiles(input);
+ if (isEqual(files, state.files)) {
+ return {
+ hasChanges: false,
+ };
+ }
+
+ return {
+ hasChanges: true,
+ result: {
+ output: this.buildFiles(files),
+ state: {
+ files,
+ },
+ },
+ };
+ }
+
+ private async fetchFiles(input: FileListQueryInput): Promise<FileRow[]> {
+ const workspaceDatabase = await databaseManager.getWorkspaceDatabase(
+ input.userId,
+ );
+
+ const offset = input.page * input.count;
+ const files = await workspaceDatabase
+ .selectFrom('nodes')
+ .leftJoin('downloads', (join) =>
+ join.onRef('nodes.id', '=', 'downloads.node_id'),
+ )
+ .select([
+ 'nodes.id',
+ 'nodes.attributes',
+ 'nodes.parent_id',
+ 'nodes.type',
+ 'downloads.progress as download_progress',
+ 'nodes.created_at',
+ 'nodes.created_by',
+ ])
+ .where((eb) =>
+ eb.and([
+ eb('parent_id', '=', input.parentId),
+ eb('type', '=', NodeTypes.File),
+ ]),
+ )
+ .orderBy('id', 'asc')
+ .limit(input.count)
+ .offset(offset)
+ .execute();
+
+ return files;
+ }
+
+ private buildFiles = (fileRows: FileRow[]): FileNode[] => {
+ const files: FileNode[] = [];
+ for (const fileRow of fileRows) {
+ const attributes = JSON.parse(fileRow.attributes);
+ files.push({
+ id: fileRow.id,
+ name: attributes.name,
+ mimeType: attributes.mimeType,
+ size: attributes.size,
+ extension: attributes.extension,
+ fileName: attributes.fileName,
+ createdAt: fileRow.created_at,
+ downloadProgress: fileRow.download_progress,
+ });
+ }
+
+ return files.sort((a, b) => compareString(a.id, b.id));
+ };
+}
diff --git a/desktop/src/main/handlers/queries/index.ts b/desktop/src/main/handlers/queries/index.ts
index 3774d000..7bffb202 100644
--- a/desktop/src/main/handlers/queries/index.ts
+++ b/desktop/src/main/handlers/queries/index.ts
@@ -17,6 +17,8 @@ import { WorkspaceListQueryHandler } from '@/main/handlers/queries/workspace-lis
import { WorkspaceUserListQueryHandler } from '@/main/handlers/queries/workspace-user-list';
import { RecordListQueryHandler } from '@/main/handlers/queries/record-list';
import { ChatGetQueryHandler } from '@/main/handlers/queries/chat-get';
+import { FileListQueryHandler } from '@/main/handlers/queries/file-list';
+import { FileGetQueryHandler } from '@/main/handlers/queries/file-get';
type QueryHandlerMap = {
[K in keyof QueryMap]: QueryHandler<QueryMap[K]['input']>;
@@ -41,4 +43,6 @@ export const queryHandlerMap: QueryHandlerMap = {
workspace_list: new WorkspaceListQueryHandler(),
workspace_user_list: new WorkspaceUserListQueryHandler(),
chat_get: new ChatGetQueryHandler(),
+ file_list: new FileListQueryHandler(),
+ file_get: new FileGetQueryHandler(),
};
diff --git a/desktop/src/main/mediator.ts b/desktop/src/main/mediator.ts
index 19b74712..f4bf857d 100644
--- a/desktop/src/main/mediator.ts
+++ b/desktop/src/main/mediator.ts
@@ -70,7 +70,7 @@ class Mediator {
this.subscribedQueries.delete(id);
}
- private async checkForQueryChanges(changes: MutationChange[]): Promise<void> {
+ public async checkForQueryChanges(changes: MutationChange[]): Promise<void> {
if (changes.length === 0) {
return;
}
diff --git a/desktop/src/main/synchronizer.ts b/desktop/src/main/synchronizer.ts
index 54bd79a2..ae3c2fb1 100644
--- a/desktop/src/main/synchronizer.ts
+++ b/desktop/src/main/synchronizer.ts
@@ -101,6 +101,7 @@ class Synchronizer {
try {
await this.checkForChanges(credentials);
await fileManager.checkForUploads(credentials);
+ await fileManager.checkForDownloads(credentials);
} catch (error) {
// console.log('error', error);
}
diff --git a/desktop/src/operations/mutations/file-download.ts b/desktop/src/operations/mutations/file-download.ts
new file mode 100644
index 00000000..06a8fbb8
--- /dev/null
+++ b/desktop/src/operations/mutations/file-download.ts
@@ -0,0 +1,18 @@
+export type FileDownloadMutationInput = {
+ type: 'file_download';
+ userId: string;
+ fileId: string;
+};
+
+export type FileDownloadMutationOutput = {
+ success: boolean;
+};
+
+declare module '@/operations/mutations' {
+ interface MutationMap {
+ file_download: {
+ input: FileDownloadMutationInput;
+ output: FileDownloadMutationOutput;
+ };
+ }
+}
diff --git a/desktop/src/operations/queries/file-get.ts b/desktop/src/operations/queries/file-get.ts
new file mode 100644
index 00000000..177be51a
--- /dev/null
+++ b/desktop/src/operations/queries/file-get.ts
@@ -0,0 +1,16 @@
+import { FileDetails } from '@/types/files';
+
+export type FileGetQueryInput = {
+ type: 'file_get';
+ fileId: string;
+ userId: string;
+};
+
+declare module '@/operations/queries' {
+ interface QueryMap {
+ file_get: {
+ input: FileGetQueryInput;
+ output: FileDetails;
+ };
+ }
+}
diff --git a/desktop/src/operations/queries/file-list.ts b/desktop/src/operations/queries/file-list.ts
new file mode 100644
index 00000000..7d99e628
--- /dev/null
+++ b/desktop/src/operations/queries/file-list.ts
@@ -0,0 +1,18 @@
+import { FileNode } from '@/types/files';
+
+export type FileListQueryInput = {
+ type: 'file_list';
+ parentId: string;
+ page: number;
+ count: number;
+ userId: string;
+};
+
+declare module '@/operations/queries' {
+ interface QueryMap {
+ file_list: {
+ input: FileListQueryInput;
+ output: FileNode[];
+ };
+ }
+}
diff --git a/desktop/src/renderer/components/files/file-container.tsx b/desktop/src/renderer/components/files/file-container.tsx
new file mode 100644
index 00000000..11f3dba4
--- /dev/null
+++ b/desktop/src/renderer/components/files/file-container.tsx
@@ -0,0 +1,38 @@
+import React from 'react';
+import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useQuery } from '@/renderer/hooks/use-query';
+import { FilePreview } from '@/renderer/components/files/file-preview';
+import { FileSidebar } from '@/renderer/components/files/file-sidebar';
+import { FileDownload } from '@/renderer/components/files/file-download';
+
+interface FileContainerProps {
+ nodeId: string;
+}
+
+export const FileContainer = ({ nodeId }: FileContainerProps) => {
+ const workspace = useWorkspace();
+ const { data } = useQuery({
+ type: 'file_get',
+ userId: workspace.userId,
+ fileId: nodeId,
+ });
+
+ if (!data) {
+ return null;
+ }
+
+ 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 items-center justify-center overflow-hidden">
+ {data.downloadProgress === 100 ? (
+ <FilePreview file={data} />
+ ) : (
+ <FileDownload id={data.id} downloadProgress={data.downloadProgress} />
+ )}
+ </div>
+ <div className="h-full w-72 min-w-72 overflow-hidden border-l border-gray-100 p-2 pl-3">
+ <FileSidebar file={data} />
+ </div>
+ </div>
+ );
+};
diff --git a/desktop/src/renderer/components/files/file-download.tsx b/desktop/src/renderer/components/files/file-download.tsx
new file mode 100644
index 00000000..08542a53
--- /dev/null
+++ b/desktop/src/renderer/components/files/file-download.tsx
@@ -0,0 +1,44 @@
+import React from 'react';
+import { Icon } from '@/renderer/components/ui/icon';
+import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useMutation } from '@/renderer/hooks/use-mutation';
+import { Spinner } from '@/renderer/components/ui/spinner';
+
+interface FileDownloadProps {
+ id: string;
+ downloadProgress: number | null;
+}
+
+export const FileDownload = ({ id, downloadProgress }: FileDownloadProps) => {
+ const workspace = useWorkspace();
+ const { mutate } = useMutation();
+
+ if (downloadProgress === null) {
+ return (
+ <div
+ className="flex cursor-pointer flex-col items-center gap-3 text-muted-foreground hover:text-primary"
+ onClick={() =>
+ mutate({
+ input: {
+ type: 'file_download',
+ userId: workspace.userId,
+ fileId: id,
+ },
+ })
+ }
+ >
+ <Icon name="download-2-line" className="h-10 w-10" />
+ <p className="text-sm">
+ File is not downloaded in your device. Click to download.
+ </p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col items-center gap-3 text-muted-foreground">
+ <Spinner className="h-10 w-10" />
+ <p className="text-sm">Downloading file...</p>
+ </div>
+ );
+};
diff --git a/desktop/src/renderer/components/files/file-preview.tsx b/desktop/src/renderer/components/files/file-preview.tsx
new file mode 100644
index 00000000..9dfa4c01
--- /dev/null
+++ b/desktop/src/renderer/components/files/file-preview.tsx
@@ -0,0 +1,39 @@
+import React from 'react';
+import { match } from 'ts-pattern';
+import { FileDetails } from '@/types/files';
+import { getFilePreviewType } from '@/lib/files';
+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;
+}
+
+export const FilePreview = ({ file }: FilePreviewProps) => {
+ const previewType = getFilePreviewType(file.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}
+ />
+ ))
+ .otherwise(() => null);
+};
diff --git a/desktop/src/renderer/components/files/file-sidebar.tsx b/desktop/src/renderer/components/files/file-sidebar.tsx
new file mode 100644
index 00000000..81a4d0eb
--- /dev/null
+++ b/desktop/src/renderer/components/files/file-sidebar.tsx
@@ -0,0 +1,64 @@
+import React from 'react';
+import { FileDetails } from '@/types/files';
+import { formatBytes } from '@/lib/files';
+import { formatDate } from '@/lib/utils';
+import { FileThumbnail } from '@/renderer/components/files/file-thumbnail';
+import { Avatar } from '@/renderer/components/avatars/avatar';
+
+interface FileSidebarProps {
+ file: FileDetails;
+}
+
+const FileMeta = ({ title, value }: { title: string; value: string }) => {
+ return (
+ <div>
+ <p className="text-xs text-muted-foreground">{title}</p>
+ <p className="text-foreground/80">{value}</p>
+ </div>
+ );
+};
+
+export const FileSidebar = ({ file }: FileSidebarProps) => {
+ return (
+ <React.Fragment>
+ <div className="flex items-center gap-x-4 p-2">
+ <FileThumbnail
+ id={file.id}
+ name={file.name}
+ mimeType={file.mimeType}
+ extension={file.extension}
+ downloadProgress={file.downloadProgress}
+ className="h-12 w-9 min-w-[36px] overflow-hidden rounded object-contain"
+ />
+ <div
+ className="line-clamp-3 break-words text-base font-medium"
+ title={file.name || file.fileName}
+ >
+ {file.name}
+ </div>
+ </div>
+
+ <div className="mt-5 flex flex-col gap-4">
+ <FileMeta title="Name" value={file.name} />
+ <FileMeta title="Type" value={file.mimeType} />
+ <FileMeta title="Size" value={formatBytes(file.size)} />
+ <FileMeta title="Created at" value={formatDate(file.createdAt)} />
+
+ {file.createdBy && (
+ <div>
+ <p className="text-xs text-muted-foreground">Created by</p>
+ <div className="mt-1 flex flex-row items-center gap-2">
+ <Avatar
+ id={file.createdBy.id}
+ name={file.createdBy.name}
+ avatar={file.createdBy.avatar}
+ className="h-8 w-8"
+ />
+ <p className="text-foreground/80">{file.createdBy.name}</p>
+ </div>
+ </div>
+ )}
+ </div>
+ </React.Fragment>
+ );
+};
diff --git a/desktop/src/renderer/components/files/file-thumbnail.tsx b/desktop/src/renderer/components/files/file-thumbnail.tsx
new file mode 100644
index 00000000..9aa00a93
--- /dev/null
+++ b/desktop/src/renderer/components/files/file-thumbnail.tsx
@@ -0,0 +1,39 @@
+import React from 'react';
+import { getFileIcon, getFileUrl } from '@/lib/files';
+import { Icon } from '@/renderer/components/ui/icon';
+import { useWorkspace } from '@/renderer/contexts/workspace';
+import { cn } from '@/lib/utils';
+
+interface FileThumbnailProps {
+ id: string;
+ name: string;
+ mimeType: string;
+ extension: string;
+ downloadProgress?: number | null;
+ className?: string;
+}
+
+export const FileThumbnail = ({
+ id,
+ name,
+ mimeType,
+ extension,
+ downloadProgress,
+ className,
+}: FileThumbnailProps) => {
+ const workspace = useWorkspace();
+
+ if (downloadProgress === 100 && mimeType.startsWith('image')) {
+ const url = getFileUrl(workspace.accountId, workspace.id, id, extension);
+ return (
+ <img
+ src={url}
+ alt={name}
+ className={cn('object-contain object-center', className)}
+ />
+ );
+ }
+
+ const icon = getFileIcon(mimeType);
+ return <Icon name={icon} className={className} />;
+};
diff --git a/desktop/src/renderer/components/files/previews/file-preview-image.tsx b/desktop/src/renderer/components/files/previews/file-preview-image.tsx
new file mode 100644
index 00000000..29fecca2
--- /dev/null
+++ b/desktop/src/renderer/components/files/previews/file-preview-image.tsx
@@ -0,0 +1,26 @@
+import React from 'react';
+import { useWorkspace } from '@/renderer/contexts/workspace';
+import { getFileUrl } from '@/lib/files';
+
+interface FilePreviewImageProps {
+ id: string;
+ name: string;
+ extension: string;
+}
+
+export const FilePreviewImage = ({
+ id,
+ name,
+ extension,
+}: FilePreviewImageProps) => {
+ const workspace = useWorkspace();
+ const url = getFileUrl(workspace.accountId, workspace.id, id, extension);
+
+ return (
+ <img
+ src={url}
+ alt={name}
+ className="max-h-full max-w-full object-contain"
+ />
+ );
+};
diff --git a/desktop/src/renderer/components/files/previews/file-preview-other.tsx b/desktop/src/renderer/components/files/previews/file-preview-other.tsx
new file mode 100644
index 00000000..eed7a61e
--- /dev/null
+++ b/desktop/src/renderer/components/files/previews/file-preview-other.tsx
@@ -0,0 +1,29 @@
+import React from 'react';
+import { getFileIcon, getFriendlyNameFromMimeType } from '@/lib/files';
+import { Icon } from '@/renderer/components/ui/icon';
+
+interface FilePreviewOtherProps {
+ id: string;
+ name: string;
+ extension: string;
+ mimeType: string;
+}
+
+export const FilePreviewOther = ({
+ id,
+ name,
+ extension,
+ mimeType,
+}: FilePreviewOtherProps) => {
+ const friendlyName = getFriendlyNameFromMimeType(mimeType);
+ const icon = getFileIcon(mimeType);
+
+ return (
+ <div className="flex flex-col items-center gap-3">
+ <Icon name={icon} className="h-10 w-10" />
+ <p className="text-sm text-muted-foreground">
+ No preview available for {friendlyName}
+ </p>
+ </div>
+ );
+};
diff --git a/desktop/src/renderer/components/files/previews/file-preview-video.tsx b/desktop/src/renderer/components/files/previews/file-preview-video.tsx
new file mode 100644
index 00000000..c7bc5acc
--- /dev/null
+++ b/desktop/src/renderer/components/files/previews/file-preview-video.tsx
@@ -0,0 +1,20 @@
+import React from 'react';
+import { getFileUrl } from '@/lib/files';
+import { useWorkspace } from '@/renderer/contexts/workspace';
+
+interface FilePreviewVideoProps {
+ id: string;
+ name: string;
+ extension: string;
+}
+
+export const FilePreviewVideo = ({
+ id,
+ name,
+ extension,
+}: FilePreviewVideoProps) => {
+ const workspace = useWorkspace();
+ const url = getFileUrl(workspace.accountId, workspace.id, id, extension);
+
+ return <video controls src={url} className="h-full w-full object-contain" />;
+};
diff --git a/desktop/src/renderer/components/folders/folder-container.tsx b/desktop/src/renderer/components/folders/folder-container.tsx
index 5a380156..ac440d59 100644
--- a/desktop/src/renderer/components/folders/folder-container.tsx
+++ b/desktop/src/renderer/components/folders/folder-container.tsx
@@ -14,6 +14,7 @@ import { folderLayouts, FolderLayoutType } from '@/types/folders';
import { ScrollArea } from '@/renderer/components/ui/scroll-area';
import { useMutation } from '@/renderer/hooks/use-mutation';
import { useWorkspace } from '@/renderer/contexts/workspace';
+import { FolderFiles } from '@/renderer/components/folders/folder-files';
interface FolderContainerProps {
nodeId: string;
@@ -21,7 +22,7 @@ interface FolderContainerProps {
export const FolderContainer = ({ nodeId }: FolderContainerProps) => {
const workspace = useWorkspace();
- const { mutate, isPending } = useMutation();
+ const { mutate } = useMutation();
const [layout, setLayout] = React.useState<FolderLayoutType>('grid');
const currentLayout =
@@ -105,8 +106,7 @@ export const FolderContainer = ({ nodeId }: FolderContainerProps) => {
</div>
</div>
<ScrollArea className="flex-grow">
- {/* <FolderFiles files={query.folder} layout={layout} /> */}
- List files here
+ <FolderFiles id={nodeId} name="Folder" layout={layout} />
</ScrollArea>
</div>
{/* <FolderUploads
diff --git a/desktop/src/renderer/components/folders/folder-files.tsx b/desktop/src/renderer/components/folders/folder-files.tsx
new file mode 100644
index 00000000..6b9d0f52
--- /dev/null
+++ b/desktop/src/renderer/components/folders/folder-files.tsx
@@ -0,0 +1,78 @@
+import React from 'react';
+import { match } from 'ts-pattern';
+import { FolderContext } from '@/renderer/contexts/folder';
+import { FolderLayoutType } from '@/types/folders';
+import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useInfiniteQuery } from '@/renderer/hooks/use-infinite-query';
+import { GridLayout } from '@/renderer/components/folders/grids/grid-layout';
+import { ListLayout } from '@/renderer/components/folders/lists/list-layout';
+import { GalleryLayout } from '@/renderer/components/folders/galleries/gallery-layout';
+import { getIdType, IdType } from '@/lib/id';
+
+const FILES_PER_PAGE = 100;
+
+interface FolderFilesProps {
+ id: string;
+ name: string;
+ layout: FolderLayoutType;
+}
+
+export const FolderFiles = ({ id, name, layout }: FolderFilesProps) => {
+ const workspace = useWorkspace();
+ const { data } = useInfiniteQuery({
+ initialPageInput: {
+ type: 'file_list',
+ userId: workspace.userId,
+ parentId: id,
+ count: FILES_PER_PAGE,
+ page: 0,
+ },
+ getNextPageInput: (page, pages) => {
+ if (page > pages.length) {
+ return undefined;
+ }
+
+ const lastPage = pages[page - 1];
+ if (lastPage.length < FILES_PER_PAGE) {
+ return undefined;
+ }
+
+ return {
+ type: 'file_list',
+ userId: workspace.userId,
+ parentId: id,
+ count: FILES_PER_PAGE,
+ page: page + 1,
+ };
+ },
+ });
+
+ const files = data?.flatMap((page) => page) ?? [];
+
+ return (
+ <FolderContext.Provider
+ value={{
+ id,
+ name,
+ files,
+ onClick: () => {},
+ onDoubleClick: (_, id) => {
+ const idType = getIdType(id);
+
+ if (idType === IdType.Folder) {
+ workspace.navigateToNode(id);
+ } else if (idType === IdType.File) {
+ workspace.openModal(id);
+ }
+ },
+ onMove: () => {},
+ }}
+ >
+ {match(layout)
+ .with('grid', () => <GridLayout />)
+ .with('list', () => <ListLayout />)
+ .with('gallery', () => <GalleryLayout />)
+ .exhaustive()}
+ </FolderContext.Provider>
+ );
+};
diff --git a/desktop/src/renderer/components/folders/galleries/gallery-layout.tsx b/desktop/src/renderer/components/folders/galleries/gallery-layout.tsx
new file mode 100644
index 00000000..d80c3b27
--- /dev/null
+++ b/desktop/src/renderer/components/folders/galleries/gallery-layout.tsx
@@ -0,0 +1,5 @@
+import React from 'react';
+
+export const GalleryLayout = () => {
+ return <div>GalleryLayout</div>;
+};
diff --git a/desktop/src/renderer/components/folders/grids/grid-file.tsx b/desktop/src/renderer/components/folders/grids/grid-file.tsx
new file mode 100644
index 00000000..213429d6
--- /dev/null
+++ b/desktop/src/renderer/components/folders/grids/grid-file.tsx
@@ -0,0 +1,30 @@
+import React from 'react';
+import { FileNode } from '@/types/files';
+import { FileThumbnail } from '@/renderer/components/files/file-thumbnail';
+
+interface GridFileProps {
+ file: FileNode;
+}
+
+export const GridFile = ({ file }: GridFileProps) => {
+ return (
+ <React.Fragment>
+ <div className="flex w-full justify-center">
+ <FileThumbnail
+ id={file.id}
+ mimeType={file.mimeType}
+ extension={file.extension}
+ downloadProgress={file.downloadProgress}
+ name={file.name}
+ className="h-14 w-14"
+ />
+ </div>
+ <p
+ className="line-clamp-2 w-full break-words text-center text-xs text-foreground/80"
+ title={file.name}
+ >
+ {file.name}
+ </p>
+ </React.Fragment>
+ );
+};
diff --git a/desktop/src/renderer/components/folders/grids/grid-item.tsx b/desktop/src/renderer/components/folders/grids/grid-item.tsx
new file mode 100644
index 00000000..9c0b3700
--- /dev/null
+++ b/desktop/src/renderer/components/folders/grids/grid-item.tsx
@@ -0,0 +1,26 @@
+import React from 'react';
+import { FileNode } from '@/types/files';
+import { cn } from '@/lib/utils';
+import { useFolder } from '@/renderer/contexts/folder';
+import { GridFile } from '@/renderer/components/folders/grids/grid-file';
+
+export const GridItem = ({ file }: { file: FileNode }) => {
+ const folder = useFolder();
+
+ const ref = React.useRef<HTMLDivElement>(null);
+ const selected = false;
+
+ return (
+ <div
+ ref={ref}
+ className={cn(
+ 'flex cursor-pointer select-none flex-col items-center gap-2 p-2',
+ selected ? 'bg-blue-100' : 'hover:bg-blue-50',
+ )}
+ onClick={(event) => folder.onClick(event, file.id)}
+ onDoubleClick={(event) => folder.onDoubleClick(event, file.id)}
+ >
+ <GridFile file={file} />
+ </div>
+ );
+};
diff --git a/desktop/src/renderer/components/folders/grids/grid-layout.tsx b/desktop/src/renderer/components/folders/grids/grid-layout.tsx
new file mode 100644
index 00000000..8b1bd673
--- /dev/null
+++ b/desktop/src/renderer/components/folders/grids/grid-layout.tsx
@@ -0,0 +1,15 @@
+import React from 'react';
+import { GridItem } from '@/renderer/components/folders/grids/grid-item';
+import { useFolder } from '@/renderer/contexts/folder';
+
+export const GridLayout = () => {
+ const folder = useFolder();
+
+ return (
+ <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-5 lg:grid-cols-6 xl:grid-cols-8 2xl:grid-cols-10">
+ {folder.files.map((file) => (
+ <GridItem key={file.id} file={file} />
+ ))}
+ </div>
+ );
+};
diff --git a/desktop/src/renderer/components/folders/lists/list-layout.tsx b/desktop/src/renderer/components/folders/lists/list-layout.tsx
new file mode 100644
index 00000000..b65ae4e0
--- /dev/null
+++ b/desktop/src/renderer/components/folders/lists/list-layout.tsx
@@ -0,0 +1,5 @@
+import React from 'react';
+
+export const ListLayout = () => {
+ return <div>ListLayout</div>;
+};
diff --git a/desktop/src/renderer/components/messages/message-list.tsx b/desktop/src/renderer/components/messages/message-list.tsx
index caa29ba5..ba029682 100644
--- a/desktop/src/renderer/components/messages/message-list.tsx
+++ b/desktop/src/renderer/components/messages/message-list.tsx
@@ -31,7 +31,7 @@ export const MessageList = ({
page: 0,
count: MESSAGES_PER_PAGE,
},
- getNextPageInput(page, pages) {
+ getNextPageInput: (page, pages) => {
if (page > pages.length) {
return undefined;
}
diff --git a/desktop/src/renderer/components/workspaces/containers/container.tsx b/desktop/src/renderer/components/workspaces/containers/container.tsx
index 3fd87f0f..c023361f 100644
--- a/desktop/src/renderer/components/workspaces/containers/container.tsx
+++ b/desktop/src/renderer/components/workspaces/containers/container.tsx
@@ -8,11 +8,10 @@ import { DatabaseContainer } from '@/renderer/components/databases/database-cont
import { RecordContainer } from '@/renderer/components/records/record-container';
import { ChatContainer } from '@/renderer/components/chats/chat-container';
import { FolderContainer } from '@/renderer/components/folders/folder-container';
-import { useWorkspace } from '@/renderer/contexts/workspace';
+import { FileContainer } from '@/renderer/components/files/file-container';
import { getIdType, IdType } from '@/lib/id';
export const Container = () => {
- const workspace = useWorkspace();
const { nodeId } = useParams<{ nodeId: string }>();
if (!nodeId) {
return null;
@@ -29,6 +28,7 @@ export const Container = () => {
.with(IdType.Record, () => <RecordContainer nodeId={nodeId} />)
.with(IdType.Chat, () => <ChatContainer nodeId={nodeId} />)
.with(IdType.Folder, () => <FolderContainer nodeId={nodeId} />)
+ .with(IdType.File, () => <FileContainer nodeId={nodeId} />)
.otherwise(() => null)}
</div>
);
diff --git a/desktop/src/renderer/components/workspaces/modals/modal-content.tsx b/desktop/src/renderer/components/workspaces/modals/modal-content.tsx
index deb60152..60b3c952 100644
--- a/desktop/src/renderer/components/workspaces/modals/modal-content.tsx
+++ b/desktop/src/renderer/components/workspaces/modals/modal-content.tsx
@@ -6,6 +6,7 @@ import { DatabaseContainer } from '@/renderer/components/databases/database-cont
import { RecordContainer } from '@/renderer/components/records/record-container';
import { ChatContainer } from '@/renderer/components/chats/chat-container';
import { FolderContainer } from '@/renderer/components/folders/folder-container';
+import { FileContainer } from '@/renderer/components/files/file-container';
import { getIdType, IdType } from '@/lib/id';
interface ModalContentProps {
@@ -23,6 +24,7 @@ export const ModalContent = ({ nodeId }: ModalContentProps) => {
.with(IdType.Record, () => <RecordContainer nodeId={nodeId} />)
.with(IdType.Chat, () => <ChatContainer nodeId={nodeId} />)
.with(IdType.Folder, () => <FolderContainer nodeId={nodeId} />)
+ .with(IdType.File, () => <FileContainer nodeId={nodeId} />)
.otherwise(() => null)}
</div>
);
diff --git a/desktop/src/renderer/contexts/folder.ts b/desktop/src/renderer/contexts/folder.ts
new file mode 100644
index 00000000..51c45720
--- /dev/null
+++ b/desktop/src/renderer/contexts/folder.ts
@@ -0,0 +1,15 @@
+import { FileNode } from '@/types/files';
+import { createContext, useContext } from 'react';
+
+interface FolderContext {
+ id: string;
+ name: string;
+ files: FileNode[];
+ onClick: (event: React.MouseEvent<HTMLElement>, id: string) => void;
+ onDoubleClick: (event: React.MouseEvent<HTMLElement>, id: string) => void;
+ onMove: (nodeId: string, targetId: string) => void;
+}
+
+export const FolderContext = createContext<FolderContext>({} as FolderContext);
+
+export const useFolder = () => useContext(FolderContext);
diff --git a/desktop/src/types/files.ts b/desktop/src/types/files.ts
index 4afee060..13e8111c 100644
--- a/desktop/src/types/files.ts
+++ b/desktop/src/types/files.ts
@@ -1,4 +1,36 @@
+import { UserNode } from '@/types/users';
+
export type ServerFileUploadResponse = {
id: string;
url: string;
};
+
+export type ServerFileDownloadResponse = {
+ id: string;
+ url: string;
+};
+
+export type FileNode = {
+ id: string;
+ name: string;
+ mimeType: string;
+ size: number;
+ extension: string;
+ fileName: string;
+ createdAt: string;
+ downloadProgress?: number | null;
+};
+
+export type FileDetails = {
+ id: string;
+ name: string;
+ mimeType: string;
+ size: number;
+ extension: string;
+ fileName: string;
+ downloadProgress?: number | null;
+ createdAt: string;
+ createdBy: UserNode;
+};
+
+export type FilePreviewType = 'image' | 'video' | 'other';