feat(ui): rewrite Tabs onto wire classes with URL sync and roving focus

Tabs was the only component in the library styled with Tailwind utilities, so
it could not be themed like the rest and assumed Tailwind was present. It also
fired raw CustomEvents instead of declaring outputs, and set a roving tabindex
with no keydown handler at all -- which left every inactive tab unreachable by
Tab while the arrows did nothing.

It now uses wire-* classes and a local style block, declares change and select
outputs, and opts into the roving runtime.

mode=url mirrors the selection into a query parameter via pushState. Back and
forward are handled in the runtime, which activates the matching tab rather
than assigning to component state: a popstate listener writing state would be
writing after the client function returned, and that write is dropped. The
round trip is marked so the component does not push a second history entry for
a navigation that came from history.

Also anchors Nav submenus so the viewport clamp can pull them back on screen.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-07 17:18:00 +05:30
co-authored by Claude Opus 5
parent 124da548b8
commit b4d3cb3695
7 changed files with 520 additions and 54 deletions
+11
View File
@@ -0,0 +1,11 @@
{
"version": "0.0.1",
"configurations": [
{
"name": "component-showcase",
"runtimeExecutable": "bun",
"runtimeArgs": ["run", "--cwd", "examples/component-showcase", "dev"],
"port": 3112
}
]
}
@@ -253,6 +253,80 @@ const DATATABLE_ROWS =
'[{"id": 1, "name": "Northwind", "plan": "Scale", "owner": "A. Okafor", "seats": 6, "status": "Active", "statusHtml": "<span class=\\"showcase-pill showcase-pill--success\\">Active</span>"}, {"id": 2, "name": "Acme Industrial", "plan": "Team", "owner": "R. Silva", "seats": 13, "status": "Trial", "statusHtml": "<span class=\\"showcase-pill showcase-pill--info\\">Trial</span>"}, {"id": 3, "name": "Globex", "plan": "Enterprise", "owner": "M. Chen", "seats": 20, "status": "Past due", "statusHtml": "<span class=\\"showcase-pill showcase-pill--danger\\">Past due</span>"}, {"id": 4, "name": "Initech", "plan": "Starter", "owner": "J. Dubois", "seats": 27, "status": "Active", "statusHtml": "<span class=\\"showcase-pill showcase-pill--success\\">Active</span>"}, {"id": 5, "name": "Umbrella", "plan": "Scale", "owner": "P. Novak", "seats": 34, "status": "Trial", "statusHtml": "<span class=\\"showcase-pill showcase-pill--info\\">Trial</span>"}, {"id": 6, "name": "Stark Labs", "plan": "Team", "owner": "A. Okafor", "seats": 41, "status": "Past due", "statusHtml": "<span class=\\"showcase-pill showcase-pill--danger\\">Past due</span>"}, {"id": 7, "name": "Wayne Foods", "plan": "Enterprise", "owner": "R. Silva", "seats": 48, "status": "Active", "statusHtml": "<span class=\\"showcase-pill showcase-pill--success\\">Active</span>"}, {"id": 8, "name": "Soylent", "plan": "Starter", "owner": "M. Chen", "seats": 55, "status": "Trial", "statusHtml": "<span class=\\"showcase-pill showcase-pill--info\\">Trial</span>"}, {"id": 9, "name": "Hooli", "plan": "Scale", "owner": "J. Dubois", "seats": 62, "status": "Past due", "statusHtml": "<span class=\\"showcase-pill showcase-pill--danger\\">Past due</span>"}, {"id": 10, "name": "Vehement", "plan": "Team", "owner": "P. Novak", "seats": 69, "status": "Active", "statusHtml": "<span class=\\"showcase-pill showcase-pill--success\\">Active</span>"}, {"id": 11, "name": "Massive Dynamic", "plan": "Enterprise", "owner": "A. Okafor", "seats": 76, "status": "Trial", "statusHtml": "<span class=\\"showcase-pill showcase-pill--info\\">Trial</span>"}, {"id": 12, "name": "Cyberdyne", "plan": "Starter", "owner": "R. Silva", "seats": 83, "status": "Past due", "statusHtml": "<span class=\\"showcase-pill showcase-pill--danger\\">Past due</span>"}, {"id": 13, "name": "Tyrell", "plan": "Scale", "owner": "M. Chen", "seats": 90, "status": "Active", "statusHtml": "<span class=\\"showcase-pill showcase-pill--success\\">Active</span>"}, {"id": 14, "name": "Aperture", "plan": "Team", "owner": "J. Dubois", "seats": 97, "status": "Trial", "statusHtml": "<span class=\\"showcase-pill showcase-pill--info\\">Trial</span>"}, {"id": 15, "name": "Black Mesa", "plan": "Enterprise", "owner": "P. Novak", "seats": 104, "status": "Past due", "statusHtml": "<span class=\\"showcase-pill showcase-pill--danger\\">Past due</span>"}]';
export const componentProfiles = {
Tabs: {
demos: [
standard(
"Panels and arrow keys",
"Selecting a tab swaps the panel with a short transition. Arrow keys move between tabs, Home and End jump to the ends, and only the selected tab is in the tab order.",
{
items: [
{
label: "Overview",
value: "overview",
title: "Overview",
description: "What the product does and who it is for.",
},
{
label: "Pricing",
value: "pricing",
title: "Pricing",
description: "Plans, limits and what counts as a seat.",
badge: "New",
},
{
label: "Support",
value: "support",
title: "Support",
description: "Response times and escalation paths.",
},
],
active: "overview",
},
),
advanced(
"Mirrored into the URL",
"With mode=url the selection is written to a query parameter using pushState, so the panel swaps without a page load, the tab survives a reload, and the back button steps through the tabs you visited.",
{
items: [
{ label: "Account", value: "account", description: "Profile and credentials." },
{ label: "Billing", value: "billing", description: "Invoices and payment method." },
{ label: "Team", value: "team", description: "Members and their roles." },
],
active: "account",
mode: "url",
param: "tab",
},
),
standard(
"Vertical with icons",
"Vertical orientation switches the arrow keys to up and down, and collapses back to a scrollable strip on a phone.",
{
items: [
{
label: "General",
value: "general",
icon: "icon-[lucide--settings]",
description: "Everyday preferences.",
},
{
label: "Security",
value: "security",
icon: "icon-[lucide--shield]",
description: "Sessions and two-factor.",
},
{
label: "Advanced",
value: "advanced",
icon: "icon-[lucide--flask-conical]",
description: "Experimental toggles.",
},
],
active: "security",
orientation: "vertical",
},
),
],
},
Nav: {
demos: [
standard(
+41
View File
@@ -3198,6 +3198,46 @@ export const REACTIVE_RUNTIME = String.raw`
syncRovingGroups();
}
/*
* Back/forward support for tabs that mirror their selection into the URL.
*
* The runtime deliberately does not touch component state. A popstate
* listener that assigned to it would be writing after the client function
* returned, and that write is dropped. Instead it finds the tab matching the
* query parameter and activates it, so the component updates itself through
* its own handler.
*
* data-wrn-tabs-restoring marks the round trip, so the component knows not
* to push another history entry for a navigation that came from history.
*/
function syncTabsFromUrl() {
var groups = document.querySelectorAll("[data-wrn-tabs-param]");
for (var index = 0; index < groups.length; index += 1) {
var group = groups[index];
var param = group.getAttribute("data-wrn-tabs-param");
if (!param) continue;
var value = new URLSearchParams(window.location.search).get(param);
if (value === null) continue;
var tab = group.querySelector('[role="tab"][data-value="' + value + '"]');
if (!tab || !tab.click) continue;
if (tab.getAttribute("aria-selected") === "true") continue;
group.setAttribute("data-wrn-tabs-restoring", "true");
try {
tab.click();
} finally {
group.removeAttribute("data-wrn-tabs-restoring");
}
}
}
function setupTabUrlSync() {
if (window.__wrnexusTabUrlBound) return;
window.__wrnexusTabUrlBound = true;
window.addEventListener("popstate", syncTabsFromUrl);
// Once after hydration, so a shared link opens on the right tab.
window.setTimeout(syncTabsFromUrl, 0);
}
function hydrateScopes(root) {
var host = root || document;
@@ -5416,6 +5456,7 @@ export const REACTIVE_RUNTIME = String.raw`
setupAnchoredOverlays();
setupModalDialogs();
setupRovingFocus();
setupTabUrlSync();
window.__wrnexusRepositionAnchored = repositionAnchored;
window.__wrnexusHydrateScopes = hydrateScopes;
window.__wrnexusInvalidateClientModule = function (url) { clientModuleCache.delete(url); };
+34
View File
@@ -1052,3 +1052,37 @@ test("an empty or false roving attribute opts the group out entirely", () => {
a.dispatchEvent(keydown(win, "ArrowRight"));
expect(doc.activeElement!.id).toBe("a");
});
test("popstate activates the tab named by the query parameter without re-pushing", () => {
const win = mount(
`<section data-wrn-tabs-param="tab">
<div role="tablist">
<button role="tab" data-value="one" aria-selected="true" id="t1">One</button>
<button role="tab" data-value="two" aria-selected="false" id="t2">Two</button>
</div>
</section>`,
);
const doc = win.document;
let restoringAtClick: string | null = "not-clicked";
(doc.querySelector("#t2") as unknown as HTMLElement).addEventListener("click", () => {
restoringAtClick = doc
.querySelector("[data-wrn-tabs-param]")!
.getAttribute("data-wrn-tabs-restoring");
});
win.location.search = "?tab=two";
win.dispatchEvent(
new (win as unknown as { Event: new (t: string) => unknown }).Event(
"popstate",
) as unknown as Parameters<Window["dispatchEvent"]>[0],
);
// The runtime activates the matching tab and marks the round trip, so the
// component can tell a history navigation from a real click and skip
// pushing another entry.
expect(restoringAtClick).toBe("true");
// The marker is cleaned up once the activation is done.
expect(
doc.querySelector("[data-wrn-tabs-param]")!.getAttribute("data-wrn-tabs-restoring"),
).toBeNull();
});
+6 -1
View File
@@ -106,7 +106,11 @@ component Nav {
>&#8250;</span>
</a>
<ul class="wire-nav__submenu" data-show="childrenOf(item).length > 0">
<ul
class="wire-nav__submenu"
data-wrn-anchored="true"
data-show="childrenOf(item).length > 0"
>
{#each childrenOf(item) as child}
<li class="wire-nav__item" data-has-children='{childrenOf(child).length > 0}'>
<a
@@ -133,6 +137,7 @@ component Nav {
<ul
class="wire-nav__submenu wire-nav__submenu--level3"
data-wrn-anchored="true"
data-show="childrenOf(child).length > 0"
>
{#each childrenOf(child) as leaf}
+281 -53
View File
@@ -1,90 +1,318 @@
// Tabs -- a tablist over panels.
//
// <Tabs items='[{"label":"Overview","value":"overview"}]' active="overview" />
//
// With mode="url" the selection is mirrored into a query parameter using
// history.pushState, so the panel swaps without a page load and the back
// button works. The query parameter is used rather than the hash because it
// survives a reload and does not collide with in-page anchors or Scrollspy.
//
// NOTE: the style block uses /* */ comments only -- // is not a CSS comment
// and silently swallows the rule that follows it.
component Tabs {
outputs {
change(payload: { value: string; item: object; index: number })
select(payload: { value: string; item: object; index: number })
}
props {
size: string = "default"
color: string = "primary"
label: string = "Tabs"
size: string = "default"
items: unknown[] = []
active: string = ""
orientation: string = "horizontal"
mode: string = "client"
param: string = "tab"
label: string = "Tabs"
class: string = ""
}
state activeValue = active || (items[0] ? (items[0].value || items[0].id || "0") : "")
state activeValue = ""
functions {
shared function itemList() {
return Array.isArray(items) ? items : []
}
shared function valueOf(item, index) {
return String(item.value || item.id || index)
}
shared function currentValue() {
if (activeValue) {
return activeValue
}
if (active) {
return active
}
var list = itemList()
return list.length ? valueOf(list[0], 0) : ""
}
shared function isSelected(item, index) {
return valueOf(item, index) === currentValue()
}
shared function rovingAxis() {
return orientation === "vertical" ? "vertical" : "horizontal"
}
client function selectTab(item, index, sourceEvent) {
if (item.disabled) {
return
}
var value = valueOf(item, index)
activeValue = value
// A click that came from the back button must not push another entry.
var target = sourceEvent ? sourceEvent.currentTarget : null
var group = target && target.closest ? target.closest("[data-wrn-tabs-param]") : null
var restoring = group && group.getAttribute("data-wrn-tabs-restoring") === "true"
if (mode === "url" && !restoring && window.history && window.history.pushState) {
var url = new URL(window.location.href)
url.searchParams.set(param || "tab", value)
window.history.pushState({}, "", url.toString())
}
output.change({ value: value, item: item, index: index })
output.select({ value: value, item: item, index: index })
}
}
view {
<section
{...attrs}
data-ui-component="Tabs"
class='w-full {class}'
class:flex='orientation === "vertical"'
class:items-start='orientation === "vertical"'
class:gap-6='orientation === "vertical"'
class='wire-tabs {class}'
data-orientation='{orientation}'
data-color='{color}'
data-size='{size}'
data-mode='{mode}'
data-param='{param}'
data-wrn-tabs-param='{mode === "url" ? param : ""}'
>
<div
class="wire-tabs__list"
role="tablist"
aria-label='{label}'
aria-orientation='{orientation}'
class="flex min-w-0 gap-1 overflow-x-auto rounded-xl border border-[var(--wire-color-border)] bg-[var(--wire-color-surface-soft)] p-1"
class:flex-col='orientation === "vertical"'
class:w-56='orientation === "vertical"'
class:shrink-0='orientation === "vertical"'
data-wrn-roving='{rovingAxis()}'
>
{#each items as item, index}
{#each itemList() as item, index}
<button
type="button"
class="wire-tabs__tab"
role="tab"
id='tab-{item.value || item.id || index}'
aria-selected='{activeValue === (item.value || item.id || String(index))}'
aria-controls='panel-{item.value || item.id || index}'
tabindex='{activeValue === (item.value || item.id || String(index)) ? "0" : "-1"}'
disabled='{item.disabled || false}'
class="inline-flex min-w-max flex-1 items-center justify-center gap-2 rounded-lg px-4 py-2.5 text-sm font-semibold outline-none transition disabled:cursor-not-allowed disabled:opacity-50"
class:bg-[var(--wire-color-surface-raised)]='activeValue === (item.value || item.id || String(index))'
class:text-[var(--wire-color-primary)]='activeValue === (item.value || item.id || String(index))'
class:shadow-sm='activeValue === (item.value || item.id || String(index))'
class:text-[var(--wire-color-text-muted)]='activeValue !== (item.value || item.id || String(index))'
class:hover:text-[var(--wire-color-text)]='activeValue !== (item.value || item.id || String(index))'
class:justify-start='orientation === "vertical"'
class:px-3='size === "sm"'
class:py-2='size === "sm"'
class:px-5='size === "lg"'
class:py-3='size === "lg"'
@click='activeValue = item.value || item.id || String(index); event.currentTarget.dispatchEvent(new CustomEvent("change", { bubbles: true, detail: { item: item, index: index, value: activeValue } })); event.currentTarget.dispatchEvent(new CustomEvent("select", { bubbles: true, detail: { item: item, index: index, value: activeValue } }))'
data-value='{valueOf(item, index)}'
data-wrn-roving-item="true"
id='wire-tab-{valueOf(item, index)}'
aria-controls='wire-panel-{valueOf(item, index)}'
aria-selected='{isSelected(item, index) ? "true" : "false"}'
aria-disabled='{item.disabled ? "true" : "false"}'
@click='selectTab(item, index, event)'
>
{#if item.icon}
<span class='{item.icon + " size-4"}' aria-hidden="true"></span>
{/if}
<span>{item.label || item.title}</span>
{#if item.badge}
<span class="rounded-full bg-[var(--wire-color-primary-soft)] px-2 py-0.5 text-xs text-[var(--wire-color-primary)]">{item.badge}</span>
{/if}
<span class='wire-tabs__icon {item.icon}' data-show="item.icon" aria-hidden="true"></span>
<span class="wire-tabs__label">{item.label || item.title}</span>
<span class="wire-tabs__badge" data-show="item.badge">{item.badge}</span>
</button>
{/each}
</div>
<div class="min-w-0 flex-1 pt-4" class:pt-0='orientation === "vertical"'>
{#each items as item, index}
<div class="wire-tabs__panels">
{#each itemList() as item, index}
<div
class="wire-tabs__panel"
role="tabpanel"
id='panel-{item.value || item.id || index}'
aria-labelledby='tab-{item.value || item.id || index}'
id='wire-panel-{valueOf(item, index)}'
aria-labelledby='wire-tab-{valueOf(item, index)}'
tabindex="0"
data-show='activeValue === (item.value || item.id || String(index))'
class="rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-[var(--wire-color-focus)]"
data-show='isSelected(item, index)'
>
{#if item.title && item.title !== item.label}
<h3 class="text-lg font-bold text-[var(--wire-color-text)]">{item.title}</h3>
{/if}
{#if item.description}
<p class="mt-2 leading-7 text-[var(--wire-color-text-muted)]">{item.description}</p>
{/if}
{#if item.content}
<div class="mt-4 text-[var(--wire-color-text)]">{item.content}</div>
{/if}
<h3 class="wire-tabs__title" data-show="item.title && item.title !== item.label">
{item.title}
</h3>
<p class="wire-tabs__description" data-show="item.description">{item.description}</p>
<div class="wire-tabs__content" data-show="item.content">{item.content}</div>
<slot name="panel-{valueOf(item, index)}"></slot>
</div>
{/each}
<slot></slot>
<slot />
</div>
</section>
}
style {
.wire-tabs {
--tabs-accent: var(--wire-color-primary);
display: flex;
flex-direction: column;
gap: 1rem;
max-width: 100%;
}
.wire-tabs[data-color="secondary"] {
--tabs-accent: var(--wire-color-secondary);
}
.wire-tabs[data-color="success"] {
--tabs-accent: var(--wire-color-success);
}
.wire-tabs[data-color="danger"] {
--tabs-accent: var(--wire-color-danger);
}
.wire-tabs[data-color="info"] {
--tabs-accent: var(--wire-color-info);
}
.wire-tabs[data-size="sm"] {
font-size: 0.82rem;
}
.wire-tabs[data-size="lg"] {
font-size: 1rem;
}
.wire-tabs[data-orientation="vertical"] {
flex-direction: row;
align-items: flex-start;
}
.wire-tabs__list {
display: flex;
gap: 0.25rem;
min-width: 0;
padding: 0.25rem;
border: 1px solid var(--wire-color-border);
border-radius: var(--wire-radius-md);
background: var(--wire-color-surface-soft);
/* A long tablist scrolls rather than wrapping into an unusable stack. */
overflow-x: auto;
}
.wire-tabs[data-orientation="vertical"] .wire-tabs__list {
flex-direction: column;
flex: 0 0 auto;
width: 14rem;
overflow-x: visible;
}
.wire-tabs__tab {
appearance: none;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.4rem;
flex: 1 0 auto;
padding: 0.55rem 0.9rem;
border: 0;
border-radius: var(--wire-radius-sm);
background: transparent;
color: var(--wire-color-text-muted);
font: inherit;
font-size: 0.88rem;
font-weight: 600;
white-space: nowrap;
cursor: pointer;
transition:
background 160ms ease,
color 160ms ease;
}
.wire-tabs[data-orientation="vertical"] .wire-tabs__tab {
justify-content: flex-start;
}
.wire-tabs__tab:hover {
color: var(--wire-color-text);
}
.wire-tabs__tab:focus-visible {
outline: 2px solid var(--tabs-accent);
outline-offset: 2px;
}
.wire-tabs__tab[aria-selected="true"] {
background: var(--wire-color-surface);
color: var(--tabs-accent);
box-shadow: var(--wire-shadow-1);
}
.wire-tabs__tab[aria-disabled="true"] {
opacity: 0.5;
pointer-events: none;
}
.wire-tabs__badge {
padding: 0.05rem 0.4rem;
border-radius: 999px;
background: color-mix(in srgb, var(--tabs-accent) 16%, transparent);
color: var(--tabs-accent);
font-size: 0.72rem;
}
.wire-tabs__panels {
min-width: 0;
flex: 1 1 auto;
}
.wire-tabs__panel {
outline: none;
animation: wire-tabs-in 200ms ease both;
}
.wire-tabs__panel:focus-visible {
outline: 2px solid var(--tabs-accent);
outline-offset: 4px;
border-radius: var(--wire-radius-sm);
}
.wire-tabs__title {
margin: 0 0 0.35rem;
font-size: 1rem;
font-weight: 700;
}
.wire-tabs__description {
margin: 0;
color: var(--wire-color-text-muted);
line-height: 1.6;
}
.wire-tabs__content {
margin-top: 0.6rem;
}
@keyframes wire-tabs-in {
from {
opacity: 0;
transform: translateY(4px);
}
to {
opacity: 1;
transform: none;
}
}
/* Respect a reduced-motion preference: swap instantly instead. */
@media (prefers-reduced-motion: reduce) {
.wire-tabs__panel {
animation: none;
}
}
@media (max-width: 639px) {
.wire-tabs[data-orientation="vertical"] {
flex-direction: column;
}
.wire-tabs[data-orientation="vertical"] .wire-tabs__list {
width: 100%;
flex-direction: row;
overflow-x: auto;
}
}
}
}
+73
View File
@@ -2614,3 +2614,76 @@ test("nav renders its shell with no items and rejects a non-array", async () =>
"Expected an array prop",
);
});
test("nav submenus are anchored so the viewport clamp can pull them back", async () => {
const source = readFileSync(uiComponentPath("Nav"), "utf8");
const html = await renderComponent(source, {
items: [
{
label: "Products",
value: "products",
items: [{ label: "Overview", href: "/p", value: "p" }],
},
],
active: "p",
});
const dom = mountHtml(html);
// visibility:hidden keeps layout, so the clamp can place a submenu correctly
// before it is ever shown -- which is why CSS-driven hover still composes
// with the runtime clamp.
expect(dom.querySelectorAll(".wire-nav__submenu[data-wrn-anchored]").length).toBeGreaterThan(0);
});
test("tabs use wire classes and declare real outputs instead of raw events", async () => {
const source = readFileSync(uiComponentPath("Tabs"), "utf8");
// The whole point of the rewrite: themeable wire-* classes, not Tailwind.
expect(source).toContain("outputs {");
expect(source).toContain("output.change(");
expect(source).not.toContain("new CustomEvent(");
const html = await renderComponent(source, {
items: [
{ label: "Overview", value: "overview", content: "First panel" },
{ label: "Pricing", value: "pricing", content: "Second panel" },
],
active: "overview",
});
const dom = mountHtml(html);
const list = dom.querySelector('[role="tablist"]') as HTMLElement;
expect(list.getAttribute("data-wrn-roving")).toBe("horizontal");
const tabs = dom.querySelectorAll('[role="tab"]');
expect(tabs).toHaveLength(2);
expect(tabs[0]!.getAttribute("aria-selected")).toBe("true");
expect(tabs[1]!.getAttribute("aria-selected")).toBe("false");
expect(dom.querySelector(".wire-tabs")).not.toBeNull();
expect(dom.querySelectorAll('[role="tabpanel"]')).toHaveLength(2);
});
test("tabs in url mode declare the query parameter they sync to", async () => {
const source = readFileSync(uiComponentPath("Tabs"), "utf8");
const html = await renderComponent(source, {
items: [
{ label: "One", value: "one" },
{ label: "Two", value: "two" },
],
active: "one",
mode: "url",
param: "tab",
});
const dom = mountHtml(html);
const root = dom.querySelector(".wire-tabs") as HTMLElement;
expect(root.getAttribute("data-mode")).toBe("url");
expect(root.getAttribute("data-param")).toBe("tab");
});
test("tabs vertical orientation switches the roving axis", async () => {
const source = readFileSync(uiComponentPath("Tabs"), "utf8");
const html = await renderComponent(source, {
items: [{ label: "One", value: "one" }],
active: "one",
orientation: "vertical",
});
const dom = mountHtml(html);
expect(dom.querySelector('[role="tablist"]')!.getAttribute("data-wrn-roving")).toBe("vertical");
});