Skip to content

The only tool you need to know what is happening and how to fix it.

feat: improvements on dashboard (#260)

narrow-adventure447839da84c9
diff --git a/CLAUDE.md b/CLAUDE.md
index cda10fb5..7c805f85 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -622,7 +622,11 @@ backend/
| POST | `/api/widget-groups/:id/widgets` | App+Write | Add widget |
| PUT | `/api/widget-groups/:id/widgets/:wid` | App+Write | Update widget |
| PUT | `/api/widget-groups/:id/reorder` | App+Write | Reorder widgets (explicit id order) |
+| PUT | `/api/widget-groups/:id/widgets/:wid/star` | App+Write | Star/unstar widget for the homepage |
| DELETE | `/api/widget-groups/:id/widgets/:wid` | App+Write | Delete widget |
+| GET | `/api/widget-groups/starred` | App | List starred widgets with homepage layout |
+| PUT | `/api/starred-widgets/reorder` | App+Write | Reorder homepage starred widgets (explicit id order) |
+| PUT | `/api/starred-widgets/:wid` | App+Write | Update homepage layout (colSpan/size) of a starred widget |
**Endpoints**
| Method | Endpoint | Auth | Purpose |
@@ -727,6 +731,7 @@ func (c *ReportController) Report(ctx *gin.Context) {
| `metric_registry` | Custom metric definitions (type, unit, description) |
| `widget_groups` | Dashboard widget groups (name, default flag) |
| `widget_group_widgets` | Individual widgets within groups (type, config, position) |
+| `starred_widgets` | Homepage layout for starred widgets (position, col_span, size per widget) |
#### ClickHouse vs PostgreSQL Decision Guide
- **PostgreSQL**: Relational/config data needing ACID, frequent updates, JOINs, low volume (users, organizations, projects, invitations, widgets, source maps, metric registry)
@@ -744,7 +749,7 @@ In SQLite mode (`DB_TYPE=sqlite`), the backend uses **two separate SQLite databa
**Main DB tables** (`db.DB` — transactional, uses lit with `*sql.Tx`):
- `users`, `organizations`, `organization_users`, `projects`, `invitations`
-- `source_maps`, `metric_registry`, `widget_groups`, `widget_group_widgets`
+- `source_maps`, `metric_registry`, `widget_groups`, `widget_group_widgets`, `starred_widgets`
- `notification_channels`, `notification_rules`
**Telemetry DB tables** (`db.TelemetryDB` — non-transactional, uses lit with `db.TelemetryDB` directly):
diff --git a/backend/app/controllers/routes.go b/backend/app/controllers/routes.go
index 51a4d7c8..2a89c524 100644
--- a/backend/app/controllers/routes.go
+++ b/backend/app/controllers/routes.go
@@ -84,6 +84,9 @@ func RegisterControllers(router *gin.RouterGroup) {
router.PUT("/widget-groups/:id/widgets/:wid/star", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, middleware.Transactional, WidgetController.ToggleStar)
router.DELETE("/widget-groups/:id/widgets/:wid", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, middleware.Transactional, WidgetController.Delete)
+ router.PUT("/starred-widgets/reorder", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, middleware.Transactional, WidgetController.ReorderStarred)
+ router.PUT("/starred-widgets/:wid", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, middleware.Transactional, WidgetController.UpdateStarredLayout)
+
router.POST("/endpoints", middleware.UseAppAuth, middleware.RequireProjectAccess, EndpointController.FindAllEndpoints)
router.POST("/endpoints/grouped", middleware.UseAppAuth, middleware.RequireProjectAccess, EndpointController.FindGroupedByEndpoint)
router.POST("/endpoints/endpoint", middleware.UseAppAuth, middleware.RequireProjectAccess, EndpointController.FindByEndpoint)
diff --git a/backend/app/controllers/widget.controller.go b/backend/app/controllers/widget.controller.go
index 79c42d4d..606a7c83 100644
--- a/backend/app/controllers/widget.controller.go
+++ b/backend/app/controllers/widget.controller.go
@@ -293,6 +293,11 @@ func (c *widgetController) Delete(ctx *gin.Context) {
return
}
+ if err := repositories.WidgetGroupRepository.DeleteStarredByWidgetId(tx, widgetId); err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to delete widget: %w", err))
+ return
+ }
+
if err := repositories.WidgetGroupRepository.DeleteWidget(tx, widgetId); err != nil {
ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to delete widget: %w", err))
return
@@ -344,15 +349,59 @@ func (c *widgetController) ToggleStar(ctx *gin.Context) {
return
}
- widget.IsStarred = !widget.IsStarred
- widget.UpdatedAt = time.Now().UTC()
+ starred, err := repositories.WidgetGroupRepository.FindStarredByWidgetId(tx, projectId, widgetId)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to toggle star: %w", err))
+ return
+ }
- if err := repositories.WidgetGroupRepository.UpdateWidget(tx, widget); err != nil {
+ if starred != nil {
+ if err := repositories.WidgetGroupRepository.DeleteStarredByWidgetId(tx, widgetId); err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to toggle star: %w", err))
+ return
+ }
+ ctx.JSON(http.StatusOK, gin.H{"id": widgetId, "isStarred": false})
+ return
+ }
+
+ allStarred, err := repositories.WidgetGroupRepository.FindStarredByProject(tx, projectId)
+ if err != nil {
ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to toggle star: %w", err))
return
}
- ctx.JSON(http.StatusOK, widget)
+ var cfg struct {
+ ColSpan int `json:"colSpan"`
+ Size string `json:"size"`
+ }
+ _ = json.Unmarshal(widget.Config, &cfg)
+ if cfg.ColSpan < 1 || cfg.ColSpan > 3 {
+ cfg.ColSpan = 1
+ }
+ if cfg.Size != "sm" && cfg.Size != "md" && cfg.Size != "lg" {
+ cfg.Size = "sm"
+ }
+
+ nextPosition := 0
+ for _, s := range allStarred {
+ if s.Position >= nextPosition {
+ nextPosition = s.Position + 1
+ }
+ }
+
+ row := &models.StarredWidget{
+ WidgetId: widgetId,
+ Position: nextPosition,
+ ColSpan: cfg.ColSpan,
+ Size: cfg.Size,
+ CreatedAt: time.Now().UTC(),
+ }
+ if err := repositories.WidgetGroupRepository.CreateStarred(tx, row); err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to toggle star: %w", err))
+ return
+ }
+
+ ctx.JSON(http.StatusOK, gin.H{"id": widgetId, "isStarred": true})
}
func (c *widgetController) ListStarred(ctx *gin.Context) {
@@ -371,12 +420,124 @@ func (c *widgetController) ListStarred(ctx *gin.Context) {
}
if widgets == nil {
- widgets = []*models.WidgetGroupWidget{}
+ widgets = []*models.StarredWidgetWithHome{}
}
ctx.JSON(http.StatusOK, widgets)
}
+func (c *widgetController) ReorderStarred(ctx *gin.Context) {
+ projectId, err := middleware.GetProjectId(ctx)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))
+ return
+ }
+
+ var req ReorderWidgetsRequest
+ if err := ctx.ShouldBindJSON(&req); err != nil {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ return
+ }
+
+ tx := db.GetTx(ctx)
+
+ starred, err := repositories.WidgetGroupRepository.FindStarredByProject(tx, projectId)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to reorder starred widgets: %w", err))
+ return
+ }
+
+ byWidgetId := make(map[int]*models.StarredWidget, len(starred))
+ for _, s := range starred {
+ byWidgetId[s.WidgetId] = s
+ }
+
+ if len(req.WidgetIds) != len(starred) {
+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "The widget list is out of date. Please refresh and try again."})
+ return
+ }
+
+ seen := make(map[int]bool, len(req.WidgetIds))
+ for _, id := range req.WidgetIds {
+ if byWidgetId[id] == nil || seen[id] {
+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "The widget list is out of date. Please refresh and try again."})
+ return
+ }
+ seen[id] = true
+ }
+
+ for position, id := range req.WidgetIds {
+ s := byWidgetId[id]
+ if s.Position == position {
+ continue
+ }
+ s.Position = position
+ if err := repositories.WidgetGroupRepository.UpdateStarred(tx, s); err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to reorder starred widgets: %w", err))
+ return
+ }
+ }
+
+ ctx.JSON(http.StatusOK, gin.H{"reordered": true})
+}
+
+type UpdateStarredLayoutRequest struct {
+ ColSpan int `json:"colSpan"`
+ Size string `json:"size"`
+}
+
+func (c *widgetController) UpdateStarredLayout(ctx *gin.Context) {
+ projectId, err := middleware.GetProjectId(ctx)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))
+ return
+ }
+
+ widgetIdStr := ctx.Param("wid")
+ widgetId, err := strconv.Atoi(widgetIdStr)
+ if err != nil {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid widget id"})
+ return
+ }
+
+ var req UpdateStarredLayoutRequest
+ if err := ctx.ShouldBindJSON(&req); err != nil {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ return
+ }
+
+ if req.ColSpan < 1 || req.ColSpan > 3 {
+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Width must be between 1 and 3 columns."})
+ return
+ }
+ if req.Size != "sm" && req.Size != "md" && req.Size != "lg" {
+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Height must be one of: sm, md, lg."})
+ return
+ }
+
+ tx := db.GetTx(ctx)
+
+ starred, err := repositories.WidgetGroupRepository.FindStarredByWidgetId(tx, projectId, widgetId)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to update starred widget layout: %w", err))
+ return
+ }
+ if starred == nil {
+ ctx.JSON(http.StatusNotFound, gin.H{"error": "Starred widget not found"})
+ return
+ }
+
+ starred.ColSpan = req.ColSpan
+ starred.Size = req.Size
+
+ if err := repositories.WidgetGroupRepository.UpdateStarred(tx, starred); err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to update starred widget layout: %w", err))
+ return
+ }
+
+ ctx.JSON(http.StatusOK, starred)
+}
+
func validateWidgetConfig(raw json.RawMessage) string {
var cfg struct {
Sources []struct {
diff --git a/backend/app/controllers/widget_group.controller.go b/backend/app/controllers/widget_group.controller.go
index e1549f31..0eff61be 100644
--- a/backend/app/controllers/widget_group.controller.go
+++ b/backend/app/controllers/widget_group.controller.go
@@ -179,13 +179,13 @@ func (c *widgetGroupController) GetWithWidgets(ctx *gin.Context) {
return
}
- widgets, err := repositories.WidgetGroupRepository.FindWidgetsByGroup(tx, id)
+ widgets, err := repositories.WidgetGroupRepository.FindWidgetsByGroupWithStar(tx, id)
if err != nil {
ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to get widget group widgets: %w", err))
return
}
- widgetSlice := []models.WidgetGroupWidget{}
+ widgetSlice := []models.WidgetGroupWidgetWithStar{}
for _, w := range widgets {
widgetSlice = append(widgetSlice, *w)
}
@@ -292,6 +292,11 @@ func (c *widgetGroupController) Delete(ctx *gin.Context) {
// then the group itself. Don't lean on the FK cascade — explicit deletes
// are easier to audit and survive future schema migrations that might
// drop or alter the cascade rule.
+ if err := repositories.WidgetGroupRepository.DeleteStarredByGroup(tx, id); err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to delete widget group starred widgets: %w", err))
+ return
+ }
+
if err := repositories.WidgetGroupRepository.DeleteWidgetsByGroup(tx, id); err != nil {
ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to delete widget group widgets: %w", err))
return
diff --git a/backend/app/migrations/pg/0048_create_starred_widgets.up.sql b/backend/app/migrations/pg/0048_create_starred_widgets.up.sql
new file mode 100644
index 00000000..11d66aed
--- /dev/null
+++ b/backend/app/migrations/pg/0048_create_starred_widgets.up.sql
@@ -0,0 +1,8 @@
+CREATE TABLE IF NOT EXISTS starred_widgets (
+ id SERIAL PRIMARY KEY,
+ widget_id INTEGER NOT NULL UNIQUE REFERENCES widget_group_widgets(id) ON DELETE CASCADE,
+ position INTEGER NOT NULL DEFAULT 0,
+ col_span INTEGER NOT NULL DEFAULT 1,
+ size VARCHAR(10) NOT NULL DEFAULT 'sm',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
diff --git a/backend/app/migrations/pg/0049_backfill_starred_widgets.up.sql b/backend/app/migrations/pg/0049_backfill_starred_widgets.up.sql
new file mode 100644
index 00000000..81953e1e
--- /dev/null
+++ b/backend/app/migrations/pg/0049_backfill_starred_widgets.up.sql
@@ -0,0 +1,5 @@
+INSERT INTO starred_widgets (widget_id, position, col_span, size, created_at)
+SELECT wgw.id, ROW_NUMBER() OVER (PARTITION BY wg.project_id ORDER BY wgw.updated_at DESC) - 1, 1, 'sm', NOW()
+FROM widget_group_widgets wgw
+JOIN widget_groups wg ON wg.id = wgw.widget_group_id
+WHERE wgw.is_starred;
diff --git a/backend/app/migrations/sqlite/0020_create_starred_widgets.up.sql b/backend/app/migrations/sqlite/0020_create_starred_widgets.up.sql
new file mode 100644
index 00000000..47f91b12
--- /dev/null
+++ b/backend/app/migrations/sqlite/0020_create_starred_widgets.up.sql
@@ -0,0 +1,8 @@
+CREATE TABLE IF NOT EXISTS starred_widgets (
+ id INTEGER PRIMARY KEY,
+ widget_id INTEGER NOT NULL UNIQUE REFERENCES widget_group_widgets(id) ON DELETE CASCADE,
+ position INTEGER NOT NULL DEFAULT 0,
+ col_span INTEGER NOT NULL DEFAULT 1,
+ size TEXT NOT NULL DEFAULT 'sm',
+ created_at DATETIME NOT NULL DEFAULT (datetime('now'))
+);
diff --git a/backend/app/migrations/sqlite/0021_backfill_starred_widgets.up.sql b/backend/app/migrations/sqlite/0021_backfill_starred_widgets.up.sql
new file mode 100644
index 00000000..50d5f42d
--- /dev/null
+++ b/backend/app/migrations/sqlite/0021_backfill_starred_widgets.up.sql
@@ -0,0 +1,5 @@
+INSERT INTO starred_widgets (widget_id, position, col_span, size, created_at)
+SELECT wgw.id, ROW_NUMBER() OVER (PARTITION BY wg.project_id ORDER BY wgw.updated_at DESC) - 1, 1, 'sm', datetime('now')
+FROM widget_group_widgets wgw
+JOIN widget_groups wg ON wg.id = wgw.widget_group_id
+WHERE wgw.is_starred = 1;
diff --git a/backend/app/models/models.go b/backend/app/models/models.go
index 3a8710db..c4ed38d9 100644
--- a/backend/app/models/models.go
+++ b/backend/app/models/models.go
@@ -28,6 +28,9 @@ func Init(driver lit.Driver) {
lit.RegisterModelWithNaming[MetricRegistry](driver, metricRegistryNaming{})
lit.RegisterModel[WidgetGroup](driver)
lit.RegisterModel[WidgetGroupWidget](driver)
+ lit.RegisterModel[WidgetGroupWidgetWithStar](driver)
+ lit.RegisterModel[StarredWidget](driver)
+ lit.RegisterModel[StarredWidgetWithHome](driver)
lit.RegisterModel[NotificationChannel](driver)
lit.RegisterModel[NotificationRule](driver)
lit.RegisterModel[NotificationRuleWithChannel](driver)
diff --git a/backend/app/models/widget_group.model.go b/backend/app/models/widget_group.model.go
index 91a0e224..b7053de5 100644
--- a/backend/app/models/widget_group.model.go
+++ b/backend/app/models/widget_group.model.go
@@ -19,6 +19,17 @@ type WidgetGroup struct {
}
type WidgetGroupWidget struct {
+ Id int `json:"id" lit:"id"`
+ WidgetGroupId int `json:"widgetGroupId" lit:"widget_group_id"`
+ Title string `json:"title" lit:"title"`
+ WidgetType string `json:"widgetType" lit:"widget_type"`
+ Config json.RawMessage `json:"config" lit:"config"`
+ Position int `json:"position" lit:"position"`
+ CreatedAt time.Time `json:"createdAt" lit:"created_at"`
+ UpdatedAt time.Time `json:"updatedAt" lit:"updated_at"`
+}
+
+type WidgetGroupWidgetWithStar struct {
Id int `json:"id" lit:"id"`
WidgetGroupId int `json:"widgetGroupId" lit:"widget_group_id"`
Title string `json:"title" lit:"title"`
@@ -30,7 +41,30 @@ type WidgetGroupWidget struct {
UpdatedAt time.Time `json:"updatedAt" lit:"updated_at"`
}
+type StarredWidget struct {
+ Id int `json:"id" lit:"id"`
+ WidgetId int `json:"widgetId" lit:"widget_id"`
+ Position int `json:"position" lit:"position"`
+ ColSpan int `json:"colSpan" lit:"col_span"`
+ Size string `json:"size" lit:"size"`
+ CreatedAt time.Time `json:"createdAt" lit:"created_at"`
+}
+
+type StarredWidgetWithHome struct {
+ Id int `json:"id" lit:"id"`
+ WidgetGroupId int `json:"widgetGroupId" lit:"widget_group_id"`
+ Title string `json:"title" lit:"title"`
+ WidgetType string `json:"widgetType" lit:"widget_type"`
+ Config json.RawMessage `json:"config" lit:"config"`
+ Position int `json:"position" lit:"position"`
+ HomePosition int `json:"homePosition" lit:"home_position"`
+ HomeColSpan int `json:"homeColSpan" lit:"home_col_span"`
+ HomeSize string `json:"homeSize" lit:"home_size"`
+ CreatedAt time.Time `json:"createdAt" lit:"created_at"`
+ UpdatedAt time.Time `json:"updatedAt" lit:"updated_at"`
+}
+
type WidgetGroupWithWidgets struct {
WidgetGroup
- Widgets []WidgetGroupWidget `json:"widgets"`
+ Widgets []WidgetGroupWidgetWithStar `json:"widgets"`
}
diff --git a/backend/app/repositories/widget_group.repository.go b/backend/app/repositories/widget_group.repository.go
index c9eca9a8..0e22a440 100644
--- a/backend/app/repositories/widget_group.repository.go
+++ b/backend/app/repositories/widget_group.repository.go
@@ -43,7 +43,21 @@ func (r *widgetGroupRepository) Delete(tx *sql.Tx, id int) error {
func (r *widgetGroupRepository) FindWidgetsByGroup(tx *sql.Tx, widgetGroupId int) ([]*models.WidgetGroupWidget, error) {
return lit.SelectNamed[models.WidgetGroupWidget](
tx,
- "SELECT id, widget_group_id, title, widget_type, config, position, is_starred, created_at, updated_at FROM widget_group_widgets WHERE widget_group_id = :wg_id ORDER BY position ASC",
+ "SELECT id, widget_group_id, title, widget_type, config, position, created_at, updated_at FROM widget_group_widgets WHERE widget_group_id = :wg_id ORDER BY position ASC",
+ lit.P{"wg_id": widgetGroupId},
+ )
+}
+
+func (r *widgetGroupRepository) FindWidgetsByGroupWithStar(tx *sql.Tx, widgetGroupId int) ([]*models.WidgetGroupWidgetWithStar, error) {
+ return lit.SelectNamed[models.WidgetGroupWidgetWithStar](
+ tx,
+ `SELECT wgw.id, wgw.widget_group_id, wgw.title, wgw.widget_type, wgw.config, wgw.position,
+ (sw.id IS NOT NULL) AS is_starred,
+ wgw.created_at, wgw.updated_at
+ FROM widget_group_widgets wgw
+ LEFT JOIN starred_widgets sw ON sw.widget_id = wgw.id
+ WHERE wgw.widget_group_id = :wg_id
+ ORDER BY wgw.position ASC`,
lit.P{"wg_id": widgetGroupId},
)
}
@@ -51,20 +65,84 @@ func (r *widgetGroupRepository) FindWidgetsByGroup(tx *sql.Tx, widgetGroupId int
func (r *widgetGroupRepository) FindWidgetById(tx *sql.Tx, id int) (*models.WidgetGroupWidget, error) {
return lit.SelectSingleNamed[models.WidgetGroupWidget](
tx,
- "SELECT id, widget_group_id, title, widget_type, config, position, is_starred, created_at, updated_at FROM widget_group_widgets WHERE id = :id",
+ "SELECT id, widget_group_id, title, widget_type, config, position, created_at, updated_at FROM widget_group_widgets WHERE id = :id",
lit.P{"id": id},
)
}
-func (r *widgetGroupRepository) FindStarredWidgetsByProject(tx *sql.Tx, projectId uuid.UUID) ([]*models.WidgetGroupWidget, error) {
- return lit.SelectNamed[models.WidgetGroupWidget](
+func (r *widgetGroupRepository) FindStarredWidgetsByProject(tx *sql.Tx, projectId uuid.UUID) ([]*models.StarredWidgetWithHome, error) {
+ return lit.SelectNamed[models.StarredWidgetWithHome](
tx,
- `SELECT wgw.id, wgw.widget_group_id, wgw.title, wgw.widget_type, wgw.config, wgw.position, wgw.is_starred, wgw.created_at, wgw.updated_at
- FROM widget_group_widgets wgw
+ `SELECT wgw.id, wgw.widget_group_id, wgw.title, wgw.widget_type, wgw.config, wgw.position,
+ sw.position AS home_position, sw.col_span AS home_col_span, sw.size AS home_size,
+ wgw.created_at, wgw.updated_at
+ FROM starred_widgets sw
+ JOIN widget_group_widgets wgw ON wgw.id = sw.widget_id
JOIN widget_groups wg ON wg.id = wgw.widget_group_id
- WHERE wg.project_id = :project_id AND wgw.is_starred = :starred
- ORDER BY wgw.updated_at DESC`,
- lit.P{"project_id": projectId, "starred": true},
+ WHERE wg.project_id = :project_id
+ ORDER BY sw.position ASC, sw.id ASC`,
+ lit.P{"project_id": projectId},
+ )
+}
+
+func (r *widgetGroupRepository) FindStarredByProject(tx *sql.Tx, projectId uuid.UUID) ([]*models.StarredWidget, error) {
+ return lit.SelectNamed[models.StarredWidget](
+ tx,
+ `SELECT sw.id, sw.widget_id, sw.position, sw.col_span, sw.size, sw.created_at
+ FROM starred_widgets sw
+ JOIN widget_group_widgets wgw ON wgw.id = sw.widget_id
+ JOIN widget_groups wg ON wg.id = wgw.widget_group_id
+ WHERE wg.project_id = :project_id
+ ORDER BY sw.position ASC, sw.id ASC`,
+ lit.P{"project_id": projectId},
+ )
+}
+
+func (r *widgetGroupRepository) FindStarredByWidgetId(tx *sql.Tx, projectId uuid.UUID, widgetId int) (*models.StarredWidget, error) {
+ return lit.SelectSingleNamed[models.StarredWidget](
+ tx,
+ `SELECT sw.id, sw.widget_id, sw.position, sw.col_span, sw.size, sw.created_at
+ FROM starred_widgets sw
+ JOIN widget_group_widgets wgw ON wgw.id = sw.widget_id
+ JOIN widget_groups wg ON wg.id = wgw.widget_group_id
+ WHERE sw.widget_id = :widget_id AND wg.project_id = :project_id`,
+ lit.P{"widget_id": widgetId, "project_id": projectId},
+ )
+}
+
+func (r *widgetGroupRepository) CreateStarred(tx *sql.Tx, starred *models.StarredWidget) error {
+ query, args, err := lit.ParseNamedQuery(
+ db.Driver,
+ `INSERT INTO starred_widgets (widget_id, position, col_span, size, created_at)
+ VALUES (:widget_id, :position, :col_span, :size, :created_at)
+ ON CONFLICT (widget_id) DO NOTHING`,
+ lit.P{
+ "widget_id": starred.WidgetId,
+ "position": starred.Position,
+ "col_span": starred.ColSpan,
+ "size": starred.Size,
+ "created_at": starred.CreatedAt,
+ },
+ )
+ if err != nil {
+ return err
+ }
+ return lit.UpdateNative(tx, query, args...)
+}
+
+func (r *widgetGroupRepository) UpdateStarred(tx *sql.Tx, starred *models.StarredWidget) error {
+ return lit.UpdateNamed(tx, starred, "id = :id", lit.P{"id": starred.Id})
+}
+
+func (r *widgetGroupRepository) DeleteStarredByWidgetId(tx *sql.Tx, widgetId int) error {
+ return lit.DeleteNamed(db.Driver, tx, "DELETE FROM starred_widgets WHERE widget_id = :widget_id", lit.P{"widget_id": widgetId})
+}
+
+func (r *widgetGroupRepository) DeleteStarredByGroup(tx *sql.Tx, widgetGroupId int) error {
+ return lit.DeleteNamed(
+ db.Driver, tx,
+ "DELETE FROM starred_widgets WHERE widget_id IN (SELECT id FROM widget_group_widgets WHERE widget_group_id = :wg_id)",
+ lit.P{"wg_id": widgetGroupId},
)
}
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index c6ea8366..e62b1237 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -43,6 +43,12 @@ async function request(method: string, endpoint: string, data?: unknown, options
}
if (response.status === 403) {
+ if (method !== 'GET') {
+ toast.warning("You don't have permission to perform this action", { position: 'top-center' });
+ const error = new Error('Forbidden') as Error & { status: number };
+ error.status = 403;
+ throw error;
+ }
const currentPath = window.location.pathname;
if (currentPath === '/' || currentPath === '') {
authState.logout();
diff --git a/frontend/src/lib/components/dashboard/d3-line-chart.svelte b/frontend/src/lib/components/dashboard/d3-line-chart.svelte
index 9e59a803..203ce861 100644
--- a/frontend/src/lib/components/dashboard/d3-line-chart.svelte
+++ b/frontend/src/lib/components/dashboard/d3-line-chart.svelte
@@ -4,7 +4,7 @@
import { min, max } from 'd3-array';
import { formatDateTime } from '$lib/utils/formatters';
import { getTimezone } from '$lib/state/timezone.svelte';
- import { formatMetricValue } from '$lib/utils/metric-format';
+ import { getMetricAxisScale, formatAxisTick } from '$lib/utils/metric-format';
type DataPoint = {
timestamp: Date;
@@ -125,18 +125,18 @@
// Generate Y axis ticks
const yTicks = $derived(() => yScale.ticks(4));
- const yAxisUnit = $derived(() => {
- if (!unit) return '';
+ const axisScale = $derived.by(() => {
+ if (!unit) return null;
const ticks = yTicks();
- if (ticks.length === 0) return unit;
- const maxTick = ticks[ticks.length - 1];
- return formatMetricValue(maxTick, unit).unit;
+ if (ticks.length === 0) return null;
+ return getMetricAxisScale(ticks[ticks.length - 1], unit);
});
+ const yAxisUnit = $derived(() => axisScale?.unit ?? '');
+
function formatYLabel(value: number): string {
- if (unit) {
- const result = formatMetricValue(value, unit);
- return result.text;
+ if (axisScale) {
+ return formatAxisTick(value, axisScale.divisor);
}
if (value >= 1000000) return (value / 1000000).toFixed(1) + 'M';
if (value >= 1000) return (value / 1000).toFixed(1) + 'k';
diff --git a/frontend/src/lib/components/dashboard/d3-stacked-area-chart.svelte b/frontend/src/lib/components/dashboard/d3-stacked-area-chart.svelte
index 8ed787bc..59da3f36 100644
--- a/frontend/src/lib/components/dashboard/d3-stacked-area-chart.svelte
+++ b/frontend/src/lib/components/dashboard/d3-stacked-area-chart.svelte
@@ -3,7 +3,7 @@
import { stack, area, stackOrderReverse } from 'd3-shape';
import { min, max } from 'd3-array';
import { formatDateTime } from '$lib/utils/formatters';
- import { formatMetricValue } from '$lib/utils/metric-format';
+ import { getMetricAxisScale, formatAxisTick } from '$lib/utils/metric-format';
import { getTimezone } from '$lib/state/timezone.svelte';
type DataPoint = {
@@ -164,10 +164,18 @@
// Generate Y axis ticks
const yTicks = $derived(() => yScale.ticks(4));
- // Format Y axis label — scaled number only; the unit is shown once above the axis
+ const axisScale = $derived.by(() => {
+ if (!unit) return null;
+ const ticks = yTicks();
+ if (ticks.length === 0) return null;
+ return getMetricAxisScale(ticks[ticks.length - 1], unit);
+ });
+
+ const yAxisUnit = $derived(() => axisScale?.unit ?? '');
+
function formatYLabel(value: number): string {
- if (unit) {
- return formatMetricValue(value, unit).text;
+ if (axisScale) {
+ return formatAxisTick(value, axisScale.divisor);
}
if (value >= 1000000) return (value / 1000000).toFixed(1) + 'M';
if (value >= 1000) return (value / 1000).toFixed(1) + 'k';
@@ -175,13 +183,6 @@
return value.toFixed(1);
}
- const yAxisUnit = $derived(() => {
- if (!unit) return '';
- const ticks = yTicks();
- if (ticks.length === 0) return unit;
- return formatMetricValue(ticks[ticks.length - 1], unit).unit;
- });
-
// Generate stacked area paths
const stackedAreas = $derived(() => {
const data = stackedData();
diff --git a/frontend/src/lib/components/dashboard/widget-config-panel.svelte b/frontend/src/lib/components/dashboard/widget-config-panel.svelte
index 8f81d0c6..503ad4c4 100644
--- a/frontend/src/lib/components/dashboard/widget-config-panel.svelte
+++ b/frontend/src/lib/components/dashboard/widget-config-panel.svelte
@@ -51,8 +51,6 @@
let sources = $state<WidgetSource[]>(
widget?.config?.sources ?? [{ type: 'metric', name: '', aggregation: 'avg' }]
);
- let colSpan = $state<number>(widget?.config?.colSpan ?? 1);
- let size = $state<string>(widget?.config?.size ?? 'sm');
let legend = $state<'auto' | 'on' | 'off'>(legendFromConfig(widget?.config));
let showSparkline = $state(!!widget?.config?.showSparkline);
@@ -65,8 +63,6 @@
sources = widget?.config?.sources
? [...widget.config.sources]
: [{ type: 'metric', name: '', aggregation: 'avg' }];
- colSpan = widget?.config?.colSpan ?? 1;
- size = widget?.config?.size ?? 'sm';
legend = legendFromConfig(widget?.config);
showSparkline = !!widget?.config?.showSparkline;
}
@@ -111,8 +107,8 @@
const displayTitle = title.trim() || validSources[0]?.name || '';
const config: Record<string, any> = { sources: validSources };
if (unit) config.unit = unit;
- if (colSpan !== 1) config.colSpan = colSpan;
- if (size !== 'sm') config.size = size;
+ if (widget?.config?.colSpan != null) config.colSpan = widget.config.colSpan;
+ if (widget?.config?.size != null) config.size = widget.config.size;
if (CHART_TYPES.includes(widgetType) && legend !== 'auto') config.showLegend = legend === 'on';
if (widgetType === 'single_value' && showSparkline) config.showSparkline = true;
onSave({
@@ -169,47 +165,6 @@
</Select.Root>
</div>
- <div class="grid grid-cols-2 gap-2">
- <div>
- <label class="text-sm font-medium">Width</label>
- <Select.Root
- type="single"
- value={String(colSpan)}
- onValueChange={(v) => {
- if (v) colSpan = Number(v);
- }}
- >
- <Select.Trigger>
- {({ '1': '1 column', '2': '2 columns', '3': '3 columns (full)' } as Record<string, string>)[String(colSpan)]}
- </Select.Trigger>
- <Select.Content>
- <Select.Item value="1">1 column</Select.Item>
- <Select.Item value="2">2 columns</Select.Item>
- <Select.Item value="3">3 columns (full)</Select.Item>
- </Select.Content>
- </Select.Root>
- </div>
- <div>
- <label class="text-sm font-medium">Height</label>
- <Select.Root
- type="single"
- value={size}
- onValueChange={(v) => {
- if (v) size = v;
- }}
- >
- <Select.Trigger>
- {({ sm: 'Small', md: 'Medium', lg: 'Large' } as Record<string, string>)[size]}
- </Select.Trigger>
- <Select.Content>
- <Select.Item value="sm">Small</Select.Item>
- <Select.Item value="md">Medium</Select.Item>
- <Select.Item value="lg">Large</Select.Item>
- </Select.Content>
- </Select.Root>
- </div>
- </div>
-
{#if CHART_TYPES.includes(widgetType)}
<div>
<label class="text-sm font-medium">Legend</label>
diff --git a/frontend/src/lib/components/dashboard/widget-grid.svelte b/frontend/src/lib/components/dashboard/widget-grid.svelte
index f75b9909..9e505331 100644
--- a/frontend/src/lib/components/dashboard/widget-grid.svelte
+++ b/frontend/src/lib/components/dashboard/widget-grid.svelte
@@ -8,7 +8,12 @@
Copy,
GripVertical,
Star,
- Trash2
+ Trash2,
+ ArrowUp,
+ ArrowDown,
+ ArrowLeftRight,
+ ArrowUpDown,
+ Check
} from 'lucide-svelte';
import WidgetRenderer from './widget-renderer.svelte';
@@ -30,6 +35,7 @@
onDeleteWidget,
onReorderWidgets,
onDuplicateWidget,
+ onResizeWidget,
onAddWidget,
onToggleStar,
onRangeSelect
@@ -42,6 +48,7 @@
onDeleteWidget?: (widget: Widget) => void;
onReorderWidgets?: (widgetIds: number[]) => void;
onDuplicateWidget?: (widget: Widget) => void;
+ onResizeWidget?: (widget: Widget, layout: { colSpan: number; size: string }) => void;
onAddWidget?: () => void;
onToggleStar?: (widget: Widget) => void;
onRangeSelect?: (from: Date, to: Date) => void;
@@ -91,6 +98,29 @@
dropIndex = null;
}
+ function moveWidget(i: number, delta: number) {
+ const target = i + delta;
+ if (target < 0 || target >= sortedWidgets.length) return;
+ const order = sortedWidgets.map((w: Widget) => w.id);
+ [order[i], order[target]] = [order[target], order[i]];
+ onReorderWidgets?.(order);
+ }
+
+ const hasMenu = $derived(
+ !!(onEditWidget || onDuplicateWidget || onDeleteWidget || onReorderWidgets || onResizeWidget)
+ );
+
+ const widthOptions: { value: number; label: string }[] = [
+ { value: 1, label: '1 column' },
+ { value: 2, label: '2 columns' },
+ { value: 3, label: '3 columns (full)' }
+ ];
+ const heightOptions: { value: string; label: string }[] = [
+ { value: 'sm', label: 'Small' },
+ { value: 'md', label: 'Medium' },
+ { value: 'lg', label: 'Large' }
+ ];
+
// Static maps — Tailwind can't extract dynamically-built class names
const colSpanClass: Record<number, string> = {
1: 'md:col-span-1',
@@ -119,55 +149,126 @@
<Card.Header class="pr-2 pb-1">
<div class="flex items-center justify-between">
<div class="flex min-w-0 items-center gap-1">
- <span
- class="-ml-1 inline-flex h-7 w-5 shrink-0 cursor-grab items-center justify-center rounded text-muted-foreground/60 opacity-0 transition-opacity hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100 active:cursor-grabbing"
- title="Drag to reorder"
- role="button"
- tabindex={-1}
- aria-label="Drag to reorder widget"
- draggable="true"
- ondragstart={(e) => handleDragStart(e, i)}
- ondragend={handleDragEnd}
- >
- <GripVertical class="h-4 w-4" />
- </span>
+ {#if onReorderWidgets}
+ <span
+ class="-ml-1 inline-flex h-7 w-5 shrink-0 cursor-grab items-center justify-center rounded text-muted-foreground/60 opacity-0 transition-opacity hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100 active:cursor-grabbing"
+ title="Drag to reorder"
+ role="button"
+ tabindex={-1}
+ aria-label="Drag to reorder widget"
+ draggable="true"
+ ondragstart={(e) => handleDragStart(e, i)}
+ ondragend={handleDragEnd}
+ >
+ <GripVertical class="h-4 w-4" />
+ </span>
+ {/if}
<Card.Title class="truncate text-sm font-medium">{widget.title}{#if widget.config?.unit}<span class="text-xs font-normal text-muted-foreground"> ({widget.config.unit})</span>{/if}</Card.Title>
</div>
<div class="flex items-center">
- <button
- type="button"
- aria-label={widget.isStarred ? 'Unstar widget' : 'Star widget'}
- title={widget.isStarred ? 'Unstar' : 'Star'}
- class="inline-flex h-7 w-7 items-center justify-center rounded-md transition-colors hover:bg-muted {widget.isStarred ? 'text-yellow-500 hover:text-yellow-600' : 'text-muted-foreground hover:text-foreground'}"
- onclick={() => onToggleStar?.(widget)}
- >
- <Star class="h-4 w-4 {widget.isStarred ? 'fill-current' : ''}" />
- </button>
- <DropdownMenu.Root>
- <DropdownMenu.Trigger
- class="inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
- >
- <EllipsisVertical class="h-4 w-4" />
- </DropdownMenu.Trigger>
- <DropdownMenu.Content align="end">
- <DropdownMenu.Item onclick={() => onEditWidget?.(widget)}>
- <Pencil class="mr-2 h-4 w-4" />
- Edit
- </DropdownMenu.Item>
- <DropdownMenu.Item onclick={() => onDuplicateWidget?.(widget)}>
- <Copy class="mr-2 h-4 w-4" />
- Duplicate
- </DropdownMenu.Item>
- <DropdownMenu.Separator />
- <DropdownMenu.Item
- class="text-destructive"
- onclick={() => onDeleteWidget?.(widget)}
+ {#if onToggleStar}
+ <button
+ type="button"
+ aria-label={widget.isStarred ? 'Unstar widget' : 'Star widget'}
+ title={widget.isStarred ? 'Unstar' : 'Star'}
+ class="inline-flex h-7 w-7 items-center justify-center rounded-md transition-colors hover:bg-muted {widget.isStarred ? 'text-yellow-500 hover:text-yellow-600' : 'text-muted-foreground hover:text-foreground'}"
+ onclick={() => onToggleStar?.(widget)}
+ >
+ <Star class="h-4 w-4 {widget.isStarred ? 'fill-current' : ''}" />
+ </button>
+ {/if}
+ {#if hasMenu}
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger
+ class="inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
>
- <Trash2 class="mr-2 h-4 w-4" />
- Delete
- </DropdownMenu.Item>
- </DropdownMenu.Content>
- </DropdownMenu.Root>
+ <EllipsisVertical class="h-4 w-4" />
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content align="end">
+ {#if onEditWidget}
+ <DropdownMenu.Item onclick={() => onEditWidget?.(widget)}>
+ <Pencil class="mr-2 h-4 w-4" />
+ Edit
+ </DropdownMenu.Item>
+ {/if}
+ {#if onDuplicateWidget}
+ <DropdownMenu.Item onclick={() => onDuplicateWidget?.(widget)}>
+ <Copy class="mr-2 h-4 w-4" />
+ Duplicate
+ </DropdownMenu.Item>
+ {/if}
+ {#if onReorderWidgets}
+ <DropdownMenu.Item disabled={i === 0} onclick={() => moveWidget(i, -1)}>
+ <ArrowUp class="mr-2 h-4 w-4" />
+ Move up
+ </DropdownMenu.Item>
+ <DropdownMenu.Item
+ disabled={i === sortedWidgets.length - 1}
+ onclick={() => moveWidget(i, 1)}
+ >
+ <ArrowDown class="mr-2 h-4 w-4" />
+ Move down
+ </DropdownMenu.Item>
+ {/if}
+ {#if onResizeWidget}
+ <DropdownMenu.Sub>
+ <DropdownMenu.SubTrigger>
+ <ArrowLeftRight class="mr-2 h-4 w-4" />
+ Width
+ </DropdownMenu.SubTrigger>
+ <DropdownMenu.SubContent>
+ {#each widthOptions as option (option.value)}
+ <DropdownMenu.Item
+ onclick={() =>
+ onResizeWidget?.(widget, {
+ colSpan: option.value,
+ size: widget.config?.size ?? 'sm'
+ })}
+ >
+ <Check
+ class="mr-2 h-4 w-4 {(widget.config?.colSpan ?? 1) === option.value ? '' : 'opacity-0'}"
+ />
+ {option.label}
+ </DropdownMenu.Item>
+ {/each}
+ </DropdownMenu.SubContent>
+ </DropdownMenu.Sub>
+ <DropdownMenu.Sub>
+ <DropdownMenu.SubTrigger>
+ <ArrowUpDown class="mr-2 h-4 w-4" />
+ Height
+ </DropdownMenu.SubTrigger>
+ <DropdownMenu.SubContent>
+ {#each heightOptions as option (option.value)}
+ <DropdownMenu.Item
+ onclick={() =>
+ onResizeWidget?.(widget, {
+ colSpan: widget.config?.colSpan ?? 1,
+ size: option.value
+ })}
+ >
+ <Check
+ class="mr-2 h-4 w-4 {(widget.config?.size ?? 'sm') === option.value ? '' : 'opacity-0'}"
+ />
+ {option.label}
+ </DropdownMenu.Item>
+ {/each}
+ </DropdownMenu.SubContent>
+ </DropdownMenu.Sub>
+ {/if}
+ {#if onDeleteWidget}
+ <DropdownMenu.Separator />
+ <DropdownMenu.Item
+ class="text-destructive"
+ onclick={() => onDeleteWidget?.(widget)}
+ >
+ <Trash2 class="mr-2 h-4 w-4" />
+ Delete
+ </DropdownMenu.Item>
+ {/if}
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ {/if}
</div>
</div>
</Card.Header>
@@ -186,13 +287,15 @@
</Card.Root>
</div>
{/each}
- <button
- class="flex min-h-[240px] cursor-pointer items-center justify-center rounded-lg border border-dashed border-muted-foreground/25 text-muted-foreground transition-colors hover:border-primary hover:text-primary"
- onclick={() => onAddWidget?.()}
- >
- <div class="flex flex-col items-center gap-2">
- <Plus class="h-8 w-8" />
- <span class="text-sm font-medium">Add Metric Widget</span>
- </div>
- </button>
+ {#if onAddWidget}
+ <button
+ class="flex min-h-[240px] cursor-pointer items-center justify-center rounded-lg border border-dashed border-muted-foreground/25 text-muted-foreground transition-colors hover:border-primary hover:text-primary"
+ onclick={() => onAddWidget?.()}
+ >
+ <div class="flex flex-col items-center gap-2">
+ <Plus class="h-8 w-8" />
+ <span class="text-sm font-medium">Add Metric Widget</span>
+ </div>
+ </button>
+ {/if}
</div>
diff --git a/frontend/src/lib/components/dashboard/widget-renderer.svelte b/frontend/src/lib/components/dashboard/widget-renderer.svelte
index 0e972bbe..094b899b 100644
--- a/frontend/src/lib/components/dashboard/widget-renderer.svelte
+++ b/frontend/src/lib/components/dashboard/widget-renderer.svelte
@@ -115,13 +115,19 @@
);
const units = new Set<string>();
+ const usedKeys = new Set<string>();
for (const [idx, result] of response.results.entries()) {
if (result.unit) units.add(result.unit);
const baseName = sources[idx]?.label?.trim() || result.name;
for (const [key, points] of Object.entries(result.series)) {
const label = Object.keys(result.series).length > 1 ? `${baseName} (${key})` : baseName;
+ let uniqueKey = label;
+ for (let n = 2; usedKeys.has(uniqueKey); n++) {
+ uniqueKey = `${label} (${n})`;
+ }
+ usedKeys.add(uniqueKey);
newSeries.push({
- key: label,
+ key: uniqueKey,
data: points.map((p) => ({
timestamp: new Date(p.timestamp),
value: p.value
@@ -135,8 +141,11 @@
resolvedUnit = units.size === 1 ? [...units][0] : '';
series = newSeries;
- if (widget.widgetType === 'single_value' && newSeries.length > 0 && newSeries[0].data.length > 0) {
- singleValue = newSeries[0].data[newSeries[0].data.length - 1].value;
+ if (widget.widgetType === 'single_value') {
+ singleValue =
+ newSeries.length > 0 && newSeries[0].data.length > 0
+ ? newSeries[0].data[newSeries[0].data.length - 1].value
+ : null;
}
} catch {
// keep empty
diff --git a/frontend/src/lib/state/projects.svelte.ts b/frontend/src/lib/state/projects.svelte.ts
index ca9cc904..9d54f4cb 100644
--- a/frontend/src/lib/state/projects.svelte.ts
+++ b/frontend/src/lib/state/projects.svelte.ts
@@ -105,6 +105,12 @@ class ProjectsState {
return authState.canManageOrganization(organizationId);
});
+ canWriteCurrentProject = $derived.by(() => {
+ const organizationId = this.currentProject?.organizationId;
+ if (!organizationId) return true;
+ return authState.getRoleForOrganization(organizationId) !== 'readonly';
+ });
+
constructor() {
$effect.root(() => {
$effect(() => {
diff --git a/frontend/src/lib/utils/metric-format.ts b/frontend/src/lib/utils/metric-format.ts
index 12a01a90..7070fe08 100644
--- a/frontend/src/lib/utils/metric-format.ts
+++ b/frontend/src/lib/utils/metric-format.ts
@@ -79,3 +79,78 @@ export function formatMetricLabel(value: number, unit: string): string {
if (!result.unit) return result.text;
return `${result.text} ${result.unit}`;
}
+
+type AxisScale = { divisor: number; unit: string };
+
+export function getMetricAxisScale(maxValue: number, unit: string): AxisScale {
+ if (unit === '1') {
+ return { divisor: 0.01, unit: '%' };
+ }
+
+ if (unit === 'By') {
+ return getMetricAxisScale(maxValue, 'B');
+ }
+
+ if (unit.length > 2 && unit.startsWith('{') && unit.endsWith('}')) {
+ return getMetricAxisScale(maxValue, 'count');
+ }
+
+ if (unit === '%') {
+ return { divisor: 1, unit: '%' };
+ }
+
+ if (unit === 'ms') {
+ if (maxValue < 1) return { divisor: 0.001, unit: 'µs' };
+ if (maxValue < 1000) return { divisor: 1, unit: 'ms' };
+ return { divisor: 1000, unit: 's' };
+ }
+
+ if (unit === 'ns') {
+ if (maxValue < 1000) return { divisor: 1, unit: 'ns' };
+ if (maxValue < 1_000_000) return { divisor: 1000, unit: 'µs' };
+ if (maxValue < 1_000_000_000) return { divisor: 1_000_000, unit: 'ms' };
+ return { divisor: 1_000_000_000, unit: 's' };
+ }
+
+ if (unit === 's') {
+ if (maxValue < 0.001) return { divisor: 0.000001, unit: 'µs' };
+ if (maxValue < 1) return { divisor: 0.001, unit: 'ms' };
+ if (maxValue < 60) return { divisor: 1, unit: 's' };
+ if (maxValue < 3600) return { divisor: 60, unit: 'min' };
+ return { divisor: 3600, unit: 'h' };
+ }
+
+ if (unit === 'MB') {
+ if (maxValue < 1) return { divisor: 1 / 1024, unit: 'KB' };
+ if (maxValue >= 1024) return { divisor: 1024, unit: 'GB' };
+ return { divisor: 1, unit: 'MB' };
+ }
+
+ if (unit === 'GB') {
+ if (maxValue < 1) return { divisor: 1 / 1024, unit: 'MB' };
+ if (maxValue >= 1024) return { divisor: 1024, unit: 'TB' };
+ return { divisor: 1, unit: 'GB' };
+ }
+
+ if (unit === 'bytes' || unit === 'B') {
+ if (maxValue < 1024) return { divisor: 1, unit: 'B' };
+ if (maxValue < 1024 * 1024) return { divisor: 1024, unit: 'KB' };
+ if (maxValue < 1024 * 1024 * 1024) return { divisor: 1024 * 1024, unit: 'MB' };
+ return { divisor: 1024 * 1024 * 1024, unit: 'GB' };
+ }
+
+ if (unit === 'count' || unit === '') {
+ if (maxValue >= 1_000_000) return { divisor: 1_000_000, unit: 'M' };
+ if (maxValue >= 1_000) return { divisor: 1_000, unit: 'K' };
+ return { divisor: 1, unit: '' };
+ }
+
+ return { divisor: 1, unit };
+}
+
+export function formatAxisTick(value: number, divisor: number): string {
+ const scaled = value / divisor;
+ if (Number.isInteger(scaled)) return scaled.toString();
+ if (scaled !== 0 && Math.abs(scaled) < 0.1) return scaled.toFixed(2);
+ return scaled.toFixed(1);
+}
diff --git a/frontend/src/routes/+page.svelte b/frontend/src/routes/+page.svelte
index c995b5d4..38aed31c 100644
--- a/frontend/src/routes/+page.svelte
+++ b/frontend/src/routes/+page.svelte
@@ -19,7 +19,7 @@
Unplug
} from 'lucide-svelte';
import * as Card from '$lib/components/ui/card';
- import WidgetRenderer from '$lib/components/dashboard/widget-renderer.svelte';
+ import WidgetGrid from '$lib/components/dashboard/widget-grid.svelte';
import { TracewayTableHeader } from '$lib/components/ui/traceway-table-header';
import { ImpactBadge } from '$lib/components/ui/impact-badge';
import { ViewAllTableRow } from '$lib/components/ui/view-all-table-row';
@@ -97,12 +97,25 @@
hasData: boolean;
};
+ type StarredWidgetResponse = {
+ id: number;
+ widgetGroupId: number;
+ title: string;
+ widgetType: string;
+ config: any;
+ position: number;
+ homePosition: number;
+ homeColSpan: number;
+ homeSize: string;
+ };
+
type StarredWidget = {
id: number;
widgetGroupId: number;
title: string;
widgetType: string;
config: any;
+ position: number;
isStarred: boolean;
};
@@ -294,7 +307,15 @@ service:
api.get('/widget-groups/starred', { projectId }).catch(() => [])
]);
data = overview;
- starredWidgets = (starred as StarredWidget[]) ?? [];
+ starredWidgets = ((starred as StarredWidgetResponse[]) ?? []).map((w) => ({
+ id: w.id,
+ widgetGroupId: w.widgetGroupId,
+ title: w.title,
+ widgetType: w.widgetType,
+ config: { ...w.config, colSpan: w.homeColSpan, size: w.homeSize },
+ position: w.homePosition,
+ isStarred: true
+ }));
} catch (e: any) {
errorStatus = e.status || 0;
error = e.message || 'Failed to load dashboard data';
@@ -306,6 +327,69 @@ service:
}
}
+ async function handleReorderStarred(widgetIds: number[]) {
+ const previousPositions = new Map(starredWidgets.map((w) => [w.id, w.position]));
+ for (const w of starredWidgets) {
+ w.position = widgetIds.indexOf(w.id);
+ }
+ try {
+ await api.put(
+ '/starred-widgets/reorder',
+ { widgetIds },
+ { projectId: projectsState.currentProjectId ?? undefined }
+ );
+ } catch (e: any) {
+ for (const w of starredWidgets) {
+ w.position = previousPositions.get(w.id) ?? w.position;
+ }
+ if (e?.status !== 403) {
+ toast.error(e?.message || 'Failed to reorder widgets', { position: 'top-center' });
+ }
+ await loadDashboard(false);
+ }
+ }
+
+ async function handleResizeStarred(
+ widget: { id: number },
+ layout: { colSpan: number; size: string }
+ ) {
+ const target = starredWidgets.find((w) => w.id === widget.id);
+ if (!target) return;
+ const previous = { colSpan: target.config.colSpan, size: target.config.size };
+ target.config.colSpan = layout.colSpan;
+ target.config.size = layout.size;
+ try {
+ await api.put(`/starred-widgets/${widget.id}`, layout, {
+ projectId: projectsState.currentProjectId ?? undefined
+ });
+ } catch (e: any) {
+ target.config.colSpan = previous.colSpan;
+ target.config.size = previous.size;
+ if (e?.status !== 403) {
+ toast.error(e?.message || 'Failed to resize widget', { position: 'top-center' });
+ }
+ }
+ }
+
+ async function handleUnstar(widget: { id: number }) {
+ const target = starredWidgets.find((w) => w.id === widget.id);
+ if (!target) return;
+ const previous = starredWidgets;
+ starredWidgets = starredWidgets.filter((w) => w.id !== widget.id);
+ try {
+ await api.put(
+ `/widget-groups/${target.widgetGroupId}/widgets/${target.id}/star`,
+ {},
+ { projectId: projectsState.currentProjectId ?? undefined }
+ );
+ } catch (e: any) {
+ starredWidgets = previous;
+ if (e?.status !== 403) {
+ toast.error(e?.message || 'Failed to unstar widget', { position: 'top-center' });
+ }
+ }
+ }
+
let lastProjectId = $state(projectsState.currentProjectId);
onMount(() => {
@@ -779,29 +863,15 @@ service:
</Tooltip.Content>
</Tooltip.Root>
</div>
- <div class="grid grid-cols-1 gap-4 md:grid-cols-3">
- {#each starredWidgets as widget (widget.id)}
- <Card.Root class="h-full gap-0">
- <Card.Header class="pr-2 pb-1">
- <Card.Title class="text-sm font-medium"
- >{widget.title}{#if widget.config?.unit}<span
- class="text-xs font-normal text-muted-foreground"
- >
- ({widget.config.unit})</span
- >{/if}</Card.Title
- >
- </Card.Header>
- <Card.Content class="p-1">
- <WidgetRenderer
- {widget}
- fromDateUTC={starredFromUTC}
- toDateUTC={starredToUTC}
- timeDomain={null}
- />
- </Card.Content>
- </Card.Root>
- {/each}
- </div>
+ <WidgetGrid
+ widgets={starredWidgets}
+ fromDateUTC={starredFromUTC}
+ toDateUTC={starredToUTC}
+ timeDomain={null}
+ onReorderWidgets={projectsState.canWriteCurrentProject ? handleReorderStarred : undefined}
+ onResizeWidget={projectsState.canWriteCurrentProject ? handleResizeStarred : undefined}
+ onToggleStar={projectsState.canWriteCurrentProject ? handleUnstar : undefined}
+ />
</div>
{/if}
{#if !isFrontend}
diff --git a/frontend/src/routes/metrics/+page.svelte b/frontend/src/routes/metrics/+page.svelte
index d56c6fc9..f7640087 100644
--- a/frontend/src/routes/metrics/+page.svelte
+++ b/frontend/src/routes/metrics/+page.svelte
@@ -407,7 +407,9 @@
);
} catch (e: any) {
target.isStarred = previous;
- toast.error(e?.message || 'Failed to update star', { position: 'top-center' });
+ if (e?.status !== 403) {
+ toast.error(e?.message || 'Failed to update star', { position: 'top-center' });
+ }
}
}
@@ -427,7 +429,9 @@
for (const w of activeGroup.widgets) {
w.position = previousPositions.get(w.id) ?? w.position;
}
- toast.error(e?.message || 'Failed to reorder widgets', { position: 'top-center' });
+ if (e?.status !== 403) {
+ toast.error(e?.message || 'Failed to reorder widgets', { position: 'top-center' });
+ }
await loadGroupWidgets(activeTabId);
}
}
@@ -447,7 +451,29 @@
toast.success('Successfully duplicated the Widget', { position: 'top-center' });
await loadGroupWidgets(activeTabId);
} catch (e: any) {
- toast.error(e?.message || 'Failed to duplicate widget', { position: 'top-center' });
+ if (e?.status !== 403) {
+ toast.error(e?.message || 'Failed to duplicate widget', { position: 'top-center' });
+ }
+ }
+ }
+
+ async function handleResizeWidget(widget: Widget, layout: { colSpan: number; size: string }) {
+ if (!activeGroup) return;
+ const target = activeGroup.widgets?.find((w) => w.id === widget.id);
+ if (!target) return;
+ const previousConfig = target.config;
+ target.config = { ...(target.config ?? {}), colSpan: layout.colSpan, size: layout.size };
+ try {
+ await api.put(
+ `/widget-groups/${activeGroup.id}/widgets/${widget.id}`,
+ { title: target.title, widgetType: target.widgetType, config: target.config },
+ { projectId: projectsState.currentProjectId ?? undefined }
+ );
+ } catch (e: any) {
+ target.config = previousConfig;
+ if (e?.status !== 403) {
+ toast.error(e?.message || 'Failed to resize widget', { position: 'top-center' });
+ }
}
}
@@ -660,6 +686,7 @@
onDeleteWidget={openDeleteWidgetDialog}
onReorderWidgets={handleReorderWidgets}
onDuplicateWidget={handleDuplicateWidget}
+ onResizeWidget={handleResizeWidget}
onAddWidget={openAddWidget}
onToggleStar={handleToggleStar}
onRangeSelect={handleChartRangeSelect}