
### Basic Chart

```svelte
<script lang="ts">
	import { EvilPieChart } from '$lib/components/evilcharts/charts/layerchart-pie-chart/index.js';
	import { type ChartConfig } from '$lib/components/evilcharts/ui/layerchart-chart/index.js';

	const data = [
		{ browser: 'chrome', visitors: 275 },
		{ browser: 'safari', visitors: 200 },
		{ browser: 'firefox', visitors: 187 },
		{ browser: 'edge', visitors: 173 },
		{ browser: 'other', visitors: 90 }
	];

	const chartConfig = {
		chrome: {
			label: 'Chrome',
			colors: {
				light: ['#3b82f6'],
				dark: ['#60a5fa']
			}
		},
		safari: {
			label: 'Safari',
			colors: {
				light: ['#10b981'],
				dark: ['#34d399']
			}
		},
		firefox: {
			label: 'Firefox',
			colors: {
				light: ['#f59e0b'],
				dark: ['#fbbf24']
			}
		},
		edge: {
			label: 'Edge',
			colors: {
				light: ['#8b5cf6'],
				dark: ['#a78bfa']
			}
		},
		other: {
			label: 'Other',
			colors: {
				light: ['#6b7280'],
				dark: ['#9ca3af']
			}
		}
	} satisfies ChartConfig;
</script>

<EvilPieChart
	class="h-full w-full p-4"
	{data}
	dataKey="visitors"
	nameKey="browser"
	config={chartConfig}
>
	<EvilPieChart.Legend isClickable />
	<EvilPieChart.Tooltip />
	<EvilPieChart.Pie isClickable />
</EvilPieChart>
```

## Installation


  
  
    ### npm

```bash
npx shadcn-svelte@latest add @evilcharts/layerchart-pie-chart
```

### yarn

```bash
yarn dlx shadcn-svelte@latest add @evilcharts/layerchart-pie-chart
```

### bun

```bash
bunx --bun shadcn-svelte@latest add @evilcharts/layerchart-pie-chart
```

### pnpm

```bash
pnpm dlx shadcn-svelte@latest add @evilcharts/layerchart-pie-chart
```
  
  
    
      
        ### Install the following dependencies:
        
          ### npm

```bash
npm install layerchart
```

### yarn

```bash
yarn add layerchart
```

### bun

```bash
bun add layerchart
```

### pnpm

```bash
pnpm add layerchart
```
        
      
      
        ### Copy the following code into your project.
         

Create an `evilcharts` folder with a `charts` subfolder inside your `components` directory, then paste the base pie-chart code into a new file there.


        
          ### $lib/components/evilcharts/charts/layerchart-pie-chart

`$lib/components/evilcharts/charts/layerchart-pie-chart/background.svelte`

```svelte
<script lang="ts">
	/**
	 * An optional decorative pattern drawn behind the pie. Compose it before the <Pie /> so it
	 * sits underneath the sectors.
	 */
	import { ChartBackground, type BackgroundVariant } from '../../ui/layerchart-background/index.js';

	let { variant = 'dots' }: { variant?: BackgroundVariant } = $props();
</script>

<ChartBackground {variant} />
```

`$lib/components/evilcharts/charts/layerchart-pie-chart/defs/glow-filter.svelte`

```svelte
<script lang="ts">
	/** Soft outer-glow SVG filter, one per glowing sector. */
	let { id, glowingSectors }: { id: string; glowingSectors: string[] } = $props();
</script>

{#each glowingSectors as sectorName (sectorName)}
	<filter id={`${id}-glow-${sectorName}`} x="-100%" y="-100%" width="300%" height="300%">
		<feGaussianBlur in="SourceGraphic" stdDeviation="8" result="blur" />
		<feColorMatrix
			in="blur"
			type="matrix"
			values="1 0 0 0 0
                    0 1 0 0 0
                    0 0 1 0 0
                    0 0 0 0.5 0"
			result="glow"
		/>
		<feMerge>
			<feMergeNode in="glow" />
			<feMergeNode in="SourceGraphic" />
		</feMerge>
	</filter>
{/each}
```

`$lib/components/evilcharts/charts/layerchart-pie-chart/defs/radial-color-gradient.svelte`

```svelte
<script lang="ts">
	/**
	 * Radial-style colour gradients, one per sector. Each sector's fill paints from the gradient
	 * that matches its name, supporting both single and multi-colour config entries.
	 *
	 * The gradient runs corner to corner (`0,0 → 1,1`), which is what gives a single-colour sector
	 * its flat fill and a multi-colour sector its diagonal ramp.
	 */
	import { getColorsCount } from '../../../ui/layerchart-chart/colors.js';
	import type { ChartConfig } from '../../../ui/layerchart-chart/chart-config.js';

	// `variant` is accepted for parity with the reference, which threads it through but only ever
	// has the one value; the underscore marks it as deliberately unused.
	let {
		id,
		config,
		variant: _variant
	}: { id: string; config: ChartConfig; variant?: 'gradient' } = $props();

	const sectors = $derived(
		Object.entries(config).map(([sectorKey, sectorConfig]) => ({
			sectorKey,
			colorsCount: getColorsCount(sectorConfig)
		}))
	);
</script>

{#each sectors as { sectorKey, colorsCount } (sectorKey)}
	<linearGradient id={`${id}-colors-${sectorKey}`} x1="0" y1="0" x2="1" y2="1">
		{#if colorsCount === 1}
			<stop offset="0%" stop-color={`var(--color-${sectorKey}-0)`} />
			<stop offset="100%" stop-color={`var(--color-${sectorKey}-0)`} />
		{:else}
			{#each Array.from({ length: colorsCount }, (_, index) => `${(index / (colorsCount - 1)) * 100}%`) as offset, index (offset)}
				<stop
					{offset}
					stop-color={`var(--color-${sectorKey}-${index}, var(--color-${sectorKey}-0))`}
				/>
			{/each}
		{/if}
	</linearGradient>
{/each}
```

`$lib/components/evilcharts/charts/layerchart-pie-chart/index.ts`

```ts
import Root from './pie-chart.svelte';
import Pie from './pie.svelte';
import Label from './label.svelte';
import Tooltip from './tooltip.svelte';
import Legend from './legend.svelte';
import Background from './background.svelte';

type RootComponent = typeof Root;

// Compound API: every part hangs off the root as a static member, so a consumer
// writes <EvilPieChart.Pie/>, <EvilPieChart.Tooltip/>, … from a single import
// — no colliding named marker exports when several charts share one file.
//
// The explicit annotation is required for `svelte-package` to emit types.
export const EvilPieChart: RootComponent & {
	Pie: typeof Pie;
	Label: typeof Label;
	Tooltip: typeof Tooltip;
	Legend: typeof Legend;
	Background: typeof Background;
} = Object.assign(Root, {
	Pie,
	Label,
	Tooltip,
	Legend,
	Background
});

export type { PieVariant } from './types.js';
export type { ChartAccessibility, ChartConfig } from '../../ui/layerchart-chart/index.js';
export type { DitherBloom, DitherVariant, RenderStyle } from '../../ui/layerchart-dither/index.js';
```

`$lib/components/evilcharts/charts/layerchart-pie-chart/label.svelte`

```svelte
<script lang="ts">
	/**
	 * Declares per-sector labels for the <Pie /> it is composed inside. It renders nothing on its
	 * own — the parent <Pie /> reads its props and draws the label over each sector.
	 */
	import { usePieSlots } from './pie-slots.svelte.js';

	let {
		dataKey,
		labelListProps,
		labelProps
	}: {
		dataKey?: string; // data key for the label text — defaults to the pie's value key
		labelListProps?: Record<string, unknown>; // canonical escape hatch, matching the original API
		/** @deprecated Use `labelListProps`. */
		labelProps?: Record<string, unknown>; // escape hatch for raw label attributes
	} = $props();

	const forwardedLabelProps = $derived({ ...(labelProps ?? {}), ...(labelListProps ?? {}) });

	const slots = usePieSlots();
	const token = $props.id();

	$effect.pre(() => {
		slots.registerLabel(token, { dataKey, labelProps: forwardedLabelProps });
		return () => slots.unregisterLabel(token);
	});
</script>
```

`$lib/components/evilcharts/charts/layerchart-pie-chart/legend-render.svelte`

```svelte
<script lang="ts">
	/** Renders the registered `<Legend />` slot as an HTML box outside the plot area. */
	import {
		ChartLegendContent,
		resolveLegendPlacement,
		type LegendPayloadItem,
		type LegendVerticalAlign
	} from '../../ui/layerchart-legend/index.js';
	import { usePieChart } from './pie-chart-context.svelte.js';

	let { placement }: { placement: LegendVerticalAlign } = $props();

	const chart = usePieChart();

	const slot = $derived(chart.slots.legend);
	// Recharts defaults the pie legend to the bottom, unlike the cartesian charts.
	const resolvedPlacement = $derived(resolveLegendPlacement(slot?.verticalAlign, 'bottom'));

	/** One entry per sector, carrying the row so `nameKey` can resolve its config. */
	const payload = $derived<LegendPayloadItem[]>(
		chart.data.map((row) => ({ value: String(row[chart.nameKey]), payload: row }))
	);
</script>

{#if slot && !chart.isLoading && resolvedPlacement === placement}
	<ChartLegendContent
		{payload}
		nameKey={chart.nameKey}
		verticalAlign={slot.verticalAlign}
		align={slot.align}
		variant={slot.variant}
		isClickable={slot.isClickable}
		selected={chart.selectedSector}
		onSelectChange={chart.selectSector}
		class={placement === 'middle'
			? 'pointer-events-auto absolute inset-x-[5px] top-1/2 z-10 -translate-y-1/2'
			: 'mx-[5px]'}
	/>
{/if}
```

`$lib/components/evilcharts/charts/layerchart-pie-chart/legend.svelte`

```svelte
<script lang="ts">
	/**
	 * The sector legend. When `isClickable` is set, each entry toggles selection of its sector,
	 * driving the shared selection state read by the <Pie />.
	 *
	 * Config-only: the legend is an HTML box outside the SVG, so this registers its props and the
	 * root renders it above or below the plot per `verticalAlign`.
	 */
	import type {
		ChartLegendVariant,
		LegendAlign,
		LegendVerticalAlign
	} from '../../ui/layerchart-legend/index.js';
	import { usePieChart } from './pie-chart-context.svelte.js';

	let {
		variant,
		align = 'center',
		verticalAlign = 'bottom',
		isClickable = false
	}: {
		variant?: ChartLegendVariant; // visual style of the legend indicators
		align?: LegendAlign; // horizontal placement
		verticalAlign?: LegendVerticalAlign; // vertical placement
		isClickable?: boolean; // lets each entry toggle selection of its sector
	} = $props();

	const chart = usePieChart();
	const token = $props.id();

	$effect.pre(() => {
		chart.slots.registerLegend(token, { variant, align, verticalAlign, isClickable });
		return () => chart.slots.unregisterLegend(token);
	});
</script>
```

`$lib/components/evilcharts/charts/layerchart-pie-chart/loading/loading-sector.svelte`

```svelte
<script lang="ts">
	/**
	 * A single skeleton sector shown while the chart is loading. Each sector pulses with a
	 * staggered delay, producing a wave that travels around the pie.
	 */
	import { Arc } from 'layerchart';
	import { LOADING_ANIMATION_DURATION, LOADING_SECTORS } from '../types.js';

	let {
		index,
		startAngle,
		endAngle,
		innerRadius,
		outerRadius,
		cornerRadius
	}: {
		index: number;
		startAngle: number;
		endAngle: number;
		innerRadius: number | undefined;
		outerRadius: number | undefined;
		cornerRadius: number;
	} = $props();

	// Staggered delay so the pulse sweeps around the circle
	const delay = $derived((index / LOADING_SECTORS) * (LOADING_ANIMATION_DURATION / 1000));
</script>

<g
	class="loading-sector"
	style:--loading-duration={`${LOADING_ANIMATION_DURATION}ms`}
	style:--loading-delay={`${delay}s`}
>
	<Arc
		class="lc-pie-arc"
		{startAngle}
		{endAngle}
		{innerRadius}
		{outerRadius}
		{cornerRadius}
		fill="currentColor"
		strokeWidth={0}
		motion="none"
	/>
</g>

<style>
	.loading-sector {
		opacity: 0.15;
		animation: loading-sector-pulse var(--loading-duration) ease-in-out var(--loading-delay)
			infinite;
	}

	@keyframes loading-sector-pulse {
		50% {
			opacity: 0.5;
		}
	}

	@media (prefers-reduced-motion: reduce) {
		.loading-sector {
			opacity: 0.3;
			animation: none;
		}
	}
</style>
```

`$lib/components/evilcharts/charts/layerchart-pie-chart/pie-chart-context.svelte.ts`

```ts
import { getContext, setContext } from 'svelte';
import type { ChartConfig } from '../../ui/layerchart-chart/chart-config.js';
import type { DitherVariant, RenderStyle } from '../../ui/layerchart-dither/index.js';
import { ChartSlots } from '../../ui/layerchart-chart/chart-slots.svelte.js';

const PIE_CHART_KEY = Symbol('evilcharts.pie-chart');

type Options = {
	config: () => ChartConfig;
	/** Rows rendered by the chart. */
	data: () => Record<string, unknown>[];
	/** Key holding each sector's numeric value. */
	dataKey: () => string;
	/** Key holding each sector's name. */
	nameKey: () => string;
	isLoading: () => boolean;
	introStartedAt: () => number;
	renderStyle: () => RenderStyle;
	ditherVariant: () => DitherVariant;
	selectedSector: () => string | null;
	selectSector: (sectorName: string | null) => void;
};

/**
 * Shared state for every part of the chart. Lifted into <EvilPieChart /> so that
 * <Pie />, <Tooltip />, <Legend />, and friends can read it without prop drilling.
 * Sub-components are composed freely — the provider is the single source of truth.
 */
export class PieChartContext {
	#options: Options;

	/** Parts that render outside `<Svg>` — see `ChartSlots`. */
	slots = new ChartSlots();

	constructor(options: Options) {
		this.#options = options;
	}

	get config() {
		return this.#options.config();
	}
	get data() {
		return this.#options.data();
	}
	get dataKey() {
		return this.#options.dataKey();
	}
	get nameKey() {
		return this.#options.nameKey();
	}
	get isLoading() {
		return this.#options.isLoading();
	}
	get introStartedAt() {
		return this.#options.introStartedAt();
	}
	get renderStyle() {
		return this.#options.renderStyle();
	}
	get ditherVariant() {
		return this.#options.ditherVariant();
	}
	get selectedSector() {
		return this.#options.selectedSector();
	}

	selectSector = (sectorName: string | null) => {
		this.#options.selectSector(sectorName);
	};
}

export function setPieChartContext(options: Options) {
	const context = new PieChartContext(options);
	setContext(PIE_CHART_KEY, context);
	return context;
}

/** Reads the chart context, throwing a helpful error when used outside <EvilPieChart /> */
export function usePieChart(): PieChartContext {
	const context = getContext<PieChartContext | undefined>(PIE_CHART_KEY);

	if (!context) {
		throw new Error(
			'Pie chart parts (<Pie />, <Tooltip />, …) must be used within <EvilPieChart />'
		);
	}

	return context;
}
```

`$lib/components/evilcharts/charts/layerchart-pie-chart/pie-chart.svelte`

