Skip to content
← UI Library

Code example switcher

A tabbed code block with a sliding tab indicator, syntax colours, line numbers and one-click copy.

Svelte 5 · Version 1.0.0 · Zero extra packages

Connect MCP

Live preview

events.ts
import { Relay } from 'relay';const relay = new Relay(process.env.RELAY_API_KEY);// Fetch the 20 most recent eventsconst events = await relay.events.list({ limit: 20 });

Design decision

Resend’s audit shows how an actionable example can communicate the developer workflow. Keep examples short and equivalent so switching languages preserves context.

Resend audit ↗ · Site score 5

Source and integration

Pass an examples array with label, code and optional filename. Arrow keys move between tabs. Map --ui-bg, --ui-border, --ui-text, --ui-muted and --ui-accent to your tokens. Set --ui-code-max-height to limit the code height.

You may copy and adapt this original SaaSCrisp implementation in personal and commercial websites.

CodeSwitcher.svelte
<script module lang="ts">
	type Kind = 'com' | 'str' | 'num' | 'kw' | 'fn' | 'punc' | 'plain';
	export type Token = { kind: Kind; text: string };

	const pattern =
		/((?<![:\w])\/\/.*|(?<!\S)#.*)|("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)|\b(\d+(?:\.\d+)?)\b|\b(const|let|var|await|async|import|from|export|return|function|new|if|else|def|for|in|of|true|false|null|None|True|False|curl)\b|([A-Za-z_$][\w$]*)(?=\s*\()|([{}()[\].,;:=])/g;
	const kinds: Kind[] = ['com', 'str', 'num', 'kw', 'fn', 'punc'];

	/** Splits one line of code into coloured tokens without using HTML strings. */
	export function tokenize(line: string): Token[] {
		const tokens: Token[] = [];
		let last = 0;
		for (const match of line.matchAll(pattern)) {
			const at = match.index ?? 0;
			if (at > last) tokens.push({ kind: 'plain', text: line.slice(last, at) });
			const group = match.slice(1).findIndex((value) => value !== undefined);
			tokens.push({ kind: kinds[group] ?? 'plain', text: match[0] });
			last = at + match[0].length;
		}
		if (last < line.length) tokens.push({ kind: 'plain', text: line.slice(last) });
		return tokens;
	}
</script>

<script lang="ts">
	type Example = { label: string; code: string; filename?: string };
	let { examples, label = 'Code example' }: { examples: Example[]; label?: string } = $props();

	const id = $props.id();
	let selected = $state(0);
	let copied = $state(false);
	let status = $state('');
	let tabs: HTMLButtonElement[] = $state([]);
	let indicator = $state({ x: 0, width: 0, ready: false });
	let timer: ReturnType<typeof setTimeout> | undefined;

	const active = $derived(examples[selected] ?? examples[0]);
	const lines = $derived(active ? active.code.split('\n').map(tokenize) : []);

	$effect(() => {
		const tab = tabs[selected];
		if (tab) indicator = { x: tab.offsetLeft, width: tab.offsetWidth, ready: true };
	});
	$effect(() => () => clearTimeout(timer));

	function choose(index: number, focus = false) {
		selected = (index + examples.length) % examples.length;
		copied = false;
		status = '';
		if (focus) tabs[selected]?.focus();
	}

	function onkeydown(event: KeyboardEvent) {
		const target: Record<string, number> = {
			ArrowRight: selected + 1,
			ArrowLeft: selected - 1,
			Home: 0,
			End: examples.length - 1
		};
		if (event.key in target) {
			event.preventDefault();
			choose(target[event.key], true);
		}
	}

	async function copy() {
		if (!active) return;
		clearTimeout(timer);
		try {
			await navigator.clipboard.writeText(active.code);
			copied = true;
			status = 'Copied to clipboard';
		} catch {
			copied = false;
			status = 'Copy failed. Select the code to copy it.';
		}
		timer = setTimeout(() => {
			copied = false;
			status = '';
		}, 2000);
	}
</script>

{#if active}
	<div class="cs">
		<div class="cs-head">
			<div class="cs-tabs" role="tablist" aria-label={label}>
				<span
					class="cs-indicator"
					class:ready={indicator.ready}
					style:transform="translateX({indicator.x}px)"
					style:width="{indicator.width}px"
					aria-hidden="true"
				></span>
				{#each examples as example, index (example.label)}
					<button
						bind:this={tabs[index]}
						type="button"
						role="tab"
						id="{id}-tab-{index}"
						aria-selected={index === selected}
						aria-controls="{id}-panel"
						tabindex={index === selected ? 0 : -1}
						onclick={() => choose(index)}
						{onkeydown}>{example.label}</button
					>
				{/each}
			</div>
			<div class="cs-actions">
				{#if active.filename}<span class="cs-file">{active.filename}</span>{/if}
				<button class="cs-copy" class:copied type="button" onclick={copy} aria-label={copied ? 'Copied' : 'Copy code'}>
					<svg class="cs-icon-copy" viewBox="0 0 24 24" aria-hidden="true"
						><rect x="9" y="9" width="12" height="12" rx="2.5" /><path d="M5 15H4.5A1.5 1.5 0 0 1 3 13.5v-9A1.5 1.5 0 0 1 4.5 3h9A1.5 1.5 0 0 1 15 4.5V5" /></svg
					>
					<svg class="cs-icon-check" viewBox="0 0 24 24" aria-hidden="true"><path d="M5 12.5l4.5 4.5L19 7.5" /></svg>
				</button>
			</div>
		</div>
		<div class="cs-body" role="tabpanel" id="{id}-panel" aria-labelledby="{id}-tab-{selected}" tabindex="0">
			{#key selected}
				<pre class="cs-code"><code>{#each lines as line, number}<span class="cs-line"><span class="cs-ln" aria-hidden="true">{number + 1}</span><span>{#each line as token}<span class="t-{token.kind}">{token.text}</span>{/each}</span></span>{/each}</code></pre>
			{/key}
		</div>
		<span class="cs-sr" role="status">{status}</span>
	</div>
{/if}

<style>
	.cs {
		--_bg: var(--ui-bg, #0b0b0d);
		--_border: var(--ui-border, rgb(255 255 255 / 0.08));
		--_text: var(--ui-text, #ededf0);
		--_muted: var(--ui-muted, #8b8b94);
		--_accent: var(--ui-accent, #c8ff3c);
		position: relative;
		overflow: hidden;
		border: 1px solid var(--_border);
		border-radius: var(--ui-radius, 14px);
		background:
			radial-gradient(120% 80% at 0% 0%, rgb(255 255 255 / 0.035), transparent 50%),
			var(--_bg);
		color: var(--_text);
		font-family: var(--ui-font, ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif);
		box-shadow:
			inset 0 1px 0 rgb(255 255 255 / 0.04),
			0 1px 2px rgb(0 0 0 / 0.4),
			0 16px 40px -16px rgb(0 0 0 / 0.7);
		text-align: left;
	}
	.cs::before {
		content: '';
		position: absolute;
		inset: 0 10% auto;
		height: 1px;
		background: linear-gradient(90deg, transparent, rgb(255 255 255 / 0.2), transparent);
	}
	.cs-head {
		display: flex;
		align-items: center;
		justify-content: space-between;
		gap: 12px;
		padding: 6px 6px 6px 8px;
		border-bottom: 1px solid var(--_border);
		background: rgb(255 255 255 / 0.015);
	}
	.cs-tabs {
		position: relative;
		display: flex;
		gap: 2px;
		min-width: 0;
		overflow-x: auto;
		scrollbar-width: none;
	}
	.cs-indicator {
		position: absolute;
		inset: 0 auto 0 0;
		border-radius: 8px;
		background: rgb(255 255 255 / 0.07);
		box-shadow: inset 0 0 0 1px rgb(255 255 255 / 0.06);
	}
	.cs-indicator.ready {
		transition:
			transform 0.28s cubic-bezier(0.2, 0.8, 0.2, 1),
			width 0.28s cubic-bezier(0.2, 0.8, 0.2, 1);
	}
	.cs-tabs button {
		position: relative;
		border: 0;
		border-radius: 8px;
		padding: 6px 12px;
		background: none;
		color: var(--_muted);
		font-family: inherit;
		font-size: 13px;
		font-weight: 500;
		line-height: 1.3;
		white-space: nowrap;
		cursor: pointer;
		transition: color 0.15s;
	}
	.cs-tabs button:hover,
	.cs-tabs button[aria-selected='true'] {
		color: var(--_text);
	}
	.cs-actions {
		display: flex;
		flex-shrink: 0;
		align-items: center;
		gap: 10px;
	}
	.cs-file {
		color: var(--_muted);
		font: 12px/1 var(--ui-mono, ui-monospace, 'SF Mono', Menlo, monospace);
	}
	.cs-copy {
		position: relative;
		display: grid;
		place-items: center;
		width: 30px;
		height: 30px;
		border: 1px solid var(--_border);
		border-radius: 8px;
		background: rgb(255 255 255 / 0.02);
		color: var(--_muted);
		cursor: pointer;
		transition:
			color 0.15s,
			background-color 0.15s,
			border-color 0.15s;
	}
	.cs-copy:hover {
		background: rgb(255 255 255 / 0.06);
		color: var(--_text);
	}
	.cs-copy svg {
		grid-area: 1 / 1;
		width: 15px;
		height: 15px;
		fill: none;
		stroke: currentColor;
		stroke-width: 1.8;
		stroke-linecap: round;
		stroke-linejoin: round;
		transition:
			opacity 0.18s,
			transform 0.18s cubic-bezier(0.2, 0.8, 0.2, 1);
	}
	.cs-icon-check {
		opacity: 0;
		transform: scale(0.6);
		color: var(--_accent);
	}
	.copied .cs-icon-copy {
		opacity: 0;
		transform: scale(0.6);
	}
	.copied .cs-icon-check {
		opacity: 1;
		transform: none;
	}
	.cs-tabs button:focus-visible,
	.cs-copy:focus-visible,
	.cs-body:focus-visible {
		outline: 2px solid var(--_accent);
		outline-offset: -2px;
	}
	.cs-body {
		max-height: var(--ui-code-max-height, 22rem);
		overflow: auto;
	}
	.cs-code {
		min-width: max-content;
		margin: 0;
		padding: 14px 20px 14px 0;
		font: 13px/1.75 var(--ui-mono, ui-monospace, 'SF Mono', 'JetBrains Mono', Menlo, monospace);
		tab-size: 2;
		animation: cs-in 0.22s ease-out;
	}
	.cs-line {
		display: block;
	}
	.cs-ln {
		display: inline-block;
		width: 3rem;
		padding-right: 1.15rem;
		color: rgb(255 255 255 / 0.18);
		text-align: right;
		user-select: none;
	}
	.t-plain {
		color: var(--_text);
	}
	.t-kw {
		color: #c4b5fd;
	}
	.t-str {
		color: #d9f99d;
	}
	.t-num {
		color: #fdba74;
	}
	.t-fn {
		color: #93c5fd;
	}
	.t-punc {
		color: #8b8b94;
	}
	.t-com {
		color: #5b5b66;
		font-style: italic;
	}
	.cs-sr {
		position: absolute;
		width: 1px;
		height: 1px;
		overflow: hidden;
		clip-path: inset(50%);
		white-space: nowrap;
	}
	@keyframes cs-in {
		from {
			opacity: 0;
			transform: translateY(3px);
		}
	}
	@media (prefers-reduced-motion: reduce) {
		.cs-code {
			animation: none;
		}
		.cs-indicator.ready,
		.cs-copy svg {
			transition: none;
		}
	}
</style>
Agent prompt

Use the SaaSCrisp UI Library MCP at https://www.saascrisp.com/api/library/mcp. Retrieve code-switcher version 1.0.0 for svelte with get_ui_asset. Preview: https://www.saascrisp.com/library/code-switcher. Confirm the project's stack, reuse local primitives and map CSS variables to existing design tokens. Integrate the files and run the project's checks. Report changed files and additional dependencies.