# Tabs

> Tab list switching panels horizontally or vertically in pill or underline style, with sizing, badges, and in-page link fallback.

- Kind: ui · Category: Navigation · Interactivity: script
- Install: `npx shadcn@latest add @haze/tabs`
- File: `src/components/haze/ui/tabs.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/ui/tabs

## Use when
- Two to six views of the same object, such as overview, activity and settings
- Monthly and yearly variants of the same pricing content
- Vertical sub-navigation inside settings panes or documentation views

## Avoid when
- Moving between different routes without shared controls; use segmented-control or nav links
- Content people need to compare side by side
- More than about eight tabs, or labels that must all be visible at once; use orientation="vertical", select or an accordion (scrollable handles a few extra tabs on a narrow row)

## Alternatives
- [segmented-control](https://hazeui.com/ui/segmented-control.md)
- [accordion](https://hazeui.com/ui/accordion.md)
- [select](https://hazeui.com/ui/select.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| tabs | `{ id: string; label: string; badge?: string \| number; disabled?: boolean }[]` |  | yes | One entry per tab. id matches its slot panel element id. |
| label | `string` |  | yes | Accessible name for the tab list. |
| variant | `"pill" \| "line" \| "underline"` | "pill" | no | pill slides a raised key on a sunken track; line/underline slides an indicator bar along an edge rule. |
| size | `"sm" \| "md" \| "lg"` | "md" | no | Controls tab height and horizontal padding. |
| orientation | `"horizontal" \| "vertical"` | "horizontal" | no | Stacks tabs beside panels on wide screens with vertical arrow navigation. |
| scrollable | `boolean` | false | no | Horizontal only. Keeps one row and lets a long tab list scroll sideways, with edge fades on the cut-off sides and, with script, previous / next buttons shown only where more tabs are hidden. The selected tab is scrolled into view on load and on change. |
| scrollPreviousLabel | `string` | "Scroll tabs left" | no | Accessible name of the scroll-left button (scrollable only). |
| scrollNextLabel | `string` | "Scroll tabs right" | no | Accessible name of the scroll-right button (scrollable only). |
| class | `string` |  | no | Extra classes on the wrapper. |
| default slot | `slot` |  | yes | One direct child panel per tab in the same order, each carrying the matching id. |

## Accessibility
- The script adds tablist, tab, tabpanel roles, aria-orientation when vertical, aria-selected, aria-controls, and roving tabindex while skipping disabled tabs.
- Without scripts the tab list stays a navigation landmark of in-page links, and CSS reveals the matching :target panel.
- A link or the Back button that points at a panel or any element inside one selects that tab automatically.
- With scrollable, the list keeps its native scrollbar as the visible cue and adds edge fades; the optional scroll buttons are real, labelled buttons that appear only when tabs are cut off on that side. Arrow keys still select and reveal tabs, so the buttons are a pointer and touch aid.
- The indicator updates --tab-x, --tab-y, --tab-w, and --tab-h via ResizeObserver without gliding on initial load.
- Key Left / Right (or Up / Down when vertical): Select the previous or next enabled tab, wrapping at ends
- Key Home / End: Select the first or last enabled tab
- Key Space / Enter: Select the focused tab
- Key Tab: Move from the selected tab into its panel

## Agent prompts

### Install and use

Install the Haze UI component "Tabs" with `npx shadcn@latest add @haze/tabs`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import Tabs from "@/components/haze/ui/tabs.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/tabs.md

### Customize with real content

Adapt the Haze tabs ui for our product. Replace the demo values of these props with our real content: tabs, label, variant, size, orientation, scrollable, scrollPreviousLabel, scrollNextLabel, class, default slot. Keep the layout, the heading level rules and these accessibility details: The script adds tablist, tab, tabpanel roles, aria-orientation when vertical, aria-selected, aria-controls, and roving tabindex while skipping disabled tabs. Without scripts the tab list stays a navigation landmark of in-page links, and CSS reveals the matching :target panel. A link or the Back button that points at a panel or any element inside one selects that tab automatically. With scrollable, the list keeps its native scrollbar as the visible cue and adds edge fades; the optional scroll buttons are real, labelled buttons that appear only when tabs are cut off on that side. Arrow keys still select and reveal tabs, so the buttons are a pointer and touch aid. The indicator updates --tab-x, --tab-y, --tab-w, and --tab-h via ResizeObserver without gliding on initial load. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using tabs, check it fits: use it when two to six views of the same object, such as overview, activity and settings; monthly and yearly variants of the same pricing content; vertical sub-navigation inside settings panes or documentation views. Avoid it when moving between different routes without shared controls; use segmented-control or nav links; content people need to compare side by side; more than about eight tabs, or labels that must all be visible at once; use orientation="vertical", select or an accordion (scrollable handles a few extra tabs on a narrow row). Alternatives: @haze/segmented-control, @haze/accordion, @haze/select.

## Example requests that should lead here
- Split project settings into vertical underline Account, Security, and Members tabs
- Add pill tabs with count badges for Open and Archived items
- Use compact underline tabs for Monthly and Yearly billing

## Source

```astro
---
import { ChevronLeft, ChevronRight } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface Tab {
  /** The id of the matching panel element in the slot. Unique on the page. */
  id: string;
  label: string;
  /** Optional count or short status pill displayed beside the label. */
  badge?: string | number;
  disabled?: boolean;
}

