{"spec_id":"dashboard-metrics-tiles","library":"muix","language":"javascript","code":"// anyplot.ai\n// dashboard-metrics-tiles: Real-Time Dashboard Tiles\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 91/100 | Updated: 2026-11-08\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\nimport { SparkLineChart } from \"@mui/x-charts/SparkLineChart\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\n// Status colours as the Notes ask: green for good, amber for warning, red for critical\nconst STATUS_COLOR = { good: t.palette[0], warning: t.amber, critical: t.palette[4] };\n// The most urgent status comes first in the dashboard's reading order\nconst SEVERITY_RANK = { critical: 0, warning: 1, good: 2 };\nconst FAVORABLE = t.palette[0];\nconst UNFAVORABLE = t.palette[4];\n// One neutral colour for every sparkline: the status reads from the tile's stripe alone, and the\n// amber warning hue is never needed as a thin line on the light page\nconst SPARK_COLOR = t.inkSoft;\nconst SPARK_PAD = 0.25; // share of a history's range left free above and below its sparkline\nconst SPARK_MIN_H = 130;\nconst TITLE = \"dashboard-metrics-tiles · javascript · muix · anyplot.ai\";\n\n// Columns: set these to your data's column names\nconst METRIC = \"Metric\"; // role: metric_name\nconst TIME = \"Sample time\"; // role: extra\nconst VALUE = \"Value\"; // role: history\nconst CHANGE = \"Change vs previous period (%)\"; // role: change_percent\nconst STATUS = \"Status\"; // role: status\nconst UNIT = \"Unit\"; // role: extra\nconst HIGHER_IS_BETTER = \"Higher is better\"; // role: extra\n\n// Data: replace this block with your own records, one object per row (one row per metric and sample;\n// the latest sample of each metric is its current value)\nconst data = (() => {\n  const samples = 16;\n  const snapshot = new Date(2026, 9, 14, 14, 30);\n  const metrics = [\n    { name: \"CPU Usage\", unit: \"%\", end: 63, trend: -0.16, noise: 1.0, seed: 11, change: -3.7, status: \"good\", higherIsBetter: false },\n    { name: \"Memory\", unit: \"%\", end: 58, trend: 0.17, noise: 1.0, seed: 22, change: 4.6, status: \"warning\", higherIsBetter: false },\n    { name: \"Response Time\", unit: \"ms\", end: 187, trend: -1.28, noise: 4.0, seed: 33, change: -9.3, status: \"good\", higherIsBetter: false },\n    { name: \"Error Rate\", unit: \"%\", end: 2.4, trend: 0.045, noise: 0.08, seed: 44, change: 12.3, status: \"critical\", higherIsBetter: false },\n    { name: \"Request Rate\", unit: \"req/s\", end: 1834, trend: 11, noise: 35, seed: 55, change: 6.4, status: \"good\", higherIsBetter: true },\n    { name: \"Uptime\", unit: \"%\", end: 99.95, trend: -0.001, noise: 0.015, seed: 66, change: -0.02, status: \"warning\", higherIsBetter: true },\n  ];\n  // History built backward from the current value with a fixed-seed LCG, so each sparkline ends on its headline number\n  return metrics.flatMap((m) => {\n    let state = m.seed;\n    let value = m.end;\n    const values = [m.end];\n    for (let i = 1; i < samples; i += 1) {\n      state = (state * 1664525 + 1013904223) % 4294967296;\n      value -= m.trend + (state / 4294967296 - 0.5) * m.noise;\n      values.unshift(Math.max(0, value));\n    }\n    return values.map((v, i) => ({\n      [METRIC]: m.name,\n      [TIME]: new Date(snapshot.getTime() - (samples - 1 - i) * 60000),\n      [VALUE]: v,\n      [CHANGE]: m.change,\n      [STATUS]: m.status,\n      [UNIT]: m.unit,\n      [HIGHER_IS_BETTER]: m.higherIsBetter,\n    }));\n  });\n})();\n\n// Plot: reads only data and the constants above\nconst tiles = [...new Set(data.map((d) => d[METRIC]))]\n  .map((name) => {\n    const rows = data.filter((d) => d[METRIC] === name).sort((a, b) => a[TIME] - b[TIME]);\n    const latest = rows[rows.length - 1];\n    const values = rows.map((d) => d[VALUE]);\n    const lo = Math.min(...values);\n    const hi = Math.max(...values);\n    const change = latest[CHANGE];\n    const changeAbs = Math.abs(change);\n    return {\n      name,\n      values,\n      times: rows.map((d) => d[TIME]),\n      yMin: lo - (hi - lo) * SPARK_PAD,\n      yMax: hi + (hi - lo) * SPARK_PAD,\n      status: latest[STATUS],\n      accent: STATUS_COLOR[latest[STATUS]],\n      current: latest[VALUE].toLocaleString(\"en-US\", { maximumFractionDigits: 2 }),\n      unit: latest[UNIT],\n      up: change > 0,\n      changeColor: change > 0 === latest[HIGHER_IS_BETTER] ? FAVORABLE : UNFAVORABLE,\n      // Changes under one percent keep two decimals, so the arrow never sits beside a \"0.0%\"\n      changeText: `${changeAbs.toFixed(changeAbs < 1 ? 2 : 1)}%`,\n    };\n  })\n  .sort((a, b) => SEVERITY_RANK[a.status] - SEVERITY_RANK[b.status]);\n\n// Grid as the Notes ask: 2x2 for 4 tiles, 3x2 for 6, 3x3 or 4x3 for more\nconst cols = Math.ceil(Math.sqrt(tiles.length));\nconst gridRows = Math.ceil(tiles.length / cols);\n\nconst allTimes = data.map((d) => d[TIME].getTime());\nconst spanMinutes = Math.round((Math.max(...allTimes) - Math.min(...allTimes)) / 60000);\nconst snapshotLabel = new Date(Math.max(...allTimes)).toLocaleTimeString(\"en-US\", { hour: \"2-digit\", minute: \"2-digit\", hour12: false });\nconst subtitle = `Snapshot at ${snapshotLabel} · ${tiles.length} metrics · sparklines cover the last ${spanMinutes} minutes`;\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  return (\n    <Box\n      sx={{\n        width,\n        height,\n        boxSizing: \"border-box\",\n        backgroundColor: t.pageBg,\n        padding: \"26px 36px 28px\",\n        display: \"flex\",\n        flexDirection: \"column\",\n        gap: \"16px\",\n      }}\n    >\n      <Box>\n        <Typography sx={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.3 }}>{TITLE}</Typography>\n        <Typography sx={{ fontSize: 15, color: t.inkSoft, marginTop: \"4px\" }}>{subtitle}</Typography>\n      </Box>\n\n      <Box\n        sx={{\n          flex: 1,\n          minHeight: 0,\n          display: \"grid\",\n          gridTemplateColumns: `repeat(${cols}, 1fr)`,\n          gridTemplateRows: `repeat(${gridRows}, 1fr)`,\n          gap: \"18px\",\n        }}\n      >\n        {tiles.map((tile, i) => {\n          const isCritical = tile.status === \"critical\";\n          return (\n            <Box\n              key={tile.name}\n              sx={{\n                display: \"flex\",\n                flexDirection: \"column\",\n                minWidth: 0,\n                minHeight: 0,\n                boxSizing: \"border-box\",\n                borderRadius: \"10px\",\n                border: `1px solid ${t.grid}`,\n                borderLeft: `${isCritical ? 8 : 6}px solid ${tile.accent}`,\n                background: t.elevatedBg,\n                padding: \"18px 24px\",\n              }}\n            >\n              <Typography sx={{ fontSize: 15, fontWeight: 500, color: t.inkSoft, letterSpacing: \"0.4px\" }}>\n                {tile.name.toUpperCase()}\n              </Typography>\n\n              <Box sx={{ display: \"flex\", alignItems: \"baseline\", gap: \"14px\", marginTop: \"12px\" }}>\n                <Typography sx={{ fontSize: 54, fontWeight: 700, color: t.ink, lineHeight: 1 }}>\n                  {tile.current}\n                  <Box component=\"span\" sx={{ fontSize: 24, fontWeight: 500, color: t.inkSoft, marginLeft: \"6px\" }}>\n                    {tile.unit}\n                  </Box>\n                </Typography>\n                <Box sx={{ display: \"flex\", alignItems: \"center\", gap: \"4px\" }}>\n                  <svg width=\"16\" height=\"16\" viewBox=\"0 0 10 10\" style={{ display: \"block\", flexShrink: 0 }} aria-hidden=\"true\">\n                    <path d={tile.up ? \"M5 1 L9 8 L1 8 Z\" : \"M5 9 L9 2 L1 2 Z\"} fill={tile.changeColor} />\n                  </svg>\n                  <Typography sx={{ fontSize: 20, fontWeight: 600, color: tile.changeColor }}>{tile.changeText}</Typography>\n                </Box>\n              </Box>\n\n              {/* The sparkline takes all the height the label and value leave free, so no dead band opens up */}\n              <Box sx={{ flex: 1, minHeight: SPARK_MIN_H, marginTop: \"16px\" }}>\n                <SparkLineChart\n                  data={tile.values}\n                  xAxis={{ data: tile.times, scaleType: \"time\" }}\n                  yAxis={{ min: tile.yMin, max: tile.yMax }}\n                  color={SPARK_COLOR}\n                  area\n                  baseline=\"min\"\n                  curve=\"monotoneX\"\n                  skipAnimation\n                  margin={{ top: 8, bottom: 4, left: 4, right: 4 }}\n                  sx={{\n                    \"& .MuiLineChart-area\": { fill: `url(#spark-fill-${i})` },\n                    \"& .MuiLineChart-line\": { strokeWidth: 2.5 },\n                  }}\n                >\n                  <defs>\n                    <linearGradient id={`spark-fill-${i}`} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n                      <stop offset=\"0%\" stopColor={SPARK_COLOR} stopOpacity={0.3} />\n                      <stop offset=\"100%\" stopColor={SPARK_COLOR} stopOpacity={0.03} />\n                    </linearGradient>\n                  </defs>\n                </SparkLineChart>\n              </Box>\n            </Box>\n          );\n        })}\n      </Box>\n    </Box>\n  );\n}\n"}