Method Usage by Context | Context | Method Used | Respects Preferences | HTML Detection | |------------------------------|-------------------------------------------------------|------------------------|----------------| | Tools (via useToolResources) | extractZipFiles() → extractWithPreferences() | ✅ Yes | ✅ Yes | | Automation | extractAutomationZipFiles() → extractAllFiles() | ❌ No (always extracts) | ✅ Yes | | Manual Unzip | extractAndStoreFilesWithHistory() → extractAllFiles() | ❌ No (always extracts) | ✅ Yes | | Auto-Upload | extractAllFiles() directly | ❌ No (always extracts) | ✅ Yes | Detailed Behavior Matrix | Context | HTML Files | Auto-Unzip OFF | Within Limit | Exceeds Limit | Notes | |--------------------------|-------------|----------------|--------------|---------------|----------------------------------------| | Tools (useToolResources) | Keep zipped | Keep zipped | Extract all | Keep zipped | Respects user preferences | | Automation | Keep zipped | Extract all | Extract all | Extract all | Ignores preferences (automation needs) | | Manual Unzip | Keep zipped | Extract all | Extract all | Extract all | User explicitly unzipping | | Auto-Upload | Keep zipped | Extract all | Extract all | Extract all | User dropped files | Simplified Decision Flow ZIP File Received │ ├─ Contains HTML? → Keep as ZIP (all contexts) │ └─ No HTML │ ├─ Tools Context │ ├─ Auto-unzip OFF? → Keep as ZIP │ └─ Auto-unzip ON │ ├─ File count ≤ limit? → Extract all │ └─ File count > limit? → Keep as ZIP │ └─ Automation/Manual/Auto-Upload └─ Extract all (ignore preferences) Key Changes from Previous Version | Entry Point | Code Path | skipAutoUnzip | Respects Preferences? | HTML Detection? | Extraction Behavior | |-----------------------------------------------|----------------------------------------------------------------------------------------|---------------|-----------------------|---------------------------|-------------------------------------------------------------------------| | Direct File Upload (FileEditor, LandingPage) | FileContext.addRawFiles() → fileActions.addFiles() | True | ❌ No | ✅ Yes | Always extract (except HTML ZIPs) | | Tool Outputs (Split, Merge, etc.) | useToolResources.extractZipFiles() → zipFileService.extractWithPreferences() | false | ✅ Yes | ✅ Yes | Conditional: Only if autoUnzip=true AND file count ≤ autoUnzipFileLimit | | Load from Storage (FileManager) | fileActions.addStirlingFileStubs() | N/A | N/A | N/A | No extraction - files already processed | | Automation Outputs | AutomationFileProcessor.extractAutomationZipFiles() → zipFileService.extractAllFiles() | N/A | ❌ No | ✅ Yes | Always extract (except HTML ZIPs) | | Manual Unzip Action (FileEditor context menu) | zipFileService.extractAndStoreFilesWithHistory() → extractAllFiles() | N/A | ❌ No | ✅ Yes (blocks extraction) | Always extract (except HTML ZIPs) - explicit user action | --------- Co-authored-by: Connor Yoh <connor@stirlingpdf.com>
125 lines
4.4 KiB
TypeScript
125 lines
4.4 KiB
TypeScript
import { useState, useCallback, useEffect, useRef } from 'react';
|
|
import { generateThumbnailForFile, generateThumbnailWithMetadata, ThumbnailWithMetadata } from '../../../utils/thumbnailUtils';
|
|
import { zipFileService } from '../../../services/zipFileService';
|
|
import { usePreferences } from '../../../contexts/PreferencesContext';
|
|
|
|
|
|
export const useToolResources = () => {
|
|
const { preferences } = usePreferences();
|
|
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[]> => {
|
|
console.log(`🖼️ useToolResources.generateThumbnails: Starting for ${files.length} files`);
|
|
const thumbnails: string[] = [];
|
|
|
|
for (const file of files) {
|
|
try {
|
|
console.log(`🖼️ Generating thumbnail for: ${file.name} (${file.type}, ${file.size} bytes)`);
|
|
const thumbnail = await generateThumbnailForFile(file);
|
|
console.log(`🖼️ Generated thumbnail for ${file.name}: SUCCESS`);
|
|
thumbnails.push(thumbnail);
|
|
} catch (error) {
|
|
console.warn(`🖼️ Failed to generate thumbnail for ${file.name}:`, error);
|
|
thumbnails.push('');
|
|
}
|
|
}
|
|
|
|
return thumbnails;
|
|
}, []);
|
|
|
|
const generateThumbnailsWithMetadata = useCallback(async (files: File[]): Promise<ThumbnailWithMetadata[]> => {
|
|
console.log(`🖼️ useToolResources.generateThumbnailsWithMetadata: Starting for ${files.length} files`);
|
|
const results: ThumbnailWithMetadata[] = [];
|
|
|
|
for (const file of files) {
|
|
try {
|
|
console.log(`🖼️ Generating thumbnail with metadata for: ${file.name} (${file.type}, ${file.size} bytes)`);
|
|
const result = await generateThumbnailWithMetadata(file);
|
|
console.log(`🖼️ Generated thumbnail with metadata for ${file.name}: SUCCESS, ${result.pageCount} pages`);
|
|
results.push(result);
|
|
} catch (error) {
|
|
console.warn(`🖼️ Failed to generate thumbnail with metadata for ${file.name}:`, error);
|
|
results.push({ thumbnail: '', pageCount: 1 });
|
|
}
|
|
}
|
|
|
|
console.log(`🖼️ useToolResources.generateThumbnailsWithMetadata: Complete. Generated ${results.length}/${files.length} thumbnails with metadata`);
|
|
return results;
|
|
}, []);
|
|
|
|
const extractZipFiles = useCallback(async (zipBlob: Blob, skipAutoUnzip = false): Promise<File[]> => {
|
|
try {
|
|
return await zipFileService.extractWithPreferences(zipBlob, {
|
|
autoUnzip: preferences.autoUnzip,
|
|
autoUnzipFileLimit: preferences.autoUnzipFileLimit,
|
|
skipAutoUnzip
|
|
});
|
|
} catch (error) {
|
|
console.error('useToolResources.extractZipFiles - Error:', error);
|
|
return [];
|
|
}
|
|
}, [preferences.autoUnzip, preferences.autoUnzipFileLimit]);
|
|
|
|
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,
|
|
generateThumbnailsWithMetadata,
|
|
createDownloadInfo,
|
|
extractZipFiles,
|
|
cleanupBlobUrls,
|
|
};
|
|
};
|