interface Props {
  tabs: Tab[];
  /** Accessible name for the tab list, for example "Billing period". */
  label: string;
  /** pill: a raised key slides between tabs on a sunken track. line / underline: a bar slides along an edge rule. */
  variant?: "pill" | "line" | "underline";
  /** Tab item sizing aligned with Haze button heights. */
  size?: "sm" | "md" | "lg";
  /** Horizontal row (default) or vertical navigation stack beside panels. */
  orientation?: "horizontal" | "vertical";
  /** Horizontal only. Lets a long tab list scroll sideways with edge fades and, with script, previous / next buttons. */
  scrollable?: boolean;
  /** Accessible name of the scroll-left button. */
  scrollPreviousLabel?: string;
  /** Accessible name of the scroll-right button. */
  scrollNextLabel?: string;
  class?: string;
}

const {
  tabs,
  label,
  variant = "pill",
  size = "md",
  orientation = "horizontal",
  scrollable = false,
  scrollPreviousLabel = "Scroll tabs left",
  scrollNextLabel = "Scroll tabs right",
  class: className,
} = Astro.props;
const isPill = variant === "pill";
const isVertical = orientation === "vertical";
const isScrollable = scrollable && !isVertical;
// Only a scrollable list gets a wrapper (it anchors the scroll buttons); otherwise the markup is unchanged.
const Scroller = isScrollable ? "div" : Fragment;
const scrollerProps = isScrollable ? { class: "relative min-w-0 max-w-full", "data-tabs-scroller": "" } : {};

const pillSizes = {
  sm: "h-7 px-2 text-xs/4 gap-1 rounded-sm sm:gap-1.5 sm:px-2.5",
  md: "h-8 px-2 text-xs/5 gap-1 rounded-sm sm:px-3 sm:text-[0.8125rem]/5 sm:gap-2",
  lg: "h-9 px-2.5 text-sm/5 gap-1.5 rounded-sm sm:px-3.5 sm:gap-2",
};
const lineSizes = {
  sm: "h-8 px-2 text-xs/4 gap-1.5 rounded-md sm:px-2.5",
  md: "h-9 px-2.5 text-[0.8125rem]/5 gap-1.5 rounded-md sm:px-3 sm:gap-2",
  lg: "h-10 px-3 text-sm/5 gap-2 rounded-md sm:px-3.5",
};

