SmythOS Studio: Open-Source Visual AI Agent Builder and deployable runtime stack from SmythOS. Start with an intuitive drag-and-drop workspace, extend with custom code, and deploy your agents anywhere — local, cloud, or edge — with full governance and control.
JavaScript a2aagentic-aiai-agentsdevtoolsmcp-clientn8n-alternativeno-codeopen-sourceorchestrationsmythosvisual-builder
Refactor FileItemPreview component to utilize attachment structure for improved clarity and maintainability
Salman-Ahamede822156f9bc0
diff --git a/packages/app/src/react/features/ai-chat/components/FileItemPreview.tsx b/packages/app/src/react/features/ai-chat/components/FileItemPreview.tsxindex b972c3c4..4fb06db9 100644--- a/packages/app/src/react/features/ai-chat/components/FileItemPreview.tsx+++ b/packages/app/src/react/features/ai-chat/components/FileItemPreview.tsx@@ -1,4 +1,3 @@-import { cn } from '@src/react/shared/utils/general';import { memo, useEffect, useMemo, useState, type FC, type ReactElement } from 'react';import {FaRegFileAudio,@@ -10,13 +9,16 @@ import {FaRegFileWord,FaXmark,} from 'react-icons/fa6';+import type { IAttachment } from '../types/chat';+/** Map of file extensions to their corresponding icons */const FILE_ICONS: Record<string, ReactElement> = {pdf: <FaRegFilePdf className="text-white text-xl" />,doc: <FaRegFileWord className="text-white text-xl" />,docx: <FaRegFileWord className="text-white text-xl" />,xls: <FaRegFileExcel className="text-white text-xl" />,xlsx: <FaRegFileExcel className="text-white text-xl" />,+ csv: <FaRegFileExcel className="text-white text-xl" />,mp3: <FaRegFileAudio className="text-white text-xl" />,wav: <FaRegFileAudio className="text-white text-xl" />,ogg: <FaRegFileAudio className="text-white text-xl" />,@@ -28,18 +30,24 @@ const FILE_ICONS: Record<string, ReactElement> = {py: <FaRegFileCode className="text-white text-xl" />,java: <FaRegFileCode className="text-white text-xl" />,cpp: <FaRegFileCode className="text-white text-xl" />,+ txt: <FaRegFileLines className="text-white text-xl" />,};+/** Default icon for unknown file types */const DEFAULT_ICON = <FaRegFileLines className="text-white text-xl" />;interface IRemoveButtonProps {onRemove: () => void;}+/**+ * Remove button component for file preview+ * Shows on hover with a close icon+ */const RemoveButton: FC<IRemoveButtonProps> = memo(({ onRemove }) => (<buttononClick={onRemove}- className="absolute -top-2 -right-2 size-6 flex justify-center items-center bg-white rounded-full text-[#6B7280] border border-[#E5E7EB] opacity-0 transition-opacity duration-200 z-10 cursor-pointer hover:text-[#374151] pt-0.5"+ className="size-6 flex justify-center items-center bg-white rounded-full text-[#6B7280] border border-[#E5E7EB] opacity-0 transition-opacity duration-200 z-10 cursor-pointer hover:text-[#374151] pt-0.5"aria-label="Remove file"><FaXmark />@@ -48,151 +56,168 @@ const RemoveButton: FC<IRemoveButtonProps> = memo(({ onRemove }) => (RemoveButton.displayName = 'RemoveButton';+/**+ * Props for FileItemPreview component+ * Uses IAttachment for file data, onRemove presence determines if removable+ */export interface IFileItemPreviewProps {- fileObj?: File;- url?: string;- blobUrl?: string | null;- mimeType?: string;- fileName?: string;+ /** Attachment data containing file info */+ attachment: IAttachment;+ /** If provided, shows remove button. If not, component is readonly */onRemove?: () => void;+ /** Shows upload spinner overlay when true */isUploading?: boolean;- isReadOnly?: boolean;- inChatBubble?: boolean;}-const getFileExtension = (fileName?: string, url?: string, blobUrl?: string | null): string => {+/**+ * Extracts file extension from filename or URL+ * @param fileName - The name of the file+ * @param url - Optional URL to extract extension from+ * @param blobUrl - Optional blob URL to extract extension from+ * @returns Lowercase file extension or empty string+ */+const getFileExtension = (fileName: string, url?: string, blobUrl?: string | null): string => {+ // Try to get extension from filename firstif (fileName) {- return fileName.split('.').pop()?.toLowerCase() || '';+ const ext = fileName.split('.').pop();+ if (ext) {+ return ext.toLowerCase();+ }}+ // Fallback to URL if filename doesn't have extensionconst urlToCheck = url || blobUrl;if (urlToCheck) {const urlPath = urlToCheck.split('/').pop() || urlToCheck.split('\\').pop() || '';const cleanPath = urlPath.split('?')[0];- return cleanPath.split('.').pop()?.toLowerCase() || '';+ const ext = cleanPath.split('.').pop();+ if (ext) {+ return ext.toLowerCase();+ }}return '';};-const isImageType = (mimeType?: string): boolean => {- return mimeType?.startsWith('image/') || false;+/**+ * Checks if the given MIME type is an image type+ * @param mimeType - The MIME type to check+ * @returns True if the type is an image+ */+const isImageType = (mimeType: string): boolean => {+ return mimeType.startsWith('image/');};-const getPreviewUrl = (- fileObj?: File,- url?: string,- blobUrl?: string | null,- inChatBubble?: boolean,-): string | null => {- if (inChatBubble) {- return blobUrl || url || null;+/**+ * Gets the preview URL for an attachment+ * Prioritizes blob URL, then creates object URL from file, then falls back to url+ * @param attachment - The attachment to get preview URL for+ * @returns Preview URL or null if not available+ */+const getPreviewUrl = (attachment: IAttachment): string | null => {+ // Prefer blobUrl if available+ if (attachment.blobUrl) {+ return attachment.blobUrl;}- if (fileObj) {- return URL.createObjectURL(fileObj);+ // Create object URL from File if available+ if (attachment.file) {+ return URL.createObjectURL(attachment.file);}- return blobUrl || url || null;+ // Fallback to url+ return attachment.url || null;};+/**+ * FileItemPreview component displays a preview of an attached file+ * - Shows image thumbnail for image files+ * - Shows file icon and name for other file types+ * - Optional remove button controlled by onRemove prop presence+ * - Optional upload spinner overlay+ */export const FileItemPreview: FC<IFileItemPreviewProps> = memo(- ({- fileObj,- url,- blobUrl,- mimeType,- fileName,- onRemove,- isUploading = false,- isReadOnly = false,- inChatBubble = false,- }) => {+ ({ attachment, onRemove, isUploading = false }) => {+ const { name, type, file, url, blobUrl } = attachment;++ // State for image preview URLconst [preview, setPreview] = useState<string | null>(() => {- if (inChatBubble) return blobUrl || url || null;- return null;+ // Initialize with blobUrl or url for immediate display+ return blobUrl || url || null;});- const fileExtension = useMemo(- () => getFileExtension(fileName || fileObj?.name, url, blobUrl),- [fileName, fileObj?.name, url, blobUrl],- );+ // Extract file extension from name or URLs+ const fileExtension = useMemo(() => getFileExtension(name, url, blobUrl), [name, url, blobUrl]);+ // Get appropriate icon based on file extensionconst fileIcon = useMemo(() => FILE_ICONS[fileExtension] || DEFAULT_ICON, [fileExtension]);- const isImage = useMemo(() => {- const type = mimeType || fileObj?.type;- return isImageType(type);- }, [mimeType, fileObj?.type]);+ // Check if file is an image based on MIME type+ const isImage = useMemo(() => isImageType(type), [type]);+ // Effect to handle preview URL creation and cleanupuseEffect(() => {+ // Skip if not an imageif (!isImage) {setPreview(null);return;}- const previewUrl = getPreviewUrl(fileObj, url, blobUrl, inChatBubble);+ const previewUrl = getPreviewUrl(attachment);setPreview(previewUrl);+ // Cleanup: revoke object URL if we created one from filereturn () => {- if (previewUrl && !inChatBubble && fileObj) {+ if (previewUrl && file && !blobUrl && !url) {URL.revokeObjectURL(previewUrl);}};- }, [isImage, fileObj, url, blobUrl, inChatBubble]);-- const displayName = fileName || fileObj?.name || 'Unknown file';+ }, [isImage, attachment, file, blobUrl, url]);+ /**+ * Handles image load error by trying alternative sources+ */const handleImageError = () => {- if (inChatBubble) {- if (fileObj && isImageType(fileObj.type)) {- try {- const newBlobUrl = URL.createObjectURL(fileObj);- setPreview(newBlobUrl);- return;- } catch {- // Fall through to URL check- }+ // Try creating blob URL from file if available+ if (file && isImageType(file.type)) {+ try {+ const newBlobUrl = URL.createObjectURL(file);+ setPreview(newBlobUrl);+ return;+ } catch {+ // Fall through to URL check}-- if (url && (url.startsWith('http://') || url.startsWith('https://'))) {- setPreview(url);- } else setPreview(null);- } else {- if (url && preview !== url) setPreview(url);}++ // Try using the URL if it's a valid http(s) URL+ if (url && (url.startsWith('http://') || url.startsWith('https://'))) {+ if (preview !== url) setPreview(url);+ } else setPreview(null);};+ // Render image preview for image filesif (isImage) {return (- <div- className={cn(- 'relative inline-block size-16 min-w-16 min-h-16 group',- inChatBubble ? 'mt-0' : 'mt-4',- )}- >+ <div className="relative inline-block size-16 min-w-16 min-h-16 group mt-4">{preview ? (<imgsrc={preview}- alt={displayName}+ alt={name}className="w-full h-full object-cover rounded-lg"onError={handleImageError}/>) : (<div className="w-full h-full bg-gray-200 rounded-lg flex flex-col items-center justify-center"><span className="text-xs text-gray-500">Preview unavailable</span>- {inChatBubble && url && (- <span className="text-[10px] text-gray-400 mt-1">{url.substring(0, 20)}...</span>- )}</div>)}{isUploading && (- <div className="absolute inset-0 bg-black/50 rounded-lg flex items-center justify-center">- <div className="animate-spin rounded-full p-2 border-2 border-white border-t-transparent" />+ <div className="absolute inset-0 bg-black bg-opacity-50 rounded-lg flex items-center justify-center">+ <div className="animate-spin rounded-full h-6 w-6 border-solid border-2 border-white border-t-transparent" /></div>)}- {!isReadOnly && !inChatBubble && onRemove && (- <div className="group-hover:[&>button]:opacity-100">+ {onRemove && (+ <div className="absolute -top-2 -right-2 group-hover:[&>button]:opacity-100"><RemoveButton onRemove={onRemove} /></div>)}@@ -200,10 +225,11 @@ export const FileItemPreview: FC<IFileItemPreviewProps> = memo();}+ // Render file icon preview for non-image filesreturn (- <div className={cn('relative inline-block group', inChatBubble ? 'mt-0' : 'mt-4')}>- {!isReadOnly && !inChatBubble && onRemove && (- <div className="group-hover:[&>button]:opacity-100">+ <div className="relative inline-block group mt-4">+ {onRemove && (+ <div className="absolute -top-2 -right-2 group-hover:[&>button]:opacity-100"><RemoveButton onRemove={onRemove} /></div>)}@@ -217,7 +243,7 @@ export const FileItemPreview: FC<IFileItemPreviewProps> = memo(</div><div className="min-w-0 space-y-0.5"><h6 className="whitespace-nowrap overflow-hidden text-ellipsis font-semibold">- {displayName}+ {name}</h6><p className="text-[#9CA3AF]">{fileExtension.toUpperCase() || 'FILE'}</p></div>diff --git a/packages/app/src/react/features/ai-chat/components/input.tsx b/packages/app/src/react/features/ai-chat/components/input.tsxindex e0950e8d..df97d60d 100644--- a/packages/app/src/react/features/ai-chat/components/input.tsx+++ b/packages/app/src/react/features/ai-chat/components/input.tsx@@ -235,16 +235,12 @@ export const ChatInput = () => {role="list"aria-label="Attached files">- {files.map((fileWithMetadata, index) => (+ {files.map((file, index) => (<FileItemPreview- key={`${fileWithMetadata.id}`}- fileObj={fileWithMetadata.file}- url={fileWithMetadata.url}- blobUrl={fileWithMetadata.blobUrl}- mimeType={fileWithMetadata.type}- fileName={fileWithMetadata.name}+ key={`${file.id}`}+ attachment={file}onRemove={() => handleRemoveFile(index)}- isUploading={uploadStatus[fileWithMetadata.name]?.status === 'uploading'}+ isUploading={uploadStatus[file.name]?.status === 'uploading'}/>))}</div>diff --git a/packages/app/src/react/features/ai-chat/components/user-message.tsx b/packages/app/src/react/features/ai-chat/components/user-message.tsxindex d74b5e59..a2b77432 100644--- a/packages/app/src/react/features/ai-chat/components/user-message.tsx+++ b/packages/app/src/react/features/ai-chat/components/user-message.tsx@@ -26,13 +26,7 @@ export const UserMessage: FC<IUserMessage> = ({ message, files }) => {{files.map((attachment, index) => (<FileItemPreviewkey={`${attachment.name}-${index}-${attachment.url || attachment.blobUrl || index}`}- fileObj={attachment.file}- url={attachment.url}- blobUrl={attachment.blobUrl}- mimeType={attachment.type}- fileName={attachment.name}- isReadOnly- inChatBubble+ attachment={attachment}/>))}</div>