# TreeMap

> Tree maps from @salmonui/charts/tree-map with grouped or hierarchical data, squarified and slice-and-dice layouts, headers, leaf labels, color scales, drill-down with breadcrumbs, selection and tree keyboard navigation.

Canonical: https://salmonui.dev/docs/data-visualization/tree-map

`TreeMap` lives in `@salmonui/charts/tree-map`. Flat records are grouped by
`levels: [{ groupBy }]`; hierarchical records use `childrenField`. Leaves
are weighted by `weightField`.

```tsx
import { TreeMap } from '@salmonui/charts/tree-map';
import '@salmonui/charts/tree-map/styles.css';

<TreeMap data={rows} weightField="cost" levels={[{ groupBy: 'dept' }]} leaves={{ labelField: 'team' }} height={380} />
```

### Live demo: Tree map with drill-down

Live demo: https://salmonui.dev/demos/data-visualization/tree-map-drill

A TreeMap of a budget grouped by department with headers, drill-down by click or Enter, breadcrumbs, item selection and an interactive legend.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { TreeMap, type TreeMapPath } from '@salmonui/charts/tree-map';

const budget = [
  { dept: 'Engineering', team: 'Platform', cost: 40 },
  { dept: 'Engineering', team: 'Apps', cost: 30 },
  { dept: 'Engineering', team: 'Data', cost: 20 },
  { dept: 'Sales', team: 'EMEA', cost: 25 },
  { dept: 'Sales', team: 'Americas', cost: 35 },
  { dept: 'Sales', team: 'APAC', cost: 15 },
  { dept: 'Support', team: 'Tier 1', cost: 12 },
  { dept: 'Support', team: 'Tier 2', cost: 8 },
];