// Without script the tabs are in-page links: the first panel shows until a link targets another one.
// The script upgrades this to the ARIA tabs pattern and marks the root with data-enhanced, which
// switches every rule below off. Tailwind only sees complete class names, so each one is written out.
const activeWhenTargeted = [
  "[[data-haze-tabs]:not([data-enhanced]):has([data-tabs-panels]>:nth-child(1):target)_&]:bg-card [[data-haze-tabs]:not([data-enhanced]):has([data-tabs-panels]>:nth-child(1):target)_&]:text-foreground",
  "[[data-haze-tabs]:not([data-enhanced]):has([data-tabs-panels]>:nth-child(2):target)_&]:bg-card [[data-haze-tabs]:not([data-enhanced]):has([data-tabs-panels]>:nth-child(2):target)_&]:text-foreground",
  "[[data-haze-tabs]:not([data-enhanced]):has([data-tabs-panels]>:nth-child(3):target)_&]:bg-card [[data-haze-tabs]:not([data-enhanced]):has([data-tabs-panels]>:nth-child(3):target)_&]:text-foreground",
  "[[data-haze-tabs]:not([data-enhanced]):has([data-tabs-panels]>:nth-child(4):target)_&]:bg-card [[data-haze-tabs]:not([data-enhanced]):has([data-tabs-panels]>:nth-child(4):target)_&]:text-foreground",
  "[[data-haze-tabs]:not([data-enhanced]):has([data-tabs-panels]>:nth-child(5):target)_&]:bg-card [[data-haze-tabs]:not([data-enhanced]):has([data-tabs-panels]>:nth-child(5):target)_&]:text-foreground",
  "[[data-haze-tabs]:not([data-enhanced]):has([data-tabs-panels]>:nth-child(6):target)_&]:bg-card [[data-haze-tabs]:not([data-enhanced]):has([data-tabs-panels]>:nth-child(6):target)_&]:text-foreground",
  "[[data-haze-tabs]:not([data-enhanced]):has([data-tabs-panels]>:nth-child(7):target)_&]:bg-card [[data-haze-tabs]:not([data-enhanced]):has([data-tabs-panels]>:nth-child(7):target)_&]:text-foreground",
  "[[data-haze-tabs]:not([data-enhanced]):has([data-tabs-panels]>:nth-child(8):target)_&]:bg-card [[data-haze-tabs]:not([data-enhanced]):has([data-tabs-panels]>:nth-child(8):target)_&]:text-foreground",
];
const firstStepsBack =
  "[[data-haze-tabs]:not([data-enhanced]):has([data-tabs-panels]>:not(:first-child):target,[data-tabs-panels]>:not(:first-child)_:target)_&]:bg-transparent [[data-haze-tabs]:not([data-enhanced]):has([data-tabs-panels]>:not(:first-child):target,[data-tabs-panels]>:not(:first-child)_:target)_&]:text-muted-foreground";
const panelRules =
  "[[data-haze-tabs]:not([data-enhanced])_&>*:not(:first-child):not(:target):not(:has(:target))]:hidden [[data-haze-tabs]:not([data-enhanced])_&:has(>:not(:first-child):target,>:not(:first-child)_:target)>*:first-child]:hidden";
// The incoming panel slides 8px in from the side it is on (set as data-dir by the script, only while a switch runs).
const panelSlide =
  "data-[dir]:[&>*]:transition-[opacity,translate] data-[dir]:[&>*]:duration-200 data-[dir]:[&>*]:ease-snappy data-[dir]:[&>*]:starting:opacity-0 data-[dir=next]:[&>*]:starting:translate-x-2 data-[dir=prev]:[&>*]:starting:-translate-x-2 motion-reduce:data-[dir]:[&>*]:transition-none";
const firstEnabled = tabs.findIndex((t) => !t.disabled);
---

<div
  data-haze-tabs
  data-orientation={orientation}
  data-scrollable={isScrollable ? "" : undefined}
  class={cn("@container min-w-0", className)}
