import { useQuery } from "@tanstack/react-query" import { Ban, ChevronDown, Plus, X } from "lucide-react" import { useState } from "react" import type { MessageInfo, SettingDef, WidgetDef } from "@/client" import { DEFAULT_RANGE, RANGES } from "@/components/Common/RangePicker" import { PANEL_SECTION, PanelTitle, SidePanel, } from "@/components/Flow/SidePanel" import { Button } from "@/components/ui/button" import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog" import { Input } from "@/components/ui/input" import { Label } from "@/components/ui/label" import { Popover, PopoverContent, PopoverTrigger, } from "@/components/ui/popover" import { Segmented } from "@/components/ui/segmented" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select" import { Switch } from "@/components/ui/switch" import { cn } from "@/lib/utils" import { MAX_SEGMENTS, type Segment, segmentsOf } from "./BarWidget" import { MAX_SERIES, refreshFor } from "./ChartWidget" import { COLOR_DTYPES, COLOR_FORMATS, colorFormatOf } from "./ColorWidget" import { CANVAS_PRESETS, COLUMN_CHOICES, canvasOf, columnsOf, type Dashboard, } from "./DashboardView" import { ICON_COLORS, ICON_NAMES, ICONS } from "./icons" import { messageCatalogQueryOptions } from "./queries" import { SETTING_DTYPES, type SettingName, settingIssue, settingOf, THEME_CHOICES, } from "./settings" import { acceptsDtype, INPUT_WIDGETS, type Series, seriesOf, WIDGET_LABELS, type WidgetKind, widgetIssue, } from "./widgets" const config = (widget: WidgetDef) => (widget.config ?? {}) as Record const str = (value: unknown) => (value == null ? "" : String(value)) /** Which messages this kind of widget may be pointed at. */ function choicesFor(kind: WidgetKind, catalog: MessageInfo[]): MessageInfo[] { const input = INPUT_WIDGETS.has(kind) return catalog.filter( (message) => acceptsDtype(kind, message.dtype) && // Flows own the namespace; a control can only set what one declares. (!input || message.writable !== false), ) } /** The picker, which records the payload type it bound along with the name. */ function MessagePicker({ kind, value, label, testId, placeholder = "Pick a message", filter, onPick, }: { /** Omitted where the slot is not a widget's at all — a dashboard setting * binds by payload type alone, and hands in `filter` instead. */ kind?: WidgetKind value: string label: string testId?: string placeholder?: string /** What this slot takes, when the widget's own type does not decide it — * a querying chart asks with one shape and draws another. */ filter?: (message: MessageInfo) => boolean onPick: (message: string, dtype: string) => void }) { const { data } = useQuery(messageCatalogQueryOptions()) const catalog = data?.data ?? [] const choices = filter ? catalog.filter(filter) : kind ? choicesFor(kind, catalog) : catalog return (
) } /** Where a chart's lines come from: what the engine kept, or what it asks for. */ const CHART_SOURCES = [ ["live", "Live"], ["query", "Query"], ] as const /** * Pick one of the tile glyphs, or none. * * A grid of the glyphs themselves rather than a list of their names: an icon is * chosen by how it looks. Clearing is a button rather than an option, because * Radix forbids an empty `SelectItem` value — which is why the selects this * replaces could set an icon but never take one back. * * ponytail: no filter field. `ICONS` is a few dozen and the grid shows all of * it without scrolling; add one when the map outgrows a popover. */ function IconPicker({ value, placeholder, label, testId, className, onChange, }: { value: string /** What no icon gets you, on the trigger and on the clearing button. */ placeholder: string /** Names the trigger for screen readers. */ label: string testId?: string className?: string onChange: (icon: string) => void }) { const [open, setOpen] = useState(false) const Current = ICONS[value] return (
{ICON_NAMES.map((name) => { const Glyph = ICONS[name] return ( ) })}
) } /** What a text field was meant to send: a bool, a number, or the text itself. */ function coerce(raw: string): unknown { const asNumber = Number(raw) if (raw === "true" || raw === "false") return raw === "true" return raw !== "" && Number.isFinite(asNumber) ? asNumber : raw } /** * What one widget shows or does. * * The same floating panel the flow editor uses for a node, so the two editors * read as one surface. */ export function WidgetPanel({ widget, onChange, onDelete, onClose, }: { widget: WidgetDef | null onChange: (changes: Partial) => void onDelete: () => void onClose: () => void }) { if (!widget) return null const cfg = config(widget) const isInput = INPUT_WIDGETS.has(widget.type) const issue = widgetIssue(widget) const set = (changes: Record) => onChange({ config: { ...cfg, ...changes } }) const series = seriesOf(widget) const setSeries = (next: Series[]) => set({ series: next }) // A bar's nested readings. An empty row stands in for none, so an unnested // bar still offers the picker rather than only a button. const segments = segmentsOf(widget) const rows: Segment[] = segments.length ? segments : [{}] // Always written as a list; `inner_dtype` belonged to the single binding a // bar carried before it stacked, and goes with it. const setSegments = (next: Segment[]) => set({ inner: next, inner_dtype: undefined }) // The icon widget's mapping. Position is the row's identity, as with series. const rules = (cfg.rules ?? []) as { at?: unknown icon?: string color?: string label?: string }[] const setRules = (next: typeof rules) => set({ rules: next }) // Nothing wrote these until now, so a dropdown's choices were uneditable. const options = (cfg.options ?? []) as { label?: string; value?: unknown }[] const setOptions = (next: typeof options) => set({ options: next }) const querying = cfg.source === "query" // What this chart would refresh at with nothing configured. The viewer can // pick another window on the widget, which moves it. const paced = refreshFor( RANGES.find((range) => range.hours * 3600 === Number(cfg.range_s)) ?? DEFAULT_RANGE, 0, ) return ( onChange({ title })} /> } footer={ } >
{WIDGET_LABELS[widget.type]} {issue ? (

{issue}

) : null} {widget.type === "markdown" ? (
set({ content: event.target.value })} />
) : widget.type === "chart" ? (
set({ source })} /> {querying ? (
message.dtype === "record" && message.writable !== false } onPick={(request, request_dtype) => set({ request, request_dtype }) } /> message.dtype === "series"} onPick={(message, dtype) => set({ message, dtype })} />
) : (
{series.map((entry, index) => (
setSeries( series.map((other, at) => at === index ? { ...other, message, dtype } : other, ), ) } />
setSeries( series.map((other, at) => at === index ? { ...other, label: event.target.value } : other, ), ) } />
))} {series.length < MAX_SERIES ? ( ) : null}
)}
) : // A clock reads the wall; a picker would bind a message nothing reads. widget.type === "clock" ? null : ( message.dtype === COLOR_DTYPES[colorFormatOf(widget)] && message.writable !== false : undefined } onPick={(message, dtype) => set({ [isInput ? "target" : "message"]: message, dtype }) } /> )}
{widget.type === "bar" ? (
{rows.map((segment, index) => (
setSegments( rows.map((other, at) => at === index ? { ...other, message, dtype } : other, ), ) } />
))} {rows.length < MAX_SEGMENTS ? ( ) : null}
) : null} {widget.type === "chart" && !querying ? (
set({ history: { points: Number(event.target.value) || 0 } }) } />

How much past the engine keeps for these messages.

) : null} {widget.type === "chart" && querying ? ( <>
set({ refresh_s: event.target.value === "" ? undefined : Number(event.target.value), }) } />

Empty follows the window — {paced} seconds at this range, since nothing changes until the bucket closes. A slower one is kept, a faster one only asks for the same picture twice.

A viewer can pick another on the widget itself.

) : null} {widget.type === "agenda" || widget.type === "forecast" ? (
set({ count: Number(event.target.value) || 0 }) } />
) : null} {widget.type === "chart" ? (
set({ y_min: event.target.value === "" ? undefined : Number(event.target.value), }) } />
set({ y_max: event.target.value === "" ? undefined : Number(event.target.value), }) } />
set({ y_label: event.target.value })} />
) : null} {widget.type === "stat" || widget.type === "gauge" || widget.type === "chart" || widget.type === "bar" || widget.type === "slider" ? (
set({ unit: event.target.value })} />
) : null} {widget.type === "gauge" || widget.type === "slider" || widget.type === "bar" ? (
set({ min: Number(event.target.value) || 0 }) } />
set({ max: Number(event.target.value) || 0 }) } />
{widget.type === "slider" ? (
set({ step: Number(event.target.value) || 1 }) } />
) : null}
) : null} {widget.type === "button" ? (
set({ value: coerce(event.target.value) })} />
) : null} {widget.type === "dropdown" ? (
Options {options.map((option, index) => (
setOptions( options.map((other, at) => at === index ? { ...other, label: event.target.value } : other, ), ) } /> setOptions( options.map((other, at) => at === index ? { ...other, value: coerce(event.target.value) } : other, ), ) } />
))}
) : null} {widget.type === "icon" ? (
Mapping {rules.map((rule, index) => (
setRules( rules.map((other, at) => at === index ? { ...other, at: coerce(event.target.value) } : other, ), ) } /> setRules( rules.map((other, at) => at === index ? { ...other, icon } : other, ), ) } /> setRules( rules.map((other, at) => at === index ? { ...other, label: event.target.value } : other, ), ) } />
))}

