feat(dashboard): phase B drag-resize grid (Gridstack) replacing masonry
CI / lint (push) Successful in 3s
CI / unit (push) Successful in 9s
CI / integration (push) Successful in 2m20s
CI / publish (push) Successful in 43s

Milestone 72 phase B — Grafana-style drag-resize grid for dashboard widgets:
- DashboardWidget: replace `position` with a 12-col grid placement
  (grid_x/grid_y/grid_w/grid_h). Migration 0021 backfills the old position
  order into a 3-up grid (4 cols x 4 cells each) and drops position.
- View + share render a static CSS grid from x/y/w/h: fixed cell height
  (h * 70px) with the body scrolling, so the arranged layout is what's shown;
  collapses to a single column under 820px.
- Edit view: Gridstack.js 12.6.0 (vanilla, CDN, pinned) — drag the title bar
  to move, drag a corner/edge to resize; every change autosaves to a new
  /d/<id>/edit/layout endpoint. Replaces the SortableJS position reorder.
- add_widget appends at the bottom-left; remove no longer renumbers.
  _get_widgets now orders by grid position (drives DOM + mobile fallback order).

Note: Gridstack drag-resize is browser-only, so CI can't exercise it — needs an
operator visual check of the edit experience.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-17 15:04:00 -04:00
parent 5f92340c0c
commit 525f6eedbd
8 changed files with 177 additions and 73 deletions
+30 -20
View File
@@ -38,19 +38,16 @@ def _can_edit(dash: Dashboard, user_id: str, user_role: str) -> bool:
# ── DB helpers ────────────────────────────────────────────────────────────────
async def _get_widgets(db, dashboard_id: int) -> list[DashboardWidget]:
# Reading order = grid order (top-to-bottom, then left-to-right). This drives
# DOM order, which is what the responsive single-column fallback collapses to.
result = await db.execute(
select(DashboardWidget)
.where(DashboardWidget.dashboard_id == dashboard_id)
.order_by(DashboardWidget.position)
.order_by(DashboardWidget.grid_y, DashboardWidget.grid_x, DashboardWidget.id)
)
return list(result.scalars())
async def _normalise_positions(db, dashboard_id: int) -> None:
for i, w in enumerate(await _get_widgets(db, dashboard_id)):
w.position = i
async def _accessible_dashboards(db, user_id: str, user_role: str) -> list[Dashboard]:
"""All dashboards visible to this user, ordered by id."""
result = await db.execute(select(Dashboard).order_by(Dashboard.id))
@@ -97,9 +94,11 @@ async def _get_or_create_system_default(db) -> Dashboard:
db.add(dash)
await db.flush()
plugins_cfg = current_app.config.get("PLUGINS", {})
# Seed a 3-up grid (each widget 4 cols wide x 4 cells tall on the 12-col grid).
for pos, w in enumerate(get_available_widgets(plugins_cfg)):
db.add(DashboardWidget(
dashboard_id=dash.id, widget_key=w["key"], position=pos,
dashboard_id=dash.id, widget_key=w["key"],
grid_x=(pos % 3) * 4, grid_y=(pos // 3) * 4, grid_w=4, grid_h=4,
))
return dash
@@ -408,10 +407,12 @@ async def add_widget(dash_id: int, widget_key: str):
dash = result.scalar_one_or_none()
if dash is None or not _can_edit(dash, user_id, user_role):
abort(403)
widgets = await _get_widgets(db, dash_id)
next_pos = max((w.position for w in widgets), default=-1) + 1
widgets = await _get_widgets(db, dash_id)
# Append below everything at full-left; the user then drags/resizes.
next_y = max((w.grid_y + w.grid_h for w in widgets), default=0)
db.add(DashboardWidget(
dashboard_id=dash_id, widget_key=widget_key, position=next_pos,
dashboard_id=dash_id, widget_key=widget_key,
grid_x=0, grid_y=next_y, grid_w=4, grid_h=4,
title=title, config_json=config_json,
))
return await _panels_response(dash_id)
@@ -434,30 +435,39 @@ async def remove_widget(dash_id: int, widget_id: int):
widget = result.scalar_one_or_none()
if widget and widget.dashboard_id == dash_id:
await db.delete(widget)
await _normalise_positions(db, dash_id)
return await _panels_response(dash_id)
@dashboard_bp.post("/d/<int:dash_id>/edit/reorder")
@dashboard_bp.post("/d/<int:dash_id>/edit/layout")
@require_role(UserRole.viewer)
async def reorder_widgets(dash_id: int):
async def save_layout(dash_id: int):
"""Persist the drag-resize grid (Gridstack) — one {id,x,y,w,h} per widget."""
user_id = current_user_id()
user_role = session.get("user_role", "viewer")
data = await request.get_json(silent=True)
if not data or not isinstance(data.get("order"), list):
if not data or not isinstance(data.get("items"), list):
abort(400)
order: list[int] = data["order"]
async with current_app.db_sessionmaker() as db:
async with db.begin():
result = await db.execute(select(Dashboard).where(Dashboard.id == dash_id))
dash = result.scalar_one_or_none()
if dash is None or not _can_edit(dash, user_id, user_role):
abort(403)
widgets = await _get_widgets(db, dash_id)
widget_map = {w.id: w for w in widgets}
for pos, wid in enumerate(order):
if wid in widget_map:
widget_map[wid].position = pos
widget_map = {w.id: w for w in await _get_widgets(db, dash_id)}
for it in data["items"]:
if not isinstance(it, dict):
continue
w = widget_map.get(it.get("id"))
if w is None:
continue
try:
# Clamp to the 12-col grid; widths can't exceed it.
w.grid_x = max(0, min(11, int(it["x"])))
w.grid_w = max(1, min(12, int(it["w"])))
w.grid_y = max(0, int(it["y"]))
w.grid_h = max(1, int(it["h"]))
except (KeyError, TypeError, ValueError):
continue
return ("", 204)
@@ -0,0 +1,48 @@
"""Replace dashboard_widgets.position with a Grafana-style grid (x/y/w/h)
Revision ID: 0021_dashboard_widget_grid
Revises: 0020_ansible_run_results
Create Date: 2026-06-17
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
revision: str = "0021_dashboard_widget_grid"
down_revision: Union[str, None] = "0020_ansible_run_results"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# New grid columns (server_default so existing rows are populated; the ORM
# supplies these on insert thereafter). 12-col grid, default widget 4x4.
op.add_column("dashboard_widgets",
sa.Column("grid_x", sa.Integer, nullable=False, server_default="0"))
op.add_column("dashboard_widgets",
sa.Column("grid_y", sa.Integer, nullable=False, server_default="0"))
op.add_column("dashboard_widgets",
sa.Column("grid_w", sa.Integer, nullable=False, server_default="4"))
op.add_column("dashboard_widgets",
sa.Column("grid_h", sa.Integer, nullable=False, server_default="4"))
# Backfill from the old `position` order into a 3-up grid, reproducing the
# previous masonry layout: 3 widgets per row, each 4 cols wide x 4 cells tall.
op.execute(
"UPDATE dashboard_widgets "
"SET grid_x = (position % 3) * 4, grid_y = (position / 3) * 4"
)
op.drop_column("dashboard_widgets", "position")
def downgrade() -> None:
op.add_column("dashboard_widgets",
sa.Column("position", sa.Integer, nullable=False, server_default="0"))
# Reconstruct a linear order from the grid (reading order: top-to-bottom,
# then left-to-right within a row).
op.execute(
"UPDATE dashboard_widgets SET position = grid_y * 3 + (grid_x / 4)"
)
op.drop_column("dashboard_widgets", "grid_h")
op.drop_column("dashboard_widgets", "grid_w")
op.drop_column("dashboard_widgets", "grid_y")
op.drop_column("dashboard_widgets", "grid_x")
+6 -1
View File
@@ -50,6 +50,11 @@ class DashboardWidget(Base):
Integer, ForeignKey("dashboards.id", ondelete="CASCADE"), nullable=False,
)
widget_key: Mapped[str] = mapped_column(String(64), nullable=False)
position: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
# Grid placement (Grafana-style): 12-column grid, row height in cell units.
# x/y are the top-left cell; w/h the span. Replaces the old `position` order.
grid_x: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
grid_y: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
grid_w: Mapped[int] = mapped_column(Integer, nullable=False, default=4)
grid_h: Mapped[int] = mapped_column(Integer, nullable=False, default=4)
title: Mapped[str | None] = mapped_column(String(128), nullable=True)
config_json: Mapped[str | None] = mapped_column(Text, nullable=True)
+12
View File
@@ -165,6 +165,18 @@ textarea { resize: vertical; }
.ping-meta { min-width:120px; max-width:180px; flex-shrink:1; overflow:hidden; }
.ping-name { font-size:0.875rem; font-weight:500; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; display:block; }
a.ping-name:hover { text-decoration:underline; }
/* Dashboard widget grid — Grafana-style 12-col layout; cells sized by drag-resize
(Gridstack) in the edit view and rendered statically here from each widget's
x/y/w/h. Cell height is fixed (h * cell unit) with the body scrolling, so the
layout the operator arranged is exactly what they see. */
.dash-grid { display:grid; grid-template-columns:repeat(12,1fr); grid-auto-rows:70px; gap:1rem; }
.dash-grid > .dash-cell { margin-bottom:0; min-width:0; overflow:hidden; display:flex; flex-direction:column; }
.dash-cell .dash-cell-body { flex:1; min-height:0; overflow:auto; }
@media (max-width:820px) {
.dash-grid { grid-template-columns:1fr; grid-auto-rows:auto; }
.dash-grid > .dash-cell { grid-column:1 / -1 !important; grid-row:auto !important; }
.dash-cell .dash-cell-body { overflow:visible; }
}
.ping-addr { display:block; color:var(--text-muted); font-size:0.75rem; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
.ping-pills { display:flex; gap:2px; flex:1; min-width:0; overflow:hidden; align-items:center; }
.pill { display:inline-block; width:7px; height:22px; border-radius:2px; cursor:default; transition:opacity .1s; }
+23 -20
View File
@@ -1,34 +1,37 @@
{# dashboard/_edit_panels.html — returned by all mutation routes and included by edit.html #}
<div id="edit-panels" style="display:grid;grid-template-columns:1fr 340px;gap:1.5rem;align-items:start;">
{# ── Current layout ───────────────────────────────────────────────────── #}
<div>
<div class="section-title" style="margin-bottom:0.75rem;">Current Layout</div>
{# ── Current layout (drag to move, drag the corner/edge to resize) ──────── #}
<div style="min-width:0;">
<div style="display:flex;align-items:baseline;justify-content:space-between;gap:1rem;margin-bottom:0.75rem;">
<div class="section-title" style="margin-bottom:0;">Current Layout</div>
{% if widgets %}
<span style="font-size:0.75rem;color:var(--text-dim);">Drag to move · drag a corner to resize · saved automatically</span>
{% endif %}
</div>
{% if widgets %}
<div id="widget-sort-list" data-dash-id="{{ dashboard.id }}" style="display:grid;gap:0.5rem;">
<div class="grid-stack" data-dash-id="{{ dashboard.id }}">
{% for item in widgets %}
<div class="card" data-widget-id="{{ item.db.id }}"
style="margin-bottom:0;display:flex;align-items:center;gap:0.75rem;padding:0.85rem 1rem;">
<div class="drag-handle" style="flex-shrink:0;cursor:grab;color:var(--text-muted);
font-size:1.1rem;line-height:1;user-select:none;"
title="Drag to reorder"></div>
<div style="flex:1;min-width:0;">
<div style="font-weight:600;font-size:0.9rem;">{{ item.title }}</div>
<div style="font-size:0.78rem;color:var(--text-muted);margin-top:0.1rem;">{{ item.defn.description }}</div>
<div class="grid-stack-item" gs-id="{{ item.db.id }}"
gs-x="{{ item.db.grid_x }}" gs-y="{{ item.db.grid_y }}"
gs-w="{{ item.db.grid_w }}" gs-h="{{ item.db.grid_h }}">
<div class="grid-stack-item-content edit-panel">
<div class="panel-drag" title="Drag to move">
<span style="color:var(--text-muted);"></span>
<span style="flex:1;min-width:0;font-weight:600;font-size:0.875rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"
title="{{ item.title }}">{{ item.title }}</span>
<button hx-post="/d/{{ dashboard.id }}/edit/remove/{{ item.db.id }}"
hx-target="#edit-panels" hx-swap="outerHTML"
class="btn btn-danger btn-sm" style="flex-shrink:0;">Remove</button>
</div>
<div style="font-size:0.78rem;color:var(--text-muted);margin-top:0.35rem;overflow:hidden;">{{ item.defn.description }}</div>
</div>
<button hx-post="/d/{{ dashboard.id }}/edit/remove/{{ item.db.id }}"
hx-target="#edit-panels" hx-swap="outerHTML"
class="btn btn-danger btn-sm" style="flex-shrink:0;">Remove</button>
</div>
{% endfor %}
</div>
{% else %}
<div class="card" style="color:var(--text-muted);text-align:center;padding:2rem;font-size:0.9rem;">
No widgets yet. Draw one from the right to begin.
No widgets yet. Add one from the right to begin.
</div>
{% endif %}
</div>
+37 -24
View File
@@ -2,6 +2,9 @@
{% from "_macros.html" import crumbs %}
{% block title %}Edit: {{ dashboard.name }} — Steward{% endblock %}
{% block breadcrumb %}{{ crumbs([("Dashboard", "/"), ("Dashboards", "/dashboards/"), ("Edit " ~ dashboard.name, "")]) }}{% endblock %}
{% block head %}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gridstack@12.6.0/dist/gridstack.min.css">
{% endblock %}
{% block content %}
<div style="display:flex;align-items:baseline;justify-content:space-between;margin-bottom:1.5rem;">
<h1 class="page-title" style="margin-bottom:0;">Edit: {{ dashboard.name }}</h1>
@@ -10,36 +13,46 @@
{% include "dashboard/_edit_panels.html" %}
{% endblock %}
{% block extra_scripts %}
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.2/Sortable.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/gridstack@12.6.0/dist/gridstack-all.min.js"></script>
<script>
(function () {
function initSortable() {
var el = document.getElementById('widget-sort-list');
if (!el) return;
// (Re)initialise the drag-resize grid. Called on first load and after every
// HTMX swap (add/remove re-renders #edit-panels with fresh markup, so the old
// grid DOM is gone and we bind to the new container).
function initGrid() {
var el = document.querySelector('.grid-stack');
if (!el || el.gridstack) return; // already bound to this node
var dashId = el.dataset.dashId;
Sortable.create(el, {
handle: '.drag-handle',
animation: 150,
ghostClass: 'sortable-ghost',
onEnd: function () {
var order = Array.from(el.querySelectorAll('[data-widget-id]'))
.map(function (row) { return parseInt(row.dataset.widgetId, 10); });
fetch('/d/' + dashId + '/edit/reorder', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ order: order }),
});
},
});
var grid = GridStack.init({
column: 12,
cellHeight: 70,
margin: 8,
float: false, // compact upward, no floating gaps
handle: '.panel-drag', // drag by the title bar; buttons stay clickable
resizable: { handles: 'e, se, s' },
}, el);
function save() {
var items = grid.save(false).map(function (n) {
return { id: parseInt(n.id, 10), x: n.x, y: n.y, w: n.w, h: n.h };
});
fetch('/d/' + dashId + '/edit/layout', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ items: items }),
});
}
grid.on('change', save);
}
// Init on first load and after every HTMX swap (add/remove re-renders the list)
document.addEventListener('DOMContentLoaded', initSortable);
document.addEventListener('htmx:afterSwap', initSortable);
document.addEventListener('DOMContentLoaded', initGrid);
document.addEventListener('htmx:afterSwap', initGrid);
})();
</script>
<style>
.sortable-ghost { opacity: 0.4; }
.drag-handle:active { cursor: grabbing; }
/* Each Gridstack panel reads as a card; the title bar is the drag handle. */
.edit-panel { background:var(--bg-card); border:1px solid var(--border-mid); border-radius:6px;
padding:0.7rem 0.85rem; height:100%; overflow:hidden; }
.panel-drag { display:flex; align-items:center; gap:0.5rem; cursor:grab; user-select:none; }
.panel-drag:active { cursor:grabbing; }
.grid-stack-item-content { inset:0; }
</style>
{% endblock %}
+6 -4
View File
@@ -62,14 +62,16 @@
{# ── Widget grid ───────────────────────────────────────────────────────────── #}
{% if widgets %}
<div style="column-width:380px;column-count:3;column-gap:1rem;">
<div class="dash-grid">
{% for item in widgets %}
<div class="card ping-card" style="break-inside:avoid;margin-bottom:1rem;">
{% set gw = item.db %}
<div class="card dash-cell"
style="grid-column:{{ gw.grid_x + 1 }} / span {{ gw.grid_w }};grid-row:{{ gw.grid_y + 1 }} / span {{ gw.grid_h }};">
<div class="widget-header">
<span class="widget-title">{{ item.title }}</span>
<span class="widget-title" title="{{ item.title }}">{{ item.title }}</span>
<a href="{{ item.defn.detail_url }}" class="widget-link">Details →</a>
</div>
<div id="widget-{{ item.db.id }}"
<div class="dash-cell-body" id="widget-{{ gw.id }}"
hx-get="{{ item.hx_url }}"
hx-trigger="load{% if item.defn.poll %}, every {{ poll_interval }}s{% endif %}"
hx-swap="innerHTML">
+15 -4
View File
@@ -55,6 +55,15 @@
.ping-cur-nd { color:var(--text-dim); }
.widget-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:0.75rem; }
.widget-title { font-family:var(--font-serif); font-size:0.8rem; font-weight:600; color:var(--text-muted); text-transform:uppercase; letter-spacing:0.06em; }
/* Same Grafana-style grid as the authenticated view, rendered from x/y/w/h. */
.dash-grid { display:grid; grid-template-columns:repeat(12,1fr); grid-auto-rows:70px; gap:1rem; }
.dash-grid > .dash-cell { margin-bottom:0; min-width:0; overflow:hidden; display:flex; flex-direction:column; }
.dash-cell .dash-cell-body { flex:1; min-height:0; overflow:auto; }
@media (max-width:820px) {
.dash-grid { grid-template-columns:1fr; grid-auto-rows:auto; }
.dash-grid > .dash-cell { grid-column:1 / -1 !important; grid-row:auto !important; }
.dash-cell .dash-cell-body { overflow:visible; }
}
.stat-val { font-size: 2rem; font-weight: 700; line-height: 1; }
.stat-label { font-size: 0.8rem; color: var(--text-muted); margin-left: 0.3rem; }
header { background: var(--bg-card); padding: 0 1.5rem; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--border-mid); height: 48px; font-family: var(--font-serif); }
@@ -72,14 +81,16 @@
<main>
{% if widgets %}
<div style="column-width:380px;column-count:3;column-gap:1rem;">
<div class="dash-grid">
{% for item in widgets %}
<div class="card ping-card" style="break-inside:avoid;margin-bottom:1rem;">
{% set gw = item.db %}
<div class="card ping-card dash-cell"
style="grid-column:{{ gw.grid_x + 1 }} / span {{ gw.grid_w }};grid-row:{{ gw.grid_y + 1 }} / span {{ gw.grid_h }};">
<div class="widget-header">
<span class="widget-title">{{ item.title }}</span>
<span class="widget-title" title="{{ item.title }}">{{ item.title }}</span>
</div>
{# Pass share token as &s= param so require_role allows through #}
<div id="widget-{{ item.db.id }}"
<div class="dash-cell-body" id="widget-{{ gw.id }}"
hx-get="{{ item.hx_url }}&s={{ raw_token }}"
hx-trigger="load{% if item.defn.poll %}, every {{ poll_interval }}s{% endif %}"
hx-swap="innerHTML">