@dashspec/renderer 0.1.4 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -115,7 +115,7 @@ import {
115
115
  translator,
116
116
  validateDocument,
117
117
  widgetChecks
118
- } from "./chunk-2HHYJ5WX.js";
118
+ } from "./chunk-7J6WHLG6.js";
119
119
  import {
120
120
  createStateProxy,
121
121
  getPath,
@@ -1644,6 +1644,12 @@ function themeCssVars(theme, mode) {
1644
1644
  out["--ds-control-height"] = `${d.control}px`;
1645
1645
  out["--ds-density"] = density;
1646
1646
  flatten("--ds-radius", s.radius, out, "px");
1647
+ out["--ds-chip-radius"] = `${s.chip?.radius ?? 6}px`;
1648
+ out["--ds-chip-border"] = `${s.chip?.border ?? 1}px`;
1649
+ out["--ds-chip-weight"] = String(s.chip?.weight ?? 600);
1650
+ out["--ds-chip-padding-x"] = `${s.chip?.paddingX ?? 8}px`;
1651
+ out["--ds-chip-height"] = `${s.chip?.height ?? 22}px`;
1652
+ out["--ds-chip-font-size"] = `${s.chip?.fontSize ?? 11}px`;
1647
1653
  flatten("--ds-shadow", s.shadow, out);
1648
1654
  flatten("--ds-z", s.z, out);
1649
1655
  out["--ds-motion-fast"] = `${s.motion.fast}ms`;
@@ -3519,1494 +3525,1499 @@ function InfoTip({ text }) {
3519
3525
  );
3520
3526
  }
3521
3527
 
3522
- // src/widgets/shared/motion.ts
3523
- import { useEffect as useEffect3, useRef as useRef5, useState as useState4 } from "react";
3524
- var reduced = () => typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
3525
- var easeOut = (t) => 1 - (1 - t) ** 3;
3526
- function useCountUp(target, ms = 700) {
3527
- const [shown, setShown] = useState4(() => typeof target === "number" && !reduced() ? 0 : target);
3528
- const from = useRef5(0);
3529
- useEffect3(() => {
3530
- if (typeof target !== "number" || !Number.isFinite(target) || reduced()) {
3531
- setShown(target);
3532
- return;
3533
- }
3534
- const start = performance.now();
3535
- const a = from.current;
3536
- let raf = 0;
3537
- const step = (now) => {
3538
- const t = Math.min(1, (now - start) / ms);
3539
- const v = a + (target - a) * easeOut(t);
3540
- setShown(Number.isInteger(target) && t === 1 ? target : v);
3541
- if (t < 1) raf = requestAnimationFrame(step);
3542
- else from.current = target;
3543
- };
3544
- raf = requestAnimationFrame(step);
3545
- return () => {
3546
- cancelAnimationFrame(raf);
3547
- from.current = typeof target === "number" ? target : 0;
3548
- };
3549
- }, [target, ms]);
3550
- return shown;
3528
+ // src/widgets/shared/clickable.ts
3529
+ import { useContext as useContext4 } from "react";
3530
+
3531
+ // src/components/PanelFrame.tsx
3532
+ import { useCallback as useCallback4, useEffect as useEffect3, useId as useId3, useMemo as useMemo3, useRef as useRef5, useState as useState4 } from "react";
3533
+
3534
+ // src/widgets/parseProps.ts
3535
+ function without(value, path) {
3536
+ if (path.length === 0 || value === null || typeof value !== "object") return value;
3537
+ const [head, ...rest] = path;
3538
+ if (Array.isArray(value)) {
3539
+ if (typeof head !== "number" || head < 0 || head >= value.length) return value;
3540
+ const copy2 = [...value];
3541
+ if (rest.length === 0) copy2.splice(head, 1);
3542
+ else copy2[head] = without(copy2[head], rest);
3543
+ return copy2;
3544
+ }
3545
+ if (!Object.hasOwn(value, head)) return value;
3546
+ const copy = { ...value };
3547
+ if (rest.length === 0) delete copy[head];
3548
+ else copy[head] = without(copy[head], rest);
3549
+ return copy;
3550
+ }
3551
+ function parseWidgetProps(schema, props) {
3552
+ let current = props;
3553
+ const dropped = [];
3554
+ for (let round = 0; round < 25; round++) {
3555
+ const r = schema.safeParse(current);
3556
+ if (r.success) return { props: r.data, dropped };
3557
+ const issue = r.error.issues.find((i) => i.path.length > 0);
3558
+ if (!issue) break;
3559
+ const lastIndex = issue.path.reduce((at, k, i) => typeof k === "number" ? i : at, -1);
3560
+ const path = lastIndex >= 0 ? issue.path.slice(0, lastIndex + 1) : issue.path;
3561
+ const next = without(current, path);
3562
+ if (next === current) break;
3563
+ dropped.push(path.join("."));
3564
+ current = next;
3565
+ }
3566
+ return { props, dropped };
3551
3567
  }
3552
3568
 
3553
- // src/widgets/builtins/Kpi.tsx
3554
- import { Fragment as Fragment4, jsx as jsx13, jsxs as jsxs8 } from "react/jsx-runtime";
3555
- var Kpi = defineWidget({
3556
- ...KpiContract,
3557
- implements: "kpi",
3558
- header: "widget",
3559
- empty: "widget",
3560
- meta: { label: "KPI", icon: "kpi", category: "Numbers", size: { w: 3, h: 4, minW: 2, minH: 3 } },
3561
- events: ["click", "hover"],
3562
- parts: ["value"],
3563
- defaults: { title: "New KPI", goodWhen: "up" },
3564
- component: function KpiWidget({ spec, data, source, emit, helpers }) {
3565
- const num = (v) => typeof v === "number" ? v : toNumber(field(source, v));
3566
- const value = toNumber(data) ?? data;
3567
- const animated = useCountUp(value);
3568
- const n = toNumber(value);
3569
- const fmt = (v) => formatValue(v, helpers, spec.format, spec.decimals);
3570
- const unit = spec.format === "duration" ? void 0 : spec.unit;
3571
- const empty = spec.empty === true || value === void 0 || value === null || value === "";
3572
- const hasTarget = spec.target !== void 0;
3573
- const target = hasTarget ? num(spec.target) : void 0;
3574
- const op = spec.goodWhen === "down" ? "\u2264 " : spec.goodWhen === "up" ? "\u2265 " : "";
3575
- const targetText = spec.targetLabel ?? (target !== void 0 ? `Target: ${op}${fmt(target)}${unit ? spec.format === "percent" ? "" : ` ${unit.toLowerCase()}` : ""}` : void 0);
3576
- const met = target === void 0 || n === void 0 || spec.goodWhen === "none" ? void 0 : spec.goodWhen === "down" ? n <= target : n >= target;
3577
- const labels = { good: spec.statusLabels?.good ?? "On track", bad: spec.statusLabels?.bad ?? "Action needed" };
3578
- const ref = spec.compare === void 0 ? void 0 : typeof spec.compare === "number" ? spec.compare : spec.compare.value !== void 0 ? toNumber(spec.compare.value) : toNumber(field(source, spec.compare.path));
3579
- const delta = n !== void 0 && ref !== void 0 ? n - ref : void 0;
3580
- const better = delta === void 0 || delta === 0 || spec.goodWhen === "none" ? void 0 : delta > 0 === (spec.goodWhen === "up");
3581
- const low = spec.band ? num(spec.band.low) : void 0;
3582
- const high = spec.band ? num(spec.band.high) : void 0;
3583
- const outside = n !== void 0 && (low !== void 0 && n < low || high !== void 0 && n > high);
3584
- const pTarget = spec.progress ? num(spec.progress.target) : void 0;
3585
- const ratio = n !== void 0 && pTarget ? Math.min(spec.progress?.cap ?? Number.POSITIVE_INFINITY, n / pTarget * 100) : void 0;
3586
- return /* @__PURE__ */ jsxs8("div", { className: "ds-kpi", "data-size": spec.size, children: [
3587
- /* @__PURE__ */ jsxs8("div", { className: "ds-kpi-label", children: [
3588
- /* @__PURE__ */ jsx13("span", { children: spec.title }),
3589
- spec.info && /* @__PURE__ */ jsx13(InfoTip, { text: spec.info })
3590
- ] }),
3591
- /* @__PURE__ */ jsx13(
3592
- "button",
3593
- {
3594
- type: "button",
3595
- className: "ds-kpi-main",
3596
- onClick: () => emit("click", "value", { datum: source, value }),
3597
- onMouseEnter: () => emit("hover", "value", { datum: source, value }),
3598
- "aria-label": `${spec.title ?? "Value"}: ${empty ? spec.emptyText ?? "no value" : fmt(value)}${unit ? ` ${unit}` : ""}`,
3599
- children: empty ? (
3600
- // No value is not zero: the author's text, else a dash.
3601
- /* @__PURE__ */ jsx13("span", { className: "ds-kpi-empty", children: spec.emptyText || "\u2014" })
3602
- ) : /* @__PURE__ */ jsxs8(Fragment4, { children: [
3603
- /* @__PURE__ */ jsx13(
3604
- "span",
3605
- {
3606
- className: "ds-kpi-value",
3607
- style: { color: spec.tone ? tone(spec.tone).fg : outside ? tone("bad").fg : void 0 },
3608
- children: fmt(animated)
3609
- }
3610
- ),
3611
- unit && /* @__PURE__ */ jsx13("span", { className: "ds-kpi-unit", children: unit })
3612
- ] })
3613
- }
3614
- ),
3615
- delta !== void 0 && /* @__PURE__ */ jsxs8(
3616
- "span",
3617
- {
3618
- className: "ds-kpi-delta",
3619
- style: { color: tone(better === void 0 ? "neutral" : better ? "good" : "bad").fg },
3620
- children: [
3621
- delta > 0 ? "\u2191" : delta < 0 ? "\u2193" : "\u2192",
3622
- " ",
3623
- spec.format === "duration" ? helpers.fmt.duration(Math.abs(delta)) : `${helpers.fmt.number(Math.abs(ref ? delta / Math.abs(ref) * 100 : 0), 1)}%`,
3624
- typeof spec.compare === "object" && spec.compare.label && /* @__PURE__ */ jsxs8("span", { className: "ds-kpi-sub", children: [
3625
- " ",
3626
- spec.compare.label
3627
- ] })
3628
- ]
3629
- }
3630
- ),
3631
- spec.note && /* @__PURE__ */ jsx13("span", { className: "ds-kpi-sub", children: spec.note }),
3632
- spec.sublabel && /* @__PURE__ */ jsx13("span", { className: "ds-kpi-sub", children: spec.sublabel }),
3633
- low !== void 0 && high !== void 0 && /* @__PURE__ */ jsxs8("span", { className: "ds-kpi-sub", children: [
3634
- "Expected ",
3635
- fmt(low),
3636
- "\u2013",
3637
- fmt(high)
3638
- ] }),
3639
- ratio !== void 0 && // biome-ignore lint/a11y/useFocusableInteractive: a progress bar is read-only, not interactive
3640
- /* @__PURE__ */ jsx13(
3641
- "span",
3642
- {
3643
- className: "ds-progress",
3644
- role: "progressbar",
3645
- "aria-valuenow": Math.round(ratio),
3646
- "aria-valuemin": 0,
3647
- "aria-valuemax": 100,
3648
- children: /* @__PURE__ */ jsx13(
3649
- "span",
3650
- {
3651
- style: { width: `${Math.min(100, ratio)}%`, background: tone(ratio >= 100 ? "good" : "info").solid }
3652
- }
3653
- )
3654
- }
3655
- ),
3656
- (hasTarget || targetText) && /* @__PURE__ */ jsxs8("div", { className: "ds-kpi-foot", children: [
3657
- hasTarget && target === void 0 ? /* @__PURE__ */ jsx13("span", { className: "ds-chip", "data-tone": "bad", children: spec.targetMissing }) : /* @__PURE__ */ jsx13("span", { "data-ds-part": "target", children: targetText }),
3658
- spec.badge !== false && met !== void 0 && !empty && /* @__PURE__ */ jsx13("span", { className: "ds-chip", "data-tone": met ? "good" : "bad", "data-ds-part": "badge", children: met ? labels.good : labels.bad })
3659
- ] })
3660
- ] });
3569
+ // src/components/Boundary.tsx
3570
+ import { Component } from "react";
3571
+ var sameKeys = (a, b) => a.length === b.length && a.every((x, i) => Object.is(x, b[i]));
3572
+ var Boundary = class extends Component {
3573
+ state = { error: null };
3574
+ static getDerivedStateFromError(error) {
3575
+ return { error };
3661
3576
  }
3662
- });
3577
+ componentDidCatch(error, _info) {
3578
+ this.props.onError?.(error);
3579
+ }
3580
+ componentDidUpdate(prev) {
3581
+ if (this.state.error && !sameKeys(prev.resetKeys ?? [], this.props.resetKeys ?? [])) this.setState({ error: null });
3582
+ }
3583
+ render() {
3584
+ return this.state.error ? this.props.fallback(this.state.error) : this.props.children;
3585
+ }
3586
+ };
3663
3587
 
3664
- // src/widgets/builtins/Sparkline.tsx
3665
- import "zod";
3666
- import { jsx as jsx14, jsxs as jsxs9 } from "react/jsx-runtime";
3667
- function sparkPath(values, w, h, pad = 2) {
3668
- if (values.length === 0) return { line: "", area: "" };
3669
- const min = values.reduce((a, b) => Math.min(a, b));
3670
- const max = values.reduce((a, b) => Math.max(a, b));
3671
- const span = max - min || 1;
3672
- const step = values.length > 1 ? (w - pad * 2) / (values.length - 1) : 0;
3673
- const pts = values.map((v, i) => [pad + i * step, h - pad - (v - min) / span * (h - pad * 2)]);
3674
- const line = pts.map(([x, y], i) => `${i ? "L" : "M"}${x.toFixed(1)},${y.toFixed(1)}`).join(" ");
3675
- const last = pts[pts.length - 1];
3676
- return { line, area: `${line} L${last[0].toFixed(1)},${h} L${pad},${h} Z` };
3588
+ // src/components/Slot.tsx
3589
+ import { createContext as createContext3, useContext as useContext3 } from "react";
3590
+ import { Fragment as Fragment4, jsx as jsx13, jsxs as jsxs8 } from "react/jsx-runtime";
3591
+ var NodeScopeContext = createContext3({});
3592
+ var useNodeScope = () => useContext3(NodeScopeContext);
3593
+ var SlotOwnerContext = createContext3(null);
3594
+ var SlotChildContext = createContext3(null);
3595
+ function slotChildren(def, name) {
3596
+ const slots = def?.slots;
3597
+ const list = slots?.[name];
3598
+ return Array.isArray(list) ? list.filter((x) => typeof x === "string") : [];
3677
3599
  }
3678
- function SparkSvg({
3679
- values,
3680
- area = true,
3681
- height = 32,
3682
- color: color2 = "var(--ds-series-1)"
3600
+ function Slot({
3601
+ name,
3602
+ className,
3603
+ style,
3604
+ data,
3605
+ item,
3606
+ index,
3607
+ empty
3683
3608
  }) {
3684
- const w = 120;
3685
- const { line, area: fill } = sparkPath(values, w, height);
3686
- return /* @__PURE__ */ jsxs9("svg", { viewBox: `0 0 ${w} ${height}`, preserveAspectRatio: "none", style: { width: "100%", height }, "aria-hidden": "true", children: [
3687
- area && /* @__PURE__ */ jsx14("path", { d: fill, fill: color2, opacity: 0.15 }),
3688
- /* @__PURE__ */ jsx14("path", { d: line, fill: "none", stroke: color2, strokeWidth: 1.5, vectorEffect: "non-scaling-stroke" })
3689
- ] });
3609
+ const { options } = useDashboard();
3610
+ const owner = useContext3(SlotOwnerContext);
3611
+ const outer = useNodeScope();
3612
+ const renderChild = useContext3(SlotChildContext);
3613
+ if (!owner || !renderChild) return null;
3614
+ const ids = slotChildren(owner.def, name);
3615
+ const editing = options.mode === "edit";
3616
+ if (ids.length === 0 && !editing) return null;
3617
+ const hasItem = item !== void 0 || outer.hasItem;
3618
+ const scope2 = {
3619
+ parentId: owner.id,
3620
+ parentData: owner.data,
3621
+ data: data !== void 0 ? data : item !== void 0 ? item : owner.data,
3622
+ hasItem: Boolean(hasItem),
3623
+ item: item !== void 0 ? item : outer.item,
3624
+ index: index !== void 0 ? index : outer.index
3625
+ };
3626
+ return /* @__PURE__ */ jsx13(NodeScopeContext.Provider, { value: scope2, children: /* @__PURE__ */ jsxs8(
3627
+ "div",
3628
+ {
3629
+ className: className ? `ds-slot ${className}` : "ds-slot",
3630
+ style,
3631
+ "data-slot": name,
3632
+ "data-owner": owner.id,
3633
+ "data-empty": ids.length === 0 || void 0,
3634
+ children: [
3635
+ ids.map((id) => /* @__PURE__ */ jsx13(SlotItem, { children: renderChild(id) }, id)),
3636
+ ids.length === 0 && editing && (empty ?? /* @__PURE__ */ jsx13("span", { className: "ds-slot-hint", children: "Drop here" }))
3637
+ ]
3638
+ }
3639
+ ) });
3690
3640
  }
3691
- var Sparkline = defineWidget({
3692
- ...SparklineContract,
3693
- implements: "chart",
3694
- meta: { label: "Sparkline", icon: "sparkline", category: "Charts", size: { w: 3, h: 2, minW: 2, minH: 1 } },
3695
- events: ["hover"],
3696
- defaults: { y: "value" },
3697
- component: function SparklineWidget({ spec, data, size: size2, emit }) {
3698
- const rows = asRows(data);
3699
- const values = rows.map((r) => toNumber(field(r, spec.y)) ?? 0);
3700
- return /* @__PURE__ */ jsx14(
3701
- "div",
3702
- {
3703
- onMouseEnter: () => emit("hover", "line", { value: values[values.length - 1] }),
3704
- style: { height: "100%" },
3705
- role: "img",
3706
- "aria-label": `${spec.title ?? spec.y}: ${values.length} points`,
3707
- children: /* @__PURE__ */ jsx14(SparkSvg, { values, area: spec.area, height: Math.max(24, size2.height || 32) })
3708
- }
3709
- );
3710
- }
3711
- });
3641
+ var SlotItem = ({ children }) => /* @__PURE__ */ jsx13(Fragment4, { children });
3712
3642
 
3713
- // src/widgets/builtins/StageTracker.tsx
3714
- import "zod";
3715
- import { jsx as jsx15, jsxs as jsxs10 } from "react/jsx-runtime";
3716
- var StageTracker = defineWidget({
3717
- ...StageTrackerContract,
3718
- implements: "stages",
3719
- meta: { label: "Stage tracker", icon: "stages", category: "Status", size: { w: 12, h: 3, minW: 4, minH: 2 } },
3720
- events: ["click"],
3721
- parts: ["stage"],
3722
- component: function StageTrackerWidget({ spec, data, emit }) {
3723
- const raw = typeof data === "string" || typeof data === "number" ? data : field(data, spec.current);
3724
- const idx = typeof raw === "number" ? raw : spec.stages.findIndex((s) => s.toLowerCase() === String(raw ?? "").toLowerCase());
3725
- return /* @__PURE__ */ jsx15("ol", { className: "ds-stages", children: spec.stages.map((s, i) => {
3726
- const state = i < idx ? "done" : i === idx ? "current" : "todo";
3727
- return /* @__PURE__ */ jsx15("li", { "data-state": state, children: /* @__PURE__ */ jsxs10(
3728
- "button",
3729
- {
3730
- type: "button",
3731
- onClick: () => emit("click", "stage", { value: s, index: i, datum: data }),
3732
- "aria-current": state === "current" ? "step" : void 0,
3733
- children: [
3734
- /* @__PURE__ */ jsx15("span", { className: "ds-stage-dot", "aria-hidden": "true", children: state === "done" ? "\u2713" : i + 1 }),
3735
- s
3736
- ]
3737
- }
3738
- ) }, s);
3739
- }) });
3643
+ // src/components/PanelFrame.tsx
3644
+ import { jsx as jsx14, jsxs as jsxs9 } from "react/jsx-runtime";
3645
+ var isEmpty = (d) => d === void 0 || d === null || Array.isArray(d) && d.length === 0 || typeof d === "object" && !Array.isArray(d) && Object.keys(d).length === 0;
3646
+ function useSize() {
3647
+ const [size2, setSize] = useState4({ width: 0, height: 0 });
3648
+ const observer = useRef5(null);
3649
+ const ref = useCallback4((el) => {
3650
+ observer.current?.disconnect();
3651
+ observer.current = null;
3652
+ if (!el || typeof ResizeObserver === "undefined") return;
3653
+ const ro = new ResizeObserver(([e]) => {
3654
+ const r = e?.contentRect;
3655
+ if (r)
3656
+ setSize(
3657
+ (s) => s.width === Math.round(r.width) && s.height === Math.round(r.height) ? s : { width: Math.round(r.width), height: Math.round(r.height) }
3658
+ );
3659
+ });
3660
+ ro.observe(el);
3661
+ observer.current = ro;
3662
+ }, []);
3663
+ return [ref, size2];
3664
+ }
3665
+ var DEFERRED = /(^|[^\w.$])(row|item|avg)\b/;
3666
+ var DEFERRED_IN_ITEM = /(^|[^\w.$])(row|avg)\b/;
3667
+ function interpolateMarkdown(v, scope2) {
3668
+ const bodies = placeholders(v);
3669
+ const whole = bodies.length === 1 && v.trim() === `\${${bodies[0]}}`;
3670
+ const r = interpolate(v, scope2, escapeMarkdown);
3671
+ if (!whole) return r;
3672
+ return r === null || r === void 0 ? "" : escapeMarkdown(typeof r === "object" ? JSON.stringify(r) : String(r));
3673
+ }
3674
+ function resolvePanel(v, scope2, inItem = false, key) {
3675
+ const deferred = inItem ? DEFERRED_IN_ITEM : DEFERRED;
3676
+ if (typeof v === "string") {
3677
+ if (placeholders(v).some((b) => deferred.test(stripStrings(b)))) return v;
3678
+ return key === "markdown" ? interpolateMarkdown(v, scope2) : interpolate(v, scope2);
3740
3679
  }
3741
- });
3742
-
3743
- // src/widgets/builtins/StateTimeline.tsx
3744
- import "zod";
3745
- import { jsx as jsx16, jsxs as jsxs11 } from "react/jsx-runtime";
3746
- var StateTimeline = defineWidget({
3747
- ...StateTimelineContract,
3748
- implements: "timeline",
3749
- meta: { label: "State timeline", icon: "timeline", category: "Status", size: { w: 12, h: 3, minW: 4, minH: 2 } },
3750
- events: ["click", "hover"],
3751
- parts: ["segment"],
3752
- component: function StateTimelineWidget({ spec, data, emit, helpers }) {
3753
- const all = asRows(data).map((r) => ({ r, t: Number(field(r, spec.time)), raw: String(field(r, spec.value) ?? "") })).filter((x) => Number.isFinite(x.t)).sort((a, b) => a.t - b.t);
3754
- const end = helpers.now();
3755
- const start = spec.window ? end - parseDuration(spec.window) : all[0]?.t ?? end;
3756
- const lanes = spec.rows ? [...new Set(all.map((x) => String(field(x.r, spec.rows))))] : [""];
3757
- const span = Math.max(1, end - start);
3758
- const states = /* @__PURE__ */ new Map();
3759
- return /* @__PURE__ */ jsxs11("div", { className: "ds-timeline", children: [
3760
- lanes.map((lane) => {
3761
- const pts = all.filter((x) => !spec.rows || String(field(x.r, spec.rows)) === lane);
3762
- const segs = pts.map((p, i) => {
3763
- const from = Math.max(start, p.t);
3764
- const to = Math.min(end, pts[i + 1]?.t ?? end);
3765
- const state = spec.stateMap?.[p.raw] ?? p.raw;
3766
- states.set(state, (states.get(state) ?? 0) + Math.max(0, to - from));
3767
- return { p, from, to, state };
3768
- });
3769
- return /* @__PURE__ */ jsxs11("div", { className: "ds-timeline-lane", children: [
3770
- lane && /* @__PURE__ */ jsx16("span", { className: "ds-timeline-name", children: lane }),
3771
- /* @__PURE__ */ jsx16("div", { className: "ds-timeline-bar", role: "img", "aria-label": `${spec.title ?? "Timeline"} ${lane}`, children: segs.filter((s) => s.to > s.from).map((s) => (
3772
- // biome-ignore lint/a11y/useKeyWithClickEvents: the per-state totals below summarise the same data for keyboard users
3773
- /* @__PURE__ */ jsx16(
3774
- "span",
3775
- {
3776
- title: `${s.state} \xB7 ${helpers.fmt.date(s.from, "time")}\u2013${helpers.fmt.date(s.to, "time")} (${helpers.fmt.duration((s.to - s.from) / 1e3)})`,
3777
- style: {
3778
- left: `${(s.from - start) / span * 100}%`,
3779
- width: `${(s.to - s.from) / span * 100}%`,
3780
- background: tone(spec.tones?.[s.state] ?? "neutral").solid
3781
- },
3782
- onClick: () => emit("click", "segment", { datum: s.p.r, value: s.state, x: s.from }),
3783
- onMouseEnter: () => emit("hover", "segment", { datum: s.p.r, value: s.state, x: s.from })
3784
- },
3785
- `${s.from}-${s.state}`
3786
- )
3787
- )) })
3788
- ] }, lane);
3789
- }),
3790
- /* @__PURE__ */ jsxs11("div", { className: "ds-timeline-axis", children: [
3791
- /* @__PURE__ */ jsx16("span", { children: helpers.fmt.date(start, "time") }),
3792
- /* @__PURE__ */ jsx16("span", { children: spec.endLabel ?? helpers.fmt.date(end, "time") })
3793
- ] }),
3794
- /* @__PURE__ */ jsx16("ul", { className: "ds-legend", children: [...states.entries()].map(([s, ms]) => /* @__PURE__ */ jsxs11("li", { children: [
3795
- /* @__PURE__ */ jsx16(
3796
- "span",
3797
- {
3798
- className: "ds-dot",
3799
- style: { background: tone(spec.tones?.[s] ?? "neutral").solid },
3800
- "aria-hidden": "true"
3801
- }
3802
- ),
3803
- s,
3804
- " ",
3805
- /* @__PURE__ */ jsx16("strong", { children: helpers.fmt.duration(ms / 1e3) })
3806
- ] }, s)) })
3807
- ] });
3680
+ if (Array.isArray(v)) return v.map((x) => resolvePanel(x, scope2, inItem));
3681
+ if (v && typeof v === "object")
3682
+ return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, resolvePanel(x, scope2, inItem, k)]));
3683
+ return v;
3684
+ }
3685
+ function withFunctions(v, make) {
3686
+ if (Array.isArray(v)) return v.map((x) => withFunctions(x, make));
3687
+ if (v && typeof v === "object") {
3688
+ const o = v;
3689
+ if (typeof o.fn === "string" && Object.keys(o).length === 1) return make(o.fn);
3690
+ return Object.fromEntries(Object.entries(o).map(([k, x]) => [k, withFunctions(x, make)]));
3808
3691
  }
3809
- });
3810
-
3811
- // src/widgets/builtins/Status.tsx
3812
- import "zod";
3813
- import { jsx as jsx17, jsxs as jsxs12 } from "react/jsx-runtime";
3814
- var Status = defineWidget({
3815
- ...StatusContract,
3816
- implements: "badge",
3817
- // A badge, not a card: it can sit anywhere, including in another widget's header.
3818
- frame: "plain",
3819
- meta: { label: "Status badge", icon: "status", category: "Numbers", size: { w: 3, h: 2, minW: 1, minH: 1 } },
3820
- events: ["click"],
3821
- component: function StatusWidget({ spec, data, emit }) {
3822
- const row = asRows(data)[0] ?? {};
3823
- const state = String(field(row, spec.state) ?? "unknown");
3824
- const t = spec.text ? spec.tone ?? "info" : spec.stateMap?.[state] ?? spec.tone ?? "neutral";
3825
- const text = spec.text ?? spec.labels?.[state] ?? state.charAt(0).toUpperCase() + state.slice(1);
3826
- return /* @__PURE__ */ jsxs12("button", { type: "button", className: "ds-status", onClick: () => emit("click", "status", { datum: row, value: state }), children: [
3827
- /* @__PURE__ */ jsxs12("span", { className: "ds-pill", style: { background: tone(t).bg, color: tone(t).fg, borderColor: tone(t).border }, children: [
3828
- /* @__PURE__ */ jsx17("span", { className: "ds-dot", style: { background: tone(t).solid }, "aria-hidden": "true" }),
3829
- text
3830
- ] }),
3831
- spec.label && /* @__PURE__ */ jsx17("span", { className: "ds-status-label", children: String(field(row, spec.label) ?? "") })
3832
- ] });
3692
+ return v;
3693
+ }
3694
+ var SHADOWS = {
3695
+ none: "none",
3696
+ sm: "0 1px 3px rgba(13, 13, 13, 0.08)",
3697
+ md: "0 6px 16px rgba(13, 13, 13, 0.10)",
3698
+ lg: "0 14px 36px rgba(13, 13, 13, 0.14)"
3699
+ };
3700
+ var PADDING = { none: "0", compact: "8px", roomy: "24px" };
3701
+ var colour = (v) => {
3702
+ if (typeof v !== "string" || !v) return void 0;
3703
+ if (/^[a-z]+(-[a-z]+)+$/.test(v) && !v.includes("(")) return `var(--ds-color-${v})`;
3704
+ return /^(#[0-9a-f]{3,8}|rgba?\([\d\s.,%]+\)|hsla?\([\d\s.,%deg]+\)|[a-z]+)$/i.test(v) ? v : void 0;
3705
+ };
3706
+ var size = (v) => typeof v === "number" ? `${v}px` : typeof v === "string" && /^[\d.]+(px|%|rem|em|vw)?$/.test(v) ? v : void 0;
3707
+ var PART_CLASSES = [
3708
+ [".ds-panel-title, .ds-kpi-label", "title"],
3709
+ [".ds-info", "info"],
3710
+ [".ds-panel-meta, .ds-live", "meta"],
3711
+ [".ds-kpi-foot", "target"],
3712
+ [".ds-chip", "badge"],
3713
+ [".ds-kpi-main, .ds-kpi-value, .ds-kpi-unit", "value"],
3714
+ [".ds-kpi-sub, .ds-kpi-delta", "note"],
3715
+ [".ds-tile", "tile"],
3716
+ [".ds-meters > *, .ds-segbar, .ds-legend", "bars"],
3717
+ [".ds-status, .ds-pill", "state"],
3718
+ [".ds-table-tools", "tools"],
3719
+ [".ds-pager", "pager"]
3720
+ ];
3721
+ var PART_SELECTOR = ["[data-ds-part]", ...PART_CLASSES.map(([sel]) => sel)].join(", ");
3722
+ function partAt(target, frame) {
3723
+ let el = target?.closest(PART_SELECTOR) ?? null;
3724
+ while (el && frame?.contains(el)) {
3725
+ if (el.closest(".ds-panel") !== frame) return void 0;
3726
+ const own = el.getAttribute("data-ds-part");
3727
+ if (own) return { part: own, node: el };
3728
+ const hit = PART_CLASSES.find(([sel]) => el?.matches(sel));
3729
+ if (hit) return { part: hit[1], node: el };
3730
+ el = el.parentElement?.closest(PART_SELECTOR) ?? null;
3833
3731
  }
3834
- });
3835
-
3836
- // src/widgets/builtins/Table.tsx
3837
- import { useEffect as useEffect4, useMemo as useMemo3, useRef as useRef6, useState as useState5 } from "react";
3838
- import { jsx as jsx18, jsxs as jsxs13 } from "react/jsx-runtime";
3839
- var ROW_H = 36;
3840
- function pageList(current, pages) {
3841
- if (pages <= 7) return Array.from({ length: pages }, (_, i) => i + 1);
3842
- const set = new Set([1, pages, current - 1, current, current + 1].filter((n) => n >= 1 && n <= pages));
3843
- const sorted = [...set].sort((a, b) => a - b);
3844
- const out = [];
3845
- sorted.forEach((n, i) => {
3846
- if (i > 0 && n - sorted[i - 1] > 1) out.push(0);
3847
- out.push(n);
3848
- });
3849
- return out;
3732
+ return void 0;
3850
3733
  }
3851
- var Table = defineWidget({
3852
- ...TableContract,
3853
- implements: "table",
3854
- exposes: { selection: "the clicked row", page: "current page (ui.page)", search: "search text (ui.search)" },
3855
- meta: { label: "Table", icon: "table", category: "Lists", size: { w: 12, h: 8, minW: 4, minH: 4 } },
3856
- events: ["rowClick", "cellClick", "hover"],
3857
- parts: ["row", "cell"],
3858
- rows: (data) => asRows(data),
3859
- component: function TableWidget({ spec, data, source, emit, helpers, size: size2, state, setUi, status }) {
3860
- const tpl = (t, row, item) => {
3861
- try {
3862
- const v = interpolate(t, scope({ row, item, datum: row }, helpers));
3863
- return v === null || v === void 0 ? "" : String(v);
3864
- } catch {
3865
- return "";
3866
- }
3867
- };
3868
- const base = useMemo3(() => {
3869
- const rows2 = asRows(data);
3870
- return spec.pivot ? applyTransform(rows2, [{ pivot: spec.pivot }], scope()) : rows2;
3871
- }, [data, spec.pivot]);
3872
- const columns = useMemo3(() => {
3873
- if (spec.columns?.length) return spec.columns;
3874
- if (spec.columnsFrom) {
3875
- const cf = spec.columnsFrom;
3876
- return asRows(field(source, cf.path)).map((c) => ({
3877
- key: String(field(c, cf.key)),
3878
- label: String(field(c, cf.label) ?? field(c, cf.key)),
3879
- ...cf.type ? { type: cf.type } : {},
3880
- ...cf.format ? { format: cf.format } : {}
3881
- }));
3882
- }
3883
- return Object.keys(base[0] ?? {}).map((k) => ({ key: k }));
3884
- }, [spec.columns, spec.columnsFrom, source, base]);
3885
- const pg = spec.pagination && spec.pagination.enabled !== false ? spec.pagination : void 0;
3886
- const sr = spec.search === true ? { enabled: true, mode: "client" } : spec.search && spec.search.enabled !== false ? spec.search : void 0;
3887
- const so = spec.sorting ?? { enabled: true, mode: "client" };
3888
- const fl = spec.filtering && spec.filtering.enabled !== false ? spec.filtering : void 0;
3889
- const server = {
3890
- paging: pg?.mode === "server",
3891
- search: sr?.mode === "server",
3892
- sort: so.mode === "server",
3893
- filter: fl?.mode === "server"
3894
- };
3895
- const anyServer = server.paging || server.search || server.sort || server.filter;
3896
- const ui = state.ui ?? {};
3897
- const [view, setView] = useState5(() => ({
3898
- page: Number(ui.page ?? 1),
3899
- pageSize: Number(ui.pageSize ?? pg?.pageSize ?? 20),
3900
- search: String(ui.search ?? ""),
3901
- sortKey: ui.sortKey ?? so.default?.key,
3902
- sortOrder: ui.sortOrder ?? so.default?.order ?? "asc",
3903
- filters: ui.filters ?? {}
3904
- }));
3905
- const update = (patch) => {
3906
- const next = { ...view, ...patch };
3907
- setView(next);
3908
- if (anyServer)
3909
- setUi({
3910
- page: next.page,
3911
- pageSize: next.pageSize,
3912
- offset: (next.page - 1) * next.pageSize,
3913
- search: next.search || void 0,
3914
- sortKey: next.sortKey,
3915
- sortOrder: next.sortKey ? next.sortOrder : void 0,
3916
- ordering: next.sortKey ? `${next.sortOrder === "desc" ? "-" : ""}${next.sortKey}` : void 0,
3917
- filters: Object.fromEntries(Object.entries(next.filters).filter(([, v]) => v !== ""))
3918
- });
3919
- };
3920
- const [searchText, setSearchText] = useState5(view.search);
3921
- const searchTimer = useRef6(void 0);
3922
- useEffect4(() => () => clearTimeout(searchTimer.current), []);
3923
- const [scrollTop, setScrollTop] = useState5(0);
3924
- const scroller = useRef6(null);
3925
- const sort = view.sortKey ? { key: view.sortKey, order: view.sortOrder } : void 0;
3926
- const rows = useMemo3(() => {
3927
- let r = base;
3928
- if (fl && !server.filter)
3929
- for (const [k, v] of Object.entries(view.filters)) {
3930
- if (v === "") continue;
3931
- const c = columns.find((x) => x.key === k);
3932
- if (c?.filter === "min")
3933
- r = r.filter((row) => (toNumber(field(row, k)) ?? Number.NEGATIVE_INFINITY) >= Number(v));
3934
- else if (c?.filter === "select") r = r.filter((row) => String(field(row, k) ?? "") === v);
3935
- else
3936
- r = r.filter(
3937
- (row) => String(field(row, k) ?? "").toLowerCase().includes(v.toLowerCase())
3938
- );
3734
+ function markPart(frame, node) {
3735
+ const root = frame?.closest(".ds-root") ?? frame?.ownerDocument;
3736
+ for (const n of root?.querySelectorAll(".ds-part-selected") ?? []) n.classList.remove("ds-part-selected");
3737
+ node?.classList.add("ds-part-selected");
3738
+ }
3739
+ function panelStyle(s) {
3740
+ if (!s) return void 0;
3741
+ const out = {};
3742
+ const bg = colour(s.background);
3743
+ if (bg) out.background = bg;
3744
+ if (typeof s.borderWidth === "number" || s.borderColor)
3745
+ out.border = `${s.borderWidth ?? 1}px solid ${colour(s.borderColor) ?? "var(--ds-color-border-default)"}`;
3746
+ if (typeof s.radius === "number") out.borderRadius = s.radius;
3747
+ if (typeof s.shadow === "string" && SHADOWS[s.shadow]) out.boxShadow = SHADOWS[s.shadow];
3748
+ if (typeof s.padding === "number") out.padding = s.padding;
3749
+ else if (typeof s.padding === "string" && PADDING[s.padding]) out.padding = PADDING[s.padding];
3750
+ if (typeof s.minHeight === "number") out.minHeight = s.minHeight;
3751
+ if (typeof s.flex === "string" && /^[\d.\s]*(auto|[\d.]+(px|%|rem)?)?$/.test(s.flex)) out.flex = s.flex;
3752
+ const minW = size(s.minWidth);
3753
+ const maxW = size(s.maxWidth);
3754
+ if (minW) out.minWidth = minW;
3755
+ if (maxW) out.maxWidth = maxW;
3756
+ if (typeof s.align === "string")
3757
+ out.alignSelf = s.align === "start" ? "flex-start" : s.align === "end" ? "flex-end" : s.align;
3758
+ return Object.keys(out).length ? out : void 0;
3759
+ }
3760
+ var samePanelView = (a, b) => Object.keys(a).every(
3761
+ (k) => k === "data" || k === "sourceData" ? Object.is(a[k], b[k]) : Object.is(a[k], b[k]) || JSON.stringify(a[k]) === JSON.stringify(b[k])
3762
+ );
3763
+ var RESERVED = /^(filters|panels|view|modal|highlight|datasources|context)(\.|$)/;
3764
+ function widgetStore(runtime) {
3765
+ const get = (path) => getPath(runtime.getTree(), path);
3766
+ return {
3767
+ get,
3768
+ use: function useStoreValue(pathOrSelect) {
3769
+ return useTree(
3770
+ useCallback4(
3771
+ (t) => typeof pathOrSelect === "string" ? getPath(t, pathOrSelect) : pathOrSelect(t),
3772
+ [pathOrSelect]
3773
+ ),
3774
+ (a, b) => Object.is(a, b) || JSON.stringify(a) === JSON.stringify(b)
3775
+ );
3776
+ },
3777
+ set: (path, value) => {
3778
+ if (RESERVED.test(path)) throw new Error(`"${path}" belongs to the runtime; use setFilter or an action`);
3779
+ runtime.store.dispatch(stateActions.set({ path, value }));
3780
+ },
3781
+ setFilter: (name, value) => runtime.store.dispatch(stateActions.setFilter({ name, value })),
3782
+ subscribe: (path, fn) => {
3783
+ let prev = get(path);
3784
+ return runtime.store.subscribe(() => {
3785
+ const next = get(path);
3786
+ if (!Object.is(next, prev) && JSON.stringify(next) !== JSON.stringify(prev)) {
3787
+ prev = next;
3788
+ fn(next);
3939
3789
  }
3940
- if (sr && !server.search && view.search) {
3941
- const q = view.search.toLowerCase();
3942
- const fields = sr.mode === "client" && "fields" in sr ? sr.fields : void 0;
3943
- r = r.filter(
3944
- (row) => (fields ? fields.map((f) => field(row, f)) : Object.values(row)).some(
3945
- (v) => v !== null && v !== void 0 && typeof v !== "object" && String(v).toLowerCase().includes(q)
3946
- )
3947
- );
3948
- }
3949
- if (sort && !server.sort) {
3950
- const dir = sort.order === "desc" ? -1 : 1;
3951
- r = [...r].sort((a, b) => {
3952
- const x = field(a, sort.key);
3953
- const y = field(b, sort.key);
3954
- if (x === y) return 0;
3955
- if (x === null || x === void 0) return 1;
3956
- if (y === null || y === void 0) return -1;
3957
- const nx = toNumber(x);
3958
- const ny = toNumber(y);
3959
- return (nx !== void 0 && ny !== void 0 ? nx - ny : String(x).localeCompare(String(y), void 0, { numeric: true })) * dir;
3790
+ });
3791
+ }
3792
+ };
3793
+ }
3794
+ function findPanel(doc, id) {
3795
+ const top = doc.spec.panels[id];
3796
+ if (top) return top;
3797
+ for (const m of Object.values(doc.spec.modals ?? {})) if (m.panels[id]) return m.panels[id];
3798
+ return void 0;
3799
+ }
3800
+ function useHiddenPanels(ids) {
3801
+ const { runtime } = useDashboard();
3802
+ const key = ids.join(",");
3803
+ const list = useTree(
3804
+ // biome-ignore lint/correctness/useExhaustiveDependencies: ids are compared by key
3805
+ useCallback4(
3806
+ (tree) => ids.filter((id) => {
3807
+ const def = findPanel(runtime.doc, id);
3808
+ if (!def) return false;
3809
+ if (tree.panels[id]?.hidden) return true;
3810
+ if (typeof def.visibleWhen !== "string") return false;
3811
+ try {
3812
+ return !evaluate(
3813
+ def.visibleWhen,
3814
+ rootScope(tree, runtime.helpers, { panel: tree.panels[id] ?? {}, drill: drillValues(tree, id) })
3815
+ );
3816
+ } catch {
3817
+ return false;
3818
+ }
3819
+ }),
3820
+ [key, runtime]
3821
+ ),
3822
+ (a, b) => a.join(",") === b.join(",")
3823
+ );
3824
+ return useMemo3(() => new Set(list), [list]);
3825
+ }
3826
+ function panelUnder(x, y, exclude) {
3827
+ if (typeof document === "undefined") return void 0;
3828
+ for (const el of document.elementsFromPoint(x, y)) {
3829
+ const p = el.closest(".ds-panel[data-panel]");
3830
+ if (p && (!exclude || !exclude.contains(p) && !p.contains(exclude))) return p;
3831
+ }
3832
+ return void 0;
3833
+ }
3834
+ function indexIn(box, x, y) {
3835
+ const row = getComputedStyle(box).flexDirection === "row";
3836
+ const kids = [...box.children].filter((c) => c.classList.contains("ds-panel"));
3837
+ return kids.filter((k) => {
3838
+ const r = k.getBoundingClientRect();
3839
+ return row ? r.left + r.width / 2 < x && r.top < y : r.top + r.height / 2 < y;
3840
+ }).length;
3841
+ }
3842
+ function dropIndexAt(panel, x, y) {
3843
+ const id = panel.getAttribute("data-panel") ?? "";
3844
+ const under = document.elementsFromPoint(x, y).find((el) => el.closest(`[data-slot][data-owner="${CSS.escape(id)}"]`));
3845
+ const box = under?.closest(`[data-slot][data-owner="${CSS.escape(id)}"]`) ?? panel.querySelector(`[data-slot][data-owner="${CSS.escape(id)}"]`);
3846
+ if (!box) return {};
3847
+ return { slot: box.getAttribute("data-slot") ?? void 0, index: indexIn(box, x, y) };
3848
+ }
3849
+ function PanelFrame({ id, nested = false }) {
3850
+ return /* @__PURE__ */ jsx14(Boundary, { resetKeys: [id], fallback: (e) => /* @__PURE__ */ jsx14(PanelCrash, { id, error: e }), children: /* @__PURE__ */ jsx14(PanelFrameInner, { id, nested }) });
3851
+ }
3852
+ function PanelCrash({ id, error }) {
3853
+ const { options } = useDashboard();
3854
+ let custom;
3855
+ try {
3856
+ custom = options.renderError?.({ code: "render", message: error.message }, id);
3857
+ } catch {
3858
+ custom = void 0;
3859
+ }
3860
+ return /* @__PURE__ */ jsx14("section", { className: "ds-panel", "data-panel": id, "aria-label": id, children: /* @__PURE__ */ jsx14("div", { className: "ds-panel-body", children: custom ?? /* @__PURE__ */ jsxs9("div", { className: "ds-state ds-state-error", role: "alert", children: [
3861
+ "This panel could not be shown: ",
3862
+ error.message
3863
+ ] }) }) });
3864
+ }
3865
+ function PanelFrameInner({ id, nested }) {
3866
+ const { runtime, registry, options, visibility } = useDashboard();
3867
+ const instance = `${id}\0${useId3()}`;
3868
+ const inherited = useNodeScope();
3869
+ const def = findPanel(runtime.doc, id);
3870
+ const widget = registry.byKind.get(def.kind);
3871
+ const spec = def.spec ?? {};
3872
+ const binding = spec.data;
3873
+ const drillLevels = def.drill?.levels ?? [];
3874
+ const view = useTree(
3875
+ // biome-ignore lint/correctness/useExhaustiveDependencies: the panel definition is fixed for a runtime
3876
+ useCallback4(
3877
+ (tree) => {
3878
+ const ps = tree.panels[id] ?? {};
3879
+ const level = drillLevels[(ps.drill ?? []).length];
3880
+ const baseSource = level?.source ?? binding?.source;
3881
+ const drillId = baseSource && level?.query ? drillSourceId(baseSource, id, level.name) : void 0;
3882
+ const source = drillId && runtime.datasourceIds.has(drillId) ? drillId : baseSource;
3883
+ const scope2 = rootScope(tree, runtime.helpers, {
3884
+ panel: { ...ps, controls: ps.controls ?? {} },
3885
+ drill: drillValues(tree, id),
3886
+ parent: inherited.parentData,
3887
+ ...inherited.hasItem ? { item: inherited.item, index: inherited.index } : {}
3960
3888
  });
3961
- }
3962
- return r;
3963
- }, [base, view, columns]);
3964
- const pageSize = pg ? view.pageSize : void 0;
3965
- const rowTotal = server.paging ? toNumber(field(source, pg?.totalPath ?? "count")) ?? rows.length : rows.length;
3966
- const pages = pageSize ? Math.max(1, Math.ceil(rowTotal / pageSize)) : 1;
3967
- const current = Math.min(view.page, pages);
3968
- const shown = pageSize && !server.paging ? rows.slice((current - 1) * pageSize, current * pageSize) : rows;
3969
- const hasFilters = Boolean(fl) && columns.some((c) => c.filter);
3970
- const height = Math.max(120, (size2.height || 300) - (sr ? 48 : 0) - (pageSize ? 48 : 0));
3971
- const windowed = spec.virtual && shown.length > 60;
3972
- const first = windowed ? Math.max(0, Math.floor(scrollTop / ROW_H) - 10) : 0;
3973
- const last = windowed ? Math.min(shown.length, first + Math.ceil(height / ROW_H) + 20) : shown.length;
3974
- const busy = status === "loading" && base.length > 0;
3975
- const filterChoices = (c) => c.filterOptions ?? [
3976
- ...new Set(
3977
- base.map((r) => field(r, c.key)).filter((v) => v !== null && v !== void 0 && v !== "").map(String)
3978
- )
3979
- ].sort();
3980
- const cell = (c, row) => {
3981
- const v = field(row, c.key);
3982
- if (c.type === "badge") {
3983
- const text = c.template ? tpl(c.template, row) : v === null || v === void 0 || v === "" ? "" : String(v);
3984
- if (!text) return c.empty ? /* @__PURE__ */ jsx18("span", { className: "ds-cell-empty", children: c.empty }) : "";
3985
- let t = c.map?.[String(v)] ?? "neutral";
3986
- if (c.tone) {
3889
+ let visible = true;
3890
+ if (typeof def.visibleWhen === "string") {
3987
3891
  try {
3988
- t = String(
3989
- evaluate(c.tone, scope({ row, value: v }, helpers))
3990
- );
3892
+ visible = Boolean(evaluate(def.visibleWhen, scope2));
3991
3893
  } catch {
3894
+ visible = true;
3992
3895
  }
3993
3896
  }
3994
- return /* @__PURE__ */ jsx18("span", { className: "ds-chip", "data-tone": t, children: text });
3995
- }
3996
- if (c.template) return tpl(c.template, row) || (c.empty ? /* @__PURE__ */ jsx18("span", { className: "ds-cell-empty", children: c.empty }) : "");
3997
- if (c.list !== void 0) {
3998
- const items = Array.isArray(v) ? v : [];
3999
- if (items.length === 0) return c.empty ?? "";
4000
- return /* @__PURE__ */ jsx18("span", { className: "ds-cell-list", children: items.map((it, i) => (
4001
- // biome-ignore lint/suspicious/noArrayIndexKey: list items have no id and never reorder within a render
4002
- /* @__PURE__ */ jsx18("span", { children: tpl(c.list, row, it) }, i)
4003
- )) });
4004
- }
4005
- if (v === null || v === void 0 || v === "")
4006
- return c.empty ? /* @__PURE__ */ jsx18("span", { className: "ds-cell-empty", children: c.empty }) : "";
4007
- switch (c.type) {
4008
- case "link": {
4009
- const href = safeLink(c.href ? tpl(c.href, row) : String(v));
4010
- return href ? /* @__PURE__ */ jsx18("a", { className: "ds-link", href, onClick: (e) => e.stopPropagation(), children: String(v) }) : String(v);
4011
- }
4012
- case "image":
4013
- return safeImageSrc(v) ? /* @__PURE__ */ jsx18("img", { src: v, alt: "", style: { height: 28, borderRadius: 4 } }) : null;
4014
- case "progress": {
4015
- const n = toNumber(v) ?? 0;
4016
- const pct = Math.min(100, n / (c.max ?? 100) * 100);
4017
- return /* @__PURE__ */ jsxs13("span", { className: "ds-inline", children: [
4018
- /* @__PURE__ */ jsx18("span", { className: "ds-progress", style: { flex: 1, minWidth: 40 }, children: /* @__PURE__ */ jsx18("span", { style: { width: `${pct}%`, background: "var(--ds-series-1)" } }) }),
4019
- formatValue(n, helpers, c.format, c.decimals),
4020
- c.suffix
4021
- ] });
4022
- }
4023
- case "sparkline":
4024
- return /* @__PURE__ */ jsx18(
4025
- SparkSvg,
4026
- {
4027
- values: (Array.isArray(v) ? v : []).map(
4028
- (x) => toNumber(typeof x === "object" ? field(x, "value") : x) ?? 0
4029
- ),
4030
- height: 24,
4031
- area: false
4032
- }
4033
- );
4034
- default:
4035
- return `${c.prefix ?? ""}${typeof v === "number" || c.format ? formatValue(v, helpers, c.format, c.decimals) : String(v)}${c.suffix ?? ""}`;
4036
- }
4037
- };
4038
- const total = (c) => {
4039
- const how = spec.totals?.columns[c.key];
4040
- if (!how) return null;
4041
- const nums = rows.map((r) => toNumber(field(r, c.key))).filter((n) => n !== void 0);
4042
- if (how !== "count" && nums.length === 0) return "";
4043
- const v = how === "count" ? rows.length : how === "sum" ? nums.reduce((a, b) => a + b, 0) : how === "avg" ? nums.reduce((a, b) => a + b, 0) / (nums.length || 1) : how === "min" ? nums.reduce((a, b) => Math.min(a, b)) : nums.reduce((a, b) => Math.max(a, b));
4044
- return `${c.prefix ?? ""}${formatValue(v, helpers, c.format === "date" ? "number" : c.format, c.decimals)}${c.suffix ?? ""}`;
4045
- };
4046
- const muted = (row) => {
4047
- if (!spec.rowMutedWhen) return false;
4048
- try {
4049
- return Boolean(evaluate(spec.rowMutedWhen, scope({ row }, helpers)));
4050
- } catch {
4051
- return false;
4052
- }
4053
- };
4054
- const align = (c) => c.align ?? (c.type === "number" || c.format && c.format !== "date" && c.format !== "text" ? "right" : "left");
4055
- return /* @__PURE__ */ jsxs13("div", { className: "ds-table-wrap", "data-density": spec.density, children: [
4056
- sr && /* @__PURE__ */ jsxs13("div", { className: "ds-table-tools", children: [
4057
- /* @__PURE__ */ jsxs13("label", { className: "ds-search", children: [
4058
- /* @__PURE__ */ jsxs13("svg", { viewBox: "0 0 16 16", width: "15", height: "15", "aria-hidden": "true", children: [
4059
- /* @__PURE__ */ jsx18("circle", { cx: "7", cy: "7", r: "4.5", fill: "none", stroke: "currentColor", strokeWidth: "1.5" }),
4060
- /* @__PURE__ */ jsx18("path", { d: "m10.5 10.5 3 3", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round" })
4061
- ] }),
4062
- /* @__PURE__ */ jsx18(
4063
- "input",
4064
- {
4065
- type: "search",
4066
- "aria-label": "Search table",
4067
- placeholder: "placeholder" in sr && sr.placeholder || "Search",
4068
- value: searchText,
4069
- onChange: (e) => {
4070
- const v = e.target.value;
4071
- setSearchText(v);
4072
- clearTimeout(searchTimer.current);
4073
- searchTimer.current = setTimeout(() => update({ search: v, page: 1 }), server.search ? 350 : 120);
4074
- }
4075
- }
4076
- )
4077
- ] }),
4078
- /* @__PURE__ */ jsxs13("span", { className: "ds-table-count", children: [
4079
- helpers.fmt.number(rowTotal),
4080
- " rows"
4081
- ] })
4082
- ] }),
4083
- /* @__PURE__ */ jsxs13(
4084
- "div",
4085
- {
4086
- className: "ds-table-scroll",
4087
- ref: scroller,
4088
- style: { maxHeight: height },
4089
- onScroll: windowed ? (e) => setScrollTop(e.currentTarget.scrollTop) : void 0,
4090
- children: [
4091
- busy && /* @__PURE__ */ jsx18("div", { className: "ds-table-busy", "aria-hidden": "true" }),
4092
- /* @__PURE__ */ jsxs13("table", { className: "ds-table", "aria-busy": busy || void 0, children: [
4093
- /* @__PURE__ */ jsxs13("thead", { "data-sticky": spec.sticky || void 0, children: [
4094
- /* @__PURE__ */ jsx18("tr", { children: columns.map((c, i) => {
4095
- const sorted = sort?.key === c.key ? sort.order : void 0;
4096
- return /* @__PURE__ */ jsx18(
4097
- "th",
4098
- {
4099
- "data-ds-part": `column:${i}`,
4100
- style: { textAlign: align(c), width: c.width },
4101
- "aria-sort": sorted === "asc" ? "ascending" : sorted === "desc" ? "descending" : void 0,
4102
- children: so.enabled === false || c.sortable === false || c.list !== void 0 ? c.label ?? c.key : /* @__PURE__ */ jsxs13(
4103
- "button",
4104
- {
4105
- type: "button",
4106
- onClick: () => update(
4107
- sorted === "asc" ? { sortKey: c.key, sortOrder: "desc", page: 1 } : sorted === "desc" ? { sortKey: void 0, page: 1 } : { sortKey: c.key, sortOrder: "asc", page: 1 }
4108
- ),
4109
- children: [
4110
- c.label ?? c.key,
4111
- /* @__PURE__ */ jsx18("span", { className: "ds-sort", "data-dir": sorted, "aria-hidden": "true" })
4112
- ]
4113
- }
4114
- )
4115
- },
4116
- `${c.key}-${i}`
4117
- );
4118
- }) }),
4119
- hasFilters && /* @__PURE__ */ jsx18("tr", { className: "ds-filter-row", children: columns.map((c, i) => /* @__PURE__ */ jsx18("th", { children: c.filter === "select" ? /* @__PURE__ */ jsx18(
4120
- SelectControl,
4121
- {
4122
- size: "sm",
4123
- block: true,
4124
- plain: true,
4125
- ariaLabel: `Filter ${c.label ?? c.key}`,
4126
- options: [
4127
- { value: "", label: "All" },
4128
- ...filterChoices(c).map((o) => ({ value: o, label: o }))
4129
- ],
4130
- value: view.filters[c.key] ?? "",
4131
- onChange: (v) => update({ filters: { ...view.filters, [c.key]: String(v ?? "") }, page: 1 })
4132
- }
4133
- ) : c.filter ? /* @__PURE__ */ jsx18(
4134
- "input",
4135
- {
4136
- className: "ds-cell-filter",
4137
- type: c.filter === "min" ? "number" : "text",
4138
- placeholder: c.filter === "min" ? "Min" : "Filter",
4139
- "aria-label": `Filter ${c.label ?? c.key}`,
4140
- value: view.filters[c.key] ?? "",
4141
- onChange: (e) => update({ filters: { ...view.filters, [c.key]: e.target.value }, page: 1 })
4142
- }
4143
- ) : null }, `f-${c.key}-${i}`)) })
4144
- ] }),
4145
- /* @__PURE__ */ jsxs13("tbody", { children: [
4146
- windowed && first > 0 && /* @__PURE__ */ jsx18("tr", { className: "ds-spacer", children: /* @__PURE__ */ jsx18("td", { colSpan: columns.length, style: { height: first * ROW_H, padding: 0 } }) }),
4147
- shown.slice(first, last).map((row, k) => {
4148
- const i = first + k;
4149
- const key = spec.rowKey ? String(field(row, spec.rowKey)) : String(i);
4150
- return /* @__PURE__ */ jsx18(
4151
- "tr",
4152
- {
4153
- "data-muted": muted(row) || void 0,
4154
- onClick: () => emit("rowClick", "row", { datum: row, index: i }),
4155
- onMouseEnter: () => emit("hover", "row", { datum: row, index: i }),
4156
- tabIndex: 0,
4157
- onKeyDown: (e) => e.key === "Enter" && emit("rowClick", "row", { datum: row, index: i }),
4158
- children: columns.map((c, j) => (
4159
- // biome-ignore lint/a11y/useKeyWithClickEvents: rows are focusable and open with Enter; cell clicks add detail for pointer users
4160
- /* @__PURE__ */ jsx18(
4161
- "td",
4162
- {
4163
- style: { textAlign: align(c) },
4164
- onClick: () => emit("cellClick", "cell", { datum: row, index: i, value: field(row, c.key), column: c.key }),
4165
- children: cell(c, row)
4166
- },
4167
- `${c.key}-${j}`
4168
- )
4169
- ))
4170
- },
4171
- key
4172
- );
4173
- }),
4174
- windowed && last < shown.length && /* @__PURE__ */ jsx18("tr", { className: "ds-spacer", children: /* @__PURE__ */ jsx18("td", { colSpan: columns.length, style: { height: (shown.length - last) * ROW_H, padding: 0 } }) })
4175
- ] }),
4176
- spec.totals && /* @__PURE__ */ jsx18("tfoot", { children: /* @__PURE__ */ jsx18("tr", { children: columns.map((c, j) => /* @__PURE__ */ jsx18("td", { style: { textAlign: align(c) }, children: j === 0 && !spec.totals?.columns[c.key] ? spec.totals?.label : total(c) }, `${c.key}-${j}`)) }) })
4177
- ] })
4178
- ]
3897
+ let data;
3898
+ let sourceData;
3899
+ let status = "success";
3900
+ let error;
3901
+ let stale = false;
3902
+ let updatedAt;
3903
+ if (source) {
3904
+ const s = tree.datasources[source];
3905
+ status = s?.status ?? "idle";
3906
+ error = s?.error;
3907
+ stale = Boolean(s?.stale);
3908
+ updatedAt = s?.updatedAt;
3909
+ sourceData = s?.data;
3910
+ data = typeof binding?.path === "string" ? getPath(s?.data, binding.path) : s?.data;
3911
+ } else if (binding && typeof binding.panel === "string")
3912
+ data = getPath(tree.panels[binding.panel], binding.path ?? "selection");
3913
+ else if (binding && typeof binding.state === "string") data = getPath(tree, binding.state);
3914
+ else if (binding && "value" in binding) data = binding.value;
3915
+ else if (!binding && inherited.parentId) data = inherited.data;
3916
+ const { data: _d, ...rest } = spec;
3917
+ let props2 = {};
3918
+ try {
3919
+ props2 = resolvePanel(rest, scope2, Boolean(inherited.hasItem));
3920
+ } catch (e) {
3921
+ error = { code: "template", message: e.message };
4179
3922
  }
4180
- ),
4181
- pageSize && /* @__PURE__ */ jsxs13("div", { className: "ds-pager", children: [
4182
- /* @__PURE__ */ jsxs13("span", { className: "ds-pager-size", children: [
4183
- "Rows",
4184
- /* @__PURE__ */ jsx18(
4185
- SelectControl,
4186
- {
4187
- size: "sm",
4188
- plain: true,
4189
- ariaLabel: "Rows per page",
4190
- options: (pg?.pageSizes ?? [10, 20, 50, 100]).map((n) => ({ value: n, label: String(n) })),
4191
- value: pageSize,
4192
- onChange: (v) => update({ pageSize: Number(v), page: 1 })
4193
- }
4194
- )
4195
- ] }),
4196
- /* @__PURE__ */ jsxs13("span", { children: [
4197
- rowTotal === 0 ? 0 : (current - 1) * pageSize + 1,
4198
- "\u2013",
4199
- Math.min(current * pageSize, rowTotal),
4200
- " of",
4201
- " ",
4202
- helpers.fmt.number(rowTotal)
4203
- ] }),
4204
- /* @__PURE__ */ jsxs13("span", { className: "ds-pages", children: [
4205
- /* @__PURE__ */ jsx18(
4206
- "button",
4207
- {
4208
- type: "button",
4209
- "aria-label": "Previous page",
4210
- disabled: current <= 1,
4211
- onClick: () => update({ page: current - 1 }),
4212
- children: "\u2039"
4213
- }
4214
- ),
4215
- pageList(current, pages).map(
4216
- (n, i) => n === 0 ? /* @__PURE__ */ jsx18("span", { className: "ds-page-gap", children: "\u2026" }, `gap-${i < 3 ? "a" : "b"}`) : /* @__PURE__ */ jsx18(
4217
- "button",
4218
- {
4219
- type: "button",
4220
- "aria-current": n === current ? "page" : void 0,
4221
- onClick: () => update({ page: n }),
4222
- children: n
4223
- },
4224
- n
4225
- )
4226
- ),
4227
- /* @__PURE__ */ jsx18(
4228
- "button",
4229
- {
4230
- type: "button",
4231
- "aria-label": "Next page",
4232
- disabled: current >= pages,
4233
- onClick: () => update({ page: current + 1 }),
4234
- children: "\u203A"
4235
- }
4236
- )
4237
- ] })
4238
- ] })
4239
- ] });
4240
- }
4241
- });
4242
-
4243
- // src/widgets/builtins/Tiles.tsx
4244
- import "zod";
4245
- import { Fragment as Fragment5, jsx as jsx19, jsxs as jsxs14 } from "react/jsx-runtime";
4246
- var Tiles = defineWidget({
4247
- ...TilesContract,
4248
- implements: "tiles",
4249
- exposes: { selection: "the clicked tile's row" },
4250
- meta: { label: "Tiles", icon: "tiles", category: "Numbers", size: { w: 12, h: 4, minW: 3, minH: 3 } },
4251
- events: ["click", "hover", "select"],
4252
- parts: ["tile"],
4253
- defaults: { label: "name", value: "value" },
4254
- component: function TilesWidget({ spec, data, emit, helpers }) {
4255
- const rows = asRows(data);
4256
- const caption = (row) => {
4257
- if (!spec.caption) return void 0;
4258
- try {
4259
- return String(interpolate(spec.caption, scope({ row }, helpers)) ?? "");
4260
- } catch {
4261
- return spec.caption;
4262
- }
3923
+ const msg = def.messages;
3924
+ const messages = msg ? resolvePanel(msg, scope2) : void 0;
3925
+ const group = props2.highlight ?? void 0;
3926
+ return {
3927
+ visible,
3928
+ hidden: Boolean(ps.hidden),
3929
+ panel: ps,
3930
+ source,
3931
+ data,
3932
+ sourceData,
3933
+ status,
3934
+ error,
3935
+ stale,
3936
+ updatedAt,
3937
+ props: props2,
3938
+ messages,
3939
+ highlight: group ? tree.highlight[group] : void 0,
3940
+ x: level?.x ?? void 0
3941
+ };
3942
+ },
3943
+ [id, runtime, inherited.parentId, inherited.data, inherited.parentData, inherited.item, inherited.index]
3944
+ ),
3945
+ samePanelView
3946
+ );
3947
+ const renderNested = useCallback4((child) => /* @__PURE__ */ jsx14(PanelFrame, { id: child, nested: true }, child), []);
3948
+ const store = useMemo3(() => widgetStore(runtime), [runtime]);
3949
+ const [bodyRef, size2] = useSize();
3950
+ const frameRef = useRef5(null);
3951
+ useEffect3(() => {
3952
+ if (!view.visible || view.hidden) {
3953
+ visibility.set(instance, null);
3954
+ return;
3955
+ }
3956
+ const el = frameRef.current;
3957
+ if (!el || typeof IntersectionObserver === "undefined") {
3958
+ visibility.set(instance, view.source ? [view.source] : []);
3959
+ return () => visibility.set(instance, null);
3960
+ }
3961
+ const io = new IntersectionObserver(
3962
+ ([e]) => visibility.set(instance, e?.isIntersecting && view.source ? [view.source] : []),
3963
+ { rootMargin: "200px" }
3964
+ );
3965
+ io.observe(el);
3966
+ return () => {
3967
+ io.disconnect();
3968
+ visibility.set(instance, null);
4263
3969
  };
4264
- return /* @__PURE__ */ jsx19(
4265
- "div",
3970
+ }, [instance, view.visible, view.hidden, view.source, visibility]);
3971
+ const emit = useCallback4(
3972
+ (type, part, detail) => {
3973
+ const event = { type, panel: id, ...part ? { part } : {}, ...detail };
3974
+ options.onEvent?.(event);
3975
+ void runtime.emit(event);
3976
+ },
3977
+ [id, options, runtime]
3978
+ );
3979
+ const run = useCallback4(
3980
+ (action, detail) => void runtime.runAction(action, { type: "click", panel: id, ...detail }),
3981
+ [runtime, id]
3982
+ );
3983
+ const setUi = useCallback4(
3984
+ (patch) => runtime.store.dispatch(
3985
+ stateActions.patchPanel({ id, patch: { ui: { ...runtime.getTree().panels[id]?.ui, ...patch } } })
3986
+ ),
3987
+ [runtime, id]
3988
+ );
3989
+ const dataRef = useRef5(view.data);
3990
+ dataRef.current = view.data;
3991
+ const props = useMemo3(() => {
3992
+ let p = { ...view.props, ...view.panel.props ?? {} };
3993
+ if (view.x) p = { ...p, x: view.x };
3994
+ p = withFunctions(p, (code) => {
3995
+ const f = runtime.scripts.fnProp(code, ["p", "data"]);
3996
+ return (arg) => {
3997
+ try {
3998
+ return f(arg, dataRef.current);
3999
+ } catch (e) {
4000
+ console.warn(`[dashspec] ${id}: function prop failed: ${e.message}`);
4001
+ return "";
4002
+ }
4003
+ };
4004
+ });
4005
+ return widget ? parseWidgetProps(widget.schema, p).props : p;
4006
+ }, [view.props, view.panel.props, view.x, runtime, widget, id]);
4007
+ if (!view.visible || view.hidden) return null;
4008
+ const ownHeader = widget?.header === "widget";
4009
+ const title = ownHeader ? void 0 : props.title;
4010
+ const info = ownHeader ? void 0 : props.info;
4011
+ const meta2 = props.meta;
4012
+ const live2 = Boolean(props.live);
4013
+ const drill = view.panel.drill ?? [];
4014
+ const controls = def.controls ?? [];
4015
+ const tone2 = def.style?.tone ?? (widget?.frame === "plain" ? "plain" : "default");
4016
+ const headerKids = slotChildren(def, "header");
4017
+ const footerKids = slotChildren(def, "footer");
4018
+ const hideHeader = Boolean(def.style?.hideHeader) || !title && !meta2 && !live2 && drill.length === 0 && controls.length === 0 && !view.stale && headerKids.length === 0;
4019
+ const dnd = Boolean(options.onDropOnPanel);
4020
+ let body;
4021
+ if (!widget) body = /* @__PURE__ */ jsxs9("div", { className: "ds-state", children: [
4022
+ "Unknown widget \u201C",
4023
+ String(def.kind),
4024
+ "\u201D"
4025
+ ] });
4026
+ else if (view.error && view.data === void 0)
4027
+ body = options.renderError?.(view.error, id) ?? /* @__PURE__ */ jsx14("div", { className: "ds-state ds-state-error", role: "alert", children: view.messages?.error ?? view.error.message });
4028
+ else if (view.source && view.data === void 0 && (view.status === "loading" || view.status === "idle"))
4029
+ body = options.renderLoading?.(id, loadingText(view.messages)) ?? /* @__PURE__ */ jsx14(LoadingState, { text: loadingText(view.messages) });
4030
+ else if (view.source && isEmpty(view.data) && widget.empty !== "widget")
4031
+ body = options.renderEmpty?.(id) ?? /* @__PURE__ */ jsx14("div", { className: "ds-state", children: view.messages?.empty ?? "No data" });
4032
+ else {
4033
+ const W = widget.component;
4034
+ body = /* @__PURE__ */ jsx14(
4035
+ Boundary,
4266
4036
  {
4267
- className: "ds-tiles",
4268
- role: spec.selectable ? "radiogroup" : "list",
4269
- "aria-label": spec.title,
4270
- "data-wrap": spec.wrap === false ? "off" : void 0,
4271
- style: {
4272
- "--ds-tile-min": `${spec.minTileWidth ?? 128}px`,
4273
- ...spec.columns ? { "--ds-tile-cols": spec.columns } : {}
4274
- },
4275
- children: rows.map((r, i) => {
4276
- const label = field(r, spec.label);
4277
- const v = field(r, spec.value);
4278
- const n = toNumber(v);
4279
- const status = spec.status ? String(field(r, spec.status)) : void 0;
4280
- const st = status ? spec.statusMap?.[status] ?? status : void 0;
4281
- const vt = n === void 0 || !spec.valueTone ? void 0 : n > 0 ? spec.valueTone.positive : n < 0 ? spec.valueTone.negative : spec.valueTone.zero;
4282
- const active = spec.selectable && spec.selected !== void 0 && spec.selected === label;
4283
- return /* @__PURE__ */ jsxs14(
4284
- "button",
4285
- {
4286
- type: "button",
4287
- className: "ds-tile",
4288
- role: spec.selectable ? "radio" : "listitem",
4289
- "aria-checked": spec.selectable ? active : void 0,
4290
- "data-active": active || void 0,
4291
- onClick: () => {
4292
- emit("click", "tile", { datum: r, value: label, index: i });
4293
- if (spec.selectable) emit("select", "tile", { datum: r, value: label, index: i });
4294
- },
4295
- onMouseEnter: () => emit("hover", "tile", { datum: r, value: label, index: i }),
4296
- children: [
4297
- /* @__PURE__ */ jsxs14("span", { className: "ds-tile-label", children: [
4298
- st && /* @__PURE__ */ jsx19("span", { className: "ds-dot", style: { background: tone(st).solid }, "aria-hidden": "true" }),
4299
- String(label ?? ""),
4300
- spec.count && /* @__PURE__ */ jsx19("span", { className: "ds-chip-count", children: String(field(r, spec.count) ?? "") })
4301
- ] }),
4302
- /* @__PURE__ */ jsxs14(
4303
- "span",
4304
- {
4305
- className: "ds-tile-value",
4306
- style: vt ? { color: vt === "muted" ? "var(--ds-color-text-disabled)" : tone(vt).fg } : void 0,
4307
- children: [
4308
- /* @__PURE__ */ jsx19(CountUp, { value: v, render: (x) => formatValue(x, helpers, spec.format, spec.decimals) }),
4309
- spec.unit && /* @__PURE__ */ jsx19("span", { className: "ds-kpi-unit", children: spec.unit })
4310
- ]
4311
- }
4312
- ),
4313
- spec.caption && /* @__PURE__ */ jsx19("span", { className: "ds-tile-caption", children: caption(r) })
4314
- ]
4315
- },
4316
- `${String(label)}-${i}`
4317
- );
4318
- })
4037
+ resetKeys: [view.data, props],
4038
+ fallback: (e) => /* @__PURE__ */ jsxs9("div", { className: "ds-state ds-state-error", role: "alert", children: [
4039
+ "This panel could not be shown: ",
4040
+ e.message
4041
+ ] }),
4042
+ children: /* @__PURE__ */ jsx14(
4043
+ W,
4044
+ {
4045
+ spec: props,
4046
+ data: view.data,
4047
+ source: view.sourceData,
4048
+ run,
4049
+ emit,
4050
+ state: view.panel,
4051
+ setUi,
4052
+ status: view.status,
4053
+ highlight: view.highlight,
4054
+ size: size2,
4055
+ mode: options.mode,
4056
+ helpers: runtime.helpers,
4057
+ panelId: id,
4058
+ renderSlot: (name, o) => /* @__PURE__ */ jsx14(Slot, { name, ...o }),
4059
+ store
4060
+ }
4061
+ )
4319
4062
  }
4320
4063
  );
4321
4064
  }
4322
- });
4323
- function CountUp({ value, render }) {
4324
- const n = toNumber(value);
4325
- const shown = useCountUp(n ?? value);
4326
- return /* @__PURE__ */ jsx19(Fragment5, { children: render(n === void 0 ? value : shown) });
4327
- }
4328
-
4329
- // src/widgets/builtins/atoms.tsx
4330
- import "zod";
4331
-
4332
- // src/widgets/shared/clickable.ts
4333
- import { useContext as useContext4 } from "react";
4334
-
4335
- // src/components/PanelFrame.tsx
4336
- import { useCallback as useCallback4, useEffect as useEffect5, useId as useId3, useMemo as useMemo4, useRef as useRef7, useState as useState6 } from "react";
4337
-
4338
- // src/widgets/parseProps.ts
4339
- function without(value, path) {
4340
- if (path.length === 0 || value === null || typeof value !== "object") return value;
4341
- const [head, ...rest] = path;
4342
- if (Array.isArray(value)) {
4343
- if (typeof head !== "number" || head < 0 || head >= value.length) return value;
4344
- const copy2 = [...value];
4345
- if (rest.length === 0) copy2.splice(head, 1);
4346
- else copy2[head] = without(copy2[head], rest);
4347
- return copy2;
4348
- }
4349
- if (!Object.hasOwn(value, head)) return value;
4350
- const copy = { ...value };
4351
- if (rest.length === 0) delete copy[head];
4352
- else copy[head] = without(copy[head], rest);
4353
- return copy;
4354
- }
4355
- function parseWidgetProps(schema, props) {
4356
- let current = props;
4357
- const dropped = [];
4358
- for (let round = 0; round < 25; round++) {
4359
- const r = schema.safeParse(current);
4360
- if (r.success) return { props: r.data, dropped };
4361
- const issue = r.error.issues.find((i) => i.path.length > 0);
4362
- if (!issue) break;
4363
- const lastIndex = issue.path.reduce((at, k, i) => typeof k === "number" ? i : at, -1);
4364
- const path = lastIndex >= 0 ? issue.path.slice(0, lastIndex + 1) : issue.path;
4365
- const next = without(current, path);
4366
- if (next === current) break;
4367
- dropped.push(path.join("."));
4368
- current = next;
4369
- }
4370
- return { props, dropped };
4371
- }
4372
-
4373
- // src/components/Boundary.tsx
4374
- import { Component } from "react";
4375
- var sameKeys = (a, b) => a.length === b.length && a.every((x, i) => Object.is(x, b[i]));
4376
- var Boundary = class extends Component {
4377
- state = { error: null };
4378
- static getDerivedStateFromError(error) {
4379
- return { error };
4380
- }
4381
- componentDidCatch(error, _info) {
4382
- this.props.onError?.(error);
4383
- }
4384
- componentDidUpdate(prev) {
4385
- if (this.state.error && !sameKeys(prev.resetKeys ?? [], this.props.resetKeys ?? [])) this.setState({ error: null });
4386
- }
4387
- render() {
4388
- return this.state.error ? this.props.fallback(this.state.error) : this.props.children;
4389
- }
4390
- };
4391
-
4392
- // src/components/Slot.tsx
4393
- import { createContext as createContext3, useContext as useContext3 } from "react";
4394
- import { Fragment as Fragment6, jsx as jsx20, jsxs as jsxs15 } from "react/jsx-runtime";
4395
- var NodeScopeContext = createContext3({});
4396
- var useNodeScope = () => useContext3(NodeScopeContext);
4397
- var SlotOwnerContext = createContext3(null);
4398
- var SlotChildContext = createContext3(null);
4399
- function slotChildren(def, name) {
4400
- const slots = def?.slots;
4401
- const list = slots?.[name];
4402
- return Array.isArray(list) ? list.filter((x) => typeof x === "string") : [];
4403
- }
4404
- function Slot({
4405
- name,
4406
- className,
4407
- style,
4408
- data,
4409
- item,
4410
- index,
4411
- empty
4412
- }) {
4413
- const { options } = useDashboard();
4414
- const owner = useContext3(SlotOwnerContext);
4415
- const outer = useNodeScope();
4416
- const renderChild = useContext3(SlotChildContext);
4417
- if (!owner || !renderChild) return null;
4418
- const ids = slotChildren(owner.def, name);
4419
- const editing = options.mode === "edit";
4420
- if (ids.length === 0 && !editing) return null;
4421
- const hasItem = item !== void 0 || outer.hasItem;
4422
- const scope2 = {
4423
- parentId: owner.id,
4424
- parentData: owner.data,
4425
- data: data !== void 0 ? data : item !== void 0 ? item : owner.data,
4426
- hasItem: Boolean(hasItem),
4427
- item: item !== void 0 ? item : outer.item,
4428
- index: index !== void 0 ? index : outer.index
4429
- };
4430
- return /* @__PURE__ */ jsx20(NodeScopeContext.Provider, { value: scope2, children: /* @__PURE__ */ jsxs15(
4431
- "div",
4432
- {
4433
- className: className ? `ds-slot ${className}` : "ds-slot",
4434
- style,
4435
- "data-slot": name,
4436
- "data-owner": owner.id,
4437
- "data-empty": ids.length === 0 || void 0,
4065
+ const selected = options.selectedPanel === id;
4066
+ const defaultSlot = widget?.slots ? Object.keys(widget.slots)[0] ?? "header" : "header";
4067
+ const dropTarget = (target, x, y) => {
4068
+ const own = `[data-slot][data-owner="${CSS.escape(id)}"]`;
4069
+ const el = target?.closest(own) ?? frameRef.current?.querySelector(`${own}:not([data-slot="header"]):not([data-slot="footer"])`) ?? void 0;
4070
+ const name = el?.getAttribute("data-slot") ?? defaultSlot;
4071
+ return { slot: name, index: el ? indexIn(el, x, y) : void 0 };
4072
+ };
4073
+ return /* @__PURE__ */ jsx14(SlotOwnerContext.Provider, { value: { id, data: view.data, def }, children: /* @__PURE__ */ jsx14(SlotChildContext.Provider, { value: renderNested, children: /* @__PURE__ */ jsxs9(
4074
+ "section",
4075
+ {
4076
+ ref: frameRef,
4077
+ className: "ds-panel",
4078
+ style: panelStyle(def.style),
4079
+ "data-tone": tone2,
4080
+ "data-panel": id,
4081
+ "data-selected": selected || void 0,
4082
+ "data-nested": nested || void 0,
4083
+ "aria-label": title ?? id,
4084
+ draggable: dnd && nested ? true : void 0,
4085
+ onDragStart: dnd && nested ? (e) => {
4086
+ e.stopPropagation();
4087
+ e.dataTransfer.setData("text/plain", id);
4088
+ e.dataTransfer.effectAllowed = "move";
4089
+ options.onDragPanelStart?.(id);
4090
+ } : void 0,
4091
+ onDragOver: dnd ? (e) => {
4092
+ const t = dropTarget(e.target, e.clientX, e.clientY);
4093
+ if (!options.canDropOn?.(id, void 0, t.slot)) return;
4094
+ e.preventDefault();
4095
+ e.stopPropagation();
4096
+ frameRef.current?.setAttribute("data-drop-over", t.slot);
4097
+ } : void 0,
4098
+ onDragLeave: dnd ? (e) => {
4099
+ if (!frameRef.current?.contains(e.relatedTarget))
4100
+ frameRef.current?.removeAttribute("data-drop-over");
4101
+ } : void 0,
4102
+ onDrop: dnd ? (e) => {
4103
+ frameRef.current?.removeAttribute("data-drop-over");
4104
+ const t = dropTarget(e.target, e.clientX, e.clientY);
4105
+ if (!options.canDropOn?.(id, void 0, t.slot)) return;
4106
+ e.preventDefault();
4107
+ e.stopPropagation();
4108
+ options.onDropOnPanel?.(id, t.index, void 0, t.slot);
4109
+ } : void 0,
4110
+ onPointerDownCapture: options.onPanelSelect ? (e) => {
4111
+ const el = partAt(e.target, frameRef.current);
4112
+ markPart(frameRef.current, el?.node);
4113
+ options.onPanelSelect?.(id, el?.part);
4114
+ } : void 0,
4115
+ onClickCapture: options.onPanelSelect ? (e) => {
4116
+ e.preventDefault();
4117
+ e.stopPropagation();
4118
+ } : void 0,
4438
4119
  children: [
4439
- ids.map((id) => /* @__PURE__ */ jsx20(SlotItem, { children: renderChild(id) }, id)),
4440
- ids.length === 0 && editing && (empty ?? /* @__PURE__ */ jsx20("span", { className: "ds-slot-hint", children: "Drop here" }))
4120
+ !hideHeader && /* @__PURE__ */ jsxs9("header", { className: "ds-panel-head", children: [
4121
+ /* @__PURE__ */ jsxs9("div", { style: { minWidth: 0 }, children: [
4122
+ title && /* @__PURE__ */ jsxs9("h3", { className: "ds-panel-title", children: [
4123
+ title,
4124
+ info && /* @__PURE__ */ jsx14(InfoTip, { text: info })
4125
+ ] }),
4126
+ drill.length > 0 && /* @__PURE__ */ jsxs9("nav", { className: "ds-crumbs", "aria-label": "Drill path", children: [
4127
+ /* @__PURE__ */ jsx14("button", { type: "button", onClick: () => runtime.runAction({ do: "drillReset", panel: id }), children: "All" }),
4128
+ drill.map((d, i) => /* @__PURE__ */ jsxs9("span", { children: [
4129
+ "\u203A",
4130
+ " ",
4131
+ i < drill.length - 1 ? /* @__PURE__ */ jsx14(
4132
+ "button",
4133
+ {
4134
+ type: "button",
4135
+ onClick: () => runtime.store.dispatch(
4136
+ stateActions.patchPanel({ id, patch: { drill: drill.slice(0, i + 1) } })
4137
+ ),
4138
+ children: String(d.value)
4139
+ }
4140
+ ) : String(d.value)
4141
+ ] }, `${d.level}-${i}`))
4142
+ ] })
4143
+ ] }),
4144
+ /* @__PURE__ */ jsxs9("div", { className: "ds-panel-tools", children: [
4145
+ headerKids.length > 0 && /* @__PURE__ */ jsx14(Slot, { name: "header", className: "ds-panel-addons" }),
4146
+ meta2 && /* @__PURE__ */ jsx14("span", { className: "ds-panel-meta", children: meta2 }),
4147
+ live2 ? /* @__PURE__ */ jsxs9("span", { className: "ds-live", "data-stale": view.stale || void 0, title: view.error?.message, children: [
4148
+ /* @__PURE__ */ jsx14("span", { "aria-hidden": "true" }),
4149
+ "Live, updated ",
4150
+ view.updatedAt ? runtime.helpers.fmt.ago(view.updatedAt) : "\u2026"
4151
+ ] }) : view.stale && /* @__PURE__ */ jsx14("span", { className: "ds-badge ds-badge-stale", title: view.error?.message, children: "Stale" }),
4152
+ controls.map((c) => /* @__PURE__ */ jsx14(
4153
+ ControlField,
4154
+ {
4155
+ def: c,
4156
+ compact: true,
4157
+ value: view.panel.controls?.[c.name],
4158
+ onChange: (v) => runtime.store.dispatch(
4159
+ stateActions.patchPanel({
4160
+ id,
4161
+ patch: { controls: { ...view.panel.controls, [c.name]: v } }
4162
+ })
4163
+ )
4164
+ },
4165
+ c.name
4166
+ ))
4167
+ ] })
4168
+ ] }),
4169
+ /* @__PURE__ */ jsx14("div", { className: "ds-panel-body", ref: bodyRef, children: body }),
4170
+ footerKids.length > 0 && /* @__PURE__ */ jsx14(Slot, { name: "footer", className: "ds-panel-foot" })
4441
4171
  ]
4442
4172
  }
4443
- ) });
4444
- }
4445
- var SlotItem = ({ children }) => /* @__PURE__ */ jsx20(Fragment6, { children });
4446
-
4447
- // src/components/PanelFrame.tsx
4448
- import { jsx as jsx21, jsxs as jsxs16 } from "react/jsx-runtime";
4449
- var isEmpty = (d) => d === void 0 || d === null || Array.isArray(d) && d.length === 0 || typeof d === "object" && !Array.isArray(d) && Object.keys(d).length === 0;
4450
- function useSize() {
4451
- const [size2, setSize] = useState6({ width: 0, height: 0 });
4452
- const observer = useRef7(null);
4453
- const ref = useCallback4((el) => {
4454
- observer.current?.disconnect();
4455
- observer.current = null;
4456
- if (!el || typeof ResizeObserver === "undefined") return;
4457
- const ro = new ResizeObserver(([e]) => {
4458
- const r = e?.contentRect;
4459
- if (r)
4460
- setSize(
4461
- (s) => s.width === Math.round(r.width) && s.height === Math.round(r.height) ? s : { width: Math.round(r.width), height: Math.round(r.height) }
4462
- );
4463
- });
4464
- ro.observe(el);
4465
- observer.current = ro;
4466
- }, []);
4467
- return [ref, size2];
4468
- }
4469
- var DEFERRED = /(^|[^\w.$])(row|item|avg)\b/;
4470
- var DEFERRED_IN_ITEM = /(^|[^\w.$])(row|avg)\b/;
4471
- function interpolateMarkdown(v, scope2) {
4472
- const bodies = placeholders(v);
4473
- const whole = bodies.length === 1 && v.trim() === `\${${bodies[0]}}`;
4474
- const r = interpolate(v, scope2, escapeMarkdown);
4475
- if (!whole) return r;
4476
- return r === null || r === void 0 ? "" : escapeMarkdown(typeof r === "object" ? JSON.stringify(r) : String(r));
4477
- }
4478
- function resolvePanel(v, scope2, inItem = false, key) {
4479
- const deferred = inItem ? DEFERRED_IN_ITEM : DEFERRED;
4480
- if (typeof v === "string") {
4481
- if (placeholders(v).some((b) => deferred.test(stripStrings(b)))) return v;
4482
- return key === "markdown" ? interpolateMarkdown(v, scope2) : interpolate(v, scope2);
4483
- }
4484
- if (Array.isArray(v)) return v.map((x) => resolvePanel(x, scope2, inItem));
4485
- if (v && typeof v === "object")
4486
- return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, resolvePanel(x, scope2, inItem, k)]));
4487
- return v;
4488
- }
4489
- function withFunctions(v, make) {
4490
- if (Array.isArray(v)) return v.map((x) => withFunctions(x, make));
4491
- if (v && typeof v === "object") {
4492
- const o = v;
4493
- if (typeof o.fn === "string" && Object.keys(o).length === 1) return make(o.fn);
4494
- return Object.fromEntries(Object.entries(o).map(([k, x]) => [k, withFunctions(x, make)]));
4495
- }
4496
- return v;
4497
- }
4498
- var SHADOWS = {
4499
- none: "none",
4500
- sm: "0 1px 3px rgba(13, 13, 13, 0.08)",
4501
- md: "0 6px 16px rgba(13, 13, 13, 0.10)",
4502
- lg: "0 14px 36px rgba(13, 13, 13, 0.14)"
4503
- };
4504
- var PADDING = { none: "0", compact: "8px", roomy: "24px" };
4505
- var colour = (v) => {
4506
- if (typeof v !== "string" || !v) return void 0;
4507
- if (/^[a-z]+(-[a-z]+)+$/.test(v) && !v.includes("(")) return `var(--ds-color-${v})`;
4508
- return /^(#[0-9a-f]{3,8}|rgba?\([\d\s.,%]+\)|hsla?\([\d\s.,%deg]+\)|[a-z]+)$/i.test(v) ? v : void 0;
4509
- };
4510
- var size = (v) => typeof v === "number" ? `${v}px` : typeof v === "string" && /^[\d.]+(px|%|rem|em|vw)?$/.test(v) ? v : void 0;
4511
- var PART_CLASSES = [
4512
- [".ds-panel-title, .ds-kpi-label", "title"],
4513
- [".ds-info", "info"],
4514
- [".ds-panel-meta, .ds-live", "meta"],
4515
- [".ds-kpi-foot", "target"],
4516
- [".ds-chip", "badge"],
4517
- [".ds-kpi-main, .ds-kpi-value, .ds-kpi-unit", "value"],
4518
- [".ds-kpi-sub, .ds-kpi-delta", "note"],
4519
- [".ds-tile", "tile"],
4520
- [".ds-meters > *, .ds-segbar, .ds-legend", "bars"],
4521
- [".ds-status, .ds-pill", "state"],
4522
- [".ds-table-tools", "tools"],
4523
- [".ds-pager", "pager"]
4524
- ];
4525
- var PART_SELECTOR = ["[data-ds-part]", ...PART_CLASSES.map(([sel]) => sel)].join(", ");
4526
- function partAt(target, frame) {
4527
- let el = target?.closest(PART_SELECTOR) ?? null;
4528
- while (el && frame?.contains(el)) {
4529
- if (el.closest(".ds-panel") !== frame) return void 0;
4530
- const own = el.getAttribute("data-ds-part");
4531
- if (own) return { part: own, node: el };
4532
- const hit = PART_CLASSES.find(([sel]) => el?.matches(sel));
4533
- if (hit) return { part: hit[1], node: el };
4534
- el = el.parentElement?.closest(PART_SELECTOR) ?? null;
4535
- }
4536
- return void 0;
4173
+ ) }) });
4537
4174
  }
4538
- function markPart(frame, node) {
4539
- const root = frame?.closest(".ds-root") ?? frame?.ownerDocument;
4540
- for (const n of root?.querySelectorAll(".ds-part-selected") ?? []) n.classList.remove("ds-part-selected");
4541
- node?.classList.add("ds-part-selected");
4175
+ function loadingText(messages) {
4176
+ const v = messages?.loading;
4177
+ return v === void 0 || v === null || v === "" ? void 0 : String(v);
4542
4178
  }
4543
- function panelStyle(s) {
4544
- if (!s) return void 0;
4545
- const out = {};
4546
- const bg = colour(s.background);
4547
- if (bg) out.background = bg;
4548
- if (typeof s.borderWidth === "number" || s.borderColor)
4549
- out.border = `${s.borderWidth ?? 1}px solid ${colour(s.borderColor) ?? "var(--ds-color-border-default)"}`;
4550
- if (typeof s.radius === "number") out.borderRadius = s.radius;
4551
- if (typeof s.shadow === "string" && SHADOWS[s.shadow]) out.boxShadow = SHADOWS[s.shadow];
4552
- if (typeof s.padding === "number") out.padding = s.padding;
4553
- else if (typeof s.padding === "string" && PADDING[s.padding]) out.padding = PADDING[s.padding];
4554
- if (typeof s.minHeight === "number") out.minHeight = s.minHeight;
4555
- if (typeof s.flex === "string" && /^[\d.\s]*(auto|[\d.]+(px|%|rem)?)?$/.test(s.flex)) out.flex = s.flex;
4556
- const minW = size(s.minWidth);
4557
- const maxW = size(s.maxWidth);
4558
- if (minW) out.minWidth = minW;
4559
- if (maxW) out.maxWidth = maxW;
4560
- if (typeof s.align === "string")
4561
- out.alignSelf = s.align === "start" ? "flex-start" : s.align === "end" ? "flex-end" : s.align;
4562
- return Object.keys(out).length ? out : void 0;
4179
+ function LoadingState({ text }) {
4180
+ if (!text) return /* @__PURE__ */ jsx14("div", { className: "ds-skeleton", "aria-busy": "true", "aria-label": "Loading" });
4181
+ return /* @__PURE__ */ jsxs9("output", { className: "ds-loading", "aria-busy": "true", children: [
4182
+ /* @__PURE__ */ jsx14("div", { className: "ds-skeleton", "aria-hidden": "true" }),
4183
+ /* @__PURE__ */ jsx14("span", { className: "ds-loading-text", children: text })
4184
+ ] });
4563
4185
  }
4564
- var samePanelView = (a, b) => Object.keys(a).every(
4565
- (k) => k === "data" || k === "sourceData" ? Object.is(a[k], b[k]) : Object.is(a[k], b[k]) || JSON.stringify(a[k]) === JSON.stringify(b[k])
4566
- );
4567
- var RESERVED = /^(filters|panels|view|modal|highlight|datasources|context)(\.|$)/;
4568
- function widgetStore(runtime) {
4569
- const get = (path) => getPath(runtime.getTree(), path);
4186
+
4187
+ // src/widgets/shared/clickable.ts
4188
+ function useClickable(panelId, activate) {
4189
+ const ctx = useContext4(DashboardContext);
4190
+ const def = ctx && panelId ? findPanel(ctx.runtime.doc, panelId) : void 0;
4191
+ const on = def?.on;
4192
+ if (on?.click === void 0) return { onClick: activate };
4570
4193
  return {
4571
- get,
4572
- use: function useStoreValue(pathOrSelect) {
4573
- return useTree(
4574
- useCallback4(
4575
- (t) => typeof pathOrSelect === "string" ? getPath(t, pathOrSelect) : pathOrSelect(t),
4576
- [pathOrSelect]
4577
- ),
4578
- (a, b) => Object.is(a, b) || JSON.stringify(a) === JSON.stringify(b)
4579
- );
4580
- },
4581
- set: (path, value) => {
4582
- if (RESERVED.test(path)) throw new Error(`"${path}" belongs to the runtime; use setFilter or an action`);
4583
- runtime.store.dispatch(stateActions.set({ path, value }));
4584
- },
4585
- setFilter: (name, value) => runtime.store.dispatch(stateActions.setFilter({ name, value })),
4586
- subscribe: (path, fn) => {
4587
- let prev = get(path);
4588
- return runtime.store.subscribe(() => {
4589
- const next = get(path);
4590
- if (!Object.is(next, prev) && JSON.stringify(next) !== JSON.stringify(prev)) {
4591
- prev = next;
4592
- fn(next);
4194
+ onClick: activate,
4195
+ role: "button",
4196
+ tabIndex: 0,
4197
+ onKeyDown: (e) => {
4198
+ if (e.key !== "Enter" && e.key !== " ") return;
4199
+ e.preventDefault();
4200
+ activate();
4201
+ }
4202
+ };
4203
+ }
4204
+
4205
+ // src/widgets/shared/motion.ts
4206
+ import { useEffect as useEffect4, useRef as useRef6, useState as useState5 } from "react";
4207
+ var reduced = () => typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
4208
+ var easeOut = (t) => 1 - (1 - t) ** 3;
4209
+ function useCountUp(target, ms = 700) {
4210
+ const [shown, setShown] = useState5(() => typeof target === "number" && !reduced() ? 0 : target);
4211
+ const from = useRef6(0);
4212
+ useEffect4(() => {
4213
+ if (typeof target !== "number" || !Number.isFinite(target) || reduced()) {
4214
+ setShown(target);
4215
+ return;
4216
+ }
4217
+ const start = performance.now();
4218
+ const a = from.current;
4219
+ let raf = 0;
4220
+ const step = (now) => {
4221
+ const t = Math.min(1, (now - start) / ms);
4222
+ const v = a + (target - a) * easeOut(t);
4223
+ setShown(Number.isInteger(target) && t === 1 ? target : v);
4224
+ if (t < 1) raf = requestAnimationFrame(step);
4225
+ else from.current = target;
4226
+ };
4227
+ raf = requestAnimationFrame(step);
4228
+ return () => {
4229
+ cancelAnimationFrame(raf);
4230
+ from.current = typeof target === "number" ? target : 0;
4231
+ };
4232
+ }, [target, ms]);
4233
+ return shown;
4234
+ }
4235
+
4236
+ // src/widgets/builtins/Kpi.tsx
4237
+ import { Fragment as Fragment5, jsx as jsx15, jsxs as jsxs10 } from "react/jsx-runtime";
4238
+ var Kpi = defineWidget({
4239
+ ...KpiContract,
4240
+ implements: "kpi",
4241
+ header: "widget",
4242
+ empty: "widget",
4243
+ meta: { label: "KPI", icon: "kpi", category: "Numbers", size: { w: 3, h: 4, minW: 2, minH: 3 } },
4244
+ events: ["click", "hover"],
4245
+ parts: ["value"],
4246
+ defaults: { title: "New KPI", goodWhen: "up" },
4247
+ component: function KpiWidget({ spec, data, source, emit, helpers, panelId }) {
4248
+ const clickable = useClickable(panelId, () => {
4249
+ }).role === "button";
4250
+ const num = (v) => typeof v === "number" ? v : toNumber(field(source, v));
4251
+ const value = toNumber(data) ?? data;
4252
+ const animated = useCountUp(value);
4253
+ const n = toNumber(value);
4254
+ const fmt = (v) => formatValue(v, helpers, spec.format, spec.decimals);
4255
+ const unit = spec.format === "duration" ? void 0 : spec.unit;
4256
+ const empty = spec.empty === true || value === void 0 || value === null || value === "";
4257
+ const hasTarget = spec.target !== void 0;
4258
+ const target = hasTarget ? num(spec.target) : void 0;
4259
+ const op = spec.goodWhen === "down" ? "\u2264 " : spec.goodWhen === "up" ? "\u2265 " : "";
4260
+ const targetText = spec.targetLabel ?? (target !== void 0 ? `Target: ${op}${fmt(target)}${unit ? spec.format === "percent" ? "" : ` ${unit.toLowerCase()}` : ""}` : void 0);
4261
+ const met = target === void 0 || n === void 0 || spec.goodWhen === "none" ? void 0 : spec.goodWhen === "down" ? n <= target : n >= target;
4262
+ const labels = { good: spec.statusLabels?.good ?? "On track", bad: spec.statusLabels?.bad ?? "Action needed" };
4263
+ const ref = spec.compare === void 0 ? void 0 : typeof spec.compare === "number" ? spec.compare : spec.compare.value !== void 0 ? toNumber(spec.compare.value) : toNumber(field(source, spec.compare.path));
4264
+ const delta = n !== void 0 && ref !== void 0 ? n - ref : void 0;
4265
+ const better = delta === void 0 || delta === 0 || spec.goodWhen === "none" ? void 0 : delta > 0 === (spec.goodWhen === "up");
4266
+ const low = spec.band ? num(spec.band.low) : void 0;
4267
+ const high = spec.band ? num(spec.band.high) : void 0;
4268
+ const outside = n !== void 0 && (low !== void 0 && n < low || high !== void 0 && n > high);
4269
+ const pTarget = spec.progress ? num(spec.progress.target) : void 0;
4270
+ const ratio = n !== void 0 && pTarget ? Math.min(spec.progress?.cap ?? Number.POSITIVE_INFINITY, n / pTarget * 100) : void 0;
4271
+ return /* @__PURE__ */ jsxs10("div", { className: "ds-kpi", "data-size": spec.size, children: [
4272
+ /* @__PURE__ */ jsxs10("div", { className: "ds-kpi-label", children: [
4273
+ /* @__PURE__ */ jsx15("span", { children: spec.title }),
4274
+ spec.info && /* @__PURE__ */ jsx15(InfoTip, { text: spec.info })
4275
+ ] }),
4276
+ /* @__PURE__ */ jsx15(
4277
+ "button",
4278
+ {
4279
+ type: "button",
4280
+ className: "ds-kpi-main",
4281
+ "data-clickable": clickable || void 0,
4282
+ onClick: () => emit("click", "value", { datum: source, value }),
4283
+ onMouseEnter: () => emit("hover", "value", { datum: source, value }),
4284
+ "aria-label": `${spec.title ?? "Value"}: ${empty ? spec.emptyText ?? "no value" : fmt(value)}${unit ? ` ${unit}` : ""}`,
4285
+ children: empty ? (
4286
+ // No value is not zero: the author's text, else a dash.
4287
+ /* @__PURE__ */ jsx15("span", { className: "ds-kpi-empty", children: spec.emptyText || "\u2014" })
4288
+ ) : /* @__PURE__ */ jsxs10(Fragment5, { children: [
4289
+ /* @__PURE__ */ jsxs10(
4290
+ "span",
4291
+ {
4292
+ className: "ds-kpi-value",
4293
+ style: { color: spec.tone ? tone(spec.tone).fg : outside ? tone("bad").fg : void 0 },
4294
+ children: [
4295
+ fmt(animated),
4296
+ unit && spec.unitStyle === "value" ? unit : null
4297
+ ]
4298
+ }
4299
+ ),
4300
+ unit && spec.unitStyle !== "value" && /* @__PURE__ */ jsx15("span", { className: "ds-kpi-unit", children: unit })
4301
+ ] })
4593
4302
  }
4594
- });
4595
- }
4596
- };
4303
+ ),
4304
+ delta !== void 0 && /* @__PURE__ */ jsxs10(
4305
+ "span",
4306
+ {
4307
+ className: "ds-kpi-delta",
4308
+ style: { color: tone(better === void 0 ? "neutral" : better ? "good" : "bad").fg },
4309
+ children: [
4310
+ delta > 0 ? "\u2191" : delta < 0 ? "\u2193" : "\u2192",
4311
+ " ",
4312
+ spec.format === "duration" ? helpers.fmt.duration(Math.abs(delta)) : `${helpers.fmt.number(Math.abs(ref ? delta / Math.abs(ref) * 100 : 0), 1)}%`,
4313
+ typeof spec.compare === "object" && spec.compare.label && /* @__PURE__ */ jsxs10("span", { className: "ds-kpi-sub", children: [
4314
+ " ",
4315
+ spec.compare.label
4316
+ ] })
4317
+ ]
4318
+ }
4319
+ ),
4320
+ spec.note && /* @__PURE__ */ jsx15("span", { className: "ds-kpi-sub", children: spec.note }),
4321
+ spec.sublabel && /* @__PURE__ */ jsx15("span", { className: "ds-kpi-sub", children: spec.sublabel }),
4322
+ low !== void 0 && high !== void 0 && /* @__PURE__ */ jsxs10("span", { className: "ds-kpi-sub", children: [
4323
+ "Expected ",
4324
+ fmt(low),
4325
+ "\u2013",
4326
+ fmt(high)
4327
+ ] }),
4328
+ ratio !== void 0 && // biome-ignore lint/a11y/useFocusableInteractive: a progress bar is read-only, not interactive
4329
+ /* @__PURE__ */ jsx15(
4330
+ "span",
4331
+ {
4332
+ className: "ds-progress",
4333
+ role: "progressbar",
4334
+ "aria-valuenow": Math.round(ratio),
4335
+ "aria-valuemin": 0,
4336
+ "aria-valuemax": 100,
4337
+ children: /* @__PURE__ */ jsx15(
4338
+ "span",
4339
+ {
4340
+ style: { width: `${Math.min(100, ratio)}%`, background: tone(ratio >= 100 ? "good" : "info").solid }
4341
+ }
4342
+ )
4343
+ }
4344
+ ),
4345
+ (hasTarget || targetText) && /* @__PURE__ */ jsxs10("div", { className: "ds-kpi-foot", children: [
4346
+ hasTarget && target === void 0 ? /* @__PURE__ */ jsx15("span", { className: "ds-chip", "data-tone": "bad", children: spec.targetMissing }) : /* @__PURE__ */ jsx15("span", { "data-ds-part": "target", children: targetText }),
4347
+ spec.badge !== false && met !== void 0 && !empty && /* @__PURE__ */ jsx15("span", { className: "ds-chip", "data-tone": met ? "good" : "bad", "data-ds-part": "badge", children: met ? labels.good : labels.bad })
4348
+ ] })
4349
+ ] });
4350
+ }
4351
+ });
4352
+
4353
+ // src/widgets/builtins/Sparkline.tsx
4354
+ import "zod";
4355
+ import { jsx as jsx16, jsxs as jsxs11 } from "react/jsx-runtime";
4356
+ function sparkPath(values, w, h, pad = 2) {
4357
+ if (values.length === 0) return { line: "", area: "" };
4358
+ const min = values.reduce((a, b) => Math.min(a, b));
4359
+ const max = values.reduce((a, b) => Math.max(a, b));
4360
+ const span = max - min || 1;
4361
+ const step = values.length > 1 ? (w - pad * 2) / (values.length - 1) : 0;
4362
+ const pts = values.map((v, i) => [pad + i * step, h - pad - (v - min) / span * (h - pad * 2)]);
4363
+ const line = pts.map(([x, y], i) => `${i ? "L" : "M"}${x.toFixed(1)},${y.toFixed(1)}`).join(" ");
4364
+ const last = pts[pts.length - 1];
4365
+ return { line, area: `${line} L${last[0].toFixed(1)},${h} L${pad},${h} Z` };
4597
4366
  }
4598
- function findPanel(doc, id) {
4599
- const top = doc.spec.panels[id];
4600
- if (top) return top;
4601
- for (const m of Object.values(doc.spec.modals ?? {})) if (m.panels[id]) return m.panels[id];
4602
- return void 0;
4367
+ function SparkSvg({
4368
+ values,
4369
+ area = true,
4370
+ height = 32,
4371
+ color: color2 = "var(--ds-series-1)"
4372
+ }) {
4373
+ const w = 120;
4374
+ const { line, area: fill } = sparkPath(values, w, height);
4375
+ return /* @__PURE__ */ jsxs11("svg", { viewBox: `0 0 ${w} ${height}`, preserveAspectRatio: "none", style: { width: "100%", height }, "aria-hidden": "true", children: [
4376
+ area && /* @__PURE__ */ jsx16("path", { d: fill, fill: color2, opacity: 0.15 }),
4377
+ /* @__PURE__ */ jsx16("path", { d: line, fill: "none", stroke: color2, strokeWidth: 1.5, vectorEffect: "non-scaling-stroke" })
4378
+ ] });
4603
4379
  }
4604
- function useHiddenPanels(ids) {
4605
- const { runtime } = useDashboard();
4606
- const key = ids.join(",");
4607
- const list = useTree(
4608
- // biome-ignore lint/correctness/useExhaustiveDependencies: ids are compared by key
4609
- useCallback4(
4610
- (tree) => ids.filter((id) => {
4611
- const def = findPanel(runtime.doc, id);
4612
- if (!def) return false;
4613
- if (tree.panels[id]?.hidden) return true;
4614
- if (typeof def.visibleWhen !== "string") return false;
4615
- try {
4616
- return !evaluate(
4617
- def.visibleWhen,
4618
- rootScope(tree, runtime.helpers, { panel: tree.panels[id] ?? {}, drill: drillValues(tree, id) })
4619
- );
4620
- } catch {
4621
- return false;
4380
+ var Sparkline = defineWidget({
4381
+ ...SparklineContract,
4382
+ implements: "chart",
4383
+ meta: { label: "Sparkline", icon: "sparkline", category: "Charts", size: { w: 3, h: 2, minW: 2, minH: 1 } },
4384
+ events: ["hover"],
4385
+ defaults: { y: "value" },
4386
+ component: function SparklineWidget({ spec, data, size: size2, emit }) {
4387
+ const rows = asRows(data);
4388
+ const values = rows.map((r) => toNumber(field(r, spec.y)) ?? 0);
4389
+ return /* @__PURE__ */ jsx16(
4390
+ "div",
4391
+ {
4392
+ onMouseEnter: () => emit("hover", "line", { value: values[values.length - 1] }),
4393
+ style: { height: "100%" },
4394
+ role: "img",
4395
+ "aria-label": `${spec.title ?? spec.y}: ${values.length} points`,
4396
+ children: /* @__PURE__ */ jsx16(SparkSvg, { values, area: spec.area, height: Math.max(24, size2.height || 32) })
4397
+ }
4398
+ );
4399
+ }
4400
+ });
4401
+
4402
+ // src/widgets/builtins/StageTracker.tsx
4403
+ import "zod";
4404
+ import { jsx as jsx17, jsxs as jsxs12 } from "react/jsx-runtime";
4405
+ var StageTracker = defineWidget({
4406
+ ...StageTrackerContract,
4407
+ implements: "stages",
4408
+ meta: { label: "Stage tracker", icon: "stages", category: "Status", size: { w: 12, h: 3, minW: 4, minH: 2 } },
4409
+ events: ["click"],
4410
+ parts: ["stage"],
4411
+ component: function StageTrackerWidget({ spec, data, emit }) {
4412
+ const raw = typeof data === "string" || typeof data === "number" ? data : field(data, spec.current);
4413
+ const idx = typeof raw === "number" ? raw : spec.stages.findIndex((s) => s.toLowerCase() === String(raw ?? "").toLowerCase());
4414
+ return /* @__PURE__ */ jsx17("ol", { className: "ds-stages", children: spec.stages.map((s, i) => {
4415
+ const state = i < idx ? "done" : i === idx ? "current" : "todo";
4416
+ return /* @__PURE__ */ jsx17("li", { "data-state": state, children: /* @__PURE__ */ jsxs12(
4417
+ "button",
4418
+ {
4419
+ type: "button",
4420
+ onClick: () => emit("click", "stage", { value: s, index: i, datum: data }),
4421
+ "aria-current": state === "current" ? "step" : void 0,
4422
+ children: [
4423
+ /* @__PURE__ */ jsx17("span", { className: "ds-stage-dot", "aria-hidden": "true", children: state === "done" ? "\u2713" : i + 1 }),
4424
+ s
4425
+ ]
4622
4426
  }
4427
+ ) }, s);
4428
+ }) });
4429
+ }
4430
+ });
4431
+
4432
+ // src/widgets/builtins/StateTimeline.tsx
4433
+ import "zod";
4434
+ import { jsx as jsx18, jsxs as jsxs13 } from "react/jsx-runtime";
4435
+ var StateTimeline = defineWidget({
4436
+ ...StateTimelineContract,
4437
+ implements: "timeline",
4438
+ meta: { label: "State timeline", icon: "timeline", category: "Status", size: { w: 12, h: 3, minW: 4, minH: 2 } },
4439
+ events: ["click", "hover"],
4440
+ parts: ["segment"],
4441
+ component: function StateTimelineWidget({ spec, data, emit, helpers }) {
4442
+ const all = asRows(data).map((r) => ({ r, t: Number(field(r, spec.time)), raw: String(field(r, spec.value) ?? "") })).filter((x) => Number.isFinite(x.t)).sort((a, b) => a.t - b.t);
4443
+ const end = helpers.now();
4444
+ const start = spec.window ? end - parseDuration(spec.window) : all[0]?.t ?? end;
4445
+ const lanes = spec.rows ? [...new Set(all.map((x) => String(field(x.r, spec.rows))))] : [""];
4446
+ const span = Math.max(1, end - start);
4447
+ const states = /* @__PURE__ */ new Map();
4448
+ return /* @__PURE__ */ jsxs13("div", { className: "ds-timeline", children: [
4449
+ lanes.map((lane) => {
4450
+ const pts = all.filter((x) => !spec.rows || String(field(x.r, spec.rows)) === lane);
4451
+ const segs = pts.map((p, i) => {
4452
+ const from = Math.max(start, p.t);
4453
+ const to = Math.min(end, pts[i + 1]?.t ?? end);
4454
+ const state = spec.stateMap?.[p.raw] ?? p.raw;
4455
+ states.set(state, (states.get(state) ?? 0) + Math.max(0, to - from));
4456
+ return { p, from, to, state };
4457
+ });
4458
+ return /* @__PURE__ */ jsxs13("div", { className: "ds-timeline-lane", children: [
4459
+ lane && /* @__PURE__ */ jsx18("span", { className: "ds-timeline-name", children: lane }),
4460
+ /* @__PURE__ */ jsx18("div", { className: "ds-timeline-bar", role: "img", "aria-label": `${spec.title ?? "Timeline"} ${lane}`, children: segs.filter((s) => s.to > s.from).map((s) => (
4461
+ // biome-ignore lint/a11y/useKeyWithClickEvents: the per-state totals below summarise the same data for keyboard users
4462
+ /* @__PURE__ */ jsx18(
4463
+ "span",
4464
+ {
4465
+ title: `${s.state} \xB7 ${helpers.fmt.date(s.from, "time")}\u2013${helpers.fmt.date(s.to, "time")} (${helpers.fmt.duration((s.to - s.from) / 1e3)})`,
4466
+ style: {
4467
+ left: `${(s.from - start) / span * 100}%`,
4468
+ width: `${(s.to - s.from) / span * 100}%`,
4469
+ background: tone(spec.tones?.[s.state] ?? "neutral").solid
4470
+ },
4471
+ onClick: () => emit("click", "segment", { datum: s.p.r, value: s.state, x: s.from }),
4472
+ onMouseEnter: () => emit("hover", "segment", { datum: s.p.r, value: s.state, x: s.from })
4473
+ },
4474
+ `${s.from}-${s.state}`
4475
+ )
4476
+ )) })
4477
+ ] }, lane);
4623
4478
  }),
4624
- [key, runtime]
4625
- ),
4626
- (a, b) => a.join(",") === b.join(",")
4627
- );
4628
- return useMemo4(() => new Set(list), [list]);
4629
- }
4630
- function panelUnder(x, y, exclude) {
4631
- if (typeof document === "undefined") return void 0;
4632
- for (const el of document.elementsFromPoint(x, y)) {
4633
- const p = el.closest(".ds-panel[data-panel]");
4634
- if (p && (!exclude || !exclude.contains(p) && !p.contains(exclude))) return p;
4479
+ /* @__PURE__ */ jsxs13("div", { className: "ds-timeline-axis", children: [
4480
+ /* @__PURE__ */ jsx18("span", { children: helpers.fmt.date(start, "time") }),
4481
+ /* @__PURE__ */ jsx18("span", { children: spec.endLabel ?? helpers.fmt.date(end, "time") })
4482
+ ] }),
4483
+ /* @__PURE__ */ jsx18("ul", { className: "ds-legend", children: [...states.entries()].map(([s, ms]) => /* @__PURE__ */ jsxs13("li", { children: [
4484
+ /* @__PURE__ */ jsx18(
4485
+ "span",
4486
+ {
4487
+ className: "ds-dot",
4488
+ style: { background: tone(spec.tones?.[s] ?? "neutral").solid },
4489
+ "aria-hidden": "true"
4490
+ }
4491
+ ),
4492
+ s,
4493
+ " ",
4494
+ /* @__PURE__ */ jsx18("strong", { children: helpers.fmt.duration(ms / 1e3) })
4495
+ ] }, s)) })
4496
+ ] });
4635
4497
  }
4636
- return void 0;
4637
- }
4638
- function indexIn(box, x, y) {
4639
- const row = getComputedStyle(box).flexDirection === "row";
4640
- const kids = [...box.children].filter((c) => c.classList.contains("ds-panel"));
4641
- return kids.filter((k) => {
4642
- const r = k.getBoundingClientRect();
4643
- return row ? r.left + r.width / 2 < x && r.top < y : r.top + r.height / 2 < y;
4644
- }).length;
4645
- }
4646
- function dropIndexAt(panel, x, y) {
4647
- const id = panel.getAttribute("data-panel") ?? "";
4648
- const under = document.elementsFromPoint(x, y).find((el) => el.closest(`[data-slot][data-owner="${CSS.escape(id)}"]`));
4649
- const box = under?.closest(`[data-slot][data-owner="${CSS.escape(id)}"]`) ?? panel.querySelector(`[data-slot][data-owner="${CSS.escape(id)}"]`);
4650
- if (!box) return {};
4651
- return { slot: box.getAttribute("data-slot") ?? void 0, index: indexIn(box, x, y) };
4652
- }
4653
- function PanelFrame({ id, nested = false }) {
4654
- return /* @__PURE__ */ jsx21(Boundary, { resetKeys: [id], fallback: (e) => /* @__PURE__ */ jsx21(PanelCrash, { id, error: e }), children: /* @__PURE__ */ jsx21(PanelFrameInner, { id, nested }) });
4655
- }
4656
- function PanelCrash({ id, error }) {
4657
- const { options } = useDashboard();
4658
- let custom;
4659
- try {
4660
- custom = options.renderError?.({ code: "render", message: error.message }, id);
4661
- } catch {
4662
- custom = void 0;
4498
+ });
4499
+
4500
+ // src/widgets/builtins/Status.tsx
4501
+ import "zod";
4502
+ import { jsx as jsx19, jsxs as jsxs14 } from "react/jsx-runtime";
4503
+ var Status = defineWidget({
4504
+ ...StatusContract,
4505
+ implements: "badge",
4506
+ // A badge, not a card: it can sit anywhere, including in another widget's header.
4507
+ frame: "plain",
4508
+ meta: { label: "Status badge", icon: "status", category: "Numbers", size: { w: 3, h: 2, minW: 1, minH: 1 } },
4509
+ events: ["click"],
4510
+ component: function StatusWidget({ spec, data, emit }) {
4511
+ const row = asRows(data)[0] ?? {};
4512
+ const state = String(field(row, spec.state) ?? "unknown");
4513
+ const t = spec.text ? spec.tone ?? "info" : spec.stateMap?.[state] ?? spec.tone ?? "neutral";
4514
+ const text = spec.text ?? spec.labels?.[state] ?? state.charAt(0).toUpperCase() + state.slice(1);
4515
+ return /* @__PURE__ */ jsxs14("button", { type: "button", className: "ds-status", onClick: () => emit("click", "status", { datum: row, value: state }), children: [
4516
+ /* @__PURE__ */ jsxs14("span", { className: "ds-pill", style: { background: tone(t).bg, color: tone(t).fg, borderColor: tone(t).border }, children: [
4517
+ /* @__PURE__ */ jsx19("span", { className: "ds-dot", style: { background: tone(t).solid }, "aria-hidden": "true" }),
4518
+ text
4519
+ ] }),
4520
+ spec.label && /* @__PURE__ */ jsx19("span", { className: "ds-status-label", children: String(field(row, spec.label) ?? "") })
4521
+ ] });
4663
4522
  }
4664
- return /* @__PURE__ */ jsx21("section", { className: "ds-panel", "data-panel": id, "aria-label": id, children: /* @__PURE__ */ jsx21("div", { className: "ds-panel-body", children: custom ?? /* @__PURE__ */ jsxs16("div", { className: "ds-state ds-state-error", role: "alert", children: [
4665
- "This panel could not be shown: ",
4666
- error.message
4667
- ] }) }) });
4523
+ });
4524
+
4525
+ // src/widgets/builtins/Table.tsx
4526
+ import { useEffect as useEffect5, useMemo as useMemo4, useRef as useRef7, useState as useState6 } from "react";
4527
+ import { jsx as jsx20, jsxs as jsxs15 } from "react/jsx-runtime";
4528
+ var ROW_H = 36;
4529
+ function pageList(current, pages) {
4530
+ if (pages <= 7) return Array.from({ length: pages }, (_, i) => i + 1);
4531
+ const set = new Set([1, pages, current - 1, current, current + 1].filter((n) => n >= 1 && n <= pages));
4532
+ const sorted = [...set].sort((a, b) => a - b);
4533
+ const out = [];
4534
+ sorted.forEach((n, i) => {
4535
+ if (i > 0 && n - sorted[i - 1] > 1) out.push(0);
4536
+ out.push(n);
4537
+ });
4538
+ return out;
4668
4539
  }
4669
- function PanelFrameInner({ id, nested }) {
4670
- const { runtime, registry, options, visibility } = useDashboard();
4671
- const instance = `${id}\0${useId3()}`;
4672
- const inherited = useNodeScope();
4673
- const def = findPanel(runtime.doc, id);
4674
- const widget = registry.byKind.get(def.kind);
4675
- const spec = def.spec ?? {};
4676
- const binding = spec.data;
4677
- const drillLevels = def.drill?.levels ?? [];
4678
- const view = useTree(
4679
- // biome-ignore lint/correctness/useExhaustiveDependencies: the panel definition is fixed for a runtime
4680
- useCallback4(
4681
- (tree) => {
4682
- const ps = tree.panels[id] ?? {};
4683
- const level = drillLevels[(ps.drill ?? []).length];
4684
- const baseSource = level?.source ?? binding?.source;
4685
- const drillId = baseSource && level?.query ? drillSourceId(baseSource, id, level.name) : void 0;
4686
- const source = drillId && runtime.datasourceIds.has(drillId) ? drillId : baseSource;
4687
- const scope2 = rootScope(tree, runtime.helpers, {
4688
- panel: { ...ps, controls: ps.controls ?? {} },
4689
- drill: drillValues(tree, id),
4690
- parent: inherited.parentData,
4691
- ...inherited.hasItem ? { item: inherited.item, index: inherited.index } : {}
4692
- });
4693
- let visible = true;
4694
- if (typeof def.visibleWhen === "string") {
4695
- try {
4696
- visible = Boolean(evaluate(def.visibleWhen, scope2));
4697
- } catch {
4698
- visible = true;
4699
- }
4700
- }
4701
- let data;
4702
- let sourceData;
4703
- let status = "success";
4704
- let error;
4705
- let stale = false;
4706
- let updatedAt;
4707
- if (source) {
4708
- const s = tree.datasources[source];
4709
- status = s?.status ?? "idle";
4710
- error = s?.error;
4711
- stale = Boolean(s?.stale);
4712
- updatedAt = s?.updatedAt;
4713
- sourceData = s?.data;
4714
- data = typeof binding?.path === "string" ? getPath(s?.data, binding.path) : s?.data;
4715
- } else if (binding && typeof binding.panel === "string")
4716
- data = getPath(tree.panels[binding.panel], binding.path ?? "selection");
4717
- else if (binding && typeof binding.state === "string") data = getPath(tree, binding.state);
4718
- else if (binding && "value" in binding) data = binding.value;
4719
- else if (!binding && inherited.parentId) data = inherited.data;
4720
- const { data: _d, ...rest } = spec;
4721
- let props2 = {};
4722
- try {
4723
- props2 = resolvePanel(rest, scope2, Boolean(inherited.hasItem));
4724
- } catch (e) {
4725
- error = { code: "template", message: e.message };
4726
- }
4727
- const msg = def.messages;
4728
- const messages = msg ? resolvePanel(msg, scope2) : void 0;
4729
- const group = props2.highlight ?? void 0;
4730
- return {
4731
- visible,
4732
- hidden: Boolean(ps.hidden),
4733
- panel: ps,
4734
- source,
4735
- data,
4736
- sourceData,
4737
- status,
4738
- error,
4739
- stale,
4740
- updatedAt,
4741
- props: props2,
4742
- messages,
4743
- highlight: group ? tree.highlight[group] : void 0,
4744
- x: level?.x ?? void 0
4745
- };
4746
- },
4747
- [id, runtime, inherited.parentId, inherited.data, inherited.parentData, inherited.item, inherited.index]
4748
- ),
4749
- samePanelView
4750
- );
4751
- const renderNested = useCallback4((child) => /* @__PURE__ */ jsx21(PanelFrame, { id: child, nested: true }, child), []);
4752
- const store = useMemo4(() => widgetStore(runtime), [runtime]);
4753
- const [bodyRef, size2] = useSize();
4754
- const frameRef = useRef7(null);
4755
- useEffect5(() => {
4756
- if (!view.visible || view.hidden) {
4757
- visibility.set(instance, null);
4758
- return;
4759
- }
4760
- const el = frameRef.current;
4761
- if (!el || typeof IntersectionObserver === "undefined") {
4762
- visibility.set(instance, view.source ? [view.source] : []);
4763
- return () => visibility.set(instance, null);
4764
- }
4765
- const io = new IntersectionObserver(
4766
- ([e]) => visibility.set(instance, e?.isIntersecting && view.source ? [view.source] : []),
4767
- { rootMargin: "200px" }
4768
- );
4769
- io.observe(el);
4770
- return () => {
4771
- io.disconnect();
4772
- visibility.set(instance, null);
4540
+ var Table = defineWidget({
4541
+ ...TableContract,
4542
+ implements: "table",
4543
+ exposes: { selection: "the clicked row", page: "current page (ui.page)", search: "search text (ui.search)" },
4544
+ meta: { label: "Table", icon: "table", category: "Lists", size: { w: 12, h: 8, minW: 4, minH: 4 } },
4545
+ events: ["rowClick", "cellClick", "hover"],
4546
+ parts: ["row", "cell"],
4547
+ rows: (data) => asRows(data),
4548
+ component: function TableWidget({ spec, data, source, emit, helpers, size: size2, state, setUi, status }) {
4549
+ const tpl = (t, row, item) => {
4550
+ try {
4551
+ const v = interpolate(t, scope({ row, item, datum: row }, helpers));
4552
+ return v === null || v === void 0 ? "" : String(v);
4553
+ } catch {
4554
+ return "";
4555
+ }
4773
4556
  };
4774
- }, [instance, view.visible, view.hidden, view.source, visibility]);
4775
- const emit = useCallback4(
4776
- (type, part, detail) => {
4777
- const event = { type, panel: id, ...part ? { part } : {}, ...detail };
4778
- options.onEvent?.(event);
4779
- void runtime.emit(event);
4780
- },
4781
- [id, options, runtime]
4782
- );
4783
- const run = useCallback4(
4784
- (action, detail) => void runtime.runAction(action, { type: "click", panel: id, ...detail }),
4785
- [runtime, id]
4786
- );
4787
- const setUi = useCallback4(
4788
- (patch) => runtime.store.dispatch(
4789
- stateActions.patchPanel({ id, patch: { ui: { ...runtime.getTree().panels[id]?.ui, ...patch } } })
4790
- ),
4791
- [runtime, id]
4792
- );
4793
- const dataRef = useRef7(view.data);
4794
- dataRef.current = view.data;
4795
- const props = useMemo4(() => {
4796
- let p = { ...view.props, ...view.panel.props ?? {} };
4797
- if (view.x) p = { ...p, x: view.x };
4798
- p = withFunctions(p, (code) => {
4799
- const f = runtime.scripts.fnProp(code, ["p", "data"]);
4800
- return (arg) => {
4801
- try {
4802
- return f(arg, dataRef.current);
4803
- } catch (e) {
4804
- console.warn(`[dashspec] ${id}: function prop failed: ${e.message}`);
4805
- return "";
4557
+ const base = useMemo4(() => {
4558
+ const rows2 = asRows(data);
4559
+ return spec.pivot ? applyTransform(rows2, [{ pivot: spec.pivot }], scope()) : rows2;
4560
+ }, [data, spec.pivot]);
4561
+ const columns = useMemo4(() => {
4562
+ if (spec.columns?.length) return spec.columns;
4563
+ if (spec.columnsFrom) {
4564
+ const cf = spec.columnsFrom;
4565
+ return asRows(field(source, cf.path)).map((c) => ({
4566
+ key: String(field(c, cf.key)),
4567
+ label: String(field(c, cf.label) ?? field(c, cf.key)),
4568
+ ...cf.type ? { type: cf.type } : {},
4569
+ ...cf.format ? { format: cf.format } : {}
4570
+ }));
4571
+ }
4572
+ return Object.keys(base[0] ?? {}).map((k) => ({ key: k }));
4573
+ }, [spec.columns, spec.columnsFrom, source, base]);
4574
+ const pg = spec.pagination && spec.pagination.enabled !== false ? spec.pagination : void 0;
4575
+ const sr = spec.search === true ? { enabled: true, mode: "client" } : spec.search && spec.search.enabled !== false ? spec.search : void 0;
4576
+ const so = spec.sorting ?? { enabled: true, mode: "client" };
4577
+ const fl = spec.filtering && spec.filtering.enabled !== false ? spec.filtering : void 0;
4578
+ const server = {
4579
+ paging: pg?.mode === "server",
4580
+ search: sr?.mode === "server",
4581
+ sort: so.mode === "server",
4582
+ filter: fl?.mode === "server"
4583
+ };
4584
+ const anyServer = server.paging || server.search || server.sort || server.filter;
4585
+ const ui = state.ui ?? {};
4586
+ const [view, setView] = useState6(() => ({
4587
+ page: Number(ui.page ?? 1),
4588
+ pageSize: Number(ui.pageSize ?? pg?.pageSize ?? 20),
4589
+ search: String(ui.search ?? ""),
4590
+ sortKey: ui.sortKey ?? so.default?.key,
4591
+ sortOrder: ui.sortOrder ?? so.default?.order ?? "asc",
4592
+ filters: ui.filters ?? {}
4593
+ }));
4594
+ const update = (patch) => {
4595
+ const next = { ...view, ...patch };
4596
+ setView(next);
4597
+ if (anyServer)
4598
+ setUi({
4599
+ page: next.page,
4600
+ pageSize: next.pageSize,
4601
+ offset: (next.page - 1) * next.pageSize,
4602
+ search: next.search || void 0,
4603
+ sortKey: next.sortKey,
4604
+ sortOrder: next.sortKey ? next.sortOrder : void 0,
4605
+ ordering: next.sortKey ? `${next.sortOrder === "desc" ? "-" : ""}${next.sortKey}` : void 0,
4606
+ filters: Object.fromEntries(Object.entries(next.filters).filter(([, v]) => v !== ""))
4607
+ });
4608
+ };
4609
+ const [searchText, setSearchText] = useState6(view.search);
4610
+ const searchTimer = useRef7(void 0);
4611
+ useEffect5(() => () => clearTimeout(searchTimer.current), []);
4612
+ const [scrollTop, setScrollTop] = useState6(0);
4613
+ const scroller = useRef7(null);
4614
+ const sort = view.sortKey ? { key: view.sortKey, order: view.sortOrder } : void 0;
4615
+ const rows = useMemo4(() => {
4616
+ let r = base;
4617
+ if (fl && !server.filter)
4618
+ for (const [k, v] of Object.entries(view.filters)) {
4619
+ if (v === "") continue;
4620
+ const c = columns.find((x) => x.key === k);
4621
+ if (c?.filter === "min")
4622
+ r = r.filter((row) => (toNumber(field(row, k)) ?? Number.NEGATIVE_INFINITY) >= Number(v));
4623
+ else if (c?.filter === "select") r = r.filter((row) => String(field(row, k) ?? "") === v);
4624
+ else
4625
+ r = r.filter(
4626
+ (row) => String(field(row, k) ?? "").toLowerCase().includes(v.toLowerCase())
4627
+ );
4806
4628
  }
4807
- };
4808
- });
4809
- return widget ? parseWidgetProps(widget.schema, p).props : p;
4810
- }, [view.props, view.panel.props, view.x, runtime, widget, id]);
4811
- if (!view.visible || view.hidden) return null;
4812
- const ownHeader = widget?.header === "widget";
4813
- const title = ownHeader ? void 0 : props.title;
4814
- const info = ownHeader ? void 0 : props.info;
4815
- const meta2 = props.meta;
4816
- const live2 = Boolean(props.live);
4817
- const drill = view.panel.drill ?? [];
4818
- const controls = def.controls ?? [];
4819
- const tone2 = def.style?.tone ?? (widget?.frame === "plain" ? "plain" : "default");
4820
- const headerKids = slotChildren(def, "header");
4821
- const footerKids = slotChildren(def, "footer");
4822
- const hideHeader = Boolean(def.style?.hideHeader) || !title && !meta2 && !live2 && drill.length === 0 && controls.length === 0 && !view.stale && headerKids.length === 0;
4823
- const dnd = Boolean(options.onDropOnPanel);
4824
- let body;
4825
- if (!widget) body = /* @__PURE__ */ jsxs16("div", { className: "ds-state", children: [
4826
- "Unknown widget \u201C",
4827
- String(def.kind),
4828
- "\u201D"
4829
- ] });
4830
- else if (view.error && view.data === void 0)
4831
- body = options.renderError?.(view.error, id) ?? /* @__PURE__ */ jsx21("div", { className: "ds-state ds-state-error", role: "alert", children: view.messages?.error ?? view.error.message });
4832
- else if (view.source && view.data === void 0 && (view.status === "loading" || view.status === "idle"))
4833
- body = options.renderLoading?.(id, loadingText(view.messages)) ?? /* @__PURE__ */ jsx21(LoadingState, { text: loadingText(view.messages) });
4834
- else if (view.source && isEmpty(view.data) && widget.empty !== "widget")
4835
- body = options.renderEmpty?.(id) ?? /* @__PURE__ */ jsx21("div", { className: "ds-state", children: view.messages?.empty ?? "No data" });
4836
- else {
4837
- const W = widget.component;
4838
- body = /* @__PURE__ */ jsx21(
4839
- Boundary,
4840
- {
4841
- resetKeys: [view.data, props],
4842
- fallback: (e) => /* @__PURE__ */ jsxs16("div", { className: "ds-state ds-state-error", role: "alert", children: [
4843
- "This panel could not be shown: ",
4844
- e.message
4845
- ] }),
4846
- children: /* @__PURE__ */ jsx21(
4847
- W,
4848
- {
4849
- spec: props,
4850
- data: view.data,
4851
- source: view.sourceData,
4852
- run,
4853
- emit,
4854
- state: view.panel,
4855
- setUi,
4856
- status: view.status,
4857
- highlight: view.highlight,
4858
- size: size2,
4859
- mode: options.mode,
4860
- helpers: runtime.helpers,
4861
- panelId: id,
4862
- renderSlot: (name, o) => /* @__PURE__ */ jsx21(Slot, { name, ...o }),
4863
- store
4629
+ if (sr && !server.search && view.search) {
4630
+ const q = view.search.toLowerCase();
4631
+ const fields = sr.mode === "client" && "fields" in sr ? sr.fields : void 0;
4632
+ r = r.filter(
4633
+ (row) => (fields ? fields.map((f) => field(row, f)) : Object.values(row)).some(
4634
+ (v) => v !== null && v !== void 0 && typeof v !== "object" && String(v).toLowerCase().includes(q)
4635
+ )
4636
+ );
4637
+ }
4638
+ if (sort && !server.sort) {
4639
+ const dir = sort.order === "desc" ? -1 : 1;
4640
+ r = [...r].sort((a, b) => {
4641
+ const x = field(a, sort.key);
4642
+ const y = field(b, sort.key);
4643
+ if (x === y) return 0;
4644
+ if (x === null || x === void 0) return 1;
4645
+ if (y === null || y === void 0) return -1;
4646
+ const nx = toNumber(x);
4647
+ const ny = toNumber(y);
4648
+ return (nx !== void 0 && ny !== void 0 ? nx - ny : String(x).localeCompare(String(y), void 0, { numeric: true })) * dir;
4649
+ });
4650
+ }
4651
+ return r;
4652
+ }, [base, view, columns]);
4653
+ const pageSize = pg ? view.pageSize : void 0;
4654
+ const rowTotal = server.paging ? toNumber(field(source, pg?.totalPath ?? "count")) ?? rows.length : rows.length;
4655
+ const pages = pageSize ? Math.max(1, Math.ceil(rowTotal / pageSize)) : 1;
4656
+ const current = Math.min(view.page, pages);
4657
+ const shown = pageSize && !server.paging ? rows.slice((current - 1) * pageSize, current * pageSize) : rows;
4658
+ const hasFilters = Boolean(fl) && columns.some((c) => c.filter);
4659
+ const height = spec.maxHeight ?? Math.max(120, (size2.height || 300) - (sr ? 48 : 0) - (pageSize ? 48 : 0));
4660
+ const windowed = spec.virtual && shown.length > 60;
4661
+ const first = windowed ? Math.max(0, Math.floor(scrollTop / ROW_H) - 10) : 0;
4662
+ const last = windowed ? Math.min(shown.length, first + Math.ceil(height / ROW_H) + 20) : shown.length;
4663
+ const busy = status === "loading" && base.length > 0;
4664
+ const filterChoices = (c) => c.filterOptions ?? [
4665
+ ...new Set(
4666
+ base.map((r) => field(r, c.key)).filter((v) => v !== null && v !== void 0 && v !== "").map(String)
4667
+ )
4668
+ ].sort();
4669
+ const cell = (c, row) => {
4670
+ const v = field(row, c.key);
4671
+ if (c.type === "badge") {
4672
+ const text = c.template ? tpl(c.template, row) : v === null || v === void 0 || v === "" ? "" : String(v);
4673
+ if (!text) return c.empty ? /* @__PURE__ */ jsx20("span", { className: "ds-cell-empty", children: c.empty }) : "";
4674
+ let t = c.map?.[String(v)] ?? "neutral";
4675
+ if (c.tone) {
4676
+ try {
4677
+ t = String(
4678
+ evaluate(c.tone, scope({ row, value: v }, helpers))
4679
+ );
4680
+ } catch {
4864
4681
  }
4865
- )
4682
+ }
4683
+ return /* @__PURE__ */ jsx20("span", { className: "ds-chip", "data-tone": t, children: text });
4866
4684
  }
4867
- );
4868
- }
4869
- const selected = options.selectedPanel === id;
4870
- const defaultSlot = widget?.slots ? Object.keys(widget.slots)[0] ?? "header" : "header";
4871
- const dropTarget = (target, x, y) => {
4872
- const own = `[data-slot][data-owner="${CSS.escape(id)}"]`;
4873
- const el = target?.closest(own) ?? frameRef.current?.querySelector(`${own}:not([data-slot="header"]):not([data-slot="footer"])`) ?? void 0;
4874
- const name = el?.getAttribute("data-slot") ?? defaultSlot;
4875
- return { slot: name, index: el ? indexIn(el, x, y) : void 0 };
4876
- };
4877
- return /* @__PURE__ */ jsx21(SlotOwnerContext.Provider, { value: { id, data: view.data, def }, children: /* @__PURE__ */ jsx21(SlotChildContext.Provider, { value: renderNested, children: /* @__PURE__ */ jsxs16(
4878
- "section",
4879
- {
4880
- ref: frameRef,
4881
- className: "ds-panel",
4882
- style: panelStyle(def.style),
4883
- "data-tone": tone2,
4884
- "data-panel": id,
4885
- "data-selected": selected || void 0,
4886
- "data-nested": nested || void 0,
4887
- "aria-label": title ?? id,
4888
- draggable: dnd && nested ? true : void 0,
4889
- onDragStart: dnd && nested ? (e) => {
4890
- e.stopPropagation();
4891
- e.dataTransfer.setData("text/plain", id);
4892
- e.dataTransfer.effectAllowed = "move";
4893
- options.onDragPanelStart?.(id);
4894
- } : void 0,
4895
- onDragOver: dnd ? (e) => {
4896
- const t = dropTarget(e.target, e.clientX, e.clientY);
4897
- if (!options.canDropOn?.(id, void 0, t.slot)) return;
4898
- e.preventDefault();
4899
- e.stopPropagation();
4900
- frameRef.current?.setAttribute("data-drop-over", t.slot);
4901
- } : void 0,
4902
- onDragLeave: dnd ? (e) => {
4903
- if (!frameRef.current?.contains(e.relatedTarget))
4904
- frameRef.current?.removeAttribute("data-drop-over");
4905
- } : void 0,
4906
- onDrop: dnd ? (e) => {
4907
- frameRef.current?.removeAttribute("data-drop-over");
4908
- const t = dropTarget(e.target, e.clientX, e.clientY);
4909
- if (!options.canDropOn?.(id, void 0, t.slot)) return;
4910
- e.preventDefault();
4911
- e.stopPropagation();
4912
- options.onDropOnPanel?.(id, t.index, void 0, t.slot);
4913
- } : void 0,
4914
- onPointerDownCapture: options.onPanelSelect ? (e) => {
4915
- const el = partAt(e.target, frameRef.current);
4916
- markPart(frameRef.current, el?.node);
4917
- options.onPanelSelect?.(id, el?.part);
4918
- } : void 0,
4919
- onClickCapture: options.onPanelSelect ? (e) => {
4920
- e.preventDefault();
4921
- e.stopPropagation();
4922
- } : void 0,
4923
- children: [
4924
- !hideHeader && /* @__PURE__ */ jsxs16("header", { className: "ds-panel-head", children: [
4925
- /* @__PURE__ */ jsxs16("div", { style: { minWidth: 0 }, children: [
4926
- title && /* @__PURE__ */ jsxs16("h3", { className: "ds-panel-title", children: [
4927
- title,
4928
- info && /* @__PURE__ */ jsx21(InfoTip, { text: info })
4929
- ] }),
4930
- drill.length > 0 && /* @__PURE__ */ jsxs16("nav", { className: "ds-crumbs", "aria-label": "Drill path", children: [
4931
- /* @__PURE__ */ jsx21("button", { type: "button", onClick: () => runtime.runAction({ do: "drillReset", panel: id }), children: "All" }),
4932
- drill.map((d, i) => /* @__PURE__ */ jsxs16("span", { children: [
4933
- "\u203A",
4934
- " ",
4935
- i < drill.length - 1 ? /* @__PURE__ */ jsx21(
4936
- "button",
4685
+ if (c.template) return tpl(c.template, row) || (c.empty ? /* @__PURE__ */ jsx20("span", { className: "ds-cell-empty", children: c.empty }) : "");
4686
+ if (c.list !== void 0) {
4687
+ const items = Array.isArray(v) ? v : [];
4688
+ if (items.length === 0) return c.empty ?? "";
4689
+ return /* @__PURE__ */ jsx20("span", { className: "ds-cell-list", children: items.map((it, i) => (
4690
+ // biome-ignore lint/suspicious/noArrayIndexKey: list items have no id and never reorder within a render
4691
+ /* @__PURE__ */ jsx20("span", { children: tpl(c.list, row, it) }, i)
4692
+ )) });
4693
+ }
4694
+ if (v === null || v === void 0 || v === "")
4695
+ return c.empty ? /* @__PURE__ */ jsx20("span", { className: "ds-cell-empty", children: c.empty }) : "";
4696
+ switch (c.type) {
4697
+ case "link": {
4698
+ const href = safeLink(c.href ? tpl(c.href, row) : String(v));
4699
+ return href ? /* @__PURE__ */ jsx20("a", { className: "ds-link", href, onClick: (e) => e.stopPropagation(), children: String(v) }) : String(v);
4700
+ }
4701
+ case "image":
4702
+ return safeImageSrc(v) ? /* @__PURE__ */ jsx20("img", { src: v, alt: "", style: { height: 28, borderRadius: 4 } }) : null;
4703
+ case "progress": {
4704
+ const n = toNumber(v) ?? 0;
4705
+ const pct = Math.min(100, n / (c.max ?? 100) * 100);
4706
+ return /* @__PURE__ */ jsxs15("span", { className: "ds-inline", children: [
4707
+ /* @__PURE__ */ jsx20("span", { className: "ds-progress", style: { flex: 1, minWidth: 40 }, children: /* @__PURE__ */ jsx20("span", { style: { width: `${pct}%`, background: "var(--ds-series-1)" } }) }),
4708
+ formatValue(n, helpers, c.format, c.decimals),
4709
+ c.suffix
4710
+ ] });
4711
+ }
4712
+ case "sparkline":
4713
+ return /* @__PURE__ */ jsx20(
4714
+ SparkSvg,
4715
+ {
4716
+ values: (Array.isArray(v) ? v : []).map(
4717
+ (x) => toNumber(typeof x === "object" ? field(x, "value") : x) ?? 0
4718
+ ),
4719
+ height: 24,
4720
+ area: false
4721
+ }
4722
+ );
4723
+ default:
4724
+ return `${c.prefix ?? ""}${typeof v === "number" || c.format ? formatValue(v, helpers, c.format, c.decimals) : String(v)}${c.suffix ?? ""}`;
4725
+ }
4726
+ };
4727
+ const total = (c) => {
4728
+ const how = spec.totals?.columns[c.key];
4729
+ if (!how) return null;
4730
+ const nums = rows.map((r) => toNumber(field(r, c.key))).filter((n) => n !== void 0);
4731
+ if (how !== "count" && nums.length === 0) return "";
4732
+ const v = how === "count" ? rows.length : how === "sum" ? nums.reduce((a, b) => a + b, 0) : how === "avg" ? nums.reduce((a, b) => a + b, 0) / (nums.length || 1) : how === "min" ? nums.reduce((a, b) => Math.min(a, b)) : nums.reduce((a, b) => Math.max(a, b));
4733
+ return `${c.prefix ?? ""}${formatValue(v, helpers, c.format === "date" ? "number" : c.format, c.decimals)}${c.suffix ?? ""}`;
4734
+ };
4735
+ const muted = (row) => {
4736
+ if (!spec.rowMutedWhen) return false;
4737
+ try {
4738
+ return Boolean(evaluate(spec.rowMutedWhen, scope({ row }, helpers)));
4739
+ } catch {
4740
+ return false;
4741
+ }
4742
+ };
4743
+ const align = (c) => c.align ?? (c.type === "number" || c.format && c.format !== "date" && c.format !== "text" ? "right" : "left");
4744
+ return /* @__PURE__ */ jsxs15("div", { className: "ds-table-wrap", "data-density": spec.density, children: [
4745
+ sr && /* @__PURE__ */ jsxs15("div", { className: "ds-table-tools", children: [
4746
+ /* @__PURE__ */ jsxs15("label", { className: "ds-search", children: [
4747
+ /* @__PURE__ */ jsxs15("svg", { viewBox: "0 0 16 16", width: "15", height: "15", "aria-hidden": "true", children: [
4748
+ /* @__PURE__ */ jsx20("circle", { cx: "7", cy: "7", r: "4.5", fill: "none", stroke: "currentColor", strokeWidth: "1.5" }),
4749
+ /* @__PURE__ */ jsx20("path", { d: "m10.5 10.5 3 3", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round" })
4750
+ ] }),
4751
+ /* @__PURE__ */ jsx20(
4752
+ "input",
4753
+ {
4754
+ type: "search",
4755
+ "aria-label": "Search table",
4756
+ placeholder: "placeholder" in sr && sr.placeholder || "Search",
4757
+ value: searchText,
4758
+ onChange: (e) => {
4759
+ const v = e.target.value;
4760
+ setSearchText(v);
4761
+ clearTimeout(searchTimer.current);
4762
+ searchTimer.current = setTimeout(() => update({ search: v, page: 1 }), server.search ? 350 : 120);
4763
+ }
4764
+ }
4765
+ )
4766
+ ] }),
4767
+ /* @__PURE__ */ jsxs15("span", { className: "ds-table-count", children: [
4768
+ helpers.fmt.number(rowTotal),
4769
+ " rows"
4770
+ ] })
4771
+ ] }),
4772
+ /* @__PURE__ */ jsxs15(
4773
+ "div",
4774
+ {
4775
+ className: "ds-table-scroll",
4776
+ "data-max": spec.maxHeight !== void 0 || void 0,
4777
+ ref: scroller,
4778
+ style: { maxHeight: height },
4779
+ onScroll: windowed ? (e) => setScrollTop(e.currentTarget.scrollTop) : void 0,
4780
+ children: [
4781
+ busy && /* @__PURE__ */ jsx20("div", { className: "ds-table-busy", "aria-hidden": "true" }),
4782
+ /* @__PURE__ */ jsxs15("table", { className: "ds-table", "aria-busy": busy || void 0, children: [
4783
+ /* @__PURE__ */ jsxs15("thead", { "data-sticky": spec.sticky || void 0, children: [
4784
+ /* @__PURE__ */ jsx20("tr", { children: columns.map((c, i) => {
4785
+ const sorted = sort?.key === c.key ? sort.order : void 0;
4786
+ return /* @__PURE__ */ jsx20(
4787
+ "th",
4788
+ {
4789
+ "data-ds-part": `column:${i}`,
4790
+ style: { textAlign: align(c), width: c.width },
4791
+ "aria-sort": sorted === "asc" ? "ascending" : sorted === "desc" ? "descending" : void 0,
4792
+ children: so.enabled === false || c.sortable === false || c.list !== void 0 ? c.label ?? c.key : /* @__PURE__ */ jsxs15(
4793
+ "button",
4794
+ {
4795
+ type: "button",
4796
+ onClick: () => update(
4797
+ sorted === "asc" ? { sortKey: c.key, sortOrder: "desc", page: 1 } : sorted === "desc" ? { sortKey: void 0, page: 1 } : { sortKey: c.key, sortOrder: "asc", page: 1 }
4798
+ ),
4799
+ children: [
4800
+ c.label ?? c.key,
4801
+ /* @__PURE__ */ jsx20("span", { className: "ds-sort", "data-dir": sorted, "aria-hidden": "true" })
4802
+ ]
4803
+ }
4804
+ )
4805
+ },
4806
+ `${c.key}-${i}`
4807
+ );
4808
+ }) }),
4809
+ hasFilters && /* @__PURE__ */ jsx20("tr", { className: "ds-filter-row", children: columns.map((c, i) => /* @__PURE__ */ jsx20("th", { children: c.filter === "select" ? /* @__PURE__ */ jsx20(
4810
+ SelectControl,
4937
4811
  {
4938
- type: "button",
4939
- onClick: () => runtime.store.dispatch(
4940
- stateActions.patchPanel({ id, patch: { drill: drill.slice(0, i + 1) } })
4941
- ),
4942
- children: String(d.value)
4812
+ size: "sm",
4813
+ block: true,
4814
+ plain: true,
4815
+ ariaLabel: `Filter ${c.label ?? c.key}`,
4816
+ options: [
4817
+ { value: "", label: "All" },
4818
+ ...filterChoices(c).map((o) => ({ value: o, label: o }))
4819
+ ],
4820
+ value: view.filters[c.key] ?? "",
4821
+ onChange: (v) => update({ filters: { ...view.filters, [c.key]: String(v ?? "") }, page: 1 })
4943
4822
  }
4944
- ) : String(d.value)
4945
- ] }, `${d.level}-${i}`))
4823
+ ) : c.filter ? /* @__PURE__ */ jsx20(
4824
+ "input",
4825
+ {
4826
+ className: "ds-cell-filter",
4827
+ type: c.filter === "min" ? "number" : "text",
4828
+ placeholder: c.filter === "min" ? "Min" : "Filter",
4829
+ "aria-label": `Filter ${c.label ?? c.key}`,
4830
+ value: view.filters[c.key] ?? "",
4831
+ onChange: (e) => update({ filters: { ...view.filters, [c.key]: e.target.value }, page: 1 })
4832
+ }
4833
+ ) : null }, `f-${c.key}-${i}`)) })
4834
+ ] }),
4835
+ /* @__PURE__ */ jsxs15("tbody", { children: [
4836
+ windowed && first > 0 && /* @__PURE__ */ jsx20("tr", { className: "ds-spacer", children: /* @__PURE__ */ jsx20("td", { colSpan: columns.length, style: { height: first * ROW_H, padding: 0 } }) }),
4837
+ shown.slice(first, last).map((row, k) => {
4838
+ const i = first + k;
4839
+ const key = spec.rowKey ? String(field(row, spec.rowKey)) : String(i);
4840
+ return /* @__PURE__ */ jsx20(
4841
+ "tr",
4842
+ {
4843
+ "data-muted": muted(row) || void 0,
4844
+ onClick: () => emit("rowClick", "row", { datum: row, index: i }),
4845
+ onMouseEnter: () => emit("hover", "row", { datum: row, index: i }),
4846
+ tabIndex: 0,
4847
+ onKeyDown: (e) => e.key === "Enter" && emit("rowClick", "row", { datum: row, index: i }),
4848
+ children: columns.map((c, j) => (
4849
+ // biome-ignore lint/a11y/useKeyWithClickEvents: rows are focusable and open with Enter; cell clicks add detail for pointer users
4850
+ /* @__PURE__ */ jsx20(
4851
+ "td",
4852
+ {
4853
+ style: { textAlign: align(c) },
4854
+ onClick: () => emit("cellClick", "cell", { datum: row, index: i, value: field(row, c.key), column: c.key }),
4855
+ children: cell(c, row)
4856
+ },
4857
+ `${c.key}-${j}`
4858
+ )
4859
+ ))
4860
+ },
4861
+ key
4862
+ );
4863
+ }),
4864
+ windowed && last < shown.length && /* @__PURE__ */ jsx20("tr", { className: "ds-spacer", children: /* @__PURE__ */ jsx20("td", { colSpan: columns.length, style: { height: (shown.length - last) * ROW_H, padding: 0 } }) })
4865
+ ] }),
4866
+ spec.totals && /* @__PURE__ */ jsx20("tfoot", { children: /* @__PURE__ */ jsx20("tr", { children: columns.map((c, j) => /* @__PURE__ */ jsx20("td", { style: { textAlign: align(c) }, children: j === 0 && !spec.totals?.columns[c.key] ? spec.totals?.label : total(c) }, `${c.key}-${j}`)) }) })
4946
4867
  ] })
4947
- ] }),
4948
- /* @__PURE__ */ jsxs16("div", { className: "ds-panel-tools", children: [
4949
- headerKids.length > 0 && /* @__PURE__ */ jsx21(Slot, { name: "header", className: "ds-panel-addons" }),
4950
- meta2 && /* @__PURE__ */ jsx21("span", { className: "ds-panel-meta", children: meta2 }),
4951
- live2 ? /* @__PURE__ */ jsxs16("span", { className: "ds-live", "data-stale": view.stale || void 0, title: view.error?.message, children: [
4952
- /* @__PURE__ */ jsx21("span", { "aria-hidden": "true" }),
4953
- "Live, updated ",
4954
- view.updatedAt ? runtime.helpers.fmt.ago(view.updatedAt) : "\u2026"
4955
- ] }) : view.stale && /* @__PURE__ */ jsx21("span", { className: "ds-badge ds-badge-stale", title: view.error?.message, children: "Stale" }),
4956
- controls.map((c) => /* @__PURE__ */ jsx21(
4957
- ControlField,
4868
+ ]
4869
+ }
4870
+ ),
4871
+ pageSize && /* @__PURE__ */ jsxs15("div", { className: "ds-pager", children: [
4872
+ /* @__PURE__ */ jsxs15("span", { className: "ds-pager-size", children: [
4873
+ "Rows",
4874
+ /* @__PURE__ */ jsx20(
4875
+ SelectControl,
4876
+ {
4877
+ size: "sm",
4878
+ plain: true,
4879
+ ariaLabel: "Rows per page",
4880
+ options: (pg?.pageSizes ?? [10, 20, 50, 100]).map((n) => ({ value: n, label: String(n) })),
4881
+ value: pageSize,
4882
+ onChange: (v) => update({ pageSize: Number(v), page: 1 })
4883
+ }
4884
+ )
4885
+ ] }),
4886
+ /* @__PURE__ */ jsxs15("span", { children: [
4887
+ rowTotal === 0 ? 0 : (current - 1) * pageSize + 1,
4888
+ "\u2013",
4889
+ Math.min(current * pageSize, rowTotal),
4890
+ " of",
4891
+ " ",
4892
+ helpers.fmt.number(rowTotal)
4893
+ ] }),
4894
+ /* @__PURE__ */ jsxs15("span", { className: "ds-pages", children: [
4895
+ /* @__PURE__ */ jsx20(
4896
+ "button",
4897
+ {
4898
+ type: "button",
4899
+ "aria-label": "Previous page",
4900
+ disabled: current <= 1,
4901
+ onClick: () => update({ page: current - 1 }),
4902
+ children: "\u2039"
4903
+ }
4904
+ ),
4905
+ pageList(current, pages).map(
4906
+ (n, i) => n === 0 ? /* @__PURE__ */ jsx20("span", { className: "ds-page-gap", children: "\u2026" }, `gap-${i < 3 ? "a" : "b"}`) : /* @__PURE__ */ jsx20(
4907
+ "button",
4958
4908
  {
4959
- def: c,
4960
- compact: true,
4961
- value: view.panel.controls?.[c.name],
4962
- onChange: (v) => runtime.store.dispatch(
4963
- stateActions.patchPanel({
4964
- id,
4965
- patch: { controls: { ...view.panel.controls, [c.name]: v } }
4966
- })
4967
- )
4909
+ type: "button",
4910
+ "aria-current": n === current ? "page" : void 0,
4911
+ onClick: () => update({ page: n }),
4912
+ children: n
4968
4913
  },
4969
- c.name
4970
- ))
4971
- ] })
4972
- ] }),
4973
- /* @__PURE__ */ jsx21("div", { className: "ds-panel-body", ref: bodyRef, children: body }),
4974
- footerKids.length > 0 && /* @__PURE__ */ jsx21(Slot, { name: "footer", className: "ds-panel-foot" })
4975
- ]
4976
- }
4977
- ) }) });
4978
- }
4979
- function loadingText(messages) {
4980
- const v = messages?.loading;
4981
- return v === void 0 || v === null || v === "" ? void 0 : String(v);
4982
- }
4983
- function LoadingState({ text }) {
4984
- if (!text) return /* @__PURE__ */ jsx21("div", { className: "ds-skeleton", "aria-busy": "true", "aria-label": "Loading" });
4985
- return /* @__PURE__ */ jsxs16("output", { className: "ds-loading", "aria-busy": "true", children: [
4986
- /* @__PURE__ */ jsx21("div", { className: "ds-skeleton", "aria-hidden": "true" }),
4987
- /* @__PURE__ */ jsx21("span", { className: "ds-loading-text", children: text })
4988
- ] });
4989
- }
4914
+ n
4915
+ )
4916
+ ),
4917
+ /* @__PURE__ */ jsx20(
4918
+ "button",
4919
+ {
4920
+ type: "button",
4921
+ "aria-label": "Next page",
4922
+ disabled: current >= pages,
4923
+ onClick: () => update({ page: current + 1 }),
4924
+ children: "\u203A"
4925
+ }
4926
+ )
4927
+ ] })
4928
+ ] })
4929
+ ] });
4930
+ }
4931
+ });
4990
4932
 
4991
- // src/widgets/shared/clickable.ts
4992
- function useClickable(panelId, activate) {
4993
- const ctx = useContext4(DashboardContext);
4994
- const def = ctx && panelId ? findPanel(ctx.runtime.doc, panelId) : void 0;
4995
- const on = def?.on;
4996
- if (on?.click === void 0) return { onClick: activate };
4997
- return {
4998
- onClick: activate,
4999
- role: "button",
5000
- tabIndex: 0,
5001
- onKeyDown: (e) => {
5002
- if (e.key !== "Enter" && e.key !== " ") return;
5003
- e.preventDefault();
5004
- activate();
5005
- }
5006
- };
4933
+ // src/widgets/builtins/Tiles.tsx
4934
+ import "zod";
4935
+ import { Fragment as Fragment6, jsx as jsx21, jsxs as jsxs16 } from "react/jsx-runtime";
4936
+ var Tiles = defineWidget({
4937
+ ...TilesContract,
4938
+ implements: "tiles",
4939
+ exposes: { selection: "the clicked tile's row" },
4940
+ meta: { label: "Tiles", icon: "tiles", category: "Numbers", size: { w: 12, h: 4, minW: 3, minH: 3 } },
4941
+ events: ["click", "hover", "select"],
4942
+ parts: ["tile"],
4943
+ defaults: { label: "name", value: "value" },
4944
+ component: function TilesWidget({ spec, data, emit, helpers }) {
4945
+ const rows = asRows(data);
4946
+ const caption = (row) => {
4947
+ if (!spec.caption) return void 0;
4948
+ try {
4949
+ return String(interpolate(spec.caption, scope({ row }, helpers)) ?? "");
4950
+ } catch {
4951
+ return spec.caption;
4952
+ }
4953
+ };
4954
+ return /* @__PURE__ */ jsx21(
4955
+ "div",
4956
+ {
4957
+ className: "ds-tiles",
4958
+ role: spec.selectable ? "radiogroup" : "list",
4959
+ "aria-label": spec.title,
4960
+ "data-wrap": spec.wrap === false ? "off" : void 0,
4961
+ style: {
4962
+ "--ds-tile-min": `${spec.minTileWidth ?? 128}px`,
4963
+ ...spec.columns ? { "--ds-tile-cols": spec.columns } : {}
4964
+ },
4965
+ children: rows.map((r, i) => {
4966
+ const label = field(r, spec.label);
4967
+ const v = field(r, spec.value);
4968
+ const n = toNumber(v);
4969
+ const status = spec.status ? String(field(r, spec.status)) : void 0;
4970
+ const st = status ? spec.statusMap?.[status] ?? status : void 0;
4971
+ const vt = n === void 0 || !spec.valueTone ? void 0 : n > 0 ? spec.valueTone.positive : n < 0 ? spec.valueTone.negative : spec.valueTone.zero;
4972
+ const active = spec.selectable && spec.selected !== void 0 && spec.selected === label;
4973
+ return /* @__PURE__ */ jsxs16(
4974
+ "button",
4975
+ {
4976
+ type: "button",
4977
+ className: "ds-tile",
4978
+ role: spec.selectable ? "radio" : "listitem",
4979
+ "aria-checked": spec.selectable ? active : void 0,
4980
+ "data-active": active || void 0,
4981
+ onClick: () => {
4982
+ emit("click", "tile", { datum: r, value: label, index: i });
4983
+ if (spec.selectable) emit("select", "tile", { datum: r, value: label, index: i });
4984
+ },
4985
+ onMouseEnter: () => emit("hover", "tile", { datum: r, value: label, index: i }),
4986
+ children: [
4987
+ /* @__PURE__ */ jsxs16("span", { className: "ds-tile-label", children: [
4988
+ st && /* @__PURE__ */ jsx21("span", { className: "ds-dot", style: { background: tone(st).solid }, "aria-hidden": "true" }),
4989
+ String(label ?? ""),
4990
+ spec.count && /* @__PURE__ */ jsx21("span", { className: "ds-chip-count", children: String(field(r, spec.count) ?? "") })
4991
+ ] }),
4992
+ /* @__PURE__ */ jsxs16(
4993
+ "span",
4994
+ {
4995
+ className: "ds-tile-value",
4996
+ style: vt ? { color: vt === "muted" ? "var(--ds-color-text-disabled)" : tone(vt).fg } : void 0,
4997
+ children: [
4998
+ /* @__PURE__ */ jsx21(CountUp, { value: v, render: (x) => formatValue(x, helpers, spec.format, spec.decimals) }),
4999
+ spec.unit && /* @__PURE__ */ jsx21("span", { className: "ds-kpi-unit", children: spec.unit })
5000
+ ]
5001
+ }
5002
+ ),
5003
+ spec.caption && /* @__PURE__ */ jsx21("span", { className: "ds-tile-caption", children: caption(r) })
5004
+ ]
5005
+ },
5006
+ `${String(label)}-${i}`
5007
+ );
5008
+ })
5009
+ }
5010
+ );
5011
+ }
5012
+ });
5013
+ function CountUp({ value, render }) {
5014
+ const n = toNumber(value);
5015
+ const shown = useCountUp(n ?? value);
5016
+ return /* @__PURE__ */ jsx21(Fragment6, { children: render(n === void 0 ? value : shown) });
5007
5017
  }
5008
5018
 
5009
5019
  // src/widgets/builtins/atoms.tsx
5020
+ import "zod";
5010
5021
  import { jsx as jsx22, jsxs as jsxs17 } from "react/jsx-runtime";
5011
5022
  var color = (t) => t === "subtle" ? "var(--ds-color-text-subtle)" : t === "primary" ? "var(--ds-color-action-primary)" : t && t !== "default" ? tone(t).fg : void 0;
5012
5023
  var boundValue = (data, path) => {
@@ -5993,10 +6004,17 @@ function Grid({
5993
6004
  return Object.fromEntries(
5994
6005
  Object.entries(rgl).map(([bp, l]) => [
5995
6006
  bp,
5996
- (l ?? []).map((i) => {
5997
- const want = base.fit.has(i.i) ? fitRows[i.i] : void 0;
5998
- return want && want > i.h ? { ...i, h: want } : i;
5999
- })
6007
+ (() => {
6008
+ const rowWant = /* @__PURE__ */ new Map();
6009
+ for (const i of l ?? []) {
6010
+ const want = base.fit.has(i.i) ? fitRows[i.i] : void 0;
6011
+ if (want) rowWant.set(i.y, Math.max(rowWant.get(i.y) ?? 0, want));
6012
+ }
6013
+ return (l ?? []).map((i) => {
6014
+ const want = base.fit.has(i.i) ? rowWant.get(i.y) : void 0;
6015
+ return want && want > i.h ? { ...i, h: want } : i;
6016
+ });
6017
+ })()
6000
6018
  ])
6001
6019
  );
6002
6020
  }, [rgl, base.fit, fitRows, editable]);
@@ -6641,7 +6659,7 @@ var RENDERER_CSS = `
6641
6659
  .ds-tip::after { content: ""; position: absolute; left: var(--ds-tip-arrow); top: 100%; transform: translateX(-50%); border: 6px solid transparent; border-top-color: var(--ds-color-chart-tooltip-bg); }
6642
6660
  .ds-tip[data-below]::after { top: auto; bottom: 100%; border-top-color: transparent; border-bottom-color: var(--ds-color-chart-tooltip-bg); }
6643
6661
 
6644
- .ds-chip { display: inline-flex; align-items: center; height: 22px; padding: 0 8px; border-radius: 6px; font: 600 11px/1 var(--ds-font-body); white-space: nowrap; background: var(--ds-color-status-neutral-bg); color: var(--ds-color-status-neutral-fg); }
6662
+ .ds-chip { display: inline-flex; align-items: center; height: var(--ds-chip-height, 22px); padding: 0 var(--ds-chip-padding-x, 8px); border-radius: var(--ds-chip-radius, 6px); border-width: var(--ds-chip-border, 1px); font: var(--ds-chip-weight, 600) var(--ds-chip-font-size, 11px)/1 var(--ds-font-body); white-space: nowrap; background: var(--ds-color-status-neutral-bg); color: var(--ds-color-status-neutral-fg); }
6645
6663
  .ds-chip[data-tone="good"] { background: var(--ds-color-status-good-bg); color: var(--ds-color-status-good-fg); }
6646
6664
  .ds-chip[data-tone="bad"] { background: var(--ds-color-status-bad-bg); color: var(--ds-color-status-bad-fg); }
6647
6665
  .ds-chip[data-tone="warn"] { background: var(--ds-color-status-warn-bg); color: var(--ds-color-status-warn-fg); }
@@ -6664,9 +6682,13 @@ var RENDERER_CSS = `
6664
6682
  /* Grid items with fit: the panel takes its natural height (at least the cell's), so the grid can measure it. */
6665
6683
  [data-fit] > .ds-fit { height: 100%; }
6666
6684
  .ds-fit > .ds-panel { height: auto !important; min-height: 100%; }
6667
- [data-fit] .ds-panel-body { flex: none; }
6685
+ /* The body still fills a taller card, so footers (a KPI's target chip) stay at the bottom. */
6686
+ [data-fit] .ds-panel-body { flex: 1 0 auto; display: flex; flex-direction: column; }
6687
+ [data-fit] .ds-panel-body > * { flex: 1 0 auto; }
6668
6688
  [data-fit] .ds-tiles, [data-fit] .ds-table-wrap { height: auto; max-height: none; overflow-y: visible; }
6689
+ /* In a fit card the rows set the height, unless the table has its own maxHeight. */
6669
6690
  [data-fit] .ds-table-scroll { flex: none; }
6691
+ [data-fit] .ds-table-scroll:not([data-max]) { max-height: none !important; overflow-y: visible; }
6670
6692
  .ds-tiles[data-wrap="off"] { grid-template-columns: none; grid-auto-flow: column; grid-auto-columns: minmax(var(--ds-tile-min, 128px), 1fr); overflow-x: auto; scroll-snap-type: x proximity; padding-bottom: 4px; }
6671
6693
  .ds-tiles[data-wrap="off"] > * { scroll-snap-align: start; }
6672
6694
  .ds-tile { min-width: 0; overflow-wrap: anywhere; }
@@ -6718,7 +6740,7 @@ var RENDERER_CSS = `
6718
6740
  .ds-tile:hover { transform: translateY(-2px); box-shadow: 0 6px 16px rgba(21, 121, 190, .10); }
6719
6741
  .ds-tile:active { transform: translateY(0); }
6720
6742
  .ds-kpi-main { transition: opacity 160ms ease; }
6721
- .ds-kpi-main:hover .ds-kpi-value { color: var(--ds-color-action-primary); transition: color 160ms ease; }
6743
+ .ds-kpi-main[data-clickable]:hover .ds-kpi-value { color: var(--ds-color-action-primary); transition: color 160ms ease; }
6722
6744
  .ds-chip { animation: ds-fade 300ms ease both; transition: background 200ms ease, color 200ms ease; }
6723
6745
  .ds-progress > span { transform-origin: left; animation: ds-grow-x 800ms cubic-bezier(.2,.7,.2,1) both; transition: width 500ms cubic-bezier(.2,.7,.2,1); }
6724
6746
  .ds-segbar button { transform-origin: left; animation: ds-grow-x 700ms cubic-bezier(.2,.7,.2,1) both; }