Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"dependencies": {
"@internxt/css-config": "^1.1.0",
"@internxt/lib": "^1.4.1",
"@internxt/sdk": "^1.17.4",
"@internxt/sdk": "^1.17.5",
"@internxt/ui": "^0.1.16",
"@phosphor-icons/react": "^2.1.10",
"@reduxjs/toolkit": "^2.11.2",
Expand All @@ -45,7 +45,7 @@
"dompurify": "^3.3.3",
"i18next": "^25.8.13",
"idb": "^8.0.3",
"internxt-crypto": "1.4.0",
"internxt-crypto": "^1.5.0",
"prettysize": "^2.0.0",
"react": "^19.2.0",
"react-device-detect": "^2.2.3",
Expand Down
94 changes: 52 additions & 42 deletions src/components/compose-message/hooks/useAttachments.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { renderHook, act } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import useAttachments from './useAttachments';
import { UploadManager } from '@/services/upload-manager';
import notificationsService, { ToastType } from '@/services/notifications';
import type { UploadAttachmentCallbacks, UploadHandle } from '@/types/mail/upload-manager';
import { MAX_TOTAL_ATTACHMENT_BYTES_PER_MAIL } from '@/constants';
import type { UploadManagerCallbacks } from '@/services/upload-manager';

vi.mock('@/i18n', () => ({ useTranslationContext: () => ({ translate: (key: string) => key }) }));

Expand All @@ -13,54 +12,65 @@ vi.mock('@/services/notifications', () => ({
ToastType: { Success: 'success', Error: 'error', Warning: 'warning', Info: 'info', Loading: 'loading' },
}));

vi.mock('internxt-crypto', () => ({ genSymmetricKey: () => new Uint8Array(32) }));

const enqueue = vi.fn();
const retryFn = vi.fn();
const cancel = vi.fn();
const clear = vi.fn();
let lastCallbacks: UploadManagerCallbacks | undefined;

vi.mock('@/services/upload-manager', () => ({
UploadManager: { instance: { run: vi.fn(), retry: vi.fn(), remove: vi.fn(), clear: vi.fn() } },
UploadManager: class {
constructor(_sessionKey: Uint8Array, callbacks: UploadManagerCallbacks) {
lastCallbacks = callbacks;
}
enqueue = enqueue;
retry = retryFn;
cancel = cancel;
clear = clear;
},
}));

const run = vi.mocked(UploadManager.instance.run);
const retry = vi.mocked(UploadManager.instance.retry);
const remove = vi.mocked(UploadManager.instance.remove);
const clear = vi.mocked(UploadManager.instance.clear);
const show = vi.mocked(notificationsService.show);

let lastCallbacks: UploadAttachmentCallbacks | undefined;

let idSeq = 0;
const fileOfSize = (size: number, name = 'a.txt', type = 'text/plain'): File => {
const f = new File(['x'], name, { type });
Object.defineProperty(f, 'size', { value: size });
return f;
};

describe('Attachments - custom hook', () => {
beforeEach(() => {
run.mockReset();
retry.mockReset();
remove.mockReset();
clear.mockReset();
show.mockReset();
lastCallbacks = undefined;
run.mockImplementation((files: File[], callbacks: UploadAttachmentCallbacks): UploadHandle[] => {
lastCallbacks = callbacks;
return files.map((file, i) => ({ id: `id-${i}`, file }));
});
});
beforeEach(() => {
idSeq = 0;
vi.stubGlobal('crypto', { ...globalThis.crypto, randomUUID: () => `id-${idSeq++}` });
enqueue.mockReset();
retryFn.mockReset();
cancel.mockReset();
clear.mockReset();
show.mockReset();
lastCallbacks = undefined;
});

afterEach(() => {
vi.restoreAllMocks();
});
afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
Comment thread
xabg2 marked this conversation as resolved.

describe('Attachments - custom hook', () => {
describe('Adding files', () => {
test('When files are added, then files are handled as expected', () => {
const f1 = fileOfSize(100, '1.txt');
const f2 = fileOfSize(200, '2.bin', 'application/octet-stream');
const { result } = renderHook(() => useAttachments());
const { result } = renderHook(() => useAttachments(new Uint8Array(32)));

act(() => result.current.addFiles([f1, f2]));

expect(run).toHaveBeenCalledWith([f1, f2], expect.any(Object));
expect(enqueue).toHaveBeenNthCalledWith(1, 'id-0', f1);
expect(enqueue).toHaveBeenNthCalledWith(2, 'id-1', f2);
expect(result.current.attachments).toEqual([
{ id: 'id-0', name: '1.txt', size: 100, type: 'text/plain', status: 'uploading' },
{ id: 'id-1', name: '2.bin', size: 200, type: 'application/octet-stream', status: 'uploading' },
{ id: 'id-0', name: '1.txt', size: 100, type: 'text/plain', status: 'uploading', file: f1 },
{ id: 'id-1', name: '2.bin', size: 200, type: 'application/octet-stream', status: 'uploading', file: f2 },
]);
expect(result.current.totalSize).toBe(f1.size + f2.size);
expect(result.current.isUploading).toBe(true);
Expand All @@ -74,23 +84,23 @@ describe('Attachments - custom hook', () => {
expect(result.current.totalSize).toBe(300);
});

test('When the new batch would exceed 25 MB total, then it shows a warning toast and does not enqueue', () => {
test('When the new batch would exceed the limit, then it shows a warning toast and does not enqueue', () => {
const big = fileOfSize(MAX_TOTAL_ATTACHMENT_BYTES_PER_MAIL + 1);
const { result } = renderHook(() => useAttachments());
const { result } = renderHook(() => useAttachments(new Uint8Array(32)));

act(() => result.current.addFiles([big]));

expect(show).toHaveBeenCalledWith({
text: 'modals.composeMessageDialog.errors.attachmentsTooLarge',
type: ToastType.Warning,
});
expect(run).not.toHaveBeenCalled();
expect(enqueue).not.toHaveBeenCalled();
expect(result.current.attachments).toHaveLength(0);
});

test('When the cumulative size reaches the 25 MB limit, then a subsequent batch is rejected', () => {
test('When the cumulative size reaches the limit, then a subsequent batch is rejected', () => {
const half = fileOfSize(MAX_TOTAL_ATTACHMENT_BYTES_PER_MAIL / 2);
const { result } = renderHook(() => useAttachments());
const { result } = renderHook(() => useAttachments(new Uint8Array(32)));

act(() => result.current.addFiles([half]));
act(() => lastCallbacks?.onSuccess('id-0', 'blob-0'));
Expand All @@ -102,8 +112,8 @@ describe('Attachments - custom hook', () => {
});

describe('upload callbacks', () => {
test('When the manager reports success, then the attachment moves to done and the id of the blob is stored', () => {
const { result } = renderHook(() => useAttachments());
test('When the manager reports success, then the attachment moves to done and the blobId is stored', () => {
const { result } = renderHook(() => useAttachments(new Uint8Array(32)));
act(() => result.current.addFiles([fileOfSize(10)]));

act(() => lastCallbacks?.onSuccess('id-0', 'blob-1'));
Expand All @@ -114,7 +124,7 @@ describe('Attachments - custom hook', () => {
});

test('When the manager reports an error, then the attachment moves to error', () => {
const { result } = renderHook(() => useAttachments());
const { result } = renderHook(() => useAttachments(new Uint8Array(32)));
act(() => result.current.addFiles([fileOfSize(10)]));

act(() => lastCallbacks?.onError('id-0', new Error('boom')));
Expand All @@ -127,33 +137,33 @@ describe('Attachments - custom hook', () => {

describe('retry', () => {
test('When retry is called on a failed attachment, then it goes back to uploading and the manager is notified', () => {
const { result } = renderHook(() => useAttachments());
const { result } = renderHook(() => useAttachments(new Uint8Array(32)));
act(() => result.current.addFiles([fileOfSize(10)]));
act(() => lastCallbacks?.onError('id-0', new Error('x')));

act(() => result.current.retry('id-0'));

expect(retry).toHaveBeenCalledWith('id-0', expect.any(Object));
expect(retryFn).toHaveBeenCalledWith('id-0');
expect(result.current.attachments[0].status).toBe('uploading');
});
});

describe('remove', () => {
test('When remove is called, then the attachment is dropped and the manager is notified', () => {
const { result } = renderHook(() => useAttachments());
const { result } = renderHook(() => useAttachments(new Uint8Array(32)));
act(() => result.current.addFiles([fileOfSize(10, '1.txt'), fileOfSize(20, '2.txt')]));

act(() => result.current.remove('id-0'));

expect(remove).toHaveBeenCalledWith('id-0');
expect(cancel).toHaveBeenCalledWith('id-0');
expect(result.current.attachments).toHaveLength(1);
expect(result.current.attachments[0].id).toBe('id-1');
});
});

describe('clear', () => {
test('When clear is called, then every attachment is removed from the manager and state', () => {
const { result } = renderHook(() => useAttachments());
const { result } = renderHook(() => useAttachments(new Uint8Array(32)));
act(() => result.current.addFiles([fileOfSize(10, '1.txt'), fileOfSize(20, '2.txt')]));

act(() => result.current.clear());
Expand Down
77 changes: 44 additions & 33 deletions src/components/compose-message/hooks/useAttachments.ts
Original file line number Diff line number Diff line change
@@ -1,44 +1,41 @@
import { useCallback, useMemo, useState } from 'react';
import { useCallback, useMemo, useRef, useState } from 'react';
import type { AttachmentRef } from '@internxt/sdk/dist/mail/types';
import { useTranslationContext } from '@/i18n';
import notificationsService, { ToastType } from '@/services/notifications';
import { bytesToString } from '@/utils/bytes-to-string';
import { UploadManager } from '@/services/upload-manager';
import type { AttachmentRef } from '@internxt/sdk/dist/mail/types';
import { MAX_TOTAL_ATTACHMENT_BYTES_PER_MAIL } from '@/constants';
import type { UploadAttachmentCallbacks } from '@/types/mail/upload-manager';
import { ErrorService } from '@/services/error';
import { UploadManager } from '@/services/upload-manager';

export type AttachmentStatus = 'uploading' | 'done' | 'error';

export interface AttachmentTask extends Omit<AttachmentRef, 'blobId'> {
id: string;
status: AttachmentStatus;
blobId?: string;
file: File;
}

const useAttachments = () => {
const useAttachments = (sessionKey: Uint8Array) => {
const { translate } = useTranslationContext();
const [attachments, setAttachments] = useState<AttachmentTask[]>([]);

const managerRef = useRef<UploadManager | null>(null);
managerRef.current ??= new UploadManager(sessionKey, {
onSuccess: (id, blobId) =>
setAttachments((prev) => prev.map((a) => (a.id === id ? { ...a, blobId, status: 'done' } : a))),
onError: (id, error) => {
console.error('ERROR UPLOADING ATTACHMENT', ErrorService.instance.castError(error));
setAttachments((prev) => prev.map((a) => (a.id === id ? { ...a, status: 'error' } : a)));
},
});

const manager = managerRef.current;

const totalSize = useMemo(() => attachments.reduce((s, a) => s + a.size, 0), [attachments]);
const isUploading = useMemo(() => attachments.some((a) => a.status === 'uploading'), [attachments]);
const hasErrors = useMemo(() => attachments.some((a) => a.status === 'error'), [attachments]);

const onTaskCompleted = (attachmentTaskId: AttachmentTask['id'], blobId: string) => {
setAttachments((prev) => prev.map((a) => (a.id === attachmentTaskId ? { ...a, blobId, status: 'done' } : a)));
};

const onTaskError = (attachmentTaskId: AttachmentTask['id'], error: unknown) => {
const castedError = ErrorService.instance.castError(error);
setAttachments((prev) => prev.map((a) => (a.id === attachmentTaskId ? { ...a, status: 'error' } : a)));
console.error('ERROR UPLOADING ATTACHMENT', castedError);
};

const callbacks: UploadAttachmentCallbacks = {
onSuccess: onTaskCompleted,
onError: onTaskError,
};

const addFiles = useCallback(
(files: FileList | File[]) => {
const list = Array.from(files);
Expand All @@ -52,38 +49,52 @@ const useAttachments = () => {
});
return;
}
const handles = UploadManager.instance.run(list, callbacks);
const pending: AttachmentTask[] = handles.map(({ id, file }) => ({
id,

const pending: AttachmentTask[] = list.map((file) => ({
id: crypto.randomUUID(),
name: file.name,
size: file.size,
type: file.type ?? 'application/octet-stream',
status: 'uploading',
file,
}));
setAttachments((prev) => [...prev, ...pending]);
pending.forEach(({ id, file }) => manager.enqueue(id, file));
},
[totalSize, translate, callbacks],
[totalSize, translate, manager],
);

const retry = useCallback(
(id: string) => {
setAttachments((prev) => prev.map((a) => (a.id === id ? { ...a, status: 'uploading' } : a)));
UploadManager.instance.retry(id, callbacks);
manager.retry(id);
},
[callbacks],
[manager],
);

const remove = useCallback((id: string) => {
UploadManager.instance.remove(id);
setAttachments((prev) => prev.filter((a) => a.id !== id));
}, []);
const remove = useCallback(
(id: string) => {
manager.cancel(id);
setAttachments((prev) => prev.filter((a) => a.id !== id));
},
[manager],
);

const clear = useCallback(() => {
UploadManager.instance.clear();
manager.clear();
setAttachments([]);
}, []);
}, [manager]);

return { attachments, totalSize, isUploading, hasErrors, addFiles, retry, remove, clear };
return {
attachments,
totalSize,
isUploading,
hasErrors,
addFiles,
retry,
remove,
clear,
};
};

export default useAttachments;
Loading
Loading