>
  <div
    class={cn(
      "grid min-w-0 gap-4",
      isVertical && "@[420px]:grid-cols-[minmax(9.5rem,auto)_minmax(0,1fr)] @[420px]:items-start @[420px]:gap-5",
    )}
  >
    <Scroller {...scrollerProps}>
    <nav
      data-tabs-list
      aria-label={label}
      class={cn(
        "relative isolate flex max-w-full",
        isVertical ? "w-full flex-col @[420px]:w-44" : "w-fit items-center overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
        // Edge fade: the same mask technique as marquee, applied only on the sides that have more tabs.
        isScrollable &&
          "data-[fade=start]:[mask-image:linear-gradient(to_right,transparent,black_12%)] data-[fade=end]:[mask-image:linear-gradient(to_left,transparent,black_12%)] data-[fade=both]:[mask-image:linear-gradient(to_right,transparent,black_12%,black_88%,transparent)]",
        isPill
          ? "gap-0.5 sm:gap-1 rounded-lg border border-frame bg-muted p-1"
          : isVertical
            ? "gap-0.5 border-l border-border pl-1.5"
            : "w-full gap-1 border-b border-border pb-1",
      )}
    >
    <span
      data-tabs-indicator
      aria-hidden="true"
      class={cn(
        "pointer-events-none absolute hidden [[data-enhanced]_&]:block [[data-ready]_&]:transition-[translate,width,height] [[data-ready]_&]:duration-200 [[data-ready]_&]:ease-snappy motion-reduce:[[data-ready]_&]:transition-none",
        isPill
          ? "top-0 left-0 -z-10 h-(--tab-h) w-(--tab-w) translate-x-(--tab-x) translate-y-(--tab-y) rounded-sm border border-frame bg-background shadow-key"
          : isVertical
            ? "top-0 left-0 z-10 h-(--tab-h) w-0.5 translate-y-(--tab-y) rounded-full bg-foreground forced-colors:forced-color-adjust-none forced-colors:bg-[Highlight]"
            : "bottom-0 left-0 z-10 h-0.5 w-(--tab-w) translate-x-(--tab-x) rounded-full bg-foreground forced-colors:forced-color-adjust-none forced-colors:bg-[Highlight]",
      )}
    ></span>
    {
      tabs.map((tab, index) => (
        <a
          href={`#${tab.id}`}
          data-tab
          data-active={index === (firstEnabled >= 0 ? firstEnabled : 0) ? "" : undefined}
          data-disabled={tab.disabled ? "" : undefined}
          aria-disabled={tab.disabled ? "true" : undefined}
          tabindex={tab.disabled ? -1 : undefined}
          class={cn(
            "inline-flex shrink-0 items-center whitespace-nowrap font-medium text-muted-foreground transition-colors duration-150 ease-snappy hover:text-foreground focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring",
            isVertical ? "w-full justify-start" : "justify-center",
            !isPill && "hover:bg-accent",
            tab.disabled ? "pointer-events-none opacity-45" : "cursor-pointer",
            "data-[active]:bg-card data-[active]:text-foreground [[data-enhanced]_&]:data-[active]:bg-transparent",
            isPill ? pillSizes[size] : lineSizes[size],
            index === (firstEnabled >= 0 ? firstEnabled : 0) && firstStepsBack,
            activeWhenTargeted[index],
          )}
        >
          <span class="truncate">{tab.label}</span>
          {tab.badge !== undefined && (
            <span class={cn(
              "inline-flex h-4.5 min-w-4.5 items-center justify-center rounded-sm bg-foreground/8 px-1 font-mono text-[0.6875rem]/4 text-muted-foreground tabular-nums",
              isVertical && "ml-auto",
            )}>
              {tab.badge}
            </span>
          )}
        </a>
      ))
    }
  </nav>
    {
      isScrollable && (
        <>
          <button
            type="button"
            hidden
            data-tabs-scroll="prev"
            class="absolute top-1/2 left-1 z-20 inline-flex size-6 -translate-y-1/2 cursor-pointer items-center justify-center rounded-md border border-frame bg-background text-foreground transition-[background-color,scale] duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-90 active:duration-75"
          >
            <ChevronLeft class="size-4" aria-hidden="true" />
            <span class="sr-only">{scrollPreviousLabel}</span>
          </button>
          <button
            type="button"
            hidden
            data-tabs-scroll="next"
            class="absolute top-1/2 right-1 z-20 inline-flex size-6 -translate-y-1/2 cursor-pointer items-center justify-center rounded-md border border-frame bg-background text-foreground transition-[background-color,scale] duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-90 active:duration-75"
          >
            <ChevronRight class="size-4" aria-hidden="true" />
            <span class="sr-only">{scrollNextLabel}</span>
          </button>
        </>
      )
    }
    </Scroller>
    <div
      data-tabs-panels
      class={cn("min-w-0", panelRules, "[&>*]:focus-visible:outline-2 [&>*]:focus-visible:-outline-offset-2 [&>*]:focus-visible:outline-ring", panelSlide)}
    >
      <slot />
    </div>
  </div>
