Files
papercrate/frontend/src/documents/documentActions.ts
T

86 lines
2.1 KiB
TypeScript

import { openTextContentInNewTab } from '../utils/ocr';
import type {
EnsureAssetUrl,
EnsurePreviewData,
GetDocumentAsset,
} from '../utils/ocr';
import type { Document } from '../types/documents';
const asyncFalse = async () => false;
export const resolveDocumentDownloadHref = (document?: Document | null): string | null => {
if (!document) {
return null;
}
const download = document.current_version?.download;
if (!download?.url) {
return null;
}
if (download.expires_at && download.expires_at <= Date.now()) {
return null;
}
return download.url;
};
const hasDocumentTextContentAsset = (document?: Document | null, getDocumentAsset?: GetDocumentAsset | null): boolean => {
if (!document || !getDocumentAsset) {
return false;
}
return Boolean(getDocumentAsset(document, 'text-content'));
};
interface CreateDocumentActionStateArgs {
document: Document | null;
ensurePreviewData: EnsurePreviewData;
ensureAssetUrl: EnsureAssetUrl;
getDocumentAsset?: GetDocumentAsset | null;
notifyApiError?: (error: unknown, message: string) => void;
ocrErrorMessage?: string;
}
export const createDocumentActionState = ({
document,
ensurePreviewData,
ensureAssetUrl,
getDocumentAsset,
notifyApiError,
ocrErrorMessage = 'Unable to open text content.',
}: CreateDocumentActionStateArgs) => {
if (!document) {
return {
downloadHref: null,
hasOcr: false,
openOcr: asyncFalse,
};
}
const downloadHref = resolveDocumentDownloadHref(document);
const hasOcr = hasDocumentTextContentAsset(document, getDocumentAsset);
const openOcr = hasOcr
? async () => {
try {
const success = await openTextContentInNewTab({
document,
ensurePreviewData,
getDocumentAsset,
ensureAssetUrl,
});
if (!success) {
notifyApiError?.(new Error('Text content URL unavailable.'), ocrErrorMessage);
}
return success;
} catch (error) {
notifyApiError?.(error, ocrErrorMessage);
throw error;
}
}
: asyncFalse;
return {
downloadHref,
hasOcr,
openOcr,
};
};