Files
chatkit/src/image.ts
T
CatoandClaude dce645fff5 feat: @bitbaum/chatkit/attach for any uploader, and the file-input check every app runs (0.4.0) (#9)
- `@bitbaum/chatkit/attach`: AttachMenu, ATTACH_SOURCE_INPUT, isTextFile,
  acceptFamilies and shrinkImage without the composer, so an app with no chat
  (avatars, product photos, receipts) uses the same picker instead of
  re-rolling a file input. AttachMenu takes `sources` (an image uploader offers
  Camera + Photos; one source skips the sheet) and a `trigger`.
- `chatkit-check-file-inputs` (bin): fails CI on a literal accept that mixes
  file families — the shape that hid screenshots on Android in loki, orangecat
  and evig. Same rule as the package (acceptFamilies), so there is one
  definition; a justified exception is marked on the line.
- shrinkImage moves out of the composer hook into src/image.ts (unchanged).
- README: install releases from npm, never a commit — heidi and substrata
  stayed on the broken paperclip because they pinned old versions.


Claude-Session: https://claude.ai/code/session_01BWXjqiHm8jFta4FXuc7Tck

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-07 04:43:16 -07:00

43 lines
1.6 KiB
TypeScript

/**
* Shrinking a picture in the browser before it leaves the device — for a chat
* attachment and for any uploader (an avatar, a product photo, a receipt).
* Browser-only: it needs `createImageBitmap` and a canvas, and returns null
* where they are missing rather than throwing.
*/
import { dataUrlBytes, fitWithin } from "./attachments.js";
/**
* Draw the image no larger than `maxEdge` and encode it as JPEG, stepping the
* quality down until it fits `maxBytes`. Null when it cannot be made to fit,
* or the browser cannot decode it (no `createImageBitmap`, no canvas).
*/
export async function shrinkImage(
file: File,
maxEdge: number,
maxBytes: number,
): Promise<string | null> {
if (typeof createImageBitmap !== "function" || typeof document === "undefined") return null;
const bitmap = await createImageBitmap(file);
try {
const size = fitWithin(bitmap.width, bitmap.height, maxEdge);
const canvas = document.createElement("canvas");
canvas.width = size.width;
canvas.height = size.height;
const ctx = canvas.getContext("2d");
if (!ctx) return null;
// JPEG has no alpha: paint white first so a transparent PNG does not turn black.
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, size.width, size.height);
ctx.drawImage(bitmap, 0, 0, size.width, size.height);
let quality = 0.82;
let dataUrl = canvas.toDataURL("image/jpeg", quality);
while (dataUrlBytes(dataUrl) > maxBytes && quality > 0.4) {
quality -= 0.15;
dataUrl = canvas.toDataURL("image/jpeg", quality);
}
return dataUrlBytes(dataUrl) > maxBytes ? null : dataUrl;
} finally {
bitmap.close();
}
}