import { openTextContentInNewTab } from '../utils/ocr'; import type { EnsureAssetUrl, EnsurePreviewData, GetDocumentAsset, } from '../utils/ocr'; import type { Document } from '../types/documents'; const asyncFalse = async () => false; const resolveDocumentDownloadHref = (document?: Document | null): string | null => { if (!document) { return null; } const downloadUrl = (document.current_version as { download?: { url: string } | null } | null)?.download?.url; if (!downloadUrl) { return null; } return downloadUrl; }; 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, }; };