Merge remote-tracking branch 'origin/main'
Docs / docs (push) Successful in 20s
Playwright Tests / test-playwright (1, 2) (push) Failing after 4m22s
Playwright Tests / test-playwright (2, 2) (push) Successful in 2m12s
pre-commit / pre-commit (push) Failing after 2m33s
Test Backend / test-backend (3.12) (push) Successful in 5m1s
Test Backend / test-backend (3.14) (push) Successful in 4m52s
Compose Smoke Test / test-compose (push) Successful in 33s
Playwright Tests / merge-reports (push) Successful in 1m32s

This commit is contained in:
Melvin Strobl
2026-10-15 21:17:33 +02:00
210 changed files with 8018 additions and 1237 deletions
@@ -9,7 +9,6 @@ import {
type Position,
setTransform,
} from "react-grid-layout"
import "react-grid-layout/css/styles.css"
import {
type ApiError,
@@ -42,6 +41,7 @@ import { handleError } from "@/utils"
import { DashboardPalette } from "./DashboardPalette"
import {
areaOf,
CanvasGround,
CanvasSurface,
canvasOf,
columnsOf,
@@ -288,6 +288,41 @@ const scaledStrategy = (scale: number) => ({
calcStyle: setTransform as (pos: Position) => CSSProperties,
})
/** Dashboards to step back and forward through, newest last. */
type History = {
past: Dashboard[]
future: Dashboard[]
/** When the last entry was recorded, so a burst of typing stays one edit. */
at: number
}
const HISTORY_LIMIT = 50
const TYPING_WINDOW = 500
/**
* Remember the dashboard as it was before a change.
*
* Fields commit on every keystroke, and the grid writes back its own
* correction a moment after a widget comes or goes, so consecutive edits that
* leave the same widgets in place fold into the entry already on the stack.
* Adding, removing or reordering a widget is a finished action and starts its
* own.
*/
function record(history: History, previous: Dashboard, next: Dashboard) {
const before = widgetsOf(previous)
const after = widgetsOf(next)
const sameWidgets =
before.length === after.length &&
before.every((widget, index) => widget.id === after[index].id)
if (!sameWidgets || Date.now() - history.at >= TYPING_WINDOW) {
history.past.push(previous)
if (history.past.length > HISTORY_LIMIT) history.past.shift()
}
history.at = Date.now()
// A new change is a new branch: what was undone is not coming back.
history.future = []
}
const same = (a: Layout, b: Layout) =>
a.length === b.length &&
a.every((item, index) => {
@@ -349,6 +384,7 @@ export function DashboardEditor({
// 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)
const history = useRef<History>({ past: [], future: [], at: 0 })
useEffect(() => {
version.current = dashboard.version
@@ -369,7 +405,8 @@ export function DashboardEditor({
return request
}
const commit = (next: Dashboard) => {
/** Put a dashboard on the canvas and on its way to the server. */
const apply = (next: Dashboard) => {
setDraft(next)
if (timer.current) clearTimeout(timer.current)
timer.current = setTimeout(() => {
@@ -378,6 +415,25 @@ export function DashboardEditor({
}, AUTOSAVE_MS)
}
/** Apply a change and make it undoable. */
const commit = (next: Dashboard) => {
record(history.current, draft, next)
apply(next)
}
/**
* Step through the history. Undo and redo save like any other edit, so the
* autosave debounce collapses a run of them into one write.
*/
const step = (back: boolean) => {
const { past, future } = history.current
const remembered = (back ? past : future).pop()
if (!remembered) return
;(back ? future : past).push(draft)
history.current.at = 0
apply(remembered)
}
/** Send what is queued and wait for the server to have it. */
const flush = async () => {
if (timer.current) {
@@ -439,10 +495,13 @@ export function DashboardEditor({
setSettingsOpen(true)
}
// As on the flow canvas, and reachable while typing for the same reasons.
// Outside edit mode both keys stay the browser's.
// As on the flow canvas: undo and redo step aside while typing, since a
// field keeps its own, and ⌘P and ⌘S stay reachable for the same reasons.
// Outside edit mode every key stays the browser's.
useShortcuts(
{
"mod+z": () => (edit ? step(true) : false),
"mod+shift+z": () => (edit ? step(false) : false),
"mod+p": () => (edit ? setPaletteOpen((open) => !open) : false),
// An edit still waiting for its autosave counts: publishing flushes it.
"mod+s": () => {
@@ -502,6 +561,11 @@ export function DashboardEditor({
// now falls past its bottom edge drawn under the clip. A round face has no
// grid to fall off.
const clipped = round ? [] : layout.filter((item) => item.y + item.h > rows)
// Editing, the canvas grows to reach them, so they can be dragged back.
const reach =
edit && clipped.length
? Math.max(...clipped.map((item) => item.y + item.h))
: undefined
const shown = Math.max(
0,
widgets.findIndex((widget) => widget.id === (selected ?? face)),
@@ -593,7 +657,8 @@ export function DashboardEditor({
)}
style={root.style}
>
<div className={cn("h-full overflow-y-auto", rail && "pb-20")}>
<CanvasGround dashboard={draft} />
<div className={cn("relative h-full overflow-y-auto", rail && "pb-20")}>
<DashboardView
dashboard={draft}
stacked
@@ -610,7 +675,7 @@ export function DashboardEditor({
) : null}
</div>
) : (
<CanvasSurface dashboard={draft} dots={edit} rail={rail}>
<CanvasSurface dashboard={draft} dots={edit} rail={rail} reach={reach}>
{(scale) =>
!edit ? (
<DashboardView dashboard={draft} rail={hasRail} />
@@ -176,6 +176,7 @@ export function CanvasSurface({
dots,
rail,
touch,
reach,
children,
}: {
dashboard: Dashboard
@@ -185,6 +186,13 @@ export function CanvasSurface({
rail?: React.ReactNode
/** Whether the panel this canvas hangs on is touched rather than pointed at. */
touch?: boolean
/**
* How many grid rows the arrangement reaches down to, while it is being
* arranged. A canvas they fall off grows to reach them, with its own edge
* still drawn, so they can be scrolled to and moved back. The scale stays
* the panel's.
*/
reach?: number
children: (scale: number) => React.ReactNode
}) {
const ref = useRef<HTMLDivElement>(null)
@@ -208,6 +216,17 @@ export function CanvasSurface({
const root = useCanvasRoot(dashboard, touch)
const round = isRound(dashboard)
const area = areaOf(dashboard, Boolean(rail))
// How far past the bottom edge the rows reached go, margin included.
const beyond = reach
? Math.max(
0,
area.top +
reach * rowPitchOf(dashboard, Boolean(rail)) -
GRID_GAP +
GRID_INSET -
height,
)
: 0
// The arrangement, held across the renders that are not about it. This
// component reads the dashboard's own settings, so a bound one wakes it on
// every message the flow sends — and calling a render prop again rebuilds
@@ -219,7 +238,17 @@ export function CanvasSurface({
)
return (
<div ref={ref} className="relative size-full overflow-hidden">
<div
ref={ref}
className={cn(
"relative size-full",
// The gutter is kept, so a scrollbar coming and going cannot change
// the width the scale is measured from.
beyond
? "overflow-x-hidden overflow-y-auto [scrollbar-gutter:stable]"
: "overflow-hidden",
)}
>
{/* Measured first: a guessed scale would place the whole panel once and
then move it. */}
{scale > 0 ? (
@@ -238,7 +267,7 @@ export function CanvasSurface({
{
...root.style,
width,
height,
height: height + beyond,
// Round, nothing outside the circle is drawn.
clipPath: round ? "circle(50%)" : undefined,
left: (box.width - width * scale) / 2,
@@ -255,14 +284,30 @@ export function CanvasSurface({
{/* Full bleed, and under everything: a background covers the
panel, margin included. */}
<CanvasGround dashboard={dashboard} />
{rail}
{beyond ? (
<div
aria-hidden
data-testid="canvas-beyond"
className="canvas-beyond pointer-events-none absolute inset-x-0"
style={{ top: height, height: beyond }}
/>
) : null}
{/* Centred on the panel, not on a canvas grown past it. */}
{rail ? (
<div
className="pointer-events-none absolute inset-x-0 top-0"
style={{ height }}
>
{rail}
</div>
) : null}
<div
className="absolute"
style={{
left: area.left,
top: area.top,
width: area.width,
height: area.height,
height: area.height + beyond,
}}
>
{/* Over the ground rather than under it: the dots are what is
@@ -348,6 +393,7 @@ export function DashboardView({
editing,
onDashboard,
around,
turned,
}: {
dashboard: Dashboard
renderWidget?: (widget: WidgetDef) => React.ReactNode
@@ -362,6 +408,9 @@ export function DashboardView({
* previous (-1), and their names. */
onDashboard?: (by: number) => void
around?: [string | undefined, string | undefined]
/** Which way along a panel's rail it was reached: down (1) or up (-1).
* Its tiles come in from that side. */
turned?: number
}) {
const all = widgetsOf(dashboard)
const round = isRound(dashboard)
@@ -379,15 +428,15 @@ export function DashboardView({
)
}
// Stacked, the arrangement becomes a reading order, so it follows the rows
// the panel shows rather than the order widgets happened to be added in.
const widgets = stacked
? [...all].sort((a, b) => {
const left = placement(a)
const right = placement(b)
return (left.y ?? 0) - (right.y ?? 0) || (left.x ?? 0) - (right.x ?? 0)
})
: all
// In the rows the panel shows rather than the order widgets happened to be
// added in: the reading order a stack follows, and the order tiles arrive
// in. A grid places each one itself, and one nobody arranged has them all
// at 0,0, which the sort leaves as they were.
const widgets = [...all].sort((a, b) => {
const left = placement(a)
const right = placement(b)
return (left.y ?? 0) - (right.y ?? 0) || (left.x ?? 0) - (right.x ?? 0)
})
const columns = columnsOf(dashboard)
const grid = (
@@ -404,11 +453,15 @@ export function DashboardView({
/>
) : (
<WidgetGrid
// Drawn afresh for another dashboard, so its tiles arrive as a page
// rather than all at once under a grid already shown.
key={dashboard.name}
dashboard={dashboard}
widgets={widgets}
columns={columns}
stacked={stacked}
rail={rail}
from={turned !== undefined && turned < 0 ? -1 : 1}
renderWidget={renderWidget}
/>
)}
@@ -435,6 +488,7 @@ function WidgetGrid({
columns,
stacked,
rail,
from,
renderWidget,
}: {
dashboard: Dashboard
@@ -442,6 +496,8 @@ function WidgetGrid({
columns: number
stacked?: boolean
rail?: boolean
/** The side the tiles come in from: below (1) or above (-1). */
from: number
renderWidget?: (widget: WidgetDef) => React.ReactNode
}) {
const { Frame } = useUi()
@@ -451,6 +507,7 @@ function WidgetGrid({
className={cn("widget-grid", stacked && "widget-stacked")}
data-placed={isPlaced(widgets) || undefined}
variants={gridStagger}
custom={from}
initial="hidden"
animate="visible"
style={
@@ -468,6 +525,7 @@ function WidgetGrid({
style={widgetStyle(widget, columns)}
className="widget-cell"
variants={LOOK[look].enter}
custom={from}
transition={LOOK[look].spring}
>
{renderWidget ? (
@@ -2,6 +2,7 @@ import { useCallback } from "react"
import type { Dashboard } from "@/components/Dashboard/DashboardView"
import {
CanvasGround,
CanvasSurface,
DashboardView,
isRound,
@@ -29,6 +30,7 @@ export function PanelSurface({
touch,
onDashboard,
around,
turned,
}: {
dashboard: Dashboard
/** A landscape arrangement scaled onto a phone comes out at about a fifth of
@@ -44,6 +46,9 @@ export function PanelSurface({
* others instead, whose names are `around` it. */
onDashboard?: (by: number) => void
around?: [string | undefined, string | undefined]
/** Which way along the rail this dashboard was reached: down (1) or up
* (-1). */
turned?: number
}) {
const hasRail = Boolean(rail)
const stack = stacked && !isRound(dashboard)
@@ -56,9 +61,10 @@ export function PanelSurface({
rail={hasRail}
onDashboard={onDashboard}
around={around}
turned={turned}
/>
),
[dashboard, hasRail, onDashboard, around],
[dashboard, hasRail, onDashboard, around, turned],
)
return (
<div className="relative size-full">
@@ -67,10 +73,15 @@ export function PanelSurface({
// the look on: this branch mounts what `CanvasSurface` mounts for the
// other one, touch included.
<LookProvider dashboard={dashboard} touch={touch}>
{/* The look's ground, held to the screen while the stack scrolls
over it, as it stays put under a canvas. */}
<div className="pointer-events-none fixed inset-0">
<CanvasGround dashboard={dashboard} />
</div>
{/* Padded here rather than by the route: the stack overflows this
box, so only padding inside the overflow clears the rail. */}
<div className={cn(rail && "pb-24")}>
<DashboardView dashboard={dashboard} stacked />
<div className={cn("relative", rail && "pb-24")}>
<DashboardView dashboard={dashboard} stacked turned={turned} />
</div>
{rail ? (
// No column to spare on a phone, so the rail is a row floating
@@ -1,6 +1,6 @@
import { useMutation, useQuery } from "@tanstack/react-query"
import { Plus, Trash2, X } from "lucide-react"
import { useState } from "react"
import { useEffect, useState } from "react"
import {
type ApiError,
@@ -18,6 +18,7 @@ import {
useSavePanels,
useUnpairPanel,
} from "@/components/Dashboard/queries"
import { qualifiedProblem } from "@/components/Flow/deriveEdges"
import { JsonField } from "@/components/Flow/JsonField"
import { InfoTip, PanelSection } from "@/components/Flow/SidePanel"
import { Button } from "@/components/ui/button"
@@ -49,14 +50,7 @@ const slugify = (value: string) =>
/** Port names the panel firmware knows; `gpio.` takes a pin number. */
// ponytail: free-text ports, no device capability report; add PUT /panels/{id}/device when a second device kind exists
const PORT_SUGGESTIONS = [
"gpio.",
"backlight",
"screen",
"touch",
"mic",
"speaker",
]
const PORT_SUGGESTIONS = ["gpio.", "backlight", "touch", "mic", "speaker"]
const DIRECTIONS = [
["in", "In"],
@@ -67,6 +61,10 @@ const DIRECTIONS = [
const portOf = (value: string) =>
value.toLowerCase().replace(/[^a-z0-9_.]/g, "")
/** A new port the server will take: a name, and a message named with its flow. */
const ready = (port: PanelPort) =>
Boolean(port.port) && qualifiedProblem(port.message) === null
const objectOnly = (value: unknown) =>
value && typeof value === "object" && !Array.isArray(value)
? null
@@ -79,7 +77,7 @@ const objectOnly = (value: unknown) =>
* publish, so it lives in a dialog over the dashboards list instead of a page
* of its own. Every change saves as it is made — there is no form to submit.
*/
export function PanelsDialog() {
export function PanelsDialog({ focus }: { focus?: string } = {}) {
const { data: config } = useQuery(panelsQueryOptions())
const { data: dashboards } = useQuery(dashboardsQueryOptions())
const { user } = useAuth()
@@ -104,6 +102,17 @@ export function PanelsDialog() {
// Reading panels is any account's; every change to them is a superuser's.
const canEdit = Boolean(user?.is_superuser)
const [name, setName] = useState("")
// A port being added, per panel, until it is ready to save. Held here rather
// than in its row: the rows unmount when the dialog closes and this does
// not, so a port still missing its message is there again on reopening.
const [drafts, setDrafts] = useState<Record<string, PanelPort>>({})
const setDraft = (id: string, draft: PanelPort | null) =>
setDrafts((all) => {
const next = { ...all }
if (draft) next[id] = draft
else delete next[id]
return next
})
const panels = config?.panels ?? []
const known = dashboards?.data ?? []
@@ -114,18 +123,53 @@ export function PanelsDialog() {
const host = config?.frontend_host ?? ""
const write = (next: PanelsConfig) =>
save.mutate(next, {
onError: (error) => handleError.call(showErrorToast, error as ApiError),
})
save.mutate(
{ ...next, version: config?.version },
{
onError: (error) =>
(error as ApiError).status === 409
? showErrorToast(
"Someone else changed the panels first. Their version is shown now, so make the change again.",
)
: handleError.call(showErrorToast, error as ApiError),
},
)
const replace = (id: string, panel: PanelDef) =>
write({ panels: panels.map((p) => (p.id === id ? panel : p)) })
// Closing saves every new port that is ready, in one write. Its port field
// only commits on blur, and Escape closes the dialog without one.
const saveDrafts = () => {
const done = Object.keys(drafts).filter((id) => ready(drafts[id]))
if (!done.length) return
for (const id of done) setDraft(id, null)
write({
panels: panels.map((panel) =>
done.includes(panel.id)
? { ...panel, io: [...(panel.io ?? []), drafts[panel.id]] }
: panel,
),
})
}
const newId = slugify(name)
const taken = panels.some((panel) => panel.id === newId)
// Arriving about one panel, from its port on a flow canvas, lands on it.
const focusLoaded = Boolean(config) && Boolean(focus)
useEffect(() => {
if (!focusLoaded) return
document
.querySelector(`[data-testid="panel-${focus}"]`)
?.scrollIntoView({ block: "start" })
}, [focusLoaded, focus])
return (
<DialogContent className="max-h-[80vh] overflow-y-auto sm:max-w-lg">
<DialogContent
className="max-h-[80vh] overflow-y-auto sm:max-w-lg"
onCloseAutoFocus={saveDrafts}
>
<DialogHeader>
<DialogTitle>Panels</DialogTitle>
<DialogDescription>
@@ -145,6 +189,9 @@ export function PanelsDialog() {
<PanelRow
key={panel.id}
panel={panel}
focused={panel.id === focus}
draft={drafts[panel.id] ?? null}
onDraft={(draft) => setDraft(panel.id, draft)}
host={host}
remoteHost={remoteHost}
canEdit={canEdit}
@@ -210,6 +257,9 @@ export function PanelsDialog() {
function PanelRow({
panel,
focused,
draft,
onDraft,
host,
remoteHost,
canEdit,
@@ -218,6 +268,11 @@ function PanelRow({
onRemove,
}: {
panel: PanelDef
/** The one a link arrived about, marked so it is found at a glance. */
focused: boolean
/** A port being added to it, held by the dialog. */
draft: PanelPort | null
onDraft: (draft: PanelPort | null) => void
/** Where this instance answers, as it knows itself. */
host: string
/** Where the portal serves this instance, when it is enrolled. */
@@ -287,7 +342,14 @@ function PanelRow({
: `Remove ${panel.id}`
return (
<div className="grid gap-3" data-testid={`panel-${panel.id}`}>
<div
className={cn(
"grid scroll-mt-2 gap-3",
// An outline rather than a border, so the row does not shift.
focused && "rounded-md outline-2 outline-offset-4 outline-primary/40",
)}
data-testid={`panel-${panel.id}`}
>
<div className="flex items-center gap-2">
<Input
value={panel.title}
@@ -390,7 +452,13 @@ function PanelRow({
</div>
)}
<PanelIo panel={panel} canEdit={canEdit} onChange={onChange} />
<PanelIo
panel={panel}
canEdit={canEdit}
draft={draft}
onDraft={onDraft}
onChange={onChange}
/>
<div className="grid gap-2">
<Input
@@ -496,26 +564,30 @@ function PanelRow({
* The device's own inputs and outputs, each wired to a message.
*
* Every change saves as it is made, like the rest of the dialog. A new port
* is held here until it has both a name and a message, since the server
* refuses a port without either.
* is held by the dialog until it has a name and a qualified message, since
* the server refuses a port without either, and closing the dialog saves one
* that has both.
*/
function PanelIo({
panel,
canEdit,
draft,
onDraft,
onChange,
}: {
panel: PanelDef
canEdit: boolean
draft: PanelPort | null
onDraft: (draft: PanelPort | null) => void
onChange: (next: PanelDef) => void
}) {
const io = panel.io ?? []
const [draft, setDraft] = useState<PanelPort | null>(null)
const listId = `ports-${panel.id}`
const write = (next: PanelPort[]) => onChange({ ...panel, io: next })
const keepDraft = (next: PanelPort) => {
if (!next.port || !next.message) return setDraft(next)
setDraft(null)
if (!ready(next)) return onDraft(next)
onDraft(null)
write([...io, next])
}
@@ -553,7 +625,8 @@ function PanelIo({
listId={listId}
testId={`io-${panel.id}-new`}
onChange={keepDraft}
onRemove={() => setDraft(null)}
onType={(port) => onDraft({ ...draft, port })}
onRemove={() => onDraft(null)}
/>
) : null}
{canEdit && !draft ? (
@@ -562,7 +635,7 @@ function PanelIo({
size="sm-touch"
className="justify-self-start"
data-testid={`add-port-${panel.id}`}
onClick={() => setDraft({ port: "", message: "", direction: "in" })}
onClick={() => onDraft({ port: "", message: "", direction: "in" })}
>
<Plus />
Add port
@@ -578,6 +651,7 @@ function IoRow({
listId,
testId,
onChange,
onType,
onRemove,
}: {
row: PanelPort
@@ -585,26 +659,44 @@ function IoRow({
listId: string
testId: string
onChange: (next: PanelPort) => void
/**
* A new port's name as it is typed, so closing the dialog before the field
* blurs still finds it. A saved port commits on blur instead.
*/
onType?: (port: string) => void
onRemove: () => void
}) {
const name = row.port || "new port"
const problem = row.message ? qualifiedProblem(row.message) : null
return (
<div className="grid gap-2" data-testid={testId}>
<div className="flex items-center gap-2">
<Input
// Remounted with whatever was saved, so a refused name snaps back.
key={row.port}
defaultValue={row.port}
placeholder="Port, e.g. gpio.4"
aria-label={`Port of ${name}`}
autoComplete="off"
list={listId}
onBlur={(event) => {
const port = portOf(event.currentTarget.value)
event.currentTarget.value = port || row.port
if (port && port !== row.port) onChange({ ...row, port })
}}
/>
{onType ? (
<Input
value={row.port}
placeholder="Port, e.g. gpio.4"
aria-label={`Port of ${name}`}
autoComplete="off"
list={listId}
onChange={(event) => onType(portOf(event.currentTarget.value))}
onBlur={() => onChange(row)}
/>
) : (
<Input
// Remounted with whatever was saved, so a refused name snaps back.
key={row.port}
defaultValue={row.port}
placeholder="Port, e.g. gpio.4"
aria-label={`Port of ${name}`}
autoComplete="off"
list={listId}
onBlur={(event) => {
const port = portOf(event.currentTarget.value)
event.currentTarget.value = port || row.port
if (port && port !== row.port) onChange({ ...row, port })
}}
/>
)}
<div className="shrink-0">
<Segmented
value={row.direction}
@@ -654,6 +746,7 @@ function IoRow({
}
/>
</div>
{problem ? <p className="text-xs text-destructive">{problem}</p> : null}
</div>
)
}
@@ -15,6 +15,7 @@ import type { WidgetDef } from "@/client"
import { slotsFor } from "@/components/Common/UplotChart"
import { duration, fadeIn } from "@/lib/motion"
import { useShortcuts } from "@/lib/shortcuts"
import { cn } from "@/lib/utils"
import { useClock } from "./ClockWidget"
import type { Dashboard } from "./DashboardView"
import { useBoundValue, useBoundValues } from "./dataContext"
@@ -40,7 +41,7 @@ import {
text,
} from "./ui/core/config"
import { TESTID } from "./ui/core/contract"
import { useLook } from "./ui/core/look"
import { LookProvider, useCanvasRoot, useLook } from "./ui/core/look"
import { LOOK } from "./ui/core/motion"
import {
ANNOUNCE_MS,
@@ -334,12 +335,7 @@ export function RoundPanel({
return (
// Keyed by name, so a neighbour becomes the one shown, and back,
// without being drawn afresh: its own face memory and all.
<div
key={page.name}
className="absolute inset-0"
style={{ translate: `0 ${at * size}px` }}
inert={at !== 0}
>
<TrackPage key={page.name} dashboard={page} at={at} size={size}>
<PaletteProvider dashboard={page}>
{editing ? (
view
@@ -347,13 +343,52 @@ export function RoundPanel({
<LockedProvider dashboard={page}>{view}</LockedProvider>
)}
</PaletteProvider>
</div>
</TrackPage>
)
})}
</motion.div>
)
}
/**
* One dashboard on a round panel's track, in its own look.
*
* The canvas states the look, theme and palette of the dashboard shown, so a
* neighbour beside it, or the one a turn is leaving, would wear those too.
* Each page restates its own instead. The ground stays the canvas's, which
* changes over as soon as the turn begins.
*/
function TrackPage({
dashboard,
at,
size,
children,
}: {
dashboard: Dashboard
/** Its place on the track, in screens from the one shown. */
at: number
size: number
children: React.ReactNode
}) {
// Touch belongs to the screen, so it is the canvas's whichever page this is.
const { touch } = useLook()
const root = useCanvasRoot(dashboard, touch)
return (
<LookProvider dashboard={dashboard} touch={touch}>
<div
data-look={root["data-look"]}
data-touch={root["data-touch"]}
data-palette={root["data-palette"]}
className={cn("absolute inset-0 text-foreground", root.className)}
style={{ ...root.style, translate: `0 ${at * size}px` }}
inert={at !== 0}
>
{children}
</div>
</LookProvider>
)
}
/** A dashboard's icon and title: what a panel shows for a moment of a
* dashboard it has just landed on. Opaque, so the face under it does not
* read through the name. */
@@ -19,6 +19,21 @@
background-position: -1px -1px;
}
/*
* Below the panel's bottom edge, while the editor has grown the canvas to
* reach widgets that fell off it: hatched, under a dashed line where the panel
* ends, so what it will not show reads as outside it.
*/
.canvas-beyond {
border-top: 3px dashed
color-mix(in srgb, var(--muted-foreground) 70%, transparent);
background: repeating-linear-gradient(
-45deg,
color-mix(in srgb, var(--muted-foreground) 14%, transparent) 0 3px,
transparent 3px 16px
);
}
/*
* View mode's grid. Column count is per dashboard (`--widget-cols`), so a wall
* panel can be matched to its own width. It does not reflow: the grid lives on
+12 -1
View File
@@ -1,6 +1,7 @@
import { useMutation, useQueryClient } from "@tanstack/react-query"
import {
ApiError,
type DashboardDef_Input,
DashboardsService,
MessagesService,
@@ -55,7 +56,13 @@ export const panelQueryOptions = (id: string) => ({
queryFn: () => PanelsService.readPanel({ panelId: id }),
})
/** Replace the panels. Superuser-only on the server. */
/**
* Replace the panels, carrying the version they were read at. Superuser-only
* on the server.
*
* A 409 means someone else saved first, so the list is read again and the
* next change is based on theirs.
*/
export function useSavePanels() {
const queryClient = useQueryClient()
return useMutation({
@@ -65,6 +72,10 @@ export function useSavePanels() {
queryClient.setQueryData(panelKeys.all, saved)
queryClient.invalidateQueries({ queryKey: panelKeys.all })
},
onError: (error) => {
if (error instanceof ApiError && error.status === 409)
queryClient.invalidateQueries({ queryKey: panelKeys.all })
},
})
}
@@ -139,8 +139,9 @@ export function useDashboardBackground(
* The class that themes a dashboard's own surface, or `""` to follow the app.
*
* A class rather than the root, because inside the app shell this must not
* flip the chrome around it. `.light` and `.dark` both redefine the tokens on
* whatever carries them (`index.css`), so either direction works on a subtree.
* flip the chrome around it. `.theme-light` and `.theme-dark` both redefine the
* tokens on whatever carries them (`index.css`), and `dark:` follows the
* nearest of them, so either direction works on a subtree.
*
* A palette decides this for itself: its first colour *is* the ground, so
* whether the surface is light or dark is a fact about the palette rather than
@@ -425,7 +425,7 @@
);
--dui-reading: var(--foreground);
--dui-reading-reached: var(--primary-foreground);
--dui-reading-on-handle: var(--foreground);
--dui-reading-on-handle: var(--dui-on-handle, var(--foreground));
}
/*
@@ -576,8 +576,9 @@
outline-offset: 2px;
}
/* The rail comes before the input, so no sibling selector reaches it. */
.dui-slider-input:disabled ~ .dui-slider-thumb,
.dui-slider-input:disabled ~ .dui-slider-rail {
.dui-slider:has(.dui-slider-input:disabled) .dui-slider-rail {
opacity: 0.45;
}
@@ -716,6 +717,12 @@
line-height: 1.35;
}
/* A press is a disc of a fixed size, as tall as the body, so there is no text
to clip and its shadow falls outside the body by design. */
.dui-face-body:has(> .dui-face-press) {
overflow: visible;
}
.dui-face-body .dui-clock {
font-size: 72px;
line-height: 1;
@@ -784,6 +791,47 @@
outline: none;
}
/*
* The ring's paint. Each look states it on its root as these variables rather
* than in rules under `[data-look]`: a round panel draws a dashboard beside
* one in another look, and a descendant rule would reach into both, where an
* inherited value stops at the nearer root. Reset on every root, so a look
* that leaves one out takes the fallback rather than the outer root's.
*/
:where([data-look]) {
--dui-ring-track: initial;
--dui-ring-glow: initial;
--dui-ring-handle: initial;
--dui-ring-handle-edge: initial;
--dui-ring-handle-edge-width: initial;
--dui-ring-handle-shadow: initial;
--dui-ring-swatch: initial;
--dui-ring-swatch-width: initial;
--dui-on-handle: initial;
}
.dui-ring-track {
stroke: var(--dui-ring-track, var(--muted));
}
.dui-ring-fill {
stroke: var(--primary);
filter: var(--dui-ring-glow, none);
}
.dui-ring-handle {
fill: var(--dui-ring-handle, var(--primary));
stroke: var(--dui-ring-handle-edge, none);
stroke-width: var(--dui-ring-handle-edge-width, 0);
filter: var(--dui-ring-handle-shadow, none);
}
/* A colour's handle is filled with the colour, so only its edge is the look's. */
.dui-ring-swatch {
stroke: var(--dui-ring-swatch, var(--card));
stroke-width: var(--dui-ring-swatch-width, 3px);
}
.dui-ring-hit {
pointer-events: stroke;
cursor: pointer;
@@ -6,9 +6,10 @@
* below reads them from there: the tokens by inheritance, the look and the
* touch flag through this context.
*
* The style is carried in the context as well as on the element, because a
* menu is portalled to `body` and lands outside the canvas. A surface that
* floats out of the tree re-states the tokens rather than borrowing the app's.
* The style and the theme class are carried in the context as well as on the
* element, because a menu is portalled to `body` and lands outside the canvas.
* A surface that floats out of the tree re-states them rather than borrowing
* the app's.
*/
import { createContext, useContext, useMemo } from "react"
@@ -28,6 +29,8 @@ type Canvas = {
touch: boolean
/** The palette's tokens, or `{}` when the dashboard names none. */
style: React.CSSProperties
/** The theme scope class, `theme-light` or `theme-dark`. */
theme: string
}
/** A dashboard that names no palette, as one object rather than one per render. */
@@ -37,6 +40,7 @@ const LookContext = createContext<Canvas>({
look: "material",
touch: false,
style: {},
theme: "",
})
/** The look everything under here is drawn in. */
@@ -46,10 +50,10 @@ export const useLook = () => useContext(LookContext)
* What the canvas root carries: the theme class, the palette, and the two
* attributes the looks' stylesheets key off.
*
* The class is always resolved to `light` or `dark`, rather than left empty
* for a dashboard that follows the device: the sets state their own colours
* per theme, and a chart canvas has to be told which one it is drawing in.
* Restating the app's own resolved theme changes nothing when they agree.
* The class is always resolved to `theme-light` or `theme-dark`, rather than
* left empty for a dashboard that follows the device: the sets state their own
* colours per theme, and a chart canvas has to be told which one it is drawing
* in. Restating the app's own resolved theme changes nothing when they agree.
*
* `touch` is passed in rather than read off the document, because it belongs to
* the screen rather than to the dashboard: the same document may hang on a
@@ -73,7 +77,7 @@ export function useCanvasRoot(
[roles],
)
return {
className: stated || (resolvedTheme === "dark" ? "dark" : "light"),
className: `theme-${stated || resolvedTheme}`,
style,
"data-look": look,
"data-touch": touch ? "" : undefined,
@@ -101,13 +105,13 @@ export function LookProvider({
const root = useCanvasRoot(dashboard, touch)
const look = root["data-look"]
const touched = root["data-touch"] !== undefined
const { style } = root
const { style, className: theme } = root
// A bound setting wakes this component on every message its flow sends, and
// what the widgets below actually react to is the value — so it changes only
// when one of the three things it carries does.
// when one of the four things it carries does.
const value = useMemo(
() => ({ look, touch: touched, style }),
[look, touched, style],
() => ({ look, touch: touched, style, theme }),
[look, touched, style, theme],
)
return <LookContext.Provider value={value}>{children}</LookContext.Provider>
}
@@ -21,7 +21,8 @@ import type { Look } from "../../settings"
type LookMotion = {
spring: Transition
/** How a widget arrives on the canvas. */
/** How a widget arrives on the canvas. `custom` is the side it comes from,
* as `gridStagger` takes it. */
enter: Variants
/** Seconds for one round of the ambient ground; 0 draws none. */
drift: number
@@ -34,7 +35,7 @@ export const LOOK: Record<Look, LookMotion> = {
// the way the rest of the product does.
spring: { type: "spring", stiffness: 420, damping: 34, mass: 1 },
enter: {
hidden: { opacity: 0, y: 8 },
hidden: (from = 1) => ({ opacity: 0, y: 8 * from }),
visible: { opacity: 1, y: 0 },
},
drift: 0,
@@ -42,7 +43,7 @@ export const LOOK: Record<Look, LookMotion> = {
material: {
spring: { type: "spring", stiffness: 550, damping: 38, mass: 1 },
enter: {
hidden: { opacity: 0, y: 8 },
hidden: (from = 1) => ({ opacity: 0, y: 8 * from }),
visible: { opacity: 1, y: 0 },
},
drift: 0,
@@ -50,15 +51,23 @@ export const LOOK: Record<Look, LookMotion> = {
glass: {
spring: { type: "spring", stiffness: 320, damping: 22, mass: 0.8 },
enter: {
hidden: { opacity: 0, y: 12, scale: 0.96 },
hidden: (from = 1) => ({ opacity: 0, y: 12 * from, scale: 0.96 }),
visible: { opacity: 1, y: 0, scale: 1 },
},
drift: 46,
},
}
/** Widgets arrive as a page rather than all at once. */
/**
* Widgets arrive as a page rather than all at once, row by row.
*
* `custom` is the side they come from: below (1), as a round panel's next
* dashboard rises, or above (-1) for one further up a panel's rail, which
* brings the last row in first.
*/
export const gridStagger: Variants = {
hidden: {},
visible: { transition: { staggerChildren: 0.03 } },
visible: (from = 1) => ({
transition: { staggerChildren: 0.03, staggerDirection: from < 0 ? -1 : 1 },
}),
}
@@ -121,7 +121,7 @@ assert.deepEqual(
)
assert.deepEqual(
rolesOf(["#0a0a0a"])?.series.slice(1),
slots(block(".dark {")),
slots(block(".theme-dark {")),
"a dark dashboard continues with the dark --chart-2…8",
)
@@ -10,7 +10,7 @@
*
* The result is written onto the canvas as the plain token variables the app
* already themes with (`--background`, `--card`, `--primary`, …), which is the
* same mechanism `.light` and `.dark` use on a subtree. Nothing here touches
* same mechanism `.theme-light` and `.theme-dark` use on a subtree. Nothing here touches
* `index.css`: that file's token blocks are byte-identical with the website's
* and `make design-check` holds them there.
*
@@ -154,8 +154,10 @@ export function Select({
onChange,
}: SelectProps) {
// The menu is portalled to `body`, which is outside the canvas — so it
// re-states the dashboard's own colours rather than borrowing the app's.
const { style } = useLook()
// re-states the dashboard's own theme, colours and look rather than
// borrowing the app's. The look carries the variables its menu is painted
// with: without it a glass menu has no blur, and the tile under it shows.
const { style, theme, look } = useLook()
return (
<SelectPrimitive.Root
value={value}
@@ -178,7 +180,11 @@ export function Select({
position="popper"
sideOffset={4}
style={style}
className="fx-menu z-50 max-h-64 min-w-[var(--radix-select-trigger-width)] overflow-y-auto p-1 data-[state=open]:animate-in data-[state=open]:zoom-in-95 data-[state=open]:fade-in-0"
data-look={look}
className={cn(
theme,
"fx-menu z-50 max-h-64 min-w-[var(--radix-select-trigger-width)] overflow-y-auto p-1 data-[state=open]:animate-in data-[state=open]:zoom-in-95 data-[state=open]:fade-in-0",
)}
>
<SelectPrimitive.Viewport>
{options.map((option) => (
@@ -31,13 +31,14 @@ export function Readout({
}: ReadoutProps) {
const { label, numeric } = useAnimatedNumber(value, precision)
return (
<span data-testid="readout" className="flex min-w-0 items-baseline gap-1.5">
<span
className={cn(
"min-w-0 truncate",
size === "hero" ? "dui-hero" : "tabular-nums",
)}
>
<span
data-testid="readout"
className={cn(
"flex min-w-0 items-baseline gap-1.5",
size === "hero" && "dui-hero",
)}
>
<span className="min-w-0 truncate tabular-nums">
{numeric ? (
<motion.span>{label}</motion.span>
) : (
@@ -21,6 +21,12 @@
[data-look="fluksio"] {
--fx-radius: var(--radius-lg);
--fx-field: var(--radius-md);
/* A round face's ring (`core.css`): the slider's handle, a ring of primary
around the page colour. */
--dui-ring-handle: var(--background);
--dui-ring-handle-edge: var(--primary);
--dui-ring-handle-edge-width: 2px;
--dui-ring-handle-shadow: drop-shadow(0 1px 2px rgb(0 0 0 / 0.2));
}
/* --- surfaces ------------------------------------------------------------ */
@@ -315,26 +321,3 @@
outline: none;
box-shadow: 0 0 0 3px color-mix(in srgb, var(--ring) 50%, transparent);
}
/* --- a round dashboard's ring -------------------------------------------- */
[data-look="fluksio"] .dui-ring-track {
stroke: var(--muted);
}
[data-look="fluksio"] .dui-ring-fill {
stroke: var(--primary);
}
/* The slider's handle: a ring of primary around the page colour. */
[data-look="fluksio"] .dui-ring-handle {
fill: var(--background);
stroke: var(--primary);
stroke-width: 2px;
filter: drop-shadow(0 1px 2px rgb(0 0 0 / 0.2));
}
[data-look="fluksio"] .dui-ring-swatch {
stroke: var(--card);
stroke-width: 3px;
}
@@ -172,8 +172,10 @@ export function Select({
onChange,
}: SelectProps) {
// The menu is portalled to `body`, which is outside the canvas — so it
// re-states the dashboard's own colours rather than borrowing the app's.
const { style } = useLook()
// re-states the dashboard's own theme, colours and look rather than
// borrowing the app's. The look carries the variables its menu is painted
// with: without it a glass menu has no blur, and the tile under it shows.
const { style, theme, look } = useLook()
return (
<SelectPrimitive.Root
value={value}
@@ -200,7 +202,11 @@ export function Select({
position="popper"
sideOffset={4}
style={style}
className="gl-menu z-50 max-h-64 min-w-[var(--radix-select-trigger-width)] overflow-y-auto p-1 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95"
data-look={look}
className={cn(
theme,
"gl-menu z-50 max-h-64 min-w-[var(--radix-select-trigger-width)] overflow-y-auto p-1 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
)}
>
<SelectPrimitive.Viewport>
{options.map((option) => (
@@ -30,13 +30,14 @@ export function Readout({
}: ReadoutProps) {
const { label, numeric } = useAnimatedNumber(value, precision)
return (
<span data-testid="readout" className="flex min-w-0 items-baseline gap-1.5">
<span
className={cn(
"min-w-0 truncate",
size === "hero" ? "dui-hero" : "tabular-nums",
)}
>
<span
data-testid="readout"
className={cn(
"flex min-w-0 items-baseline gap-1.5",
size === "hero" && "dui-hero",
)}
>
<span className="min-w-0 truncate tabular-nums">
{numeric ? (
<motion.span>{label}</motion.span>
) : (
@@ -26,9 +26,23 @@
--gl-radius: 1.25rem;
--gl-track: rgb(255 255 255 / 0.16);
--gl-blob-opacity: 0.5;
/* A round face's press, which has no card behind it. See below. */
--gl-press: var(--gl-bg);
--gl-press-shadow: var(--gl-inset);
/* A round face's ring (`core.css`): lit, as the gauge's arc is, under a
white handle, which a reading's dot on it shows dark against. */
--dui-ring-track: var(--gl-track);
--dui-ring-glow: drop-shadow(0 0 4px var(--primary));
--dui-ring-handle: #fff;
--dui-ring-handle-edge: var(--gl-border);
--dui-ring-handle-edge-width: 1px;
--dui-ring-handle-shadow: drop-shadow(0 2px 8px rgb(0 0 0 / 0.35));
--dui-ring-swatch: rgb(255 255 255 / 0.85);
--dui-ring-swatch-width: 2px;
--dui-on-handle: rgb(0 0 0 / 0.75);
}
[data-look="glass"].light {
[data-look="glass"].theme-light {
--gl-bg: rgb(255 255 255 / 0.5);
--gl-bg-strong: rgb(255 255 255 / 0.7);
--gl-border: rgb(255 255 255 / 0.75);
@@ -37,6 +51,8 @@
--gl-track: rgb(0 0 0 / 0.1);
/* Diluted by the white it mixes into, so it takes more of it to show. */
--gl-blob-opacity: 0.6;
--gl-press: color-mix(in srgb, var(--primary) 14%, rgb(255 255 255 / 0.85));
--gl-press-shadow: var(--gl-shadow), var(--gl-inset);
}
/* --- the ground ---------------------------------------------------------- */
@@ -238,6 +254,19 @@
pointer-events: none;
}
/*
* A Switch's or a Button's face on a round dashboard is one large press with
* only the ground behind it. A tile's button has a card for contrast; this has
* none, so in light the white wash all but disappears into the ground. The
* look's root states the press's own wash, so a dashboard keeps its own when
* a round panel draws it beside one in another look or theme.
*/
.dui-face-press
> .gl-button:not([data-variant="filled"], [aria-pressed="true"]) {
background: var(--gl-press);
box-shadow: var(--gl-press-shadow);
}
.gl-switch {
position: relative;
display: inline-flex;
@@ -415,32 +444,3 @@
outline: 2px solid var(--ring);
outline-offset: 2px;
}
/* --- a round dashboard's ring -------------------------------------------- */
[data-look="glass"] .dui-ring-track {
stroke: var(--gl-track);
}
/* Lit, as the gauge's arc is. */
[data-look="glass"] .dui-ring-fill {
stroke: var(--primary);
filter: drop-shadow(0 0 4px var(--primary));
}
[data-look="glass"] .dui-ring-handle {
fill: #fff;
stroke: var(--gl-border);
stroke-width: 1px;
filter: drop-shadow(0 2px 8px rgb(0 0 0 / 0.35));
}
/* A reading's dot on the handle, which is white here in either theme. */
[data-look="glass"] :is(.dui-ring, .dui-slider) {
--dui-reading-on-handle: rgb(0 0 0 / 0.75);
}
[data-look="glass"] .dui-ring-swatch {
stroke: rgb(255 255 255 / 0.85);
stroke-width: 2px;
}
@@ -199,8 +199,10 @@ export function Select({
onChange,
}: SelectProps) {
// The menu is portalled to `body`, which is outside the canvas — so it
// re-states the dashboard's own colours rather than borrowing the app's.
const { style } = useLook()
// re-states the dashboard's own theme, colours and look rather than
// borrowing the app's. The look carries the variables its menu is painted
// with: without it a glass menu has no blur, and the tile under it shows.
const { style, theme, look } = useLook()
return (
<SelectPrimitive.Root
value={value}
@@ -226,7 +228,11 @@ export function Select({
position="popper"
sideOffset={4}
style={style}
className="m3-menu z-50 max-h-64 min-w-[var(--radix-select-trigger-width)] overflow-y-auto p-1 data-[state=open]:animate-in data-[state=open]:zoom-in-95 data-[state=open]:fade-in-0"
data-look={look}
className={cn(
theme,
"m3-menu z-50 max-h-64 min-w-[var(--radix-select-trigger-width)] overflow-y-auto p-1 data-[state=open]:animate-in data-[state=open]:zoom-in-95 data-[state=open]:fade-in-0",
)}
>
<SelectPrimitive.Viewport>
{options.map((option) => (
@@ -29,13 +29,14 @@ export function Readout({
}: ReadoutProps) {
const { label, numeric } = useAnimatedNumber(value, precision)
return (
<span data-testid="readout" className="flex min-w-0 items-baseline gap-1.5">
<span
className={cn(
"min-w-0 truncate",
size === "hero" ? "dui-hero" : "tabular-nums",
)}
>
<span
data-testid="readout"
className={cn(
"flex min-w-0 items-baseline gap-1.5",
size === "hero" && "dui-hero",
)}
>
<span className="min-w-0 truncate tabular-nums">
{numeric ? (
<motion.span>{label}</motion.span>
) : (
@@ -23,6 +23,7 @@ import type {
RailProps,
} from "../core/contract"
import { railGeometry, TESTID } from "../core/contract"
import { useLook } from "../core/look"
import { LOOK } from "../core/motion"
/** Material's ground is the surface colour itself; only an image is drawn. */
@@ -39,6 +40,8 @@ export function Backdrop({ image }: BackdropProps) {
}
function Issue({ issue }: { issue: string }) {
// Portalled to `body`, so it re-states the dashboard's theme and colours.
const { style, theme } = useLook()
return (
<Tooltip>
<TooltipTrigger asChild>
@@ -49,7 +52,12 @@ function Issue({ issue }: { issue: string }) {
data-testid={TESTID.issue}
/>
</TooltipTrigger>
<TooltipContent className="max-w-xs break-words">{issue}</TooltipContent>
<TooltipContent
className={cn(theme, "max-w-xs break-words")}
style={style}
>
{issue}
</TooltipContent>
</Tooltip>
)
}
@@ -19,6 +19,10 @@
--m3-sc: color-mix(in oklab, var(--primary) 22%, var(--card));
--m3-outline: var(--border);
--m3-radius: 1rem;
/* A round face's ring (`core.css`): a tonal track under a primary handle,
which a reading's dot on it shows light against. */
--dui-ring-track: var(--m3-sc);
--dui-on-handle: var(--primary-foreground);
}
/* --- surfaces ----------------------------------------------------------- */
@@ -319,27 +323,3 @@
outline: 2px solid var(--primary);
outline-offset: 2px;
}
/* --- a round dashboard's ring -------------------------------------------- */
[data-look="material"] .dui-ring-track {
stroke: var(--m3-sc);
}
[data-look="material"] .dui-ring-fill {
stroke: var(--primary);
}
[data-look="material"] .dui-ring-handle {
fill: var(--primary);
}
/* A reading's dot on the handle, which is primary here. */
[data-look="material"] :is(.dui-ring, .dui-slider) {
--dui-reading-on-handle: var(--primary-foreground);
}
[data-look="material"] .dui-ring-swatch {
stroke: var(--card);
stroke-width: 3px;
}