
### Basic Chart

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

<EvilLineChart {data} config={chartConfig} class="h-full w-full p-4" xDataKey="month">
	<EvilLineChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilLineChart.Brush formatLabel={(value) => String(value).substring(0, 3)} />
	<EvilLineChart.Legend isClickable />
	<EvilLineChart.Tooltip />
	<EvilLineChart.Line dataKey="desktop" strokeVariant="solid" isClickable>
		<EvilLineChart.Dot variant="border" />
		<EvilLineChart.ActiveDot variant="colored-border" />
	</EvilLineChart.Line>
	<EvilLineChart.Line dataKey="mobile" strokeVariant="solid" isClickable>
		<EvilLineChart.Dot variant="border" />
		<EvilLineChart.ActiveDot variant="colored-border" />
	</EvilLineChart.Line>
</EvilLineChart>
```

## Installation


  
  
    ### npm

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

### yarn

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

### bun

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

### pnpm

```bash
pnpm dlx shadcn-svelte@latest add @evilcharts/layerchart-line-chart
```
  
  
    
      
        ### Install 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
```
        
      
      
        ### Add the base chart code to your project.
         

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


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

`$lib/components/evilcharts/charts/layerchart-line-chart/active-dot.svelte`

```svelte
<script lang="ts">
	/**
	 * Declares the hovered/active point marker for the <Line /> it is composed
	 * inside. Like <Dot />, it is a configuration slot and renders nothing itself.
	 */
	import { useLineSlots } from './line-slots.svelte.js';
	import type { DotVariant } from '../../ui/layerchart-dot/types.js';

	let { variant }: { variant?: DotVariant } = $props();

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

	$effect.pre(() => {
		slots.registerActiveDot(token, variant);
		return () => slots.unregisterActiveDot(token);
	});
</script>
```

`$lib/components/evilcharts/charts/layerchart-line-chart/buffer-line.svelte.ts`

```ts
import type { Attachment } from 'svelte/attachments';
import { BUFFER_DASH_SIZE, BUFFER_GAP_SIZE } from './types.js';

/**
 * Binary-search the path to find the length at which path.x ≈ targetX,
 * using the browser's native getPointAtLength for exact curve measurement.
 */
function findLengthAtX(path: SVGPathElement, totalLength: number, targetX: number): number {
	let lo = 0;
	let hi = totalLength;
	// ~0.5px precision is more than enough for a dasharray split
	while (hi - lo > 0.5) {
		const mid = (lo + hi) / 2;
		const pt = path.getPointAtLength(mid);
		if (pt.x < targetX) lo = mid;
		else hi = mid;
	}
	return (lo + hi) / 2;
}

/** Builds `<solidLength> 0 4 3 4 3 …` — a solid run, then repeating dash/gap for the buffer. */
function buildDashArray(path: SVGPathElement, splitX: number): string | null {
	const totalLength = path.getTotalLength();
	if (!totalLength) return null;

	const solidLength = findLengthAtX(path, totalLength, splitX);
	const lastSegmentLength = totalLength - solidLength;

	const reps = Math.ceil(lastSegmentLength / (BUFFER_DASH_SIZE + BUFFER_GAP_SIZE)) + 1;
	const dashedPart = Array.from(
		{ length: reps },
		() => `${BUFFER_DASH_SIZE} ${BUFFER_GAP_SIZE}`
	).join(' ');

	return `${solidLength} 0 ${dashedPart}`;
}

/**
 * Renders a line's last segment as dashed while the rest stays solid.
 *
 * Measures the real SVG path with `getTotalLength()` + `getPointAtLength()` and sets
 * `stroke-dasharray` imperatively, so it works with any curve type — a direct port of the
 * reference's `bufferLineShape`.
 *
 * Attaches to the wrapping `<g>` rather than the `<path>`: LayerChart's `<Spline>` cannot forward
 * an attachment (symbol-keyed props do not survive its rest-props plumbing), and an attachment on
 * the `<g>` runs before the child path is mounted. A `MutationObserver` on the subtree covers
 * both — it fires when the path appears and again whenever its `d` changes, which is exactly when
 * the dash must be recomputed (resize, curve change, brush filtering).
 *
 * @param splitX x coordinate of the second-to-last point — where solid meets dashed.
 */
export function bufferLine(splitX: () => number | undefined): Attachment<SVGGElement> {
	return (g) => {
		const x = splitX();
		if (x === undefined) return;

		let lastApplied: string | null = null;

		function apply() {
			const path = g.querySelector('path');
			if (!path) return;

			const dashArray = buildDashArray(path, x!);
			if (!dashArray || dashArray === lastApplied) return;

			lastApplied = dashArray;
			path.setAttribute('stroke-dasharray', dashArray);
		}

		apply();

		const observer = new MutationObserver(apply);
		observer.observe(g, { childList: true, subtree: true, attributeFilter: ['d'] });

		return () => observer.disconnect();
	};
}
```

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

```svelte
<script lang="ts">
	/**
	 * Horizontal left-to-right color gradient for a series. Always rendered — every
	 * fill variant, the stroke, and the dots all 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,
		isExpanded
	}: { id: string; dataKey: string; config: ChartConfig; isExpanded: boolean } = $props();

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

<linearGradient
	id={`${id}-colors-${dataKey}`}
	x1="0"
	y1="0"
	x2="1"
	y2="0"
	gradientUnits={isExpanded ? 'userSpaceOnUse' : 'objectBoundingBox'}
>
	{#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-line-chart/defs/glow-filter.svelte`

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

<filter id={`${id}-glow-${dataKey}`} x="-50%" y="-50%" width="200%" height="200%">
	<feGaussianBlur in="SourceGraphic" stdDeviation="10" 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 2 0"
		result="glow"
	/>
	<feMerge>
		<feMergeNode in="glow" />
		<feMergeNode in="SourceGraphic" />
	</feMerge>
</filter>
```

`$lib/components/evilcharts/charts/layerchart-line-chart/defs/reveal-mask.svelte`

```svelte
<script lang="ts">
	/**
	 * Wipe mask driven by motion.dev, played once when an <Area /> mounts. The same
	 * mask is applied to the area's fill, stroke, and resting dots, so all three
	 * reveal in lockstep — fixing the default behaviour, where the dots appeared
	 * before the line had finished drawing.
	 *
	 * `maskUnits`/`maskContentUnits` are both userSpaceOnUse so every masked element
	 * shares one coordinate space and the wipe edge lands at the same x on each.
	 *
	 * Each rect animates `scaleX` 0 → 1; `originX` decides which edge it grows from.
	 * "edges-in" needs two rects — each half grows inward from an opposite edge.
	 */
	import { motion } from '@humanspeak/svelte-motion';
	import { getRevealAnimation } from '../../../ui/layerchart-chart/intros.js';
	import { REVEAL_DURATION, REVEAL_EASE, SINGLE_REVEAL_ORIGIN } from '../types.js';
	import type { RevealAnimationType } from '../types.js';

	let {
		id,
		type,
		introStartedAt
	}: { id: string; type: RevealAnimationType; introStartedAt: number } = $props();

	const reveal = $derived(
		getRevealAnimation(REVEAL_DURATION, REVEAL_EASE, introStartedAt) ?? {
			initial: { scaleX: 1 },
			animate: { scaleX: 1 },
			transition: { duration: 0, ease: REVEAL_EASE }
		}
	);
</script>

<mask
	id={`${id}-reveal-mask`}
	maskUnits="userSpaceOnUse"
	maskContentUnits="userSpaceOnUse"
	x="0"
	y="0"
	width="100%"
	height="100%"