export default function TreeMapDrillDemo() {
  const [path, setPath] = useState<TreeMapPath>([]);
  return (
    <div className="demo-stack">
      <TreeMap
        title="Budget by team"
        data={budget}
        weightField="cost"
        levels={[{ groupBy: 'dept', header: { format: (item) => `${item.label} (${item.value})` } }]}
        leaves={{ labelField: 'team', showValue: true, labelPosition: 'center', labelOverflow: 'wrapWord' }}
        path={path}
        onPathChange={setPath}
        breadcrumbs
        selection
        legend={{ mode: 'interactive' }}
        height={380}
      />
      <p className="demo-status" aria-live="polite">
        Path: <code>{path.join(' / ') || 'All'}</code>
      </p>
    </div>
  );
}
```

## Layout

`layout` is `'squarified'` (default), `'sliceHorizontal'`,
`'sliceVertical'` or `'sliceAuto'`; `direction` is `'topStart'`,
`'topEnd'`, `'bottomStart'` or `'bottomEnd'` (the drawing does not mirror
under `dir="rtl"`, like data axes; choose `topEnd` explicitly). Each level
takes `groupBy` (a field name or a function of the record), `gap` (px,
default 2) and `header` (`true` by default, `false` or `{ format, render,
align: 'start' | 'center' | 'end' }`).

`leaves: { labelField, format, labelPosition, labelOverflow, render, gap,
showValue }` (`gap` default 1 px; `format` is `Intl.NumberFormatOptions` or a
function of the value). `labelPosition` is one of nine positions (`'topStart'` ...
`'bottomEnd'`); `labelOverflow` is `'trim'` (ellipsis, default), `'hide'`,
`'wrapWord'` or `'wrap'`. `render(item)` lays HTML over the leaf.

## Colors

Top-level groups take the derived palette (or `palette` data colors);
`colorField` reads a data color per record, and `colorScale: { kind:
'range' | 'value' | 'opacity', field, stops }` maps a field by range start,
by exact value, or to opacity (desaturation: 30 % at the first stop value, full at the last).
`getItemStyle(item)` has the last word.

### Live demo: Portfolio colored by range, value and opacity

Live demo: https://salmonui.dev/demos/data-visualization/tree-map-portfolio

A TreeMap of holdings by sector that switches between palette, range, value and opacity color scales, with getItemStyle, hover highlight, a custom tooltip, item hover and click events and a root context-menu handler.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { TreeMap, type TreeMapColorScale, type TreeMapItem } from '@salmonui/charts/tree-map';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Select } from '@salmonui/dropdowns/select';

const holdings = [
  { sector: 'Technology', name: 'Northwind Systems', value: 42, change: 3.1, rating: 'Buy' },
  { sector: 'Technology', name: 'Contoso Cloud', value: 30, change: -1.4, rating: 'Hold' },
  { sector: 'Technology', name: 'Fabrikam Chips', value: 18, change: 5.2, rating: 'Buy' },
  { sector: 'Health', name: 'Adatum Bio', value: 22, change: -2.8, rating: 'Sell' },
  { sector: 'Health', name: 'Litware Clinics', value: 14, change: 0.6, rating: 'Hold' },
  { sector: 'Energy', name: 'Tailspin Solar', value: 16, change: 1.9, rating: 'Buy' },
  { sector: 'Energy', name: 'Proseware Grid', value: 11, change: -0.7, rating: 'Hold' },
  { sector: 'Cash', name: 'Money market', value: 9, change: 0, rating: 'Hold' },
];

type ScaleKind = 'group' | TreeMapColorScale['kind'];
const scales: Record<TreeMapColorScale['kind'], TreeMapColorScale> = {
  // Range starts: the highest stop the change reaches colors the tile.
  range: { kind: 'range', field: 'change', stops: [{ value: -10, color: '#dc2626' }, { value: -1, color: '#ef4444' }, { value: 1, color: '#16a34a' }, { value: 3, color: '#15803d' }] },
  value: { kind: 'value', field: 'rating', stops: [{ value: 'Buy', color: '#15803d' }, { value: 'Hold', color: '#a16207' }, { value: 'Sell', color: '#dc2626' }] },
  opacity: { kind: 'opacity', field: 'value', stops: [{ value: 9, color: '#1d4ed8' }, { value: 42, color: '#1d4ed8' }] },
};
const money = (v: number) => `$${v}k`;
const pct = (v: number) => `${v > 0 ? '+' : ''}${v.toFixed(1)}%`;
const fieldOf = (item: TreeMapItem, key: 'change' | 'rating') => (item.leaf ? (item.datum as (typeof holdings)[number])[key] : undefined);

/** A portfolio by sector: switch the color scale, hover, click and right-click tiles. */
export default function TreeMapPortfolioDemo() {
  const [kind, setKind] = useState<ScaleKind>('range');
  const [highlight, setHighlight] = useState(true);
  const [hovered, setHovered] = useState('none');
  const [clicked, setClicked] = useState('none');
  const [menu, setMenu] = useState(0);
  return (
    <div className="demo-stack">
      <div className="demo-toolbar" role="group" aria-label="Tree map options">
        <label>
          Color by
          <Select aria-label="Color by" data={[{ value: 'group', label: 'Sector (palette)' }, { value: 'range', label: 'Daily change (range)' }, { value: 'value', label: 'Analyst rating (value)' }, { value: 'opacity', label: 'Position size (opacity)' }]} value={kind} onValueChange={(value) => value != null && setKind(value as ScaleKind)} />
        </label>
        <Checkbox checked={highlight} onCheckedChange={(checked) => setHighlight(checked)}>
          Highlight on hover
        </Checkbox>
      </div>
      <TreeMap
        title="Portfolio"
        subtitle="Tile area is the position value"
        data={holdings}
        weightField="value"
        levels={[{ groupBy: 'sector' }]}
        leaves={{ labelField: 'name', showValue: true, format: money }}
        drill={false}
        palette={['#4f46e5', '#0891b2', '#b45309', '#6b7280']}
        colorScale={kind === 'group' ? undefined : scales[kind]}
        getItemStyle={(item) => (item.leaf && item.label === 'Money market' ? { color: '#6b7280' } : undefined)}
        highlight={highlight}
        tooltip={{
          render: (item) => {
            const change = fieldOf(item, 'change');
            return (
              <span>
                <strong>{item.label}</strong>: {money(item.value)}
                {typeof change === 'number' ? `, ${pct(change)} today, ${String(fieldOf(item, 'rating'))}` : ''}
              </span>
            );
          },
        }}
        onItemHover={(item) => setHovered(item ? item.path.join(' / ') : 'none')}
        onItemClick={(item) => setClicked(`${item.path.join(' / ')} (${money(item.value)})`)}
        onContextMenu={(e) => {
          e.preventDefault();
          setMenu((n) => n + 1);
        }}
        height={360}
      />
      <p className="demo-status" aria-live="polite">
        Hover: <code>{hovered}</code> · Click: <code>{clicked}</code> · Right-clicks: <code>{menu}</code>
      </p>
    </div>
  );
}
```

