
### Basic Chart

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

	const data = [
		{ month: 'January', desktop: 342, mobile: 184 },
		{ month: 'February', desktop: 876, mobile: 491 },
		{ month: 'March', desktop: 512, mobile: 290 },
		{ month: 'April', desktop: 629, mobile: 391 },
		{ month: 'May', desktop: 458, mobile: 309 },
		{ month: 'June', desktop: 781, mobile: 449 },
		{ month: 'July', desktop: 394, mobile: 234 },
		{ month: 'August', desktop: 925, mobile: 557 },
		{ month: 'September', desktop: 647, mobile: 367 },
		{ month: 'October', desktop: 532, mobile: 357 },
		{ month: 'November', desktop: 803, mobile: 515 },
		{ month: 'December', desktop: 271, mobile: 149 }
	];

	const chartConfig = {
		desktop: {
			label: 'Desktop',
			colors: {
				light: ['#047857'],
				dark: ['#10b981']
			}
		},
		mobile: {
			label: 'Mobile',
			colors: {
				light: ['#be123c'],
				dark: ['#f43f5e']
			}
		}
	} satisfies ChartConfig;
</script>

<EvilBarChart {data} config={chartConfig} class="h-full w-full p-4" xDataKey="month">
	<EvilBarChart.Grid />
	<EvilBarChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilBarChart.Brush formatLabel={(value) => String(value).substring(0, 3)} />
	<EvilBarChart.Legend isClickable />
	<EvilBarChart.Tooltip />
	<EvilBarChart.Bar dataKey="desktop" variant="default" isClickable />
	<EvilBarChart.Bar dataKey="mobile" variant="default" isClickable />
</EvilBarChart>
```

## Installation


  
  
    ### npm

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

### yarn

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

### bun

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

### pnpm

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

```bash
npm install layerchart @humanspeak/svelte-motion
```

### yarn

```bash
yarn add layerchart @humanspeak/svelte-motion
```

### bun

```bash
bun add layerchart @humanspeak/svelte-motion
```

### pnpm

```bash
pnpm add layerchart @humanspeak/svelte-motion
```
        
      
      
        ### Copy the code into your project.
         

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


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

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

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

const BAR_CHART_KEY = Symbol('evilcharts.bar-chart');

type Options = {
	config: () => ChartConfig;
	/** Rows currently rendered by the chart (brush-filtered, or the loading skeleton). */
	data: () => Record<string, unknown>[];
	/** Resolved category key for the x scale. */
	xKey: () => string | undefined;
	/** Series keys rendered by the chart, in config order. */
	seriesKeys: () => string[];
	/** Data keys of the `<Bar />` children currently rendered, in registration order. */
	barKeys: () => string[];
	animationType: () => BarAnimationType;
	isStacked: () => boolean;
	isPercent: () => boolean;
	isHorizontal: () => boolean;
	barRadius: () => number;
	/** Gap between bars sharing a category, in pixels. Recharts' default is 4. */
	barGap: () => number | undefined;
	/** Gap on each side of a category. Recharts' default is `"10%"`. */
	barCategoryGap: () => number | undefined;
	/** Timestamp the chart mounted — anchors the one-shot grow-in. */
	introStartedAt: () => number;
	renderStyle: () => RenderStyle;
	ditherVariant: () => DitherVariant;
	/** Whether the pointer is currently over the chart. */
	isMouseInChart: () => boolean;
	/** The row the pointer is currently over, so a bar can tell if it is the active one. */
	activeRow: () => Record<string, unknown> | undefined;
	isLoading: () => boolean;
	chartId: () => string;
	selectedDataKey: () => string | null;
	selectDataKey: (dataKey: string | null) => void;
	/**
	 * Called by `<XAxis dataKey>` on mount.
	 *
	 * Recharts reads the category key off `<XAxis dataKey>`; LayerChart needs it on the root's
	 * `x` accessor, so the axis pushes it up rather than the root reading down. Keeping the
	 * state on the root avoids a circular dependency between `xKey` and this context.
	 */
	/**
	 * Called by each `<Bar />` so the root knows how many bars share a category.
	 *
	 * Recharts divides a category between the bars it finds in the tree; the port needs the same
	 * count to place them, so the bars announce themselves.
	 */
	registerBar: (token: string, dataKey: string | undefined) => void;
	registerXAxisDataKey: (token: string, dataKey: string | undefined) => void;
	/**
	 * Called by `<XAxis />` / `<YAxis />` so the root can reserve plot-area space for them.
	 *
	 * Recharts sizes the plot from the axes it renders (default chart margin 5 on every side, plus
	 * a 30px band for an `<XAxis>` and a 60px gutter for a `<YAxis>`). LayerChart takes `padding`
	 * as a single explicit value, so the axes announce themselves and the root derives it.
	 */
	registerAxis: (token: string, axis: 'x' | 'y', present: boolean) => void;
};

/**
 * Shared state for every part of the chart. Lifted into <EvilBarChart /> so that
 * <Bar />, <XAxis />, <Legend />, and friends can read it without prop drilling.
 * Sub-components are composed freely — the provider is the single source of truth.
 */
export class BarChartContext {
	#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 xKey() {
		return this.#options.xKey();
	}
	get seriesKeys() {
		return this.#options.seriesKeys();
	}
	get barKeys() {
		return this.#options.barKeys();
	}
	get animationType() {
		return this.#options.animationType();
	}
	get isStacked() {
		return this.#options.isStacked();
	}
	get isPercent() {
		return this.#options.isPercent();
	}
	get isHorizontal() {
		return this.#options.isHorizontal();
	}
	get barRadius() {
		return this.#options.barRadius();
	}
	get barGap() {
		return this.#options.barGap();
	}
	get barCategoryGap() {
		return this.#options.barCategoryGap();
	}
	get introStartedAt() {
		return this.#options.introStartedAt();
	}
	get renderStyle() {
		return this.#options.renderStyle();
	}
	get ditherVariant() {
		return this.#options.ditherVariant();
	}
	get isMouseInChart() {
		return this.#options.isMouseInChart();
	}
	get activeRow() {
		return this.#options.activeRow();
	}
	get dataLength() {
		return this.#options.data().length;
	}
	get isLoading() {
		return this.#options.isLoading();
	}
	get chartId() {
		return this.#options.chartId();
	}
	get selectedDataKey() {
		return this.#options.selectedDataKey();
	}

	selectDataKey = (dataKey: string | null) => {
		this.#options.selectDataKey(dataKey);
	};

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

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

	registerAxis = (token: string, axis: 'x' | 'y', present: boolean) => {
		this.#options.registerAxis(token, axis, present);
	};
}

export function setBarChartContext(options: Options) {
	const context = new BarChartContext(options);
	setContext(BAR_CHART_KEY, context);
	return context;
}

/** Reads the chart context, throwing a helpful error when used outside <EvilBarChart /> */
export function useBarChart(): BarChartContext {
	const context = getContext<BarChartContext | undefined>(BAR_CHART_KEY);

	if (!context) {
		throw new Error('Bar chart parts (<Bar />, <XAxis />, …) must be used within <EvilBarChart />');
	}

	return context;
}
```

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

