Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

measure widget heights per commit, not only on observed resizes

[._.]/ Adam Eivy7ddf734efcb6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 0c1f427a26..b5789ca83c 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,7 +2,7 @@
## Changed
-- **Dashboard widgets are sized by their content and float up into the space above them, and the "MODULE.04 // ALERTS" tabs are gone.** The grid used to lay every cell out at the row count stored in the layout, so a card with two lines in it still reserved five 80px rows and left the rest as dead space — with more of it wherever a gated widget dropped out or a hand-arranged row was uneven. Cells now measure their widget and pack in pixels: each one drops as high as it can go without landing on an already-placed cell that shares a column, which is what lets the space a short card doesn't use get reclaimed by whatever sits beneath it. Reading order (stored `y`, then `x`) still decides the packing order, so the result matches the arrangement that was saved rather than reshuffling to whatever fits best. Nothing gets clipped on the way in either — a widget taller than its declared rows used to be cut off by the cell's `overflow-hidden`, and now grows.
+- **Dashboard widgets are sized by their content and float up into the space above them, and the "MODULE.04 // ALERTS" tabs are gone.** The grid used to lay every cell out at the row count stored in the layout, so a card with two lines in it still reserved five 80px rows and left the rest as dead space — with more of it wherever a gated widget dropped out or a hand-arranged row was uneven. Cells now measure their widget and pack in pixels: each one drops as high as it can go without landing on an already-placed cell that shares a column, which is what lets the space a short card doesn't use get reclaimed by whatever sits beneath it. Reading order (stored `y`, then `x`) still decides the packing order, so the result matches the arrangement that was saved rather than reshuffling to whatever fits best. Nothing gets clipped on the way in either — a widget taller than its declared rows used to be cut off by the cell's `overflow-hidden`, and now grows. A widget that renders *nothing* (several self-hide on empty data without carrying a `gate`, so a fresh install hits this as the normal state) now takes up nothing rather than reserving its declared slot — a measured 0 is a real height, distinct from "hasn't measured yet," which is the difference the cell keys on. Arrange mode floors those to a grabbable 48px so the handles have somewhere to sit.
Heights are still adjustable, they're just opt-in: dragging the ↘ handle's vertical axis pins that cell (`fixedH: true` on the grid item), and a ⌃⌄ handle appears on pinned cells in Arrange mode to hand the height back to the content. Stored `h` survives as the first-paint fallback and is refreshed from the measurement on every commit, which is also what a client too old to know about `fixedH` renders from — an install that hasn't updated yet reads a layout saved by one that has and lays it out close to right. The drag math moved into the pack's coordinate space along with it, because once heights are measured, stored `y` describes an ordering and not a position: reasoning in stored rows would have moved the cursor and the card at different speeds.
diff --git a/PLAN.md b/PLAN.md
index 54e4172449..72a309b336 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -342,3 +342,7 @@ is not reliably announced.
### Make LayoutEditor's Move up/down buttons actually move a widget
- [ ] `client/src/components/dashboard/LayoutEditor.jsx:97` (`move`) reorders the layout's `widgets` array, but `Dashboard.jsx#saveLayout` persists the grid via `reconcileGrid(baseGrid, widgets)`, which iterates the **grid** and uses `widgets` only for membership — and the renderer reads the grid. So once a layout has a `grid` (every layout, after the first Arrange or the `synthesizeGrid` fallback is saved), those buttons produce no visible change at all. The component's own header calls itself a "keyboard-first editor… reorder uses up/down buttons," so this is a control advertising a capability it lost. The mobile reorder handle now edits the same underlying order through `reflowToOrder`, which makes the contradiction user-facing: two reorder affordances for the same widgets, one inert. Fix: have `saveLayout` reflow the grid when the incoming `widgets` order differs from `readingOrderIds(existing.grid)` (both exported from `DashboardGrid.jsx` already). The reason this was NOT rolled into the mobile-drag change: layouts arranged before `saveGridEdit` started syncing `widgets` to reading order can have the two already out of sync, so a naive "orders differ → reflow" would re-pack a carefully arranged desktop layout the first time someone renames it or toggles a widget. Needs either a one-shot migration that stamps `widgets = readingOrderIds(grid)` onto every stored layout (`server/services/dashboardLayouts.js`, `scripts/migrations/`) before the comparison goes live, or a reorder signal from LayoutEditor that says "this save is a reorder" instead of inferring it. Surfaced by the /simplify altitude review.
+
+### Collapse the dashboard grid's two coordinate systems into one
+
+- [ ] Since widget cells became content-measured (`packVertically` in `client/src/components/dashboard/DashboardGrid.jsx`), `y` and `h` carry two contradictory jobs. The renderer packs in PIXELS and treats `y` as reading order only; but `placeAndCompact` still resolves rectangle collisions on `{x,y,w,h}`, `reflowToOrder` still tracks `rowMaxH`, and `GRID_ROW_MAX` still clamps `y` as a position. `toPackSpace` exists purely to reconcile the two, so every gesture round-trips pixels → rows → compact → rows to keep them agreeing. Not a correctness bug — the round-trip is what makes them agree — but anyone touching drag has to hold both models at once, which is why `toPackSpace` needs a six-line comment to justify itself. **The call to make:** demote the persisted shape to `{ id, x, w, order, h?, fixedH? }`, delete `overlaps` + the y-compaction entirely, and let the pack own vertical placement outright. Keep `h` as the first-paint/older-client fallback (that compatibility story is the reason it survives at all — see the `fixedH` note in the dashboard CLAUDE.md). Blocked on nothing technical; it needs a migration in `scripts/migrations/` that rewrites each stored layout's grid to the new shape (`data/dashboard-layouts.json`, plus the seven `DEFAULT_LAYOUTS`/`INTENT_LAYOUTS` grids in `server/services/dashboardLayouts.js`) and a version-gated read so an install that has not upgraded still gets usable geometry. Surfaced by the /simplify altitude review.
diff --git a/client/src/components/dashboard/CLAUDE.md b/client/src/components/dashboard/CLAUDE.md
index b2f4a84b0c..2514459086 100644
--- a/client/src/components/dashboard/CLAUDE.md
+++ b/client/src/components/dashboard/CLAUDE.md
@@ -4,7 +4,7 @@ Dashboard widgets are registered in `widgetRegistry.jsx` — each entry has `{ i
**Grid positions:** layouts also carry a `grid: [{ id, x, y, w, h, fixedH? }]` array — free-form positions on a 12-column grid (rows ~80px each). When `grid` is empty (legacy/unmigrated layouts) the renderer auto-flows widgets using `synthesizeGrid` based on each widget's `width` keyword and `defaultH`. The "Arrange" button on the Dashboard enters edit mode where every widget exposes a move (top-right) and resize (bottom-right) handle; drag is snap-to-grid with collision-resolve via `placeAndCompact` (pins the moved item, slots others into the smallest non-colliding y). Save persists to the active layout's `grid`. The grid renderer collapses to a single-column stack below 640px container width, rendered in reading order (`y`, then `x`) — never grid-array order, which `placeAndCompact` deliberately scrambles by hoisting the moved item to the front.
-**Height is measured, not declared.** `h` is NOT the rendered height. A cell measures its widget's natural height with a `ResizeObserver` and `packVertically` positions everything in pixels — each cell floats up to just below the nearest already-placed cell that shares a column. That's what stops an 80px card from reserving a 400px slot and leaving a band of dead whitespace across the row. `h` survives as the pre-measurement fallback (first paint) and as what an older client — which knows nothing about `fixedH` — reads out of a saved layout, so every drag commit refreshes it from the measurement via `toGridUnits`. A cell whose height the user actually dragged carries `fixedH: true` and keeps `h` exactly, clipping content the way the whole grid used to; the ⌃⌄ handle (edit mode, pinned cells only) hands the height back to the content. Stored `y` no longer sets the pixel offset — it only decides reading order, which is also the packing order, which is why the visual result still matches the arrangement the user saved. `defaultH` in the registry is likewise only a first-paint ballpark.
+**Height is measured, not declared.** `h` is NOT the rendered height. A cell measures its widget's natural height with a `ResizeObserver` and `packVertically` positions everything in pixels — each cell floats up to just below the nearest already-placed cell that shares a column. That's what stops an 80px card from reserving a 400px slot and leaving a band of dead whitespace across the row. `h` survives as the pre-measurement fallback (first paint) and as what an older client — which knows nothing about `fixedH` — reads out of a saved layout, so every drag commit refreshes it from the measurement via `toPackSpace`. A cell whose height the user actually dragged carries `fixedH: true` and keeps `h` exactly, clipping content the way the whole grid used to; the ⌃⌄ handle (edit mode, pinned cells only) hands the height back to the content. Stored `y` no longer sets the pixel offset — it only decides reading order, which is also the packing order, which is why the visual result still matches the arrangement the user saved. `defaultH` in the registry is likewise only a first-paint ballpark.
**Mobile editing.** Free-form move/resize is desktop-only (a phone has no room for positional editing), but *reordering* works on mobile: edit mode swaps the two grid handles for a single reorder handle. The 1-D sort goes through **`@dnd-kit/sortable`** — the same `PointerSensor` + `KeyboardSensor` + `verticalListSortingStrategy` pairing as `cos/tabs/TasksTab.jsx` and `universeBuilder/InfluenceChipsInput.jsx` — which is what supplies touch, keyboard (space to lift, arrows to move), multi-pointer safety, screen-reader announcements and edge auto-scroll. **Do not hand-roll a pointer gesture for this**; the free-form 2-D drag stays hand-rolled only because arbitrary grid placement is not what a sortable list does. Use `dndTransformToCss` from `client/src/lib/dndTransform.js` in the style object, never `@dnd-kit/utilities`.
diff --git a/client/src/components/dashboard/DashboardGrid.jsx b/client/src/components/dashboard/DashboardGrid.jsx
index 07449a8556..0d09e0cfc7 100644
--- a/client/src/components/dashboard/DashboardGrid.jsx
+++ b/client/src/components/dashboard/DashboardGrid.jsx
@@ -1,4 +1,4 @@
-import { useState, useRef, useEffect, useMemo, useCallback, memo } from 'react';
+import { useState, useRef, useEffect, useLayoutEffect, useMemo, useCallback, memo } from 'react';
import { GripVertical, MoveDiagonal2, GripHorizontal, ChevronsDownUp } from 'lucide-react';
import {
DndContext,
@@ -44,10 +44,12 @@ import { dndTransformToCss } from '../../lib/dndTransform';
// result always matches the order the user arranged.
//
// In edit mode each item exposes a top-right move handle and a bottom-right
-// resize handle. Pointer events power both so the same handlers work for
-// mouse and touch. Pointer capture isn't used because the drag math reads
-// window-level coordinates regardless of which element the pointer crosses
-// — the listener lives on `window` for the duration of the gesture.
+// resize handle — plus, on a cell that's already pinned, a bottom-left
+// auto-fit handle that hands the height back to the content. Pointer events
+// power the two drags so the same handlers work for mouse and touch. Pointer
+// capture isn't used because the drag math reads window-level coordinates
+// regardless of which element the pointer crosses — the listener lives on
+// `window` for the duration of the gesture.
//
// Below MOBILE_BREAKPOINT_PX the grid collapses to a single column, so x/w
// have nowhere to go — but ORDER still does. There, edit mode swaps the two
@@ -59,16 +61,25 @@ import { dndTransformToCss } from '../../lib/dndTransform';
// but the 1-D case is exactly dnd-kit's job, and going through it is what
// buys touch, keyboard, multi-pointer and edge auto-scroll for free.
//
-// Collision policy after drag/resize: pin the moved item at its dropped
-// position, then slot every other item into the smallest y that doesn't
-// collide with anything already placed (top-left items processed first).
-// Tetris-style compaction — same feel as react-grid-layout / gridstack.
+// Collision policy after drag/resize (`placeAndCompact`): pin the moved item
+// at its dropped position, then slot every other item into the smallest y that
+// doesn't collide with anything already placed (top-left items processed
+// first). Tetris-style compaction — same feel as react-grid-layout /
+// gridstack. This runs in GRID UNITS and settles what gets persisted; the
+// pixel pack above is what actually gets drawn. The two agree because a
+// commit first re-expresses the layout in pack space (`toPackSpace`), so the
+// y/h it compacts are the ones the pack produced.
const ROW_HEIGHT_PX = 80;
const GAP_PX = 16;
const ROW_STEP_PX = ROW_HEIGHT_PX + GAP_PX;
const MIN_W = 2;
const MIN_H = 2;
+// Floor applied to every cell in edit mode only. A widget that renders nothing
+// collapses to zero out of view — which is the point — but a zero-height cell
+// has nowhere to put the move/resize handles, so Arrange gives it enough room
+// to grab.
+const EDIT_MIN_HEIGHT_PX = 48;
// Mobile breakpoint: below this width the grid collapses to a single column
// stacked vertically. Free-form move/resize is off there — a phone has no
// room for positional editing — but drag-to-reorder is on (see above).
@@ -103,17 +114,23 @@ export function pxToRows(px) {
// tall as they measured; `fixedH` cells keep the height the user dragged onto
// them. `h` is the fallback until the first measurement lands — which is also
// why every commit refreshes it (see `toPackSpace`).
+//
+// Keyed on PRESENCE, not truthiness: a widget that renders nothing (several
+// self-hide on empty data) measures a legitimate 0, and collapsing that into
+// "not measured yet" would hand it back the whole declared slot — the exact
+// dead band this grid exists to reclaim, in the one case where the reclaim is
+// total.
export function itemHeightPx(item, heights = {}) {
- if (!item.fixedH) {
- const measured = heights[item.id];
- if (measured > 0) return measured;
- }
+ if (!item.fixedH && item.id in heights) return heights[item.id];
return rowsToPx(item.h);
}
function shareColumns(a, b) {
return !(a.x + a.w <= b.x || b.x + b.w <= a.x);
}
+function shareRows(a, b) {
+ return !(a.y + a.h <= b.y || b.y + b.h <= a.y);
+}
// Masonry float. Walk cells in reading order and drop each one as high as it
// will go without landing on an already-placed cell that shares a column.
@@ -124,11 +141,13 @@ function shareColumns(a, b) {
// through the gap instead of leaving a band of dead space across the row.
// Reading order (not grid-array order) is what keeps the result stable — the
// caller must pass items already sorted by `byReadingOrder`.
-export function packVertically(ordered, heights = {}) {
+// `minHeight` floors every cell — passed in edit mode so a widget that
+// currently renders nothing still has something to grab the handles on.
+export function packVertically(ordered, heights = {}, minHeight = 0) {
const placed = [];
const rects = new Map();
for (const item of ordered) {
- const height = itemHeightPx(item, heights);
+ const height = Math.max(minHeight, itemHeightPx(item, heights));
let top = 0;
for (const p of placed) {
if (!shareColumns(item, p)) continue;
@@ -165,7 +184,7 @@ function toPackSpace(items, rects) {
}
function overlaps(a, b) {
- return !(a.x + a.w <= b.x || b.x + b.w <= a.x || a.y + a.h <= b.y || b.y + b.h <= a.y);
+ return shareColumns(a, b) && shareRows(a, b);
}
function sameRect(a, b) {
@@ -325,34 +344,55 @@ const GridCell = memo(function GridCell({
disabled: !sortable,
});
const measureRef = useRef(null);
- const pinned = Boolean(item.fixedH);
- // Report the widget's natural height so the parent can pack around it. The
- // measured node is INSIDE the clipping wrapper, so a pinned cell still
- // reports the size its content wants — it just gets clipped to `height`.
- // Off on mobile: the single-column stack measures at a totally different
- // width, and those numbers would be wrong for the desktop pack.
+ // Report the widget's natural height so the parent can pack around it.
+ // Skipped when:
+ // - mobile, where the single-column stack measures at a totally different
+ // width and those numbers would be wrong for the desktop pack;
+ // - pinned, where the measured node is stretched to the declared height, so
+ // all it could publish is that height back — and the pack would then spend
+ // the frame after an unpin laying the cell out at its clipped size.
+ // Skipping leaves the last natural height in place, which is a far better
+ // starting guess.
+ // Post-commit measurement, pre-paint. This is the AUTHORITATIVE one: it
+ // catches whatever React just put in the cell — a lazy chunk resolving out
+ // of Suspense, a list arriving — without depending on the observer having
+ // noticed. Relying on the observer alone made this racy: a widget whose
+ // content landed without a delivered resize notification kept whatever it
+ // measured while it was still a skeleton, so it packed (and clipped) at the
+ // wrong height. No dep array — every render of this cell re-measures, and
+ // `onMeasure` bails on an unchanged value, so a settled cell costs one read
+ // and one comparison.
+ useLayoutEffect(() => {
+ const node = measureRef.current;
+ if (node && !isMobile && !item.fixedH) onMeasure(item.id, node.offsetHeight);
+ });
+
+ // The observer covers what the commit pass can't see: growth with no render
+ // of this cell at all — images and fonts loading, a widget's own async DOM
+ // work, or a state change inside the memoized widget subtree.
+ //
+ // Published straight from the callback, same as `useContainerWidth`. There
+ // is no feedback loop to defer around: the measured node's height comes from
+ // its content, never from the cell height this publish goes on to set. An
+ // rAF here is not just unnecessary, it's harmful — a frame in which the
+ // pack is still using the old height is a frame in which this cell is drawn
+ // shorter than its content and the one below it sits on top.
useEffect(() => {
const node = measureRef.current;
- if (!node || isMobile) return undefined;
- let raf = 0;
- const ro = new ResizeObserver((entries) => {
- if (!Number.isFinite(entries[0]?.contentRect?.height)) return;
- // Defer out of the observer callback: publishing a height re-packs every
- // cell below this one, and mutating layout synchronously from inside the
- // callback is what trips the "ResizeObserver loop" warning.
- if (raf) return;
- raf = requestAnimationFrame(() => {
- raf = 0;
- onMeasure(item.id, Math.ceil(node.offsetHeight));
- });
- });
+ if (!node || isMobile || item.fixedH) return undefined;
+ // 0 is published like any other height — a widget that renders nothing
+ // should occupy nothing. `itemHeightPx` keys on presence, so this is what
+ // tells it apart from "not measured yet".
+ const ro = new ResizeObserver(() => onMeasure(item.id, node.offsetHeight));
ro.observe(node);
- return () => {
- ro.disconnect();
- if (raf) cancelAnimationFrame(raf);
- };
- }, [isMobile, item.id, onMeasure]);
+ return () => ro.disconnect();
+ }, [isMobile, item.fixedH, item.id, onMeasure]);
+
+ // Memoized so a cell that merely MOVED doesn't re-render its widget: every
+ // measurement anywhere in the grid repacks, and without this each repack
+ // would re-render the whole subtree of every cell it shifted.
+ const content = useMemo(() => renderItem(item), [renderItem, item]);
// The cell is ALWAYS laid out at exactly the height the pack gave it, even
// when that height is auto-derived. Letting an auto cell size itself would
@@ -379,13 +419,13 @@ const GridCell = memo(function GridCell({
one case where the declared height is the answer. `flow-root` keeps
a widget root's margin from collapsing out of the measurement. */}
<div ref={measureRef} className={autoHeight ? 'flow-root' : 'h-full flow-root'}>
- {renderItem(item)}
+ {content}
</div>
{editable && !isMobile && (
<>
<DragHandle kind="move" item={item} onPointerDown={(e) => onStartGridDrag(e, item, 'move')} />
<DragHandle kind="resize" item={item} onPointerDown={(e) => onStartGridDrag(e, item, 'resize')} />
- {pinned && (
+ {item.fixedH && (
<DragHandle kind="auto-height" item={item} onClick={() => onClearFixedHeight(item)} />
)}
</>
@@ -402,14 +442,16 @@ export default function DashboardGrid({ items, editable, onChange, onLayoutModeC
const [containerRef, containerWidth] = useContainerWidth();
// Drag state lives outside React when active to avoid a setState on every
// pointermove (would spam re-renders of every widget). React only learns
- // about the new ghost when we call setDragGhost, throttled by RAF.
+ // about the new ghost when we call setDrag, throttled by RAF.
+ //
+ // `drag` is `{ kind, baseline, ghost }`. `baseline` is the layout as it
+ // stood when the gesture started, in pack space (see `toPackSpace`):
+ // everything the drag reasons about — the ghost, the live preview, the
+ // committed grid — is relative to it, not to the stored coordinates, which
+ // no longer describe where anything is drawn. `ghost` stays a plain grid
+ // item so the commit can spread it straight onto one.
const dragRef = useRef(null);
- const [dragGhost, setDragGhost] = useState(null);
- // The layout as it stood when the gesture started, in pack space (see
- // `toPackSpace`). Everything the drag reasons about — the ghost, the live
- // preview, the committed grid — is relative to this, not to the stored
- // coordinates, which no longer describe where anything is drawn.
- const [dragBaseline, setDragBaseline] = useState(null);
+ const [drag, setDrag] = useState(null);
// Measured natural heights, px, keyed by widget id.
const [heights, setHeights] = useState({});
@@ -437,17 +479,17 @@ export default function DashboardGrid({ items, editable, onChange, onLayoutModeC
// as a pinned cell — the drag is defining a height, so the preview must
// show that height and not the content's.
const previewItems = useMemo(() => {
- if (!dragGhost || !dragBaseline) return ordered;
- return dragBaseline
- .map((it) => (it.id === dragGhost.id
- ? { ...it, ...dragGhost, ...(dragGhost.kind === 'resize' ? { fixedH: true } : {}) }
+ if (!drag) return ordered;
+ return drag.baseline
+ .map((it) => (it.id === drag.ghost.id
+ ? { ...it, ...drag.ghost, ...(drag.kind === 'resize' ? { fixedH: true } : {}) }
: it))
.sort(byReadingOrder);
- }, [ordered, dragBaseline, dragGhost]);
+ }, [ordered, drag]);
const rects = useMemo(
- () => (isMobile ? new Map() : packVertically(previewItems, heights)),
- [isMobile, previewItems, heights]
+ () => (isMobile ? new Map() : packVertically(previewItems, heights, editable ? EDIT_MIN_HEIGHT_PX : 0)),
+ [isMobile, previewItems, heights, editable]
);
// Read by the drag handlers, which must not re-bind every time a widget
// re-measures (that would churn every memoized cell mid-gesture).
@@ -465,7 +507,9 @@ export default function DashboardGrid({ items, editable, onChange, onLayoutModeC
// load open with a 150ms shuffle. Cells snap into place instead, and the
// transition switches on for genuine edits afterwards.
const settled = useMemo(
- () => ordered.every((it) => it.fixedH || heights[it.id] > 0),
+ // Presence again, not truthiness — a legitimately 0-tall widget has
+ // reported, and gating on `> 0` would latch the transition off forever.
+ () => ordered.every((it) => it.fixedH || it.id in heights),
[ordered, heights]
);
@@ -480,73 +524,80 @@ export default function DashboardGrid({ items, editable, onChange, onLayoutModeC
// drawn — grabbing the resize handle on an auto-height cell would
// otherwise snap it to a stale row count before the pointer has moved.
const baseline = toPackSpace(items, rectsRef.current);
- const startItem = { ...(baseline.find((it) => it.id === item.id) ?? item), kind };
+ const found = baseline.find((it) => it.id === item.id) ?? item;
+ // A resize gesture's floor applies to where the drag STARTS too. Without
+ // it, a cell measuring under MIN_H rows (a widget rendering little or
+ // nothing) has its height "changed" by the clamp alone — so a purely
+ // horizontal drag would silently pin it.
+ const startItem = kind === 'resize' ? { ...found, h: Math.max(MIN_H, found.h) } : found;
dragRef.current = {
id: item.id,
kind,
startPointer: { x: e.clientX, y: e.clientY },
startItem,
ghost: { ...startItem },
- baseline,
};
- setDragBaseline(baseline);
- setDragGhost({ ...startItem });
+ setDrag({ kind, baseline, ghost: { ...startItem } });
}, [editable, isMobile, items]);
useEffect(() => {
- if (!dragGhost) return undefined;
+ if (!drag) return undefined;
const colWidth = getColWidth(containerWidth);
+ // Both are fixed for the life of the gesture, and this effect re-installs
+ // exactly when one starts — so capturing them here can't go stale, and the
+ // per-snap `setDrag` doesn't have to re-bind the window listeners.
+ const { kind, baseline } = drag;
let raf = 0;
const onPointerMove = (e) => {
- const drag = dragRef.current;
- if (!drag) return;
- const dx = e.clientX - drag.startPointer.x;
- const dy = e.clientY - drag.startPointer.y;
+ const gesture = dragRef.current;
+ if (!gesture) return;
+ const dx = e.clientX - gesture.startPointer.x;
+ const dy = e.clientY - gesture.startPointer.y;
const colStep = colWidth + GAP_PX;
- const rowStep = ROW_HEIGHT_PX + GAP_PX;
+ const start = gesture.startItem;
let next;
- if (drag.kind === 'move') {
- const newX = Math.max(0, Math.min(GRID_COLS - drag.startItem.w, Math.round(drag.startItem.x + dx / colStep)));
- const newY = Math.max(0, Math.round(drag.startItem.y + dy / rowStep));
- next = { ...drag.startItem, x: newX, y: newY };
+ if (kind === 'move') {
+ const newX = Math.max(0, Math.min(GRID_COLS - start.w, Math.round(start.x + dx / colStep)));
+ const newY = Math.max(0, Math.round(start.y + dy / ROW_STEP_PX));
+ next = { ...start, x: newX, y: newY };
} else {
- const newW = Math.max(MIN_W, Math.min(GRID_COLS - drag.startItem.x, Math.round(drag.startItem.w + dx / colStep)));
- const newH = Math.max(MIN_H, Math.round(drag.startItem.h + dy / rowStep));
- next = { ...drag.startItem, w: newW, h: newH };
+ const newW = Math.max(MIN_W, Math.min(GRID_COLS - start.x, Math.round(start.w + dx / colStep)));
+ const newH = Math.max(MIN_H, Math.round(start.h + dy / ROW_STEP_PX));
+ next = { ...start, w: newW, h: newH };
}
// Snap dedup: pointermove fires at 200+ Hz, but `next` only changes
// when the cursor crosses a snap boundary. Skip the React update
// when we're still inside the same snap cell — saves ~60 widget
// re-renders per drag and keeps the rAF callback a no-op.
- if (sameRect(drag.ghost, next)) return;
- drag.ghost = next;
+ if (sameRect(gesture.ghost, next)) return;
+ gesture.ghost = next;
if (!raf) {
raf = requestAnimationFrame(() => {
raf = 0;
- if (dragRef.current) setDragGhost({ ...dragRef.current.ghost });
+ const ghost = dragRef.current?.ghost;
+ if (ghost) setDrag((prev) => (prev ? { ...prev, ghost: { ...ghost } } : prev));
});
}
};
const finish = (commit) => {
if (raf) { cancelAnimationFrame(raf); raf = 0; }
- const drag = dragRef.current;
+ const gesture = dragRef.current;
dragRef.current = null;
- setDragGhost(null);
- setDragBaseline(null);
- if (!drag || !commit) return;
+ setDrag(null);
+ if (!gesture || !commit) return;
// Skip the write entirely when nothing actually changed — avoids a
// 200 OK on every accidental click on the drag handle.
- if (sameRect(drag.startItem, drag.ghost)) return;
+ if (sameRect(gesture.startItem, gesture.ghost)) return;
// A resize that actually changed the HEIGHT is the user declaring one:
// pin it. A width-only resize (or a move) leaves the cell auto-sized.
- const pins = drag.kind === 'resize' && drag.ghost.h !== drag.startItem.h;
- const updated = drag.baseline.map((it) => (it.id === drag.id
- ? { ...it, x: drag.ghost.x, y: drag.ghost.y, w: drag.ghost.w, h: drag.ghost.h, ...(pins ? { fixedH: true } : {}) }
+ const pins = kind === 'resize' && gesture.ghost.h !== gesture.startItem.h;
+ const updated = baseline.map((it) => (it.id === gesture.id
+ ? { ...it, ...gesture.ghost, ...(pins ? { fixedH: true } : {}) }
: it));
- onChange(placeAndCompact(updated, drag.id));
+ onChange(placeAndCompact(updated, gesture.id));
};
const onPointerUp = () => finish(true);
@@ -564,9 +615,10 @@ export default function DashboardGrid({ items, editable, onChange, onLayoutModeC
window.removeEventListener('pointercancel', onPointerCancel);
if (raf) cancelAnimationFrame(raf);
};
- // dragGhost in the deps array re-installs the listeners only when the
- // gesture starts/ends — pointermove updates dragRef.current directly.
- }, [dragGhost ? 'active' : 'idle', onChange, containerWidth]);
+ // The active/idle key re-installs the listeners only when the gesture
+ // starts/ends, never on a snap — pointermove writes dragRef.current
+ // directly, and the `kind`/`baseline` captured above are gesture-constant.
+ }, [drag ? 'active' : 'idle', onChange, containerWidth]);
// A short activation distance keeps a tap on the handle from registering as
// a drag; the keyboard sensor is what makes the handle usable without one.
@@ -587,8 +639,13 @@ export default function DashboardGrid({ items, editable, onChange, onLayoutModeC
// unconstrained, the observer reports its natural height, and the pack
// closes the gap on the next frame.
const clearFixedHeight = useCallback((item) => {
- const next = toPackSpace(items, rectsRef.current)
- .map((it) => (it.id === item.id ? { id: it.id, x: it.x, y: it.y, w: it.w, h: it.h } : it));
+ const next = toPackSpace(items, rectsRef.current).map((it) => {
+ if (it.id !== item.id) return it;
+ // Drop the pin by omission rather than whitelisting the fields to keep,
+ // so a field added to the grid item later doesn't get eaten here.
+ const { fixedH: _pinned, ...rest } = it;
+ return rest;
+ });
onChange(placeAndCompact(next, item.id));
}, [items, onChange]);
@@ -615,12 +672,13 @@ export default function DashboardGrid({ items, editable, onChange, onLayoutModeC
style={isMobile ? undefined : { height: containerWidth ? containerHeight : 'auto', minHeight: '4rem' }}
>
{ordered.map((item) => {
+ const dragged = drag?.ghost.id === item.id;
const rect = rects.get(item.id);
- const { left, width } = columnRect(dragGhost?.id === item.id ? { ...item, ...dragGhost } : item, colWidth);
+ const { left, width } = columnRect(dragged ? drag.ghost : item, colWidth);
// A cell's height comes from its content unless it is pinned OR is
// the one currently being resized (where the drag, not the content,
// is defining the height).
- const pinned = item.fixedH || (dragGhost?.id === item.id && dragGhost.kind === 'resize');
+ const pinned = item.fixedH || (dragged && drag.kind === 'resize');
return (
<GridCell
key={item.id}
@@ -633,8 +691,8 @@ export default function DashboardGrid({ items, editable, onChange, onLayoutModeC
width={width}
height={rect?.height ?? rowsToPx(item.h)}
autoHeight={!pinned}
- isGridDragging={!isMobile && dragGhost?.id === item.id}
- suppressTransition={Boolean(dragGhost) || !settled}
+ isGridDragging={!isMobile && dragged}
+ suppressTransition={Boolean(drag) || !settled}
onStartGridDrag={startDrag}
onClearFixedHeight={clearFixedHeight}
onMeasure={onMeasure}
@@ -646,10 +704,10 @@ export default function DashboardGrid({ items, editable, onChange, onLayoutModeC
{/* Drop preview during the free-form drag — outline over the packed
position the item will actually land in. Pointer-events:none so
it never intercepts the gesture. */}
- {!isMobile && dragGhost && containerWidth > 0 && rects.has(dragGhost.id) && (
+ {!isMobile && drag && containerWidth > 0 && rects.has(drag.ghost.id) && (
<div
className="absolute pointer-events-none border-2 border-dashed border-port-accent rounded-xl bg-port-accent/10 z-30"
- style={{ ...columnRect(dragGhost, colWidth), ...rects.get(dragGhost.id) }}
+ style={{ ...columnRect(drag.ghost, colWidth), ...rects.get(drag.ghost.id) }}
/>
)}
</div>
diff --git a/client/src/components/dashboard/DashboardGrid.test.jsx b/client/src/components/dashboard/DashboardGrid.test.jsx
index 7a83dbe8bc..0ab3f2e389 100644
--- a/client/src/components/dashboard/DashboardGrid.test.jsx
+++ b/client/src/components/dashboard/DashboardGrid.test.jsx
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
// Stub @dnd-kit/core's DndContext so drag-end can be fired imperatively. The
@@ -57,11 +57,25 @@ class FakeResizeObserver {
disconnect() {}
}
+// jsdom does no layout, so every element reports offsetHeight 0 — and the grid
+// now believes that ("renders nothing, so occupy nothing"). Give cells a
+// height so the packing assertions below exercise the measured path instead of
+// a collapsed one.
+const MEASURED_PX = 100;
+
beforeEach(() => {
vi.stubGlobal('ResizeObserver', FakeResizeObserver);
+ Object.defineProperty(HTMLElement.prototype, 'offsetHeight', {
+ configurable: true,
+ get() { return MEASURED_PX; },
+ });
dndState.onDragEnd = null;
});
+afterEach(() => {
+ delete HTMLElement.prototype.offsetHeight;
+});
+
const THREE = [
{ id: 'a', x: 0, y: 0, w: 12, h: 2 },
{ id: 'b', x: 0, y: 2, w: 12, h: 2 },
@@ -139,8 +153,14 @@ describe('itemHeightPx', () => {
it('falls back to the declared rows until a measurement lands', () => {
expect(itemHeightPx(item, {})).toBe(rowsToPx(4));
- // A zero measurement means "not painted yet", not "zero tall".
- expect(itemHeightPx(item, { a: 0 })).toBe(rowsToPx(4));
+ });
+
+ // Several widgets render nothing on empty data. Treating that 0 as "not
+ // measured yet" would hand the widget back its whole declared slot — the
+ // dead band this grid exists to reclaim, in the case where the reclaim is
+ // total. So the sentinel is presence, not truthiness.
+ it('honors a measured zero instead of reading it as "not measured yet"', () => {
+ expect(itemHeightPx(item, { a: 0 })).toBe(0);
});
it('ignores the measurement for a cell whose height the user pinned', () => {
@@ -175,6 +195,25 @@ describe('packVertically', () => {
expect(rects.get('under').top).toBe(116);
});
+ it('lets a widget that renders nothing occupy nothing, and closes over it', () => {
+ const rects = packVertically([
+ { id: 'empty', x: 0, y: 0, w: 12, h: 5 },
+ { id: 'below', x: 0, y: 5, w: 12, h: 2 },
+ ], { empty: 0, below: 100 });
+ expect(rects.get('empty').height).toBe(0);
+ expect(rects.get('below').top).toBe(16);
+ });
+
+ it('floors cells to a grabbable height when edit mode asks for one', () => {
+ const rects = packVertically(
+ [{ id: 'empty', x: 0, y: 0, w: 12, h: 5 }, { id: 'below', x: 0, y: 5, w: 12, h: 2 }],
+ { empty: 0, below: 100 },
+ 48
+ );
+ expect(rects.get('empty').height).toBe(48);
+ expect(rects.get('below').top).toBe(64);
+ });
+
it('clears every cell it overlaps, not just the last one placed', () => {
const rects = packVertically([
{ id: 'a', x: 0, y: 0, w: 4, h: 2 },
@@ -274,11 +313,13 @@ describe('DashboardGrid cell sizing', () => {
// Every cell is laid out at exactly the height the pack assigned it — an
// auto cell that sized itself would overlap its neighbours for every frame
// its content was taller than the last measurement.
- it('lays every cell out at its packed height, and stacks from the pack', () => {
+ it('lays every cell out at its MEASURED height, not its declared rows', () => {
+ // All three declare h:2 (176px) but measure 100px.
renderGrid();
- expect(cellFor('a').style.height).toBe(`${rowsToPx(2)}px`);
+ expect(cellFor('a').style.height).toBe(`${MEASURED_PX}px`);
expect(cellFor('a').style.top).toBe('0px');
- expect(cellFor('b').style.top).toBe(`${rowsToPx(2) + 16}px`);
+ expect(cellFor('b').style.top).toBe(`${MEASURED_PX + 16}px`);
+ expect(cellFor('c').style.top).toBe(`${(MEASURED_PX + 16) * 2}px`);
});
it('measures the widget free of the cell height, and stretches it when pinned', () => {
diff --git a/client/src/components/micrographics/micrographics.css b/client/src/components/micrographics/micrographics.css
index 93d01deba9..6eadefcb8a 100644
--- a/client/src/components/micrographics/micrographics.css
+++ b/client/src/components/micrographics/micrographics.css
@@ -78,11 +78,14 @@
.port-schematic-label--muted { color: rgb(var(--port-border)); opacity: 0.85; }
/* Card-tab variant: sits like a blueprint tab on the card's top border.
- The host needs `position: relative` plus enough top padding/space that
- the tab isn't clipped by an `overflow: hidden` ancestor (e.g. the
- dashboard grid wraps each widget in a clipped container). The tab is
- anchored INSIDE the host so it can't escape; the card's own border
- line is masked by the tab's own background where they overlap. */
+ The host needs `position: relative` plus enough top padding/space that the
+ tab isn't clipped by an `overflow: hidden` ancestor — the reason the host
+ has to reserve a header strip, and the reason the dashboard grid stopped
+ using this variant (that strip is fixed dead space in the one dimension
+ its cells now size to content). Live hosts are the Chief of Staff task
+ lists. The tab is anchored INSIDE the host so it can't escape; the card's
+ own border line is masked by the tab's own background where they
+ overlap. */
.port-schematic-label--tab {
position: absolute;
top: 0.35rem;
diff --git a/server/services/dashboardLayouts.js b/server/services/dashboardLayouts.js
index adecafa5dd..9c3e459b66 100644
--- a/server/services/dashboardLayouts.js
+++ b/server/services/dashboardLayouts.js
@@ -27,10 +27,13 @@ const makeErr = (message, code) => Object.assign(new Error(message), { code });
// see client/src/components/dashboard/widgetRegistry.jsx. If a layout refers
// to an unknown id, the client skips it gracefully.
// Built-in layouts ship with a `grid` so they look right out-of-the-box
-// instead of falling back to the client's row-flow synthesis. The grids
-// are designed for a typical desktop viewport (12 cols × ~80px rows): the
-// most useful widgets sit in rows 0–7 (~768px) so they're above the fold
-// without scrolling, and lower-priority widgets stack below.
+// instead of falling back to the client's row-flow synthesis. `x`/`w` are
+// real: they place the widget in the 12 columns. `y` decides reading order —
+// and therefore the order the client packs in — while `h` is only the
+// first-paint height, because the renderer measures each widget and floats it
+// up (see client/src/components/dashboard/DashboardGrid.jsx). So order these
+// grids by what should be seen first; do NOT budget above-the-fold space by
+// counting 80px rows, the arithmetic won't hold.
// Intent-named layouts shipped post-029. Exported so the migration that
// seeds them into existing installs (scripts/migrations/030-…) imports
@@ -206,9 +209,11 @@ export const WIDGETS_MAX = 50;
export const WIDGET_ID_MAX_LENGTH = 80;
// Grid placement bounds. The dashboard is a 12-column responsive grid; rows
-// are integer steps (each ~80px tall). GRID_ROW_MAX caps total layout depth
-// so a hand-edited file can't push y to absurd values that break the
-// container-height calculation in DashboardGrid.jsx.
+// are integer steps (each ~80px tall). GRID_ROW_MAX caps total layout depth so
+// a hand-edited file can't push `y` to absurd values — the renderer sorts by
+// it, so a runaway value is a nonsense ordering rather than a nonsense
+// position, but it stays clamped for the same reason `h` does: an older
+// client still reads both as literal geometry.
export const GRID_COLS = 12;
export const GRID_ROW_MAX = 200;
export const GRID_ITEM_H_MAX = 50;
diff --git a/server/services/dashboardLayouts.test.js b/server/services/dashboardLayouts.test.js
index 6ba39ae877..271b1909e2 100644
--- a/server/services/dashboardLayouts.test.js
+++ b/server/services/dashboardLayouts.test.js
@@ -210,9 +210,12 @@ describe('dashboardLayouts service', () => {
});
describe('built-in layout grids have no overlapping cells', () => {
- // Regression: a hand-tuned grid edit can place two widgets in the same
- // rows/cols, so fresh installs render stacked cards. Every built-in
- // layout's grid rectangles must be pairwise non-overlapping.
+ // A hand-tuned grid edit can place two widgets in the same rows/cols. The
+ // renderer no longer stacks them — it packs measured heights and resolves
+ // any declared overlap — but `y` is what it sorts reading order by, so an
+ // overlap means two widgets with an arbitrary relative order that will
+ // flip on an unrelated edit. Keep every built-in's rectangles pairwise
+ // non-overlapping so the seeded order is the one that was intended.
const rectsOverlap = (a, b) =>
a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;