Native images (#6619)
Co-authored-by: Douwe Osinga <douwe@squareup.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import { useCallback, useState, useRef, useEffect } from 'react';
|
||||
import { compressImageDataUrl } from '../utils/conversionUtils';
|
||||
|
||||
export interface DroppedFile {
|
||||
id: string;
|
||||
@@ -6,7 +7,7 @@ export interface DroppedFile {
|
||||
name: string;
|
||||
type: string;
|
||||
isImage: boolean;
|
||||
dataUrl?: string; // For image previews
|
||||
dataUrl?: string;
|
||||
isLoading?: boolean;
|
||||
error?: string;
|
||||
}
|
||||
@@ -71,25 +72,41 @@ export const useFileDrop = () => {
|
||||
|
||||
droppedFileObjects.push(droppedFile);
|
||||
|
||||
// For images, generate a preview (only if successfully processed)
|
||||
if (droppedFile.isImage && !droppedFile.error) {
|
||||
const reader = new FileReader();
|
||||
activeReadersRef.current.add(reader);
|
||||
|
||||
reader.onload = (event) => {
|
||||
reader.onload = async (event) => {
|
||||
const dataUrl = event.target?.result as string;
|
||||
setDroppedFiles((prev) =>
|
||||
prev.map((f) => (f.id === droppedFile.id ? { ...f, dataUrl, isLoading: false } : f))
|
||||
);
|
||||
try {
|
||||
// Compress the image
|
||||
const compressedDataUrl = await compressImageDataUrl(dataUrl);
|
||||
setDroppedFiles((prev) =>
|
||||
prev.map((f) =>
|
||||
f.id === droppedFile.id
|
||||
? { ...f, dataUrl: compressedDataUrl, isLoading: false }
|
||||
: f
|
||||
)
|
||||
);
|
||||
} catch (compressionError) {
|
||||
console.error('Failed to compress image:', file.name, compressionError);
|
||||
setDroppedFiles((prev) =>
|
||||
prev.map((f) =>
|
||||
f.id === droppedFile.id
|
||||
? { ...f, error: 'Failed to compress image', isLoading: false }
|
||||
: f
|
||||
)
|
||||
);
|
||||
}
|
||||
activeReadersRef.current.delete(reader);
|
||||
};
|
||||
|
||||
reader.onerror = () => {
|
||||
console.error('Failed to generate preview for:', file.name);
|
||||
console.error('Failed to read image:', file.name);
|
||||
setDroppedFiles((prev) =>
|
||||
prev.map((f) =>
|
||||
f.id === droppedFile.id
|
||||
? { ...f, error: 'Failed to load image preview', isLoading: false }
|
||||
? { ...f, error: 'Failed to load image', isLoading: false }
|
||||
: f
|
||||
)
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user