// Small, dependency-free helpers shared across the app. export const clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v); export const lerp = (a, b, t) => a + (b - a) * t; let uidCounter = 0; export function uid(prefix = 'id') { uidCounter += 1; return `${prefix}_${Date.now().toString(36)}_${uidCounter.toString(36)}`; } /** Create an offscreen 2D canvas. */ export function createCanvas(w, h) { const c = document.createElement('canvas'); c.width = Math.max(1, Math.round(w)); c.height = Math.max(1, Math.round(h)); return c; } export function ctx2d(canvas, opts) { return canvas.getContext('2d', { willReadFrequently: false, ...opts }); } /** Duplicate a canvas (pixels and size). */ export function cloneCanvas(src) { const c = createCanvas(src.width, src.height); c.getContext('2d').drawImage(src, 0, 0); return c; } /** Copy a sub-rectangle of a canvas into a new canvas. */ export function cropCanvas(src, x, y, w, h) { const c = createCanvas(w, h); c.getContext('2d').drawImage(src, -x, -y); return c; } export function clearCanvas(canvas) { const ctx = canvas.getContext('2d'); ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = 1; ctx.globalCompositeOperation = 'source-over'; ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.restore(); } // ---- rectangles: {x, y, w, h} in integer pixels ---- export const Rect = { empty() { return null; }, fromPoints(x0, y0, x1, y1) { const x = Math.min(x0, x1), y = Math.min(y0, y1); return { x, y, w: Math.abs(x1 - x0), h: Math.abs(y1 - y0) }; }, union(a, b) { if (!a) return b ? { ...b } : null; if (!b) return { ...a }; const x = Math.min(a.x, b.x), y = Math.min(a.y, b.y); return { x, y, w: Math.max(a.x + a.w, b.x + b.w) - x, h: Math.max(a.y + a.h, b.y + b.h) - y }; }, intersect(a, b) { if (!a || !b) return null; const x = Math.max(a.x, b.x), y = Math.max(a.y, b.y); const r = Math.min(a.x + a.w, b.x + b.w), btm = Math.min(a.y + a.h, b.y + b.h); if (r <= x || btm <= y) return null; return { x, y, w: r - x, h: btm - y }; }, /** Expand to integer bounds and pad. */ outset(r, pad) { if (!r) return null; const x = Math.floor(r.x - pad), y = Math.floor(r.y - pad); return { x, y, w: Math.ceil(r.x + r.w + pad) - x, h: Math.ceil(r.y + r.h + pad) - y }; }, clampTo(r, w, h) { return Rect.intersect(r, { x: 0, y: 0, w, h }); }, }; export function debounce(fn, ms) { let t = null; return (...args) => { clearTimeout(t); t = setTimeout(() => fn(...args), ms); }; } export function downloadBlob(blob, filename) { const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 5000); } export function canvasToBlob(canvas, type = 'image/png', quality) { return new Promise((resolve, reject) => { canvas.toBlob((b) => (b ? resolve(b) : reject(new Error(`Encoding ${type} failed`))), type, quality); }); } export function loadImage(src) { return new Promise((resolve, reject) => { const img = new Image(); img.onload = () => resolve(img); img.onerror = () => reject(new Error('Could not decode image')); img.src = src; }); } export async function blobToImage(blob) { const url = URL.createObjectURL(blob); try { return await loadImage(url); } finally { setTimeout(() => URL.revokeObjectURL(url), 1000); } } export function blobToDataURL(blob) { return new Promise((resolve, reject) => { const r = new FileReader(); r.onload = () => resolve(r.result); r.onerror = () => reject(r.error); r.readAsDataURL(blob); }); } /** Prompt the user to choose file(s). Resolves to an array of File (possibly empty). */ export function pickFiles({ accept = '', multiple = false } = {}) { return new Promise((resolve) => { const input = document.createElement('input'); input.type = 'file'; input.accept = accept; input.multiple = multiple; input.style.display = 'none'; document.body.appendChild(input); input.addEventListener('change', () => { resolve(Array.from(input.files || [])); input.remove(); }); input.click(); }); } export function el(tag, attrs = {}, ...children) { const node = document.createElement(tag); for (const [k, v] of Object.entries(attrs || {})) { if (v == null || v === false) continue; if (k === 'class') node.className = v; else if (k === 'style' && typeof v === 'object') Object.assign(node.style, v); else if (k.startsWith('on') && typeof v === 'function') node.addEventListener(k.slice(2), v); else if (k === 'html') node.innerHTML = v; else if (k in node && typeof v !== 'string') node[k] = v; else node.setAttribute(k, v === true ? '' : v); } for (const c of children.flat()) { if (c == null || c === false) continue; node.appendChild(typeof c === 'string' || typeof c === 'number' ? document.createTextNode(String(c)) : c); } return node; } export function formatBytes(n) { if (n < 1024) return `${n} B`; if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`; return `${(n / 1024 / 1024).toFixed(2)} MB`; } export const isMac = /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent); /** Human readable shortcut, e.g. "Ctrl+Shift+Z" -> "⌘⇧Z" on mac. */ export function prettyShortcut(s) { if (!s) return ''; if (!isMac) return s; return s.replace(/Ctrl\+/g, '⌘').replace(/Shift\+/g, '⇧').replace(/Alt\+/g, '⌥'); } export function stripExtension(name) { return name.replace(/\.[^.]+$/, ''); } /** Bounding box of non-transparent pixels in a canvas, or null if empty. */ export function opaqueBounds(canvas, threshold = 0) { const { width: w, height: h } = canvas; const data = canvas.getContext('2d').getImageData(0, 0, w, h).data; let minX = w, minY = h, maxX = -1, maxY = -1; for (let y = 0; y < h; y++) { let row = y * w * 4 + 3; for (let x = 0; x < w; x++, row += 4) { if (data[row] > threshold) { if (x < minX) minX = x; if (x > maxX) maxX = x; if (y < minY) minY = y; if (y > maxY) maxY = y; } } } if (maxX < 0) return null; return { x: minX, y: minY, w: maxX - minX + 1, h: maxY - minY + 1 }; }