
### Basic Chart

```svelte
<script lang="ts">
	import { EvilRadialChart } from '$lib/components/evilcharts/charts/layerchart-radial-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>

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

## Installation


  
  
    ### npm

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

### yarn

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

### bun

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

### pnpm

```bash
pnpm dlx shadcn-svelte@latest add @evilcharts/layerchart-radial-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 and paste the following code snippets into your project.
         

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


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

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

```svelte
<script lang="ts">
	/**
	 * Diagonal colour gradient applied to every radial bar, one per config key.
	 *
	 * A single chart-level block keyed by `chartId`, unlike the per-series generators in the other
	 * charts — the reference does the same, because every bar shares one `<defs>`.
	 */
	import { getColorsCount } from '../../../ui/layerchart-chart/colors.js';
	import type { ChartConfig } from '../../../ui/layerchart-chart/chart-config.js';

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

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

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

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

```ts
import Root from './radial-chart.svelte';
import RadialBar from './radial-bar.svelte';
import Tooltip from './tooltip.svelte';
import Legend from './legend.svelte';

type RootComponent = typeof Root;

// Compound API: every part hangs off the root as a static member, so a consumer
// writes <EvilRadialChart.RadialBar/>, <EvilRadialChart.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 EvilRadialChart: RootComponent & {
	RadialBar: typeof RadialBar;
	Tooltip: typeof Tooltip;
	Legend: typeof Legend;
} = Object.assign(Root, {
	RadialBar,
	Tooltip,
	Legend
});

