~james/core

core/web/src/lib/components/ui/SegmentedControl.svelte -rw-r--r-- 4.4 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 15 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
<script module lang="ts">
	import { getContext, setContext } from "svelte";
	import { tv } from "tailwind-variants";
	import type { ResolvedPathname } from "$app/types";

	export const segmentedControl = tv({
		slots: {
			group: [
				"relative isolate inline-flex items-stretch rounded-md bg-background-inset p-0.5 ring ring-border-default/70 dark:bg-background-canvas",
				"[--btn-press:1] [--seg-inset:4px] *:[--btn-radius:calc(var(--radius-md)-2px)]",
				"[&>*:focus-visible]:-outline-offset-2"
			],
			thumb: [
				"pointer-events-none absolute top-0 left-0 rounded-(--btn-radius) bg-background-default edge-ring-inset",
				"transition-[translate,width,height]"
			]
		},
		variants: {
			ready: {
				true: { thumb: "opacity-100" },
				false: { thumb: "opacity-0" }
			}
		}
	});

	interface SegmentedControlContext {
		readonly value: string | undefined;
		readonly ready: boolean;
		href?: (value: string) => ResolvedPathname;
		select: (value: string) => void;
	}

	const SEGMENTED_CONTROL = Symbol("segmented-control");

	export const getSegmentedControl = () => getContext<SegmentedControlContext>(SEGMENTED_CONTROL);
</script>

<script lang="ts" generics="T extends string">
	import type { Snippet } from "svelte";
	import { afterNavigate, beforeNavigate } from "$app/navigation";
	import { prefersReducedMotion } from "svelte/motion";
	import { RAIL_DURATION, RAIL_EASING } from "#lib/motion/spring.ts";

	interface Props {
		value: T;
		href?: (value: T) => ResolvedPathname;
		label?: string;
		class?: string;
		children: Snippet;
	}

	let { value = $bindable(), href, label, class: className, children }: Props = $props();

	let pending = $state<T>();
	const current = $derived.by(() => {
		const settled = value;
		return pending ?? settled;
	});

	let latest: string | undefined;
	beforeNavigate(({ to }) => {
		latest = to?.url.href;
	});
	afterNavigate(({ to }) => {
		if (to?.url.href === latest) pending = undefined;
	});

	let group = $state<HTMLElement>();
	let box = $state<{ left: number; top: number; width: number; height: number }>();
	let animate = $state(false);

	let placed: string | undefined;

	const measure = (animated: boolean) => {
		const node = group?.querySelector<HTMLElement>(`[data-segment="${CSS.escape(current)}"]`);
		const next = node?.offsetParent
			? {
					left: node.offsetLeft,
					top: node.offsetTop,
					width: node.offsetWidth,
					height: node.offsetHeight
				}
			: undefined;
		animate = animated;
		box = next;
		return next !== undefined;
	};

	$effect(() => {
		placed = measure(placed !== undefined && placed !== current) ? current : undefined;
	});

	$effect(() => {
		if (!group) return;
		const observer = new ResizeObserver(() => measure(false));
		observer.observe(group);
		for (const node of group.querySelectorAll("[data-segment]")) observer.observe(node);
		return () => observer.disconnect();
	});

	setContext<SegmentedControlContext>(SEGMENTED_CONTROL, {
		get value() {
			return current;
		},
		get ready() {
			return box !== undefined;
		},
		get href() {
			return href as ((value: string) => ResolvedPathname) | undefined;
		},
		select: (next) => {
			if (href) {
				latest = undefined;
				pending = next as T;
			} else value = next as T;
		}
	});

	const onkeydown = (event: KeyboardEvent) => {
		if (!group) return;
		const radios = [
			...group.querySelectorAll<HTMLButtonElement>('[role="radio"]:not(:disabled)')
		];
		const index = radios.indexOf(event.target as HTMLButtonElement);
		if (index < 0) return;
		const target = {
			ArrowRight: index + 1,
			ArrowDown: index + 1,
			ArrowLeft: index - 1,
			ArrowUp: index - 1,
			Home: 0,
			End: radios.length - 1
		}[event.key];
		if (target === undefined) return;
		event.preventDefault();
		const radio = radios[(target + radios.length) % radios.length];
		radio.focus();
		radio.click();
	};

	const style = $derived(segmentedControl({ ready: box !== undefined }));
</script>

<div
	bind:this={group}
	role={href ? "group" : "radiogroup"}
	aria-label={label}
	class={style.group({ class: className })}
	onkeydown={href ? undefined : onkeydown}
>
	<span
		aria-hidden="true"
		class={style.thumb()}
		style:translate="{box?.left ?? 0}px {box?.top ?? 0}px"
		style:width="{box?.width ?? 0}px"
		style:height="{box?.height ?? 0}px"
		style:transition-duration="{animate && !prefersReducedMotion.current ? RAIL_DURATION : 0}ms"
		style:transition-timing-function={RAIL_EASING}
	></span>
	{@render children()}
</div>