{"spec_id":"area-stacked","library":"muix","language":"javascript","code":"// anyplot.ai\n// area-stacked: Stacked Area Chart\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 86/100 | Updated: 2026-10-23\nimport { LineChart } from \"@mui/x-charts/LineChart\";\nimport { ChartsReferenceLine } from \"@mui/x-charts/ChartsReferenceLine\";\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Columns: set these to your data's column names\nconst MONTH = \"Month\"; // role: x (Date)\nconst SOURCE = \"Source\"; // role: group\nconst VISITS = \"Monthly Visits\"; // role: value\n\n// Data: replace this block with your own records, one object per row\n// Monthly website traffic by source, Jan 2024 – Dec 2025 (24 months), generated\n// with a tiny fixed-seed LCG — the browser has no seeded RNG\nfunction lcg(seed: number) {\n  let s = seed >>> 0;\n  return () => {\n    s = (Math.imul(1664525, s) + 1013904223) >>> 0;\n    return s / 4294967295;\n  };\n}\nconst rand = lcg(42);\nconst SOURCE_SHAPES: [string, (i: number) => number, number][] = [\n  [\n    \"Organic Search\",\n    (i) => 4200 + i * 55 + 300 * Math.sin(((i - 6) * Math.PI) / 6),\n    200,\n  ],\n  [\n    \"Direct\",\n    (i) => 2100 + i * 22 + 120 * Math.sin(((i - 3) * Math.PI) / 6),\n    140,\n  ],\n  [\n    \"Referral\",\n    (i) => 1150 + i * 9 + 80 * Math.sin(((i - 9) * Math.PI) / 6),\n    90,\n  ],\n  [\"Social\", (i) => 650 + i * 30 + 150 * Math.sin((i * Math.PI) / 6), 110],\n];\nconst data = SOURCE_SHAPES.flatMap(([source, trend, noise]) =>\n  Array.from({ length: 24 }, (_, i) => ({\n    [MONTH]: new Date(2024, i, 1),\n    [SOURCE]: source,\n    [VISITS]: Math.round(trend(i) + (rand() - 0.5) * noise),\n  })),\n);\n\n// Plot: reads only data and the constants above\nconst fmtMonth = (v: Date) =>\n  v.toLocaleString(\"en-US\", { month: \"short\", year: \"numeric\" });\n\nconst months = [\n  ...new Map(data.map((d) => [d[MONTH].getTime(), d[MONTH]])).values(),\n].sort((a, b) => a.getTime() - b.getTime());\nconst valueAt = (source: string, m: Date) =>\n  data.find(\n    (d) => d[SOURCE] === source && d[MONTH].getTime() === m.getTime(),\n  )?.[VISITS] ?? null;\nconst seriesValues = (source: string) => months.map((m) => valueAt(source, m));\nconst sum = (vs: (number | null)[]) => vs.reduce((a, v) => a + (v ?? 0), 0);\n\n// Largest source at the bottom of the stack (the first series stacks first)\nconst sources = [...new Set(data.map((d) => d[SOURCE]))].sort(\n  (a, b) => sum(seriesValues(b)) - sum(seriesValues(a)),\n);\n\n// Storytelling aids: the average stack total (reference line) and the\n// fastest-growing source's overall lift (callout), both derived from the data.\nconst totals = months.map((m) => sum(sources.map((s) => valueAt(s, m))));\nconst avgTotal = sum(totals) / totals.length;\nconst growth = sources.map((s) => {\n  const vs = seriesValues(s).filter((v): v is number => v != null);\n  return vs.length > 1 && vs[0] ? (vs[vs.length - 1] - vs[0]) / vs[0] : -Infinity;\n});\nconst focalIdx = growth.indexOf(Math.max(...growth));\nconst focalGrowthPct = Math.round(growth[focalIdx] * 100);\n\nconst TITLE =\n  \"Website Traffic Sources · area-stacked · javascript · muix · anyplot.ai\";\nconst TITLE_H = 58;\nconst LEGEND_H = 44;\n\n// --- Chart (default-exported component — the harness mounts it) ------------\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n\n  return (\n    <Box\n      sx={{\n        width,\n        height,\n        bgcolor: t.pageBg,\n        display: \"flex\",\n        flexDirection: \"column\",\n      }}\n    >\n      <Box\n        sx={{\n          height: TITLE_H,\n          display: \"flex\",\n          alignItems: \"center\",\n          justifyContent: \"space-between\",\n          px: \"40px\",\n          pt: \"10px\",\n        }}\n      >\n        <Typography\n          sx={{\n            color: t.ink,\n            fontSize: \"22px\",\n            fontWeight: 600,\n            lineHeight: 1,\n          }}\n        >\n          {TITLE}\n        </Typography>\n        <Box\n          sx={{\n            display: \"flex\",\n            alignItems: \"center\",\n            gap: \"8px\",\n            bgcolor: t.elevatedBg,\n            borderRadius: \"6px\",\n            px: \"12px\",\n            py: \"6px\",\n          }}\n        >\n          <Box\n            sx={{\n              width: \"10px\",\n              height: \"10px\",\n              borderRadius: \"50%\",\n              bgcolor: t.palette[focalIdx % t.palette.length],\n            }}\n          />\n          <Typography\n            sx={{\n              color: t.inkSoft,\n              fontSize: \"13px\",\n              fontWeight: 500,\n              lineHeight: 1,\n            }}\n          >\n            {`${sources[focalIdx]}: fastest-growing channel, ${focalGrowthPct >= 0 ? \"+\" : \"\"}${focalGrowthPct}% since ${fmtMonth(months[0])}`}\n          </Typography>\n        </Box>\n      </Box>\n\n      <LineChart\n        width={width}\n        height={height - TITLE_H - LEGEND_H}\n        skipAnimation\n        colors={t.palette}\n        grid={{ horizontal: true }}\n        xAxis={[\n          {\n            data: months,\n            scaleType: \"time\",\n            valueFormatter: fmtMonth,\n            tickNumber: 8,\n            label: MONTH,\n            height: 72,\n            tickLabelStyle: { fontSize: 14 },\n            labelStyle: { fontSize: 16 },\n          },\n        ]}\n        yAxis={[\n          {\n            min: 0,\n            label: VISITS,\n            valueFormatter: (v: number) => `${Math.round(v / 1000)}k`,\n            width: 84,\n            tickLabelStyle: { fontSize: 14 },\n            labelStyle: { fontSize: 16 },\n          },\n        ]}\n        series={sources.map((source, i) => ({\n          id: `s${i}`,\n          data: seriesValues(source),\n          label: source,\n          stack: \"traffic\",\n          area: true,\n          showMark: false,\n          curve: \"monotoneX\",\n        }))}\n        margin={{ top: 20, bottom: 10, left: 20, right: 40 }}\n        sx={{\n          \"& .MuiLineChart-area\": { fillOpacity: 0.82 },\n          \"& .MuiLineChart-line\": { strokeWidth: 2 },\n          [`& .MuiLineChart-line[data-series=\"s${focalIdx}\"]`]: {\n            strokeWidth: 3,\n          },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid, strokeWidth: 1 },\n        }}\n        slotProps={{\n          legend: {\n            position: { vertical: \"bottom\", horizontal: \"center\" },\n            sx: { fontSize: 14 },\n          },\n        }}\n      >\n        <ChartsReferenceLine\n          y={avgTotal}\n          label={`Avg total: ${(avgTotal / 1000).toFixed(1)}k`}\n          labelAlign=\"start\"\n          lineStyle={{\n            stroke: t.inkSoft,\n            strokeDasharray: \"4 4\",\n            strokeWidth: 1.5,\n          }}\n          labelStyle={{\n            fill: t.inkSoft,\n            fontSize: 13,\n            fontWeight: 600,\n            stroke: t.pageBg,\n            strokeWidth: 5,\n            paintOrder: \"stroke\",\n          }}\n        />\n      </LineChart>\n    </Box>\n  );\n}\n"}