fix: resize now uses functional setState to avoid stale closure

The onUp handler was capturing stale widgets from the render closure,
overwriting the resize dimensions. Now uses setWidgets(current => ...)
to read latest state and apply overlap resolution correctly.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Gjermund Høsøien Wiggen
2026-06-09 13:50:03 +02:00
parent b3da204bd0
commit a2005d007e

View File

@@ -190,54 +190,45 @@ export default function DashboardPage({ params }: { params: Promise<{ id: string
);
};
const onUp = async () => {
const onUp = () => {
document.removeEventListener("mousemove", onMove);
document.removeEventListener("mouseup", onUp);
setResizingId(null);
// Resolve overlaps: push overlapping widgets out of the way
let resolved = widgets.map((w) => (w.id === widgetId ? { ...w, position: { ...w.position } } : w));
const movedIds = new Set<string>();
// Resolve overlaps using latest state via functional updater
setWidgets((current) => {
let resolved = current.map((w) => ({ ...w, position: { ...w.position } }));
// Keep pushing until no overlaps
for (let pass = 0; pass < 10; pass++) {
let hasOverlap = false;
for (let i = 0; i < resolved.length; i++) {
for (let j = i + 1; j < resolved.length; j++) {
const a = resolved[i].position;
const b = resolved[j].position;
const ax2 = a.x + a.w;
const ay2 = a.y + a.h;
const bx2 = b.x + b.w;
const by2 = b.y + b.h;
if (ax2 > b.x && a.x < bx2 && ay2 > b.y && a.y < by2) {
if (a.x + a.w > b.x && a.x < b.x + b.w && a.y + a.h > b.y && a.y < b.y + b.h) {
hasOverlap = true;
// Fix the resized widget in place, push the OTHER widget down
const toMove = widgetId === resolved[i].id ? j : i;
const movedW = resolved[toMove];
const fixedW = resolved[widgetId === resolved[i].id ? i : j];
const newY = fixedW.position.y + fixedW.position.h;
resolved[toMove] = {
...movedW,
position: { ...movedW.position, y: newY },
...resolved[toMove],
position: { ...resolved[toMove].position, y: fixedW.position.y + fixedW.position.h },
};
movedIds.add(movedW.id);
}
}
}
if (!hasOverlap) break;
}
setWidgets(resolved);
// Persist positions
// Persist changed positions
for (const w of resolved) {
const original = widgets.find((o) => o.id === w.id);
if (original && (original.position.y !== w.position.y || original.position.h !== w.position.h)) {
await updateWidget(id, w.id, { position: w.position });
const orig = current.find((o) => o.id === w.id);
if (orig && (orig.position.y !== w.position.y || orig.position.h !== w.position.h)) {
updateWidget(id, w.id, { position: w.position });
}
}
return resolved;
});
};
document.addEventListener("mousemove", onMove);