{"version":3,"file":"WaffleChart.mjs","names":["classes"],"sources":["../../src/WaffleChart/WaffleChart.tsx"],"sourcesContent":["import { useState } from 'react';\nimport {\n  Box,\n  BoxProps,\n  createVarsResolver,\n  ElementProps,\n  factory,\n  Factory,\n  getThemeColor,\n  MantineColor,\n  rem,\n  StylesApiProps,\n  Tooltip,\n  useMantineTheme,\n  useProps,\n  useStyles,\n} from '@mantine/core';\nimport classes from './WaffleChart.module.css';\n\nexport interface WaffleChartCell {\n  /** Segment name */\n  name: string;\n\n  /** Segment value */\n  value: number;\n\n  /** Segment color */\n  color: MantineColor;\n\n  /** Unique key for the segment */\n  key?: string | number;\n}\n\nexport type WaffleChartStylesNames =\n  | 'root'\n  | 'grid'\n  | 'cell'\n  | 'legend'\n  | 'legendItem'\n  | 'legendSwatch'\n  | 'legendLabel';\n\nexport type WaffleChartCssVariables = {\n  root: '--waffle-cell-radius' | '--waffle-empty-color';\n};\n\nexport interface WaffleChartProps\n  extends BoxProps, StylesApiProps<WaffleChartFactory>, ElementProps<'div'> {\n  /** Array of data segments with name, value, and color */\n  data: WaffleChartCell[];\n\n  /** Number of rows, @default 10 */\n  rows?: number;\n\n  /** Number of columns, @default 10 */\n  columns?: number;\n\n  /** Total value for the chart, determines how many cells are filled vs empty, sum of all values by default */\n  total?: number;\n\n  /** Gap between cells in px, @default 2 */\n  gap?: number;\n\n  /** Cell border radius, @default 0 */\n  cellRadius?: number;\n\n  /** Color of empty (unfilled) cells */\n  emptyColor?: MantineColor;\n\n  /** Whether to show tooltip on hover, @default false */\n  withTooltip?: boolean;\n\n  /** Custom tooltip label formatter */\n  getTooltipLabel?: (cell: WaffleChartCell & { count: number }) => React.ReactNode;\n\n  /** Whether to show legend, @default true */\n  withLegend?: boolean;\n\n  /** Legend position, @default 'bottom' */\n  legendPosition?: 'top' | 'bottom' | 'left' | 'right';\n\n  /** Fill direction, @default 'left-to-right' */\n  fillDirection?: 'left-to-right' | 'right-to-left' | 'top-to-bottom' | 'bottom-to-top';\n\n  /** Chart size (width), auto-calculated from columns if not set */\n  size?: number;\n}\n\nexport type WaffleChartFactory = Factory<{\n  props: WaffleChartProps;\n  ref: HTMLDivElement;\n  stylesNames: WaffleChartStylesNames;\n  vars: WaffleChartCssVariables;\n}>;\n\nconst defaultProps = {\n  rows: 10,\n  columns: 10,\n  gap: 2,\n  cellRadius: 0,\n  withTooltip: false,\n  withLegend: true,\n  legendPosition: 'bottom',\n  fillDirection: 'left-to-right',\n} satisfies Partial<WaffleChartProps>;\n\nconst varsResolver = createVarsResolver<WaffleChartFactory>(\n  (theme, { cellRadius, emptyColor }) => ({\n    root: {\n      '--waffle-cell-radius': rem(cellRadius),\n      '--waffle-empty-color': emptyColor ? getThemeColor(emptyColor, theme) : undefined,\n    },\n  })\n);\n\ninterface AllocatedCell {\n  segmentIndex: number;\n}\n\n/**\n * A part-to-whole chart has no meaning for negative values, and letting them through would\n * allocate more cells than the grid can hold. Non-finite values are normalized to zero as\n * well – `Math.max(0, NaN)` is `NaN`, which would poison the sum and leave every segment\n * without cells instead of dropping just the offending one.\n */\nfunction normalizeSegmentValue(value: number) {\n  return Number.isFinite(value) ? Math.max(0, value) : 0;\n}\n\nfunction allocateCells(\n  data: WaffleChartCell[],\n  gridCells: number,\n  totalValue?: number\n): AllocatedCell[] {\n  const values = data.map((d) => normalizeSegmentValue(d.value));\n  const sum = values.reduce((acc, value) => acc + value, 0);\n\n  if (sum === 0) {\n    return Array.from({ length: gridCells }, () => ({ segmentIndex: -1 }));\n  }\n\n  const denominator = totalValue != null ? Math.max(totalValue, sum) : sum;\n  const filledTarget = Math.round((sum / denominator) * gridCells);\n  const raw = values.map((value) => (value / sum) * filledTarget);\n  const floored = raw.map(Math.floor);\n  const remainder = filledTarget - floored.reduce((a, b) => a + b, 0);\n\n  const fractions = raw.map((v, i) => ({ i, frac: v - floored[i] }));\n  fractions.sort((a, b) => b.frac - a.frac);\n  for (let j = 0; j < Math.min(remainder, fractions.length); j++) {\n    floored[fractions[j].i]++;\n  }\n\n  const cells: AllocatedCell[] = [];\n  data.forEach((_, i) => {\n    for (let j = 0; j < floored[i] && cells.length < gridCells; j++) {\n      cells.push({ segmentIndex: i });\n    }\n  });\n\n  while (cells.length < gridCells) {\n    cells.push({ segmentIndex: -1 });\n  }\n\n  return cells;\n}\n\nconst DEFAULT_CELL_SIZE = 20;\n\nexport const WaffleChart = factory<WaffleChartFactory>((_props) => {\n  const props = useProps('WaffleChart', defaultProps, _props);\n  const {\n    classNames,\n    className,\n    style,\n    styles,\n    unstyled,\n    vars,\n    attributes,\n    data,\n    rows,\n    columns,\n    total,\n    gap,\n    cellRadius,\n    emptyColor,\n    withTooltip,\n    getTooltipLabel,\n    withLegend,\n    legendPosition,\n    fillDirection,\n    size,\n    variant,\n    ...others\n  } = props;\n\n  const theme = useMantineTheme();\n\n  const getStyles = useStyles<WaffleChartFactory>({\n    name: 'WaffleChart',\n    classes,\n    props,\n    className,\n    style,\n    classNames,\n    styles,\n    unstyled,\n    attributes,\n    vars,\n    varsResolver,\n  });\n\n  const [hoveredCell, setHoveredCell] = useState<(WaffleChartCell & { count: number }) | null>(\n    null\n  );\n  const [hoveredLegendIndex, setHoveredLegendIndex] = useState<number | null>(null);\n\n  const resolvedRows = Math.max(1, Math.floor(rows!));\n  const resolvedColumns = Math.max(1, Math.floor(columns!));\n  const resolvedGap = Math.max(0, gap!);\n\n  const totalCells = resolvedRows * resolvedColumns;\n\n  // `size` is the total width of the grid, gaps included. When the gaps alone would exceed\n  // it, the gap shrinks too – clamping only the cell size would render a grid wider than\n  // the caller asked for. `size != null` rather than a truthiness check so `size={0}` is\n  // honored instead of silently falling back to the default cell size.\n  const hasSize = size != null;\n  const gapTotal = (resolvedColumns - 1) * resolvedGap;\n  const effectiveGap =\n    hasSize && gapTotal > size! && resolvedColumns > 1\n      ? size! / (resolvedColumns - 1)\n      : resolvedGap;\n  const cellSize = hasSize\n    ? Math.max(0, (size! - (resolvedColumns - 1) * effectiveGap) / resolvedColumns)\n    : DEFAULT_CELL_SIZE;\n  const allocated = allocateCells(data, totalCells, total);\n\n  const cellCounts = new Map<number, number>();\n  for (const cell of allocated) {\n    if (cell.segmentIndex >= 0) {\n      cellCounts.set(cell.segmentIndex, (cellCounts.get(cell.segmentIndex) || 0) + 1);\n    }\n  }\n\n  const svgWidth = resolvedColumns * cellSize + (resolvedColumns - 1) * effectiveGap;\n  const svgHeight = resolvedRows * cellSize + (resolvedRows - 1) * effectiveGap;\n\n  const cellElements = allocated.map((cell, index) => {\n    let row: number;\n    let col: number;\n\n    if (fillDirection === 'top-to-bottom') {\n      col = Math.floor(index / resolvedRows);\n      row = index % resolvedRows;\n    } else if (fillDirection === 'bottom-to-top') {\n      col = Math.floor(index / resolvedRows);\n      row = resolvedRows - 1 - (index % resolvedRows);\n    } else if (fillDirection === 'right-to-left') {\n      row = Math.floor(index / resolvedColumns);\n      col = resolvedColumns - 1 - (index % resolvedColumns);\n    } else {\n      row = Math.floor(index / resolvedColumns);\n      col = index % resolvedColumns;\n    }\n\n    const x = col * (cellSize + effectiveGap);\n    const y = row * (cellSize + effectiveGap);\n    const segmentIndex = cell.segmentIndex;\n    const isEmpty = segmentIndex < 0;\n    const color = isEmpty ? undefined : getThemeColor(data[segmentIndex].color, theme);\n\n    const dimmed = hoveredLegendIndex != null && segmentIndex !== hoveredLegendIndex;\n\n    return (\n      <rect\n        key={index}\n        {...getStyles('cell', {\n          style: dimmed ? { opacity: 0.4 } : undefined,\n        })}\n        x={x}\n        y={y}\n        width={cellSize}\n        height={cellSize}\n        rx={cellRadius}\n        ry={cellRadius}\n        fill={color}\n        data-empty={isEmpty || undefined}\n        onMouseEnter={\n          withTooltip\n            ? () =>\n                isEmpty\n                  ? setHoveredCell(null)\n                  : setHoveredCell({\n                      ...data[segmentIndex],\n                      count: cellCounts.get(segmentIndex) || 0,\n                    })\n            : undefined\n        }\n      />\n    );\n  });\n\n  const tooltipLabel =\n    getTooltipLabel && hoveredCell && withTooltip\n      ? getTooltipLabel(hoveredCell)\n      : hoveredCell?.name;\n\n  const legendItems = withLegend\n    ? data.map((segment, index) => {\n        const legendDimmed = hoveredLegendIndex != null && hoveredLegendIndex !== index;\n\n        return (\n          <div\n            key={segment.key ?? index}\n            {...getStyles('legendItem', {\n              style: legendDimmed ? { opacity: 0.4 } : undefined,\n            })}\n            onMouseEnter={() => setHoveredLegendIndex(index)}\n            onMouseLeave={() => setHoveredLegendIndex(null)}\n          >\n            <span\n              {...getStyles('legendSwatch', {\n                style: { backgroundColor: getThemeColor(segment.color, theme) },\n              })}\n            />\n            <span {...getStyles('legendLabel')}>{segment.name}</span>\n          </div>\n        );\n      })\n    : null;\n\n  const isVertical = legendPosition === 'left' || legendPosition === 'right';\n\n  // The cells carry no accessible information on their own, and the legend (when shown)\n  // exposes segment names but not their values – this gives assistive tech one readable\n  // summary of the data regardless of whether the legend is rendered. Values are reported\n  // as they are drawn, so a clamped negative or non-finite value is announced as 0.\n  const segmentsLabel = data\n    .map((segment) => `${segment.name}: ${normalizeSegmentValue(segment.value)}`)\n    .join(', ');\n\n  // The denominator is what makes the filled/empty split readable – without it a listener\n  // hears \"Completed: 68\" while a sighted user sees 68 of 100 cells filled.\n  const segmentsTotal = data.reduce(\n    (acc, segment) => acc + normalizeSegmentValue(segment.value),\n    0\n  );\n  const effectiveTotal = total != null ? Math.max(total, segmentsTotal) : segmentsTotal;\n  const gridLabel = segmentsLabel ? `${segmentsLabel} of ${effectiveTotal}` : '';\n\n  // A plain div has an implicit `generic` role, which cannot carry an accessible name, so\n  // a caller-supplied label would be dropped. Promoting the root to a group lets their\n  // label describe the chart while the grid keeps the generated data summary.\n  const hasCallerLabel =\n    others['aria-label'] !== undefined || others['aria-labelledby'] !== undefined;\n\n  const grid = (\n    <Box\n      component=\"svg\"\n      width={svgWidth}\n      height={svgHeight}\n      role={gridLabel ? 'img' : undefined}\n      aria-label={gridLabel || undefined}\n      {...getStyles('grid')}\n    >\n      <Tooltip.Floating label={tooltipLabel} disabled={!withTooltip || !hoveredCell} position=\"top\">\n        <g onMouseLeave={withTooltip ? () => setHoveredCell(null) : undefined}>\n          {withTooltip && <rect fill=\"transparent\" width={svgWidth} height={svgHeight} />}\n          {cellElements}\n        </g>\n      </Tooltip.Floating>\n    </Box>\n  );\n\n  return (\n    <Box\n      {...getStyles('root')}\n      variant={variant}\n      mod={{ 'legend-position': withLegend ? legendPosition : undefined, vertical: isVertical }}\n      role={hasCallerLabel ? 'group' : undefined}\n      {...others}\n    >\n      {withLegend && (legendPosition === 'top' || legendPosition === 'left') && (\n        <div {...getStyles('legend')} aria-hidden>\n          {legendItems}\n        </div>\n      )}\n      {grid}\n      {withLegend && (legendPosition === 'bottom' || legendPosition === 'right') && (\n        <div {...getStyles('legend')} aria-hidden>\n          {legendItems}\n        </div>\n      )}\n    </Box>\n  );\n});\n\nWaffleChart.displayName = '@mantine/charts/WaffleChart';\nWaffleChart.classes = classes;\nWaffleChart.varsResolver = varsResolver;\n"],"mappings":";;;;;;AA+FA,MAAM,eAAe;CACnB,MAAM;CACN,SAAS;CACT,KAAK;CACL,YAAY;CACZ,aAAa;CACb,YAAY;CACZ,gBAAgB;CAChB,eAAe;AACjB;AAEA,MAAM,eAAe,oBAClB,OAAO,EAAE,YAAY,kBAAkB,EACtC,MAAM;CACJ,wBAAwB,IAAI,UAAU;CACtC,wBAAwB,aAAa,cAAc,YAAY,KAAK,IAAI,KAAA;AAC1E,EACF,EACF;;;;;;;AAYA,SAAS,sBAAsB,OAAe;CAC5C,OAAO,OAAO,SAAS,KAAK,IAAI,KAAK,IAAI,GAAG,KAAK,IAAI;AACvD;AAEA,SAAS,cACP,MACA,WACA,YACiB;CACjB,MAAM,SAAS,KAAK,KAAK,MAAM,sBAAsB,EAAE,KAAK,CAAC;CAC7D,MAAM,MAAM,OAAO,QAAQ,KAAK,UAAU,MAAM,OAAO,CAAC;CAExD,IAAI,QAAQ,GACV,OAAO,MAAM,KAAK,EAAE,QAAQ,UAAU,UAAU,EAAE,cAAc,GAAG,EAAE;C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