>
	{#if type === 'edges-in'}
		<!-- left half wipes inward from the left edge toward the centre -->
		<motion.rect
			{...reveal}
			x="0"
			y="0"
			width="50%"
			height="100%"
			fill="white"
			style={{ originX: 0 }}
		/>
		<!-- right half wipes inward from the right edge toward the centre -->
		<motion.rect
			{...reveal}
			x="50%"
			y="0"
			width="50%"
			height="100%"
			fill="white"
			style={{ originX: 1 }}
		/>
	{:else}
		<motion.rect
			{...reveal}
			x="0"
			y="0"
			width="100%"
			height="100%"
			fill="white"
			style={{ originX: SINGLE_REVEAL_ORIGIN[type] }}
		/>
	{/if}
</mask>
```

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

```svelte
<script lang="ts">
	/**
	 * Declares a resting point marker for the <Line /> it is composed inside.
	 * It renders nothing on its own — the parent <Line /> reads its variant and
	 * wires it into the dot slot.
	 */
	import { useLineSlots } from './line-slots.svelte.js';
	import type { DotVariant } from '../../ui/layerchart-dot/types.js';

	let { variant }: { variant?: DotVariant } = $props();

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

	$effect.pre(() => {
		slots.registerDot(token, variant);
		return () => slots.unregisterDot(token);
	});
</script>
```

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

```svelte
<script lang="ts">
	/**
	 * The background grid lines. Defaults to horizontal-only dashed lines and
	 * forwards every LayerChart Grid prop for full control.
	 *
	 * Recharts takes `strokeDasharray` on the grid itself; LayerChart takes the dash pattern on
	 * each axis' line props, so it is threaded into both.
	 */
	import { Grid as LayerGrid } from 'layerchart';
	import { rechartsValueAxisTicks } from '../../ui/layerchart-chart/ticks.js';

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

<LayerGrid
	x={vertical ? { dashArray: strokeDasharray } : false}
	y={horizontal ? { dashArray: strokeDasharray } : false}
	yTicks={rechartsValueAxisTicks}
	{...restProps}
/>
```

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

```ts
// Returns stroke/dot opacity — dims a series only when another is selected
export const getOpacity = (selectedDataKey: string | null, dataKey: string) => {
	if (selectedDataKey === null) {
		return { stroke: 1, dot: 1 };
	}

	return selectedDataKey === dataKey ? { stroke: 1, dot: 1 } : { stroke: 0.3, dot: 0.3 };
};

// Resolves a line's stroke-dasharray — the buffer line manages its own dashes
export const getStrokeDasharray = (enableBufferLine: boolean, isDashed: boolean) => {
	if (enableBufferLine) return undefined;

	return isDashed ? '5 5' : undefined;
};
```

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

```ts
import Root from './line-chart.svelte';
import Line from './line.svelte';
import Dot from './dot.svelte';
import ActiveDot from './active-dot.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 <EvilLineChart.Line/>, <EvilLineChart.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 EvilLineChart: RootComponent & {
	Line: typeof Line;
	Dot: typeof Dot;
	ActiveDot: typeof ActiveDot;
	XAxis: typeof XAxis;
	YAxis: typeof YAxis;
	Grid: typeof Grid;
	Tooltip: typeof Tooltip;
	Legend: typeof Legend;
	Brush: typeof Brush;
} = Object.assign(Root, {
	Line,
	Dot,
	ActiveDot,
	XAxis,
	YAxis,
	Grid,
	Tooltip,
	Legend,
	Brush
});

export type { CurveType, LineAnimationType, StrokeVariant } 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-line-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 { useLineChart } from './line-chart-context.svelte.js';

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

	const chart = useLineChart();

	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-line-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 <Line />.
	 *
	 * 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 { useLineChart } from './line-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 = useLineChart();
	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-line-chart/line-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 { LineAnimationType, CurveType } from './types.js';

const LINE_CHART_KEY = Symbol('evilcharts.line-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 mounted `<Line />` marks, in composition order. */
	seriesKeys: () => string[];
	curveType: () => CurveType;
	animationType: () => LineAnimationType;
	introStartedAt: () => number;
	renderStyle: () => RenderStyle;
	ditherVariant: () => DitherVariant;
	isLoading: () => boolean;
	xAxisLeadingInset: () => number;
	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.
	 */
	registerXAxisDataKey: (token: string, dataKey: string | undefined) => void;
	/** Called by each `<Line />` so geometry, legends, and tooltips use rendered marks only. */
	registerSeries: (token: symbol, dataKey: string, present: boolean) => 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, size?: number) => void;
};

/**
 * Shared state for every part of the chart. Lifted into <EvilLineChart /> so that
 * <Line />, <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 LineChartContext {
	#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 curveType() {
		return this.#options.curveType();
	}
	get animationType() {
		return this.#options.animationType();
	}
	get introStartedAt() {
		return this.#options.introStartedAt();
	}
	get renderStyle() {
		return this.#options.renderStyle();
	}
	get ditherVariant() {
		return this.#options.ditherVariant();
	}
	get isLoading() {
		return this.#options.isLoading();
	}
	get xAxisLeadingInset() {
		return this.#options.xAxisLeadingInset();
	}
	get chartId() {
		return this.#options.chartId();
	}
	get selectedDataKey() {
		return this.#options.selectedDataKey();
	}

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

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

	registerSeries = (token: symbol, dataKey: string, present: boolean) => {
		this.#options.registerSeries(token, dataKey, present);
	};

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

export function setLineChartContext(options: Options) {
	const context = new LineChartContext(options);
	setContext(LINE_CHART_KEY, context);
	return context;
}

/** Reads the chart context, throwing a helpful error when used outside <EvilLineChart /> */
export function useLineChart(): LineChartContext {
	const context = getContext<LineChartContext | undefined>(LINE_CHART_KEY);

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

	return context;
}
```

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

```svelte
<script lang="ts" generics="TData extends Record<string, unknown>">
	/**
	 * Root of the composable line chart. Owns the data, the shared context, the
	 * loading skeleton, and the optional zoom brush. Everything visual — axes,
	 * grid, tooltip, legend, and the lines themselves — is composed as children,
	 * so a consumer renders exactly the parts they need.
	 */
	import { Chart, Html, Svg, type ChartState } from 'layerchart';
	import { scalePoint, type ScalePoint } from 'd3-scale';
	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 LegendRender from './legend-render.svelte';
	import { setLineChartContext } from './line-chart-context.svelte.js';
	import {
		DitherDomLayer,
		type DitherBloom,
		type DitherVariant,
		type RenderStyle
	} from '../../ui/layerchart-dither/index.js';
	import LoadingLine from './loading/loading-line.svelte';
	import { LoadingDataState } from './loading/use-loading-data.svelte.js';
	import TooltipCursor from './tooltip-cursor.svelte';
	import TooltipRender from './tooltip-render.svelte';
	import { LOADING_LINE_DATA_KEY, type CurveType, type LineAnimationType } from './types.js';
	import { SvelteMap, SvelteSet } from 'svelte/reactivity';

	let {
		config,
		data,
		children,
		class: className,
		chartProps,
		accessibility,
		curveType = 'linear',
		animationType = 'left-to-right',
		defaultSelectedDataKey = null,
		onSelectionChange,
		isLoading = false,
		loadingPoints,
		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 — <Line />, <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
		curveType?: CurveType; // default curve interpolation for every <Line />
		animationType?: LineAnimationType; // default intro reveal for every <Line />
		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
		loadingPoints?: number; // number of points 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 introStartedAt = $state(Date.now());
	let chartDimension = $state(untrack(() => initialDimension));
	let previousLoading = untrack(() => isLoading);
	let layerContext = $state<ChartState<Record<string, unknown>, ScalePoint<string>> | undefined>(
		undefined
	);

	$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));

	const loading = new LoadingDataState({
		isLoading: () => isLoading,
		loadingPoints: () => loadingPoints ?? 14
	});

	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);

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

	/**
	 * Which axes are rendered, so the plot area reserves the same 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 SvelteMap<string, number>() };
	const renderedSeries = new SvelteMap<symbol, string>();

	const CHART_MARGIN = 5; // Recharts' default <LineChart margin>
	const X_AXIS_HEIGHT = 30; // Recharts' default <XAxis height>
	const EDGE_LEGEND_HEIGHT = 32;
	let lineContext: ReturnType<typeof setLineChartContext>;
	const edgeLegendPlacement = $derived.by(() => {
		if (isLoading || !lineContext) return null;
		const align = lineContext.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 ? 0 : Math.max(0, ...axesPresent.y.values()))
	});

	// Recharts derives its value domain, legend payload, and tooltip payload from the rendered
	// `<Line />` children. Config only supplies presentation metadata; extra config entries must not
	// create phantom marks or stretch the value scale.
	const seriesKeys = $derived([...new Set(renderedSeries.values())]);
	const displayData = $derived(showBrush && !isLoading ? brush.visibleData : data);
	const chartData = $derived(
		(isLoading ? loading.loadingData : displayData) as Record<string, unknown>[]
	);

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

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

	/** Resolve the nearest category exactly like Recharts, keeping the left row on a midpoint tie. */
	function showCategoryTooltip(event: PointerEvent) {
		if (isLoading || !layerContext || chartData.length === 0) return;

		const box = (event.currentTarget as HTMLElement).getBoundingClientRect();
		const x = event.clientX - box.left;
		const y = event.clientY - box.top;
		const start = padding.left;
		const end = box.width - padding.right;
		const top = padding.top;
		const bottom = box.height - padding.bottom;
		if (x < start || x > end || y < top || y > bottom) {
			layerContext.tooltip.hide();
			return;
		}

		const step = chartData.length > 1 ? (end - start) / (chartData.length - 1) : 0;
		let nearest = 0;
		let nearestDistance = Number.POSITIVE_INFINITY;
		for (let index = 0; index < chartData.length; index += 1) {
			const distance = Math.abs(x - (start + index * step));
			if (distance < nearestDistance - Number.EPSILON) {
				nearest = index;
				nearestDistance = distance;
			}
		}

		layerContext.tooltip.show(event, chartData[nearest]);
	}

	lineContext = setLineChartContext({
		config: () => config,
		data: () => chartData,
		xKey: () => xKey,
		seriesKeys: () => seriesKeys,
		curveType: () => curveType,
		animationType: () => animationType,
		introStartedAt: () => introStartedAt,
		renderStyle: () => renderStyle,
		ditherVariant: () => ditherVariant,
		isLoading: () => isLoading,
		xAxisLeadingInset: () => padding.left,
		chartId: () => chartId,
		selectedDataKey: () => selectedDataKey,
		selectDataKey: (next) => {
			selectedDataKey = next;
			onSelectionChange?.(next);
		},
		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;
		},
		registerSeries: (token, key, present) => {
			if (present) renderedSeries.set(token, key);
			else renderedSeries.delete(token);
		},
		registerAxis: (token, axis, present, size) => {
			if (axis === 'x') {
				if (present) axesPresent.x.add(token);
				else axesPresent.x.delete(token);
			} else if (present) axesPresent.y.set(token, size ?? 42);
			else axesPresent.y.delete(token);
		}
	});
