{"spec_id":"alluvial-basic","library":"muix","language":"javascript","code":"// anyplot.ai\n// alluvial-basic: Basic Alluvial Diagram\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 86/100 | Updated: 2026-10-23\nimport * as React from \"react\";\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { useXScale, useYScale, useDrawingArea } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst NODE_W = 18;\nconst MID_LABEL_FONT = 13;\nconst MID_LABEL_MIN_HEIGHT = MID_LABEL_FONT + 6;\n\n// Columns: set these to your data's column names\nconst TIME_POINT = \"Quarter\"; // role: time_point\nconst NEXT_TIME_POINT = \"Next quarter\"; // role: extra\nconst CATEGORY = \"Subscription tier\"; // role: category\nconst TO_CATEGORY = \"Next tier\"; // role: extra\nconst VALUE = \"Customers\"; // role: value\nconst FLOW = \"Transition count\"; // role: flow\n\n// Data: replace this block with your own records, one object per row\nconst data = (() => {\n  const stackOrder = [\"Enterprise\", \"Pro\", \"Basic\", \"Free\", \"Churned\"];\n  const timePoints = [\"Q1 2024\", \"Q2 2024\", \"Q3 2024\", \"Q4 2024\"];\n  const transition = {\n    Free: { Free: 0.7, Basic: 0.22, Pro: 0, Enterprise: 0, Churned: 0.08 },\n    Basic: { Free: 0.1, Basic: 0.55, Pro: 0.28, Enterprise: 0, Churned: 0.07 },\n    Pro: { Free: 0, Basic: 0.1, Pro: 0.65, Enterprise: 0.2, Churned: 0.05 },\n    Enterprise: { Free: 0, Basic: 0, Pro: 0.08, Enterprise: 0.9, Churned: 0.02 },\n    Churned: { Free: 0.03, Basic: 0, Pro: 0, Enterprise: 0, Churned: 0.97 },\n  };\n  const populations = [\n    { Free: 500, Basic: 300, Pro: 150, Enterprise: 50, Churned: 0 },\n  ];\n  for (let i = 1; i < timePoints.length; i += 1) {\n    const prev = populations[i - 1];\n    const next = {};\n    stackOrder.forEach((to) => {\n      next[to] = stackOrder.reduce(\n        (sum, from) => sum + prev[from] * transition[from][to],\n        0,\n      );\n    });\n    populations.push(next);\n  }\n\n  const rows = [];\n  for (let step = 0; step < timePoints.length - 1; step += 1) {\n    const pop = populations[step];\n    stackOrder.forEach((from) => {\n      stackOrder.forEach((to) => {\n        const rate = transition[from][to];\n        rows.push({\n          [TIME_POINT]: timePoints[step],\n          [NEXT_TIME_POINT]: timePoints[step + 1],\n          [CATEGORY]: from,\n          [TO_CATEGORY]: to,\n          [VALUE]: pop[from],\n          [FLOW]: pop[from] * rate,\n        });\n      });\n    });\n  }\n  return rows;\n})();\n\n// Plot: reads only data and the constants above\nconst categories = [...new Set(data.map((d) => d[CATEGORY]))];\nconst timePoints = [\n  ...new Set([\n    ...data.map((d) => d[TIME_POINT]),\n    ...data.map((d) => d[NEXT_TIME_POINT]),\n  ]),\n];\nconst categoryColor = Object.fromEntries(\n  categories.map((cat, i) => [cat, t.palette[i]]),\n);\n\nconst populations = timePoints.map((tp, idx) => {\n  const pop = {};\n  categories.forEach((cat) => {\n    if (idx < timePoints.length - 1) {\n      pop[cat] = data\n        .filter((d) => d[TIME_POINT] === tp && d[CATEGORY] === cat)\n        .reduce((sum, d) => sum + d[FLOW], 0);\n    } else {\n      const prevTp = timePoints[idx - 1];\n      pop[cat] = data\n        .filter((d) => d[TIME_POINT] === prevTp && d[TO_CATEGORY] === cat)\n        .reduce((sum, d) => sum + d[FLOW], 0);\n    }\n  });\n  return pop;\n});\n\nconst total = categories.reduce((sum, cat) => sum + populations[0][cat], 0);\n\nconst nodeExtents = populations.map((pop) => {\n  let cursor = total;\n  const extents = {};\n  categories.forEach((cat) => {\n    const bottom = cursor - pop[cat];\n    extents[cat] = { top: cursor, bottom };\n    cursor = bottom;\n  });\n  return extents;\n});\n\nconst flows = (() => {\n  const result = [];\n  for (let step = 0; step < timePoints.length - 1; step += 1) {\n    const tp = timePoints[step];\n    const outCursor = {};\n    const inCursor = {};\n    categories.forEach((cat) => {\n      outCursor[cat] = nodeExtents[step][cat].top;\n      inCursor[cat] = nodeExtents[step + 1][cat].top;\n    });\n    categories.forEach((from) => {\n      categories.forEach((to) => {\n        const row = data.find(\n          (d) =>\n            d[TIME_POINT] === tp &&\n            d[CATEGORY] === from &&\n            d[TO_CATEGORY] === to,\n        );\n        const val = row ? row[FLOW] : 0;\n        if (val < 0.5) return;\n        const srcTop = outCursor[from];\n        const srcBottom = srcTop - val;\n        outCursor[from] = srcBottom;\n        const dstTop = inCursor[to];\n        const dstBottom = dstTop - val;\n        inCursor[to] = dstBottom;\n        result.push({\n          step,\n          from,\n          to,\n          value: val,\n          srcTop,\n          srcBottom,\n          dstTop,\n          dstBottom,\n        });\n      });\n    });\n  }\n  return result;\n})();\n\nfunction AlluvialFlows() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  return (\n    <g data-drawing-container>\n      {flows.map((f, i) => {\n        const x1 = xScale(timePoints[f.step]) + NODE_W / 2;\n        const x2 = xScale(timePoints[f.step + 1]) - NODE_W / 2;\n        const midX = (x1 + x2) / 2;\n        const ySrcTop = yScale(f.srcTop);\n        const ySrcBottom = yScale(f.srcBottom);\n        const yDstTop = yScale(f.dstTop);\n        const yDstBottom = yScale(f.dstBottom);\n        return (\n          <path\n            key={`flow-${i}`}\n            d={`M ${x1} ${ySrcTop} C ${midX} ${ySrcTop}, ${midX} ${yDstTop}, ${x2} ${yDstTop} L ${x2} ${yDstBottom} C ${midX} ${yDstBottom}, ${midX} ${ySrcBottom}, ${x1} ${ySrcBottom} Z`}\n            fill={categoryColor[f.from]}\n            fillOpacity={0.55}\n            stroke={categoryColor[f.from]}\n            strokeOpacity={0.55}\n            strokeWidth={1}\n          />\n        );\n      })}\n    </g>\n  );\n}\n\nfunction AlluvialNodes() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  return (\n    <g data-drawing-container>\n      {timePoints.map((timePoint, colIndex) => {\n        const cx = xScale(timePoint);\n        const isFirst = colIndex === 0;\n        const isLast = colIndex === timePoints.length - 1;\n        return categories.map((cat) => {\n          const value = populations[colIndex][cat];\n          if (value < 0.5) return null;\n          const { top, bottom } = nodeExtents[colIndex][cat];\n          const yTop = yScale(top);\n          const yBottom = yScale(bottom);\n          const midY = (yTop + yBottom) / 2;\n          const segmentH = yBottom - yTop;\n          const showMidLabel =\n            !isFirst && !isLast && segmentH >= MID_LABEL_MIN_HEIGHT;\n          const midPillW = cat.length * MID_LABEL_FONT * 0.6 + 14;\n          const midPillH = MID_LABEL_FONT + 8;\n          return (\n            <React.Fragment key={`${timePoint}-${cat}`}>\n              <rect\n                x={cx - NODE_W / 2}\n                y={yTop}\n                width={NODE_W}\n                height={segmentH}\n                fill={categoryColor[cat]}\n                stroke={t.pageBg}\n                strokeWidth={1.5}\n              />\n              {(isFirst || isLast) && (\n                <text\n                  x={isFirst ? cx - NODE_W / 2 - 10 : cx + NODE_W / 2 + 10}\n                  y={midY + 4}\n                  textAnchor={isFirst ? \"end\" : \"start\"}\n                  fontSize={13}\n                  fill={t.inkSoft}\n                >\n                  {`${cat} · ${Math.round(value)}`}\n                </text>\n              )}\n              {showMidLabel && (\n                <>\n                  <rect\n                    x={cx - midPillW / 2}\n                    y={midY - midPillH / 2}\n                    width={midPillW}\n                    height={midPillH}\n                    rx={midPillH / 2}\n                    fill={t.pageBg}\n                    opacity={0.92}\n                  />\n                  <text\n                    x={cx}\n                    y={midY + MID_LABEL_FONT / 2 - 1}\n                    textAnchor=\"middle\"\n                    fontSize={MID_LABEL_FONT}\n                    fill={t.inkSoft}\n                  >\n                    {cat}\n                  </text>\n                </>\n              )}\n            </React.Fragment>\n          );\n        });\n      })}\n    </g>\n  );\n}\n\nfunction ValueAxisTitle() {\n  const { top, height } = useDrawingArea();\n  const cy = top + height / 2;\n  return (\n    <text\n      x={16}\n      y={cy}\n      textAnchor=\"middle\"\n      fontSize={13}\n      fill={t.inkSoft}\n      transform={`rotate(-90, 16, ${cy})`}\n    >\n      {VALUE}\n    </text>\n  );\n}\n\nconst TITLE = \"alluvial-basic · javascript · muix · anyplot.ai\";\nconst TITLE_FONT_DEFAULT = 28;\nconst titleFontSize =\n  TITLE.length > 67\n    ? Math.round(TITLE_FONT_DEFAULT * (67 / TITLE.length))\n    : TITLE_FONT_DEFAULT;\nconst SUBTITLE = `Simulated SaaS subscription-tier migration · ${Math.round(total).toLocaleString(\"en-US\")} ${VALUE.toLowerCase()} across ${timePoints.length} ${TIME_POINT.toLowerCase()}s`;\nconst TITLE_H = 44;\nconst SUBTITLE_H = 26;\nconst LEGEND_H = 34;\n\nfunction Legend() {\n  return (\n    <div\n      style={{\n        height: LEGEND_H,\n        display: \"flex\",\n        alignItems: \"center\",\n        gap: \"16px\",\n        flexWrap: \"wrap\",\n      }}\n    >\n      {categories.map((cat) => (\n        <div\n          key={cat}\n          style={{ display: \"flex\", alignItems: \"center\", gap: \"7px\" }}\n        >\n          <span\n            style={{\n              width: \"13px\",\n              height: \"13px\",\n              borderRadius: \"3px\",\n              backgroundColor: categoryColor[cat],\n              display: \"inline-block\",\n            }}\n          />\n          <span style={{ fontSize: \"14px\", color: t.inkSoft }}>{cat}</span>\n        </div>\n      ))}\n      <span style={{ fontSize: \"14px\", color: t.inkSoft, fontStyle: \"italic\" }}>\n        Band width ∝ {FLOW.toLowerCase()}\n      </span>\n    </div>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  const chartHeight = height - TITLE_H - SUBTITLE_H - LEGEND_H;\n\n  return (\n    <div style={{ width, height, display: \"flex\", flexDirection: \"column\" }}>\n      <div style={{ paddingLeft: \"20px\" }}>\n        <div\n          style={{\n            height: `${TITLE_H}px`,\n            lineHeight: `${TITLE_H}px`,\n            fontSize: `${titleFontSize}px`,\n            fontWeight: 500,\n            color: t.ink,\n          }}\n        >\n          {TITLE}\n        </div>\n        <div\n          style={{\n            height: `${SUBTITLE_H}px`,\n            lineHeight: `${SUBTITLE_H}px`,\n            fontSize: \"15px\",\n            fontStyle: \"italic\",\n            color: t.inkSoft,\n          }}\n        >\n          {SUBTITLE}\n        </div>\n        <Legend />\n      </div>\n      <ChartsContainer\n        width={width}\n        height={chartHeight}\n        series={[]}\n        margin={{ top: 20, bottom: 20, left: 150, right: 150 }}\n        xAxis={[\n          {\n            id: \"time\",\n            scaleType: \"point\",\n            data: timePoints,\n            position: \"top\",\n            disableLine: true,\n            disableTicks: true,\n            height: 40,\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft, fontWeight: 600 },\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"value\",\n            scaleType: \"linear\",\n            min: 0,\n            max: total,\n            position: \"none\",\n          },\n        ]}\n        skipAnimation\n      >\n        <ChartsXAxis axisId=\"time\" />\n        <ValueAxisTitle />\n        <AlluvialFlows />\n        <AlluvialNodes />\n      </ChartsContainer>\n    </div>\n  );\n}\n"}