Rows are checked top to bottom and the first match wins. A number also matches anything above it, so a descending ladder reads as thresholds.

set({ icon })} />
) : null} {widget.type === "color" ? (
set({ format, // Both triples are a `list` and hex is a `str`, so a change // between the two shapes takes the binding with it rather // than leaving a message this control can no longer carry. ...(COLOR_DTYPES[format as keyof typeof COLOR_DTYPES] === str(cfg.dtype) ? {} : { target: "", dtype: undefined }), }) } />

HSV is{" "} [h 0-360, s 0-100, v 0-100], RGB [r, g, b] 0-255, Hex{" "} "#rrggbb".

) : null} {widget.type === "switch" || widget.type === "dropdown" ? (
{widget.type === "switch" ? ( set({ style })} /> ) : ( set({ style })} /> )}
) : null}
) } /** Presets are matched on their size, so a custom one simply matches none. */ const sizeKey = (size: { width: number; height: number }) => `${size.width}x${size.height}` /** * The optional half of a setting: which message, if any, drives it. * * Deliberately drawn as an addition rather than a requirement — the placeholder * says what leaving it alone means, and the value control above it is the whole * setting until something is picked here. Binding is how a flow takes the * setting over; a node publishing on a cron is what a schedule is in this * system, so there is no scheduling UI to build. * * The picker records the payload type beside the name, which is what lets the * pairing be judged from the document alone — the same rule a widget's binding * is held to, and the same one the server enforces. */ function SettingBinding({ name, setting, onChange, }: { name: SettingName setting: SettingDef onChange: (setting: SettingDef) => void }) { const want = SETTING_DTYPES[name] const issue = settingIssue(name, setting) return (
message.dtype === want} onPick={(message, dtype) => onChange({ ...setting, message, dtype }) } />
{setting.message ? ( ) : null}
{issue ? (

{issue}

) : null}
) } /** How a setting's own value reads in the "nothing is driving it" line. */ function valueLabel(name: SettingName, value: unknown): string { if (name === "locked") return value === true ? "read-only" : "editable" const chosen = THEME_CHOICES.find(([option]) => option === value) return (chosen?.[1] ?? "System").toLowerCase() } /** * The dashboard's own settings, in the panel its widgets use. * * The canvas is the one that matters: a wall panel is a fixed size, and twelve * columns on a seven-inch screen is a different dashboard than twelve on a * television. */ export function DashboardPanel({ open, dashboard, widgetCount, onChange, onDelete, onClose, }: { open: boolean dashboard: Dashboard widgetCount: number onChange: (changes: Partial) => void onDelete: () => void onClose: () => void }) { const [confirmOpen, setConfirmOpen] = useState(false) const canvas = canvasOf(dashboard) const theme = settingOf(dashboard, "theme") const locked = settingOf(dashboard, "locked") /** Settings are a map, so one of them changing rewrites the whole of it. */ const setSetting = (name: SettingName, setting: SettingDef) => onChange({ settings: { ...(dashboard.settings ?? {}), [name]: setting } }) return ( <> onChange({ title })} /> } footer={ } >
Rail icon onChange({ icon })} />

