shadcn-svelte map
DocsComponentsBlocks
All blocks

Region analytics

Data

Shade sales territories by revenue, orders or growth and rank them side by side.

Use the arrow keys to pan, plus and minus to zoom, and Shift with the arrow keys to rotate.

Centre

29% of all revenue

Revenue
€4.7M
Orders
26,900
Growth
+18%

Install

Adds the block to src/lib/components/region-analytics and the map if you do not have it yet.

pnpm dlx shadcn-svelte@latest add https://shadcn-svelte-map.vercel.app/r/region-analytics.json
npx shadcn-svelte@latest add https://shadcn-svelte-map.vercel.app/r/region-analytics.json
yarn dlx shadcn-svelte@latest add https://shadcn-svelte-map.vercel.app/r/region-analytics.json
bunx --bun shadcn-svelte@latest add https://shadcn-svelte-map.vercel.app/r/region-analytics.json

Code

<script lang="ts">
	import type { FeatureCollection, Polygon } from 'geojson';
	import TrendingDownIcon from '@lucide/svelte/icons/trending-down';
	import TrendingUpIcon from '@lucide/svelte/icons/trending-up';
	import { cn } from '$lib/utils.js';
	import { Button } from '$lib/components/ui/button/index.js';
	import { ButtonGroup } from '$lib/components/ui/button-group/index.js';
	import * as Card from '$lib/components/ui/card/index.js';
	import {
		Map,
		MapControlContainer,
		MapGeoJSON,
		MapZoomControl,
		type MapStyle
	} from '$lib/components/ui/map/index.js';
	import { METRICS, REGIONS, VIEWPORT, type MetricId, type Region } from './data.js';

	interface Props {
		/** Basemap. Defaults to OpenFreeMap. */
		mapStyle?: MapStyle;
		class?: string;
	}

	let { mapStyle, class: className }: Props = $props();

	/**
	 * Five shades of the theme's primary colour, light to dark. Each bucket is its own layer
	 * so the fill follows the theme; the swatch classes match the fill opacities.
	 */
	const BUCKETS = [
		{ id: 'lowest', opacity: 0.12, swatch: 'bg-primary/12' },
		{ id: 'low', opacity: 0.27, swatch: 'bg-primary/27' },
		{ id: 'middle', opacity: 0.42, swatch: 'bg-primary/42' },
		{ id: 'high', opacity: 0.57, swatch: 'bg-primary/57' },
		{ id: 'highest', opacity: 0.72, swatch: 'bg-primary/72' }
	] as const;
	const HOVER_LIFT = 0.15;
	const PERCENT = 100;

	let metricId = $state<MetricId>('revenue');
	let hoveredId = $state<string | null>(null);
	let selectedId = $state<string>('centre');

	const metric = $derived(METRICS.find((item) => item.id === metricId) ?? METRICS[0]);
	const values = $derived(REGIONS.map((region) => region.properties[metricId]));
	const low = $derived(Math.min(...values));
	const high = $derived(Math.max(...values));

	function bucketOf(value: number): number {
		if (high === low) return 0;
		const share = (value - low) / (high - low);
		return Math.min(BUCKETS.length - 1, Math.floor(share * BUCKETS.length));
	}

	const buckets: FeatureCollection<Polygon, Region>[] = $derived(
		BUCKETS.map((_, index) => ({
			type: 'FeatureCollection',
			features: REGIONS.filter((region) => bucketOf(region.properties[metricId]) === index)
		}))
	);

	const ranking: Region[] = $derived(
		REGIONS.map((region) => region.properties).sort((a, b) => b[metricId] - a[metricId])
	);

	const focusId = $derived(hoveredId ?? selectedId);
	// Null only when there are no regions at all; the card then says so.
	const focus: Region | null = $derived(
		ranking.find((region) => region.id === focusId) ?? ranking.at(0) ?? null
	);
	const total = $derived(values.reduce((sum, value) => sum + value, 0));
	const isAdditive = $derived(metricId !== 'growth');
	// With nothing to share out, every region holds 0% rather than NaN.
	const share = $derived(focus && total > 0 ? Math.round((focus[metricId] / total) * PERCENT) : 0);

	function regionId(feature: { properties: Record<string, unknown> } | null): string | null {
		return feature ? String(feature.properties.id) : null;
	}
</script>