```svelte
<script lang="ts" generics="TData extends Record<string, unknown>">
	/**
	 * Root of the composable pie chart. Owns the data, the shared context, and the loading
	 * skeleton. Everything visual — the pie itself, tooltip, legend, and an optional background —
	 * is composed as children, so a consumer renders exactly the parts they need.
	 */
	import { Chart, Group, Html, Svg } from 'layerchart';
	import { untrack, type Snippet } from 'svelte';
	import {
		ChartContainer,
		LoadingIndicator,
		type ChartAccessibility,
		type ChartConfig
	} from '../../ui/layerchart-chart/index.js';
	import LegendRender from './legend-render.svelte';
	import { setPieChartContext } from './pie-chart-context.svelte.js';
	import {
		DitherDomLayer,
		type DitherBloom,
		type DitherVariant,
		type RenderStyle
	} from '../../ui/layerchart-dither/index.js';
	import TooltipRender from './tooltip-render.svelte';
	import { ANIMATION_BEGIN, ANIMATION_DURATION } from './types.js';

	let {
		config,
		data,
		dataKey,
		nameKey,
		children,
		class: className,
		chartProps,
		accessibility,
		defaultSelectedSector = null,
		onSelectionChange,
		isLoading = false,
		initialDimension = { width: 320, height: 200 },
		renderStyle = 'svg',
		ditherVariant = 'gradient',
		ditherCellSize = 2,
		bloom = 'off'
	}: {
		config: ChartConfig; // sector colors + labels
		data: TData[]; // rows rendered by the chart
		dataKey: keyof TData & string; // key holding each sector's numeric value
		nameKey: keyof TData & string; // key holding each sector's name
		children: Snippet; // composed parts — <Pie />, <Tooltip />, <Legend />, …
		class?: string; // extra classes for the chart container
		chartProps?: Record<string, unknown>; // escape hatch for the raw LayerChart Chart
		accessibility?: ChartAccessibility; // accessible name and description for the chart group
		defaultSelectedSector?: string | null; // sector selected on first render
		onSelectionChange?: (selection: { dataKey: string; value: number } | null) => void; // fires when the selected sector changes
		isLoading?: boolean; // shows the animated loading skeleton
		initialDimension?: { width: number; height: number }; // zero-size/first-render fallback
		renderStyle?: RenderStyle;
		ditherVariant?: DitherVariant;
		ditherCellSize?: number;
		bloom?: DitherBloom;
	} = $props();

	// One-time initialisation, mirroring the reference's `useState(defaultSelectedSector)`.
	let selectedSector = $state<string | null>(untrack(() => defaultSelectedSector));
	let chartDimension = $state(untrack(() => initialDimension));
	let introStartedAt = $state(Date.now());
	let previousLoading = untrack(() => isLoading);

	$effect(() => {
		const loadingNow = isLoading;
		if (previousLoading && !loadingNow) introStartedAt = Date.now();
		previousLoading = loadingNow;
	});

	const rows = $derived(data as Record<string, unknown>[]);

	/** Recharts' default `<PieChart margin>`, which is what its maximum radius measures against. */
	const CHART_MARGIN = 5;
	const EDGE_LEGEND_HEIGHT = 32;
	// An empty Recharts legend wrapper still reserves 24px while the loading pie is visible.
	const LOADING_EDGE_LEGEND_HEIGHT = 24;
	let pieContext: ReturnType<typeof setPieChartContext>;
	const edgeLegendPlacement = $derived.by(() => {
		if (!pieContext) return null;
		const align = pieContext.slots.legend?.verticalAlign;
		return align === 'top' || align === 'bottom' ? align : null;
	});
	const edgeLegendHeight = $derived(isLoading ? LOADING_EDGE_LEGEND_HEIGHT : EDGE_LEGEND_HEIGHT);
	const padding = $derived({
		top: CHART_MARGIN + (edgeLegendPlacement === 'top' ? edgeLegendHeight : 0),
		right: CHART_MARGIN,
		bottom: CHART_MARGIN + (edgeLegendPlacement === 'bottom' ? edgeLegendHeight : 0),
		left: CHART_MARGIN
	});

	pieContext = setPieChartContext({
		config: () => config,
		data: () => rows,
		dataKey: () => dataKey,
		nameKey: () => nameKey,
		isLoading: () => isLoading,
		introStartedAt: () => introStartedAt,
		renderStyle: () => renderStyle,
		ditherVariant: () => ditherVariant,
		selectedSector: () => selectedSector,
		selectSector: (sectorName) => {
			selectedSector = sectorName;

			if (sectorName === null) {
				onSelectionChange?.(null);
				return;
			}

			const selectedItem = rows.find((item) => item[nameKey] === sectorName);

			if (selectedItem) {
				onSelectionChange?.({ dataKey: sectorName, value: selectedItem[dataKey] as number });
			}
		}
	});
</script>

<ChartContainer
	{config}
	{initialDimension}
	{accessibility}
	bind:dimension={chartDimension}
	class={className}
>
	<LoadingIndicator {isLoading} />
	<LegendRender placement="top" />
	<Chart
		width={chartDimension.width}
		height={chartDimension.height}
		data={rows}
		x={dataKey}
		{padding}
		class="h-full w-full"
		{...chartProps}
	>
		{#if renderStyle === 'dither'}
			<Html pointerEvents={false} clip zIndex={0}>
				<DitherDomLayer
					{ditherVariant}
					cellSize={ditherCellSize}
					{bloom}
					paused={isLoading}
					animationDuration={ANIMATION_BEGIN + ANIMATION_DURATION}
					animationRevision={introStartedAt}
				/>
			</Html>
		{/if}
		<Svg zIndex={1}>
			<!--
				The pie is centred in the plot box, which is how Recharts places it: `cx`/`cy` both
				default to `"50%"`, and the sectors' radii are measured from there.
			-->
			<Group center>
				{@render children()}
			</Group>
		</Svg>
		<TooltipRender />
	</Chart>
	<LegendRender placement="middle" />
	<LegendRender placement="bottom" />
</ChartContainer>
```

`$lib/components/evilcharts/charts/layerchart-pie-chart/pie-slots.svelte.ts`

```ts
import { getContext, setContext } from 'svelte';

const PIE_SLOTS_KEY = Symbol('evilcharts.pie-slots');

export type LabelSlot = {
	/** Data key for the label text — defaults to the pie's value key. */
	dataKey?: string;
	/** Escape hatch for raw label props. */
	labelProps?: Record<string, unknown>;
};

/**
 * Registry for the `<Label />` child of one `<Pie />`.
 *
 * The reference resolves it with `React.Children.forEach`; Svelte cannot inspect a snippet, so
 * the slot registers itself here instead. Tokens prevent a remount's stale teardown from clearing
 * the live slot.
 */
export class PieSlots {
	#labelToken: string | null = null;

	label = $state<LabelSlot | null>(null);

	registerLabel(token: string, slot: LabelSlot) {
		this.#labelToken = token;
		this.label = slot;
	}

	unregisterLabel(token: string) {
		if (this.#labelToken !== token) return;
		this.#labelToken = null;
		this.label = null;
	}
}

export function setPieSlotsContext() {
	const slots = new PieSlots();
	setContext(PIE_SLOTS_KEY, slots);
	return slots;
}

export function usePieSlots(): PieSlots {
	const slots = getContext<PieSlots | undefined>(PIE_SLOTS_KEY);

	if (!slots) {
		throw new Error('<Label /> must be composed inside a <Pie />');
	}

	return slots;
}
```

`$lib/components/evilcharts/charts/layerchart-pie-chart/pie.svelte`

