1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import type { Attachment } from "./types";
import { uid } from "./utils";
const MAX_IMAGE_SIDE = 1280;
const MAX_FILE_BYTES = 800 * 1024;
function readAsDataURL(file: File | Blob): Promise<string> {
return new Promise((resolve, reject) => {
const r = new FileReader();
r.onload = () => resolve(String(r.result));
r.onerror = () => reject(new Error("read failed"));
r.readAsDataURL(file);
});
}
export async function imageToDataUrl(file: File | Blob): Promise<string> {
const bitmap = await createImageBitmap(file);
const scale = Math.min(1, MAX_IMAGE_SIDE / Math.max(bitmap.width, bitmap.height));
const w = Math.round(bitmap.width * scale);
const h = Math.round(bitmap.height * scale);
const canvas = document.createElement("canvas");
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext("2d");
if (!ctx) throw new Error("no canvas 2d");
ctx.drawImage(bitmap, 0, 0, w, h);
bitmap.close();
return canvas.toDataURL("image/jpeg", 0.85);
}
export async function fileToAttachment(file: File): Promise<Attachment> {
if (file.type.startsWith("image/")) {
const dataUrl = await imageToDataUrl(file);
return {
id: uid("att"),
name: file.name || "image.jpg",
mime: "image/jpeg",
dataUrl,
size: Math.round(dataUrl.length * 0.75),
};
}
if (file.size > MAX_FILE_BYTES) {
throw new Error(`Файл «${file.name}» слишком большой — до 800 КБ`);
}
const dataUrl = await readAsDataURL(file);
return {
id: uid("att"),
name: file.name,
mime: file.type || "application/octet-stream",
dataUrl,
size: file.size,
};
}
export function fmtSize(bytes: number): string {
if (bytes < 1024) return `${bytes} Б`;
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} КБ`;
return `${(bytes / (1024 * 1024)).toFixed(1)} МБ`;
}
export function downloadDataUrl(name: string, dataUrl: string) {
const a = document.createElement("a");
a.href = dataUrl;
a.download = name;
a.click();
}
export function downloadBlob(name: string, blob: Blob) {
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = name;
a.click();
setTimeout(() => URL.revokeObjectURL(url), 5000);
}