<div class={cn('grid min-h-[560px] gap-4 p-4 lg:grid-cols-[minmax(0,1fr)_20rem]', className)}>
	<Map
		class="min-h-[360px] rounded-lg border"
		aria-label="Region map"
		{mapStyle}
		viewport={VIEWPORT}
	>
		{#each BUCKETS as bucket, index (bucket.id)}
			<MapGeoJSON
				id="region-{bucket.id}"
				data={buckets[index]}
				promoteId="id"
				fillOpacity={bucket.opacity}
				hoverFillOpacity={bucket.opacity + HOVER_LIFT}
				lineWidth={1}
				hoverLineWidth={2.5}
				onhover={(feature) => (hoveredId = regionId(feature))}
				onclick={(feature) => (selectedId = regionId(feature) ?? selectedId)}
			/>
		{/each}
		<MapControlContainer position="top-left">
			<ButtonGroup aria-label="Colour regions by">
				{#each METRICS as item (item.id)}
					<Button
						variant={metricId === item.id ? 'default' : 'outline'}
						size="sm"
						aria-pressed={metricId === item.id}
						onclick={() => (metricId = item.id)}
					>
						{item.label}
					</Button>
				{/each}
			</ButtonGroup>
		</MapControlContainer>
		<MapControlContainer position="top-right">
			<MapZoomControl />
		</MapControlContainer>
		<MapControlContainer position="bottom-left">
			<div
				class="flex items-center gap-2 rounded-md border bg-background/90 px-2 py-1 text-xs shadow-sm"
				aria-label="{metric.label} from {metric.format(low)} to {metric.format(high)}"
				role="img"
			>
				<span class="text-muted-foreground">{metric.format(low)}</span>
				<span class="flex">
					{#each BUCKETS as bucket (bucket.id)}
						<span class={['h-2.5 w-5', bucket.swatch]}></span>
					{/each}
				</span>
				<span class="text-muted-foreground">{metric.format(high)}</span>
			</div>
		</MapControlContainer>
	</Map>

	<Card.Root class="min-h-0 gap-4 overflow-y-auto">
		{#if focus}
			<Card.Header>
				<Card.Title data-testid="focus-name">{focus.name}</Card.Title>
				<Card.Description>
					{#if isAdditive}
						{share}% of all {metric.label.toLowerCase()}
					{:else}
						Change against last quarter
					{/if}
				</Card.Description>
			</Card.Header>
		{:else}
			<Card.Header>
				<Card.Title>No regions to show</Card.Title>
			</Card.Header>
		{/if}
		<Card.Content class="flex flex-col gap-4">
			{#if focus}
				<dl class="grid grid-cols-3 gap-2 text-sm">
					{#each METRICS as item (item.id)}
						<div class="rounded-md border p-2">
							<dt class="text-xs text-muted-foreground">{item.label}</dt>
							<dd class="font-semibold tabular-nums">{item.format(focus[item.id])}</dd>
						</div>
					{/each}
				</dl>
			{/if}
			<ol class="flex flex-col gap-1" aria-label="Regions by {metric.label.toLowerCase()}">
				{#each ranking as region, index (region.id)}
					<li>
						<button
							type="button"
							class={[
								'flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-accent',
								region.id === focus?.id && 'bg-accent'
							]}
							onclick={() => (selectedId = region.id)}
							data-testid="rank"
						>
							<span class="w-4 text-muted-foreground tabular-nums">{index + 1}</span>
							<span class="flex-1">{region.name}</span>
							{#if metricId === 'growth'}
								{#if region.growth < 0}
									<TrendingDownIcon class="size-3.5 text-destructive" />
								{:else}
									<TrendingUpIcon class="size-3.5 text-muted-foreground" />
								{/if}
							{/if}
							<span class="tabular-nums">{metric.format(region[metricId])}</span>
						</button>
					</li>
				{/each}
			</ol>
		</Card.Content>
	</Card.Root>
</div>
import type { Feature, Polygon } from 'geojson';
import { rectangleRing, type MapViewport } from '$lib/components/ui/map/index.js';

/** Sales territories laid over Madrid. */
export const VIEWPORT: MapViewport = {
	center: [-3.7038, 40.4168],
	zoom: 10,
	bearing: 0,
	pitch: 0
};

export type MetricId = 'revenue' | 'orders' | 'growth';

export interface Metric {
	id: MetricId;
	label: string;
	format: (value: number) => string;
}

const euros = new Intl.NumberFormat('en', {
	style: 'currency',
	currency: 'EUR',
	notation: 'compact'
});
const count = new Intl.NumberFormat('en');

export const METRICS: readonly Metric[] = [
	{ id: 'revenue', label: 'Revenue', format: (value) => euros.format(value) },
	{ id: 'orders', label: 'Orders', format: (value) => count.format(value) },
	{ id: 'growth', label: 'Growth', format: (value) => `${value > 0 ? '+' : ''}${value}%` }
];

export interface Region {
	id: string;
	name: string;
	revenue: number;
	orders: number;
	/** Change against last quarter, in percent. */
	growth: number;
}

const COLUMNS = 3;
const CELL = { lng: 0.11, lat: 0.085 };
/** North-west corner of the grid. */
const ORIGIN = { lng: -3.869, lat: 40.544 };

/** Territories row by row from the north-west. */
const FIGURES: Region[] = [
	{ id: 'north-west', name: 'North-west', revenue: 1_240_000, orders: 8_410, growth: 6 },
	{ id: 'north', name: 'North', revenue: 2_980_000, orders: 17_250, growth: 12 },
	{ id: 'north-east', name: 'North-east', revenue: 1_610_000, orders: 9_870, growth: -3 },
	{ id: 'west', name: 'West', revenue: 860_000, orders: 5_320, growth: 2 },
	{ id: 'centre', name: 'Centre', revenue: 4_720_000, orders: 26_900, growth: 18 },
	{ id: 'east', name: 'East', revenue: 2_140_000, orders: 12_480, growth: 9 },
	{ id: 'south-west', name: 'South-west', revenue: 540_000, orders: 3_610, growth: -8 },
	{ id: 'south', name: 'South', revenue: 1_330_000, orders: 8_020, growth: 4 },
	{ id: 'south-east', name: 'South-east', revenue: 980_000, orders: 6_150, growth: 15 }
];

export const REGIONS: Feature<Polygon, Region>[] = FIGURES.map((region, index) => {
	const west = ORIGIN.lng + (index % COLUMNS) * CELL.lng;
	const north = ORIGIN.lat - Math.floor(index / COLUMNS) * CELL.lat;
	return {
		type: 'Feature',
		properties: region,
		geometry: {
			type: 'Polygon',
			coordinates: [
				rectangleRing([
					[west, north - CELL.lat],
					[west + CELL.lng, north]
				])
			]
		}
	};
});

Handcrafted by Oggy. The source code is on GitHub.