~james/core

core/web/src/lib/components/ui/ToggleFaces.svelte -rw-r--r-- 1.7 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
<script lang="ts">
	import type { Snippet } from "svelte";
	import { buttonIcon, type ButtonIconVariants } from "#lib/components/ui/Button.svelte";
	import { CROSSFADE_DURATION, CROSSFADE_EASING } from "#lib/motion/spring.ts";

	interface Props {
		on: boolean;
		failed?: boolean;
		size?: ButtonIconVariants["size"];
		offLabel: string;
		onLabel: string;
		labelClass?: string;
		off: Snippet<[string]>;
		onIcon: Snippet<[string]>;
		err: Snippet<[string]>;
	}

	let {
		on,
		failed = false,
		size = "small",
		offLabel,
		onLabel,
		labelClass,
		off,
		onIcon,
		err
	}: Props = $props();

	const icon = $derived(buttonIcon({ size }));
	const face = $derived(failed ? "err" : on ? "on" : "off");
	const layer = (key: typeof face) => `swap-layer ${icon}${key === face ? "" : " swap-icon-out"}`;

	let armed = $state(false);

	const armOnClick = (node: HTMLElement) => {
		const control = node.closest("button, a") ?? node;
		const arm = () => (armed = true);
		control.addEventListener("click", arm, { capture: true });
		return () => control.removeEventListener("click", arm, { capture: true });
	};
</script>

<span
	class="contents"
	{@attach armOnClick}
	style:--swap-duration={armed ? `${CROSSFADE_DURATION}ms` : "0ms"}
	style:--swap-easing={CROSSFADE_EASING}
>
	<span class={["grid", icon]} aria-hidden="true">
		{@render off(layer("off"))}
		{@render onIcon(layer("on"))}
		{@render err(layer("err"))}
	</span>
	<span class={["grid", labelClass]} aria-hidden="true">
		<span class={["whitespace-nowrap swap-layer", on && "swap-label-out"]}>{offLabel}</span>
		<span class={["whitespace-nowrap swap-layer", !on && "swap-label-out"]}>{onLabel}</span>
	</span>
	<span class="sr-only">{on ? onLabel : offLabel}</span>
</span>