feat: Attachment preview

This commit is contained in:
iamsivin
2024-11-18 23:47:58 +05:30
parent 2e30d4b825
commit 610b05ed5a
7 changed files with 200 additions and 12 deletions
@@ -19,3 +19,19 @@ export const checkFileSizeLimit = (file, maximumUploadLimit) => {
const fileSizeInMB = fileSizeInMegaBytes(fileSize);
return fileSizeInMB <= maximumUploadLimit;
};
export const fileNameWithEllipsis = (file, maxLength = 26, ellipsis = '…') => {
const fullName = file?.filename ?? file?.name ?? 'Untitled';
const dotIndex = fullName.lastIndexOf('.');
if (dotIndex === -1) return fullName;
const [name, extension] = [
fullName.slice(0, dotIndex),
fullName.slice(dotIndex),
];
if (name.length <= maxLength) return fullName;
return `${name.slice(0, maxLength)}${ellipsis}${extension}`;
};
@@ -2,6 +2,7 @@ import {
formatBytes,
fileSizeInMegaBytes,
checkFileSizeLimit,
fileNameWithEllipsis,
} from '../FileHelper';
describe('#File Helpers', () => {
@@ -35,4 +36,51 @@ describe('#File Helpers', () => {
expect(checkFileSizeLimit({ file: { size: 199154 } }, 40)).toBe(true);
});
});
describe('fileNameWithEllipsis', () => {
it('should return original filename if name length is within limit', () => {
const file = { name: 'document.pdf' };
expect(fileNameWithEllipsis(file)).toBe('document.pdf');
});
it('should truncate filename if it exceeds max length', () => {
const file = { name: 'very-long-filename-that-needs-truncating.pdf' };
expect(fileNameWithEllipsis(file)).toBe(
'very-long-filename-that-ne….pdf'
);
});
it('should handle files without extension', () => {
const file = { name: 'README' };
expect(fileNameWithEllipsis(file)).toBe('README');
});
it('should handle files with multiple dots', () => {
const file = { name: 'archive.tar.gz' };
expect(fileNameWithEllipsis(file)).toBe('archive.tar.gz');
});
it('should handle hidden files', () => {
const file = { name: '.gitignore' };
expect(fileNameWithEllipsis(file)).toBe('.gitignore');
});
it('should handle both filename and name properties', () => {
const file = {
filename: 'from-filename.pdf',
name: 'from-name.pdf',
};
expect(fileNameWithEllipsis(file)).toBe('from-filename.pdf');
});
it('should handle special characters', () => {
const file = { name: 'résumé-2023_final-version.doc' };
expect(fileNameWithEllipsis(file)).toBe('résumé-2023_final-version.doc');
});
it('should handle very short filenames', () => {
const file = { name: 'a.txt' };
expect(fileNameWithEllipsis(file)).toBe('a.txt');
});
});
});