Add in-place dashboard edit mode

A toggle on the dashboard flips into edit mode where widgets get
drag/edit/delete handles and a "+ Add widget" button per column. Most
edits no longer require touching YAML.

- Drag-drop reorder via SortableJS, persisted through a bulk-layout
  endpoint that rebuilds each column's widgets sequence in the
  yaml.Node tree.
- Inline form dialog driven by per-widget field schemas
  (admin-schemas.go) covering 25 widget types. Surgical updates apply
  changed fields to the widget node so untouched keys and comments
  survive. Falls back to the existing YAML editor for group and
  split-column (those need a recursive nested-widget UI).
- Per-column "+ Add widget" picker that opens the dialog pre-filled
  with sensible defaults for the chosen type.
- Field validation and autocomplete for weather location (Open-Meteo
  geocoding), market symbol (Yahoo Finance), and RSS feed URL
  (gofeed). Network failures soft-pass for weather/markets so the
  save isn't blocked when external APIs are unreachable.
- Picking a market suggestion auto-fills the company name field via
  per-suggestion `extra` fields.
- Edit mode persists across reloads via localStorage so saves don't
  drop the user back into view mode.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
uhlwoogi
2026-04-30 16:51:52 +00:00
co-authored by Claude Opus 4.7
parent 2e198a19b4
commit 4b8a34a2ae
10 changed files with 2347 additions and 43 deletions
+383
View File
@@ -1,6 +1,7 @@
package glance
import (
"encoding/json"
"fmt"
"log"
"net/http"
@@ -553,3 +554,385 @@ func (a *application) handleAdminCreateWidget(w http.ResponseWriter, r *http.Req
}
http.Redirect(w, r, a.Config.Server.BaseURL+"/edit/pages/"+slug, http.StatusSeeOther)
}
// handleAdminLayout accepts a JSON description of a page's new column/widget
// layout and rewrites the yaml.Node tree by moving widget nodes between
// columns. Used by the dashboard edit-mode drag-drop UI. The request must
// reference each existing widget exactly once so we never lose or duplicate
// nodes. Edits to widget contents stay untouched — only positions move.
func (a *application) handleAdminLayout(w http.ResponseWriter, r *http.Request) {
if !a.adminAccessAllowed(w, r) {
return
}
slug := r.PathValue("page")
pageIdx, ok := a.freshPageIndexBySlug(slug)
if !ok {
http.Error(w, "page not found", http.StatusNotFound)
return
}
var req struct {
Columns [][]struct {
Col int `json:"col"`
Idx int `json:"idx"`
} `json:"columns"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
editor, err := loadConfigEditor(a.ConfigPath)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
pageNode, err := editor.pageNodeAt(pageIdx)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
columns, err := columnsOf(pageNode)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if len(req.Columns) != len(columns.Content) {
http.Error(w, fmt.Sprintf("layout has %d columns, page has %d", len(req.Columns), len(columns.Content)), http.StatusBadRequest)
return
}
// Snapshot the existing widget nodes by [col][idx] so we can splice them
// into the new layout without mutating during traversal.
snapshot := make([][]*yaml.Node, len(columns.Content))
totalCount := 0
for c, colNode := range columns.Content {
widgets, err := widgetsOf(colNode)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
snapshot[c] = make([]*yaml.Node, len(widgets.Content))
copy(snapshot[c], widgets.Content)
totalCount += len(widgets.Content)
}
// Validate: each widget referenced exactly once, all references in range.
seen := make(map[[2]int]bool, totalCount)
refCount := 0
for _, newCol := range req.Columns {
for _, ref := range newCol {
if ref.Col < 0 || ref.Col >= len(snapshot) || ref.Idx < 0 || ref.Idx >= len(snapshot[ref.Col]) {
http.Error(w, fmt.Sprintf("invalid widget reference col=%d idx=%d", ref.Col, ref.Idx), http.StatusBadRequest)
return
}
key := [2]int{ref.Col, ref.Idx}
if seen[key] {
http.Error(w, fmt.Sprintf("widget col=%d idx=%d referenced more than once", ref.Col, ref.Idx), http.StatusBadRequest)
return
}
seen[key] = true
refCount++
}
}
if refCount != totalCount {
http.Error(w, fmt.Sprintf("layout references %d widgets but page has %d", refCount, totalCount), http.StatusBadRequest)
return
}
// Apply: rebuild each column's widgets sequence from the snapshot.
for c, newCol := range req.Columns {
widgets, _ := widgetsOf(columns.Content[c])
newContent := make([]*yaml.Node, 0, len(newCol))
for _, ref := range newCol {
newContent = append(newContent, snapshot[ref.Col][ref.Idx])
}
widgets.Content = newContent
}
if err := editor.save(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
// jsonToYAMLNode converts the JSON-decoded value (string/float64/bool/nil/
// []any/map[string]any) into a yaml.Node so it can be spliced into the
// config tree. Numbers come in as float64 from encoding/json; we render them
// as ints when they have no fractional part (most widget fields are int).
func jsonToYAMLNode(v interface{}) (*yaml.Node, error) {
switch x := v.(type) {
case nil:
return &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!null", Value: "null"}, nil
case string:
return &yaml.Node{Kind: yaml.ScalarNode, Value: x}, nil
case bool:
return &yaml.Node{Kind: yaml.ScalarNode, Value: strconv.FormatBool(x)}, nil
case float64:
if x == float64(int64(x)) {
return &yaml.Node{Kind: yaml.ScalarNode, Value: strconv.FormatInt(int64(x), 10)}, nil
}
return &yaml.Node{Kind: yaml.ScalarNode, Value: strconv.FormatFloat(x, 'f', -1, 64)}, nil
case []interface{}:
seq := &yaml.Node{Kind: yaml.SequenceNode}
for _, item := range x {
n, err := jsonToYAMLNode(item)
if err != nil {
return nil, err
}
seq.Content = append(seq.Content, n)
}
return seq, nil
case map[string]interface{}:
m := &yaml.Node{Kind: yaml.MappingNode}
for k, vv := range x {
if vv == nil {
// Skip null fields rather than writing `title: null`.
continue
}
n, err := jsonToYAMLNode(vv)
if err != nil {
return nil, err
}
m.Content = append(m.Content,
&yaml.Node{Kind: yaml.ScalarNode, Value: k},
n,
)
}
return m, nil
}
return nil, fmt.Errorf("unsupported JSON type %T", v)
}
// applyFieldsToWidget surgically updates a widget mapping node from a JSON
// fields map. Existing keys are replaced; new keys are appended. A null
// value removes the key. Other keys (and comments) on the widget are left
// untouched, so users can still hand-edit advanced fields the dialog
// doesn't know about.
func applyFieldsToWidget(widget *yaml.Node, fields map[string]interface{}) error {
if widget.Kind != yaml.MappingNode {
return fmt.Errorf("widget node is not a mapping")
}
for key, val := range fields {
existing := -1
for i := 0; i+1 < len(widget.Content); i += 2 {
if widget.Content[i].Value == key {
existing = i
break
}
}
if val == nil {
if existing != -1 {
widget.Content = append(widget.Content[:existing], widget.Content[existing+2:]...)
}
continue
}
valNode, err := jsonToYAMLNode(val)
if err != nil {
return fmt.Errorf("field %q: %w", key, err)
}
if existing == -1 {
widget.Content = append(widget.Content,
&yaml.Node{Kind: yaml.ScalarNode, Value: key},
valNode,
)
} else {
widget.Content[existing+1] = valNode
}
}
return nil
}
// handleAdminUpdateFields applies JSON form values to an existing widget
// without touching its other YAML fields. Used by the inline edit dialog.
func (a *application) handleAdminUpdateFields(w http.ResponseWriter, r *http.Request) {
if !a.adminAccessAllowed(w, r) {
return
}
slug := r.PathValue("page")
pageIdx, ok := a.freshPageIndexBySlug(slug)
if !ok {
http.Error(w, "page not found", http.StatusNotFound)
return
}
col, err := strconv.Atoi(r.PathValue("col"))
if err != nil {
http.Error(w, "bad column", http.StatusBadRequest)
return
}
idx, err := strconv.Atoi(r.PathValue("idx"))
if err != nil {
http.Error(w, "bad index", http.StatusBadRequest)
return
}
var fields map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&fields); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
editor, err := loadConfigEditor(a.ConfigPath)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
seq, pos, err := editor.widgetSlot(pageIdx, col, idx)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := applyFieldsToWidget(seq.Content[pos], fields); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := editor.save(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
}
// handleAdminCreateFromFields creates a new widget at the end of a column
// from a JSON {type, fields} payload. The dialog uses this when the user
// clicks the "+" button in edit mode and fills in a form.
func (a *application) handleAdminCreateFromFields(w http.ResponseWriter, r *http.Request) {
if !a.adminAccessAllowed(w, r) {
return
}
slug := r.PathValue("page")
pageIdx, ok := a.freshPageIndexBySlug(slug)
if !ok {
http.Error(w, "page not found", http.StatusNotFound)
return
}
col, err := strconv.Atoi(r.PathValue("col"))
if err != nil {
http.Error(w, "bad column", http.StatusBadRequest)
return
}
var req struct {
Type string `json:"type"`
Fields map[string]interface{} `json:"fields"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if req.Type == "" {
http.Error(w, "type is required", http.StatusBadRequest)
return
}
if _, err := newWidget(req.Type); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
editor, err := loadConfigEditor(a.ConfigPath)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
pageNode, err := editor.pageNodeAt(pageIdx)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
columns, err := columnsOf(pageNode)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if col < 0 || col >= len(columns.Content) {
http.Error(w, "column index out of range", http.StatusBadRequest)
return
}
widgets, err := widgetsOf(columns.Content[col])
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
widget := &yaml.Node{Kind: yaml.MappingNode, Content: []*yaml.Node{
{Kind: yaml.ScalarNode, Value: "type"},
{Kind: yaml.ScalarNode, Value: req.Type},
}}
if err := applyFieldsToWidget(widget, req.Fields); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
widgets.Content = append(widgets.Content, widget)
if err := editor.save(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
}
// handleAdminGetFields returns the current values of one widget as JSON,
// drawn from the on-disk yaml.Node so unresolved ${env:X} tokens stay as
// the user typed them. The dialog form generator uses this to populate
// initial values when editing an existing widget.
func (a *application) handleAdminGetFields(w http.ResponseWriter, r *http.Request) {
if !a.adminAccessAllowed(w, r) {
return
}
slug := r.PathValue("page")
pageIdx, ok := a.freshPageIndexBySlug(slug)
if !ok {
http.Error(w, "page not found", http.StatusNotFound)
return
}
col, err := strconv.Atoi(r.PathValue("col"))
if err != nil {
http.Error(w, "bad column", http.StatusBadRequest)
return
}
idx, err := strconv.Atoi(r.PathValue("idx"))
if err != nil {
http.Error(w, "bad index", http.StatusBadRequest)
return
}
editor, err := loadConfigEditor(a.ConfigPath)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
seq, pos, err := editor.widgetSlot(pageIdx, col, idx)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var fields map[string]interface{}
if err := seq.Content[pos].Decode(&fields); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(fields); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
// handleAdminWidgetSchemas exposes the widget field schemas as JSON for the
// edit-mode dialog. Cached client-side; no auth-related data here.
func (a *application) handleAdminWidgetSchemas(w http.ResponseWriter, r *http.Request) {
if !a.adminAccessAllowed(w, r) {
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(widgetSchemas); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}