## Drill-down, selection, legend

With `drill="click"` (default) a click on a group, or Enter, drills in;
Backspace and Escape drill out; `drill={false}` turns drilling off. The path
(an array of group keys from the root) is the `path` / `defaultPath` /
`onPathChange(path, { source, reason })` triad: with `path` the drill is
controlled, so the application can persist it or veto it by not applying the
change; with `defaultPath` the component keeps it. `reason` is `'drill'`,
`'breadcrumb'` or `'keyboard'`. `breadcrumbs` renders a path navigation
(`nav` > `ol` with buttons and `aria-current`, the root labelled by
`rootLabel`, default "All"); `showParentLevels` keeps the ancestors as header
bands.

```tsx
import { useState } from 'react';
import { TreeMap, type TreeMapPath } from '@salmonui/charts/tree-map';

function Costs({ rows }: { rows: readonly { dept: string; team: string; cost: number }[] }) {
  const [path, setPath] = useState<TreeMapPath>([]);
  return (
    <TreeMap
      data={rows}
      weightField="cost"
      levels={[{ groupBy: 'dept' }]}
      leaves={{ labelField: 'team' }}
      path={path}
      onPathChange={setPath}
      breadcrumbs
      height={380}
    />
  );
}
```
 `selection` (`true`
or `{ mode: 'item' | 'group', multiple }`) uses `selectedItems` /
`defaultSelectedItems` / `onSelectedItemsChange`. `legend` lists the
top-level groups; `mode: 'interactive'` highlights a group on hover.
`highlight` (default `true`), `onItemHover(item | null)`,
`onItemClick(item, event)` and the tooltip (`tooltip: true` or
`{ render(item) }`) complete the interaction; items are `TreeMapItem`s
(`path`, `label`, `value`, `depth`, `leaf`, `datum`, `color`). The root
`<figure>` also takes `onClick`, `onDoubleClick`, `onContextMenu` and
`onPointerMove`.

## Keyboard and accessibility

APG Tree View semantics: one tab stop, arrows move across the siblings of
the drilled node, Home / End to the first and last sibling, Enter drills in
(or activates a leaf), Space selects, Backspace / Escape drill out (at the
root Escape closes the tooltip); the focused item is announced. The accessible
equivalent is a nested list of the hierarchy instead of a flat table.
`title`, `subtitle` and `description` label the figure.

## Server rendering and API

The layout is a pure function of `data` and the size, so the server renders
the final markup at `width` / `height` (including a controlled or default
`path`) and hydration matches; tooltips and hover are client only.
`animated` (default `true`) runs the transition after hydration with the
opt-in `@salmonui/charts/viz-animations.css` and is off under
`prefers-reduced-motion`. `onResize` reports size changes.

`ref` receives a `TreeMapApi`: `element`, `export(options)`, `toBlob`,
`toDataURL`, `toSVGString`, `print()` and `focus()`. Every prop and type is
in the [API reference](https://salmonui.dev/docs/reference/charts/tree-map).

Custom content uses render props (`leaves.render`, `header.render`,
`tooltip.render`, `getItemStyle`), not HTML string templates. `data` is a
plain array: load it through a `@salmonui/data` source or your own fetch.
Visual tokens are system-owned (see [Rendering and colors](https://salmonui.dev/docs/data-visualization/rendering-and-colors)).