```svelte
<script lang="ts" generics="TData extends Record<string, unknown>">
	/**
	 * Root of the composable bar chart. Owns the data, the shared context, the
	 * loading skeleton, and the optional zoom brush. Everything visual — axes,
	 * grid, tooltip, legend, and the bars themselves — is composed as children,
	 * so a consumer renders exactly the parts they need.
	 */
	import { Chart, Html, Svg, type ChartState } from 'layerchart';
	import { untrack, type Snippet } from 'svelte';
	import {
		ChartContainer,
		LOADING_CATEGORY_DATA_KEY,
		LoadingIndicator,
		type ChartAccessibility,
		type ChartConfig
	} from '../../ui/layerchart-chart/index.js';
	import {
		EvilBrush,
		EvilBrushState,
		setBrushSlotContext
	} from '../../ui/layerchart-brush/index.js';
	import { ChartBackground, type BackgroundVariant } from '../../ui/layerchart-background/index.js';
	import { setBarChartContext } from './bar-chart-context.svelte.js';
	import {
		DitherDomLayer,
		type DitherBloom,
		type DitherVariant,
		type RenderStyle
	} from '../../ui/layerchart-dither/index.js';
	import LegendRender from './legend-render.svelte';
	import LoadingBar from './loading/loading-bar.svelte';
	import { LoadingDataState } from './loading/use-loading-data.svelte.js';
	import TooltipRender from './tooltip-render.svelte';
	import { SvelteMap, SvelteSet } from 'svelte/reactivity';
	import {
		DEFAULT_BAR_RADIUS,
		LOADING_BAR_DATA_KEY,
		type BarAnimationType,
		type BarLayout,
		type StackType
	} from './types.js';

	let {
		config,
		data,
		children,
		class: className,
		chartProps,
		accessibility,
		stackType = 'default',
		layout = 'vertical',
		barRadius = DEFAULT_BAR_RADIUS,
		animationType = 'left-to-right',
		barGap,
		barCategoryGap,
		backgroundVariant,
		defaultSelectedDataKey = null,
		onSelectionChange,
		isLoading = false,
		loadingBars,
		xDataKey,
		initialDimension = { width: 320, height: 200 },
		renderStyle = 'svg',
		ditherVariant = 'gradient',
		ditherCellSize = 2,
		bloom = 'off'
	}: {
		config: ChartConfig; // series colors + labels
		data: TData[]; // rows rendered by the chart
		children: Snippet; // composed parts — <Bar />, <XAxis />, <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
		stackType?: StackType; // how multiple bars combine
		layout?: BarLayout; // orientation of the bars
		barRadius?: number; // default corner radius for every <Bar />
		animationType?: BarAnimationType; // default grow-in order for every <Bar />
		barGap?: number; // gap between bars within the same category
		barCategoryGap?: number; // gap between categories of bars
		backgroundVariant?: BackgroundVariant; // background pattern drawn behind the chart
		defaultSelectedDataKey?: string | null; // series selected on first render
		onSelectionChange?: (selectedDataKey: string | null) => void; // fires when the selected series changes
		isLoading?: boolean; // shows the animated loading skeleton
		loadingBars?: number; // number of bars in the loading skeleton
		xDataKey?: keyof TData & string; // x-axis key — also used by the <Brush /> footer
		initialDimension?: { width: number; height: number }; // zero-size/first-render fallback
		renderStyle?: RenderStyle;
		ditherVariant?: DitherVariant;
		ditherCellSize?: number;
		bloom?: DitherBloom;
	} = $props();

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

	/**
	 * Anchors the grow-in to a fixed moment so it plays exactly once — re-renders read elapsed
	 * time from here instead of replaying.
	 */
	let introStartedAt = $state(Date.now());
	let previousLoading = untrack(() => isLoading);

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

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

	/** LayerChart's chart state, read for the row the pointer is currently over. */
	let layerContext = $state<ChartState<Record<string, unknown>> | undefined>(undefined);

	const loading = new LoadingDataState({
		isLoading: () => isLoading,
		loadingBars: () => loadingBars ?? 12
	});

	const brush = new EvilBrushState({ data: () => data as Record<string, unknown>[] });

	// The <Brush> child is config-only: its presence turns the footer on. The reference pulls it
	// out of `children`; Svelte registers it into this context instead.
	const brushSlot = setBrushSlotContext();
	const showBrush = $derived(brushSlot.present);

	const isPercent = $derived(stackType === 'percent');
	const isStacked = $derived(stackType === 'stacked' || isPercent);
	const isHorizontal = $derived(layout === 'horizontal');

	/** Category key pushed up by the rendered `<XAxis dataKey>`, when there is one. */
	let registeredXKey = $state<string | undefined>(undefined);
	let registeredXKeyToken: string | null = null;

	/** Data keys of the rendered `<Bar />` children, so a category can be divided between them. */
	// `SvelteMap` for the same reactive mutation behavior as `axesPresent` below.
	const barKeyByToken = new SvelteMap<string, string>();
	const barKeys = $derived([...barKeyByToken.values()]);

	/** Which axes are rendered, so the plot reserves the space Recharts does. */
	// `SvelteSet`, not a plain `Set` in `$state`: `$state` proxies objects and arrays but not
	// `Map`/`Set`, so `.add()` / `.delete()` would not notify and the padding would never
	// pick up an axis.
	const axesPresent = { x: new SvelteSet<string>(), y: new SvelteSet<string>() };

	const CHART_MARGIN = 5; // Recharts' default <BarChart margin>
	const X_AXIS_HEIGHT = 30; // Recharts' default <XAxis height>
	const Y_AXIS_WIDTH = 60; // Recharts' default <YAxis width>

	// Recharts reserves the legend wrapper's full 32px height inside the chart surface.
	const EDGE_LEGEND_HEIGHT = 32;
	let barContext: ReturnType<typeof setBarChartContext>;
	const edgeLegendPlacement = $derived.by(() => {
		if (isLoading || !barContext) return null;
		const align = barContext.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 +
			(!isLoading && axesPresent.x.size > 0 ? X_AXIS_HEIGHT : 0) +
			(edgeLegendPlacement === 'bottom' ? EDGE_LEGEND_HEIGHT : 0),
		left: CHART_MARGIN + (!isLoading && axesPresent.y.size > 0 ? Y_AXIS_WIDTH : 0)
	});

	const configuredKeys = $derived(Object.keys(config));
	// Recharts derives domains, legends and tooltips from rendered graphical children. Config is
	// only presentation metadata, so unused config entries must never become phantom series.
	const seriesKeys = $derived(barKeys);
	const displayData = $derived(showBrush && !isLoading ? brush.visibleData : data);
	const chartData = $derived(
		(isLoading ? loading.loadingData : displayData) as Record<string, unknown>[]
	);
	const ditherAnimationDuration = $derived(500 + Math.max(0, chartData.length - 1) * 50);

	/** Category key for the band scale, resolved from the mounted axis before falling back to data. */
	const fallbackXKey = $derived(
		Object.keys(chartData[0] ?? {}).find(
			(key) => !configuredKeys.includes(key) && key !== LOADING_BAR_DATA_KEY
		)
	);
	const xKey = $derived(
		isLoading ? LOADING_CATEGORY_DATA_KEY : (xDataKey ?? registeredXKey ?? fallbackXKey)
	);

	const series = $derived(
		isLoading
			? [{ key: LOADING_BAR_DATA_KEY, value: LOADING_BAR_DATA_KEY }]
			: seriesKeys.map((key) => ({ key, value: key }))
	);

	// The baseline and `nice` rounding belong to the value axis, which the layout picks.
	/**
	 * Grouped bars are positioned by `getBarPositions` rather than by a nested band scale, so the
	 * series only ever `overlap` here.
	 */
	const seriesLayout = $derived(
		isPercent ? ('stackExpand' as const) : isStacked ? ('stack' as const) : ('overlap' as const)
	);

	barContext = setBarChartContext({
		config: () => config,
		data: () => chartData,
		xKey: () => xKey,
		seriesKeys: () => seriesKeys,
		barKeys: () => barKeys,
		animationType: () => animationType,
		isStacked: () => isStacked,
		isPercent: () => isPercent,
		isHorizontal: () => isHorizontal,
		barRadius: () => barRadius,
		barGap: () => barGap,
		barCategoryGap: () => barCategoryGap,
		introStartedAt: () => introStartedAt,
		renderStyle: () => renderStyle,
		ditherVariant: () => ditherVariant,
		isMouseInChart: () => isMouseInChart,
		activeRow: () => layerContext?.tooltip?.data as Record<string, unknown> | undefined,
		isLoading: () => isLoading,
		chartId: () => chartId,
		selectedDataKey: () => selectedDataKey,
		selectDataKey: (next) => {
			selectedDataKey = next;
			onSelectionChange?.(next);
		},
		registerBar: (token, key) => {
			if (key === undefined) barKeyByToken.delete(token);
			else barKeyByToken.set(token, key);
		},
		registerXAxisDataKey: (token, key) => {
			// Ignore a stale teardown from LayerChart's mount-time remount.
			if (key === undefined && registeredXKeyToken !== token) return;
			registeredXKeyToken = key === undefined ? null : token;
			registeredXKey = key;
		},
		registerAxis: (token, axis, present) => {
			if (present) axesPresent[axis].add(token);
			else axesPresent[axis].delete(token);
		}
	});
</script>

<ChartContainer
	{config}
	{initialDimension}
	{accessibility}
	bind:dimension={chartDimension}
	class={className}
>
	<LoadingIndicator {isLoading} />
	<LegendRender placement="top" />
	<!-- The reference tracks pointer enter/leave on the chart to drive the hover highlight. -->
	<div
		class="flex min-h-0 w-full flex-1 flex-col"
		onpointerenter={() => (isMouseInChart = true)}
		onpointerleave={() => (isMouseInChart = false)}
		role="presentation"
	>
		<Chart
			width={chartDimension.width}
			height={chartDimension.height}
			bind:context={layerContext}
			data={chartData}
			x={isHorizontal ? undefined : xKey}
			y={isHorizontal ? xKey : undefined}
			valueAxis={isHorizontal ? 'x' : 'y'}
			{series}
			{seriesLayout}
			bandPadding={0}
			xBaseline={isHorizontal ? 0 : undefined}
			yBaseline={isHorizontal ? undefined : 0}
			xNice={isHorizontal}
			yNice={!isHorizontal}
			{padding}
			tooltipContext={{ mode: 'band' }}
			class="h-full w-full"
			{...chartProps}
		>
			{#if renderStyle === 'dither'}
				<Html pointerEvents={false} clip zIndex={0}>
					<DitherDomLayer
						{ditherVariant}
						cellSize={ditherCellSize}
						{bloom}
						paused={isLoading}
						animationDuration={ditherAnimationDuration}
						animationRevision={introStartedAt}
					/>
				</Html>
			{/if}
			<Svg>
				{#if backgroundVariant}
					<ChartBackground variant={backgroundVariant} />
				{/if}
				{@render children()}
				{#if isLoading}
					<LoadingBar {chartId} onShimmerExit={loading.onShimmerExit} />
				{/if}
			</Svg>
			<TooltipRender />
		</Chart>
	</div>
	<LegendRender placement="middle" />
	<LegendRender placement="bottom" />

	{#snippet footer()}
		{#if showBrush && !isLoading}
			<EvilBrush
				data={data as Record<string, unknown>[]}
				chartConfig={config}
				{xDataKey}
				variant="bar"
				{barRadius}
				height={brushSlot.slot?.height}
				formatLabel={brushSlot.slot?.formatLabel}
				stacked={isStacked}
				skipStyle
				class="mt-1"
				startIndex={brush.brushProps.startIndex}
				endIndex={brush.brushProps.endIndex}
				onChange={(range) => {
					brush.brushProps.onChange(range);
					brushSlot.slot?.onChange?.(range);
				}}
			/>
		{/if}
	{/snippet}
</ChartContainer>
```

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

