1import { type JSX, onCleanup, onMount } from "solid-js";
2
3/**
4 * A `.segmented` group of `aria-pressed` buttons, or links marked `aria-current="page"`, whose highlight slides to
5 * the chosen one. A copy of the labels in the highlight's text color is clipped to the highlight as it moves, so
6 * each letter takes its color from whatever is under it at that moment.
7 */
8export function TabBar(props: { label: string; children: JSX.Element }) {
9 let root!: HTMLDivElement;
10 let pill!: HTMLSpanElement;
11 let ink!: HTMLDivElement;
12 let shown = false;
13 const place = () => {
14 ink.replaceChildren(...[...root.children].filter((el) => el !== pill && el !== ink).map((el) => el.cloneNode(true)));
15 const chosen = root.querySelector<HTMLElement>(':scope > :is([aria-pressed="true"], [aria-current="page"])');
16 pill.hidden = ink.hidden = !chosen;
17 if (!chosen) return;
18 // Back from display: none it jumps; a slide would start from stale geometry and can stall in a throttled tab.
19 const jump = !shown;
20 shown = pill.getClientRects().length > 0;
21 if (!shown) return;
22 if (jump) pill.style.transition = ink.style.transition = "none";
23 pill.style.left = `${chosen.offsetLeft}px`;
24 pill.style.width = `${chosen.offsetWidth}px`;
25 const right = root.clientWidth - chosen.offsetLeft - chosen.offsetWidth;
26 ink.style.clipPath = `inset(2px ${right}px 2px ${chosen.offsetLeft}px round 7px)`;
27 if (jump) {
28 pill.getBoundingClientRect();
29 pill.style.transition = ink.style.transition = "";
30 }
31 };
32 onMount(() => {
33 place();
34 const changes = new MutationObserver((records) => records.some((record) => !ink.contains(record.target)) && place());
35 changes.observe(root, { subtree: true, childList: true, characterData: true, attributeFilter: ["aria-pressed", "aria-current"] });
36 const resizes = new ResizeObserver(place);
37 resizes.observe(root);
38 onCleanup(() => {
39 changes.disconnect();
40 resizes.disconnect();
41 });
42 });
43 return (
44 <div ref={root} class="segmented" role="group" aria-label={props.label}>
45 <span ref={pill} class="pill" aria-hidden="true" />
46 {props.children}
47 <div ref={ink} class="ink" aria-hidden="true" inert />
48 </div>
49 );
50}