Files
hamlab/web/src/WidgetPicker.tsx
T

68 lines
3.9 KiB
TypeScript

import { useEffect, useMemo, useState } from 'react'
import { Sensor, fetchCatalog, fmtValue } from './sensors'
import { apiPath } from './api'
import { WIDGET_TYPES, WidgetSpec, WidgetType } from './widgets'
import { Btn, Loading, useEscape } from './ui'
// Pick a sensor from this machine's catalog (or type a pattern) and how to draw it.
export default function WidgetPicker({ onAdd, onClose, initial }: { onAdd: (w: WidgetSpec) => void; onClose: () => void; initial?: WidgetSpec }) {
const [cat, setCat] = useState<Sensor[] | null>(null)
const [err, setErr] = useState('')
const [filter, setFilter] = useState('')
const [sensor, setSensor] = useState(initial?.sensor ?? '')
const [type, setType] = useState<WidgetType>(initial?.type ?? 'stat')
const [title, setTitle] = useState(initial?.title ?? '')
const [bad, setBad] = useState('')
// One bad pattern would 400 the stream every widget on the page shares, so ask the API first.
const add = async () => {
try {
const r = await fetch(apiPath('/api/sensors/query'), { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ w: sensor }) })
if (!r.ok) { setBad((await r.json().catch(() => ({}))).error ?? `the API refused it (${r.status})`); return }
} catch { setBad('could not reach the API'); return }
onAdd({ id: initial?.id ?? 'w' + Date.now().toString(36), type: pattern ? 'list' : type === 'list' ? 'stat' : type, sensor, title: title.trim() || undefined })
}
useEffect(() => { fetchCatalog().then(setCat).catch((e) => setErr(e instanceof Error ? e.message : 'failed')) }, [])
const shown = useMemo(() => {
const f = filter.trim().toLowerCase()
return (cat ?? []).filter((s) => !f || s.id.includes(f) || s.name.toLowerCase().includes(f))
}, [cat, filter])
useEscape(onClose)
const pattern = /[*?[]/.test(sensor)
const pick = (id: string) => { setSensor(id); setBad(''); if (/[*?[]/.test(id)) setType('list') }
return (
<div className="modal-back" onClick={onClose}>
<div className="modal picker" onClick={(e) => e.stopPropagation()}>
<h3>{initial ? 'Edit widget' : 'Add a widget'}</h3>
<input autoFocus value={filter} onChange={(e) => setFilter(e.target.value)} placeholder="filter sensors — cpu, temp, fan, enp3s0…" />
{err && <div className="error">{err}</div>}
{!cat && !err && <Loading label="Reading the catalog…" />}
{cat && (
<div className="picker-list">
{shown.map((s) => (
<button key={s.id} className={'picker-row' + (s.id === sensor ? ' active' : '')} onClick={() => pick(s.id)}>
<span className="mono">{s.id}</span><span className="muted num">{fmtValue(s.value, s.unit)}</span>
</button>
))}
{shown.length === 0 && <div className="muted small" style={{ padding: 8 }}>No sensor matches.</div>}
</div>
)}
<label className="muted">Sensor ID, or a pattern for a list (<span className="mono">fan.*</span>, <span className="mono">cpu.core.*.usage</span>)
<input className="mono" value={sensor} onChange={(e) => pick(e.target.value.trim())} placeholder="cpu.usage" />
</label>
<div className="chips">
{WIDGET_TYPES.filter((t) => !!t.many === pattern).map((t) => <button key={t.id} className={'chip' + (type === t.id ? ' on' : '')} onClick={() => setType(t.id)}>{t.label}</button>)}
</div>
<label className="muted">Title (optional)
<input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="the sensor's own name" />
</label>
{bad && <div className="error">{bad}</div>}
<div className="svc-actions">
<Btn className="btn on" disabled={!sensor} onClick={add}>{initial ? 'Save' : 'Add'}</Btn>
<span className="spacer" />
<button className="btn" onClick={onClose}>Cancel</button>
</div>
</div>
</div>
)
}