```svelte
<script lang="ts">
	/**
	 * A single bar series. Each <Bar /> is fully self-contained: it generates its
	 * own gradient/pattern definitions under a unique id, so any number of bars —
	 * each with its own variant, radius, glow, and clickability — can live in one
	 * chart without style collisions.
	 */
	import { Bar as LayerBar, getChartContext } from 'layerchart';
	import { useReducedMotion } from '@humanspeak/svelte-motion';
	import { useBarChart } from './bar-chart-context.svelte.js';
	import ColorGradient from './defs/color-gradient.svelte';
	import BufferHatchedPattern from './defs/buffer-hatched-pattern.svelte';
	import DuotonePattern from './defs/duotone-pattern.svelte';
	import DuotoneReversePattern from './defs/duotone-reverse-pattern.svelte';
	import GlowFilter from './defs/glow-filter.svelte';
	import GradientPattern from './defs/gradient-pattern.svelte';
	import HatchedPattern from './defs/hatched-pattern.svelte';
	import StrippedPattern from './defs/stripped-pattern.svelte';
	import { getBarPositions, type BarInsets } from '../../ui/layerchart-chart/bar-geometry.js';
	import AnimatedGrow from '../../ui/layerchart-chart/animated-grow.svelte';
	import type { DitherVariant } from '../../ui/layerchart-dither/index.js';
	import { getBarGrowAnimation, getBarOpacity, getVariantFill } from './helpers.js';
	import type { BarAnimationType, BarVariant } from './types.js';

	let {
		dataKey,
		variant = 'default',
		radius,
		animationType,
		isClickable = false,
		enableHoverHighlight = false,
		glowing = false,
		bufferBar = false,
		barProps,
		ditherVariant
	}: {
		dataKey: string; // series key — must exist on the data and config
		variant?: BarVariant; // fill style for this bar only
		radius?: number; // corner radius — falls back to the chart default
		animationType?: BarAnimationType; // grow-in order — falls back to the chart default
		isClickable?: boolean; // lets this bar be selected by clicking it
		enableHoverHighlight?: boolean; // dims this bar while another bar is hovered
		glowing?: boolean; // applies a soft outer glow to this bar
		bufferBar?: boolean; // renders the last data point as a hatched "buffer" bar
		barProps?: Record<string, unknown>; // escape hatch for raw LayerChart Bar props
		ditherVariant?: DitherVariant; // ordered-dither texture override
	} = $props();

	const chart = useBarChart();
	/** LayerChart's own context, for the category band this bar is placed in. */
	const layer = getChartContext();
	const id = $props.id(); // unique id scopes this bar's style defs

	// Announce this bar so the root can divide the category between every bar it finds,
	// the way Recharts does.
	$effect.pre(() => {
		chart.registerBar(id, dataKey);
		return () => chart.registerBar(id, undefined);
	});
	// Devices set to "reduce motion" skip the grow-in animation entirely
	const shouldReduceMotion = useReducedMotion();

	const resolvedRadius = $derived(radius ?? chart.barRadius);
	const isSelected = $derived(chart.selectedDataKey === dataKey);

	// The grow-in is a per-frame animation — heavier than a static chart — so
	// `"none"` and the OS reduce-motion preference both opt out of it.
	const revealType = $derived<BarAnimationType>(
		shouldReduceMotion.current ? 'none' : (animationType ?? chart.animationType)
	);

	const isStripped = $derived(variant === 'stripped');
	// Stripped bars round only their top corners; every other variant rounds all four
	const rounded = $derived(isStripped ? ('top' as const) : ('all' as const));

	const filter = $derived(glowing ? `url(#${id}-bar-glow-${dataKey})` : undefined);
	const isDither = $derived(chart.renderStyle === 'dither');
	const resolvedDitherVariant = $derived(ditherVariant ?? chart.ditherVariant);

	/**
	 * This bar's slice of the category, in pixels.
	 *
	 * The chart runs with `bandPadding={0}`, so the band and the step are the same width — the
	 * shape Recharts' arithmetic assumes. `getBarPositions` then divides it exactly as Recharts
	 * does (category gap, inter-bar gaps, whole-pixel widths) and the result is applied as insets,
	 * rather than letting LayerChart nest a second band scale.
	 */
	const bandSize = $derived(
		(chart.isHorizontal ? layer.yScale.bandwidth?.() : layer.xScale.bandwidth?.()) ?? 0
	);

	const slot = $derived.by(() => {
		// Stacked series share one slot, exactly as a Recharts `stackId` does.
		const count = chart.isStacked ? 1 : Math.max(1, chart.barKeys.length);
		const index = chart.isStacked ? 0 : Math.max(0, chart.barKeys.indexOf(dataKey));

		return getBarPositions({
			bandSize,
			count,
			barGap: chart.barGap,
			barCategoryGap: chart.barCategoryGap
		})[index];
	});

	/** Leading/trailing insets that place the bar in its slot along the category axis. */
	const bandInsets = $derived.by<BarInsets>(() => {
		if (!slot) return {};
		const trailing = Math.max(0, bandSize - slot.offset - slot.size);
		return chart.isHorizontal
			? { top: slot.offset, bottom: trailing }
			: { left: slot.offset, right: trailing };
	});

	const cursorClass = $derived(isClickable || enableHoverHighlight ? 'cursor-pointer' : undefined);

	/**
	 * Length of this bar's painted body along the value axis, in pixels.
	 *
	 * The stripped variant's cap is a 2px strip floating 4px clear of the bar's top edge. LayerChart
	 * re-centres a bar when given an explicit `height`/`width` (`Bar.shared` does
	 * `y += (height - props.height) / 2`), so the cap is expressed as insets measured against the
	 * value scale instead.
	 *
	 * A stacked bar's segment runs from the running total below it to the total including it, which
	 * is how LayerChart stacks the series — in config order.
	 */
	function bodyLength(row: Record<string, unknown>) {
		const scale = chart.isHorizontal ? layer.xScale : layer.yScale;
		const valueOf = (key: string) => {
			const value = row[key];
			return typeof value === 'number' && Number.isFinite(value) ? value : 0;
		};

		if (!chart.isStacked) {
			return Math.abs(Number(scale(valueOf(dataKey))) - Number(scale(0)));
		}

		const keys = chart.barKeys.length > 0 ? chart.barKeys : chart.seriesKeys;
		const below = keys
			.slice(0, Math.max(0, keys.indexOf(dataKey)))
			.reduce((total, key) => total + valueOf(key), 0);

		return Math.abs(Number(scale(below + valueOf(dataKey))) - Number(scale(below)));
	}

	/** Insets that turn the bar's own box into the 2px cap sitting 4px above it. */
	function capInsets(row: Record<string, unknown>) {
		const trailing = Math.max(0, bodyLength(row) + 2);
		return chart.isHorizontal
			? { ...bandInsets, left: -4, right: trailing }
			: { ...bandInsets, top: -4, bottom: trailing };
	}

	function select() {
		if (!isClickable) return;
		// Clicking the selected bar clears the selection, otherwise selects it
		chart.selectDataKey(isSelected ? null : dataKey);
	}

	/** The last row renders as the hatched buffer bar when `bufferBar` is set. */
	function isLastBar(index: number) {
		return bufferBar && chart.dataLength > 0 && index === chart.dataLength - 1;
	}

	/**
	 * Everything each row needs to paint, resolved in one derivation.
	 *
	 * Template declaration tags inside a keyed `{#each}` do not reliably re-derive
	 * when an outer value changes, which is what froze the tooltip and the selection dimming
	 * elsewhere in this port.
	 */
	const rows = $derived(
		chart.data.map((row, index) => {
			const last = isLastBar(index);

			return {
				row,
				last,
				grow: getBarGrowAnimation(
					revealType,
					index,
					chart.dataLength,
					chart.isHorizontal,
					chart.introStartedAt
				),
				fill: last ? `url(#${id}-buffer-hatched-${dataKey})` : getVariantFill(variant, id, dataKey),
				fillOpacity: getBarOpacity({
					isClickable,
					selectedDataKey: chart.selectedDataKey,
					dataKey,
					enableHoverHighlight,
					isMouseInChart: chart.isMouseInChart,
					isActive: chart.activeRow === row
				}),
				capInset: isStripped ? capInsets(row) : undefined
			};
		})
	);
</script>

<!-- The root renders the skeleton bars while loading, so real bars step aside -->
{#if !chart.isLoading}
	<!--
		One `<Bar>` per row rather than a single `<Bars>`, so each bar can be wrapped in its own
		staggered grow-in. LayerChart still computes every bar's geometry from the chart scales,
		including stacking and grouping.
	-->
	{#each rows as { row, grow, fill, fillOpacity, last, capInset }, index (index)}
		<g class={cursorClass} onclick={select} role="presentation">
			<!-- Transparent twin outside the grow wrapper keeps the column hoverable from frame one -->
			<LayerBar
				data={row}
				seriesKey={dataKey}
				radius={resolvedRadius}
				{rounded}
				fill="transparent"
				insets={bandInsets}
				motion="none"
				tooltip
			/>
			{#if grow}
				<AnimatedGrow animation={grow}>
					{@render painted(row, fill, fillOpacity, last, capInset)}
				</AnimatedGrow>
			{:else}
				{@render painted(row, fill, fillOpacity, last, capInset)}
			{/if}
		</g>
	{/each}

	<defs>
		<ColorGradient {id} {dataKey} config={chart.config} />
		{#if variant === 'hatched'}
			<HatchedPattern {id} {dataKey} />
		{/if}
		{#if variant === 'duotone'}
			<DuotonePattern {id} {dataKey} config={chart.config} />
		{/if}
		{#if variant === 'duotone-reverse'}
			<DuotoneReversePattern {id} {dataKey} config={chart.config} />
		{/if}
		{#if variant === 'gradient'}
			<GradientPattern {id} {dataKey} />
		{/if}
		{#if variant === 'stripped'}
			<StrippedPattern {id} {dataKey} />
		{/if}
		{#if bufferBar}
			<BufferHatchedPattern {id} {dataKey} />
		{/if}
		{#if glowing}
			<GlowFilter {id} {dataKey} />
		{/if}
	</defs>
{/if}

{#snippet painted(
	row: Record<string, unknown>,
	fill: string,
	fillOpacity: number,
	last: boolean,
	capInset: BarInsets | undefined
)}
	<!--
		The painted bar. `insets` shortens it by the reference's 3px so the bar never touches the
		next stacked segment, and the stripped variant adds a solid cap above it.
	-->
	<LayerBar
		data={row}
		seriesKey={dataKey}
		radius={resolvedRadius}
		{rounded}
		fill={isDither ? 'transparent' : fill}
		{fillOpacity}
		{filter}
		stroke={last ? `url(#${id}-colors-${dataKey})` : undefined}
		strokeWidth={last ? 1 : undefined}
		data-evil-dither-mark={isDither ? 'fill' : undefined}
		data-evil-dither-key={isDither ? dataKey : undefined}
		data-evil-dither-variant={isDither ? (last ? 'hatched' : resolvedDitherVariant) : undefined}
		data-evil-dither-glow={isDither && glowing ? 'true' : undefined}
		insets={{ ...bandInsets, ...(chart.isHorizontal ? { right: 3 } : { bottom: 3 }) }}
		motion="none"
		{...barProps}
	/>
	{#if isStripped}
		<!--
			The stripped variant's solid cap: a fixed 2px strip sitting 4px clear of the bar's top
			edge, exactly as the reference draws it. `height`/`width` pin the strip's thickness and
			the negative inset lifts it off the bar.
		-->
		<LayerBar
			data={row}
			seriesKey={dataKey}
			radius={1}
			rounded="all"
			fill={isDither ? 'transparent' : `url(#${id}-colors-${dataKey})`}
			data-evil-dither-mark={isDither ? 'fill' : undefined}
			data-evil-dither-key={isDither ? dataKey : undefined}
			data-evil-dither-variant={isDither ? 'solid' : undefined}
			insets={capInset}
			motion="none"
		/>
	{/if}
{/snippet}
```

`$lib/components/evilcharts/charts/layerchart-bar-chart/defs/buffer-hatched-pattern.svelte`

```svelte
<script lang="ts">
	/** Hatched diagonal lines with no background fill, used for the buffer bar. */
	let { id, dataKey }: { id: string; dataKey: string } = $props();
</script>

<pattern
	id={`${id}-buffer-hatched-mask-pattern`}
	x="0"
	y="0"
	width="5"
	height="5"
	patternUnits="userSpaceOnUse"
	patternTransform="rotate(-45)"
>
	<rect width="5" height="5" fill="black" fill-opacity={0} />
	<rect width="1" height="5" fill="white" fill-opacity={1} />
</pattern>
<mask id={`${id}-buffer-hatched-mask-${dataKey}`}>
	<rect width="100%" height="100%" fill={`url(#${id}-buffer-hatched-mask-pattern)`} />
</mask>
<pattern
	id={`${id}-buffer-hatched-${dataKey}`}
	patternUnits="userSpaceOnUse"
	width="100%"
	height="100%"
>
	<rect
		width="100%"
		height="100%"
		fill={`url(#${id}-colors-${dataKey})`}
		mask={`url(#${id}-buffer-hatched-mask-${dataKey})`}
	/>
</pattern>
```

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

```svelte
<script lang="ts">
	/**
	 * Vertical top-to-bottom color gradient for a series. Always rendered — every
	 * fill variant and the buffer-bar stroke paint from this single gradient.
	 */
	import { getColorsCount } from '../../../ui/layerchart-chart/colors.js';
	import type { ChartConfig } from '../../../ui/layerchart-chart/chart-config.js';

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

	const colorsCount = $derived(getColorsCount(config[dataKey] ?? {}));
</script>

<linearGradient id={`${id}-colors-${dataKey}`} x1="0" y1="0" x2="0" 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 / (colorsCount - 1)) * 100}%`) as offset, index (offset)}
			<stop {offset} stop-color={`var(--color-${dataKey}-${index}, var(--color-${dataKey}-0))`} />
		{/each}
	{/if}
</linearGradient>
```

`$lib/components/evilcharts/charts/layerchart-bar-chart/defs/duotone-pattern.svelte`

```svelte
<script lang="ts">
	/** Two-tone fill — a half-faded, half-solid split applied per bar bounding box. */
	import { getColorsCount } from '../../../ui/layerchart-chart/colors.js';
	import type { ChartConfig } from '../../../ui/layerchart-chart/chart-config.js';

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

	const colorsCount = $derived(getColorsCount(config[dataKey] ?? {}));
</script>

<linearGradient
	id={`${id}-duotone-mask-gradient-${dataKey}`}
	gradientUnits="objectBoundingBox"
	x1="0"
	y1="0"
	x2="1"
	y2="0"
>
	<stop offset="50%" stop-color="white" stop-opacity={0.4} />
	<stop offset="50%" stop-color="white" stop-opacity={1} />
</linearGradient>
<linearGradient
	id={`${id}-duotone-colors-${dataKey}`}
	gradientUnits="objectBoundingBox"
	x1="0"
	y1="0"
	x2="0"
	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 / (colorsCount - 1)) * 100}%`) as offset, index (offset)}
			<stop {offset} stop-color={`var(--color-${dataKey}-${index}, var(--color-${dataKey}-0))`} />
		{/each}
	{/if}
</linearGradient>
<mask id={`${id}-duotone-mask-${dataKey}`} maskContentUnits="objectBoundingBox">
	<rect x="0" y="0" width="1" height="1" fill={`url(#${id}-duotone-mask-gradient-${dataKey})`} />
</mask>
<pattern
	id={`${id}-duotone-${dataKey}`}
	patternUnits="objectBoundingBox"
	patternContentUnits="objectBoundingBox"
	width="1"
	height="1"
>
	<rect
		x="0"
		y="0"
		width="1"
		height="1"
		fill={`url(#${id}-duotone-colors-${dataKey})`}
		mask={`url(#${id}-duotone-mask-${dataKey})`}
	/>
</pattern>
```

`$lib/components/evilcharts/charts/layerchart-bar-chart/defs/duotone-reverse-pattern.svelte`

```svelte
<script lang="ts">
	/** Two-tone fill with the solid and faded halves reversed from `duotone`. */
	import { getColorsCount } from '../../../ui/layerchart-chart/colors.js';
	import type { ChartConfig } from '../../../ui/layerchart-chart/chart-config.js';

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

	const colorsCount = $derived(getColorsCount(config[dataKey] ?? {}));
</script>

<linearGradient
	id={`${id}-duotone-reverse-mask-gradient-${dataKey}`}
	gradientUnits="objectBoundingBox"
	x1="0"
	y1="0"
	x2="1"
	y2="0"
>
	<stop offset="50%" stop-color="white" stop-opacity={1} />
	<stop offset="50%" stop-color="white" stop-opacity={0.4} />
</linearGradient>
<linearGradient
	id={`${id}-duotone-reverse-colors-${dataKey}`}
	gradientUnits="objectBoundingBox"
	x1="0"
	y1="0"
	x2="0"
	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 / (colorsCount - 1)) * 100}%`) as offset, index (offset)}
			<stop {offset} stop-color={`var(--color-${dataKey}-${index}, var(--color-${dataKey}-0))`} />
		{/each}
	{/if}
</linearGradient>
<mask id={`${id}-duotone-reverse-mask-${dataKey}`} maskContentUnits="objectBoundingBox">
	<rect
		x="0"
		y="0"
		width="1"
		height="1"
		fill={`url(#${id}-duotone-reverse-mask-gradient-${dataKey})`}
	/>
</mask>
<pattern
	id={`${id}-duotone-reverse-${dataKey}`}
	patternUnits="objectBoundingBox"
	patternContentUnits="objectBoundingBox"
	width="1"
	height="1"
>
	<rect
		x="0"
		y="0"
		width="1"
		height="1"
		fill={`url(#${id}-duotone-reverse-colors-${dataKey})`}
		mask={`url(#${id}-duotone-reverse-mask-${dataKey})`}
	/>
</pattern>
```

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

```svelte
<script lang="ts">
	/** Soft outer-glow filter applied to a glowing bar. */
	let { id, dataKey }: { id: string; dataKey: string } = $props();
</script>

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

`$lib/components/evilcharts/charts/layerchart-bar-chart/defs/gradient-pattern.svelte`

```svelte
<script lang="ts">
	/** Gradient fill that fades the series color from solid at the top to clear. */
	let { id, dataKey }: { id: string; dataKey: string } = $props();
</script>

<linearGradient id={`${id}-gradient-mask-gradient`} x1="0" y1="0" x2="0" y2="1">
	<stop offset="20%" stop-color="white" stop-opacity={1} />
	<stop offset="90%" stop-color="white" stop-opacity={0} />
</linearGradient>
<mask id={`${id}-gradient-mask-${dataKey}`}>
	<rect width="100%" height="100%" fill={`url(#${id}-gradient-mask-gradient)`} />
</mask>
<pattern id={`${id}-gradient-${dataKey}`} patternUnits="userSpaceOnUse" width="100%" height="100%">
	<rect
		width="100%"
		height="100%"
		fill={`url(#${id}-colors-${dataKey})`}
		mask={`url(#${id}-gradient-mask-${dataKey})`}
	/>
</pattern>
```

`$lib/components/evilcharts/charts/layerchart-bar-chart/defs/hatched-pattern.svelte`

```svelte
<script lang="ts">
	/** Diagonal hatched-stripe fill, masked from the series color gradient. */
	let { id, dataKey }: { id: string; dataKey: string } = $props();
</script>

<pattern
	id={`${id}-hatched-mask-pattern`}
	x="0"
	y="0"
	width="5"
	height="5"
	patternUnits="userSpaceOnUse"
	patternTransform="rotate(-45)"
>
	<rect width="5" height="5" fill="white" fill-opacity={0.3} />
	<rect width="1.5" height="5" fill="white" fill-opacity={1} />
</pattern>
<mask id={`${id}-hatched-mask-${dataKey}`}>
	<rect width="100%" height="100%" fill={`url(#${id}-hatched-mask-pattern)`} />
</mask>
<pattern id={`${id}-hatched-${dataKey}`} patternUnits="userSpaceOnUse" width="100%" height="100%">
	<rect
		width="100%"
		height="100%"
		fill={`url(#${id}-colors-${dataKey})`}
		mask={`url(#${id}-hatched-mask-${dataKey})`}
	/>
</pattern>
```

`$lib/components/evilcharts/charts/layerchart-bar-chart/defs/stripped-pattern.svelte`

```svelte
<script lang="ts">
	/** Low-opacity body fill, paired with a solid top strip drawn by the bar itself. */
	let { id, dataKey }: { id: string; dataKey: string } = $props();
</script>

<linearGradient id={`${id}-stripped-mask-gradient`} x1="0" y1="0" x2="0" y2="1">
	<stop offset="0%" stop-color="white" stop-opacity={0.2} />
	<stop offset="100%" stop-color="white" stop-opacity={0.2} />
</linearGradient>
<mask id={`${id}-stripped-mask-${dataKey}`}>
	<rect width="100%" height="100%" fill={`url(#${id}-stripped-mask-gradient)`} />
</mask>
<pattern id={`${id}-stripped-${dataKey}`} patternUnits="userSpaceOnUse" width="100%" height="100%">
	<rect
		width="100%"
		height="100%"
		fill={`url(#${id}-colors-${dataKey})`}
		mask={`url(#${id}-stripped-mask-${dataKey})`}
	/>
</pattern>
```

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

```svelte
<script lang="ts">
	/**
	 * The background grid lines. Defaults to dashed lines aligned to the value axis based on the
	 * chart layout, and forwards every LayerChart Grid prop for full control.
	 */
	import { Grid as LayerGrid } from 'layerchart';
	import { rechartsValueAxisTicks } from '../../ui/layerchart-chart/ticks.js';
	import { useBarChart } from './bar-chart-context.svelte.js';

	let {
		vertical,
		horizontal,
		strokeDasharray = '3 3',
		...restProps
	}: {
		vertical?: boolean;
		horizontal?: boolean;
		strokeDasharray?: string;
		[key: string]: unknown;
	} = $props();

	const chart = useBarChart();

	const showVertical = $derived(vertical ?? chart.isHorizontal);
	const showHorizontal = $derived(horizontal ?? !chart.isHorizontal);
</script>

<LayerGrid
	x={showVertical ? { dashArray: strokeDasharray } : false}
	y={showHorizontal ? { dashArray: strokeDasharray } : false}
	{...chart.isHorizontal ? { xTicks: rechartsValueAxisTicks } : { yTicks: rechartsValueAxisTicks }}
	{...restProps}
/>
```

`$lib/components/evilcharts/charts/layerchart-bar-chart/helpers.ts`

```ts
import {
	BAR_GROW_DURATION,
	BAR_STAGGER,
	REVEAL_EASE,
	type BarAnimationType,
	type BarVariant
} from './types.js';

// Resolves the SVG paint reference for a bar's fill based on its variant
export const getVariantFill = (variant: BarVariant, id: string, dataKey: string): string => {
	switch (variant) {
		case 'hatched':
			return `url(#${id}-hatched-${dataKey})`;
		case 'duotone':
			return `url(#${id}-duotone-${dataKey})`;
		case 'duotone-reverse':
			return `url(#${id}-duotone-reverse-${dataKey})`;
		case 'gradient':
			return `url(#${id}-gradient-${dataKey})`;
		case 'stripped':
			return `url(#${id}-stripped-${dataKey})`;
		default:
			return `url(#${id}-colors-${dataKey})`;
	}
};

// Computes bar opacity from the click selection and hover-highlight state
export const getBarOpacity = ({
	isClickable,
	selectedDataKey,
	dataKey,
	enableHoverHighlight,
	isMouseInChart,
	isActive
}: {
	isClickable?: boolean;
	selectedDataKey?: string | null;
	dataKey: string;
	enableHoverHighlight?: boolean;
	isMouseInChart?: boolean;
	isActive?: boolean;
}) => {
	const isSelectedDataKey = selectedDataKey === null || selectedDataKey === dataKey;
	const clickOpacity = isClickable && selectedDataKey !== null ? (isSelectedDataKey ? 1 : 0.15) : 1;

	// While hovering, the hovered bar keeps its click opacity and the rest dim further
	if (enableHoverHighlight && isMouseInChart) {
		return isActive ? clickOpacity : clickOpacity * 0.3;
	}

	return clickOpacity;
};

/**
 * Builds the motion.dev grow-in animation for a single bar, or returns `null`
 * when the bar should render statically (`"none"`, reduced motion, an unknown
 * index, or — crucially — once the bar has already finished growing).
 *
 * Every bar grows from its baseline — `scaleY` from the bottom for vertical
 * layout, `scaleX` from the left for horizontal — and `animationType` decides
 * the stagger order, so the chart fills in one bar at a time.
 *
 * The intro is anchored to `introStartedAt` (stamped once when the chart
 * mounts) rather than to component mount, so a re-render caught mid-grow
 * resumes from the progress it should already be at instead of replaying.
 */
export const getBarGrowAnimation = (
	animationType: BarAnimationType,
	index: number,
	dataLength: number,
	isHorizontal: boolean,
	introStartedAt: number
) => {
	if (animationType === 'none' || index < 0 || dataLength <= 0) return null;

	const lastIndex = dataLength - 1;
	const center = lastIndex / 2;

	// How many bars this one waits behind before it starts growing
	let step: number;
	switch (animationType) {
		case 'right-to-left':
			step = lastIndex - index;
			break;
		case 'center-out':
			step = Math.abs(index - center);
			break;
		case 'edges-in':
			step = center - Math.abs(index - center);
			break;
		default: // left-to-right
			step = index;
	}

	const startMs = step * BAR_STAGGER * 1000;
	const durationMs = BAR_GROW_DURATION * 1000;
	const endMs = startMs + durationMs;
	const elapsed = Date.now() - introStartedAt;

	// Already finished — render static so re-renders can't replay it
	if (elapsed >= endMs) return null;

	// Resume from wherever this bar should already be: 0 before it starts,
	// partway through if a re-render caught it mid-grow.
	const from = elapsed <= startMs ? 0 : (elapsed - startMs) / durationMs;
	const transition = {
		duration: (endMs - Math.max(elapsed, startMs)) / 1000,
		ease: REVEAL_EASE,
		delay: Math.max(0, startMs - elapsed) / 1000
	};

	// Horizontal bars grow rightward from the left edge, vertical from the bottom
	return isHorizontal
		? { initial: { scaleX: from }, animate: { scaleX: 1 }, transition, style: { originX: 0 } }
		: { initial: { scaleY: from }, animate: { scaleY: 1 }, transition, style: { originY: 1 } };
};
```

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

```ts
import Root from './bar-chart.svelte';
import Bar from './bar.svelte';
import XAxis from './x-axis.svelte';
import YAxis from './y-axis.svelte';
import Grid from './grid.svelte';
import Tooltip from './tooltip.svelte';
import Legend from './legend.svelte';
import { Brush } from '../../ui/layerchart-brush/index.js';

type RootComponent = typeof Root;

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

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

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

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

	const chart = useBarChart();

	const slot = $derived(chart.slots.legend);
	const resolvedPlacement = $derived(resolveLegendPlacement(slot?.verticalAlign, 'top'));

	const payload = $derived<LegendPayloadItem[]>(
		chart.seriesKeys.map((key) => ({ dataKey: key, value: key }))
	);
</script>

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

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

```svelte
<script lang="ts">
	/**
	 * The series legend. When `isClickable` is set, each entry toggles selection of
	 * its series, driving the shared selection state read by every <Bar />.
	 *
	 * 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 { useBarChart } from './bar-chart-context.svelte.js';

	let {
		variant,
		align = 'right',
		verticalAlign = 'top',
		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 series
	} = $props();

	const chart = useBarChart();
	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-bar-chart/loading/gradient-stops.ts`

```ts
// Builds bell-curve eased gradient stops for the loading shimmer
export const generateEasedGradientStops = (
	steps: number = 17,
	minOpacity: number = 0.05,
	maxOpacity: number = 0.9
) => {
	return Array.from({ length: steps }, (_, i) => {
		const t = i / (steps - 1); // 0 to 1
		// Sine-based bell curve easing: peaks at center (t=0.5), smooth falloff at edges
		const eased = Math.sin(t * Math.PI) ** 2;
		const opacity = minOpacity + eased * (maxOpacity - minOpacity);
		return { offset: `${(t * 100).toFixed(0)}%`, opacity: Number(opacity.toFixed(3)) };
	});
};
```

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

```svelte
<script lang="ts">
	/**
	 * Animated shimmer pattern for the loading skeleton.
	 *
	 * The visible chart area is normalized to 0-1, the shimmer gradient has width 1,
	 * and the pattern is 3x wide so the shimmer has buffer on both sides. The motion
	 * rect travels x from -1 to 2; onShimmerExit fires as it crosses x=1, letting the
	 * data swap happen while the shimmer is off-screen for a seamless loop.
	 */
	import { animate, useReducedMotion } from '@humanspeak/svelte-motion';
	import { LOADING_ANIMATION_DURATION } from '../types.js';
	import { generateEasedGradientStops } from './gradient-stops.js';

	let { chartId, onShimmerExit }: { chartId: string; onShimmerExit: () => void } = $props();

	const gradientStops = generateEasedGradientStops();

	// 1 (left buffer) + 1 (visible) + 1 (right buffer)
	const patternWidth = 3;
	const startX = -1;
	const endX = 2;
	const shouldReduceMotion = useReducedMotion();

	// Tracks the last x value to detect the exit threshold crossing
	let lastX = startX;

	function runShimmer(reduced: boolean) {
		return (node: SVGRectElement) => {
			node.setAttribute('x', reduced ? '0' : String(startX));
			if (reduced) return undefined;

			const controls = animate(startX, endX, {
				duration: LOADING_ANIMATION_DURATION / 1000,
				ease: 'linear',
				repeat: Infinity,
				repeatType: 'loop',
				onUpdate(xValue: number) {
					node.setAttribute('x', String(xValue));
					if (xValue >= 1 && lastX < 1) onShimmerExit();
					lastX = xValue;
				}
			});
			return () => controls.stop();
		};
	}
</script>

<linearGradient id={`${chartId}-loading-mask-gradient`} x1="0" y1="0" x2="1" y2="0">
	{#each gradientStops as { offset, opacity } (offset)}
		<stop {offset} stop-color="white" stop-opacity={opacity} />
	{/each}
</linearGradient>
<pattern
	id={`${chartId}-loading-mask-pattern`}
	patternUnits="objectBoundingBox"
	patternContentUnits="objectBoundingBox"
	patternTransform="rotate(25)"
	width={patternWidth}
	height="1"
	x="0"
	y="0"
>
	<rect
		{@attach runShimmer(shouldReduceMotion.current)}
		y="0"
		width="1"
		height="1"
		fill={`url(#${chartId}-loading-mask-gradient)`}
	/>
</pattern>
<mask id={`${chartId}-loading-mask`} maskUnits="userSpaceOnUse">
	<rect width="100%" height="100%" fill={`url(#${chartId}-loading-mask-pattern)`} />
</mask>
```

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

```svelte
<script lang="ts">
	/**
	 * The skeleton bars shown while the chart is loading. Rendered by the root in
	 * place of the real bars, paired with its own masked shimmer pattern.
	 */
	import { Bars, getChartContext } from 'layerchart';
	import { getBarPositions } from '../../../ui/layerchart-chart/bar-geometry.js';
	import { useBarChart } from '../bar-chart-context.svelte.js';
	import { DEFAULT_BAR_RADIUS, LOADING_BAR_DATA_KEY } from '../types.js';
	import LoadingBarPattern from './loading-bar-pattern.svelte';

	let { chartId, onShimmerExit }: { chartId: string; onShimmerExit: () => void } = $props();

	const chart = useBarChart();
	const layer = getChartContext();
	const bandSize = $derived(
		chart.isHorizontal
			? ((layer.yScale as { bandwidth?: () => number }).bandwidth?.() ?? 0)
			: ((layer.xScale as { bandwidth?: () => number }).bandwidth?.() ?? 0)
	);
	const slot = $derived(getBarPositions({ bandSize, count: 1 })[0]);
	const insets = $derived(
		chart.isHorizontal
			? { top: slot?.offset ?? 0, bottom: bandSize - (slot?.offset ?? 0) - (slot?.size ?? 0) }
			: { left: slot?.offset ?? 0, right: bandSize - (slot?.offset ?? 0) - (slot?.size ?? 0) }
	);
</script>

<Bars
	seriesKey={LOADING_BAR_DATA_KEY}
	fill="currentColor"
	fillOpacity={0.15}
	radius={DEFAULT_BAR_RADIUS}
	rounded="all"
	{insets}
	motion="none"
	mask={`url(#${chartId}-loading-mask)`}
/>
<defs>
	<LoadingBarPattern {chartId} {onShimmerExit} />
</defs>
```

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

```ts
import { getLoadingData } from '../../../ui/layerchart-chart/loading.js';

/**
 * Loading data with pixel-perfect shimmer synchronization.
 *
 * Uses motion.dev's onUpdate callback to ensure chart data is only regenerated
 * when the shimmer has completely exited the visible area. This eliminates
 * timing drift issues from setTimeout/setInterval.
 */
export class LoadingDataState {
	#isLoading: () => boolean;
	#loadingBars: () => number;
	/** Toggled by `onShimmerExit`; regenerates the skeleton data once per shimmer loop. */
	#tick = $state(0);

	constructor(options: { isLoading: () => boolean; loadingBars?: () => number }) {
		this.#isLoading = options.isLoading;
		this.#loadingBars = options.loadingBars ?? (() => 12);
	}

	get loadingData() {
		this.#tick;
		return getLoadingData(this.#loadingBars(), 20, 80);
	}

	/** Fired by motion.dev when the shimmer exits the visible area. */
	onShimmerExit = () => {
		if (this.#isLoading()) {
			this.#tick += 1;
		}
	};
}
```

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

	const chart = useBarChart();
	/** 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]
	);

	function toPayload(row: Record<string, unknown>): TooltipPayloadItem[] {
		return chart.seriesKeys.map((key) => ({
			dataKey: key,
			name: key,
			value: row[key] as number | string | null,
			payload: row
		}));
	}
</script>

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

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

```svelte
<script lang="ts">
	/**
	 * The hover tooltip. Reads the chart's selection from context so its content
	 * dims unselected series. Hidden automatically while the chart is loading.
	 *
	 * Config-only: the tooltip box and its cursor cannot render inside `<Svg>`, so this
	 * registers its props and the root renders them in the right place.
	 */
	import type { TooltipRoundness, TooltipVariant } from '../../ui/layerchart-tooltip/index.js';
	import { useBarChart } from './bar-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; // data index shown by default with no hover
	} = $props();

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

```ts
// Constants
export const DEFAULT_BAR_RADIUS = 2;
export const LOADING_BAR_DATA_KEY = 'loading';
export const LOADING_ANIMATION_DURATION = 2000; // in milliseconds
export const STACK_ID = 'evil-stacked';
export const BAR_GROW_DURATION = 0.5; // per-bar grow-in length, in seconds
export const BAR_STAGGER = 0.05; // delay between consecutive bars, in seconds
export const REVEAL_EASE: [number, number, number, number] = [0, 0.7, 0.5, 1]; // grow-in easing

export type BarVariant =
	'default' | 'hatched' | 'duotone' | 'duotone-reverse' | 'gradient' | 'stripped';
export type StackType = 'default' | 'stacked' | 'percent';
export type BarLayout = 'vertical' | 'horizontal';

/**
 * Order in which bars grow into view. LayerChart's own bar animation is permanently
 * disabled — every bar instead grows from its baseline (bottom for vertical
 * layout, left for horizontal), and this controls the stagger sequence.
 *
 * NOTE: the grow-in is a per-frame animation, so it is heavier than a static
 * chart. `"none"` opts out entirely; it is also what a device with the OS
 * "reduce motion" preference falls back to automatically.
 */
export type BarAnimationType =
	'none' | 'left-to-right' | 'right-to-left' | 'center-out' | 'edges-in';
```

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

```svelte
<script lang="ts">
	/**
	 * The bottom axis. Ships with the chart's flat default styling and forwards every LayerChart
	 * Axis prop. Hidden automatically while the chart is loading. It carries the categories when
	 * the bars run vertically and the values when they run horizontally — the scale type swaps
	 * with the layout, the side does not, exactly as Recharts does it.
	 *
	 * `dataKey` names the category key. Recharts reads it here; LayerChart needs it on the
	 * root's `x` accessor, so it is registered into the chart context on mount.
	 */
	import { Axis } from 'layerchart';
	import {
		layerChartFormatter,
		RECHARTS_X_AXIS_TICK_OFFSET,
		thinAxisTicks
	} from '../../ui/layerchart-chart/ticks.js';
	import type { ComponentProps } from 'svelte';
	import { useBarChart } from './bar-chart-context.svelte.js';

	type Props = Omit<ComponentProps<typeof Axis>, 'placement' | 'format'> & {
		dataKey?: string;
		tickFormatter?: (value: unknown, index: number) => string;
		tickLine?: boolean;
		axisLine?: boolean;
		tickMargin?: number;
		minTickGap?: number;
	};

	let {
		dataKey,
		tickLine = false,
		axisLine = false,
		tickMargin = 8,
		minTickGap = 8,
		tickFormatter,
		...restProps
	}: Props = $props();

	const chart = useBarChart();
	const token = $props.id();
	const translatedTickLength = $derived(tickMargin + RECHARTS_X_AXIS_TICK_OFFSET);
	const format = $derived(tickFormatter ? layerChartFormatter(tickFormatter) : undefined);
	const ticks = $derived(
		thinAxisTicks({
			minGap: minTickGap,
			format: (value, index) => tickFormatter?.(value, index) ?? String(value)
		})
	);

	$effect.pre(() => {
		chart.registerXAxisDataKey(token, dataKey);
		chart.registerAxis(token, 'x', true);
		return () => {
			chart.registerXAxisDataKey(token, undefined);
			chart.registerAxis(token, 'x', false);
		};
	});
</script>

{#if !chart.isLoading}
	<Axis
		placement="bottom"
		{ticks}
		rule={axisLine}
		tickMarks={tickLine}
		tickLength={translatedTickLength}
		{format}
		{...restProps}
	/>
{/if}
```

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

```svelte
<script lang="ts">
	/**
	 * The left axis. Forwards every LayerChart Axis prop and, when the chart uses a percent stack,
	 * formats ticks as percentages automatically. Hidden while the chart is loading. It carries the
	 * values when the bars run vertically and the categories when they run horizontally.
	 */
	import { Axis } from 'layerchart';
	import { axisValueToPercentFormatter } from '../../ui/layerchart-chart/format.js';
	import { layerChartFormatter } from '../../ui/layerchart-chart/ticks.js';
	import type { ComponentProps } from 'svelte';
	import { useBarChart } from './bar-chart-context.svelte.js';

	type Props = Omit<ComponentProps<typeof Axis>, 'placement' | 'format'> & {
		dataKey?: string;
		tickFormatter?: (value: unknown, index: number) => string;
		tickLine?: boolean;
		axisLine?: boolean;
		tickMargin?: number;
		minTickGap?: number;
	};

	let {
		tickLine = false,
		axisLine = false,
		tickMargin = 8,
		minTickGap: _minTickGap = 8,
		tickFormatter,
		dataKey: _dataKey,
		...restProps
	}: Props = $props();

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

	$effect.pre(() => {
		chart.registerAxis(token, 'y', true);
		return () => chart.registerAxis(token, 'y', false);
	});

	const format = $derived(
		chart.isPercent
			? (value: unknown) => axisValueToPercentFormatter(Number(value))
			: tickFormatter
				? layerChartFormatter(tickFormatter)
				: undefined
	);
</script>

{#if !chart.isLoading}
	<Axis
		placement="left"
		rule={axisLine}
		tickMarks={tickLine}
		tickLength={tickMargin}
		{format}
		{...restProps}
	/>
{/if}
```
        
      
       
        ### Add the chart component.
        

The chart needs these components to render. Make 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 bar chart is composable. `<EvilBarChart>` is the container, and every part hangs off it as a compound member — `<EvilBarChart.Grid>`, `<EvilBarChart.XAxis>`, `<EvilBarChart.YAxis>`, `<EvilBarChart.Legend>`, `<EvilBarChart.Tooltip>`, and one or more `<EvilBarChart.Bar>` — as children. Each `<Bar>` sets its own `variant`, `radius`, `glowing`, `bufferBar`, and `isClickable`, so one chart can mix fill styles and make only some series interactive.

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

```svelte
<EvilBarChart {data} config={chartConfig} stackType="default">
	<EvilBarChart.Grid />
	<EvilBarChart.XAxis dataKey="month" />
	<EvilBarChart.Legend isClickable />
	<EvilBarChart.Tooltip />
	<EvilBarChart.Bar dataKey="desktop" variant="default" isClickable />
	<EvilBarChart.Bar dataKey="mobile" variant="hatched" isClickable />
</EvilBarChart>
```

### Interactive Selection

Add `isClickable` to any `<Bar>` (and `<Legend>`) to make its series selectable, then handle events with the `onSelectionChange` callback on `<EvilBarChart>`:

```svelte
<EvilBarChart
	{data}
	config={chartConfig}
	onSelectionChange={(selectedDataKey) => {
		if (selectedDataKey) {
			console.log('Selected:', selectedDataKey);
		} else {
			console.log('Deselected');
		}
	}}
>
	<EvilBarChart.XAxis dataKey="month" />
	<EvilBarChart.Legend isClickable />
	<EvilBarChart.Tooltip />
	<EvilBarChart.Bar dataKey="desktop" variant="default" isClickable />
	<EvilBarChart.Bar dataKey="mobile" variant="default" isClickable />
</EvilBarChart>
```

### Loading State

### isLoading='true'

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

	const chartConfig = {
		desktop: {
			label: 'Desktop',
			colors: {
				light: ['#047857'],
				dark: ['#10b981']
			}
		},
		mobile: {
			label: 'Mobile',
			colors: {
				light: ['#be123c'],
				dark: ['#f43f5e']
			}
		}
	} satisfies ChartConfig;
</script>

<!-- [!code highlight:6] -->
<EvilBarChart data={[]} config={chartConfig} class="h-full w-full p-4" isLoading={true}>
	<EvilBarChart.Grid />
	<EvilBarChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilBarChart.Legend />
	<EvilBarChart.Tooltip />
	<EvilBarChart.Bar dataKey="desktop" variant="default" />
	<EvilBarChart.Bar dataKey="mobile" variant="default" />
</EvilBarChart>
```
>  
  

Pass `isLoading` to show a shimmer skeleton while data loads.




### Buffer Bar

### <Bar bufferBar />

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

	const data = [
		{ month: 'January', desktop: 342, mobile: 184 },
		{ month: 'February', desktop: 876, mobile: 491 },
		{ month: 'March', desktop: 512, mobile: 290 },
		{ month: 'April', desktop: 629, mobile: 391 },
		{ month: 'May', desktop: 458, mobile: 309 },
		{ month: 'June', desktop: 781, mobile: 449 },
		{ month: 'July', desktop: 394, mobile: 234 },
		{ month: 'August', desktop: 925, mobile: 557 },
		{ month: 'September', desktop: 647, mobile: 367 },
		{ month: 'October', desktop: 532, mobile: 357 },
		{ month: 'November', desktop: 503, mobile: 215 },
		{ month: 'December', desktop: 971, mobile: 749 }
	];

	const chartConfig = {
		desktop: {
			label: 'Desktop',
			colors: {
				light: ['#047857'],
				dark: ['#10b981']
			}
		},
		mobile: {
			label: 'Mobile',
			colors: {
				light: ['#be123c'],
				dark: ['#f43f5e']
			}
		}
	} satisfies ChartConfig;
</script>

<EvilBarChart {data} config={chartConfig} class="h-full w-full p-4">
	<EvilBarChart.Grid />
	<EvilBarChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilBarChart.Legend isClickable />
	<EvilBarChart.Tooltip />
	<!-- [!code highlight] -->
	<EvilBarChart.Bar dataKey="desktop" variant="default" bufferBar isClickable />
	<!-- [!code highlight] -->
	<EvilBarChart.Bar dataKey="mobile" variant="default" bufferBar isClickable />
</EvilBarChart>
```
>  
  

With `bufferBar` set, a `<Bar>`'s last data point renders as a hatched pattern while the rest stay solid — handy for flagging projected or incomplete data, as in financial and forecasting charts.




## Examples

Examples across different `variants`. Each `<Bar>` sets its own `variant`; the chart-wide `stackType` and `layout` shape the rest.

### Hover Highlight

### <Bar enableHoverHighlight />

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

	const data = [
		{ month: 'January', desktop: 342, mobile: 184 },
		{ month: 'February', desktop: 876, mobile: 491 },
		{ month: 'March', desktop: 512, mobile: 290 },
		{ month: 'April', desktop: 629, mobile: 391 },
		{ month: 'May', desktop: 458, mobile: 309 },
		{ month: 'June', desktop: 781, mobile: 449 },
		{ month: 'July', desktop: 394, mobile: 234 },
		{ month: 'August', desktop: 925, mobile: 557 },
		{ month: 'September', desktop: 647, mobile: 367 },
		{ month: 'October', desktop: 532, mobile: 357 },
		{ month: 'November', desktop: 803, mobile: 515 },
		{ month: 'December', desktop: 271, mobile: 149 }
	];

	const chartConfig = {
		desktop: {
			label: 'Desktop',
			colors: {
				light: ['#047857'],
				dark: ['#10b981']
			}
		},
		mobile: {
			label: 'Mobile',
			colors: {
				light: ['#be123c'],
				dark: ['#f43f5e']
			}
		}
	} satisfies ChartConfig;
</script>

<EvilBarChart {data} config={chartConfig} class="h-full w-full p-4">
	<EvilBarChart.Grid />
	<EvilBarChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilBarChart.Legend />
	<EvilBarChart.Tooltip />
	<!-- [!code highlight] -->
	<EvilBarChart.Bar dataKey="desktop" variant="default" enableHoverHighlight />
	<!-- [!code highlight] -->
	<EvilBarChart.Bar dataKey="mobile" variant="default" enableHoverHighlight />
</EvilBarChart>
```
>  
  

Set `enableHoverHighlight` on a `<Bar>` to dim the other bars on hover, keeping focus on one series.




### Gradient Colors

### gradient colors

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

	const data = [
		{ month: 'January', desktop: 342, mobile: 184 },
		{ month: 'February', desktop: 876, mobile: 491 },
		{ month: 'March', desktop: 512, mobile: 290 },
		{ month: 'April', desktop: 629, mobile: 391 },
		{ month: 'May', desktop: 458, mobile: 309 },
		{ month: 'June', desktop: 781, mobile: 449 },
		{ month: 'July', desktop: 394, mobile: 234 },
		{ month: 'August', desktop: 925, mobile: 557 },
		{ month: 'September', desktop: 647, mobile: 367 },
		{ month: 'October', desktop: 532, mobile: 357 },
		{ month: 'November', desktop: 803, mobile: 515 },
		{ month: 'December', desktop: 271, mobile: 149 }
	];

	const chartConfig = {
		desktop: {
			label: 'Desktop',
			colors: {
				light: ['#a855f7', '#6366f1', '#3b82f6'], // [!code highlight]
				dark: ['#f43f5e', '#ec4899', '#a855f7', '#6366f1', '#3b82f6'] // [!code highlight]
			}
		},
		mobile: {
			label: 'Mobile',
			colors: {
				light: ['#10b981', '#34d399', '#6ee7b7'], // [!code highlight]
				dark: ['#10b981', '#14b8a6', '#06b6d4'] // [!code highlight]
			}
		}
	} satisfies ChartConfig;
</script>

<EvilBarChart {data} config={chartConfig} class="h-full w-full p-4">
	<EvilBarChart.Grid />
	<EvilBarChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilBarChart.Legend isClickable />
	<EvilBarChart.Tooltip />
	<EvilBarChart.Bar dataKey="desktop" variant="default" isClickable />
	<EvilBarChart.Bar dataKey="mobile" variant="default" isClickable />
</EvilBarChart>
```

### Bar Variants

### variant='default'

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

	const data = [
		{ month: 'January', desktop: 342, mobile: 184 },
		{ month: 'February', desktop: 876, mobile: 491 },
		{ month: 'March', desktop: 512, mobile: 290 },
		{ month: 'April', desktop: 629, mobile: 391 },
		{ month: 'May', desktop: 458, mobile: 309 },
		{ month: 'June', desktop: 781, mobile: 449 },
		{ month: 'July', desktop: 394, mobile: 234 },
		{ month: 'August', desktop: 925, mobile: 557 },
		{ month: 'September', desktop: 647, mobile: 367 },
		{ month: 'October', desktop: 532, mobile: 357 },
		{ month: 'November', desktop: 803, mobile: 515 },
		{ month: 'December', desktop: 271, mobile: 149 }
	];

	const chartConfig = {
		desktop: {
			label: 'Desktop',
			colors: {
				light: ['#047857'],
				dark: ['#10b981']
			}
		},
		mobile: {
			label: 'Mobile',
			colors: {
				light: ['#be123c'],
				dark: ['#f43f5e']
			}
		}
	} satisfies ChartConfig;
</script>

<EvilBarChart {data} config={chartConfig} class="h-full w-full p-4">
	<EvilBarChart.Grid />
	<EvilBarChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilBarChart.Legend isClickable />
	<EvilBarChart.Tooltip />
	<!-- [!code highlight] -->
	<EvilBarChart.Bar dataKey="desktop" variant="default" isClickable />
	<!-- [!code highlight] -->
	<EvilBarChart.Bar dataKey="mobile" variant="default" isClickable />
</EvilBarChart>
```
### variant='hatched'

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

	const data = [
		{ month: 'January', desktop: 342, mobile: 184 },
		{ month: 'February', desktop: 876, mobile: 491 },
		{ month: 'March', desktop: 512, mobile: 290 },
		{ month: 'April', desktop: 629, mobile: 391 },
		{ month: 'May', desktop: 458, mobile: 309 },
		{ month: 'June', desktop: 781, mobile: 449 },
		{ month: 'July', desktop: 394, mobile: 234 },
		{ month: 'August', desktop: 925, mobile: 557 },
		{ month: 'September', desktop: 647, mobile: 367 },
		{ month: 'October', desktop: 532, mobile: 357 },
		{ month: 'November', desktop: 803, mobile: 515 },
		{ month: 'December', desktop: 271, mobile: 149 }
	];

	const chartConfig = {
		desktop: {
			label: 'Desktop',
			colors: {
				light: ['#047857'],
				dark: ['#10b981']
			}
		},
		mobile: {
			label: 'Mobile',
			colors: {
				light: ['#be123c'],
				dark: ['#f43f5e']
			}
		}
	} satisfies ChartConfig;
</script>

<EvilBarChart {data} config={chartConfig} class="h-full w-full p-4">
	<EvilBarChart.Grid />
	<EvilBarChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilBarChart.Legend isClickable />
	<EvilBarChart.Tooltip />
	<!-- [!code highlight] -->
	<EvilBarChart.Bar dataKey="desktop" variant="hatched" isClickable />
	<!-- [!code highlight] -->
	<EvilBarChart.Bar dataKey="mobile" variant="hatched" isClickable />
</EvilBarChart>
```
### variant='duotone'

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

	const data = [
		{ month: 'January', desktop: 342, mobile: 184 },
		{ month: 'February', desktop: 876, mobile: 491 },
		{ month: 'March', desktop: 512, mobile: 290 },
		{ month: 'April', desktop: 629, mobile: 391 },
		{ month: 'May', desktop: 458, mobile: 309 },
		{ month: 'June', desktop: 781, mobile: 449 },
		{ month: 'July', desktop: 394, mobile: 234 },
		{ month: 'August', desktop: 925, mobile: 557 },
		{ month: 'September', desktop: 647, mobile: 367 },
		{ month: 'October', desktop: 532, mobile: 357 },
		{ month: 'November', desktop: 803, mobile: 515 },
		{ month: 'December', desktop: 271, mobile: 149 }
	];

	const chartConfig = {
		desktop: {
			label: 'Desktop',
			colors: {
				light: ['#047857'],
				dark: ['#10b981']
			}
		},
		mobile: {
			label: 'Mobile',
			colors: {
				light: ['#be123c'],
				dark: ['#f43f5e']
			}
		}
	} satisfies ChartConfig;
</script>

<EvilBarChart {data} config={chartConfig} class="h-full w-full p-4">
	<EvilBarChart.Grid />
	<EvilBarChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilBarChart.Legend isClickable />
	<EvilBarChart.Tooltip />
	<!-- [!code highlight] -->
	<EvilBarChart.Bar dataKey="desktop" variant="duotone" isClickable />
	<!-- [!code highlight] -->
	<EvilBarChart.Bar dataKey="mobile" variant="duotone" isClickable />
</EvilBarChart>
```
### variant='duotone-reverse'

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

	const data = [
		{ month: 'January', desktop: 342, mobile: 184 },
		{ month: 'February', desktop: 876, mobile: 491 },
		{ month: 'March', desktop: 512, mobile: 290 },
		{ month: 'April', desktop: 629, mobile: 391 },
		{ month: 'May', desktop: 458, mobile: 309 },
		{ month: 'June', desktop: 781, mobile: 449 },
		{ month: 'July', desktop: 394, mobile: 234 },
		{ month: 'August', desktop: 925, mobile: 557 },
		{ month: 'September', desktop: 647, mobile: 367 },
		{ month: 'October', desktop: 532, mobile: 357 },
		{ month: 'November', desktop: 803, mobile: 515 },
		{ month: 'December', desktop: 271, mobile: 149 }
	];

	const chartConfig = {
		desktop: {
			label: 'Desktop',
			colors: {
				light: ['#047857'],
				dark: ['#10b981']
			}
		},
		mobile: {
			label: 'Mobile',
			colors: {
				light: ['#be123c'],
				dark: ['#f43f5e']
			}
		}
	} satisfies ChartConfig;
</script>

<EvilBarChart {data} config={chartConfig} class="h-full w-full p-4">
	<EvilBarChart.Grid />
	<EvilBarChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilBarChart.Legend isClickable />
	<EvilBarChart.Tooltip />
	<!-- [!code highlight] -->
	<EvilBarChart.Bar dataKey="desktop" variant="duotone-reverse" isClickable />
	<!-- [!code highlight] -->
	<EvilBarChart.Bar dataKey="mobile" variant="duotone-reverse" isClickable />
</EvilBarChart>
```
### variant='gradient'

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

	const data = [
		{ month: 'January', desktop: 342, mobile: 184 },
		{ month: 'February', desktop: 876, mobile: 491 },
		{ month: 'March', desktop: 512, mobile: 290 },
		{ month: 'April', desktop: 629, mobile: 391 },
		{ month: 'May', desktop: 458, mobile: 309 },
		{ month: 'June', desktop: 781, mobile: 449 },
		{ month: 'July', desktop: 394, mobile: 234 },
		{ month: 'August', desktop: 925, mobile: 557 },
		{ month: 'September', desktop: 647, mobile: 367 },
		{ month: 'October', desktop: 532, mobile: 357 },
		{ month: 'November', desktop: 803, mobile: 515 },
		{ month: 'December', desktop: 271, mobile: 149 }
	];

	const chartConfig = {
		desktop: {
			label: 'Desktop',
			colors: {
				light: ['#047857'],
				dark: ['#10b981']
			}
		},
		mobile: {
			label: 'Mobile',
			colors: {
				light: ['#be123c'],
				dark: ['#f43f5e']
			}
		}
	} satisfies ChartConfig;
</script>

<EvilBarChart {data} config={chartConfig} class="h-full w-full p-4">
	<EvilBarChart.Grid />
	<EvilBarChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilBarChart.Legend isClickable />
	<EvilBarChart.Tooltip />
	<!-- [!code highlight] -->
	<EvilBarChart.Bar dataKey="desktop" variant="gradient" isClickable />
	<!-- [!code highlight] -->
	<EvilBarChart.Bar dataKey="mobile" variant="gradient" isClickable />
</EvilBarChart>
```
### variant='stripped'

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

	const data = [
		{ month: 'January', desktop: 342, mobile: 184 },
		{ month: 'February', desktop: 876, mobile: 491 },
		{ month: 'March', desktop: 512, mobile: 290 },
		{ month: 'April', desktop: 629, mobile: 391 },
		{ month: 'May', desktop: 458, mobile: 309 },
		{ month: 'June', desktop: 781, mobile: 449 },
		{ month: 'July', desktop: 394, mobile: 234 },
		{ month: 'August', desktop: 925, mobile: 557 },
		{ month: 'September', desktop: 647, mobile: 367 },
		{ month: 'October', desktop: 532, mobile: 357 },
		{ month: 'November', desktop: 803, mobile: 515 },
		{ month: 'December', desktop: 271, mobile: 149 }
	];

	const chartConfig = {
		desktop: {
			label: 'Desktop',
			colors: {
				light: ['#047857'],
				dark: ['#10b981']
			}
		},
		mobile: {
			label: 'Mobile',
			colors: {
				light: ['#be123c'],
				dark: ['#f43f5e']
			}
		}
	} satisfies ChartConfig;
</script>

<EvilBarChart {data} config={chartConfig} class="h-full w-full p-4">
	<EvilBarChart.Grid />
	<EvilBarChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilBarChart.Legend isClickable />
	<EvilBarChart.Tooltip />
	<!-- [!code highlight] -->
	<EvilBarChart.Bar dataKey="desktop" variant="stripped" isClickable />
	<!-- [!code highlight] -->
	<EvilBarChart.Bar dataKey="mobile" variant="stripped" isClickable />
</EvilBarChart>
```

### Stack Types

### stackType='stacked'

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

	const data = [
		{ month: 'January', desktop: 342, mobile: 184 },
		{ month: 'February', desktop: 876, mobile: 491 },
		{ month: 'March', desktop: 512, mobile: 290 },
		{ month: 'April', desktop: 629, mobile: 391 },
		{ month: 'May', desktop: 458, mobile: 309 },
		{ month: 'June', desktop: 781, mobile: 449 },
		{ month: 'July', desktop: 394, mobile: 234 },
		{ month: 'August', desktop: 925, mobile: 557 },
		{ month: 'September', desktop: 647, mobile: 367 },
		{ month: 'October', desktop: 532, mobile: 357 },
		{ month: 'November', desktop: 803, mobile: 515 },
		{ month: 'December', desktop: 271, mobile: 149 }
	];

	const chartConfig = {
		desktop: {
			label: 'Desktop',
			colors: {
				light: ['#047857'],
				dark: ['#10b981']
			}
		},
		mobile: {
			label: 'Mobile',
			colors: {
				light: ['#be123c'],
				dark: ['#f43f5e']
			}
		}
	} satisfies ChartConfig;
</script>

<!-- [!code highlight:6] -->
<EvilBarChart {data} config={chartConfig} class="h-full w-full p-4" stackType="stacked">
	<EvilBarChart.Grid />
	<EvilBarChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilBarChart.Legend isClickable />
	<EvilBarChart.Tooltip />
	<EvilBarChart.Bar dataKey="desktop" variant="default" isClickable />
	<EvilBarChart.Bar dataKey="mobile" variant="default" isClickable />
</EvilBarChart>
```
### stackType='percent'

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

	const data = [
		{ month: 'January', desktop: 342, mobile: 184 },
		{ month: 'February', desktop: 876, mobile: 491 },
		{ month: 'March', desktop: 512, mobile: 290 },
		{ month: 'April', desktop: 629, mobile: 391 },
		{ month: 'May', desktop: 458, mobile: 309 },
		{ month: 'June', desktop: 781, mobile: 449 },
		{ month: 'July', desktop: 394, mobile: 234 },
		{ month: 'August', desktop: 925, mobile: 557 },
		{ month: 'September', desktop: 647, mobile: 367 },
		{ month: 'October', desktop: 532, mobile: 357 },
		{ month: 'November', desktop: 803, mobile: 515 },
		{ month: 'December', desktop: 271, mobile: 149 }
	];

	const chartConfig = {
		desktop: {
			label: 'Desktop',
			colors: {
				light: ['#047857'],
				dark: ['#10b981']
			}
		},
		mobile: {
			label: 'Mobile',
			colors: {
				light: ['#be123c'],
				dark: ['#f43f5e']
			}
		}
	} satisfies ChartConfig;
</script>

<!-- [!code highlight:6] -->
<EvilBarChart {data} config={chartConfig} class="h-full w-full p-4" stackType="percent">
	<EvilBarChart.Grid />
	<EvilBarChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilBarChart.Legend isClickable />
	<EvilBarChart.Tooltip />
	<EvilBarChart.Bar dataKey="desktop" variant="default" isClickable />
	<EvilBarChart.Bar dataKey="mobile" variant="default" isClickable />
</EvilBarChart>
```

### Horizontal Layout

### layout='horizontal'

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

	const data = [
		{ month: 'January', desktop: 186 },
		{ month: 'February', desktop: 305 },
		{ month: 'March', desktop: 237 },
		{ month: 'April', desktop: 173 },
		{ month: 'May', desktop: 209 },
		{ month: 'June', desktop: 214 }
	];

	const chartConfig = {
		desktop: {
			label: 'Desktop',
			colors: {
				light: ['#2563eb'],
				dark: ['#3b82f6']
			}
		}
	} satisfies ChartConfig;
</script>

<!-- [!code highlight:6] -->
<EvilBarChart {data} config={chartConfig} class="h-full w-full p-4" layout="horizontal">
	<EvilBarChart.Grid />
	<!-- [!code highlight] -->
	<EvilBarChart.YAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilBarChart.Legend />
	<EvilBarChart.Tooltip />
	<EvilBarChart.Bar dataKey="desktop" variant="default" />
</EvilBarChart>
```
>  
  

Set `layout="horizontal"` on `<EvilBarChart>` to lay bars sideways. The `<YAxis>` then shows categories and the `<XAxis>` shows values — pass a `tickFormatter` to `<YAxis>` to format categories.




### Glowing Bars

### <Bar glowing /> - desktop

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

	const data = [
		{ month: 'January', desktop: 342, mobile: 184 },
		{ month: 'February', desktop: 876, mobile: 491 },
		{ month: 'March', desktop: 512, mobile: 290 },
		{ month: 'April', desktop: 629, mobile: 391 },
		{ month: 'May', desktop: 458, mobile: 309 },
		{ month: 'June', desktop: 781, mobile: 449 },
		{ month: 'July', desktop: 394, mobile: 234 },
		{ month: 'August', desktop: 925, mobile: 557 },
		{ month: 'September', desktop: 647, mobile: 367 },
		{ month: 'October', desktop: 532, mobile: 357 },
		{ month: 'November', desktop: 803, mobile: 515 },
		{ month: 'December', desktop: 271, mobile: 149 }
	];

	const chartConfig = {
		desktop: {
			label: 'Desktop',
			colors: {
				light: ['#047857'],
				dark: ['#10b981']
			}
		},
		mobile: {
			label: 'Mobile',
			colors: {
				light: ['#be123c'],
				dark: ['#f43f5e']
			}
		}
	} satisfies ChartConfig;
</script>

<EvilBarChart {data} config={chartConfig} class="h-full w-full p-4">
	<EvilBarChart.Grid />
	<EvilBarChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilBarChart.Legend isClickable />
	<EvilBarChart.Tooltip />
	<!-- [!code highlight] -->
	<EvilBarChart.Bar dataKey="desktop" variant="default" glowing isClickable />
	<EvilBarChart.Bar dataKey="mobile" variant="default" isClickable />
</EvilBarChart>
```
### <Bar glowing /> - mobile

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

	const data = [
		{ month: 'January', desktop: 342, mobile: 184 },
		{ month: 'February', desktop: 876, mobile: 491 },
		{ month: 'March', desktop: 512, mobile: 290 },
		{ month: 'April', desktop: 629, mobile: 391 },
		{ month: 'May', desktop: 458, mobile: 309 },
		{ month: 'June', desktop: 781, mobile: 449 },
		{ month: 'July', desktop: 394, mobile: 234 },
		{ month: 'August', desktop: 925, mobile: 557 },
		{ month: 'September', desktop: 647, mobile: 367 },
		{ month: 'October', desktop: 532, mobile: 357 },
		{ month: 'November', desktop: 803, mobile: 515 },
		{ month: 'December', desktop: 271, mobile: 149 }
	];

	const chartConfig = {
		desktop: {
			label: 'Desktop',
			colors: {
				light: ['#047857'],
				dark: ['#10b981']
			}
		},
		mobile: {
			label: 'Mobile',
			colors: {
				light: ['#be123c'],
				dark: ['#f43f5e']
			}
		}
	} satisfies ChartConfig;
</script>

<EvilBarChart {data} config={chartConfig} class="h-full w-full p-4">
	<EvilBarChart.Grid />
	<EvilBarChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilBarChart.Legend isClickable />
	<EvilBarChart.Tooltip />
	<EvilBarChart.Bar dataKey="desktop" variant="default" isClickable />
	<!-- [!code highlight] -->
	<EvilBarChart.Bar dataKey="mobile" variant="default" glowing isClickable />
</EvilBarChart>
```

### Dither rendering

Set `renderStyle="dither"` on the existing chart root for ordered-dither bars without changing grouping, stacking, horizontal layout, hover, selection, loading, or brush behavior. A bar-level `ditherVariant` overrides the root texture.

### renderStyle='dither'

```svelte
<script lang="ts">
	import {
		EvilBarChart,
		type ChartConfig
	} from '$lib/components/evilcharts/charts/layerchart-bar-chart/index.js';
	const data = [
		{ month: 'Jan', desktop: 42, mobile: 25 },
		{ month: 'Feb', desktop: 76, mobile: 54 },
		{ month: 'Mar', desktop: 51, mobile: 38 },
		{ month: 'Apr', desktop: 84, mobile: 62 },
		{ month: 'May', desktop: 63, mobile: 47 },
		{ month: 'Jun', desktop: 91, mobile: 70 }
	];
	const config = {
		desktop: {
			label: 'Desktop',
			colors: { light: ['#047857', '#34d399'], dark: ['#10b981', '#6ee7b7'] }
		},
		mobile: { label: 'Mobile', colors: { light: ['#be123c'], dark: ['#f43f5e'] } }
	} satisfies ChartConfig;
</script>

<EvilBarChart
	{data}
	{config}
	xDataKey="month"
	renderStyle="dither"
	bloom="low"
	class="h-full w-full p-4"
>
	<EvilBarChart.Grid /><EvilBarChart.XAxis dataKey="month" /><EvilBarChart.Legend
		isClickable
	/><EvilBarChart.Tooltip />
	<EvilBarChart.Bar dataKey="desktop" ditherVariant="gradient" isClickable enableHoverHighlight />
	<EvilBarChart.Bar dataKey="mobile" ditherVariant="hatched" isClickable enableHoverHighlight />
</EvilBarChart>
```

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

## API Reference

The chart has several parts. Props below are grouped by component.

### EvilBarChart

The root container. It owns the data, shared selection state, loading skeleton, and optional brush — everything visual is composed as its children.


  ### `data` (required)

type: `TData[]`

The chart data — an array of objects, one per data point (`TData extends Record<string, unknown>`).
  ### `config` (required)

type: `Record<string, ChartConfig[string]>`

Defines the chart's series. Each key matches a data key and maps to a color or color array.
  ### `children` (required)

type: `Snippet`

The composed chart parts — `<Grid />`, `<XAxis />`, `<YAxis />`, `<Legend />`, `<Tooltip />`, and one or more `<Bar />`.
  ### `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.
  ### `stackType`

type: `"default" | "stacked" | "percent"` · default: `"default"`

How multiple bars combine. `"default"` sits them side by side, `"stacked"` stacks them, and `"percent"` normalizes them to a percentage distribution.
  ### `layout`

type: `"vertical" | "horizontal"` · default: `"vertical"`

Bar orientation. `"vertical"` draws upright bars; `"horizontal"` lays them sideways, so the `<YAxis />` shows categories and the `<XAxis />` shows values.
  ### `barRadius`

type: `number` · default: `2`

Default corner radius (px) for every `<Bar />`. Each `<Bar />` can override it with its own `radius` prop.
  ### `animationType`

type: `"none" | "left-to-right" | "right-to-left" | "center-out" | "edges-in"` · default: `"left-to-right"`

Order in which bars grow into view, inherited by every `<Bar />`. Each grows from its baseline (bottom when vertical, left when horizontal). `"none"` disables it; the OS reduce-motion preference forces `"none"` automatically.
  ### `barGap`

type: `number`

Gap between bars in the same category (multiple series).
  ### `barCategoryGap`

type: `number`

Gap between bar categories.
  ### `backgroundVariant`

type: `BackgroundVariant`

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

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

Data key selected by default.
  ### `onSelectionChange`

type: `(selectedDataKey: string | null) => void`

Fires when a series is selected or deselected by clicking a clickable `<Bar />` or `<Legend />` entry. Receives the data key, or `null` when deselected.
  ### `isLoading`

type: `boolean` · default: `false`

Shows a shimmer skeleton while data loads.
  ### `loadingBars`

type: `number` · default: `12`

Number of bars in the loading skeleton.
  ### `xDataKey`

type: `keyof TData & string`

X-axis data key. Only the brush footer needs it — the axis reads its own key from `<XAxis dataKey="…" />`.
  ### `renderStyle`

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

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

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

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

type: `number` · default: `2`

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

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

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

type: `ComponentProps<typeof BarChart>`

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


### Bar

A single bar series. Each `<Bar />` is self-contained and generates its own gradient/pattern defs, so a chart can hold any number — each with its own variant, radius, glow, and clickability.


  ### `dataKey` (required)

type: `string`

The series key. Must exist on both the data rows and the chart `config`.
  ### `variant`

type: `"default" | "hatched" | "duotone" | "duotone-reverse" | "gradient" | "stripped"` · default: `"default"`

Fill style for this bar only.
  ### `radius`

type: `number`

Corner radius (px) for this bar. Falls back to the chart's `barRadius` when omitted.
  ### `animationType`

type: `"none" | "left-to-right" | "right-to-left" | "center-out" | "edges-in"`

Grow-in order for this series. Falls back to the chart's `animationType` when omitted.
  ### `isClickable`

type: `boolean` · default: `false`

Lets this bar be selected on click. While any bar is selected, unselected bars turn semi-transparent.
  ### `enableHoverHighlight`

type: `boolean` · default: `false`

Dims this bar while another is hovered, keeping focus on one series.
  ### `glowing`

type: `boolean` · default: `false`

Adds a soft outer glow to this series.
  ### `bufferBar`

type: `boolean` · default: `false`

Renders this series' last data point as a hatched pattern while the rest stay solid — good for projected or incomplete data.
  ### `barProps`

type: `ComponentProps<typeof Bar>`

Escape hatch for raw props forwarded to the LayerChart Bar.


### XAxis and YAxis

The category and value axes. Both use the chart's flat default styling and forward every LayerChart axis prop, so `dataKey`, `tickFormatter`, `tickMargin`, etc. pass straight through. They hide automatically while the chart loads, and each resolves its `type` from the chart `layout` — categorical or numeric — unless you set `type` explicitly.


  ### `dataKey`

type: `string`

The data key for the axis values.
  ### `…axisProps`



Every other LayerChart axis prop is forwarded as-is. See the [LayerChart Axis documentation](https://www.layerchart.com/docs/components/Axis).


### Grid

The background grid lines. Defaults to dashed lines aligned to the value axis for the current layout, and forwards every LayerChart CartesianGrid prop.


  ### `…gridProps`



Every LayerChart grid prop is forwarded as-is. See the [LayerChart Grid documentation](https://www.layerchart.com/docs/components/Grid).


### Tooltip

The hover tooltip. It reads the chart's selection state, dimming unselected series.


  ### `variant`

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

The visual style of the tooltip surface.
  ### `roundness`

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

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

type: `number`

Shows the tooltip by default at this data point index.


### Legend

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


  ### `variant`

type: `"square" | "circle" | "circle-outline" | "rounded-square" | "rounded-square-outline" | "vertical-bar" | "horizontal-bar"`

The visual style of the legend indicators.
  ### `align`

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

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

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

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

type: `boolean` · default: `false`

Lets each legend entry toggle selection of its series.


### Brush

An optional zoom brush below the chart. Include `<EvilBarChart.Brush />` to render it; dragging the range filters the main chart.


  ### `height`

type: `number`

Height of the brush preview strip in pixels.
  ### `formatLabel`

type: `(value: unknown, index: number) => string`

Formats the range-handle labels below the brush.
  ### `onChange`

type: `(range: { startIndex: number; endIndex: number }) => void`

Fires when the brush selection range changes.

