// Pure helpers for desktop widgets: item edits, move snapping and resizing. // Rects are {x, y, w, h} in output-local logical pixels. function newId(items) { let id; do id = "w-" + Date.now().toString(36) + "-" + Math.floor(Math.random() * 1296).toString(36); while (items.some(i => i.id === id)); return id; } function addItem(items, item) {return items.concat([item]);} function updateItem(items, id, patch) {return items.map(i => i.id === id ? Object.assign({}, i, patch) : i);} function removeItem(items, id) {return items.filter(i => i.id !== id);} function clampRect(r, bounds) { const w = Math.min(r.w, bounds.w), h = Math.min(r.h, bounds.h); return {x: Math.max(0, Math.min(bounds.w - w, r.x)), y: Math.max(0, Math.min(bounds.h - h, r.y)), w: w, h: h}; } // Snap a moved rect to the grid, or to screen edges/centre and other widgets' // edges/centres within `threshold`. Returns the rect plus guide lines to draw. function snapMove(r, others, bounds, grid, threshold) { let x = r.x, y = r.y; const guides = {x: [], y: []}; if (grid > 0) { x = Math.round(x / grid) * grid; y = Math.round(y / grid) * grid; } else { const xs = [0, bounds.w / 2, bounds.w], ys = [0, bounds.h / 2, bounds.h]; for (const o of others) { xs.push(o.x, o.x + o.w / 2, o.x + o.w); ys.push(o.y, o.y + o.h / 2, o.y + o.h); } const best = (start, size, lines) => { let found = null; for (const line of lines) for (const offset of [0, size / 2, size]) { const delta = line - (start + offset); if (Math.abs(delta) <= threshold && (!found || Math.abs(delta) < Math.abs(found.delta))) found = {delta: delta, line: line}; } return found; }; const bx = best(x, r.w, xs), by = best(y, r.h, ys); if (bx) {x += bx.delta; guides.x.push(bx.line);} if (by) {y += by.delta; guides.y.push(by.line);} } const c = clampRect({x: x, y: y, w: r.w, h: r.h}, bounds); return {x: c.x, y: c.y, w: c.w, h: c.h, guides: guides}; } // Resize from `start` by a pointer delta on the given edges ({left,right,top,bottom}), // honouring minimum/maximum sizes, the grid and the output bounds. function resizeRect(start, dx, dy, edges, limits, bounds, grid) { const snap = v => grid > 0 ? Math.round(v / grid) * grid : v; let left = start.x, top = start.y, right = start.x + start.w, bottom = start.y + start.h; if (edges.left) left = snap(Math.max(0, start.x + dx)); if (edges.right) right = snap(Math.min(bounds.w, start.x + start.w + dx)); if (edges.top) top = snap(Math.max(0, start.y + dy)); if (edges.bottom) bottom = snap(Math.min(bounds.h, start.y + start.h + dy)); const fit = (a, b, lo, hi, moveA) => { const size = Math.max(lo, Math.min(hi, b - a)); return moveA ? [b - size, b] : [a, a + size]; }; [left, right] = fit(left, right, limits.minW, limits.maxW, !!edges.left); [top, bottom] = fit(top, bottom, limits.minH, limits.maxH, !!edges.top); return clampRect({x: left, y: top, w: right - left, h: bottom - top}, bounds); }