Drawn on the rail when a panel carries more than one dashboard.

Grid

How many columns wide this dashboard is laid out, so it can be matched to the panel it will hang on.

Canvas
onChange({ canvas_width: Number(event.target.value) || 0 }) } /> onChange({ canvas_height: Number(event.target.value) || 0 }) } />

The panel this is drawn for, in pixels. Editing and viewing both scale that surface to fit, so the arrangement is the same everywhere.

Theme setSetting("theme", { ...theme, value })} /> setSetting("theme", setting)} />

What this dashboard wears wherever it is shown — a screen on a wall has nobody to set the device preference System otherwise follows. Bind a message and a flow drives it instead: a node publishing on a cron is what a schedule looks like here, and the choice above stays the fallback.

Lock
Read-only setSetting("locked", { ...locked, value }) } />
setSetting("locked", setting)} />

Locked, the controls on this dashboard are shown but stop publishing, and the surface says so. It is a read-only surface rather than a permission: what a paired screen may reach is still decided by its own credential.

Contents

{dashboard.name} —{" "} {widgetCount === 0 ? "nothing on it yet." : `${widgetCount} widget${widgetCount === 1 ? "" : "s"}.`}

Delete {dashboard.title || dashboard.name}? This removes the dashboard and its widgets. The flows it read from are untouched, and its history stays in the flow store's git repository. ) }