import type { FileUpload, ImageUpload } from '../api'; // Images in the composer, as the terminal client keeps them // (cli/internal/tui/attachments.go): each attached image puts a numbered // marker in the text at the cursor, deleting the marker drops the image, and // sending numbers the images still marked 1..n in reading order. // Generic files are cards beside the prose and never put text in it, so any // `[File #n: name]` a person types stays their words. export const MAX_IMAGES = 10; export const MAX_FILES = 10; export const MAX_BYTES = 20 * 1024 * 1024; const MARKER = /\[Image #(\d+)\]/g; const TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp']; export interface Attached extends ImageUpload { /** A data URL, for the thumbnail. */ preview: string; name?: string; size?: number; } export interface AttachedFile extends FileUpload { size: number; } export interface AttachmentSelection { imageCount: number; fileCount: number; bytes: number; } export const REMOTE_FILES_NOTICE = 'files need a local workspace; images still work here'; /** What a send would carry: the images the text still marks, and every file card. */ export function attachmentSelection( text: string, images: Map, files: Map, ): AttachmentSelection { const marked = referenced(text, images); return { imageCount: marked.length, fileCount: files.size, bytes: marked.reduce((sum, n) => sum + attachmentSize(images.get(n)!), 0) + [...files.values()].reduce((sum, file) => sum + file.size, 0), }; } /** Deleting an image tile frees its bytes; file cards own their bytes until removed. */ export function collectAttachments( text: string, images: Map, files: Map, ): AttachmentSelection { const marked = new Set(referenced(text, images)); for (const n of images.keys()) if (!marked.has(n)) images.delete(n); return attachmentSelection(text, images, files); } /** * Why a selection cannot be sent as one message, or null. A restored draft can * hold more than one message allows; its bytes stay until the person removes some. */ export function attachmentProblem( selection: AttachmentSelection, ): string | null { if (selection.imageCount > MAX_IMAGES) return `${selection.imageCount} images attached — remove some to send at most ${MAX_IMAGES}`; if (selection.fileCount > MAX_FILES) return `${selection.fileCount} files attached — remove some to send at most ${MAX_FILES}`; if (selection.bytes > MAX_BYTES) return `attachments total ${formatSize(selection.bytes)} — remove some to send at most 20 MiB`; return null; } /** Admission uses browser metadata; reading the accepted file happens later. */ export function chooseAttachment( file: Pick, selected: AttachmentSelection, remote = false, ): { kind: 'image' | 'file' } | { problem: string } { const image = attachable(file); if (!image && remote) return { problem: REMOTE_FILES_NOTICE }; const count = image ? selected.imageCount : selected.fileCount; const limit = image ? MAX_IMAGES : MAX_FILES; if (count >= limit) return { problem: `this message is full — up to ${limit} ${image ? 'images' : 'files'} at a time`, }; if (selected.bytes + file.size > MAX_BYTES) return { problem: `${file.name} won't fit — keep attachments at 20 MiB or less`, }; if ( !image && (!file.name || file.name === '.' || file.name === '..' || new TextEncoder().encode(file.name).length > 255 || /[/\\\0\r\n]/.test(file.name)) ) { return { problem: `${file.name || 'this file'} needs a plain filename of at most 255 bytes, with no path separators or newlines`, }; } return { kind: image ? 'image' : 'file' }; } /** Keep a short extension visible while a long filename's stem ellipsizes. */ export function filenameParts(name: string): { stem: string; extension: string; } { const dot = name.lastIndexOf('.'); return dot > 0 && name.length - dot <= 17 ? { stem: name.slice(0, dot), extension: name.slice(dot) } : { stem: name, extension: '' }; } /** Exact decoded bytes, also for an image restored without browser metadata. */ export function attachmentSize(file: { data: string; size?: number }): number { return ( file.size ?? Math.floor((file.data.length * 3) / 4) - (file.data.endsWith('==') ? 2 : file.data.endsWith('=') ? 1 : 0) ); } export function formatSize(size: number): string { if (size < 1024) return `${size.toLocaleString()} B`; const scale = size < 1024 * 1024 ? 1024 : 1024 * 1024; return `${(size / scale).toLocaleString(undefined, { maximumFractionDigits: 1 })} ${scale === 1024 ? 'KiB' : 'MiB'}`; } export function marker(n: number): string { return `[Image #${n}]`; } /** Whether a file is an image the daemon accepts. */ export function attachable(file: Pick): boolean { return TYPES.includes(file.type); } function readDataURL(file: File): Promise<{ preview: string; data: string }> { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => { const result = reader.result; // Accommodate an empty-file representation without treating a malformed // nonempty result as its own base64 payload. if (file.size === 0 && result === 'data:') { resolve({ preview: `data:${file.type || 'application/octet-stream'};base64,`, data: '', }); return; } if (typeof result !== 'string') { reject(new Error('file reader did not return a data URL')); return; } const separator = result.indexOf(','); if ( separator < 0 || !/^data:[^,]*;base64$/i.test(result.slice(0, separator)) ) { reject(new Error('file reader returned a malformed data URL')); return; } const data = result.slice(separator + 1); const padding = data.indexOf('='); if ( data.length % 4 || /[^A-Za-z0-9+/=]/.test(data) || (padding >= 0 && !/^={1,2}$/.test(data.slice(padding))) || attachmentSize({ data }) !== file.size ) { reject(new Error('file reader returned incomplete or invalid bytes')); return; } resolve({ preview: result, data }); }; reader.onerror = () => reject(reader.error); reader.onabort = () => reject(new Error('file read was cancelled')); reader.readAsDataURL(file); }); } export async function readImage(file: File): Promise { const image = await readDataURL(file); return { mime_type: file.type as ImageUpload['mime_type'], ...image, name: file.name, size: file.size, }; } /** The numbers of the images the text still marks, in reading order, each once. */ export function referenced( text: string, images: Map, ): number[] { const numbers: number[] = []; for (const match of text.matchAll(MARKER)) { const n = Number(match[1]); if (images.has(n) && !numbers.includes(n)) numbers.push(n); } return numbers; } export async function readFile(file: File): Promise { const encoded = await readDataURL(file); return { name: file.name, data: encoded.data, size: file.size }; } /** Renumbers the marked images 1..n and returns the text to match with the images in order. */ export function resolve( text: string, images: Map, ): { text: string; images: Attached[] } { const numbers = referenced(text, images); const renumbered = new Map(numbers.map((n, index) => [n, index + 1])); return { text: text.replace(MARKER, (found, n) => renumbered.has(Number(n)) ? marker(renumbered.get(Number(n))!) : found, ), images: numbers.map((n) => images.get(n)!), }; } /** The text with every image marker (and the space before it) taken out, for text kept without its images. */ export function withoutMarkers(text: string): string { return text.replaceAll(new RegExp(` ?${MARKER.source}`, 'g'), ''); } /** A canvas note carries the prose; the images it marks stay in the composer. */ export function splitForNote( text: string, images: Map, ): { note: string; text: string } { const retained = new Set(); const note = text.replaceAll( new RegExp(` ?${MARKER.source}`, 'g'), (found, n) => { if (!images.has(Number(n))) return found; retained.add(marker(Number(n))); return ''; }, ); const markers = [...retained]; return { note, text: markers.join(' ') + (markers.length ? ' ' : '') }; } /** The text without one image's markers. */ export function unmark(text: string, n: number): string { return text.replaceAll(` ${marker(n)}`, '').replaceAll(marker(n), ''); } /** The text with each image marker it backs renumbered; other text is left alone. */ export function remapMarkers( text: string, images: Map, ): string { return text.replace(MARKER, (found, n) => images.has(Number(n)) ? marker(images.get(Number(n))!) : found, ); }