Stirling-PDF/frontend/src/hooks/useFileWithUrl.ts
James Brunton af5a9d1ae1
Enforce type checking in CI (#4126)
# Description of Changes
Currently, the `tsconfig.json` file enforces strict type checking, but
nothing in CI checks that the code is actually correctly typed. [Vite
only transpiles TypeScript
code](https://vite.dev/guide/features.html#transpile-only) so doesn't
ensure that the TS code we're running is correct.

This PR adds running of the type checker to CI and fixes the type errors
that have already crept into the codebase.

Note that many of the changes I've made to 'fix the types' are just
using `any` to disable the type checker because the code is under too
much churn to fix anything properly at the moment. I still think
enabling the type checker now is the best course of action though
because otherwise we'll never be able to fix all of them, and it should
at least help us not break things when adding new code.

Co-authored-by: James <james@crosscourtanalytics.com>
2025-08-11 09:16:16 +01:00

51 lines
1.4 KiB
TypeScript

import { useMemo } from 'react';
/**
* Hook to convert a File object to { file: File; url: string } format
* Creates blob URL on-demand and handles cleanup
*/
export function useFileWithUrl(file: File | Blob | null): { file: File | Blob; url: string } | null {
return useMemo(() => {
if (!file) return null;
// Validate that file is a proper File or Blob object
if (!(file instanceof File) && !(file instanceof Blob)) {
console.warn('useFileWithUrl: Expected File or Blob, got:', file);
return null;
}
try {
const url = URL.createObjectURL(file);
// Return object with cleanup function
const result = { file, url };
// Store cleanup function for later use
(result as any)._cleanup = () => URL.revokeObjectURL(url);
return result;
} catch (error) {
console.error('useFileWithUrl: Failed to create object URL:', error, file);
return null;
}
}, [file]);
}
/**
* Hook variant that returns cleanup function separately
*/
export function useFileWithUrlAndCleanup(file: File | null): {
fileObj: { file: File; url: string } | null;
cleanup: () => void;
} {
return useMemo(() => {
if (!file) return { fileObj: null, cleanup: () => {} };
const url = URL.createObjectURL(file);
const fileObj = { file, url };
const cleanup = () => URL.revokeObjectURL(url);
return { fileObj, cleanup };
}, [file]);
}