1import type { PreviewAnnotationPayload } from "@t3tools/contracts";
2
3import { dataUrlToFile } from "./imageCompression";
4
5export type PreviewAnnotationCapture =
6 /** The crop is ready to attach. */
7 | { readonly status: "captured"; readonly file: File }
8 /** The pick carried no crop, which is normal for comment-only annotations. */
9 | { readonly status: "none" }
10 /** The crop could not be decoded. Send the annotation without it. */
11 | { readonly status: "failed" };
12
13const PNG_DATA_URL_PREFIX = "data:image/png;base64,";
14
15/** Decode Electron's PNG crop locally; fetching a data URL violates desktop connect-src. */
16export function capturePreviewAnnotationScreenshot(
17 annotation: PreviewAnnotationPayload,
18): PreviewAnnotationCapture {
19 if (!annotation.screenshot) return { status: "none" };
20 try {
21 const { dataUrl } = annotation.screenshot;
22 if (!dataUrl.startsWith(PNG_DATA_URL_PREFIX)) {
23 return { status: "failed" };
24 }
25 const file = dataUrlToFile(dataUrl, `preview-annotation-${annotation.id}.png`, "image/png");
26 return file.size > 0 ? { status: "captured", file } : { status: "failed" };
27 } catch {
28 return { status: "failed" };
29 }
30}