Stirling-PDF/frontend/src/hooks/tools/shared/useToolResources.ts
Reece Browne f353d3404c Refactor file context and tool operations
- Updated `useToolOperation` to include file ID and operation parameters for better tracking.
- Enhanced `useToolResources` to utilize refs for blob URL cleanup, improving performance and reducing unnecessary state updates.
- Modified `ThumbnailGenerationService` to clarify worker setup and fallback mechanisms, removing excessive logging for cleaner output.
- Refactored tool components (Compress, Convert, OCR, Split) to use `useFileActions` for state management, ensuring consistency across tools.
- Expanded `FileContextState` and `FileContextActions` to support new file processing features and improved state management.
- Added new `FileContextSelectors` for efficient file access and state querying, minimizing re-renders in components.
2025-08-12 14:37:45 +01:00

125 lines
3.7 KiB
TypeScript

import { useState, useCallback, useEffect, useRef } from 'react';
import { generateThumbnailForFile } from '../../../utils/thumbnailUtils';
import { zipFileService } from '../../../services/zipFileService';
export const useToolResources = () => {
const [blobUrls, setBlobUrls] = useState<string[]>([]);
const addBlobUrl = useCallback((url: string) => {
setBlobUrls(prev => [...prev, url]);
}, []);
const cleanupBlobUrls = useCallback(() => {
setBlobUrls(prev => {
prev.forEach(url => {
try {
URL.revokeObjectURL(url);
} catch (error) {
console.warn('Failed to revoke blob URL:', error);
}
});
return [];
});
}, []); // No dependencies - use functional update pattern
// Cleanup on unmount - use ref to avoid dependency on blobUrls state
const blobUrlsRef = useRef<string[]>([]);
useEffect(() => {
blobUrlsRef.current = blobUrls;
}, [blobUrls]);
useEffect(() => {
return () => {
blobUrlsRef.current.forEach(url => {
try {
URL.revokeObjectURL(url);
} catch (error) {
console.warn('Failed to revoke blob URL during cleanup:', error);
}
});
};
}, []); // No dependencies - use ref to access current URLs
const generateThumbnails = useCallback(async (files: File[]): Promise<string[]> => {
const thumbnails: string[] = [];
for (const file of files) {
try {
const thumbnail = await generateThumbnailForFile(file);
if (thumbnail) {
thumbnails.push(thumbnail);
}
} catch (error) {
console.warn(`Failed to generate thumbnail for ${file.name}:`, error);
thumbnails.push('');
}
}
return thumbnails;
}, []);
const extractZipFiles = useCallback(async (zipBlob: Blob): Promise<File[]> => {
try {
const zipFile = new File([zipBlob], 'temp.zip', { type: 'application/zip' });
const extractionResult = await zipFileService.extractPdfFiles(zipFile);
return extractionResult.success ? extractionResult.extractedFiles : [];
} catch (error) {
console.error('useToolResources.extractZipFiles - Error:', error);
return [];
}
}, []);
const extractAllZipFiles = useCallback(async (zipBlob: Blob): Promise<File[]> => {
try {
const JSZip = (await import('jszip')).default;
const zip = new JSZip();
const arrayBuffer = await zipBlob.arrayBuffer();
const zipContent = await zip.loadAsync(arrayBuffer);
const extractedFiles: File[] = [];
for (const [filename, file] of Object.entries(zipContent.files)) {
if (!file.dir) {
const content = await file.async('blob');
const extractedFile = new File([content], filename, { type: 'application/pdf' });
extractedFiles.push(extractedFile);
}
}
return extractedFiles;
} catch (error) {
console.error('Error in extractAllZipFiles:', error);
return [];
}
}, []);
const createDownloadInfo = useCallback(async (
files: File[],
operationType: string
): Promise<{ url: string; filename: string }> => {
if (files.length === 1) {
const url = URL.createObjectURL(files[0]);
addBlobUrl(url);
return { url, filename: files[0].name };
}
// Multiple files - create zip using shared service
const { zipFile } = await zipFileService.createZipFromFiles(files, `${operationType}_results.zip`);
const url = URL.createObjectURL(zipFile);
addBlobUrl(url);
return { url, filename: zipFile.name };
}, [addBlobUrl]);
return {
generateThumbnails,
createDownloadInfo,
extractZipFiles,
extractAllZipFiles,
cleanupBlobUrls,
};
};