```svelte
<script lang="ts">
	/**
	 * The pie series. Self-contained: it generates its own radial colour gradients and glow
	 * filters under a unique id, so any number of pies — each with its own shape and
	 * clickability — can live on one page without style collisions. While the chart is loading it
	 * renders an animated skeleton in place of the data. Compose <Label /> inside it to draw
	 * labels on each sector.
	 */
	import { Arc, getChartContext } from 'layerchart';
	import { animate, useMotionValue, useReducedMotion } from '@humanspeak/svelte-motion';
	import type { DitherVariant } from '../../ui/layerchart-dither/index.js';
	import type { Snippet } from 'svelte';
	import ColorGradient from './defs/radial-color-gradient.svelte';
	import GlowFilter from './defs/glow-filter.svelte';
	import LoadingSector from './loading/loading-sector.svelte';
	import { usePieChart } from './pie-chart-context.svelte.js';
	import { setPieSlotsContext } from './pie-slots.svelte.js';
	import { getSectors, interpolateSectors, type PieSector } from './sectors.js';
	import { untrack } from 'svelte';
	import {
		ANIMATION_BEGIN,
		ANIMATION_DURATION,
		ANIMATION_EASE,
		DEFAULT_CORNER_RADIUS,
		DEFAULT_END_ANGLE,
		DEFAULT_INNER_RADIUS,
		DEFAULT_OUTER_RADIUS,
		DEFAULT_PADDING_ANGLE,
		DEFAULT_START_ANGLE,
		LOADING_PIE_DATA,
		polarToCartesian,
		resolveRadii,
		toArcAngle,
		toArcRadius,
		type PieVariant
	} from './types.js';

	let {
		variant = 'gradient',
		innerRadius = DEFAULT_INNER_RADIUS,
		outerRadius = DEFAULT_OUTER_RADIUS,
		cornerRadius = DEFAULT_CORNER_RADIUS,
		paddingAngle = DEFAULT_PADDING_ANGLE,
		startAngle = DEFAULT_START_ANGLE,
		endAngle = DEFAULT_END_ANGLE,
		isClickable = false,
		glowingSectors = [],
		children,
		pieProps,
		arcProps,
		ditherVariant
	}: {
		variant?: PieVariant; // fill style for the pie's sectors
		innerRadius?: number | string; // inner radius — set above 0 for a donut
		outerRadius?: number | string; // outer radius of the pie
		cornerRadius?: number; // border-radius of each sector in pixels
		paddingAngle?: number; // gap between sectors in degrees — negative overlaps them
		startAngle?: number; // angle the pie starts drawing from
		endAngle?: number; // angle the pie stops drawing at
		isClickable?: boolean; // lets sectors be selected by clicking them
		glowingSectors?: string[]; // sector names that render with a soft outer glow
		children?: Snippet; // optional <Label /> composition for sector labels
		pieProps?: Record<string, unknown>; // canonical escape hatch, matching the original EvilCharts API
		/** @deprecated Use `pieProps`. */
		arcProps?: Record<string, unknown>; // escape hatch for raw LayerChart Arc props
		ditherVariant?: DitherVariant; // ordered-dither texture override
	} = $props();

	const forwardedPieProps = $derived({ ...(arcProps ?? {}), ...(pieProps ?? {}) });

	const chart = usePieChart();
	/** LayerChart's own context, for the plot box the radii are measured against. */
	const layer = getChartContext();
	const id = $props.id(); // unique id scopes this pie's style defs

	const slots = setPieSlotsContext();
	const shouldReduceMotion = useReducedMotion();
	const isDither = $derived(chart.renderStyle === 'dither');
	const resolvedDitherVariant = $derived(ditherVariant ?? chart.ditherVariant);

	const resolvedInner = $derived(toArcRadius(innerRadius));
	const resolvedOuter = $derived(toArcRadius(outerRadius));

	/**
	 * The intro sweep, reproducing Recharts' own `<Pie>` animation: every sector grows to its
	 * final span together, so the pie unrolls from its start angle. Same begin, duration and
	 * easing curve as `<Pie animationBegin animationDuration animationEasing>`.
	 */
	const progress = useMotionValue(1);
	let sourceSectors = $state<PieSector[]>([]);
	let targetSectors = $state<PieSector[]>([]);
	let previousLoading: boolean | undefined;

	/**
	 * The skeleton's equal sectors, re-keyed onto the chart's own name/value keys so the same
	 * accessors work for both.
	 */
	const loadingRows = $derived(
		LOADING_PIE_DATA.map((row) => ({
			[chart.nameKey]: row.name,
			[chart.dataKey]: row.value
		}))
	);

	const resolvedSectors = $derived(
		getSectors({
			rows: chart.isLoading ? loadingRows : chart.data,
			dataKey: chart.dataKey,
			startAngle,
			endAngle,
			paddingAngle
		})
	);

	// Recharts animates every change to the pie's sector geometry, not only the first render. Keep
	// the currently painted sectors as the next animation's source so interrupted updates remain
	// continuous. `untrack` prevents per-frame motion-value reads from restarting the tween.
	$effect(() => {
		const loadingNow = chart.isLoading;
		const nextSectors = resolvedSectors;
		const reduceMotion = shouldReduceMotion.current;
		let controls: ReturnType<typeof animate> | undefined;

		untrack(() => {
			if (loadingNow) {
				sourceSectors = nextSectors;
				targetSectors = nextSectors;
				progress.set(1);
			} else {
				const entering = previousLoading === undefined || previousLoading;
				const currentSectors = entering
					? []
					: interpolateSectors(sourceSectors, targetSectors, progress.get());

				sourceSectors = currentSectors;
				targetSectors = nextSectors;

				if (reduceMotion) {
					progress.set(1);
				} else {
					progress.set(0);
					controls = animate(progress, 1, {
						delay: ANIMATION_BEGIN / 1000,
						duration: ANIMATION_DURATION / 1000,
						ease: ANIMATION_EASE
					});
				}
			}
			previousLoading = loadingNow;
		});

		return () => controls?.stop();
	});

	const rawSectors = $derived(
		chart.isLoading
			? resolvedSectors
			: interpolateSectors(sourceSectors, targetSectors, progress.current)
	);
	const isAnimating = $derived(
		!chart.isLoading && !shouldReduceMotion.current && progress.current < 1
	);

	/**
	 * Sectors with their name resolved.
	 *
	 * A declaration tag inside the keyed `{#each}` below would not re-derive when the row at an
	 * index changes, so the name — which drives the fill, the glow and the click target — is
	 * resolved here.
	 */
	const sectors = $derived(
		rawSectors.map((sector) => ({ ...sector, name: String(sector.row[chart.nameKey]) }))
	);

	/**
	 * A negative `paddingAngle` overlaps the sectors, so the reference separates them with a thick
	 * background-coloured outline instead of a gap.
	 */
	const overlapping = $derived(paddingAngle < 0);

	const label = $derived(slots.label);
	const labelKey = $derived(label?.dataKey ?? chart.dataKey);

	/**
	 * Label anchors, in the same pixel space as the arcs.
	 *
	 * Recharts' `<LabelList>` defaults a polar view box to `position="middle"`: the sector's
	 * mid-angle at `(innerRadius + outerRadius) / 2`. That is computed here rather than read from
	 * `<Arc>`'s `centroid` snippet parameter, which does not track the intro sweep — it stays at
	 * the angles the arc had on its first frame.
	 */
	const radii = $derived(
		resolveRadii(resolvedInner, resolvedOuter, Math.min(layer.width, layer.height) / 2)
	);
	const labelAnchors = $derived(
		sectors.map((sector) =>
			polarToCartesian((radii.inner + radii.outer) / 2, (sector.startAngle + sector.endAngle) / 2)
		)
	);

	function select(sectorName: string) {
		if (!isClickable) return;
		// Clicking the selected sector clears the selection, otherwise selects it
		chart.selectSector(chart.selectedSector === sectorName ? null : sectorName);
	}

	function selectFromKeyboard(event: KeyboardEvent, sectorName: string) {
		if (!isClickable || (event.key !== 'Enter' && event.key !== ' ')) return;
		event.preventDefault();
		select(sectorName);
	}
</script>

{@render children?.()}

{#if chart.isLoading}
	{#each sectors as sector (sector.index)}
		<LoadingSector
			index={sector.index}
			startAngle={toArcAngle(sector.startAngle)}
			endAngle={toArcAngle(sector.endAngle)}
			innerRadius={resolvedInner}
			outerRadius={resolvedOuter}
			{cornerRadius}
		/>
	{/each}
{:else}
	{#each sectors as sector (sector.index)}
		<Arc
			class={['lc-pie-arc transition-opacity duration-200', isClickable && 'cursor-pointer']
				.filter(Boolean)
				.join(' ')}
			data-evil-animation-state={isAnimating ? 'running' : 'idle'}
			startAngle={toArcAngle(sector.startAngle)}
			endAngle={toArcAngle(sector.endAngle)}
			innerRadius={resolvedInner}
			outerRadius={resolvedOuter}
			{cornerRadius}
			fill={isDither ? 'transparent' : `url(#${id}-colors-${sector.name})`}
			filter={glowingSectors.includes(sector.name) ? `url(#${id}-glow-${sector.name})` : undefined}
			stroke={overlapping ? 'var(--background)' : 'none'}
			strokeWidth={overlapping ? 5 : 0}
			opacity={isClickable && chart.selectedSector !== null && chart.selectedSector !== sector.name
				? 0.15
				: 1}
			data-evil-dither-mark={isDither ? 'fill' : undefined}
			data-evil-dither-key={isDither ? sector.name : undefined}
			data-evil-dither-variant={isDither ? resolvedDitherVariant : undefined}
			data-evil-dither-glow={isDither && glowingSectors.includes(sector.name) ? 'true' : undefined}
			data={sector.row}
			tooltip
			motion="none"
			role={isClickable ? 'button' : 'presentation'}
			tabindex={isClickable ? 0 : undefined}
			aria-label={isClickable
				? `${sector.name}: ${String(sector.row[chart.dataKey] ?? '')}`
				: undefined}
			aria-pressed={isClickable ? chart.selectedSector === sector.name : undefined}
			onkeydown={(event: KeyboardEvent) => selectFromKeyboard(event, sector.name)}
			onclick={() => select(sector.name)}
			{...forwardedPieProps}
		/>
	{/each}

	{#if label && !isAnimating}
		{#each sectors as sector, index (sector.index)}
			<!--
				`dy` matches the `0.355em` Recharts' `<Text>` emits for a single line with
				`verticalAnchor="middle"`; the rest of the attributes are the reference's
				`<LabelList>` defaults.
			-->
			<text
				x={labelAnchors[index][0]}
				y={labelAnchors[index][1]}
				dy="0.355em"
				text-anchor="middle"
				stroke="none"
				font-size={12}
				font-weight={500}
				fill="currentColor"
				class="fill-background"
				{...label.labelProps}
			>
				{sector.row[labelKey]}
			</text>
		{/each}
	{/if}

	<defs>
		<ColorGradient {id} config={chart.config} {variant} />
		{#if glowingSectors.length > 0}
			<GlowFilter {id} {glowingSectors} />
		{/if}
	</defs>
{/if}
```

`$lib/components/evilcharts/charts/layerchart-pie-chart/sectors.ts`

```ts
/**
 * Sector angles for a pie, ported from Recharts' own `getSectors` arithmetic.
 *
 * LayerChart draws arcs with d3-pie, whose `padAngle` widens each arc and then relies on d3-arc to
 * inset the gap back out. That differs from Recharts twice over: d3-arc insets *inside* the
 * sector's own span (so the first sector no longer starts exactly at `startAngle`), and it ignores
 * a negative pad entirely (so `paddingAngle={-25}` loses its overlap). Recharts instead divides
 * `360° − paddingAngle × n` between the sectors and steps the start angle by `paddingAngle`
 * between them, which is what these numbers reproduce.
 */

export type PieSector = {
	/** Recharts-space start angle, in degrees. */
	startAngle: number;
	/** Recharts-space end angle, in degrees. */
	endAngle: number;
	row: Record<string, unknown>;
	index: number;
};

/**
 * Interpolates the angular spans exactly as Recharts' animated pie does.
 *
 * Existing sectors grow or shrink from their currently painted span. A sector added at a new
 * index grows from zero. Target padding is applied between the interpolated spans rather than
 * interpolated itself, matching `SectorsWithAnimation` in Recharts.
 */
export function interpolateSectors(
	previous: PieSector[],
	target: PieSector[],
	progress: number
): PieSector[] {
	if (progress >= 1) return target;

	let currentAngle = target[0]?.startAngle ?? 0;

	return target.map((sector, index) => {
		const previousSector = previous[index];
		const previousSpan = previousSector ? previousSector.endAngle - previousSector.startAngle : 0;
		const targetSpan = sector.endAngle - sector.startAngle;
		const padding = index > 0 ? sector.startAngle - target[index - 1].endAngle : 0;
		const startAngle = currentAngle + padding;
		const endAngle = startAngle + previousSpan + (targetSpan - previousSpan) * progress;

		currentAngle = endAngle;
		return { ...sector, startAngle, endAngle };
	});
}

/** `sign × min(|end − start|, 360)`, as Recharts' `parseDeltaAngle` computes it. */
function parseDeltaAngle(startAngle: number, endAngle: number) {
	const sign = Math.sign(endAngle - startAngle) || 1;
	return sign * Math.min(Math.abs(endAngle - startAngle), 360);
}

export function getSectors({
	rows,
	dataKey,
	startAngle,
	endAngle,
	paddingAngle,
	minAngle = 0,
	progress = 1
}: {
	rows: Record<string, unknown>[];
	dataKey: string;
	startAngle: number;
	endAngle: number;
	paddingAngle: number;
	minAngle?: number;
	/**
	 * Intro progress, 0 → 1. Recharts scales every sector's span by it and lays the sectors
	 * end to end from the first one's start angle, so the pie unrolls as it grows.
	 */
	progress?: number;
}): PieSector[] {
	const valueOf = (row: Record<string, unknown>) => {
		const value = row[dataKey];
		return typeof value === 'number' && Number.isFinite(value) ? value : 0;
	};

	const deltaAngle = parseDeltaAngle(startAngle, endAngle);
	const absDeltaAngle = Math.abs(deltaAngle);
	const sign = Math.sign(deltaAngle) || 1;

	// A single sector has nothing to be padded against.
	const pad = rows.length <= 1 ? 0 : paddingAngle;
	const notZeroItemCount = rows.filter((row) => valueOf(row) !== 0).length;
	// A full turn pads after the last sector too, since it meets the first one again.
	const totalPaddingAngle = (absDeltaAngle >= 360 ? notZeroItemCount : notZeroItemCount - 1) * pad;
	const realTotalAngle = absDeltaAngle - notZeroItemCount * minAngle - totalPaddingAngle;

	const sum = rows.reduce((total, row) => total + valueOf(row), 0);
	if (sum <= 0) return [];

	let previousEnd = startAngle;

	return rows.map((row, index) => {
		const value = valueOf(row);
		const percent = value / sum;
		const sectorStart = index === 0 ? startAngle : previousEnd + sign * pad * (value !== 0 ? 1 : 0);
		const span = sign * ((value !== 0 ? minAngle : 0) + percent * realTotalAngle) * progress;
		const sectorEnd = sectorStart + span;

		previousEnd = sectorEnd;

		return { startAngle: sectorStart, endAngle: sectorEnd, row, index };
	});
}
```

`$lib/components/evilcharts/charts/layerchart-pie-chart/tooltip-render.svelte`

```svelte
<script lang="ts">
	/** Renders the registered `<Tooltip />` slot: the floating box, as a sibling of `<Svg>`. */
	import { getChartContext } from 'layerchart';
	import {
		ChartTooltip,
		ChartTooltipContent,
		type TooltipPayloadItem
	} from '../../ui/layerchart-tooltip/index.js';
	import { usePieChart } from './pie-chart-context.svelte.js';

	const chart = usePieChart();
	/** LayerChart's own context, to tell a hovered row from the `defaultIndex` one. */
	const layer = getChartContext();

	const slot = $derived(chart.slots.tooltip);

	/**
	 * Row shown when nothing is hovered — the reference's `defaultIndex`.
	 *
	 * LayerChart resolves its tooltip data as `dataProp ?? ctx.tooltip.data`, so passing `data`
	 * unconditionally pins the tooltip to that row forever: with `defaultIndex` set, hovering any
	 * other category still reported the default one. The hovered row therefore takes precedence
	 * here and `defaultRow` only fills in when nothing is hovered.
	 */
	const defaultRow = $derived(
		slot?.defaultIndex === undefined ? undefined : chart.data[slot.defaultIndex]
	);

	/**
	 * One payload entry for the hovered sector.
	 *
	 * Recharts hands the pie tooltip a single item whose `name` is the sector name and whose
	 * `payload` is the row, so `nameKey` can resolve the config entry from it.
	 */
	function toPayload(row: Record<string, unknown>): TooltipPayloadItem[] {
		return [
			{
				dataKey: chart.dataKey,
				name: String(row[chart.nameKey]),
				value: row[chart.dataKey] as number | string | null,
				payload: row
			}
		];
	}
</script>

{#if slot && !chart.isLoading}
	<ChartTooltip data={layer.tooltip.data ?? defaultRow}>
		{#snippet children({ data })}
			<!-- Read inline rather than through a `{const}`: a declaration tag in a snippet body does
			     not re-derive when the snippet's argument changes, which froze the tooltip on the
			     first sector it was shown for. -->
			<ChartTooltipContent
				active
				hideLabel
				payload={toPayload(data as Record<string, unknown>)}
				nameKey={chart.nameKey}
				roundness={slot.roundness}
				variant={slot.variant}
			/>
		{/snippet}
	</ChartTooltip>
{/if}
```

`$lib/components/evilcharts/charts/layerchart-pie-chart/tooltip.svelte`

```svelte
<script lang="ts">
	/**
	 * The hover tooltip. Hidden automatically while the chart is loading.
	 *
	 * Config-only: the tooltip box cannot render inside `<Svg>`, so this registers its props and
	 * the root renders it in the right place.
	 */
	import type { TooltipRoundness, TooltipVariant } from '../../ui/layerchart-tooltip/index.js';
	import { usePieChart } from './pie-chart-context.svelte.js';

	let {
		variant,
		roundness,
		defaultIndex
	}: {
		variant?: TooltipVariant; // visual style of the tooltip surface
		roundness?: TooltipRoundness; // border-radius of the tooltip
		defaultIndex?: number; // sector index shown by default with no hover
	} = $props();

	const chart = usePieChart();
	const token = $props.id();

	$effect.pre(() => {
		chart.slots.registerTooltip(token, { variant, roundness, defaultIndex, cursor: false });
		return () => chart.slots.unregisterTooltip(token);
	});
</script>
```

`$lib/components/evilcharts/charts/layerchart-pie-chart/types.ts`

```ts
// Constants
export const LOADING_SECTORS = 5;
export const LOADING_ANIMATION_DURATION = 2000; // full loading cycle duration in milliseconds
export const DEFAULT_INNER_RADIUS = 0;
export const DEFAULT_OUTER_RADIUS = '80%';
export const DEFAULT_CORNER_RADIUS = 0;
export const DEFAULT_PADDING_ANGLE = 0;
export const DEFAULT_START_ANGLE = 0;
export const DEFAULT_END_ANGLE = 360;
export const ANIMATION_BEGIN = 400; // Recharts' <Pie animationBegin>, in milliseconds
export const ANIMATION_DURATION = 1500; // Recharts' <Pie animationDuration>, in milliseconds
/** Recharts' `animationEasing: "ease"` — the CSS `ease` curve. */
export const ANIMATION_EASE: [number, number, number, number] = [0.25, 0.1, 0.25, 1];

/** Fill style for the pie's sectors — currently always a diagonal colour gradient. */
export type PieVariant = 'gradient';

/** Equal-sized sectors used to render the circular pulsing loading skeleton. */
export const LOADING_PIE_DATA = Array.from({ length: LOADING_SECTORS }, (_, i) => ({
	name: `loading${i}`,
	value: 100 / LOADING_SECTORS
}));

/**
 * Converts a Recharts polar angle to the equivalent d3-arc angle, in radians.
 *
 * Recharts measures degrees anticlockwise from 3 o'clock (`polarToCartesian` negates the angle
 * before taking its cosine and sine); d3-arc measures radians clockwise from 12 o'clock. Mapping
 * `θ → (90 − θ)` handles both differences at once, so a Recharts sweep of `0 → 360` becomes a
 * d3 sweep of `π/2 → −3π/2` — a full turn starting at 3 o'clock and running anticlockwise, which
 * is exactly what the reference draws.
 */
export const toArcAngle = (degrees: number) => ((90 - degrees) * Math.PI) / 180;

/**
 * Recharts' `polarToCartesian`, relative to the pie's centre.
 *
 * Degrees are measured anticlockwise from 3 o'clock, which is why the angle is negated before
 * the sine and cosine — copied straight from Recharts so labels land on the same pixels.
 */
export const polarToCartesian = (radius: number, degrees: number): [number, number] => {
	const radians = (-degrees * Math.PI) / 180;
	return [radius * Math.cos(radians), radius * Math.sin(radians)];
};

/**
 * Resolves the pie's radii to pixels, matching LayerChart's `Arc`.
 *
 * `Arc` reads a value above 1 as pixels, a fraction as a proportion of the chart radius, and a
 * negative value as an offset from it; `chartRadius` is half the smaller plot dimension, which is
 * also how Recharts derives its maximum radius. Recomputing it here lets a label be placed at
 * `(innerRadius + outerRadius) / 2` without depending on the arc element.
 */
export const resolveRadii = (
	innerRadius: number | undefined,
	outerRadius: number | undefined,
	chartRadius: number
) => {
	const outer = !outerRadius
		? chartRadius
		: outerRadius > 1
			? outerRadius
			: outerRadius > 0
				? chartRadius * outerRadius
				: chartRadius + outerRadius;

	const inner =
		innerRadius == null
			? 0
			: innerRadius > 1
				? innerRadius
				: innerRadius > 0
					? outer * innerRadius
					: innerRadius < 0
						? outer + innerRadius
						: 0;

	return { inner, outer };
};

/**
 * Resolves a Recharts radius to the number LayerChart's `Arc` expects.
 *
 * Recharts takes a pixel number or a `"80%"`-style string measured against the plot's maximum
 * radius; LayerChart reads a value above 1 as pixels and a fraction as a proportion of that same
 * maximum, so a percentage string only has to become its fraction.
 */
export const toArcRadius = (radius: number | string | undefined) => {
	if (radius === undefined) return undefined;
	if (typeof radius === 'number') return radius;

	const percent = radius.trim().endsWith('%') ? Number.parseFloat(radius) / 100 : Number(radius);
	return Number.isFinite(percent) ? percent : undefined;
};
```
        
      
       
        ### Add the chart component.
        

These components render the chart. Create a `ui` folder inside `evilcharts` and paste the code there.

Below is the main chart component.


        
          ### $lib/components/evilcharts/ui/layerchart-chart

`$lib/components/evilcharts/ui/layerchart-chart/accessibility.ts`

```ts
/**
 * Accessible name and description for a chart root.
 *
 * A chart may be named directly or by visible text elsewhere on the page. Descriptions can be
 * supplied directly, linked from existing content, or both. The container exposes this as a
 * `group`, rather than an image, so interactive legends and marks remain discoverable.
 */
type ChartAccessibleName =
	{ label: string; labelledBy?: never } | { label?: never; labelledBy: string };

export type ChartAccessibility = ChartAccessibleName & {
	description?: string;
	describedBy?: string;
};
```

`$lib/components/evilcharts/ui/layerchart-chart/animated-grow.svelte`

```svelte
<script lang="ts">
	import type { Snippet } from 'svelte';

	type GrowAnimation = {
		initial: { scaleX: number } | { scaleY: number };
		animate: { scaleX: number } | { scaleY: number };
		transition: {
			duration: number;
			delay: number;
			ease: number[];
		};
		style: { originX: number } | { originY: number };
	};

	let { animation, children }: { animation: GrowAnimation; children: Snippet } = $props();

	function runGrow(value: GrowAnimation) {
		return (node: SVGGElement) => {
			node.style.transformBox = 'fill-box';
			const options: KeyframeAnimationOptions = {
				duration: value.transition.duration * 1000,
				delay: value.transition.delay * 1000,
				easing: `cubic-bezier(${value.transition.ease.join(',')})`,
				fill: 'both'
			};

			if ('scaleX' in value.initial) {
				const to = 'scaleX' in value.animate ? value.animate.scaleX : 1;
				node.style.transformOrigin = '0% 50%';
				const animation = node.animate(
					[{ transform: `scaleX(${value.initial.scaleX})` }, { transform: `scaleX(${to})` }],
					options
				);
				return () => animation.cancel();
			}

			const to = 'scaleY' in value.animate ? value.animate.scaleY : 1;
			node.style.transformOrigin = '50% 100%';
			const animation = node.animate(
				[{ transform: `scaleY(${value.initial.scaleY})` }, { transform: `scaleY(${to})` }],
				options
			);
			return () => animation.cancel();
		};
	}
</script>

<g {@attach runGrow(animation)}>
	{@render children()}
</g>
```

`$lib/components/evilcharts/ui/layerchart-chart/bar-geometry.ts`

```ts
/**
 * Bar sizing and placement within a category, ported from Recharts' `getBarPositions`.
 *
 * LayerChart divides a band with a nested `scaleBand`, which cannot reproduce Recharts' numbers:
 * Recharts subtracts the category gap and the inter-bar gaps from the band, divides what is left
 * between the bars, and **floors the result to a whole pixel** — so a 49px band holding two bars
 * with `barCategoryGap="10%"` and `barGap={4}` yields bars of exactly 17px, not 17.6px. It also
 * supports a fixed `barSize`, which centres a group of that width in the band.
 *
 * The port therefore computes each bar's offset and width here and applies them as `insets` on
 * LayerChart's `<Bar>`, leaving the band itself undivided.
 */

/** Leading/trailing insets along one axis, as LayerChart's `<Bar insets>` takes them. */
export type BarInsets = { left?: number; right?: number; top?: number; bottom?: number };

export type BarSlot = {
	/** Distance from the band's leading edge to this bar's leading edge, in pixels. */
	offset: number;
	/** Width of this bar along the category axis, in pixels. */
	size: number;
};

/**
 * Recharts' `getPercentValue` for a gap: a `"10%"` string resolves against the band, a number is
 * taken as pixels, and the result is clamped into `[0, bandSize]`.
 */
function resolveGap(
	value: number | string | undefined,
	bandSize: number,
	fallback: number | string
) {
	const raw = value ?? fallback;
	const resolved =
		typeof raw === 'string' && raw.trim().endsWith('%')
			? (Number.parseFloat(raw) / 100) * bandSize
			: Number(raw);

	if (!Number.isFinite(resolved)) return 0;
	return Math.max(0, Math.min(resolved, bandSize));
}

export function getBarPositions({
	bandSize,
	count,
	barGap,
	barCategoryGap,
	barSize,
	maxBarSize
}: {
	/** The category band's full size along the category axis. */
	bandSize: number;
	/** How many bars share the category. Stacked series count as one. */
	count: number;
	/** Gap between bars sharing a category. Recharts' default is `4`. */
	barGap?: number | string;
	/** Gap on each side of the category. Recharts' default is `"10%"`. */
	barCategoryGap?: number | string;
	/** Fixed bar width. When set, the group is centred in the band at that width. */
	barSize?: number;
	/** Upper bound on the derived width. */
	maxBarSize?: number;
}): BarSlot[] {
	if (count < 1 || !(bandSize > 0)) return [];

	let realBarGap = resolveGap(barGap, bandSize, 4);

	if (barSize != null && Number.isFinite(barSize)) {
		let useFull = false;
		let fullBarSize = bandSize / count;
		let sum = count * barSize + (count - 1) * realBarGap;

		// Too wide to fit: first drop the gaps, then fall back to 90% of an even share.
		if (sum >= bandSize) {
			sum -= (count - 1) * realBarGap;
			realBarGap = 0;
		}
		if (sum >= bandSize && fullBarSize > 0) {
			useFull = true;
			fullBarSize *= 0.9;
			sum = count * fullBarSize;
		}

		// Recharts truncates the centring offset to a whole pixel (`>> 0`).
		const offset = Math.trunc((bandSize - sum) / 2);
		const size = useFull ? fullBarSize : barSize;

		return Array.from({ length: count }, (_, index) => ({
			offset: offset + (size + realBarGap) * index,
			size
		}));
	}

	const categoryOffset = resolveGap(barCategoryGap, bandSize, '10%');
	// No room left for gaps once the category inset is taken out.
	if (bandSize - 2 * categoryOffset - (count - 1) * realBarGap <= 0) realBarGap = 0;

	let originalSize = (bandSize - 2 * categoryOffset - (count - 1) * realBarGap) / count;
	// Recharts floors anything above a pixel (`>>= 0`), which is why bars land on whole pixels.
	if (originalSize > 1) originalSize = Math.trunc(originalSize);

	const size =
		maxBarSize != null && Number.isFinite(maxBarSize)
			? Math.min(originalSize, maxBarSize)
			: originalSize;

	// The stride uses the unclamped size, so `maxBarSize` narrows a bar in place rather than
	// re-packing the group — again matching Recharts.
	return Array.from({ length: count }, (_, index) => ({
		offset: categoryOffset + (originalSize + realBarGap) * index + (originalSize - size) / 2,
		size
	}));
}
```

`$lib/components/evilcharts/ui/layerchart-chart/chart-config.ts`

```ts
import type { Component, Snippet } from 'svelte';

// Format: { THEME_NAME: CSS_SELECTOR }
const THEMES = { light: '', dark: '.dark' } as const;

export type ThemeKey = keyof typeof THEMES;

// All Keys are optional at first
type ThemeColorsBase = {
	[K in ThemeKey]?: string[];
};

// Require at least one theme key
type AtLeastOneThemeColor = {
	[K in ThemeKey]: Required<Pick<ThemeColorsBase, K>> & Partial<Omit<ThemeColorsBase, K>>;
}[ThemeKey];

export const VALID_THEME_KEYS = Object.keys(THEMES) as ThemeKey[];

export { THEMES };

// Validation for chart config colors at runtime
export function validateChartConfigColors(config: ChartConfig): void {
	for (const [key, value] of Object.entries(config)) {
		if (value.colors) {
			const hasValidThemeKey = VALID_THEME_KEYS.some(
				(themeKey) => value.colors?.[themeKey] !== undefined
			);

			if (!hasValidThemeKey) {
				throw new Error(
					`[EvilCharts] Invalid chart config for "${key}": colors object must have at least one theme key (${VALID_THEME_KEYS.join(', ')}). Received empty object or invalid keys.`
				);
			}
		}
	}
}

export type ChartConfig = Record<
	string,
	{
		label?: string | Snippet;
		icon?: Component<Record<string, never>>;
		colors?: AtLeastOneThemeColor;
	}
>;

/** Validates that every config key also exists on the data row type. */
export type ValidateConfigKeys<TData, TConfig> = {
	[K in keyof TConfig]: K extends keyof TData ? ChartConfig[string] : never;
};
```

`$lib/components/evilcharts/ui/layerchart-chart/chart-container.svelte`

```svelte
<script lang="ts">
	import type { HTMLAttributes } from 'svelte/elements';
	import type { Snippet } from 'svelte';
	import { cn } from '$lib/utils.js';
	import { validateChartConfigColors, type ChartConfig } from './chart-config.js';
	import type { ChartAccessibility } from './accessibility.js';
	import { setChartContext } from './chart-context.svelte.js';
	import ChartStyle from './chart-style.svelte';

	type Props = Omit<HTMLAttributes<HTMLDivElement>, 'children'> & {
		config: ChartConfig;
		children?: Snippet;
		/** Size used before the container has been measured. */
		initialDimension?: { width: number; height: number };
		/** @internal Resolved fallback-or-measured size used by chart roots. */
		dimension?: { width: number; height: number };
		/** Optional content rendered below the chart (e.g. EvilBrush) */
		footer?: Snippet;
		/** Accessible name and optional description for the chart as an interactive group. */
		accessibility?: ChartAccessibility;
	};

	let {
		id,
		config,
		initialDimension = { width: 320, height: 200 },
		dimension = $bindable(),
		class: className,
		children,
		footer,
		accessibility,
		...restProps
	}: Props = $props();

	const uniqueId = $props.id();
	const chartId = $derived(`chart-${id ?? uniqueId}`);
	const descriptionId = $derived(`${chartId}-description`);
	const describedBy = $derived(
		[accessibility?.description ? descriptionId : undefined, accessibility?.describedBy]
			.filter(Boolean)
			.join(' ') || undefined
	);
	let measuredWidth = $state(0);
	let measuredHeight = $state(0);
	const resolvedDimension = $derived(
		measuredWidth > 0 && measuredHeight > 0
			? { width: measuredWidth, height: measuredHeight }
			: initialDimension
	);

	$effect(() => {
		dimension = resolvedDimension;
	});

	// Validate chart config at runtime
	$effect.pre(() => {
		validateChartConfigColors(config);
	});

	setChartContext({
		get config() {
			return config;
		},
		get chartId() {
			return chartId;
		},
		get initialDimension() {
			return resolvedDimension;
		}
	});
</script>

<div
	data-slot="chart"
	data-chart={chartId}
	role={accessibility ? 'group' : undefined}
	aria-label={accessibility?.label}
	aria-labelledby={accessibility?.labelledBy}
	aria-describedby={describedBy}
	class={cn(
		'min-h-0 w-full flex-1',
		// Reference equivalents, retargeted from Recharts' `.recharts-*` hooks onto
		// LayerChart's `.lc-*` hooks.
		/*
			The grid and rule overrides are gated on `:not([stroke])`, mirroring the reference's
			`[&_.recharts-cartesian-grid_line[stroke='#ccc']]` / `[&_.recharts-polar-grid_[stroke='#ccc']]`
			selectors: they restyle only marks still carrying the library's *default* stroke and leave
			an explicitly-set one alone. Without the gate they also repainted the radar's polar grid,
			which sets `stroke="currentColor"` itself, washing the web out to `border/50`.
		*/
		"relative flex flex-col justify-center text-xs [&_.lc-arc-track]:fill-muted [&_.lc-axis-label]:[stroke:none] [&_.lc-axis-label]:text-xs [&_.lc-axis-label]:font-normal [&_.lc-axis-tick-label]:fill-[#666] [&_.lc-axis-tick-label]:[stroke:none] [&_.lc-axis-tick-label]:text-xs [&_.lc-axis-tick-label]:font-normal [&_.lc-axis[data-evil-scale='point']_.lc-axis-tick-group:last-of-type_.lc-axis-tick-label]:translate-x-[5px] [&_.lc-axis[data-evil-scale='point']_.lc-axis-tick-group:last-of-type_.lc-axis-tick-label]:[text-anchor:end] [&_.lc-grid-x-line:not([stroke])]:stroke-border/50 [&_.lc-grid-x-radial-line:not([stroke])]:stroke-border [&_.lc-grid-y-line:not([stroke])]:stroke-border/50 [&_.lc-grid-y-radial-circle:not([stroke])]:stroke-border [&_.lc-highlight-bar]:fill-muted [&_.lc-highlight-line]:stroke-border [&_.lc-highlight-point[stroke='#fff']]:stroke-transparent [&_.lc-layer]:outline-hidden [&_.lc-layout-svg]:outline-hidden [&_.lc-pie-arc]:outline-hidden [&_.lc-pie-arc[stroke='#fff']]:stroke-transparent [&_.lc-rule-x-line:not([stroke])]:stroke-border [&_.lc-rule-y-line:not([stroke])]:stroke-border",
		!footer && 'aspect-video',
		className
	)}
	{...restProps}
>
	{#if accessibility?.description}
		<span id={descriptionId} class="sr-only">{accessibility.description}</span>
	{/if}
	<ChartStyle id={chartId} {config} />
	<div
		class="relative flex min-h-0 w-full flex-1 flex-col"
		bind:clientWidth={measuredWidth}
		bind:clientHeight={measuredHeight}
	>
		{@render children?.()}
	</div>
	{@render footer?.()}
</div>
```

`$lib/components/evilcharts/ui/layerchart-chart/chart-context.svelte.ts`

```ts
import { getContext, setContext } from 'svelte';
import type { ChartConfig } from './chart-config.js';

const CHART_CONTEXT_KEY = Symbol('evilcharts.chart');

export type ChartContextValue = {
	readonly config: ChartConfig;
	readonly chartId: string;
	/**
	 * Size the chart falls back to before its container has been measured — the reference
	 * passes this to Recharts' `<ResponsiveContainer initialDimension>`.
	 */
	readonly initialDimension: { width: number; height: number };
};

export function setChartContext(value: ChartContextValue) {
	setContext(CHART_CONTEXT_KEY, value);
	return value;
}

/**
 * Reads the container context, throwing a helpful error when used outside <ChartContainer />.
 */
export function useChart(): ChartContextValue {
	const context = getContext<ChartContextValue | undefined>(CHART_CONTEXT_KEY);

	if (!context) {
		throw new Error('useChart must be used within a <ChartContainer />');
	}

	return context;
}
```

`$lib/components/evilcharts/ui/layerchart-chart/chart-slots.svelte.ts`

```ts
export type TooltipSlot = {
	variant?: 'default' | 'frosted-glass';
	roundness?: 'sm' | 'md' | 'lg' | 'xl';
	defaultIndex?: number;
	cursor?: boolean;
};

export type LegendSlot = {
	variant?:
		| 'square'
		| 'circle'
		| 'circle-outline'
		| 'rounded-square'
		| 'rounded-square-outline'
		| 'vertical-bar'
		| 'horizontal-bar';
	align?: 'left' | 'center' | 'right';
	verticalAlign?: 'top' | 'middle' | 'bottom';
	isClickable?: boolean;
};

/**
 * Reactive registrations for chart parts that render outside the plot SVG.
 *
 * A chart child records its tooltip or legend props here, and the root renders the matching HTML
 * layer in the correct place. Registrations use per-instance tokens because a chart subtree can
 * remount before the previous instance finishes tearing down. A stale cleanup must not clear the
 * newer live registration.
 */
export class ChartSlots {
	#tooltipToken: string | null = null;
	#legendToken: string | null = null;

	tooltip = $state<TooltipSlot | null>(null);
	legend = $state<LegendSlot | null>(null);

	registerTooltip(token: string, slot: TooltipSlot) {
		this.#tooltipToken = token;
		this.tooltip = slot;
	}

	unregisterTooltip(token: string) {
		if (this.#tooltipToken !== token) return;
		this.#tooltipToken = null;
		this.tooltip = null;
	}

	registerLegend(token: string, slot: LegendSlot) {
		this.#legendToken = token;
		this.legend = slot;
	}

	unregisterLegend(token: string) {
		if (this.#legendToken !== token) return;
		this.#legendToken = null;
		this.legend = null;
	}
}
```

`$lib/components/evilcharts/ui/layerchart-chart/chart-style.svelte`

```svelte
<script lang="ts">
	import { THEMES, type ChartConfig, type ThemeKey } from './chart-config.js';
	import { distributeColors, getColorsCount } from './colors.js';

	let { id, config }: { id: string; config: ChartConfig } = $props();

	const colorConfig = $derived(
		Object.entries(config).filter(([, itemConfig]) => itemConfig.colors)
	);

	function generateCssVars(theme: ThemeKey) {
		return colorConfig
			.flatMap(([key, itemConfig]) => {
				const colorsArray = itemConfig.colors?.[theme];
				if (!colorsArray || !Array.isArray(colorsArray) || colorsArray.length === 0) {
					return [];
				}

				// Get max count across all themes for this key
				const maxCount = getColorsCount(itemConfig);

				// Distribute colors evenly across all required slots
				const distributedColors = distributeColors(colorsArray, maxCount);

				return distributedColors.map((color, index) => `  --color-${key}-${index}: ${color};`);
			})
			.filter(Boolean)
			.join('\n');
	}

	const css = $derived(
		Object.entries(THEMES)
			.map(
				([theme, prefix]) =>
					`${prefix} [data-chart=${id}] {\n${generateCssVars(theme as ThemeKey)}\n}`
			)
			.join('\n')
	);
</script>

{#if colorConfig.length}
	<!-- A plain <style> element in a Svelte template is scoped-compiled, so the tag is built
	     dynamically to emit global CSS — the equivalent of the reference's
	     `<style dangerouslySetInnerHTML>`. Building it as an element (rather than {@html})
	     means the CSS text can never be parsed as markup. -->
	<svelte:element this={"style"}>{css}</svelte:element>
{/if}
```

`$lib/components/evilcharts/ui/layerchart-chart/colors.ts`

```ts
import { VALID_THEME_KEYS, type ChartConfig } from './chart-config.js';

// Distribute colors evenly across slots, extra slots go to last color(s)
// Example: 2 colors for 4 slots → [red, red, pink, pink]
// Example: 3 colors for 4 slots → [red, pink, blue, blue]
export function distributeColors(colorsArray: string[], maxCount: number): string[] {
	const availableCount = colorsArray.length;
	if (availableCount >= maxCount) {
		return colorsArray.slice(0, maxCount);
	}

	const result: string[] = [];
	const baseSlots = Math.floor(maxCount / availableCount);
	const extraSlots = maxCount % availableCount;

	// First (availableCount - extraSlots) colors get baseSlots each
	// Last extraSlots colors get (baseSlots + 1) each
	for (let colorIdx = 0; colorIdx < availableCount; colorIdx++) {
		const isExtraColor = colorIdx >= availableCount - extraSlots;
		const slotsForThisColor = baseSlots + (isExtraColor ? 1 : 0);
		for (let j = 0; j < slotsForThisColor; j++) {
			result.push(colorsArray[colorIdx]);
		}
	}

	return result;
}

// Get max colors count across all themes for a config entry
export function getColorsCount(config: ChartConfig[string]): number {
	if (!config.colors) return 1;
	const counts = VALID_THEME_KEYS.map((theme) => config.colors?.[theme]?.length ?? 0);
	return Math.max(...counts, 1);
}
```

`$lib/components/evilcharts/ui/layerchart-chart/curves.ts`

```ts
import {
	curveBasis,
	curveBasisClosed,
	curveBasisOpen,
	curveBumpX,
	curveBumpY,
	curveLinear,
	curveLinearClosed,
	curveMonotoneX,
	curveMonotoneY,
	curveNatural,
	curveStep,
	curveStepAfter,
	curveStepBefore,
	type CurveFactory
} from 'd3-shape';

/**
 * The curve names Recharts accepts on `<Area type>` / `<Line type>`. Kept as the public
 * `curveType` union so every chart's API reads exactly as it does in the reference.
 */
export type CurveType =
	| 'basis'
	| 'basisClosed'
	| 'basisOpen'
	| 'bumpX'
	| 'bumpY'
	| 'bump'
	| 'linear'
	| 'linearClosed'
	| 'natural'
	| 'monotoneX'
	| 'monotoneY'
	| 'monotone'
	| 'step'
	| 'stepBefore'
	| 'stepAfter';

/**
 * Recharts resolves each `type` to the identically named d3-shape curve — `bump` and
 * `monotone` being the two aliases, which it maps to the X-oriented variants for the
 * default horizontal layout. LayerChart takes the d3 curve factory directly, so the
 * mapping is all that stands between the two APIs.
 */
const CURVES: Record<CurveType, CurveFactory> = {
	basis: curveBasis,
	basisClosed: curveBasisClosed as CurveFactory,
	basisOpen: curveBasisOpen as CurveFactory,
	bumpX: curveBumpX,
	bumpY: curveBumpY,
	bump: curveBumpX,
	linear: curveLinear,
	linearClosed: curveLinearClosed as CurveFactory,
	natural: curveNatural,
	monotoneX: curveMonotoneX,
	monotoneY: curveMonotoneY,
	monotone: curveMonotoneX,
	step: curveStep,
	stepBefore: curveStepBefore,
	stepAfter: curveStepAfter
};

/**
 * Resolve a Recharts `type` string to the d3-shape curve LayerChart marks expect.
 *
 * The three closed/open variants are line-only in d3's typings; they are cast to `CurveFactory`
 * because Recharts accepts them on `<Area type>` as well and behaves the same way — the closing
 * segment simply has no area counterpart.
 */
export function resolveCurve(type: CurveType | undefined): CurveFactory {
	return CURVES[type ?? 'linear'] ?? curveLinear;
}

export const CURVE_TYPES = Object.keys(CURVES) as CurveType[];
```

`$lib/components/evilcharts/ui/layerchart-chart/format.ts`

```ts
// Format values to percent for expanded charts
export function axisValueToPercentFormatter(value: number) {
	return `${Math.round(value * 100).toFixed(0)}%`;
}
```

`$lib/components/evilcharts/ui/layerchart-chart/index.ts`

```ts
export { default as ChartContainer } from './chart-container.svelte';
export { default as ChartStyle } from './chart-style.svelte';
export { default as LoadingIndicator } from './loading-indicator.svelte';
export type { ChartAccessibility } from './accessibility.js';

export {
	THEMES,
	VALID_THEME_KEYS,
	validateChartConfigColors,
	type ChartConfig,
	type ThemeKey,
	type ValidateConfigKeys
} from './chart-config.js';
export { setChartContext, useChart, type ChartContextValue } from './chart-context.svelte.js';
export { distributeColors, getColorsCount } from './colors.js';
export { getPayloadConfigFromPayload } from './payload.js';
export { axisValueToPercentFormatter } from './format.js';
export { getLoadingData, LOADING_CATEGORY_DATA_KEY } from './loading.js';
export { resolveCurve, CURVE_TYPES, type CurveType } from './curves.js';
export { getBarPositions, type BarSlot, type BarInsets } from './bar-geometry.js';
export { dropOverflowingLeadTick, rechartsValueAxisTicks, thinAxisTicks } from './ticks.js';
```

`$lib/components/evilcharts/ui/layerchart-chart/intros.ts`

```ts
export type IntroAction = 'reset' | 'animate' | 'finish' | 'none';

/** Decides how a polar mark responds to the chart loading lifecycle. */
export function polarIntroAction(
	wasLoading: boolean | undefined,
	isLoading: boolean,
	reduceMotion: boolean
): IntroAction {
	if (isLoading) return 'reset';
	if (reduceMotion) return 'finish';
	if (wasLoading === undefined || wasLoading) return 'animate';
	return 'none';
}

/**
 * Builds a one-shot wipe animation anchored to the chart root's mount timestamp.
 * Keyed LayerChart remounts therefore resume at elapsed progress and can never jump backwards.
 */
export function getRevealAnimation(
	durationSeconds: number,
	ease: [number, number, number, number],
	startedAt: number,
	now = Date.now()
) {
	const durationMs = durationSeconds * 1000;
	const elapsed = Math.max(0, now - startedAt);
	if (elapsed >= durationMs) return null;

	const progress = durationMs > 0 ? elapsed / durationMs : 1;
	return {
		initial: { scaleX: progress },
		animate: { scaleX: 1 },
		transition: {
			duration: Math.max(0, durationSeconds - elapsed / 1000),
			ease
		}
	};
}
```

`$lib/components/evilcharts/ui/layerchart-chart/loading-indicator.svelte`

```svelte
<script lang="ts">
	let { isLoading }: { isLoading: boolean } = $props();
</script>

{#if isLoading}
	<div class="pointer-events-none absolute inset-0 z-20 flex items-center justify-center">
		<div
			class="flex items-center justify-center gap-2 rounded-md border bg-background px-2 py-0.5 text-sm text-primary"
		>
			<div
				class="h-3 w-3 animate-spin rounded-full border border-border border-t-primary motion-reduce:animate-none"
			></div>
			<span>Loading</span>
		</div>
	</div>
{/if}
```

`$lib/components/evilcharts/ui/layerchart-chart/loading.ts`

```ts
// Generate random loading data for skeleton/loading state
// min/max represent percentage of the range (0-100), defaults to 20-80 for realistic look
/** Internal ordinal key that lets LayerChart spread generated loading rows across a category scale. */
export const LOADING_CATEGORY_DATA_KEY = '__loadingCategory';

export const getLoadingData = (points: number = 10, min: number = 0, max: number = 70) => {
	const range = max - min;
	return Array.from({ length: points }, (_, index) => ({
		[LOADING_CATEGORY_DATA_KEY]: index,
		loading: Math.floor(Math.random() * range) + min
	}));
};
```

`$lib/components/evilcharts/ui/layerchart-chart/payload.ts`

```ts
import type { ChartConfig } from './chart-config.js';

// Helper to extract item config from a payload.
export function getPayloadConfigFromPayload(config: ChartConfig, payload: unknown, key: string) {
	if (typeof payload !== 'object' || payload === null) {
		return undefined;
	}

	const payloadPayload =
		'payload' in payload && typeof payload.payload === 'object' && payload.payload !== null
			? payload.payload
			: undefined;

	let configLabelKey: string = key;

	if (key in payload && typeof payload[key as keyof typeof payload] === 'string') {
		configLabelKey = payload[key as keyof typeof payload] as string;
	} else if (
		payloadPayload &&
		key in payloadPayload &&
		typeof payloadPayload[key as keyof typeof payloadPayload] === 'string'
	) {
		configLabelKey = payloadPayload[key as keyof typeof payloadPayload] as string;
	}

	return configLabelKey in config ? config[configLabelKey] : config[key];
}
```

`$lib/components/evilcharts/ui/layerchart-chart/ticks.ts`

```ts
import type { AnyScale } from 'layerchart';

/** Converts LayerChart's x-axis tick origin to Recharts' `tickMargin` baseline. */
export const RECHARTS_X_AXIS_TICK_OFFSET = 5.5;

/**
 * Axis tick values with a leading tick dropped when its label cannot fit inside the plot.
 *
 * Recharts' `<XAxis>` runs `interval="preserveEnd"`: it keeps the last tick unconditionally and
 * discards any earlier one that will not fit. For a **point** scale with no outer padding that
 * always means the first tick — its label is centred on the plot's very left edge, so half of it
 * would spill outside. A **band** scale centres the label in the band instead, half a step in, so
 * nothing is dropped. LayerChart draws every tick it is given, so the same filter is applied here.
 *
 * Pass it straight to `<Axis ticks={dropOverflowingLeadTick}>`.
 */
export function dropOverflowingLeadTick(scale: AnyScale): unknown[] {
	const values = scale.domain() as unknown[];
	if (values.length < 2) return values;

	const range = scale.range() as number[];
	const start = Math.min(...range);

	// A band scale reports its band's leading edge, but the label sits at the band's centre.
	const bandOffset =
		typeof (scale as { bandwidth?: () => number }).bandwidth === 'function'
			? ((scale as { bandwidth: () => number }).bandwidth() ?? 0) / 2
			: 0;

	const first = (scale as (value: unknown) => number | undefined)(values[0]);
	if (typeof first !== 'number') return values;

	// Less than a pixel of room means the label is centred on the boundary itself.
	return first + bandOffset - start < 1 ? values.slice(1) : values;
}

/**
 * Axis tick values thinned so their labels do not collide, the way Recharts' `interval="preserveEnd"`
 * does: it keeps the last tick and walks backwards, dropping any tick whose label would come within
 * `minTickGap` of the one already kept. LayerChart's `tickSpacing` cannot do this — it only derives a
 * tick *count*, and it is disabled outright for band scales.
 *
 * Recharts measures real text; there is no rendered text to measure before the axis draws, so the
 * width is estimated from the label's length. `charWidth` defaults to a 12px monospace-ish advance,
 * which is what these axes use.
 *
 * Pass it to `<Axis ticks={…}>`; it also applies `dropOverflowingLeadTick`'s boundary rule.
 */
export function thinAxisTicks({
	format,
	minGap = 5,
	charWidth = 6.6,
	leadingInset = 0
}: {
	/** Renders a domain value the way the axis will, so its width can be estimated. */
	format: (value: unknown, index: number) => string;
	/** Recharts' `minTickGap`, which defaults to 5. */
	minGap?: number;
	/** Estimated advance per character, in pixels. */
	charWidth?: number;
	/** Space between the SVG edge and the scale range (for example a rendered Y axis). */
	leadingInset?: number;
}) {
	return (scale: AnyScale): unknown[] => {
		const domain = scale.domain() as unknown[];
		if (domain.length < 2) return domain;

		const bandOffset =
			typeof (scale as { bandwidth?: () => number }).bandwidth === 'function'
				? ((scale as { bandwidth: () => number }).bandwidth() ?? 0) / 2
				: 0;

		const centreOf = (value: unknown) =>
			Number((scale as (v: unknown) => number)(value)) + bandOffset;
		const halfWidthOf = (value: unknown) =>
			(format(
				value,
				domain.findIndex((candidate) => Object.is(candidate, value))
			).length *
				charWidth) /
			2;
		const range = scale.range() as number[];
		const endBoundary = Math.max(...range);

		// Recharts moves the final label just far enough inward for its trailing edge to stay inside
		// the axis view box. That shifted label then owns the collision boundary, which is why a
		// narrow Jan–Dec axis keeps Dec but drops Nov even though the unshifted labels would fit.
		const kept: unknown[] = [];
		let nextHeadEdge = Number.POSITIVE_INFINITY;

		for (let index = domain.length - 1; index >= 0; index -= 1) {
			const value = domain[index];
			const half = halfWidthOf(value);
			const centre = centreOf(value);

			// The first point-scale label may use space before the plot when a Y axis has reserved it.
			// Clip against the SVG's physical leading edge (0), not the scale range's first position.
			if (index === 0 && leadingInset + centre - half < 0) continue;

			const adjustedCentre =
				index === domain.length - 1 ? Math.min(centre, endBoundary - half) : centre;
			const tail = adjustedCentre + half;

			if (tail + minGap <= nextHeadEdge) {
				kept.push(value);
				nextHeadEdge = adjustedCentre - half;
			}
		}

		return kept.reverse();
	};
}

/**
 * Recharts' numeric axes default to five ticks and include both ends of the resolved domain.
 * D3's `scale.ticks(5)` instead chooses a rounded step and can omit the upper endpoint (for
 * example `[0, 500, 1000, 1500]` for a `[0, 1800]` domain), so LayerChart needs explicit values.
 */
export function rechartsValueAxisTicks(scale: AnyScale, count = 5): unknown[] {
	const domain = scale.domain() as unknown[];
	const start = Number(domain[0]);
	const end = Number(domain.at(-1));
	if (!Number.isFinite(start) || !Number.isFinite(end) || count < 2) return domain;

	const step = (end - start) / (count - 1);
	return Array.from({ length: count }, (_, index) =>
		Number((start + step * index).toPrecision(12))
	);
}

/** Recharts' hidden 6px tick length still contributes to an auto-sized Y-axis. */
export const RECHARTS_VALUE_AXIS_TICK_LENGTH = 6;

/**
 * Resolves Recharts' `width="auto"` gutter from already measured tick labels.
 *
 * Recharts rounds the widest label to the nearest pixel, then adds the configured tick margin and
 * the default 6px tick length (even when `tickLine={false}`). Keeping this as a pure helper makes
 * the browser-only canvas measurement easy to test independently.
 */
export function rechartsAutoYAxisWidth(
	labelWidths: number[],
	tickMargin = 8,
	tickLength = RECHARTS_VALUE_AXIS_TICK_LENGTH
): number {
	return Math.round(Math.max(0, ...labelWidths) + tickMargin + tickLength);
}

/** Measures value-axis labels in the same 12px inherited font used by the chart container. */
export function measureRechartsYAxisWidth(labels: string[], tickMargin = 8): number {
	if (typeof document === 'undefined') return 42;

	const canvas = document.createElement('canvas');
	const context = canvas.getContext('2d');
	if (!context) return 42;

	const family = getComputedStyle(document.body).fontFamily;
	context.font = `400 12px ${family}`;
	return rechartsAutoYAxisWidth(
		labels.map((label) => context.measureText(label).width),
		tickMargin
	);
}

/**
 * Keeps the second argument that LayerChart supplies to format functions at runtime.
 *
 * Its public `FormatType` currently describes a single-argument callback even though Axis invokes
 * it as `format(tick, index)`. Recharts exposes that index, so this adapter keeps the runtime value
 * while remaining assignable to LayerChart's narrower callback type.
 */
export function layerChartFormatter(
	formatter: (value: unknown, index: number) => string
): (value: unknown, index?: number) => string {
	return (value, index = 0) => formatter(value, index);
}
```
        
      
       
        ### Add the sub-components.
        

Create `tooltip.svelte` inside `evilcharts/ui` and paste the code there.


        
          ### $lib/components/evilcharts/ui/layerchart-tooltip

`$lib/components/evilcharts/ui/layerchart-tooltip/index.ts`

```ts
export { default as ChartTooltip } from './tooltip.svelte';
export { default as ChartTooltipContent } from './tooltip-content.svelte';
export { getIndicatorColorStyle, roundnessMap, variantMap } from './styles.js';
export type {
	TooltipIndicator,
	TooltipPayloadItem,
	TooltipRoundness,
	TooltipVariant
} from './types.js';
```

`$lib/components/evilcharts/ui/layerchart-tooltip/styles.ts`

```ts
import { getColorsCount } from '../layerchart-chart/colors.js';
import type { ChartConfig } from '../layerchart-chart/chart-config.js';
import type { TooltipRoundness, TooltipVariant } from './types.js';

export const roundnessMap: Record<TooltipRoundness, string> = {
	sm: 'rounded-sm',
	md: 'rounded-md',
	lg: 'rounded-lg',
	xl: 'rounded-xl'
};

export const variantMap: Record<TooltipVariant, string> = {
	default: 'bg-background',
	'frosted-glass': 'bg-background/70 backdrop-blur-sm'
};

export function getIndicatorColorStyle(dataKey: string, colorsCount: number): string {
	if (colorsCount <= 1) {
		return `background: var(--color-${dataKey}-0)`;
	}

	// Multiple colors: create linear gradient with evenly distributed stops
	const stops = Array.from({ length: colorsCount }, (_, index) => {
		const offset = (index / (colorsCount - 1)) * 100;
		return `var(--color-${dataKey}-${index}) ${offset}%`;
	}).join(', ');

	return `background: linear-gradient(to right, ${stops})`;
}

export function colorsCountFor(itemConfig: ChartConfig[string] | undefined): number {
	return itemConfig ? getColorsCount(itemConfig) : 1;
}
```

`$lib/components/evilcharts/ui/layerchart-tooltip/tooltip-content.svelte`

```svelte
<script lang="ts">
	import type { Snippet } from 'svelte';
	import { cn } from '$lib/utils.js';
	import { getPayloadConfigFromPayload } from '../layerchart-chart/payload.js';
	import { useChart } from '../layerchart-chart/chart-context.svelte.js';
	import { colorsCountFor, getIndicatorColorStyle, roundnessMap, variantMap } from './styles.js';
	import type { ChartConfig } from '../layerchart-chart/chart-config.js';
	import type {
		TooltipIndicator,
		TooltipPayloadItem,
		TooltipRoundness,
		TooltipVariant
	} from './types.js';

	type Props = {
		active?: boolean;
		payload?: TooltipPayloadItem[];
		class?: string;
		indicator?: TooltipIndicator;
		hideLabel?: boolean;
		hideIndicator?: boolean;
		label?: unknown;
		labelFormatter?: Snippet<[unknown, TooltipPayloadItem[]]>;
		labelClassName?: string;
		formatter?: Snippet<[TooltipPayloadItem['value'], string, TooltipPayloadItem, number, unknown]>;
		nameKey?: string;
		labelKey?: string;
		selected?: string | null;
		roundness?: TooltipRoundness;
		variant?: TooltipVariant;
	};

	let {
		active,
		payload,
		class: className,
		indicator = 'dot',
		hideLabel = false,
		hideIndicator = false,
		label,
		labelFormatter,
		labelClassName,
		formatter,
		nameKey,
		labelKey,
		selected,
		roundness = 'lg',
		variant = 'default'
	}: Props = $props();

	const { config } = $derived(useChart());

	const labelValue = $derived.by(() => {
		if (hideLabel || !payload?.length) {
			return null;
		}

		const [item] = payload;
		const key = `${labelKey ?? item?.dataKey ?? item?.name ?? 'value'}`;
		const itemConfig = getPayloadConfigFromPayload(config, item, key);

		return !labelKey && typeof label === 'string'
			? (config[label]?.label ?? label)
			: itemConfig?.label;
	});

	const nestLabel = $derived(payload?.length === 1 && indicator !== 'dot');

	type Row = {
		item: TooltipPayloadItem;
		index: number;
		key: string;
		itemConfig: ChartConfig[string] | undefined;
		colorsCount: number;
		isDimmed: boolean;
		/** Resolved before rendering so changes to the row re-derive it. */
		icon: ChartConfig[string]['icon'];
	};

	/**
	 * Fully resolved rows.
	 *
	 * Derived as one list rather than with in-markup declarations so a later `selected` change
	 * re-derives every row — the reference recomputes these inline on each React render.
	 */
	const rows = $derived<Row[]>(
		(payload ?? [])
			.filter((item) => item.type !== 'none')
			.map((item, index) => {
				// For pie charts, item.name contains the sector name (e.g., "chrome")
				// For radial charts, the name is in item.payload[nameKey]
				// For other charts, item.name or item.dataKey contains the series name
				const payloadName =
					nameKey && item.payload ? (item.payload as Record<string, unknown>)[nameKey] : undefined;
				const key = `${payloadName ?? item.name ?? item.dataKey ?? 'value'}`;
				const itemConfig = getPayloadConfigFromPayload(config, item, key);

				return {
					item,
					index,
					key,
					itemConfig,
					// Get colors count for this item to determine gradient vs solid
					colorsCount: colorsCountFor(itemConfig),
					isDimmed: selected != null && selected !== item.dataKey,
					icon: itemConfig?.icon
				};
			})
	);
</script>

{#snippet tooltipLabel()}
	{#if !hideLabel && payload?.length}
		{#if labelFormatter}
			<div class={cn('font-medium', labelClassName)}>
				{@render labelFormatter(labelValue, payload)}
			</div>
		{:else if labelValue}
			<div class={cn('font-medium', labelClassName)}>
				{#if typeof labelValue === 'string'}{labelValue}{:else}{@render labelValue()}{/if}
			</div>
		{/if}
	{/if}
{/snippet}

{#if !active || !payload?.length}
	<!-- Empty tooltip - to prevent position getting 0.0 so it doesnt animate tooltip every time from 0.0 origin -->
	<span class="p-4"></span>
{:else}
	<div
		class={cn(
			'grid min-w-32 items-start gap-1.5 border border-border/50 px-2.5 py-1.5 text-xs shadow-xl',
			roundnessMap[roundness],
			variantMap[variant],
			className
		)}
	>
		{#if !nestLabel}{@render tooltipLabel()}{/if}
		<div class="grid gap-1.5">
			{#each rows as row (row.index)}
				<div
					class={cn(
						'flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground',
						indicator === 'dot' && 'items-center',
						row.isDimmed && 'opacity-30'
					)}
				>
					{#if formatter && row.item?.value !== undefined && row.item.name}
						{@render formatter(
							row.item.value,
							row.item.name,
							row.item,
							row.index,
							row.item.payload
						)}
					{:else}
						{#if row.icon}
							{const Icon = row.icon}
							<Icon />
						{:else if !hideIndicator}
							<div
								class={cn('shrink-0 rounded-[2px]', {
									'h-2.5 w-2.5': indicator === 'dot',
									'w-1': indicator === 'line',
									'w-0 border-[1.5px] border-dashed bg-transparent!': indicator === 'dashed',
									'my-0.5': nestLabel && indicator === 'dashed'
								})}
								style={getIndicatorColorStyle(row.key, row.colorsCount)}
							></div>
						{/if}
						<div
							class={cn(
								'flex flex-1 justify-between gap-4 leading-none',
								nestLabel ? 'items-end' : 'items-center'
							)}
						>
							<div class="grid gap-1.5">
								{#if nestLabel}{@render tooltipLabel()}{/if}
								<span class="text-muted-foreground">
									{#if row.itemConfig?.label}
										{#if typeof row.itemConfig.label === 'string'}
											{row.itemConfig.label}
										{:else}
											{@render row.itemConfig.label()}
										{/if}
									{:else}
										{row.item.name}
									{/if}
								</span>
							</div>
							{#if row.item.value != null}
								<span class="font-mono font-medium text-foreground tabular-nums">
									{typeof row.item.value === 'number'
										? row.item.value.toLocaleString()
										: String(row.item.value)}
								</span>
							{/if}
						</div>
					{/if}
				</div>
			{/each}
		</div>
	</div>
{/if}
```

`$lib/components/evilcharts/ui/layerchart-tooltip/tooltip.svelte`

```svelte
<script lang="ts">
	import { Tooltip } from 'layerchart';
	import type { ComponentProps, Snippet } from 'svelte';
	import { useChart } from '../layerchart-chart/index.js';

	type Props = Omit<ComponentProps<typeof Tooltip.Root>, 'children' | 'variant'> & {
		children: Snippet<[{ data: unknown }]>;
	};

	let { children: content, props, ...restProps }: Props = $props();

	const { chartId } = useChart();
</script>

<!-- `variant="none"` drops LayerChart's own tooltip chrome so <ChartTooltipContent> owns the
     entire look, matching the reference where Recharts' `<Tooltip content>` replaces the
     default box. Position motion is left at LayerChart's default spring.

     LayerChart's default body portal escapes overflow boundaries. Repeating the chart's
     `data-chart` value on the portaled root keeps the scoped `--color-*` variables available. -->
<Tooltip.Root
	variant="none"
	{...restProps}
	props={{ ...props, root: { ...props?.root, 'data-chart': chartId } }}
>
	{#snippet children({ data })}
		{@render content({ data })}
	{/snippet}
</Tooltip.Root>
```

`$lib/components/evilcharts/ui/layerchart-tooltip/types.ts`

```ts
export type TooltipRoundness = 'sm' | 'md' | 'lg' | 'xl';
export type TooltipVariant = 'default' | 'frosted-glass';

export type TooltipIndicator = 'line' | 'dot' | 'dashed';

/**
 * One row of tooltip data.
 *
 * Mirrors the shape Recharts hands `<Tooltip content>` in the reference, so the content
 * component stays renderer-agnostic exactly as the reference's is. Each chart's `Tooltip`
 * part builds this list from LayerChart's `TooltipContext`.
 */
export type TooltipPayloadItem = {
	dataKey?: string;
	name?: string;
	value?: number | string | null;
	payload?: unknown;
	/** Rows with `type: 'none'` are hidden, as in Recharts. */
	type?: string;
	color?: string;
};
```
        
        

Then create `legend.svelte` in the same folder and paste the code there.


        
          ### $lib/components/evilcharts/ui/layerchart-legend

`$lib/components/evilcharts/ui/layerchart-legend/index.ts`

```ts
export { default as ChartLegendContent } from './legend-content.svelte';
export { default as LegendIndicator } from './legend-indicator.svelte';
export { getLegendFillStyle, getLegendOutlineStyle } from './styles.js';
export { resolveLegendPlacement } from './types.js';
export type {
	ChartLegendVariant,
	LegendAlign,
	LegendPayloadItem,
	LegendVerticalAlign
} from './types.js';
```

`$lib/components/evilcharts/ui/layerchart-legend/legend-content.svelte`

```svelte
<script lang="ts">
	import { cn } from '$lib/utils.js';
	import { getColorsCount } from '../layerchart-chart/colors.js';
	import { getPayloadConfigFromPayload } from '../layerchart-chart/payload.js';
	import { useChart } from '../layerchart-chart/chart-context.svelte.js';
	import LegendIndicator from './legend-indicator.svelte';
	import type { ChartConfig } from '../layerchart-chart/chart-config.js';
	import type {
		ChartLegendVariant,
		LegendAlign,
		LegendPayloadItem,
		LegendVerticalAlign
	} from './types.js';

	type Props = {
		class?: string;
		hideIcon?: boolean;
		nameKey?: string;
		payload?: LegendPayloadItem[];
		verticalAlign?: LegendVerticalAlign;
		align?: LegendAlign;
		selected?: string | null;
		isClickable?: boolean;
		onSelectChange?: (selected: string | null) => void;
		variant?: ChartLegendVariant;
	};

	let {
		class: className,
		hideIcon = false,
		nameKey,
		payload,
		verticalAlign,
		align = 'right',
		selected,
		isClickable,
		onSelectChange,
		variant = 'rounded-square'
	}: Props = $props();

	const { config } = $derived(useChart());

	type Entry = {
		key: string;
		itemConfig: ChartConfig[string] | undefined;
		colorsCount: number;
		isSelected: boolean;
		/** Resolved before rendering so changes to the entry re-derive it. */
		icon: ChartConfig[string]['icon'];
	};

	/**
	 * Fully resolved entries.
	 *
	 * Everything each row needs is derived here rather than with in-markup declarations, so a later
	 * `selected` change re-derives the whole list — the reference recomputes these inline on every
	 * React render.
	 */
	/**
	 * Recharts' `<Legend>` defaults to `itemSorter="value"`, so its entries come out ordered by
	 * series name rather than in config order — a composed chart of `revenue` + `profit` lists
	 * "Profit" first, and a pie of browsers lists them alphabetically. The comparison matches
	 * lodash's `compareAscending`, which is what `sortBy` uses: plain `<` on the raw value, with
	 * anything missing sorted last. (Its `<Tooltip itemSorter>` only reaches the *default* tooltip
	 * content, so tooltip rows stay in data order — the reference behaves the same way.)
	 */
	function byValueAscending(a: LegendPayloadItem, b: LegendPayloadItem) {
		const left = a.value;
		const right = b.value;
		if (left === right) return 0;
		if (left === undefined) return 1;
		if (right === undefined) return -1;
		return left < right ? -1 : 1;
	}

	const entries = $derived<Entry[]>(
		(payload ?? [])
			.filter((item) => item.type !== 'none')
			.toSorted(byValueAscending)
			.map((item) => {
				// For pie charts, item.value contains the sector name (e.g., "chrome")
				// For radial charts, the name is in item.payload[nameKey]
				// For other charts, item.dataKey contains the series name (e.g., "desktop")
				const payloadName =
					nameKey && item.payload ? (item.payload as Record<string, unknown>)[nameKey] : undefined;
				const key = `${payloadName ?? item.value ?? item.dataKey ?? 'value'}`;
				const itemConfig = getPayloadConfigFromPayload(config, item, key);

				return {
					key,
					itemConfig,
					// Get colors count for this item to determine gradient vs solid
					colorsCount: itemConfig ? getColorsCount(itemConfig) : 1,
					isSelected: selected === null || selected === undefined || selected === key,
					icon: itemConfig?.icon
				};
			})
	);

	function entryClass(isSelected: boolean) {
		return cn(
			'[&>svg]:text-muted-foreground flex items-center gap-1.5 transition-opacity [&>svg]:h-3 [&>svg]:w-3',
			!isSelected && 'opacity-30',
			isClickable && 'cursor-pointer'
		);
	}

	function select(key: string) {
		if (!isClickable) return;

		onSelectChange?.(selected === key ? null : key);
	}
</script>

{#snippet indicator(entry: Entry)}
	{#if entry.icon && !hideIcon}
		{const Icon = entry.icon}
		<Icon />
	{:else}
		<LegendIndicator {variant} dataKey={entry.key} colorsCount={entry.colorsCount} />
	{/if}
	{#if entry.itemConfig?.label}
		{#if typeof entry.itemConfig.label === 'string'}
			{entry.itemConfig.label}
		{:else}
			{@render entry.itemConfig.label()}
		{/if}
	{/if}
{/snippet}

{#if entries.length}
	<div
		class={cn(
			'relative z-10 flex items-center gap-4 select-none',
			align === 'left' && 'justify-start',
			align === 'center' && 'justify-center',
			align === 'right' && 'justify-end',
			verticalAlign === 'top' && 'pb-4',
			verticalAlign === 'bottom' && 'pt-4',
			className
		)}
	>
		{#each entries as entry (entry.key)}
			{#if isClickable}
				<!-- The reference makes the entry clickable with a bare onClick. Keyboard support is
				     added here without changing the rendered class list. -->
				<button
					type="button"
					class={entryClass(entry.isSelected)}
					aria-pressed={selected === entry.key}
					onclick={() => select(entry.key)}
				>
					{@render indicator(entry)}
				</button>
			{:else}
				<div class={entryClass(entry.isSelected)}>
					{@render indicator(entry)}
				</div>
			{/if}
		{/each}
	</div>
{/if}
```

`$lib/components/evilcharts/ui/layerchart-legend/legend-indicator.svelte`

```svelte
<script lang="ts">
	// ---------------------------------------------------------------------------
	// Legend indicator — each variant gets its own branch so future variants
	// can diverge freely in markup & style.
	// ---------------------------------------------------------------------------
	import { getLegendFillStyle, getLegendOutlineStyle } from './styles.js';
	import type { ChartLegendVariant } from './types.js';

	let {
		variant,
		dataKey,
		colorsCount
	}: { variant: ChartLegendVariant; dataKey: string; colorsCount: number } = $props();

	const fillStyle = $derived(getLegendFillStyle(dataKey, colorsCount));
	const outlineStyle = $derived(getLegendOutlineStyle(dataKey, colorsCount));
</script>

{#if variant === 'square'}
	<div class="h-2 w-2 shrink-0" style={fillStyle}></div>
{:else if variant === 'circle'}
	<div class="h-2 w-2 shrink-0 rounded-full" style={fillStyle}></div>
{:else if variant === 'circle-outline'}
	<div class="h-2.5 w-2.5 shrink-0 rounded-full p-[1.5px]" style={outlineStyle}></div>
{:else if variant === 'vertical-bar'}
	<div class="h-3 w-1 shrink-0 rounded-[2px]" style={fillStyle}></div>
{:else if variant === 'horizontal-bar'}
	<div class="h-1 w-3 shrink-0 rounded-[2px]" style={fillStyle}></div>
{:else if variant === 'rounded-square-outline'}
	<div class="h-2.5 w-2.5 shrink-0 rounded-[3px] p-[1.5px]" style={outlineStyle}></div>
{:else}
	<div class="h-2 w-2 shrink-0 rounded-[2px]" style={fillStyle}></div>
{/if}
```

`$lib/components/evilcharts/ui/layerchart-legend/styles.ts`

```ts
/** Solid fill / gradient background for filled variants. */
export function getLegendFillStyle(dataKey: string, colorsCount: number): string {
	if (colorsCount <= 1) {
		return `background-color: var(--color-${dataKey}-0)`;
	}

	const stops = Array.from({ length: colorsCount }, (_, i) => {
		const offset = (i / (colorsCount - 1)) * 100;
		return `var(--color-${dataKey}-${i}) ${offset}%`;
	}).join(', ');

	return `background: linear-gradient(to right, ${stops})`;
}

/**
 * Outline style for stroke variants.
 * Uses background + mask-composite to punch out the center, leaving only the
 * "border" visible. Works with both solid colors and gradients, and respects
 * border-radius — unlike plain `border-color`.
 */
export function getLegendOutlineStyle(dataKey: string, colorsCount: number): string {
	const maskStyle = [
		'-webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0)',
		'-webkit-mask-composite: xor',
		'mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0)',
		'mask-composite: exclude'
	].join('; ');

	if (colorsCount <= 1) {
		return `background-color: var(--color-${dataKey}-0); ${maskStyle}`;
	}

	const stops = Array.from({ length: colorsCount }, (_, i) => {
		const offset = (i / (colorsCount - 1)) * 100;
		return `var(--color-${dataKey}-${i}) ${offset}%`;
	}).join(', ');

	return `background: linear-gradient(to right, ${stops}); ${maskStyle}`;
}
```

`$lib/components/evilcharts/ui/layerchart-legend/types.ts`

```ts
export type ChartLegendVariant =
	| 'square'
	| 'circle'
	| 'circle-outline'
	| 'rounded-square'
	| 'rounded-square-outline'
	| 'vertical-bar'
	| 'horizontal-bar';

export type LegendAlign = 'left' | 'center' | 'right';
export type LegendVerticalAlign = 'top' | 'middle' | 'bottom';

export function resolveLegendPlacement(
	requested: LegendVerticalAlign | undefined,
	fallback: 'top' | 'bottom'
): LegendVerticalAlign {
	return requested ?? fallback;
}

/**
 * One legend entry.
 *
 * Mirrors the shape Recharts hands `<Legend content>` in the reference: `value` carries the
 * series name for pie charts, `dataKey` for cartesian charts, and `payload` the raw row so
 * `nameKey` can reach into it.
 */
export type LegendPayloadItem = {
	value?: string;
	dataKey?: string;
	payload?: unknown;
	/** Entries typed `'none'` are hidden, as in Recharts. */
	type?: string;
	color?: string;
};
```
        
      
    
  


## Usage

The pie chart is composable. `<EvilPieChart>` is the container; compose the parts you need — `<EvilPieChart.Legend>`, `<EvilPieChart.Tooltip>`, `<EvilPieChart.Background>`, and one `<EvilPieChart.Pie>` — as children. Each `<EvilPieChart.Pie>` owns its shape props (`innerRadius`, `paddingAngle`, `cornerRadius`, …), `isClickable`, and `glowingSectors`, so one chart can mix any combination.

```svelte
<script lang="ts">
	import { EvilPieChart } from '$lib/components/evilcharts/charts/layerchart-pie-chart';
	import { type ChartConfig } from '$lib/components/evilcharts/ui/layerchart-chart';
</script>
```

```svelte
<script lang="ts">
	const data = [
		{ browser: 'chrome', visitors: 275 },
		{ browser: 'safari', visitors: 200 },
		{ browser: 'firefox', visitors: 187 }
	];

	const chartConfig = {
		chrome: {
			label: 'Chrome',
			colors: { light: ['#3b82f6'], dark: ['#60a5fa'] }
		},
		safari: {
			label: 'Safari',
			colors: { light: ['#10b981'], dark: ['#34d399'] }
		},
		firefox: {
			label: 'Firefox',
			colors: { light: ['#f59e0b'], dark: ['#fbbf24'] }
		}
	} satisfies ChartConfig;
</script>
```

```svelte
<EvilPieChart {data} dataKey="visitors" nameKey="browser" config={chartConfig}>
	<EvilPieChart.Legend isClickable />
	<EvilPieChart.Tooltip />
	<EvilPieChart.Pie isClickable innerRadius={60} paddingAngle={4} cornerRadius={8}>
		<EvilPieChart.Label />
	</EvilPieChart.Pie>
</EvilPieChart>
```

### Interactive Selection

Add `isClickable` to `<EvilPieChart.Pie>` (and `<EvilPieChart.Legend>`) to make sectors selectable. Handle changes with the `onSelectionChange` callback on `<EvilPieChart>`:

```svelte
<EvilPieChart
	{data}
	dataKey="visitors"
	nameKey="browser"
	config={chartConfig}
	onSelectionChange={(selection) => {
		if (selection) {
			console.log('Selected:', selection.dataKey, 'Value:', selection.value);
		} else {
			console.log('Deselected');
		}
	}}
>
	<EvilPieChart.Legend isClickable />
	<EvilPieChart.Tooltip />
	<EvilPieChart.Pie isClickable />
</EvilPieChart>
```

### Loading State

### isLoading='true'

```svelte
<script lang="ts">
	import { EvilPieChart } from '$lib/components/evilcharts/charts/layerchart-pie-chart/index.js';
	import { type ChartConfig } from '$lib/components/evilcharts/ui/layerchart-chart/index.js';

	const data = [
		{ browser: 'chrome', visitors: 275 },
		{ browser: 'safari', visitors: 200 },
		{ browser: 'firefox', visitors: 187 },
		{ browser: 'edge', visitors: 173 },
		{ browser: 'other', visitors: 90 }
	];

	const chartConfig = {
		chrome: {
			label: 'Chrome',
			colors: {
				light: ['#3b82f6'],
				dark: ['#60a5fa']
			}
		},
		safari: {
			label: 'Safari',
			colors: {
				light: ['#10b981'],
				dark: ['#34d399']
			}
		},
		firefox: {
			label: 'Firefox',
			colors: {
				light: ['#f59e0b'],
				dark: ['#fbbf24']
			}
		},
		edge: {
			label: 'Edge',
			colors: {
				light: ['#8b5cf6'],
				dark: ['#a78bfa']
			}
		},
		other: {
			label: 'Other',
			colors: {
				light: ['#6b7280'],
				dark: ['#9ca3af']
			}
		}
	} satisfies ChartConfig;
</script>

<EvilPieChart
	class="h-full w-full p-4"
	{data}
	dataKey="visitors"
	nameKey="browser"
	config={chartConfig}
	isLoading
>
	<EvilPieChart.Legend isClickable />
	<EvilPieChart.Tooltip />
	<EvilPieChart.Pie isClickable />
</EvilPieChart>
```
>  
  

Pass `isLoading` to show a placeholder animation while your data loads.




## Examples

Examples with different configurations. Customize `innerRadius`, `paddingAngle`, `cornerRadius`, and more.

### Gradient Colors

### gradient colors

```svelte
<script lang="ts">
	import { EvilPieChart } from '$lib/components/evilcharts/charts/layerchart-pie-chart/index.js';
	import { type ChartConfig } from '$lib/components/evilcharts/ui/layerchart-chart/index.js';

	const data = [
		{ browser: 'chrome', visitors: 275 },
		{ browser: 'safari', visitors: 200 },
		{ browser: 'firefox', visitors: 187 },
		{ browser: 'edge', visitors: 173 },
		{ browser: 'other', visitors: 90 }
	];

	const chartConfig = {
		chrome: {
			label: 'Chrome',
			colors: {
				// [!code highlight:2]
				light: ['#93c5fd', '#3b82f6', '#2563eb', '#1d4ed8', '#1e40af'],
				dark: ['#bfdbfe', '#60a5fa', '#3b82f6', '#2563eb', '#1d4ed8']
			}
		},
		safari: {
			label: 'Safari',
			colors: {
				// [!code highlight:2]
				light: ['#6ee7b7', '#10b981', '#059669', '#047857', '#065f46'],
				dark: ['#a7f3d0', '#34d399', '#10b981', '#059669', '#047857']
			}
		},
		firefox: {
			label: 'Firefox',
			colors: {
				// [!code highlight:2]
				light: ['#fcd34d', '#f59e0b', '#d97706', '#b45309', '#92400e'],
				dark: ['#fde68a', '#fbbf24', '#f59e0b', '#d97706', '#b45309']
			}
		},
		edge: {
			label: 'Edge',
			colors: {
				// [!code highlight:2]
				light: ['#c4b5fd', '#8b5cf6', '#7c3aed', '#6d28d9', '#5b21b6'],
				dark: ['#ddd6fe', '#a78bfa', '#8b5cf6', '#7c3aed', '#6d28d9']
			}
		},
		other: {
			label: 'Other',
			colors: {
				// [!code highlight:2]
				light: ['#d1d5db', '#9ca3af', '#6b7280', '#4b5563', '#374151'],
				dark: ['#e5e7eb', '#d1d5db', '#9ca3af', '#6b7280', '#4b5563']
			}
		}
	} satisfies ChartConfig;
</script>

<EvilPieChart
	class="h-full w-full p-4"
	{data}
	dataKey="visitors"
	nameKey="browser"
	config={chartConfig}
>
	<EvilPieChart.Legend isClickable />
	<EvilPieChart.Tooltip />
	<EvilPieChart.Pie isClickable />
</EvilPieChart>
```

### Donut Chart

### innerRadius={60}

```svelte
<script lang="ts">
	import { EvilPieChart } from '$lib/components/evilcharts/charts/layerchart-pie-chart/index.js';
	import { type ChartConfig } from '$lib/components/evilcharts/ui/layerchart-chart/index.js';

	const data = [
		{ browser: 'chrome', visitors: 275 },
		{ browser: 'safari', visitors: 200 },
		{ browser: 'firefox', visitors: 187 },
		{ browser: 'edge', visitors: 173 },
		{ browser: 'other', visitors: 90 }
	];

	const chartConfig = {
		chrome: {
			label: 'Chrome',
			colors: {
				light: ['#3b82f6'],
				dark: ['#60a5fa']
			}
		},
		safari: {
			label: 'Safari',
			colors: {
				light: ['#10b981'],
				dark: ['#34d399']
			}
		},
		firefox: {
			label: 'Firefox',
			colors: {
				light: ['#f59e0b'],
				dark: ['#fbbf24']
			}
		},
		edge: {
			label: 'Edge',
			colors: {
				light: ['#8b5cf6'],
				dark: ['#a78bfa']
			}
		},
		other: {
			label: 'Other',
			colors: {
				light: ['#6b7280'],
				dark: ['#9ca3af']
			}
		}
	} satisfies ChartConfig;
</script>

<EvilPieChart
	class="h-full w-full p-4"
	{data}
	dataKey="visitors"
	nameKey="browser"
	config={chartConfig}
>
	<EvilPieChart.Legend isClickable />
	<EvilPieChart.Tooltip />
	<EvilPieChart.Pie isClickable innerRadius={60} />
</EvilPieChart>
```
>  
  

Set `innerRadius` above 0 to create a donut — it cuts the hole in the center.




### Padded Sectors

### paddingAngle={4} cornerRadius={8}

```svelte
<script lang="ts">
	import { EvilPieChart } from '$lib/components/evilcharts/charts/layerchart-pie-chart/index.js';
	import { type ChartConfig } from '$lib/components/evilcharts/ui/layerchart-chart/index.js';

	const data = [
		{ browser: 'chrome', visitors: 275 },
		{ browser: 'safari', visitors: 200 },
		{ browser: 'firefox', visitors: 187 },
		{ browser: 'edge', visitors: 173 },
		{ browser: 'other', visitors: 90 }
	];

	const chartConfig = {
		chrome: {
			label: 'Chrome',
			colors: {
				light: ['#3b82f6'],
				dark: ['#60a5fa']
			}
		},
		safari: {
			label: 'Safari',
			colors: {
				light: ['#10b981'],
				dark: ['#34d399']
			}
		},
		firefox: {
			label: 'Firefox',
			colors: {
				light: ['#f59e0b'],
				dark: ['#fbbf24']
			}
		},
		edge: {
			label: 'Edge',
			colors: {
				light: ['#8b5cf6'],
				dark: ['#a78bfa']
			}
		},
		other: {
			label: 'Other',
			colors: {
				light: ['#6b7280'],
				dark: ['#9ca3af']
			}
		}
	} satisfies ChartConfig;
</script>

<EvilPieChart
	class="h-full w-full p-4"
	{data}
	dataKey="visitors"
	nameKey="browser"
	config={chartConfig}
>
	<EvilPieChart.Legend isClickable />
	<EvilPieChart.Tooltip />
	<EvilPieChart.Pie isClickable innerRadius={30} paddingAngle={4} cornerRadius={8} />
</EvilPieChart>
```
>  
  

`paddingAngle` adds space between sectors; `cornerRadius` rounds their corners. Combine with `innerRadius` for a modern donut look.




### innerRadius={60} paddingAngle={-20} cornerRadius={100}

```svelte
<script lang="ts">
	import { EvilPieChart } from '$lib/components/evilcharts/charts/layerchart-pie-chart/index.js';
	import { type ChartConfig } from '$lib/components/evilcharts/ui/layerchart-chart/index.js';

	const data = [
		{ browser: 'chrome', visitors: 275 },
		{ browser: 'safari', visitors: 200 },
		{ browser: 'firefox', visitors: 187 },
		{ browser: 'edge', visitors: 173 },
		{ browser: 'other', visitors: 90 }
	];

	const chartConfig = {
		chrome: {
			label: 'Chrome',
			colors: {
				light: ['#3b82f6'],
				dark: ['#60a5fa']
			}
		},
		safari: {
			label: 'Safari',
			colors: {
				light: ['#10b981'],
				dark: ['#34d399']
			}
		},
		firefox: {
			label: 'Firefox',
			colors: {
				light: ['#f59e0b'],
				dark: ['#fbbf24']
			}
		},
		edge: {
			label: 'Edge',
			colors: {
				light: ['#8b5cf6'],
				dark: ['#a78bfa']
			}
		},
		other: {
			label: 'Other',
			colors: {
				light: ['#6b7280'],
				dark: ['#9ca3af']
			}
		}
	} satisfies ChartConfig;
</script>

<EvilPieChart
	class="h-full w-full p-4"
	{data}
	dataKey="visitors"
	nameKey="browser"
	config={chartConfig}
>
	<EvilPieChart.Legend isClickable />
	<EvilPieChart.Tooltip />
	<EvilPieChart.Pie innerRadius={60} paddingAngle={-25} cornerRadius={99} />
</EvilPieChart>
```
>  
  

A negative `paddingAngle` with a high `cornerRadius` overlaps sectors into petals. Add `innerRadius` for a flower-shaped donut.




### Labels

### &lt;EvilPieChart.Label /&gt;

```svelte
<script lang="ts">
	import { EvilPieChart } from '$lib/components/evilcharts/charts/layerchart-pie-chart/index.js';
	import { type ChartConfig } from '$lib/components/evilcharts/ui/layerchart-chart/index.js';

	const data = [
		{ browser: 'chrome', visitors: 275 },
		{ browser: 'safari', visitors: 200 },
		{ browser: 'firefox', visitors: 187 },
		{ browser: 'edge', visitors: 173 },
		{ browser: 'other', visitors: 90 }
	];

	const chartConfig = {
		chrome: {
			label: 'Chrome',
			colors: {
				light: ['#3b82f6'],
				dark: ['#60a5fa']
			}
		},
		safari: {
			label: 'Safari',
			colors: {
				light: ['#10b981'],
				dark: ['#34d399']
			}
		},
		firefox: {
			label: 'Firefox',
			colors: {
				light: ['#f59e0b'],
				dark: ['#fbbf24']
			}
		},
		edge: {
			label: 'Edge',
			colors: {
				light: ['#8b5cf6'],
				dark: ['#a78bfa']
			}
		},
		other: {
			label: 'Other',
			colors: {
				light: ['#6b7280'],
				dark: ['#9ca3af']
			}
		}
	} satisfies ChartConfig;
</script>

<EvilPieChart
	class="h-full w-full p-4"
	{data}
	dataKey="visitors"
	nameKey="browser"
	config={chartConfig}
>
	<EvilPieChart.Legend isClickable />
	<EvilPieChart.Tooltip />
	<EvilPieChart.Pie isClickable innerRadius={30} paddingAngle={4} cornerRadius={8}>
		<!-- [!code highlight:2] -->
		<EvilPieChart.Label />
	</EvilPieChart.Pie>
</EvilPieChart>
```
>  
  

Compose `<EvilPieChart.Label />` inside `<EvilPieChart.Pie>` to draw a label on each sector. Use `dataKey` to change the data shown and `labelListProps` for further customization.




### Glowing Sectors

### glowingSectors={['chrome', 'safari']}

```svelte
<script lang="ts">
	import { EvilPieChart } from '$lib/components/evilcharts/charts/layerchart-pie-chart/index.js';
	import { type ChartConfig } from '$lib/components/evilcharts/ui/layerchart-chart/index.js';

	const data = [
		{ browser: 'chrome', visitors: 275 },
		{ browser: 'safari', visitors: 200 },
		{ browser: 'firefox', visitors: 187 },
		{ browser: 'edge', visitors: 173 },
		{ browser: 'other', visitors: 90 }
	];

	const chartConfig = {
		chrome: {
			label: 'Chrome',
			colors: {
				light: ['#3b82f6'],
				dark: ['#60a5fa']
			}
		},
		safari: {
			label: 'Safari',
			colors: {
				light: ['#10b981'],
				dark: ['#34d399']
			}
		},
		firefox: {
			label: 'Firefox',
			colors: {
				light: ['#f59e0b'],
				dark: ['#fbbf24']
			}
		},
		edge: {
			label: 'Edge',
			colors: {
				light: ['#8b5cf6'],
				dark: ['#a78bfa']
			}
		},
		other: {
			label: 'Other',
			colors: {
				light: ['#6b7280'],
				dark: ['#9ca3af']
			}
		}
	} satisfies ChartConfig;
</script>

<EvilPieChart
	class="h-full w-full p-4"
	{data}
	dataKey="visitors"
	nameKey="browser"
	config={chartConfig}
>
	<EvilPieChart.Legend isClickable />
	<EvilPieChart.Tooltip />
	<EvilPieChart.Pie isClickable glowingSectors={['chrome', 'safari']} />
</EvilPieChart>
```
>  
  

Pass an array of sector names (values from your `nameKey` field) to `glowingSectors` to give those sectors a subtle glow.




### Dither rendering

Set `renderStyle="dither"` on the existing pie root for ordered-dither sectors. Donut holes, padding, rounded corners, labels, tooltips, selection, loading, and sweep motion keep their existing behavior. Use `ditherVariant` on `<Pie />` to override the root texture.

### dithered donut

```svelte
<script lang="ts">
	import {
		EvilPieChart,
		type ChartConfig
	} from '$lib/components/evilcharts/charts/layerchart-pie-chart/index.js';
	const data = [
		{ browser: 'chrome', visitors: 46 },
		{ browser: 'safari', visitors: 28 },
		{ browser: 'firefox', visitors: 17 },
		{ browser: 'other', visitors: 9 }
	];
	const config = {
		chrome: { label: 'Chrome', colors: { light: ['#047857'], dark: ['#10b981'] } },
		safari: { label: 'Safari', colors: { light: ['#0369a1'], dark: ['#38bdf8'] } },
		firefox: { label: 'Firefox', colors: { light: ['#be123c'], dark: ['#f43f5e'] } },
		other: { label: 'Other', colors: { light: ['#a16207'], dark: ['#facc15'] } }
	} satisfies ChartConfig;
</script>

<EvilPieChart
	{data}
	{config}
	dataKey="visitors"
	nameKey="browser"
	renderStyle="dither"
	bloom="low"
	class="h-full w-full p-4"
>
	<EvilPieChart.Legend isClickable /><EvilPieChart.Tooltip />
	<EvilPieChart.Pie innerRadius={54} ditherVariant="gradient" isClickable />
</EvilPieChart>
```

The renderer is independently implemented for EvilCharts SV and inspired by [Dither Kit](https://github.com/Boring-Software-Inc/dither-kit) by Boring Software.

## API Reference

Props are grouped by the part they belong to.

### EvilPieChart

The root container. Owns the data, shared selection state, and loading skeleton; all visuals are composed as its children.


  ### `data` (required)

type: `TData[]`

An array of objects, one per sector (`TData extends Record<string, unknown>`).
  ### `dataKey` (required)

type: `keyof TData & string`

Data key for sector values — typically numbers that set sector size.
  ### `nameKey` (required)

type: `keyof TData & string`

Data key for sector names — the strings used in labels and legend.
  ### `config` (required)

type: `ChartConfig`

Defines each sector's colors. Keys should match the values from your `nameKey` field.
  ### `children` (required)

type: `Snippet`

The composed chart parts — `<Legend />`, `<Tooltip />`, `<Background />`, and one `<Pie />`.
  ### `accessibility`

type: `ChartAccessibility`

Names and optionally describes the chart wrapper. It remains a group, so interactive legends and marks stay available to assistive technology.
  ### `className`

type: `string`

Extra CSS classes for the chart container.
  ### `defaultSelectedSector`

type: `string | null` · default: `null`

Sector name selected by default.
  ### `onSelectionChange`

type: `(selection: { dataKey: string; value: number } | null) => void`

Fires when a sector is selected or deselected via a clickable `<Pie />` sector or `<Legend />` entry. Receives an object with `dataKey` (sector name) and `value` (sector value), or `null` when deselected.
  ### `isLoading`

type: `boolean` · default: `false`

Shows a placeholder animation while data loads.
  ### `renderStyle`

type: `"svg" | "dither"` · default: `"svg"`

Selects the SVG or ordered-dither renderer.
  ### `ditherVariant`

type: `"gradient" | "dotted" | "hatched" | "solid"` · default: `"gradient"`

Default texture for dithered sectors.
  ### `ditherCellSize`

type: `number` · default: `2`

Dither cell size in CSS pixels.
  ### `bloom`

type: `"off" | "low" | "high" | "aura"` · default: `"off"`

Optional bounded glow around dither pixels.
  ### `chartProps`

type: `ComponentProps<typeof PieChart>`

Extra props forwarded to the underlying LayerChart Chart. See the [LayerChart Chart documentation](https://www.layerchart.com/docs/components/Chart).


### Pie

The pie series. Self-contained — it generates its own gradients and glow filters, so any number of pies coexist on a page without style collisions. Compose a `<Label />` inside it to draw sector labels.


  ### `innerRadius`

type: `number | string` · default: `0`

Inner radius of the pie; set above 0 for a donut. Number (pixels) or percentage string.
  ### `outerRadius`

type: `number | string` · default: `"80%"`

Outer radius of the pie. Number (pixels) or percentage string.
  ### `cornerRadius`

type: `number` · default: `0`

Corner radius of each sector, in pixels.
  ### `paddingAngle`

type: `number` · default: `0`

Padding between sectors, in degrees. Negative values overlap sectors.
  ### `startAngle`

type: `number` · default: `0`

Starting angle, in degrees (0 is 3 o'clock, 90 is 12 o'clock).
  ### `endAngle`

type: `number` · default: `360`

Ending angle, in degrees. Below 360 draws a partial pie.
  ### `isClickable`

type: `boolean` · default: `false`

Lets users click sectors to select/deselect them; selecting one dims the rest.
  ### `glowingSectors`

type: `string[]` · default: `[]`

Array of sector names (values from your `nameKey` field) to give a smooth outer glow.
  ### `children`

type: `Snippet`

Optional `<Label />` that draws labels on each sector.
  ### `pieProps`

type: `Omit<ComponentProps<typeof Pie>, "data" | "dataKey" | "nameKey">`

Escape hatch for raw props forwarded to the underlying LayerChart Arc. See the [LayerChart Arc documentation](https://www.layerchart.com/docs/components/Arc).


### Label

Per-sector labels composed inside a `<Pie />`. Renders nothing itself — the parent `<Pie />` reads its props and draws the label list over the sectors.


  ### `dataKey`

type: `string`

Data key for label text. Falls back to the chart's `dataKey` when omitted.
  ### `labelListProps`

type: `Omit<ComponentProps<typeof LabelList>, "dataKey">`

Escape hatch for label props. See the [LayerChart Text documentation](https://www.layerchart.com/docs/components/Text).


### Tooltip

The hover tooltip. Hidden automatically while the chart loads.


  ### `variant`

type: `"default" | "frosted-glass"` · default: `"default"`

Visual style of the tooltip surface.
  ### `roundness`

type: `"sm" | "md" | "lg" | "xl"` · default: `"lg"`

Border-radius of the tooltip.
  ### `defaultIndex`

type: `number`

Shows the tooltip by default at the given sector index.


### Legend

The sector legend. When `isClickable` is set, each entry toggles selection of its sector.


  ### `variant`

type: `"square" | "circle" | "circle-outline" | "rounded-square" | "rounded-square-outline" | …`

Visual style of the legend indicators.
  ### `align`

type: `"left" | "center" | "right"` · default: `"center"`

Horizontal placement of the legend.
  ### `verticalAlign`

type: `"top" | "middle" | "bottom"` · default: `"bottom"`

Vertical placement of the legend.
  ### `isClickable`

type: `boolean` · default: `false`

Lets each legend entry toggle selection of its sector.


### Background

An optional decorative pattern behind the pie. Compose it before the `<Pie />` so it sits under the sectors.


  ### `variant`

type: `BackgroundVariant` · default: `"dots"`

The background pattern style.

