{"spec_id":"venn-labeled-items","library":"muix","language":"javascript","code":"// anyplot.ai\n// venn-labeled-items: Chartgeist-Style Venn Diagram with Labeled Items\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 88/100 | Updated: 2026-11-08\n\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst SEPARATOR = \" ∩ \"; // joins the circle names of an overlap zone\nconst OUTSIDE = \"outside\"; // the zone for items in none of the circles\nconst CENTER_DIST = 1.18; // distance between circle centres, in radii (symmetric layout)\nconst NAME_BAND = 0.22; // room above and below the circles for the category names, in radii\nconst FILL_OPACITY = 0.2;\nconst ITEM_FONT = 16;\nconst NAME_FONT = 22;\nconst CHAR_W = 0.55; // average glyph width as a share of the font size\nconst LABEL_PAD = 5; // px kept free around each item label\nconst GRID_STEP = 6; // px between candidate label positions\nconst SEP_ENOUGH = 18; // px gap between labels of one zone beyond which centrality wins\nconst TITLE = \"venn-labeled-items · javascript · muix · anyplot.ai\";\nconst TITLE_H = 90;\nconst MARGIN = { top: 8, right: 24, bottom: 16, left: 24 };\n\n// Columns: set these to your data's column names\nconst ITEM = \"Beverage\"; // role: label\nconst ZONE = \"Zone\"; // role: zone (one circle name, several joined by the separator, or \"outside\")\n\n// Data: replace this block with your own records, one object per row\nconst data = [\n  { [ITEM]: \"Kombucha\", [ZONE]: \"Pretentious\" },\n  { [ITEM]: \"Matcha Latte\", [ZONE]: \"Pretentious\" },\n  { [ITEM]: \"Oat Milk Latte\", [ZONE]: \"Pretentious ∩ Delicious\" },\n  { [ITEM]: \"Cold Brew\", [ZONE]: \"Pretentious ∩ Delicious\" },\n  { [ITEM]: \"Flat White\", [ZONE]: \"Pretentious ∩ Delicious\" },\n  { [ITEM]: \"Sparkling Water\", [ZONE]: \"Pretentious ∩ Affordable\" },\n  { [ITEM]: \"Energy Drink\", [ZONE]: \"Pretentious ∩ Affordable\" },\n  { [ITEM]: \"Espresso\", [ZONE]: \"Delicious\" },\n  { [ITEM]: \"Cappuccino\", [ZONE]: \"Delicious\" },\n  { [ITEM]: \"Diner Coffee\", [ZONE]: \"Delicious ∩ Affordable\" },\n  { [ITEM]: \"Green Tea\", [ZONE]: \"Delicious ∩ Affordable\" },\n  { [ITEM]: \"Orange Juice\", [ZONE]: \"Delicious ∩ Affordable\" },\n  { [ITEM]: \"Tap Water\", [ZONE]: \"Affordable\" },\n  { [ITEM]: \"Herbal Tea\", [ZONE]: \"Affordable\" },\n  { [ITEM]: \"Chai\", [ZONE]: \"Pretentious ∩ Delicious ∩ Affordable\" },\n];\n\n// Plot: reads only data and the constants above\nconst rows = data.filter((d) => d[ITEM] != null);\nconst zoneMembers = rows.map((d) =>\n  d[ZONE] == null || String(d[ZONE]).trim() === OUTSIDE ? [] : String(d[ZONE]).split(SEPARATOR.trim()).map((s) => s.trim()),\n);\nconst circles = [...new Set(zoneMembers.flat())];\nconst zoneMask = zoneMembers.map((members) => members.reduce((m, s) => m | (1 << circles.indexOf(s)), 0));\n\n// Symmetric three-circle layout in px of the drawing area: equal radii, the\n// centres on an equilateral triangle, the whole figure centred\nconst PLOT_W = window.ANYPLOT_SIZE.width - MARGIN.left - MARGIN.right;\nconst PLOT_H = window.ANYPLOT_SIZE.height - TITLE_H - MARGIN.top - MARGIN.bottom;\nconst R = PLOT_H / (2 + (CENTER_DIST * Math.sqrt(3)) / 2 + 2 * NAME_BAND);\nconst triangle = [\n  { x: 0, y: (-CENTER_DIST * R) / Math.sqrt(3) },\n  { x: (-CENTER_DIST * R) / 2, y: (CENTER_DIST * R) / (2 * Math.sqrt(3)) },\n  { x: (CENTER_DIST * R) / 2, y: (CENTER_DIST * R) / (2 * Math.sqrt(3)) },\n];\nconst yShift = PLOT_H / 2 - (triangle[0].y - R + triangle[1].y + R) / 2;\nconst centers = circles.map((_, i) => ({ x: PLOT_W / 2 + triangle[i].x, y: triangle[i].y + yShift }));\nconst figureCenter = { x: PLOT_W / 2, y: centers.reduce((s, c) => s + c.y, 0) / Math.max(1, centers.length) };\n\n// Category names on each circle's outer side, pointing away from the centre\nconst nameBoxes = circles.map((name, i) => {\n  const dx = centers[i].x - figureCenter.x;\n  const dy = centers[i].y - figureCenter.y;\n  const len = Math.hypot(dx, dy) || 1;\n  const [ux, uy] = [dx / len, dy / len];\n  const w = name.length * NAME_FONT * CHAR_W;\n  const reach = R + 28 + (w / 2) * Math.abs(ux) + (NAME_FONT / 2) * Math.abs(uy);\n  return { name, x: centers[i].x + ux * reach, y: centers[i].y + uy * reach, w: w + 2 * LABEL_PAD, h: NAME_FONT + 2 * LABEL_PAD };\n});\n\n// Candidate label positions: a px grid, each point with its zone (bit mask of\n// the circles containing it) and its distance to the nearest circle edge\nconst candidates = [];\nfor (let x = 0; x <= PLOT_W; x += GRID_STEP) {\n  for (let y = 0; y <= PLOT_H; y += GRID_STEP) {\n    const dists = centers.map((c) => Math.hypot(x - c.x, y - c.y));\n    candidates.push({\n      x,\n      y,\n      mask: dists.reduce((m, d, i) => (d < R ? m | (1 << i) : m), 0),\n      clearance: Math.min(...dists.map((d) => Math.abs(d - R))),\n    });\n  }\n}\n\n// Greedy placement, item by item: the label box must lie wholly inside its\n// zone; among those spots it keeps clear of the labels already in that zone\n// (and of the category names, for outside items), then prefers the zone's interior.\nconst placed = [];\nrows.forEach((row, k) => {\n  const mask = zoneMask[k];\n  const w = String(row[ITEM]).length * ITEM_FONT * CHAR_W + 2 * LABEL_PAD;\n  const h = ITEM_FONT + 2 * LABEL_PAD;\n  const rivals = [...placed.filter((p) => p.mask === mask), ...(mask === 0 ? nameBoxes : [])];\n  let best = null;\n  candidates.forEach((c) => {\n    if (c.mask !== mask || c.x - w / 2 < 0 || c.x + w / 2 > PLOT_W || c.y - h / 2 < 0 || c.y + h / 2 > PLOT_H) return;\n    const probes = [[-w / 2, -h / 2], [w / 2, -h / 2], [-w / 2, h / 2], [w / 2, h / 2], [0, -h / 2], [0, h / 2], [-w / 2, 0], [w / 2, 0]];\n    const fits = probes.every(([ox, oy]) =>\n      centers.every((ctr, i) => Math.hypot(c.x + ox - ctr.x, c.y + oy - ctr.y) < R === Boolean(mask & (1 << i))),\n    );\n    if (!fits) return;\n    const gap = Math.min(\n      Infinity,\n      ...rivals.map((p) => Math.max(Math.abs(p.x - c.x) - (p.w + w) / 2, Math.abs(p.y - c.y) - (p.h + h) / 2)),\n    );\n    const score = Math.min(gap, SEP_ENOUGH) * 1000 + c.clearance;\n    if (best == null || score > best.score) best = { x: c.x, y: c.y, score };\n  });\n  const fallback = candidates.filter((c) => c.mask === mask).sort((a, b) => b.clearance - a.clearance)[0] ?? { x: PLOT_W / 2, y: PLOT_H / 2 };\n  placed.push({ label: row[ITEM], mask, w, h, ...(best ?? fallback) });\n});\n\n// Item ink: the zone's fill seen through the translucent circles over the\n// page, then dark or light text by that blend's luminance\nconst [pageRgb, ...paletteRgb] = [t.pageBg, ...t.palette].map((hex) => [16, 8, 0].map((s) => (parseInt(hex.slice(1), 16) >> s) & 255));\nconst zoneInk = new Map(\n  [...new Set(zoneMask)].map((m) => {\n    const blend = circles.reduce(\n      (acc, _, i) => (m & (1 << i) ? acc.map((v, c) => v + (paletteRgb[i][c] - v) * FILL_OPACITY) : acc),\n      pageRgb,\n    );\n    const [r, g, b] = blend.map((v) => v / 255).map((v) => (v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4));\n    return [m, 0.2126 * r + 0.7152 * g + 0.0722 * b > 0.2 ? \"#1A1A17\" : \"#FAF8F1\"];\n  }),\n);\n\nconst zoneCount = new Set(zoneMask).size;\nconst SUBTITLE = `A taxonomy of ${rows.length} ${ITEM.toLowerCase()}s across ${circles.length} traits and ${zoneCount} zones`;\n\n// The community package has no Venn chart: a custom layer draws circles,\n// category names and item labels through the container's px-unit scales.\nfunction LabeledVenn() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n\n  return (\n    <g>\n      {circles.map((name, i) => (\n        <circle\n          key={`circle-${name}`}\n          cx={xScale(centers[i].x)}\n          cy={yScale(centers[i].y)}\n          r={xScale(R) - xScale(0)}\n          fill={t.palette[i]}\n          fillOpacity={FILL_OPACITY}\n          stroke={t.palette[i]}\n          strokeWidth={2.5}\n        />\n      ))}\n      {nameBoxes.map((box) => (\n        <text\n          key={`name-${box.name}`}\n          x={xScale(box.x)}\n          y={yScale(box.y)}\n          textAnchor=\"middle\"\n          dominantBaseline=\"middle\"\n          fontSize={NAME_FONT}\n          fontWeight={700}\n          letterSpacing={1}\n          fill={t.ink}\n        >\n          {box.name.toUpperCase()}\n        </text>\n      ))}\n      {placed.map((p) => (\n        <text\n          key={`item-${p.label}`}\n          x={xScale(p.x)}\n          y={yScale(p.y)}\n          textAnchor=\"middle\"\n          dominantBaseline=\"central\"\n          fontSize={ITEM_FONT}\n          fill={zoneInk.get(p.mask)}\n        >\n          {p.label}\n        </text>\n      ))}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n\n  return (\n    <div style={{ width, height, background: t.pageBg, display: \"flex\", flexDirection: \"column\" }}>\n      <div style={{ height: TITLE_H, padding: \"18px 36px 0\", boxSizing: \"border-box\" }}>\n        <div style={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.2 }}>{TITLE}</div>\n        <div style={{ fontSize: 20, fontStyle: \"italic\", fontFamily: \"Georgia, 'Times New Roman', serif\", color: t.inkSoft, lineHeight: 1.2, marginTop: 8 }}>\n          {SUBTITLE}\n        </div>\n      </div>\n      <ChartsContainer\n        width={width}\n        height={height - TITLE_H}\n        series={[]}\n        skipAnimation\n        margin={MARGIN}\n        xAxis={[{ id: \"px-x\", scaleType: \"linear\", min: 0, max: PLOT_W, position: \"none\" }]}\n        yAxis={[{ id: \"px-y\", scaleType: \"linear\", min: 0, max: PLOT_H, reverse: true, position: \"none\" }]}\n      >\n        <LabeledVenn />\n      </ChartsContainer>\n    </div>\n  );\n}\n"}