import { useQuery } from "@tanstack/react-query" import { ChevronLeft, ChevronRight, Plus, X } from "lucide-react" import { useEffect, useRef, useState } from "react" import type { ApiError, DashboardDef_Output, WidgetDef } from "@/client" import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" import { Label } from "@/components/ui/label" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select" import useCustomToast from "@/hooks/useCustomToast" import { handleError } from "@/utils" import { pagesOf, SectionGrid, sectionsOf, widgetStyle, widgetsOf, } from "./DashboardView" import { messageCatalogQueryOptions, useSaveDashboard } from "./queries" import { INPUT_WIDGETS, WIDGET_LABELS, WIDGET_SIZES, WidgetBody, WidgetFrame, type WidgetKind, } from "./widgets" // Charts are stored and validated, but not drawn yet, so they are not offered. const KINDS = (Object.keys(WIDGET_LABELS) as WidgetKind[]).filter( (kind) => kind !== "chart", ) /** How long to sit on edits before saving, so typing is not a save per key. */ const AUTOSAVE_MS = 800 function nextId(dashboard: DashboardDef_Output, type: string): string { const taken = new Set( pagesOf(dashboard).flatMap((page) => sectionsOf(page).flatMap((section) => widgetsOf(section).map((widget) => widget.id), ), ), ) let candidate = type for (let i = 2; taken.has(candidate); i++) candidate = `${type}${i}` return candidate } export function DashboardEditor({ dashboard, pageId, }: { dashboard: DashboardDef_Output pageId?: string }) { const [draft, setDraft] = useState(dashboard) const [selected, setSelected] = useState(null) const save = useSaveDashboard(dashboard.name) const { showErrorToast } = useCustomToast() const timer = useRef | null>(null) // The saved version is what the next save is based on; without following it // the second save of a session is always a conflict. const version = useRef(dashboard.version) useEffect(() => { version.current = dashboard.version }, [dashboard.version]) const commit = (next: DashboardDef_Output) => { setDraft(next) if (timer.current) clearTimeout(timer.current) timer.current = setTimeout(() => { save.mutate( { ...next, version: version.current }, { onSuccess: (saved) => { version.current = saved.version }, onError: (error) => handleError.call(showErrorToast, error as ApiError), }, ) }, AUTOSAVE_MS) } const pages = pagesOf(draft) const page = pages.find((candidate) => candidate.id === pageId) ?? pages[0] if (!page) return null const section = sectionsOf(page)[0] if (!section) return null const widgets = widgetsOf(section) const updateWidgets = (next: WidgetDef[]) => commit({ ...draft, pages: pagesOf(draft).map((candidate) => candidate.id !== page.id ? candidate : { ...candidate, sections: sectionsOf(candidate).map((existing) => existing.id !== section.id ? existing : { ...existing, widgets: next }, ), }, ), }) const addWidget = (type: WidgetKind) => { const id = nextId(draft, type) updateWidgets([ ...widgets, { id, type, title: WIDGET_LABELS[type], layout: { lg: { x: 0, y: 0, ...WIDGET_SIZES[type] } }, config: {}, }, ]) setSelected(id) } const patch = (id: string, changes: Partial) => updateWidgets( widgets.map((widget) => widget.id === id ? { ...widget, ...changes } : widget, ), ) const resize = (widget: WidgetDef, by: number) => { const layout = (widget.layout ?? {}) as Record< string, { x?: number; y?: number; w?: number; h?: number } > const current = layout.lg ?? { x: 0, y: 0, w: 3, h: 2 } patch(widget.id, { layout: { ...layout, lg: { ...current, w: Math.min(12, Math.max(2, (current.w ?? 3) + by)) }, }, }) } const active = widgets.find((widget) => widget.id === selected) return (
Add {KINDS.map((kind) => ( ))}
(
} > )} /> {active ? ( patch(active.id, changes)} /> ) : (

Add a widget, or pick one to configure it.

)} ) } /** What one widget shows or does. Fields differ per type; the set is small. */ function WidgetSettings({ widget, onChange, }: { widget: WidgetDef onChange: (changes: Partial) => void }) { const { data: catalog } = useQuery(messageCatalogQueryOptions()) const messages = catalog?.data ?? [] const config = (widget.config ?? {}) as Record const isInput = INPUT_WIDGETS.has(widget.type) const numericOnly = widget.type === "gauge" || widget.type === "chart" const set = (key: string, value: unknown) => onChange({ config: { ...config, [key]: value } }) const choices = messages.filter((message) => numericOnly ? message.numeric : true, ) return (
{WIDGET_LABELS[widget.type]} settings
onChange({ title: event.target.value })} />
{widget.type === "markdown" ? (
set("content", event.target.value)} />
) : (
)} {(widget.type === "stat" || widget.type === "gauge") && (
set("unit", event.target.value)} />
)} {(widget.type === "gauge" || widget.type === "slider") && (
set("min", Number(event.target.value) || 0)} />
set("max", Number(event.target.value) || 0)} />
)} {widget.type === "button" && (
{ const raw = event.target.value const asNumber = Number(raw) set( "value", raw === "true" || raw === "false" ? raw === "true" : raw !== "" && Number.isFinite(asNumber) ? asNumber : raw, ) }} />
)}
) } export { widgetStyle }