export type { RadialVariant } from './types.js';
export type { ChartAccessibility, ChartConfig } from '../../ui/layerchart-chart/index.js';
```

`$lib/components/evilcharts/charts/layerchart-radial-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 { useRadialChart } from './radial-chart-context.svelte.js';

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

	const chart = useRadialChart();

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

	/**
	 * One entry per bar, carrying the row so `nameKey` can resolve its label and colours.
	 *
	 * `value` is the row's literal `name` property, which is what Recharts' radial legend payload
	 * puts there — *not* the `nameKey` value. That matters because `<Legend itemSorter="value">`
	 * sorts on it: rows without a `name` all compare equal, so the sort is a no-op and the bars keep
	 * data order. Using the `nameKey` value here would sort the legend alphabetically, which is
	 * right for the pie (whose payload really does carry the sector name) but wrong here.
	 */
	const payload = $derived<LegendPayloadItem[]>(
		chart.data.map((row) => ({ value: row.name as string | undefined, 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.selectedBar}
		onSelectChange={(name) => chart.selectBar(name)}
		class={placement === 'middle'
			? 'pointer-events-auto absolute inset-x-0 top-1/2 z-10 -translate-y-1/2 px-4'
			: undefined}
	/>
{/if}
```

`$lib/components/evilcharts/charts/layerchart-radial-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 { useRadialChart } from './radial-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 bar
	} = $props();

	const chart = useRadialChart();
	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-radial-chart/loading/loading-radial-bar.svelte`

```svelte
<script lang="ts">
	/**
	 * The skeleton bars shown while the chart is loading. Rendered by the root in place of the real
	 * <RadialBar />, with animated values and a muted fill.
	 */
	import { Arc, getChartContext } from 'layerchart';
	import { animate, useMotionValue, useReducedMotion } from '@humanspeak/svelte-motion';
	import { untrack } from 'svelte';
	import {
		DEFAULT_BAR_SIZE,
		DEFAULT_CORNER_RADIUS,
		LOADING_ANIMATION_DURATION,
		getRings,
		getVariantConfig,
		interpolateRings,
		resolveRadius,
		toArcAngle,
		type RadialRing
	} from '../types.js';
	import { useRadialChart } from '../radial-chart-context.svelte.js';

	const chart = useRadialChart();
	const layer = getChartContext();

	const shouldReduceMotion = useReducedMotion();
	const progress = useMotionValue(1);
	let sourceRings = $state<RadialRing[]>([]);
	let targetRings = $state<RadialRing[]>([]);

	const variantConfig = $derived(getVariantConfig(chart.variant));
	// `layer.width` / `layer.height` are the plot box, already inside the chart's `padding`, so the
	// margin must not be subtracted a second time.
	const maxRadius = $derived(Math.min(layer.width, layer.height) / 2);
	const startAngle = $derived(toArcAngle(variantConfig.startAngle));
	// The track spans the chart's whole sweep, not the bar's.
	const trackEndAngle = $derived(toArcAngle(variantConfig.endAngle));

	const rings = $derived(
		getRings({
			rows: chart.data,
			dataKey: 'value',
			nameKey: 'name',
			innerRadius: resolveRadius(chart.innerRadius, maxRadius),
			outerRadius: resolveRadius(chart.outerRadius, maxRadius),
			barSize: DEFAULT_BAR_SIZE,
			startAngle,
			endAngle: toArcAngle(variantConfig.endAngle),
			max: chart.max
		})
	);

	/**
	 * Recharts interpolates the previous and next sector angles whenever the random loading rows
	 * change. LayerChart's Arc motion only drives its `value` scale; an explicit `endAngle` bypasses
	 * it, so the loading rings need the same angle interpolation used by the live RadialBar.
	 */
	$effect(() => {
		const nextRings = rings;
		const reduceMotion = shouldReduceMotion.current;
		let controls: ReturnType<typeof animate> | undefined;

		untrack(() => {
			const currentRings =
				targetRings.length === 0 ? [] : interpolateRings(sourceRings, targetRings, progress.get());

			sourceRings = currentRings;
			targetRings = nextRings;

			if (reduceMotion) {
				progress.set(1);
			} else {
				progress.set(0);
				controls = animate(progress, 1, {
					duration: LOADING_ANIMATION_DURATION / 1000,
					ease: [0.42, 0, 0.58, 1]
				});
			}
		});

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

	const animatedRings = $derived(interpolateRings(sourceRings, targetRings, progress.current));
</script>

{#each animatedRings as ring (ring.index)}
	<!--
		The reference leaves Recharts' own animation on for the skeleton, so each bar tweens to its new
		length whenever the data is regenerated.
	-->
	<Arc
		{startAngle}
		endAngle={ring.endAngle}
		innerRadius={ring.innerRadius}
		outerRadius={ring.outerRadius}
		cornerRadius={DEFAULT_CORNER_RADIUS}
		fill="currentColor"
		fillOpacity={0.25}
		track
		{trackEndAngle}
		motion="none"
	/>
{/each}
```

`$lib/components/evilcharts/charts/layerchart-radial-chart/loading/use-loading-data.svelte.ts`

```ts
import { useReducedMotion } from '@humanspeak/svelte-motion';
import { LOADING_ANIMATION_DURATION, LOADING_BARS } from '../types.js';

/** Random skeleton rows with values between 40 and 100. */
function generateLoadingData() {
	return Array.from({ length: LOADING_BARS }, (_, index) => ({
		name: `loading${index}`,
		value: 40 + Math.random() * 60
	}));
}

/** Regenerates the skeleton rows on a fixed interval, so the bars keep animating while loading. */
export class LoadingDataState {
	#isLoading: () => boolean;
	/** Bumped by the interval; regenerates the skeleton values each cycle. */
	#tick = $state(0);

	constructor(options: { isLoading: () => boolean }) {
		this.#isLoading = options.isLoading;
		const shouldReduceMotion = useReducedMotion();

		$effect(() => {
			if (!this.#isLoading() || shouldReduceMotion.current) return;

			const interval = setInterval(() => {
				this.#tick += 1;
			}, LOADING_ANIMATION_DURATION);

			return () => clearInterval(interval);
		});
	}

	get loadingData() {
		this.#tick;
		return generateLoadingData();
	}
}
```

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

```svelte
<script lang="ts">
	/**
	 * The radial bar series. Each data row becomes one bar, laid out from the inside out — row 0 is
	 * the innermost ring, which is how Recharts stacks them. Pass `isClickable` to make bars
	 * selectable.
	 */
	import { Arc, getChartContext } from 'layerchart';
	import { animate, useMotionValue, useReducedMotion } from '@humanspeak/svelte-motion';
	import { useRadialChart } from './radial-chart-context.svelte.js';
	import { untrack } from 'svelte';
	import {
		DEFAULT_BAR_SIZE,
		DEFAULT_CORNER_RADIUS,
		REVEAL_BEGIN,
		REVEAL_DURATION,
		REVEAL_EASE,
		getRings,
		getVariantConfig,
		interpolateRings,
		resolveRadius,
		toArcAngle,
		type RadialRing
	} from './types.js';

	let {
		dataKey,
		cornerRadius = DEFAULT_CORNER_RADIUS,
		barSize = DEFAULT_BAR_SIZE,
		showBackground = true,
		isClickable = false,
		radialBarProps,
		arcProps
	}: {
		dataKey: string; // value key — determines each bar's size
		cornerRadius?: number; // border radius of each bar's corners
		barSize?: number; // thickness of each radial bar
		showBackground?: boolean; // renders the unfilled track behind each bar
		isClickable?: boolean; // lets bars be selected by clicking them
		radialBarProps?: Record<string, unknown>; // canonical escape hatch, matching the original API
		/** @deprecated Use `radialBarProps`. */
		arcProps?: Record<string, unknown>; // escape hatch for raw LayerChart Arc props
	} = $props();

	const forwardedRadialBarProps = $derived({ ...(arcProps ?? {}), ...(radialBarProps ?? {}) });

	const chart = useRadialChart();
	const layer = getChartContext();
	const token = $props.id();
	// Devices set to "reduce motion" skip the intro entirely
	const shouldReduceMotion = useReducedMotion();

	/**
	 * The intro, reproducing `<RadialBar>`'s own animation: each bar's `endAngle` sweeps out from
	 * the chart's start angle over 1.5s with the CSS `ease` curve.
	 */
	const reveal = useMotionValue(1);
	let sourceRings = $state<RadialRing[]>([]);
	let targetRings = $state<RadialRing[]>([]);
	let previousLoading: boolean | undefined;

	// Push the value key up so the tooltip can read each bar's number.
	$effect.pre(() => {
		chart.registerValueKey(token, dataKey);
		return () => chart.registerValueKey(token, undefined);
	});

	const variantConfig = $derived(getVariantConfig(chart.variant));

	/**
	 * Recharts' `getMaxRadius`: half the smaller plot dimension, measured inside the chart margin.
	 * It does not shift with the `semi` variant's lower centre, so the radii are the same for both.
	 */
	// `layer.width` / `layer.height` are the plot box, already inside the chart's `padding`, so the
	// margin must not be subtracted a second time.
	const maxRadius = $derived(Math.min(layer.width, layer.height) / 2);

	const rings = $derived(
		getRings({
			rows: chart.data,
			dataKey,
			nameKey: chart.nameKey,
			innerRadius: resolveRadius(chart.innerRadius, maxRadius),
			outerRadius: resolveRadius(chart.outerRadius, maxRadius),
			barSize,
			startAngle: toArcAngle(variantConfig.startAngle),
			endAngle: toArcAngle(variantConfig.endAngle),
			max: chart.max
		})
	);

	// Recharts re-animates radial sectors whenever their geometry changes. Capture the currently
	// painted angles before each new tween so rapid updates cannot jump back to an older target.
	$effect(() => {
		const loadingNow = chart.isLoading;
		const nextRings = rings;
		const reduceMotion = shouldReduceMotion.current;
		let controls: ReturnType<typeof animate> | undefined;

		untrack(() => {
			if (loadingNow) {
				sourceRings = [];
				targetRings = [];
				reveal.set(1);
			} else {
				const entering = previousLoading === undefined || previousLoading;
				const currentRings = entering
					? []
					: interpolateRings(sourceRings, targetRings, reveal.get());

				sourceRings = currentRings;
				targetRings = nextRings;

				if (reduceMotion) {
					reveal.set(1);
				} else {
					reveal.set(0);
					controls = animate(reveal, 1, {
						delay: REVEAL_BEGIN / 1000,
						duration: REVEAL_DURATION / 1000,
						ease: REVEAL_EASE
					});
				}
			}
			previousLoading = loadingNow;
		});

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

	const animatedRings = $derived(interpolateRings(sourceRings, targetRings, reveal.current));
	const isAnimating = $derived(
		!chart.isLoading && !shouldReduceMotion.current && reveal.current < 1
	);

	/**
	 * The chart's full sweep, for the track behind each bar.
	 *
	 * LayerChart defaults `trackEndAngle` to the *arc's* own `endAngle`, so the track ended exactly
	 * where the bar did and was completely hidden behind it. Recharts' background sector always
	 * spans the whole arc.
	 */
	const trackEndAngle = $derived(toArcAngle(variantConfig.endAngle));

	/**
	 * Everything each ring needs, resolved in one derivation rather than with declaration tags in
	 * the `{#each}`.
	 */
	const bars = $derived(
		animatedRings.map((ring) => ({
			...ring,
			fill: `url(#${chart.chartId}-radial-colors-${ring.name})`,
			opacity:
				isClickable && chart.selectedBar !== null && chart.selectedBar !== ring.name ? 0.15 : 1,
			value: Number(ring.row[dataKey] ?? 0)
		}))
	);

	function select(name: string, value: number) {
		if (!isClickable) return;
		// Clicking the selected bar clears the selection, otherwise selects it
		chart.selectBar(chart.selectedBar === name ? null : name, value);
	}

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

<!-- The root renders the skeleton bar while loading, so the real bar steps aside -->
{#if !chart.isLoading}
	{#each bars as bar (bar.index)}
		<Arc
			class={['drop-shadow-sm transition-opacity duration-200', isClickable && 'cursor-pointer']
				.filter(Boolean)
				.join(' ')}
			data-evil-animation-state={isAnimating ? 'running' : 'idle'}
			startAngle={bar.startAngle}
			endAngle={bar.endAngle}
			innerRadius={bar.innerRadius}
			outerRadius={bar.outerRadius}
			{cornerRadius}
			fill={bar.fill}
			opacity={bar.opacity}
			track={showBackground}
			{trackEndAngle}
			data={bar.row}
			tooltip
			motion="none"
			role={isClickable ? 'button' : 'presentation'}
			tabindex={isClickable ? 0 : undefined}
			aria-label={isClickable ? `${bar.name}: ${bar.value}` : undefined}
			aria-pressed={isClickable ? chart.selectedBar === bar.name : undefined}
			onkeydown={(event: KeyboardEvent) => selectFromKeyboard(event, bar.name, bar.value)}
			onclick={() => select(bar.name, bar.value)}
			{...forwardedRadialBarProps}
		/>
	{/each}
{/if}
```

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

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

const RADIAL_CHART_KEY = Symbol('evilcharts.radial-chart');

type Options = {
	config: () => ChartConfig;
	/** Rows currently rendered by the chart, or the loading skeleton. */
	data: () => Record<string, unknown>[];
	/** Data key holding each bar's name. */
	nameKey: () => string;
	/**
	 * Value key, pushed up by the rendered `<RadialBar dataKey>`.
	 *
	 * Recharts reads it off the bar; the tooltip needs it too, so the bar registers it rather than
	 * the root guessing. The token prevents a stale teardown from clearing a remounted bar.
	 */
	valueKey: () => string | undefined;
	registerValueKey: (token: string, dataKey: string | undefined) => void;
	chartId: () => string;
	variant: () => RadialVariant;
	/** Value a full sweep represents; unset lets the largest row fill the arc. */
	max: () => number | undefined;
	innerRadius: () => number | string;
	outerRadius: () => number | string;
	isLoading: () => boolean;
	selectedBar: () => string | null;
	selectBar: (barName: string | null, value?: number) => void;
};

/**
 * Shared state for every part of the chart. Lifted into <EvilRadialChart /> so that
 * <RadialBar />, <Tooltip />, and <Legend /> can read it without prop drilling.
 */
export class RadialChartContext {
	#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 nameKey() {
		return this.#options.nameKey();
	}
	get valueKey() {
		return this.#options.valueKey();
	}
	get chartId() {
		return this.#options.chartId();
	}
	get variant() {
		return this.#options.variant();
	}
	get max() {
		return this.#options.max();
	}
	get innerRadius() {
		return this.#options.innerRadius();
	}
	get outerRadius() {
		return this.#options.outerRadius();
	}
	get isLoading() {
		return this.#options.isLoading();
	}
	get selectedBar() {
		return this.#options.selectedBar();
	}

	selectBar = (barName: string | null, value?: number) => {
		this.#options.selectBar(barName, value);
	};

	registerValueKey = (token: string, dataKey: string | undefined) => {
		this.#options.registerValueKey(token, dataKey);
	};
}

export function setRadialChartContext(options: Options) {
	const context = new RadialChartContext(options);
	setContext(RADIAL_CHART_KEY, context);
	return context;
}

/** Reads the chart context, throwing a helpful error when used outside <EvilRadialChart /> */
export function useRadialChart(): RadialChartContext {
	const context = getContext<RadialChartContext | undefined>(RADIAL_CHART_KEY);

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

	return context;
}
```

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

```svelte
<script lang="ts" generics="TData extends Record<string, unknown>">
	/**
	 * Root of the composable radial chart. Owns the data, the shared context, the loading skeleton,
	 * and the chart-wide arc shape. Everything visual — the tooltip, legend, and the radial bar
	 * itself — is composed as children, so a consumer renders exactly the parts they need.
	 */
	import { Chart, Group, Svg, type ChartState } from 'layerchart';
	import { untrack, type Snippet } from 'svelte';
	import {
		ChartContainer,
		LoadingIndicator,
		type ChartAccessibility,
		type ChartConfig
	} from '../../ui/layerchart-chart/index.js';
	import { ChartBackground, type BackgroundVariant } from '../../ui/layerchart-background/index.js';
	import ColorGradientStyle from './defs/color-gradient-style.svelte';
	import LegendRender from './legend-render.svelte';
	import LoadingRadialBar from './loading/loading-radial-bar.svelte';
	import { LoadingDataState } from './loading/use-loading-data.svelte.js';
	import { setRadialChartContext } from './radial-chart-context.svelte.js';
	import TooltipRender from './tooltip-render.svelte';
	import {
		CHART_MARGIN,
		DEFAULT_INNER_RADIUS,
		DEFAULT_OUTER_RADIUS,
		getVariantConfig,
		type RadialVariant
	} from './types.js';

	let {
		config,
		data,
		nameKey,
		children,
		class: className,
		chartProps,
		accessibility,
		variant = 'full',
		max,
		innerRadius = DEFAULT_INNER_RADIUS,
		outerRadius = DEFAULT_OUTER_RADIUS,
		defaultSelectedDataKey = null,
		onSelectionChange,
		isLoading = false,
		backgroundVariant,
		initialDimension = { width: 320, height: 200 }
	}: {
		config: ChartConfig; // bar colors + labels
		data: TData[]; // rows rendered by the chart
		nameKey: keyof TData & string; // data key holding each bar's name
		children: Snippet; // composed parts — <RadialBar />, <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
		variant?: RadialVariant; // arc shape — full circle or half circle
		/**
		 * Value a full sweep represents. Without it the scale is derived from the data, so the
		 * largest bar always fills the arc — set it (e.g. 100) for gauges, where a single value has
		 * to read against a fixed total.
		 */
		max?: number;
		innerRadius?: number | string; // inner radius of the radial bars
		outerRadius?: number | string; // outer radius of the radial bars
		defaultSelectedDataKey?: string | null; // bar selected on first render
		onSelectionChange?: (selection: { dataKey: string; value: number } | null) => void; // fires when the selected bar changes
		isLoading?: boolean; // shows the animated loading skeleton
		backgroundVariant?: BackgroundVariant; // background pattern behind the chart
		initialDimension?: { width: number; height: number }; // zero-size/first-render fallback
	} = $props();

	const chartId = $props.id(); // selector-safe id keeps CSS/SVG references valid
	let chartDimension = $state(untrack(() => initialDimension));

	// One-time initialisation, mirroring the reference's `useState(defaultSelectedDataKey)`.
	let selectedBar = $state<string | null>(untrack(() => defaultSelectedDataKey));

	/** Value key pushed up by the rendered `<RadialBar dataKey>`. */
	let registeredValueKey = $state<string | undefined>(undefined);
	let registeredValueToken: string | null = null;

	const loading = new LoadingDataState({ isLoading: () => isLoading });

	const rows = $derived((isLoading ? loading.loadingData : data) as Record<string, unknown>[]);
	const variantConfig = $derived(getVariantConfig(variant));

	/**
	 * LayerChart's chart state, read for the plot box the arc centre is placed against.
	 *
	 * `<Group x>` only takes a *number* as a pixel translate — handing it a function switches the
	 * group into data mode, which renders one group per row and applies no transform at all.
	 */
	let layerContext = $state<ChartState<Record<string, unknown>> | undefined>(undefined);
	const centre = $derived({
		x: (layerContext?.width ?? 0) * variantConfig.cx,
		y: (layerContext?.height ?? 0) * variantConfig.cy
	});

	const EDGE_LEGEND_HEIGHT = 32;
	let radialContext: ReturnType<typeof setRadialChartContext>;
	const edgeLegendPlacement = $derived.by(() => {
		if (isLoading || !radialContext) return null;
		const align = radialContext.slots.legend?.verticalAlign;
		return align === 'top' || align === 'bottom' ? align : null;
	});
	const padding = $derived({
		top: CHART_MARGIN + (edgeLegendPlacement === 'top' ? EDGE_LEGEND_HEIGHT : 0),
		right: CHART_MARGIN,
		bottom: CHART_MARGIN + (edgeLegendPlacement === 'bottom' ? EDGE_LEGEND_HEIGHT : 0),
		left: CHART_MARGIN
	});

	radialContext = setRadialChartContext({
		config: () => config,
		data: () => rows,
		// The skeleton rows carry their own `name` key.
		nameKey: () => (isLoading ? 'name' : nameKey),
		valueKey: () => registeredValueKey,
		chartId: () => chartId,
		variant: () => variant,
		max: () => max,
		innerRadius: () => innerRadius,
		outerRadius: () => outerRadius,
		isLoading: () => isLoading,
		selectedBar: () => selectedBar,
		selectBar: (barName, value) => {
			selectedBar = barName;
			onSelectionChange?.(barName === null ? null : { dataKey: barName, value: value ?? 0 });
		},
		registerValueKey: (token, key) => {
			// Ignore a stale teardown from LayerChart's mount-time remount.
			if (key === undefined && registeredValueToken !== token) return;
			registeredValueToken = key === undefined ? null : token;
			registeredValueKey = key;
		}
	});
</script>

<ChartContainer
	{config}
	{initialDimension}
	{accessibility}
	bind:dimension={chartDimension}
	class={className}
>
	<LoadingIndicator {isLoading} />
	<LegendRender placement="top" />
	<!--
		The arcs carry their own angles and radii, so the chart only has to supply the plot box.
		`padding` is Recharts' default `<RadialBarChart margin>`, which its maximum radius measures
		against.
	-->
	<Chart
		width={chartDimension.width}
		height={chartDimension.height}
		bind:context={layerContext}
		data={rows}
		{padding}
		class="h-full w-full"
		{...chartProps}
	>
		<Svg>
			<!--
				Recharts places the arc centre with `cx`/`cy`: the middle for `full`, and 70% down for
				`semi` so the half circle fills the box.
			-->
			<Group x={centre.x} y={centre.y}>
				{#if backgroundVariant}
					<ChartBackground variant={backgroundVariant} />
				{/if}
				{@render children()}
				{#if isLoading}
					<LoadingRadialBar />
				{/if}
			</Group>
			<defs>
				<ColorGradientStyle {config} {chartId} />
			</defs>
		</Svg>
		<TooltipRender />
	</Chart>
	<LegendRender placement="middle" />
	<LegendRender placement="bottom" />
</ChartContainer>
```

`$lib/components/evilcharts/charts/layerchart-radial-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 { useRadialChart } from './radial-chart-context.svelte.js';

	const chart = useRadialChart();
	/** 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 bar.
	 *
	 * Recharts hands the radial tooltip a single item whose `name` is the bar name and whose
	 * `payload` is the row, so `nameKey` can resolve the config entry from it.
	 */
	function toPayload(row: Record<string, unknown>): TooltipPayloadItem[] {
		const valueKey = chart.valueKey;

		return [
			{
				dataKey: valueKey,
				name: String(row[chart.nameKey]),
				value: valueKey ? (row[valueKey] as number | string | null) : 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-radial-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 { useRadialChart } from './radial-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; // bar index shown by default with no hover
	} = $props();

	const chart = useRadialChart();
	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-radial-chart/types.ts`

```ts
// Constants
export const DEFAULT_INNER_RADIUS = '30%';
export const DEFAULT_OUTER_RADIUS = '100%';
export const DEFAULT_CORNER_RADIUS = 5;
export const DEFAULT_BAR_SIZE = 14;
export const LOADING_BARS = 5;
export const LOADING_ANIMATION_DURATION = 1500; // interval between skeleton data changes, in ms

/**
 * Recharts' `<RadialBar>` animation defaults, which the reference leaves switched on — it never
 * passes `isAnimationActive={false}`, so every bar sweeps out on mount.
 *
 * `RadialBar.js` interpolates `endAngle` from `startAngle` to its final value, so one progress
 * value drives the whole reveal.
 */
export const REVEAL_BEGIN = 0; // <RadialBar animationBegin>, in milliseconds
export const REVEAL_DURATION = 1500; // <RadialBar animationDuration>, in milliseconds
/** `animationEasing: "ease"` — the CSS `ease` curve. */
export const REVEAL_EASE: [number, number, number, number] = [0.25, 0.1, 0.25, 1];

/** Recharts' `<RadialBarChart margin>` default, which its maximum radius measures against. */
export const CHART_MARGIN = 5;

export type RadialVariant = 'full' | 'semi';

/**
 * The angle + centre configuration for the chart's arc shape, copied from the reference.
 *
 * Angles are in Recharts' polar space: degrees anticlockwise from 3 o'clock. `full` runs
 * 90 → −270, a whole turn clockwise from 12 o'clock; `semi` runs 180 → 0, the top half from
 * 9 o'clock round to 3 o'clock, with the centre pushed down to 70% so the arc fills the box.
 */
export function getVariantConfig(variant: RadialVariant) {
	switch (variant) {
		case 'semi':
			return { startAngle: 180, endAngle: 0, cx: 0.5, cy: 0.7 };
		case 'full':
		default:
			return { startAngle: 90, endAngle: -270, cx: 0.5, cy: 0.5 };
	}
}

/**
 * Converts a Recharts polar angle to the equivalent d3-arc angle, in radians.
 *
 * Recharts measures degrees anticlockwise from 3 o'clock; d3-arc measures radians clockwise from
 * 12 o'clock. Mapping `θ → (90 − θ)` handles both differences at once, so `90 → −270` becomes
 * `0 → 2π` and `180 → 0` becomes `−π/2 → π/2`.
 */
export const toArcAngle = (degrees: number) => ((90 - degrees) * Math.PI) / 180;

/** Resolves a Recharts radius (`"30%"` or a pixel number) against the plot's maximum radius. */
export const resolveRadius = (radius: number | string, maxRadius: number) => {
	if (typeof radius === 'number') return radius;

	const trimmed = radius.trim();
	if (trimmed.endsWith('%')) return (Number.parseFloat(trimmed) / 100) * maxRadius;

	const parsed = Number(trimmed);
	return Number.isFinite(parsed) ? parsed : maxRadius;
};

export type RadialRing = {
	row: Record<string, unknown>;
	index: number;
	name: string;
	/** Sweep start, in d3 radians. */
	startAngle: number;
	/** Sweep end, in d3 radians. */
	endAngle: number;
	innerRadius: number;
	outerRadius: number;
};

/**
 * Interpolates radial-bar angles as Recharts' `SectorsWithAnimation` does. Radii and row payloads
 * come from the target immediately; only the start and end angles tween. A newly added ring grows
 * from its target start angle.
 */
export function interpolateRings(
	previous: RadialRing[],
	target: RadialRing[],
	progress: number
): RadialRing[] {
	if (progress >= 1) return target;

	return target.map((ring, index) => {
		const previousRing = previous[index];
		if (!previousRing) {
			return {
				...ring,
				endAngle: ring.startAngle + (ring.endAngle - ring.startAngle) * progress
			};
		}

		return {
			...ring,
			startAngle: previousRing.startAngle + (ring.startAngle - previousRing.startAngle) * progress,
			endAngle: previousRing.endAngle + (ring.endAngle - previousRing.endAngle) * progress
		};
	});
}

/**
 * Ring geometry for every row, matching Recharts' radial band layout.
 *
 * Recharts lays a band scale across `[innerRadius, outerRadius]` with one band per row — **row 0
 * innermost** — and centres a `barSize`-thick bar in each band. Measured against the reference: a
 * 143px maximum radius with `innerRadius="30%"` and five rows gives bands of 20.02px, so row 0's
 * bar spans 45.9 → 59.9 and row 4's spans 125.98 → 139.98.
 */
export function getRings({
	rows,
	dataKey,
	nameKey,
	innerRadius,
	outerRadius,
	barSize,
	startAngle,
	endAngle,
	max
}: {
	rows: Record<string, unknown>[];
	dataKey: string;
	nameKey: string;
	innerRadius: number;
	outerRadius: number;
	barSize: number;
	/** Chart start angle, in d3 radians. */
	startAngle: number;
	/** Chart end angle, in d3 radians. */
	endAngle: number;
	/**
	 * Value a full sweep represents. Without it the largest row fills the arc, which is what
	 * Recharts does when no `<PolarAngleAxis domain>` pins the scale.
	 */
	max?: number;
}): RadialRing[] {
	if (rows.length === 0) return [];

	const valueOf = (row: Record<string, unknown>) => {
		const value = row[dataKey];
		return typeof value === 'number' && Number.isFinite(value) ? value : 0;
	};

	const total = max != null && max > 0 ? max : Math.max(0, ...rows.map(valueOf)) || 1;
	const step = (outerRadius - innerRadius) / rows.length;
	// Recharts centres a fixed-size bar by flooring the leftover space at the start of each radial
	// band. Keeping the fractional half-gap would shift every ring slightly outward (0.13px in the
	// loading example at 630x360).
	const bandOffset = Math.floor((step - barSize) / 2);

	return rows.map((row, index) => {
		const ringInnerRadius = innerRadius + step * index + bandOffset;

		return {
			row,
			index,
			name: String(row[nameKey]),
			startAngle,
			endAngle: startAngle + (endAngle - startAngle) * (valueOf(row) / total),
			innerRadius: ringInnerRadius,
			outerRadius: ringInnerRadius + barSize
		};
	});
}
```
        
      
       
        ### Add the chart component.
        

The chart needs these components to render. 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 radial chart is composable. `<EvilRadialChart>` is the container, and every part hangs off it as a compound member — `<EvilRadialChart.Legend>`, `<EvilRadialChart.Tooltip>`, and a `<EvilRadialChart.RadialBar>` — so a single import gives you the whole chart. `isClickable` lives on `<EvilRadialChart.RadialBar>`, so styling and interactivity stay with the series.

```svelte
<script lang="ts">
	import { EvilRadialChart } from '$lib/components/evilcharts/charts/layerchart-radial-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
<EvilRadialChart {data} nameKey="browser" config={chartConfig} variant="full">
	<EvilRadialChart.Legend isClickable />
	<EvilRadialChart.Tooltip />
	<EvilRadialChart.RadialBar dataKey="visitors" isClickable />
</EvilRadialChart>
```

### Interactive Selection

Add `isClickable` to `<EvilRadialChart.RadialBar>` (and `<EvilRadialChart.Legend>`) to make bars selectable, then handle selection with the `onSelectionChange` callback on `<EvilRadialChart>`:

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

### Loading State

### isLoading='true'

```svelte
<script lang="ts">
	import { EvilRadialChart } from '$lib/components/evilcharts/charts/layerchart-radial-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>

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

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




## Examples

Radial charts in different configurations. Customize `variant`, `innerRadius`, `outerRadius`, and more.

### Semi-Circle Variant

### variant='semi'

```svelte
<script lang="ts">
	import { EvilRadialChart } from '$lib/components/evilcharts/charts/layerchart-radial-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>

<EvilRadialChart
	class="h-full w-full p-4"
	{data}
	nameKey="browser"
	config={chartConfig}
	variant="semi"
>
	<EvilRadialChart.Legend />
	<EvilRadialChart.Tooltip />
	<EvilRadialChart.RadialBar dataKey="visitors" />
</EvilRadialChart>
```
>  
  

Set `variant="semi"` for a half-circle chart — compact, and ideal for progress or gauges.




### Gradient Colors

### gradient colors

```svelte
<script lang="ts">
	import { EvilRadialChart } from '$lib/components/evilcharts/charts/layerchart-radial-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: ['#ff6b6b', '#feca57', '#48dbfb'], // Coral -> Gold -> Electric Blue // [!code highlight]
				dark: ['#ff7979', '#ffeaa7', '#74b9ff'] // [!code highlight]
			}
		},
		safari: {
			label: 'Safari',
			colors: {
				light: ['#a29bfe', '#fd79a8', '#fdcb6e'], // Lavender -> Pink -> Sunflower // [!code highlight]
				dark: ['#b8b5ff', '#ff9ff3', '#ffeaa7'] // [!code highlight]
			}
		},
		firefox: {
			label: 'Firefox',
			colors: {
				light: ['#00d2d3', '#54a0ff', '#5f27cd'], // Turquoise -> Blue -> Purple // [!code highlight]
				dark: ['#01e2e3', '#74b9ff', '#7c3aed'] // [!code highlight]
			}
		},
		edge: {
			label: 'Edge',
			colors: {
				light: ['#ff9f43', '#ee5a24', '#b71540'], // Tangerine -> Vermillion -> Wine // [!code highlight]
				dark: ['#ffbe76', '#f0932b', '#e74c3c'] // [!code highlight]
			}
		},
		other: {
			label: 'Other',
			colors: {
				light: ['#1dd1a1', '#10ac84', '#01a3a4'], // Mint -> Jungle -> Teal // [!code highlight]
				dark: ['#55efc4', '#00b894', '#00cec9'] // [!code highlight]
			}
		}
	} satisfies ChartConfig;
</script>

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

## API Reference

The props below are grouped by the part they belong to.

### EvilRadialChart

The root container. It owns the data, shared selection state, loading skeleton, and arc shape. Everything visual is composed as its children.


  ### `data` (required)

type: `TData[]`

Array of objects, one per radial bar (`TData extends Record<string, unknown>`).
  ### `config` (required)

type: `ChartConfig`

Defines the chart's bars. Each key matches a value from your `nameKey` field, with its colors.
  ### `nameKey` (required)

type: `keyof TData & string`

Data key for bar names — string values used for labels and the legend.
  ### `children` (required)

type: `Snippet`

The composed chart parts — `<Legend />`, `<Tooltip />`, and a `<RadialBar />`.
  ### `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.
  ### `variant`

type: `"full" | "semi"` · default: `"full"`

Arc shape. `"full"` is a full circle (360°); `"semi"` is a half circle (180°).
  ### `max`

type: `number`

Value a full sweep represents. Without it the scale is derived from the data, so the largest bar always fills the arc — set it (e.g. `100`) for gauges, where a single value has to read against a fixed total.
  ### `innerRadius`

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

Inner radius of the bars — a number (pixels) or percentage string.
  ### `outerRadius`

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

Outer radius of the bars — a number (pixels) or percentage string.
  ### `defaultSelectedDataKey`

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

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

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

Fires when a bar is selected or deselected by clicking a clickable `<RadialBar />` or `<Legend />` entry. Receives `dataKey` (bar name) and `value` (bar value), or `null` when deselected.
  ### `isLoading`

type: `boolean` · default: `false`

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

type: `BackgroundVariant`

Background pattern shown behind the chart.
  ### `chartProps`

type: `Record<string, unknown>`

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


### RadialBar

The radial bar series — each data row becomes one bar.


  ### `dataKey` (required)

type: `string`

Data key for bar values — the numbers that determine bar size.
  ### `cornerRadius`

type: `number` · default: `5`

Corner radius of each bar, in pixels.
  ### `barSize`

type: `number` · default: `14`

Thickness of each bar, in pixels.
  ### `showBackground`

type: `boolean` · default: `true`

Whether to render the background track (the unfilled portion of each bar).
  ### `isClickable`

type: `boolean` · default: `false`

Lets users click bars to select/deselect them. Unselected bars dim while a selection is active.
  ### `radialBarProps`

type: `Record<string, unknown>`

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


### Tooltip

The hover tooltip, labeling each bar by name. Render it to show a tooltip; omit it for none.


  ### `variant`

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

The tooltip's visual style.
  ### `roundness`

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

The tooltip's border-radius.
  ### `defaultIndex`

type: `number`

Shows the tooltip by default at this data point index.


### Legend

The bar legend. With `isClickable`, each entry toggles its bar's selection. Render it to show a legend; omit it for none.


  ### `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`

When enabled, each entry toggles its bar's selection, driving the shared state read by `<RadialBar />`.

