{"spec_id":"line-parametric","library":"muix","language":"javascript","code":"// anyplot.ai\n// line-parametric: Parametric Curve Plot\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 87/100 | Updated: 2026-11-08\n\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport { useDrawingArea, useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst PAD_SHARE = 0.06; // share of the larger span added around each curve\nconst LINE_WIDTH = 3.5;\nconst MARGIN = { top: 12, right: 28, bottom: 8, left: 8 };\nconst X_AXIS_H = 60;\nconst Y_AXIS_W = 68;\nconst HEADER_H = 80;\nconst PANEL_TITLE_H = 52;\nconst FOOTER_H = 56;\nconst SIDE_PAD = 32;\nconst PANEL_GAP = 32;\nconst LABEL_FONT = 15;\nconst LABEL_CHAR_EM = 0.6; // estimated width of one label character, in em, for the free-space test\nconst LABEL_RINGS = [30, 56, 84, 116]; // distances from its point at which a label is tried, in px\n// Directions a label is tried in, preferred first: the four diagonals, then above, below, right and left\nconst LABEL_DIRECTIONS = [[1, -1], [-1, -1], [1, 1], [-1, 1], [0, -1], [0, 1], [1, 0], [-1, 0]];\nconst LABEL_CLEARANCE = 6; // px kept free between a label and the curve\nconst LEADER_GAP = 12; // px between a point and the start of its leader line\n\n// Columns: set these to your data's column names\nconst CURVE = \"Curve\"; // role: extra\nconst T = \"t\"; // role: t\nconst X = \"x(t)\"; // role: x\nconst Y = \"y(t)\"; // role: y\n\n// Data: replace this block with your own records, one object per row\n// 800 samples of each curve: the Lissajous figure over one period and two turns of the spiral.\nconst data = [\n  { name: \"Lissajous figure: x = sin 3t, y = sin 2t\", tEnd: 2 * Math.PI, fx: (s) => Math.sin(3 * s), fy: (s) => Math.sin(2 * s) },\n  { name: \"Archimedean spiral: x = t cos t, y = t sin t\", tEnd: 4 * Math.PI, fx: (s) => s * Math.cos(s), fy: (s) => s * Math.sin(s) },\n].flatMap((curve) =>\n  Array.from({ length: 800 }, (_, i) => {\n    const s = (i / 799) * curve.tEnd;\n    return { [CURVE]: curve.name, [T]: s, [X]: curve.fx(s), [Y]: curve.fy(s) };\n  }),\n);\n\n// Plot: reads only data and the constants above\nconst { width: W, height: H } = window.ANYPLOT_SIZE;\nconst panelW = (W - 2 * SIDE_PAD - PANEL_GAP) / 2;\nconst panelH = H - HEADER_H - PANEL_TITLE_H - FOOTER_H;\nconst drawW = panelW - MARGIN.left - MARGIN.right - Y_AXIS_W;\nconst drawH = panelH - MARGIN.top - MARGIN.bottom - X_AXIS_H;\nconst seqRgb = t.seq.map((hex: string) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16)));\n\n// One panel per curve, its rows in order of t. Both axes get the same units per pixel\n// (equal aspect), centred on the curve, with the larger span setting the scale.\nconst panels = [...new Set(data.map((d) => d[CURVE]))].map((name) => {\n  const rows = data.filter((d) => d[CURVE] === name).sort((a, b) => a[T] - b[T]);\n  const xs = rows.map((d) => d[X]);\n  const ys = rows.map((d) => d[Y]);\n  const [x0, x1, y0, y1] = [Math.min(...xs), Math.max(...xs), Math.min(...ys), Math.max(...ys)];\n  const unitsPerPx = Math.max((x1 - x0) / drawW, (y1 - y0) / drawH) * (1 + 2 * PAD_SHARE);\n  const tStart = rows[0][T];\n  const tEnd = rows[rows.length - 1][T];\n  return {\n    name,\n    rows,\n    tStart,\n    tEnd,\n    xDomain: [(x0 + x1) / 2 - (unitsPerPx * drawW) / 2, (x0 + x1) / 2 + (unitsPerPx * drawW) / 2],\n    yDomain: [(y0 + y1) / 2 - (unitsPerPx * drawH) / 2, (y0 + y1) / 2 + (unitsPerPx * drawH) / 2],\n    // Imprint sequential ramp along increasing t: green at the start, blue at the end\n    colors: rows.map((d) => {\n      const f = tEnd > tStart ? (d[T] - tStart) / (tEnd - tStart) : 0;\n      return `rgb(${seqRgb[0].map((c: number, k: number) => Math.round(c + (seqRgb[1][k] - c) * f)).join(\", \")})`;\n    }),\n  };\n});\n\nconst TITLE = \"line-parametric · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${panels.length} curves · ${data.length.toLocaleString(\"en-US\")} samples · equal aspect ratio in each panel`;\n\n// The curve as short segments coloured by t, an arrowhead ending on the last point and a start dot.\n// Each start and end label takes the nearest spot around its point whose box holds the fewest curve\n// samples, inside the drawing area and clear of the label placed before it, with a leader to the point.\nfunction CurveLayer({ panel }: { panel: (typeof panels)[number] }) {\n  const xScale = useXScale() as (v: number) => number;\n  const yScale = useYScale() as (v: number) => number;\n  const area = useDrawingArea();\n  const pts = panel.rows.map((d) => [xScale(d[X]), yScale(d[Y])]);\n  const [sx, sy] = pts[0];\n  const [ex, ey] = pts[pts.length - 1];\n  const [px, py] = pts[pts.length - 2];\n  const angle = (Math.atan2(ey - py, ex - px) * 180) / Math.PI;\n  const labels = [\n    { x: sx, y: sy, text: `start, ${T} = ${panel.tStart.toFixed(2)}` },\n    { x: ex, y: ey, text: `end, ${T} = ${panel.tEnd.toFixed(2)}` },\n  ].reduce((placed, lab) => {\n    const w = lab.text.length * LABEL_FONT * LABEL_CHAR_EM;\n    const h = LABEL_FONT * 1.3;\n    const best = LABEL_RINGS.flatMap((r) =>\n      LABEL_DIRECTIONS.map(([dx, dy]) => {\n        const k = dx !== 0 && dy !== 0 ? Math.SQRT1_2 : 1;\n        const ax = lab.x + dx * r * k;\n        const ay = lab.y + dy * r * k;\n        const x0 = dx > 0 ? ax : dx < 0 ? ax - w : ax - w / 2;\n        const y0 = dy > 0 ? ay : dy < 0 ? ay - h : ay - h / 2;\n        const hits = pts.filter(\n          ([qx, qy]) =>\n            qx > x0 - LABEL_CLEARANCE && qx < x0 + w + LABEL_CLEARANCE && qy > y0 - LABEL_CLEARANCE && qy < y0 + h + LABEL_CLEARANCE,\n        ).length;\n        // Curve samples within the clearance of the leader segment, from LEADER_GAP off the point to the label\n        const lx = lab.x + dx * k * LEADER_GAP;\n        const ly = lab.y + dy * k * LEADER_GAP;\n        const len2 = (ax - lx) ** 2 + (ay - ly) ** 2;\n        const crossings = pts.filter(([qx, qy]) => {\n          const u = Math.max(0, Math.min(1, ((qx - lx) * (ax - lx) + (qy - ly) * (ay - ly)) / len2));\n          return Math.hypot(qx - lx - u * (ax - lx), qy - ly - u * (ay - ly)) < LABEL_CLEARANCE;\n        }).length;\n        const outside = x0 < area.left || x0 + w > area.left + area.width || y0 < area.top || y0 + h > area.top + area.height;\n        const clash = placed.some((b) => x0 < b.x0 + b.w && b.x0 < x0 + w && y0 < b.y0 + b.h && b.y0 < y0 + h);\n        return { ...lab, dx, dy, k, ax, ay, x0, y0, w, h, score: hits + crossings + (outside || clash ? pts.length : 0) };\n      }),\n    ).reduce((a, b) => (b.score < a.score ? b : a));\n    return [...placed, best];\n  }, []);\n  return (\n    <g>\n      {pts.slice(1).map(([x2, y2], i) => (\n        <line\n          key={i}\n          x1={pts[i][0]}\n          y1={pts[i][1]}\n          x2={x2}\n          y2={y2}\n          stroke={panel.colors[i + 1]}\n          strokeWidth={LINE_WIDTH}\n          strokeLinecap=\"round\"\n        />\n      ))}\n      {/* Arrow tip on the last point; the start dot comes after it so a closed curve shows both */}\n      <path\n        d=\"M 0 0 L -24 -10 L -24 10 Z\"\n        transform={`translate(${ex}, ${ey}) rotate(${angle})`}\n        fill={panel.colors[panel.colors.length - 1]}\n        stroke={t.pageBg}\n        strokeWidth={2}\n      />\n      <circle cx={sx} cy={sy} r={8} fill={panel.colors[0]} stroke={t.pageBg} strokeWidth={2.5} />\n      {labels.map((lab) => (\n        <g key={lab.text}>\n          <line\n            x1={lab.x + lab.dx * lab.k * LEADER_GAP}\n            y1={lab.y + lab.dy * lab.k * LEADER_GAP}\n            x2={lab.ax}\n            y2={lab.ay}\n            stroke={t.inkSoft}\n            strokeWidth={1.5}\n          />\n          <text\n            x={lab.dx > 0 ? lab.x0 : lab.dx < 0 ? lab.x0 + lab.w : lab.x0 + lab.w / 2}\n            y={lab.y0 + lab.h / 2}\n            textAnchor={lab.dx > 0 ? \"start\" : lab.dx < 0 ? \"end\" : \"middle\"}\n            dominantBaseline=\"central\"\n            fontSize={LABEL_FONT}\n            fontWeight={600}\n            fill={t.ink}\n            stroke={t.pageBg}\n            strokeWidth={4}\n            paintOrder=\"stroke\"\n          >\n            {lab.text}\n          </text>\n        </g>\n      ))}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  return (\n    <div style={{ width: W, height: H, display: \"flex\", flexDirection: \"column\" }}>\n      <div style={{ height: HEADER_H, padding: `16px ${SIDE_PAD}px 0 ${SIDE_PAD + 8}px`, boxSizing: \"border-box\" }}>\n        <div style={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.25 }}>{TITLE}</div>\n        <div style={{ fontSize: 15, color: t.inkSoft, marginTop: 6 }}>{SUBTITLE}</div>\n      </div>\n      <div style={{ display: \"flex\", gap: PANEL_GAP, padding: `0 ${SIDE_PAD}px` }}>\n        {panels.map((panel) => (\n          <div key={panel.name} style={{ width: panelW, display: \"flex\", flexDirection: \"column\" }}>\n            <div style={{ height: PANEL_TITLE_H, paddingLeft: MARGIN.left + Y_AXIS_W, boxSizing: \"border-box\" }}>\n              <div style={{ fontSize: 17, fontWeight: 600, color: t.ink }}>{panel.name}</div>\n              <div style={{ fontSize: 14, color: t.inkSoft, marginTop: 4 }}>\n                {panel.rows.length} samples, {T} from {panel.tStart.toFixed(2)} to {panel.tEnd.toFixed(2)}\n              </div>\n            </div>\n            <ChartsContainer\n              width={panelW}\n              height={panelH}\n              margin={MARGIN}\n              skipAnimation\n              series={[]}\n              xAxis={[\n                {\n                  scaleType: \"linear\",\n                  min: panel.xDomain[0],\n                  max: panel.xDomain[1],\n                  domainLimit: \"strict\",\n                  label: X,\n                  height: X_AXIS_H,\n                  tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n                  labelStyle: { fontSize: 16, fill: t.ink },\n                },\n              ]}\n              yAxis={[\n                {\n                  scaleType: \"linear\",\n                  min: panel.yDomain[0],\n                  max: panel.yDomain[1],\n                  domainLimit: \"strict\",\n                  label: Y,\n                  width: Y_AXIS_W,\n                  tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n                  labelStyle: { fontSize: 16, fill: t.ink },\n                },\n              ]}\n              sx={{\n                \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n                \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n                \"& .MuiChartsGrid-line\": { stroke: t.grid, strokeWidth: 1 },\n              }}\n            >\n              <ChartsGrid horizontal vertical />\n              <CurveLayer panel={panel} />\n              <ChartsXAxis />\n              <ChartsYAxis />\n            </ChartsContainer>\n          </div>\n        ))}\n      </div>\n      <div\n        style={{\n          height: FOOTER_H,\n          display: \"flex\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          gap: 12,\n          fontSize: 15,\n          color: t.inkSoft,\n        }}\n      >\n        <span>Colour along each curve: {T} at the start</span>\n        <span\n          style={{\n            width: 260,\n            height: 14,\n            borderRadius: 7,\n            background: `linear-gradient(90deg, ${t.seq[0]}, ${t.seq[1]})`,\n            display: \"inline-block\",\n          }}\n        />\n        <span>{T} at the end</span>\n      </div>\n    </div>\n  );\n}\n"}