</script>

<ChartContainer
	{config}
	{initialDimension}
	{accessibility}
	bind:dimension={chartDimension}
	class={className}
>
	<LoadingIndicator {isLoading} />
	<LegendRender placement="top" />
	<Chart
		width={chartDimension.width}
		height={chartDimension.height}
		data={chartData}
		x={xKey}
		{series}
		seriesLayout="overlap"
		xScale={scalePoint()}
		xPadding={[0, 0]}
		yBaseline={0}
		yNice
		{padding}
		bind:context={layerContext}
		tooltipContext={{ mode: 'manual' }}
		{...chartProps}
		onpointermove={showCategoryTooltip}
		onpointerleave={() => layerContext?.tooltip.hide()}
		class="h-full w-full"
	>
		{#if renderStyle === 'dither'}
			<Html pointerEvents={false} clip zIndex={0}>
				<DitherDomLayer
					{ditherVariant}
					cellSize={ditherCellSize}
					{bloom}
					paused={isLoading}
					animationDuration={1000}
					animationRevision={introStartedAt}
				/>
			</Html>
		{/if}
		<Svg zIndex={1}>
			{@render children()}
			<TooltipCursor />
			{#if isLoading}
				<LoadingLine {chartId} {curveType} onShimmerExit={loading.onShimmerExit} />
			{/if}
		</Svg>
		<TooltipRender />
	</Chart>
	<LegendRender placement="middle" />
	<LegendRender placement="bottom" />

	{#snippet footer()}
		{#if showBrush && !isLoading}
			<EvilBrush
				data={data as Record<string, unknown>[]}
				chartConfig={config}
				{xDataKey}
				variant="line"
				{curveType}
				height={brushSlot.slot?.height}
				formatLabel={brushSlot.slot?.formatLabel}
				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-line-chart/line-slots.svelte.ts`

```ts
import { getContext, setContext } from 'svelte';
import type { DotVariant } from '../../ui/layerchart-dot/types.js';

const AREA_SLOTS_KEY = Symbol('evilcharts.line-slots');

/**
 * Registry for the `<Dot />` / `<ActiveDot />` children of one `<Line />`.
 *
 * The reference resolves them with `React.Children.forEach`; Svelte cannot inspect a
 * snippet, so each slot registers itself here instead.
 */
export class LineSlots {
	#dotToken: string | null = null;
	#activeDotToken: string | null = null;

	dot = $state<{ variant?: DotVariant } | null>(null);
	activeDot = $state<{ variant?: DotVariant } | null>(null);

	/** Token-keyed so a remount's stale teardown cannot clear the live slot. */
	registerDot(token: string, variant: DotVariant | undefined) {
		this.#dotToken = token;
		this.dot = { variant };
	}

	unregisterDot(token: string) {
		if (this.#dotToken !== token) return;
		this.#dotToken = null;
		this.dot = null;
	}

	registerActiveDot(token: string, variant: DotVariant | undefined) {
		this.#activeDotToken = token;
		this.activeDot = { variant };
	}

	unregisterActiveDot(token: string) {
		if (this.#activeDotToken !== token) return;
		this.#activeDotToken = null;
		this.activeDot = null;
	}
}

export function setLineSlotsContext() {
	const slots = new LineSlots();
	setContext(AREA_SLOTS_KEY, slots);
	return slots;
}

export function useLineSlots(): LineSlots {
	const slots = getContext<LineSlots | undefined>(AREA_SLOTS_KEY);

	if (!slots) {
		throw new Error('<Dot /> and <ActiveDot /> must be composed inside a <Line />');
	}

	return slots;
}
```

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

```svelte
<script lang="ts">
	/**
	 * A single line series. Each <Line /> is fully self-contained: it generates its
	 * own gradient and glow definitions under a unique id, so any number of lines —
	 * each with its own stroke, glow, and clickability — can live in one chart
	 * without style collisions. Compose <Dot /> and <ActiveDot /> inside it to add
	 * point markers.
	 */
	import { getChartContext, Highlight, Points, Spline } from 'layerchart';
	import { useReducedMotion } from '@humanspeak/svelte-motion';
	import type { Snippet } from 'svelte';
	import { resolveCurve } from '../../ui/layerchart-chart/curves.js';
	import { ChartDot } from '../../ui/layerchart-dot/index.js';
	import type { DitherVariant } from '../../ui/layerchart-dither/index.js';
	import { bufferLine } from './buffer-line.svelte.js';
	import ColorGradient from './defs/color-gradient.svelte';
	import GlowFilter from './defs/glow-filter.svelte';
	import RevealMask from './defs/reveal-mask.svelte';
	import { getOpacity, getStrokeDasharray } from './helpers.js';
	import { useLineChart } from './line-chart-context.svelte.js';
	import { setLineSlotsContext } from './line-slots.svelte.js';
	import {
		STROKE_WIDTH,
		type CurveType,
		type LineAnimationType,
		type StrokeVariant
	} from './types.js';

	let {
		dataKey,
		strokeVariant = 'solid',
		strokeWidth = STROKE_WIDTH,
		curveType,
		animationType,
		connectNulls = false,
		isClickable = false,
		glowing = false,
		enableBufferLine = false,
		children,
		lineProps,
		ditherVariant
	}: {
		dataKey: string; // series key — must exist on the data and config
		strokeVariant?: StrokeVariant; // stroke style for this line only
		strokeWidth?: number; // stroke thickness in pixels for this line
		curveType?: CurveType; // curve interpolation — falls back to the chart default
		animationType?: LineAnimationType; // intro reveal — falls back to the chart default
		connectNulls?: boolean; // join segments across null/missing values
		isClickable?: boolean; // lets this line be selected by clicking it
		glowing?: boolean; // applies a soft outer glow to this line
		enableBufferLine?: boolean; // renders this line's last segment as a dashed buffer
		children?: Snippet; // optional <Dot /> and <ActiveDot /> composition
		lineProps?: Record<string, unknown>; // escape hatch for raw LayerChart Spline props
		ditherVariant?: DitherVariant; // ordered-dither texture override
	} = $props();

	const chart = useLineChart();
	/** LayerChart's own context, for the scales the buffer line needs to measure against. */
	const layer = getChartContext();
	const id = $props.id(); // unique id scopes this line's style defs
	const seriesToken = Symbol('line-series');
	$effect.pre(() => {
		chart.registerSeries(seriesToken, dataKey, true);
		return () => chart.registerSeries(seriesToken, dataKey, false);
	});
	// Devices set to "reduce motion" skip the intro reveal entirely
	const shouldReduceMotion = useReducedMotion();

	const slots = setLineSlotsContext();

	const resolvedCurve = $derived(curveType ?? chart.curveType);

	// The reveal is an animated SVG mask — heavier than a static chart — so
	// `"none"` and the OS reduce-motion preference both opt out of it.
	const revealType = $derived<LineAnimationType>(
		shouldReduceMotion.current ? 'none' : (animationType ?? chart.animationType)
	);
	const maskId = $derived(revealType === 'none' ? undefined : `${id}-reveal-mask`);

	const isSelected = $derived(chart.selectedDataKey === dataKey);
	const hasSelection = $derived(chart.selectedDataKey !== null);
	const opacity = $derived(getOpacity(chart.selectedDataKey, dataKey));

	const dotVariant = $derived(slots.dot?.variant);
	const activeDotVariant = $derived(slots.activeDot?.variant);

	const isAnimatedDashed = $derived(strokeVariant === 'animated-dashed');
	const isDashed = $derived(strokeVariant === 'dashed' || isAnimatedDashed);
	const isDither = $derived(chart.renderStyle === 'dither' && !isAnimatedDashed);
	const resolvedDitherVariant = $derived(ditherVariant ?? chart.ditherVariant);

	/**
	 * x of the second-to-last point — where the buffer line's solid run meets the dashes.
	 * Read straight off LayerChart's x scale so it stays in sync with resizes and brush filtering.
	 */
	const splitX = $derived.by(() => {
		if (!enableBufferLine) return undefined;
		const rows = chart.data;
		const row = rows[rows.length - 2];
		if (!row || !chart.xKey) return undefined;
		const scaled = layer.xScale(row[chart.xKey] as never);
		return typeof scaled === 'number' ? scaled : undefined;
	});

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

<!-- The root renders the skeleton line while loading, so real lines step aside -->
{#if !chart.isLoading}
	{@render children?.()}

	<g>
		{#if isClickable}
			<!-- Invisible fat stroke: a 15px hit area so the thin line is easy to click -->
			<Spline
				seriesKey={dataKey}
				curve={resolveCurve(resolvedCurve)}
				stroke="transparent"
				strokeWidth={15}
				defined={connectNulls
					? undefined
					: (d: Record<string, unknown>) => d[dataKey] !== null && d[dataKey] !== undefined}
				motion="none"
				class="cursor-pointer"
				onclick={select}
			/>
		{/if}
		<g {@attach enableBufferLine ? bufferLine(() => splitX) : undefined}>
			<Spline
				seriesKey={dataKey}
				curve={resolveCurve(resolvedCurve)}
				strokeOpacity={opacity.stroke}
				stroke={isDither ? 'transparent' : `url(#${id}-colors-${dataKey})`}
				{strokeWidth}
				stroke-dasharray={getStrokeDasharray(enableBufferLine, isDashed)}
				filter={glowing ? `url(#${id}-glow-${dataKey})` : undefined}
				defined={connectNulls
					? undefined
					: (d: Record<string, unknown>) => d[dataKey] !== null && d[dataKey] !== undefined}
				mask={maskId ? `url(#${maskId})` : undefined}
				data-evil-dither-mark={isDither ? 'stroke' : undefined}
				data-evil-dither-key={isDither ? dataKey : undefined}
				data-evil-dither-variant={isDither ? resolvedDitherVariant : undefined}
				data-evil-dither-reveal={isDither ? revealType : undefined}
				data-evil-dither-glow={isDither && glowing ? 'true' : undefined}
				class={[
					isClickable && 'cursor-pointer',
					isAnimatedDashed && !hasSelection && 'evil-line-animated-dash'
				]
					.filter(Boolean)
					.join(' ') || undefined}
				onclick={select}
				motion="none"
				{...lineProps}
			/>
		</g>
	</g>

	{#if slots.dot}
		<!-- Resting point markers, wired to the intro reveal so they wipe in with the line -->
		<Points seriesKey={dataKey} fill="none" stroke="none">
			{#snippet children({ points })}
				{#each points as point, index (index)}
					<ChartDot
						cx={point.x}
						cy={point.y}
						type={dotVariant}
						{dataKey}
						chartId={id}
						fillOpacity={opacity.dot}
						{maskId}
					/>
				{/each}
			{/snippet}
		</Points>
	{/if}

	{#if slots.activeDot}
		<!-- The active dot is left unmasked: it only appears on hover, after the intro -->
		<Highlight axis="none">
			{#snippet points({ points })}
				{#each points.filter((p) => (p as { seriesKey?: string }).seriesKey === dataKey) as point, index (index)}
					<ChartDot
						cx={point.x}
						cy={point.y}
						type={activeDotVariant}
						{dataKey}
						chartId={id}
						fillOpacity={opacity.dot}
					/>
				{/each}
			{/snippet}
		</Highlight>
	{/if}

	<defs>
		{#if revealType !== 'none'}
			<RevealMask {id} type={revealType} introStartedAt={chart.introStartedAt} />
		{/if}
		<ColorGradient {id} {dataKey} config={chart.config} isExpanded={false} />
		{#if glowing}
			<GlowFilter {id} {dataKey} />
		{/if}
	</defs>
{/if}

<style>
	/*
		Move a fixed dash pattern along the stroke. Animating the dash lengths makes the visible dash
		shrink to zero every half-cycle, which reads as a flicker instead of directional motion.
	*/
	@keyframes evil-line-dash-offset {
		from {
			stroke-dashoffset: 0;
		}
		to {
			stroke-dashoffset: -10;
		}
	}

	:global(.evil-line-animated-dash) {
		animation: evil-line-dash-offset 1s linear infinite;
	}

	@media (prefers-reduced-motion: reduce) {
		:global(.evil-line-animated-dash) {
			animation: none;
		}
	}
</style>
```

`$lib/components/evilcharts/charts/layerchart-line-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-line-chart/loading/loading-line.svelte`

```svelte
<script lang="ts">
	/**
	 * The skeleton line shown while the chart is loading. Rendered by the root in
	 * place of the real lines, paired with its own masked shimmer pattern.
	 */
	import { Spline } from 'layerchart';
	import { resolveCurve } from '../../../ui/layerchart-chart/curves.js';
	import { LOADING_LINE_DATA_KEY, STROKE_WIDTH, type CurveType } from '../types.js';
	import LoadingPattern from './loading-pattern.svelte';

	let {
		chartId,
		curveType,
		onShimmerExit
	}: { chartId: string; curveType: CurveType; onShimmerExit: () => void } = $props();
</script>

<Spline
	y={LOADING_LINE_DATA_KEY}
	curve={resolveCurve(curveType)}
	stroke="currentColor"
	strokeOpacity={0.5}
	strokeWidth={STROKE_WIDTH}
	motion="none"
	mask={`url(#${chartId}-loading-mask)`}
/>
<defs>
	<LoadingPattern {chartId} {onShimmerExit} />
</defs>
```

`$lib/components/evilcharts/charts/layerchart-line-chart/loading/loading-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-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-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-gradient)`}
	/>
</pattern>
<mask id={`${chartId}-loading-mask`} maskUnits="userSpaceOnUse">
	<rect width="100%" height="100%" fill={`url(#${chartId}-loading-pattern)`} />
</mask>
```

`$lib/components/evilcharts/charts/layerchart-line-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;
	#loadingPoints: () => number;
	/** Toggled by `onShimmerExit`; regenerates the skeleton data once per shimmer loop. */
	#tick = $state(0);

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

	get loadingData() {
		this.#tick;
		return getLoadingData(this.#loadingPoints());
	}

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

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

```svelte
<script lang="ts">
	/**
	 * Renders the registered `<Tooltip cursor>` slot: the dashed vertical rule that follows the
	 * pointer. Lives inside `<Svg>`, matching Recharts' tooltip cursor.
	 */
	import { Highlight, getChartContext } from 'layerchart';
	import { useLineChart } from './line-chart-context.svelte.js';
	import { STROKE_WIDTH } from './types.js';

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

	const slot = $derived(chart.slots.tooltip);
	const defaultRow = $derived(
		slot?.defaultIndex === undefined ? undefined : chart.data[slot.defaultIndex]
	);
	// The hovered row wins over `defaultIndex`, so pointer movement is not pinned to the initial row.
	const cursorRow = $derived(layer.tooltip.data ?? defaultRow);
</script>

{#if slot?.cursor && !chart.isLoading}
	<Highlight axis="x" lines={{ dashArray: '3 3', strokeWidth: STROKE_WIDTH }} data={cursorRow} />
{/if}
```

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

	const chart = useLineChart();
	/** 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-line-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 { useLineChart } from './line-chart-context.svelte.js';

	let {
		variant,
		roundness,
		defaultIndex,
		cursor = true
	}: {
		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
		cursor?: boolean; // whether the vertical cursor line follows the pointer
	} = $props();

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

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

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

```ts
import type { CurveType } from '../../ui/layerchart-chart/curves.js';

// Constants
export const STROKE_WIDTH = 0.8; // default series stroke — <Line strokeWidth> overrides it
export const LOADING_LINE_DATA_KEY = 'loading';
export const LOADING_ANIMATION_DURATION = 2000; // in milliseconds
export const REVEAL_DURATION = 1; // intro wipe length, in seconds
export const REVEAL_EASE: [number, number, number, number] = [0, 0.7, 0.5, 1]; // intro wipe easing

export const BUFFER_DASH_SIZE = 4;
export const BUFFER_GAP_SIZE = 3;

export type StrokeVariant = 'solid' | 'dashed' | 'animated-dashed';

/**
 * Direction of the custom motion.dev intro reveal. LayerChart's own line animation
 * is permanently disabled (Recharts' equivalent drew the line after the dots had
 * already popped in) — these reveals replace it.
 *
 * NOTE: a reveal is a per-frame animated SVG mask, 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 LineAnimationType =
	'none' | 'left-to-right' | 'right-to-left' | 'center-out' | 'edges-in';
export type RevealAnimationType = Exclude<LineAnimationType, 'none'>;

// motion `originX` for each single-rect reveal — the edge the wipe grows from.
// 0 = left edge, 1 = right edge, 0.5 = centre (grows outward to both edges).
export const SINGLE_REVEAL_ORIGIN: Record<Exclude<RevealAnimationType, 'edges-in'>, number> = {
	'left-to-right': 0,
	'right-to-left': 1,
	'center-out': 0.5
};

export type { CurveType };
```

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

```svelte
<script lang="ts">
	/**
	 * The horizontal category axis. Ships with the chart's flat default styling and
	 * forwards every LayerChart Axis prop, so `tickFormatter`, `ticks`, etc. are
	 * passed straight through. Hidden automatically while the chart is loading.
	 *
	 * `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 { useLineChart } from './line-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 = useLineChart();
	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,
			leadingInset: chart.xAxisLeadingInset,
			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"
		data-evil-scale="point"
		{ticks}
		rule={axisLine}
		tickMarks={tickLine}
		tickLength={translatedTickLength}
		{format}
		{...restProps}
	/>
{/if}
```

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

```svelte
<script lang="ts">
	/**
	 * The vertical value axis. Forwards every LayerChart Axis prop.
	 * Hidden automatically while the chart is loading.
	 */
	import { Axis, getChartContext } from 'layerchart';
	import {
		layerChartFormatter,
		measureRechartsYAxisWidth,
		rechartsValueAxisTicks
	} from '../../ui/layerchart-chart/ticks.js';
	import type { ComponentProps } from 'svelte';
	import { useLineChart } from './line-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;
		width?: number | 'auto';
	};

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

	const chart = useLineChart();
	const layer = getChartContext();
	const token = $props.id();
	const format = $derived(
		tickFormatter ? layerChartFormatter(tickFormatter) : (value: unknown) => String(value)
	);
	const tickValues = $derived(rechartsValueAxisTicks(layer.yScale));
	const resolvedWidth = $derived(
		width === 'auto'
			? measureRechartsYAxisWidth(
					tickValues.map((value, index) => format(value, index)),
					tickMargin
				)
			: width
	);

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

{#if !chart.isLoading}
	<Axis
		placement="left"
		ticks={rechartsValueAxisTicks}
		rule={axisLine}
		tickMarks={tickLine}
		tickLength={6}
		tickLabelProps={{ ...tickLabelProps, dx: -(6 + tickMargin) }}
		{format}
		{...restProps}
	/>
{/if}
```
        
      
       
        ### Add the main chart component.
        

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

Below is the main chart component.


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

export type ThemeKey = keyof typeof THEMES;

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

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

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

export { THEMES };

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return context;
}
```

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return result;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	let configLabelKey: string = key;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		return kept.reverse();
	};
}

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Next, create `legend.svelte` inside `evilcharts/ui` 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;
};
```
        
        

Finally, create `dot.svelte` inside `evilcharts/ui` and paste the code there.


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

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

```svelte
<script lang="ts">
	// The reference wraps each variant in `React.memo`; Svelte's fine-grained updates make that
	// unnecessary, so the memo boundaries are dropped and nothing else changes.
	import ColoredBorderDot from './colored-border-dot.svelte';
	import DefaultDot from './default-dot.svelte';
	import PrimaryBorderDot from './primary-border-dot.svelte';
	import type { ChartDotProps } from './types.js';

	let {
		cx,
		cy,
		dataKey,
		chartId,
		class: className,
		fillOpacity = 1,
		type = 'default',
		maskId,
		gradientX = 0,
		gradientWidth = '100%'
	}: ChartDotProps = $props();

	const dotId = $props.id();
	const gradientUrl = $derived(`url(#${chartId}-colors-${String(dataKey)})`);
</script>

{#if cx !== undefined && cy !== undefined}
	{#if type === 'border'}
		<PrimaryBorderDot
			{cx}
			{cy}
			{dotId}
			{fillOpacity}
			{gradientUrl}
			class={className}
			{maskId}
			{gradientX}
			{gradientWidth}
		/>
	{:else if type === 'colored-border'}
		<ColoredBorderDot
			{cx}
			{cy}
			{dotId}
			{fillOpacity}
			{gradientUrl}
			class={className}
			{maskId}
			{gradientX}
			{gradientWidth}
		/>
	{:else}
		<DefaultDot
			{cx}
			{cy}
			{dotId}
			{fillOpacity}
			{gradientUrl}
			class={className}
			{maskId}
			{gradientX}
			{gradientWidth}
		/>
	{/if}
{/if}
```

`$lib/components/evilcharts/ui/layerchart-dot/colored-border-dot.svelte`

```svelte
<script lang="ts">
	import { cn } from '$lib/utils.js';
	import type { DotVariantProps } from './types.js';

	let {
		cx,
		cy,
		dotId,
		fillOpacity,
		gradientUrl,
		class: className,
		maskId,
		gradientX,
		gradientWidth
	}: DotVariantProps = $props();

	const r = 3;
	const strokeWidth = 1;
</script>

<g class={cn(className, 'text-background')} mask={maskId ? `url(#${maskId})` : undefined}>
	<defs>
		<clipPath id={`dot-clip-${dotId}`}>
			<circle {cx} {cy} r={r + strokeWidth / 2} />
		</clipPath>
	</defs>
	<!-- Gradient stroke (border) via clipped rect -->
	<rect
		x={gradientX}
		y={cy - r - strokeWidth / 2}
		width={gradientWidth}
		height={(r + strokeWidth / 2) * 2}
		fill={gradientUrl}
		fill-opacity={fillOpacity}
		clip-path={`url(#dot-clip-${dotId})`}
	/>
	<!-- Inner solid fill -->
	<circle {cx} {cy} r={r - strokeWidth / 2} fill="currentColor" />
</g>
```

`$lib/components/evilcharts/ui/layerchart-dot/default-dot.svelte`

```svelte
<script lang="ts">
	import type { DotVariantProps } from './types.js';

	let {
		cx,
		cy,
		dotId,
		fillOpacity,
		gradientUrl,
		class: className,
		maskId,
		gradientX,
		gradientWidth
	}: DotVariantProps = $props();

	const r = 3;
</script>

<g class={className} mask={maskId ? `url(#${maskId})` : undefined}>
	<defs>
		<clipPath id={`dot-clip-${dotId}`}>
			<circle {cx} {cy} {r} />
		</clipPath>
	</defs>
	<!-- Full-width gradient rectangle clipped to dot shape -->
	<rect
		x={gradientX}
		y={cy - r}
		width={gradientWidth}
		height={r * 2}
		fill={gradientUrl}
		fill-opacity={fillOpacity}
		clip-path={`url(#dot-clip-${dotId})`}
	/>
</g>
```

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

```ts
export { default as ChartDot } from './chart-dot.svelte';
export type { ChartDotProps, DotVariant, DotVariantProps } from './types.js';
```

`$lib/components/evilcharts/ui/layerchart-dot/primary-border-dot.svelte`

```svelte
<script lang="ts">
	import { cn } from '$lib/utils.js';
	import type { DotVariantProps } from './types.js';

	let {
		cx,
		cy,
		dotId,
		fillOpacity,
		gradientUrl,
		class: className,
		maskId,
		gradientX,
		gradientWidth
	}: DotVariantProps = $props();

	const r = 6;
	const strokeWidth = 5;
</script>

<g class={cn(className, 'text-background')} mask={maskId ? `url(#${maskId})` : undefined}>
	<defs>
		<clipPath id={`dot-clip-${dotId}`}>
			<circle {cx} {cy} {r} />
		</clipPath>
	</defs>
	<!-- Background stroke (border) -->
	<circle {cx} {cy} {r} fill="currentColor" />
	<!-- Inner gradient circle clipped -->
	<rect
		x={gradientX}
		y={cy - (r - strokeWidth / 2)}
		width={gradientWidth}
		height={(r - strokeWidth / 2) * 2}
		fill={gradientUrl}
		fill-opacity={fillOpacity}
		clip-path={`url(#dot-clip-inner-${dotId})`}
	/>
	<defs>
		<clipPath id={`dot-clip-inner-${dotId}`}>
			<circle {cx} {cy} r={r - strokeWidth / 2} />
		</clipPath>
	</defs>
</g>
```

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

```ts
export type DotVariant = 'default' | 'border' | 'colored-border';

export type ChartDotProps = {
	cx?: number;
	cy?: number;
	dataKey: string;
	chartId: string;
	class?: string;
	fillOpacity?: number;
	type?: DotVariant;
	/** Optional SVG <mask> id — lets the dot share an area's intro reveal wipe. */
	maskId?: string;
	/**
	 * Left edge and width of the gradient rect each dot is clipped out of.
	 *
	 * The reference draws a plot-wide rect and clips it to a circle, so a dot samples the series'
	 * horizontal gradient at its own x. That assumes the origin is the plot's left edge, which is
	 * true in a cartesian chart but not inside a centred `<Group>` — there, `x="0"` starts at the
	 * *centre* and every dot left of it disappeared. A radial chart passes its own plot span.
	 */
	gradientX?: number | string;
	gradientWidth?: number | string;
};

export type DotVariantProps = {
	cx: number;
	cy: number;
	dotId: string;
	fillOpacity: number;
	gradientUrl: string;
	class?: string;
	maskId?: string;
	gradientX: number | string;
	gradientWidth: number | string;
};
```
        
      
    
  


## Usage

The line chart is composable. `<EvilLineChart>` is the container, and every part hangs off it as a compound member — `<EvilLineChart.Grid>`, `<EvilLineChart.XAxis>`, `<EvilLineChart.YAxis>`, `<EvilLineChart.Legend>`, `<EvilLineChart.Tooltip>`, and one or more `<EvilLineChart.Line>` — as children. Each `<Line>` sets its own `strokeVariant`, `curveType`, `glowing`, `enableBufferLine`, and `isClickable`, so one chart can mix stroke styles and make only some series interactive.

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

```svelte
<EvilLineChart {data} config={chartConfig} curveType="monotone">
	<EvilLineChart.Grid />
	<EvilLineChart.XAxis dataKey="month" />
	<EvilLineChart.YAxis />
	<EvilLineChart.Legend isClickable />
	<EvilLineChart.Tooltip />
	<EvilLineChart.Line dataKey="desktop" strokeVariant="solid" isClickable>
		<EvilLineChart.Dot variant="border" />
		<EvilLineChart.ActiveDot variant="colored-border" />
	</EvilLineChart.Line>
	<EvilLineChart.Line dataKey="mobile" strokeVariant="dashed" glowing>
		<EvilLineChart.ActiveDot variant="default" />
	</EvilLineChart.Line>
</EvilLineChart>
```

### Interactive Selection

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

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

### Loading State

### isLoading='true'

```svelte
<script lang="ts">
	import { EvilLineChart } from '$lib/components/evilcharts/charts/layerchart-line-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:7] -->
<EvilLineChart
	data={[]}
	config={chartConfig}
	class="h-full w-full p-4"
	isLoading={true}
	curveType="bump"
>
	<EvilLineChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilLineChart.YAxis dataKey="desktop" />
	<EvilLineChart.Legend isClickable />
	<EvilLineChart.Tooltip />
	<EvilLineChart.Line dataKey="desktop" strokeVariant="solid" isClickable>
		<EvilLineChart.ActiveDot variant="default" />
	</EvilLineChart.Line>
	<EvilLineChart.Line dataKey="mobile" strokeVariant="solid" isClickable>
		<EvilLineChart.ActiveDot variant="default" />
	</EvilLineChart.Line>
</EvilLineChart>
```
>  
  

Pass `isLoading` to show the loading skeleton, and `curveType` to shape its curve. Here, `curveType='bump'` makes it look more realistic.




### Buffer Line

### enableBufferLine='true'

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

<EvilLineChart {data} config={chartConfig} class="h-full w-full p-4" xDataKey="month">
	<EvilLineChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilLineChart.Brush />
	<EvilLineChart.Legend isClickable />
	<EvilLineChart.Tooltip />
	<!-- [!code highlight:4] -->
	<EvilLineChart.Line dataKey="desktop" strokeVariant="solid" enableBufferLine isClickable>
		<EvilLineChart.Dot variant="border" />
		<EvilLineChart.ActiveDot variant="colored-border" />
	</EvilLineChart.Line>
	<!-- [!code highlight:4] -->
	<EvilLineChart.Line dataKey="mobile" strokeVariant="solid" enableBufferLine isClickable>
		<EvilLineChart.Dot variant="border" />
		<EvilLineChart.ActiveDot variant="colored-border" />
	</EvilLineChart.Line>
</EvilLineChart>
```
>  
  

With `enableBufferLine`, each line's last segment renders as a dashed pattern while the rest stays solid — ideal for flagging projected, estimated, or incomplete data, as seen in financial and forecasting charts.




## Examples

Examples with different `variants` — change the `curveType` and `strokeVariant`.

### Gradient Colors

### gradient colors

```svelte
<script lang="ts">
	import { EvilLineChart } from '$lib/components/evilcharts/charts/layerchart-line-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: ['red', 'orange', 'rosybrown', 'purple', 'blue'], // [!code highlight]
				dark: ['red', 'orange', 'rosybrown', 'purple', 'blue'] // [!code highlight]
			}
		},
		mobile: {
			label: 'Mobile',
			colors: {
				light: ['gray'],
				dark: ['gray']
			}
		}
	} satisfies ChartConfig;
</script>

<EvilLineChart {data} config={chartConfig} class="h-full w-full p-4">
	<EvilLineChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilLineChart.Legend isClickable />
	<EvilLineChart.Tooltip />
	<EvilLineChart.Line dataKey="desktop" strokeVariant="solid" isClickable>
		<EvilLineChart.Dot variant="colored-border" />
		<EvilLineChart.ActiveDot variant="default" />
	</EvilLineChart.Line>
	<EvilLineChart.Line dataKey="mobile" strokeVariant="solid" isClickable>
		<EvilLineChart.Dot variant="colored-border" />
		<EvilLineChart.ActiveDot variant="default" />
	</EvilLineChart.Line>
</EvilLineChart>
```
### gradient colors - bump

```svelte
<script lang="ts">
	import { EvilLineChart } from '$lib/components/evilcharts/charts/layerchart-line-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: ['red', 'orange', 'rosybrown', 'purple', 'blue'],
				dark: ['red', 'orange', 'rosybrown', 'purple', 'blue']
			}
		},
		mobile: {
			label: 'Mobile',
			colors: {
				light: ['gray'],
				dark: ['gray']
			}
		}
	} satisfies ChartConfig;
</script>

<!-- [!code highlight:6] -->
<EvilLineChart {data} config={chartConfig} class="h-full w-full p-4" curveType="bump">
	<EvilLineChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilLineChart.Legend isClickable />
	<EvilLineChart.Tooltip />
	<EvilLineChart.Line dataKey="desktop" strokeVariant="solid" isClickable>
		<EvilLineChart.Dot variant="colored-border" />
		<EvilLineChart.ActiveDot variant="default" />
	</EvilLineChart.Line>
	<EvilLineChart.Line dataKey="mobile" strokeVariant="solid" isClickable>
		<EvilLineChart.Dot variant="colored-border" />
		<EvilLineChart.ActiveDot variant="default" />
	</EvilLineChart.Line>
</EvilLineChart>
```

### Curve Types

### curveType='bump'

```svelte
<script lang="ts">
	import { EvilLineChart } from '$lib/components/evilcharts/charts/layerchart-line-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] -->
<EvilLineChart {data} config={chartConfig} class="h-full w-full p-4" curveType="bump">
	<EvilLineChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilLineChart.YAxis dataKey="desktop" />
	<EvilLineChart.Legend isClickable />
	<EvilLineChart.Tooltip />
	<EvilLineChart.Line dataKey="desktop" strokeVariant="solid" isClickable>
		<EvilLineChart.Dot variant="default" />
		<EvilLineChart.ActiveDot variant="default" />
	</EvilLineChart.Line>
	<EvilLineChart.Line dataKey="mobile" strokeVariant="solid" isClickable>
		<EvilLineChart.Dot variant="default" />
		<EvilLineChart.ActiveDot variant="default" />
	</EvilLineChart.Line>
</EvilLineChart>
```
### curveType='step'

```svelte
<script lang="ts">
	import { EvilLineChart } from '$lib/components/evilcharts/charts/layerchart-line-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] -->
<EvilLineChart {data} config={chartConfig} class="h-full w-full p-4" curveType="step">
	<EvilLineChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilLineChart.YAxis dataKey="desktop" />
	<EvilLineChart.Legend isClickable />
	<EvilLineChart.Tooltip />
	<EvilLineChart.Line dataKey="desktop" strokeVariant="solid" isClickable>
		<EvilLineChart.Dot variant="default" />
		<EvilLineChart.ActiveDot variant="default" />
	</EvilLineChart.Line>
	<EvilLineChart.Line dataKey="mobile" strokeVariant="solid" isClickable>
		<EvilLineChart.Dot variant="default" />
		<EvilLineChart.ActiveDot variant="default" />
	</EvilLineChart.Line>
</EvilLineChart>
```
### curveType='monotoneY'

```svelte
<script lang="ts">
	import { EvilLineChart } from '$lib/components/evilcharts/charts/layerchart-line-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] -->
<EvilLineChart {data} config={chartConfig} class="h-full w-full p-4" curveType="monotoneY">
	<EvilLineChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilLineChart.YAxis dataKey="desktop" />
	<EvilLineChart.Legend isClickable />
	<EvilLineChart.Tooltip />
	<EvilLineChart.Line dataKey="desktop" strokeVariant="solid" isClickable>
		<EvilLineChart.Dot variant="default" />
		<EvilLineChart.ActiveDot variant="default" />
	</EvilLineChart.Line>
	<EvilLineChart.Line dataKey="mobile" strokeVariant="solid" isClickable>
		<EvilLineChart.Dot variant="default" />
		<EvilLineChart.ActiveDot variant="default" />
	</EvilLineChart.Line>
</EvilLineChart>
```

### Stroke Variants

### strokeVariant='solid'

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

<EvilLineChart {data} config={chartConfig} class="h-full w-full p-4">
	<EvilLineChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilLineChart.YAxis dataKey="desktop" />
	<EvilLineChart.Legend isClickable />
	<EvilLineChart.Tooltip />
	<!-- [!code highlight:3] -->
	<EvilLineChart.Line dataKey="desktop" strokeVariant="solid" isClickable>
		<EvilLineChart.ActiveDot variant="default" />
	</EvilLineChart.Line>
	<!-- [!code highlight:3] -->
	<EvilLineChart.Line dataKey="mobile" strokeVariant="solid" isClickable>
		<EvilLineChart.ActiveDot variant="default" />
	</EvilLineChart.Line>
</EvilLineChart>
```
### strokeVariant='dashed'

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

<EvilLineChart {data} config={chartConfig} class="h-full w-full p-4">
	<EvilLineChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilLineChart.YAxis dataKey="desktop" />
	<EvilLineChart.Legend isClickable />
	<EvilLineChart.Tooltip />
	<!-- [!code highlight:3] -->
	<EvilLineChart.Line dataKey="desktop" strokeVariant="dashed" isClickable>
		<EvilLineChart.ActiveDot variant="default" />
	</EvilLineChart.Line>
	<!-- [!code highlight:3] -->
	<EvilLineChart.Line dataKey="mobile" strokeVariant="dashed" isClickable>
		<EvilLineChart.ActiveDot variant="default" />
	</EvilLineChart.Line>
</EvilLineChart>
```
### strokeVariant='animated-dashed'

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

<EvilLineChart {data} config={chartConfig} class="h-full w-full p-4">
	<EvilLineChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilLineChart.YAxis dataKey="desktop" />
	<EvilLineChart.Legend isClickable />
	<EvilLineChart.Tooltip />
	<!-- [!code highlight:3] -->
	<EvilLineChart.Line dataKey="desktop" strokeVariant="animated-dashed" isClickable>
		<EvilLineChart.ActiveDot variant="default" />
	</EvilLineChart.Line>
	<!-- [!code highlight:3] -->
	<EvilLineChart.Line dataKey="mobile" strokeVariant="animated-dashed" isClickable>
		<EvilLineChart.ActiveDot variant="default" />
	</EvilLineChart.Line>
</EvilLineChart>
```

### Glowing Lines

### glowing - gradient colors

```svelte
<script lang="ts">
	import { EvilLineChart } from '$lib/components/evilcharts/charts/layerchart-line-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: ['red', 'orange', 'rosybrown', 'purple', 'blue'],
				dark: ['red', 'orange', 'rosybrown', 'purple', 'blue']
			}
		},
		mobile: {
			label: 'Mobile',
			colors: {
				light: ['gray'],
				dark: ['gray']
			}
		}
	} satisfies ChartConfig;
</script>

<EvilLineChart {data} config={chartConfig} class="h-full w-full p-4">
	<EvilLineChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilLineChart.Legend isClickable />
	<EvilLineChart.Tooltip />
	<!-- [!code highlight:4] -->
	<EvilLineChart.Line dataKey="desktop" strokeVariant="solid" glowing isClickable>
		<EvilLineChart.Dot variant="colored-border" />
		<EvilLineChart.ActiveDot variant="default" />
	</EvilLineChart.Line>
	<EvilLineChart.Line dataKey="mobile" strokeVariant="solid" isClickable>
		<EvilLineChart.Dot variant="colored-border" />
		<EvilLineChart.ActiveDot variant="default" />
	</EvilLineChart.Line>
</EvilLineChart>
```
### glowing - solid colors

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

<EvilLineChart {data} config={chartConfig} class="h-full w-full p-4">
	<EvilLineChart.XAxis dataKey="month" tickFormatter={(value) => String(value).substring(0, 3)} />
	<EvilLineChart.Legend isClickable />
	<EvilLineChart.Tooltip />
	<EvilLineChart.Line dataKey="desktop" strokeVariant="solid" isClickable>
		<EvilLineChart.Dot variant="border" />
		<EvilLineChart.ActiveDot variant="colored-border" />
	</EvilLineChart.Line>
	<!-- [!code highlight:4] -->
	<EvilLineChart.Line dataKey="mobile" strokeVariant="solid" glowing isClickable>
		<EvilLineChart.Dot variant="border" />
		<EvilLineChart.ActiveDot variant="colored-border" />
	</EvilLineChart.Line>
</EvilLineChart>
```

### Dither rendering

Set `renderStyle="dither"` on the existing chart root for a responsive ordered-dither stroke while the SVG line remains the tooltip, selection, dot, and brush target. A line-level `ditherVariant` overrides the root texture.

### renderStyle='dither'

```svelte
<script lang="ts">
	import {
		EvilLineChart,
		type ChartConfig
	} from '$lib/components/evilcharts/charts/layerchart-line-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'], dark: ['#10b981'] } },
		mobile: { label: 'Mobile', colors: { light: ['#be123c'], dark: ['#f43f5e'] } }
	} satisfies ChartConfig;
</script>

<EvilLineChart
	{data}
	{config}
	xDataKey="month"
	renderStyle="dither"
	bloom="low"
	class="h-full w-full p-4"
>
	<EvilLineChart.Grid /><EvilLineChart.XAxis dataKey="month" /><EvilLineChart.Legend
		isClickable
	/><EvilLineChart.Tooltip />
	<EvilLineChart.Line dataKey="desktop" isClickable /><EvilLineChart.Line
		dataKey="mobile"
		strokeVariant="dashed"
		isClickable
	/>
</EvilLineChart>
```

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

## API Reference

Props below are grouped by the component they belong to.

### EvilLineChart

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


  ### `data` (required)

type: `TData[]`

The chart data — an array of objects, each a 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, with a color or color array.
  ### `children` (required)

type: `Snippet`

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

type: `"basis" | "bumpX" | "bumpY" | "bump" | "linear" | "natural" | "monotoneX" | "monotoneY" | "monotone" | "step" | …` · default: `"linear"`

The default curve interpolation for every `<Line />`; each can override it locally.
  ### `animationType`

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

Direction of the intro reveal for every `<Line />`. `"none"` disables it; the OS reduce-motion preference falls back to `"none"` automatically.
  ### `defaultSelectedDataKey`

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

The data key selected by default.
  ### `onSelectionChange`

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

Fires when a series is selected or deselected via a clickable `<Line />` or `<Legend />`. Receives the data key, or `null` when deselected.
  ### `isLoading`

type: `boolean` · default: `false`

Shows a shimmer loading skeleton while data is being fetched.
  ### `loadingPoints`

type: `number` · default: `14`

Data points shown in the loading skeleton.
  ### `xDataKey`

type: `keyof TData & string`

The x-axis data key. Only the brush footer needs it — the axis reads its 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 LineChart>`

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


### Line

A single line series. Each `<Line />` generates its own gradient and glow definitions, so a chart can hold any number — each with its own stroke, glow, and clickability.


  ### `dataKey` (required)

type: `string`

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

type: `"solid" | "dashed" | "animated-dashed"` · default: `"solid"`

This line's stroke style.
  ### `strokeWidth`

type: `number` · default: `0.8`

Stroke thickness for this line, in pixels.
  ### `curveType`

type: `"basis" | "bump" | "linear" | "natural" | "monotoneX" | "monotoneY" | "monotone" | "step" | "stepBefore" | "stepAfter" | …`

The curve interpolation for this line. Falls back to the chart's `curveType` when omitted.
  ### `animationType`

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

The intro reveal animation for this line. Falls back to the chart's `animationType` when omitted.
  ### `connectNulls`

type: `boolean` · default: `false`

Whether to connect line segments across null or missing values.
  ### `isClickable`

type: `boolean` · default: `false`

Lets this line be selected by clicking it. When any line is selected, unselected lines become semi-transparent.
  ### `glowing`

type: `boolean` · default: `false`

Applies a soft outer glow to this line.
  ### `enableBufferLine`

type: `boolean` · default: `false`

Renders this line's last segment as a dashed buffer while the rest stays solid. Useful for indicating projected or incomplete data at the end of a series.
  ### `children`

type: `Snippet`

Optional `<Dot />` and `<ActiveDot />` markers for this line.
  ### `lineProps`

type: `ComponentProps<typeof Line>`

Escape hatch for raw props forwarded to the underlying LayerChart Line component.


### Dot and ActiveDot

Point markers composed inside a `<Line />`. `<Dot />` is the resting marker, `<ActiveDot />` the hovered one. They render nothing themselves — the parent `<Line />` reads their `variant`.


  ### `variant`

type: `"default" | "border" | "colored-border"`

The visual style of the point marker.


### 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 through. They hide automatically while the chart loads.


  ### `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 horizontal-only dashed lines 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 so its content dims unselected series.


  ### `variant`

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

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

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

Controls the border-radius of the tooltip.
  ### `defaultIndex`

type: `number`

Shows the tooltip by default at this data-point index.
  ### `cursor`

type: `boolean` · default: `true`

Whether the vertical cursor line follows the pointer on hover.


### Legend

The series legend. When the chart is clickable, 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 `<EvilLineChart.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.

