1import { FileTypeCategory } from '$lib/enums';
2import { getFileTypeCategory, getFileTypeCategoryByExtension, isImageFile } from '$lib/utils';
3
4export interface AttachmentDisplayItemsOptions {
5 uploadedFiles?: ChatUploadedFile[];
6 attachments?: DatabaseMessageExtra[];
7}
8
9/**
10 * Gets the file type category from an uploaded file, checking both MIME type and extension
11 */
12function getUploadedFileCategory(file: ChatUploadedFile): FileTypeCategory | null {
13 const categoryByMime = getFileTypeCategory(file.type);
14
15 if (categoryByMime) {
16 return categoryByMime;
17 }
18
19 return getFileTypeCategoryByExtension(file.name);
20}
21
22/**
23 * Creates a unified list of display items from uploaded files and stored attachments.
24 * Items are returned in reverse order (newest first).
25 */
26export function getAttachmentDisplayItems(
27 options: AttachmentDisplayItemsOptions
28): ChatAttachmentDisplayItem[] {
29 const { uploadedFiles = [], attachments = [] } = options;
30 const items: ChatAttachmentDisplayItem[] = [];
31
32 // Add uploaded files (ChatForm)
33 for (const file of uploadedFiles) {
34 items.push({
35 id: file.id,
36 name: file.name,
37 size: file.size,
38 preview: file.preview,
39 isImage: getUploadedFileCategory(file) === FileTypeCategory.IMAGE,
40 uploadedFile: file,
41 textContent: file.textContent
42 });
43 }
44
45 // Add stored attachments (ChatMessage)
46 for (const [index, attachment] of attachments.entries()) {
47 const isImage = isImageFile(attachment);
48
49 items.push({
50 id: `attachment-${index}`,
51 name: attachment.name,
52 preview: isImage && 'base64Url' in attachment ? attachment.base64Url : undefined,
53 isImage,
54 attachment,
55 attachmentIndex: index,
56 textContent: 'content' in attachment ? attachment.content : undefined
57 });
58 }
59
60 return items.reverse();
61}