</div>

<script>
  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const list = root.querySelector<HTMLElement>("[data-tabs-list]");
    const tabs = Array.from(list?.querySelectorAll<HTMLAnchorElement>("[data-tab]") ?? []);
    const found = tabs.map((tab) => document.getElementById(decodeURIComponent(tab.hash.slice(1))));
    if (!list || tabs.length === 0 || found.some((panel) => !panel)) return;
    const panels = found as HTMLElement[];
    const indicator = root.querySelector<HTMLElement>("[data-tabs-indicator]");
    const panelBox = root.querySelector<HTMLElement>("[data-tabs-panels]");
    let dirTimer = 0;
    const isVertical = root.dataset.orientation === "vertical";

    // Scrollable lists: edge fades and prev / next buttons that exist only where tabs are cut off.
    const scrollable = root.hasAttribute("data-scrollable");
    const scrollButtons = Array.from(root.querySelectorAll<HTMLButtonElement>("[data-tabs-scroll]"));
    const reduced = () => matchMedia("(prefers-reduced-motion: reduce)").matches;
    const updateOverflow = () => {
      if (!scrollable) return;
      const start = list.scrollLeft > 1;
      const end = list.scrollLeft < list.scrollWidth - list.clientWidth - 1;
      if (start || end) list.dataset.fade = start && end ? "both" : start ? "start" : "end";
      else delete list.dataset.fade;
      const focused = scrollButtons.find((button) => button.contains(document.activeElement));
      scrollButtons.forEach((button) => {
        button.hidden = !(button.dataset.tabsScroll === "prev" ? start : end);
      });
      // A focused button that disappears hands focus to the opposite button if that one shows, else to the selected tab, so it never falls to the page.
      if (focused?.hidden) {
        const opposite = scrollButtons.find((button) => button !== focused && !button.hidden);
        (opposite ?? tabs.find((tab) => tab.tabIndex === 0) ?? tabs[0])?.focus({ preventScroll: true });
      }
    };
    // Scrolls the list only (scrollIntoView could also scroll the page) and keeps the tab clear of the fade.
    const reveal = (tab: HTMLElement, smooth: boolean) => {
      if (!scrollable) return;
      const margin = 32;
      const left = tab.offsetLeft - list.scrollLeft;
      const right = left + tab.offsetWidth;
      let target = list.scrollLeft;
      if (left < margin) target += left - margin;
      else if (right > list.clientWidth - margin) target += right - (list.clientWidth - margin);
      list.scrollTo({ left: Math.max(0, target), behavior: smooth && !reduced() ? "smooth" : "auto" });
    };
    if (scrollable) {
      list.addEventListener("scroll", updateOverflow, { passive: true });
      scrollButtons.forEach((button) => {
        button.addEventListener("click", () => {
          const step = Math.max(96, list.clientWidth * 0.6) * (button.dataset.tabsScroll === "prev" ? -1 : 1);
          list.scrollBy({ left: step, behavior: reduced() ? "auto" : "smooth" });
        });
      });
    }

    const place = (slide = false) => {
      const tab = tabs.find((item) => item.hasAttribute("data-active"));
      if (!indicator || !tab) return;
      root.toggleAttribute("data-ready", slide);
      indicator.style.setProperty("--tab-x", `${tab.offsetLeft}px`);
      indicator.style.setProperty("--tab-y", `${tab.offsetTop}px`);
      indicator.style.setProperty("--tab-w", `${tab.offsetWidth}px`);
      indicator.style.setProperty("--tab-h", `${tab.offsetHeight}px`);
    };

    const isEnabled = (i: number) => !tabs[i]?.hasAttribute("data-disabled");

    const select = (index: number, focus = false, slide = true) => {
      if (!isEnabled(index)) return;
      const before = tabs.findIndex((tab) => tab.hasAttribute("data-active"));
      const changed = before !== index;
      // Direction for the incoming panel's entrance (CSS reads data-dir while the switch runs).
      if (changed && slide && before >= 0 && panelBox && !reduced()) {
        clearTimeout(dirTimer);
        panelBox.dataset.dir = index > before ? "next" : "prev";
        dirTimer = window.setTimeout(() => delete panelBox.dataset.dir, 260);
      }
      tabs.forEach((tab, i) => {
        const on = i === index;
        tab.setAttribute("aria-selected", String(on));
        tab.tabIndex = on ? 0 : -1;
        tab.toggleAttribute("data-active", on);
        panels[i]!.hidden = !on;
      });
      place(slide);
      reveal(tabs[index]!, slide);
      if (focus) {
        if (scrollable) {
          // reveal() above already scrolls the list (with a margin clear of the fade); the browser's own focus scroll would fight it.
          tabs[index]!.focus({ preventScroll: true });
        } else {
          tabs[index]!.focus();
          tabs[index]!.scrollIntoView({ block: "nearest", inline: "nearest" });
        }
      }
    };

    const nextEnabled = (from: number, step: 1 | -1) => {
      for (let offset = 1; offset <= tabs.length; offset++) {
        const candidate = (from + step * offset + tabs.length) % tabs.length;
        if (isEnabled(candidate)) return candidate;
      }
      return -1;
    };

    const firstEnabled = () => tabs.findIndex((_, i) => isEnabled(i));
    const lastEnabled = () => {
      for (let i = tabs.length - 1; i >= 0; i--) if (isEnabled(i)) return i;
      return -1;
    };

    const fromHash = () => {
      let id = "";
      try {
        id = decodeURIComponent(location.hash.slice(1));
      } catch {
        id = "";
      }
      const target = id ? document.getElementById(id) : null;
      const index = target ? panels.findIndex((panel) => panel === target || panel.contains(target)) : -1;
      return index >= 0 && isEnabled(index) ? index : -1;
    };

    list.setAttribute("role", "tablist");
    if (isVertical) list.setAttribute("aria-orientation", "vertical");

    tabs.forEach((tab, i) => {
      const panel = panels[i]!;
      tab.setAttribute("role", "tab");
      if (!tab.id) tab.id = `${panel.id}-tab`;
      tab.setAttribute("aria-controls", panel.id);
      panel.setAttribute("role", "tabpanel");
      panel.setAttribute("aria-labelledby", tab.id);
      panel.tabIndex = 0;

      tab.addEventListener("click", (event) => {
        event.preventDefault();
        select(i);
      });
      tab.addEventListener("keydown", (event) => {
        const prevKey = isVertical ? "ArrowUp" : "ArrowLeft";
        const nextKey = isVertical ? "ArrowDown" : "ArrowRight";
        const next =
          event.key === nextKey ? nextEnabled(i, 1)
          : event.key === prevKey ? nextEnabled(i, -1)
          : event.key === "Home" ? firstEnabled()
          : event.key === "End" ? lastEnabled()
          : event.key === " " ? i
          : -1;
        if (next < 0) return;
        event.preventDefault();
        select(next, true);
      });
    });

    const initial = fromHash();
    const start = initial >= 0 ? initial : firstEnabled();
    if (start >= 0) select(start, false, false);
    root.setAttribute("data-enhanced", "");
    if ("ResizeObserver" in window) {
      const ro = new ResizeObserver(() => {
        place();
        updateOverflow();
      });
      ro.observe(list);
      tabs.forEach((tab) => ro.observe(tab));
    }
    updateOverflow();
    document.fonts?.ready.then(() => {
      place();
      const active = tabs.find((tab) => tab.hasAttribute("data-active"));
      if (active) reveal(active, false);
      updateOverflow();
    });

    root.addEventListener("haze:tabs-hash", () => {
      const index = fromHash();
      if (index >= 0) select(index);
    });
  }

  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-tabs]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-tabs-listener")) {
    document.documentElement.setAttribute("data-haze-tabs-listener", "");
    window.addEventListener("hashchange", () => document.querySelectorAll("[data-haze-tabs]").forEach((root) => root.dispatchEvent(new Event("haze:tabs-hash"))));
    document.addEventListener("astro:page-load", init);
  }
</script>
```
