切换多个相关面板,同一时间只选中一个选项卡。

当多个视图共用同一块空间时,比如设置分区,或者预览和它的源码,就用 Tabs。每个选项卡打开与它 value 相同的面板。

<script lang="ts">
  import { Tabs, TabsList, TabsPanel, TabsTab } from "@ui-sdk/svelte/tabs"
</script>

<Tabs defaultValue="account">
  <TabsList aria-label="Settings">
    <TabsTab value="account">Account</TabsTab>
    <TabsTab value="password">Password</TabsTab>
  </TabsList>
  <TabsPanel value="account">
    Update your name, email address and profile photo. Your team sees changes
    right away.
  </TabsPanel>
  <TabsPanel value="password">
    Choose a new password for hollis@example.com. You stay signed in on this
    device.
  </TabsPanel>
</Tabs>
选择 Password 显示它的面板。用左右方向键在选项卡之间移动。

安装

npm install @ui-sdk/svelte @ui-sdk/core

组合

用下面的组合构建一个 Tabs:

Tabs
├── TabsList
│   ├── TabsTab
│   └── TabsTab
├── TabsPanel
└── TabsPanel

给每个选项卡和它的面板同一个唯一的 value。给列表一个无障碍名称。设置 defaultValue 选择初始选项卡;否则会选中第一个启用的选项卡。在服务器上,先于列表渲染的面板还不知道那个选项卡,所以面板排在列表前面的布局,比如底部选项卡栏,需要 defaultValue 或 bind:value,才能在水合前渲染出它的面板。

用法

导入各个部件并把它们组合起来:

<script lang="ts">
  import { Tabs, TabsList, TabsPanel, TabsTab } from "@ui-sdk/svelte/tabs"
</script>

<Tabs defaultValue="account">
  <TabsList aria-label="Settings">
    <TabsTab value="account">Account</TabsTab>
    <TabsTab value="password">Password</TabsTab>
  </TabsList>
  <TabsPanel value="account">Manage your profile.</TabsPanel>
  <TabsPanel value="password">Choose a new password.</TabsPanel>
</Tabs>

自己构建

@ui-sdk/svelte/tabs 自带现成的 Tabs。如果你想用自己的名字构建自己的版本,从 @ui-sdk/core 里的 tabs 原语(primitive)开始:

segments.ts
import { tabs } from "@ui-sdk/core/tabs"
import { createParts } from "@ui-sdk/svelte/primitive"

const {
  Root: Segments,
  List: SegmentList,
  Tab: Segment,
  Panel: SegmentPanel,
} = createParts(tabs, { root: "div", list: "div", tab: "button", panel: "div" })

export { Segment, SegmentList, SegmentPanel, Segments }
<Segments defaultValue="day">
  <SegmentList aria-label="Range">
    <Segment value="day">Day</Segment>
    <Segment value="week">Week</Segment>
  </SegmentList>
  <SegmentPanel value="day">128 visitors today.</SegmentPanel>
  <SegmentPanel value="week">1,024 visitors this week.</SegmentPanel>
</Segments>

把 "tab-icon": "span" 和 indicator: "span" 加到元素上,也能得到 TabIcon 和 Indicator 部件。每个部件都保留现成对应部件的行为、状态和数据属性。更多内容见渲染原语和自定义部件。

垂直

设置 orientation="vertical" 改用上、下方向键。把列表样式设成面板旁边的列,与之匹配。

<script lang="ts">
  import { Tabs, TabsList, TabsPanel, TabsTab } from "@ui-sdk/svelte/tabs"
</script>

<Tabs defaultValue="general" orientation="vertical">
  <TabsList aria-label="Preferences">
    <TabsTab value="general">General</TabsTab>
    <TabsTab value="security">Security</TabsTab>
    <TabsTab value="integrations">Integrations</TabsTab>
  </TabsList>
  <TabsPanel value="general"
    >Choose your language, time zone and the page you start on.</TabsPanel
  >
  <TabsPanel value="security"
    >Manage passkeys, signed-in sessions and recovery codes.</TabsPanel
  >
  <TabsPanel value="integrations"
    >Connect your calendar and chat apps to get reminders.</TabsPanel
  >
</Tabs>
聚焦 General,然后按向下方向键选择 Security。上方向键在垂直列表里往回移动。

要让方向随布局变化,比如宽屏时是面板旁边的列、手机上时是面板上方的行,就从媒体查询里设置 orientation。方向键会跟着它变。

<script lang="ts">
  import { MediaQuery } from "svelte/reactivity"
  import { Tabs } from "@ui-sdk/svelte/tabs"

  const isWide = new MediaQuery("min-width: 768px")
</script>

<Tabs
  defaultValue="account"
  orientation={isWide.current ? "vertical" : "horizontal"}
>
  <!-- List and panels. -->
</Tabs>

禁用

给选项卡加上 disabled 可以阻止选中。方向键仍然可以聚焦它,让人能发现它。

<script lang="ts">
  import { Tabs, TabsList, TabsPanel, TabsTab } from "@ui-sdk/svelte/tabs"
</script>

<Tabs defaultValue="overview">
  <TabsList aria-label="Dashboard">
    <TabsTab value="overview">Overview</TabsTab>
    <TabsTab value="analytics">Analytics</TabsTab>
    <TabsTab value="reports" disabled>Reports</TabsTab>
  </TabsList>
  <TabsPanel value="overview"
    >Revenue, visitors and sign-ups for the last 30 days.</TabsPanel
  >
  <TabsPanel value="analytics"
    >Where your visitors come from and the pages they read most.</TabsPanel
  >
  <TabsPanel value="reports"
    >Monthly reports are available on the Pro plan.</TabsPanel
  >
</Tabs>
用方向键到达 Reports。它可以接收焦点,但按压它不会改变当前选中的面板。

图标

把装饰性图标放进 TabsTabIcon,这样它们不会进入选项卡的无障碍名称。给有方向的图标,比如 Reply,加上 mirror,让它们在从右到左(RTL)的文本里翻转。只有图标的选项卡仍然需要 aria-label。

<script lang="ts">
  import { ArchiveIcon, MailIcon, ReplyIcon } from "@lucide/svelte"
  import {
    Tabs,
    TabsList,
    TabsPanel,
    TabsTab,
    TabsTabIcon,
  } from "@ui-sdk/svelte/tabs"
</script>

<Tabs defaultValue="inbox">
  <TabsList aria-label="Mail">
    <TabsTab value="inbox">
      <TabsTabIcon>
        <MailIcon />
      </TabsTabIcon>
      Inbox
    </TabsTab>
    <TabsTab value="replies">
      <TabsTabIcon mirror>
        <ReplyIcon />
      </TabsTabIcon>
      Replies
    </TabsTab>
    <TabsTab value="archive">
      <TabsTabIcon>
        <ArchiveIcon />
      </TabsTabIcon>
      Archive
    </TabsTab>
  </TabsList>
  <TabsPanel value="inbox"
    >3 new messages from Inès Moreau and Kofi Mensah.</TabsPanel
  >
  <TabsPanel value="replies"
    >Wren Takahashi replied to your message about the launch.</TabsPanel
  >
  <TabsPanel value="archive"
    >Messages you archived stay here and in search.</TabsPanel
  >
</Tabs>
选择 Replies。所在页面使用从右到左文本时,它的方向图标会镜像翻转。

手动激活

打开面板需要时间时,比如视图要获取数据,就设置 activation="manual"。方向键移动焦点;Enter 或 Space 选中获得焦点的选项卡。

<Tabs activation="manual" />

只有当面板里没有可聚焦内容时,面板才会成为 Tab 停靠点。面板里如果有输入框,Tab 会直接进入该输入框。

<script lang="ts">
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
  import { Input } from "@ui-sdk/svelte/input"
  import { Tabs, TabsList, TabsPanel, TabsTab } from "@ui-sdk/svelte/tabs"
</script>

<Tabs defaultValue="preview" activation="manual">
  <TabsList aria-label="Snippet">
    <TabsTab value="preview">Preview</TabsTab>
    <TabsTab value="code">Code</TabsTab>
  </TabsList>
  <TabsPanel value="preview"
    >Welcome back, Hollis. You have 3 unread messages.</TabsPanel
  >
  <TabsPanel value="code">
    <Field>
      <FieldLabel>Source</FieldLabel>
      <Input defaultValue={'<Welcome name="Hollis" unread={3} />'} />
    </Field>
  </TabsPanel>
</Tabs>
聚焦 Preview,然后按右方向键。Code 获得焦点;按 Enter 或 Space 显示它的面板。接下来 Tab 会进入 Source 输入框。

循环

方向键通常会在两端环绕。设置 loop={false} 改为停在端点上。

<script lang="ts">
  import { Tabs, TabsList, TabsPanel, TabsTab } from "@ui-sdk/svelte/tabs"

  const ranges = [
    {
      value: "day",
      label: "Day",
      content: "128 visitors today, up 12% from yesterday.",
    },
    {
      value: "week",
      label: "Week",
      content: "1,024 visitors this week, up 8% from last week.",
    },
    {
      value: "month",
      label: "Month",
      content: "4,210 visitors this month, down 3% from last month.",
    },
    {
      value: "year",
      label: "Year",
      content: "48,930 visitors this year, up 21% from last year.",
    },
  ]
</script>

<Tabs defaultValue="day" loop={false}>
  <TabsList aria-label="Range">
    {#each ranges as range (range.value)}
      <TabsTab value={range.value}>{range.label}</TabsTab>
    {/each}
  </TabsList>
  {#each ranges as range (range.value)}
    <TabsPanel value={range.value}>{range.content}</TabsPanel>
  {/each}
</Tabs>
聚焦 Year 并按右方向键。因为关闭了循环,焦点停在末尾。

指示器

TabsIndicator 测量选中的选项卡。把它放在相对定位的选项卡列表里,用它自己的 CSS 变量做一个跟随选择的标记。选项卡或列表尺寸变化时,它会重新测量。有了位置之后,它会得到 data-visible。在此之前,比如在服务器上渲染、脚本还没运行的页面里,它的变量尚未设置,所以要在它 :not([data-visible]) 时隐藏它。

[data-slot="tabs-list"] {
  position: relative;
}

[data-slot="tabs-indicator"] {
  position: absolute;
  top: var(--active-tab-top);
  left: var(--active-tab-left);
  width: var(--active-tab-width);
  height: var(--active-tab-height);
  transition-property: top, left, width, height;
  transition-duration: 200ms;

  &[data-activation-direction="none"] {
    transition: none;
  }
}

为你做动画的属性添加过渡。在 data-activation-direction="none" 时跳过过渡,避免第一次放置也播放动画。

<script lang="ts">
  import {
    Tabs,
    TabsIndicator,
    TabsList,
    TabsPanel,
    TabsTab,
  } from "@ui-sdk/svelte/tabs"

  const orientations = [
    { value: "horizontal", label: "Horizontal" },
    { value: "vertical", label: "Vertical" },
  ] as const

  let orientation = $state<"horizontal" | "vertical">("horizontal")
</script>

<div>
  <div data-slot="controls" role="group" aria-label="Orientation">
    {#each orientations as option (option.value)}
      <button
        type="button"
        data-size="sm"
        aria-pressed={orientation === option.value}
        onclick={() => (orientation = option.value)}
      >
        {option.label}
      </button>
    {/each}
  </div>
  <Tabs defaultValue="music" {orientation}>
    <TabsList aria-label="Library">
      <TabsTab value="music">Music</TabsTab>
      <TabsTab value="podcasts">Podcasts</TabsTab>
      <TabsTab value="audiobooks">Audiobooks</TabsTab>
      <TabsIndicator />
    </TabsList>
    <TabsPanel value="music"
      >312 songs in 24 albums, synced to this device.</TabsPanel
    >
    <TabsPanel value="podcasts"
      >8 shows you follow, with 3 new episodes.</TabsPanel
    >
    <TabsPanel value="audiobooks"
      >2 books in progress, 6 hours left in total.</TabsPanel
    >
  </Tabs>
</div>
选择 Podcasts,再选择 Vertical。同一个指示器在两种布局里都会测量并跟随选中的选项卡。

给它加上 followHover,它就会改为跟随指针下方的选项卡,指针离开列表后再回到选中的选项卡。同一个标记就成了悬停高亮。

保持挂载

选中另一个选项卡时,面板通常会卸载。给面板加上 keepMounted,就能让它的内容隐藏着留在页面里,保留草稿这样的本地状态。当智能体(Agent)选择另一个选项卡时,用户所在的面板也会保持挂载并隐藏,所以用户在那里输入的草稿不会丢失。等用户选中那个选项卡再离开之后,它才会卸载。

<script lang="ts">
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
  import { Textarea } from "@ui-sdk/svelte/textarea"
  import {
    Tabs,
    TabsIndicator,
    TabsList,
    TabsPanel,
    TabsTab,
  } from "@ui-sdk/svelte/tabs"
</script>

<Tabs defaultValue="reply">
  <TabsList aria-label="Comment">
    <TabsTab value="reply">Reply</TabsTab>
    <TabsTab value="formatting">Formatting</TabsTab>
    <TabsIndicator />
  </TabsList>
  <TabsPanel value="reply" keepMounted>
    <Field>
      <FieldLabel>Message</FieldLabel>
      <Textarea rows={3} placeholder="Write a reply…" />
    </Field>
  </TabsPanel>
  <TabsPanel value="formatting">
    <p>Use **bold**, _italics_ and `code` to format your reply.</p>
    <p>Paste a link on its own line to show a preview.</p>
  </TabsPanel>
</Tabs>
写一条消息,切换到 Formatting,再回到 Reply。你的草稿还在。

在页面中查找

给选项卡或面板加上 hiddenUntilFound,让关闭的内容仍能被浏览器的查找命令找到。匹配项会以 find-in-page 原因选中它所在的选项卡。这也会让面板保持挂载。

服务端渲染的面板会保留 hidden="until-found",所以它们的内容在水合之前就能被查找。

<script lang="ts">
  import { Tabs, TabsList, TabsPanel, TabsTab } from "@ui-sdk/svelte/tabs"

  const policies = [
    {
      value: "shipping",
      label: "Shipping",
      text: "Orders leave our warehouse within two working days. Express delivery arrives the next morning.",
    },
    {
      value: "returns",
      label: "Returns",
      text: "Send anything back within 30 days. Opened electronics carry a restocking fee of 10 percent.",
    },
    {
      value: "warranty",
      label: "Warranty",
      text: "Every product has a two-year warranty. Batteries are covered for one year from delivery.",
    },
  ]
</script>

<Tabs defaultValue="shipping" hiddenUntilFound>
  <TabsList aria-label="Policies">
    {#each policies as policy (policy.value)}
      <TabsTab value={policy.value}>{policy.label}</TabsTab>
    {/each}
  </TabsList>
  {#each policies as policy (policy.value)}
    <TabsPanel value={policy.value}>{policy.text}</TabsPanel>
  {/each}
</Tabs>
用浏览器的查找命令搜索“restocking fee”。Returns 会打开以显示匹配项。

动画

面板进场时暴露 data-starting-style,离场时暴露 data-ending-style。上一个面板会在退场动画期间保持挂载,之后卸载;如果它被保持挂载,则改为隐藏。

用 data-activation-direction 选择滑动方向。把面板放进同一个网格单元,让它们在过渡期间重叠,就像这个示例一样。

<script lang="ts">
  import {
    Tabs,
    TabsIndicator,
    TabsList,
    TabsPanel,
    TabsTab,
  } from "@ui-sdk/svelte/tabs"
</script>

<Tabs defaultValue="overview">
  <TabsList aria-label="Project">
    <TabsTab value="overview">Overview</TabsTab>
    <TabsTab value="activity">Activity</TabsTab>
    <TabsTab value="settings">Settings</TabsTab>
    <TabsIndicator />
  </TabsList>
  <div data-slot="stack">
    <TabsPanel value="overview"
      >The launch is on track for Friday, with 4 of 6 tasks done.</TabsPanel
    >
    <TabsPanel value="activity">
      Inès Moreau deployed to production and Kofi Mensah left a review.
    </TabsPanel>
    <TabsPanel value="settings"
      >Rename the project, transfer it to another team or archive it.</TabsPanel
    >
  </div>
</Tabs>
在 Overview、Activity 和 Settings 之间移动。面板会朝你移动的方向滑入。

受控

用 bind:value 自己掌控选中的选项卡。状态与事件介绍了这个通用模式。在变更回调里调用 details.cancel() 可以拒绝一次变更。

onValueChange 接收新的值和原因,比如 item-press、list-navigation 或 imperative。初始选择不会触发它。控制器还能让另一个控件选择选项卡。

控制台
<script lang="ts">
  import {
    Tabs,
    TabsIndicator,
    TabsList,
    TabsPanel,
    TabsTab,
    createTabsController,
  } from "@ui-sdk/svelte/tabs"
  import { useLog } from "./log"

  const log = useLog()
  const tabs = createTabsController()
  let value = $state<string | null>("inbox")
</script>

<div>
  <div data-slot="controls">
    <button type="button" onclick={() => tabs.select("sent")}
      >Show Sent Mail</button
    >
  </div>
  <Tabs
    bind:value
    onValueChange={(next, details) => log(`value: ${next} (${details.reason})`)}
    controller={tabs}
  >
    <TabsList aria-label="Mail">
      <TabsTab value="inbox">Inbox</TabsTab>
      <TabsTab value="drafts">Drafts</TabsTab>
      <TabsTab value="sent">Sent</TabsTab>
      <TabsIndicator />
    </TabsList>
    <TabsPanel value="inbox"
      >3 unread messages from Hollis Grant and Inès Moreau.</TabsPanel
    >
    <TabsPanel value="drafts"
      >2 drafts, the last one edited yesterday at 4:12 PM.</TabsPanel
    >
    <TabsPanel value="sent"
      >12 messages sent this week, all delivered.</TabsPanel
    >
  </Tabs>
</div>
选择 Drafts,然后按 Show Sent Mail。控制台会记录每个新值及其原因。

选中就意味着导航时,把选项卡渲染成链接。它仍然保持 tab role;方向键选中它时会跟随链接。带修饰键的点击,比如 Cmd 点击,保留浏览器原本的行为,不会选中选项卡。

<TabsTab value="activity">
  {#snippet render({ props, state, children })}
    <a {...props} href="#activity">{@render children?.(state)}</a>
  {/snippet}
  Activity
</TabsTab>
<script lang="ts">
  import {
    Tabs,
    TabsIndicator,
    TabsList,
    TabsPanel,
    TabsTab,
  } from "@ui-sdk/svelte/tabs"

  const pages = [
    {
      value: "overview",
      href: "#project-overview",
      label: "Overview",
      content:
        "Hollis Grant started this project in March. It has 14 open issues.",
    },
    {
      value: "activity",
      href: "#project-activity",
      label: "Activity",
      content:
        "Wren Takahashi merged 3 pull requests and closed 5 issues this week.",
    },
    {
      value: "members",
      href: "#project-members",
      label: "Members",
      content:
        "Hollis Grant owns the project. Wren Takahashi and 3 others can edit it.",
    },
  ]
</script>

<Tabs defaultValue="overview">
  <TabsList aria-label="Project">
    {#each pages as page (page.value)}
      <TabsTab value={page.value}>
        {#snippet render({ props, state, children })}
          <a {...props} href={page.href}>{@render children?.(state)}</a>
        {/snippet}
        {page.label}
      </TabsTab>
    {/each}
    <TabsIndicator />
  </TabsList>
  {#each pages as page (page.value)}
    <TabsPanel value={page.value}>{page.content}</TabsPanel>
  {/each}
</Tabs>
选择 Activity。它的面板打开,URL 哈希随之改变。带修饰键的点击保留链接通常的浏览器行为。

查询字符串

用 URL 作为选中值的来源,并对照你的选项卡值校验它。尽可能在服务器上读取参数,再把它作为受控值传进来。通过你的路由器写入变更,让浏览器导航和渲染的页面保持同步。对于纯客户端页面,更新 URL 时保留其余部分:

function saveSelectedTab(value: string | null) {
  const url = new URL(location.href)
  if (value === null) {
    url.searchParams.delete("tab")
  } else {
    url.searchParams.set("tab", value)
  }
  history.replaceState(null, "", url)
}

在接受值之后从 onValueChange 调用它。如果你的页面直接使用浏览器历史,还要在 popstate 时再读一次;视图卸载时移除这个监听器。

URL 哈希

像 #activity 这样的哈希在客户端渲染的页面上有效。在挂载后以及 hashchange 时读取它,然后选中匹配的选项卡。设置 location.hash 会增加一条历史记录。服务器读不到哈希,所以页面加载时要给它一个初始选项卡。

路由选项卡

当每个选项卡都是一个路由时,渲染链接,并从当前路径推导受控值。让导航来更新值。你不需要再写一个导航到同一路由的变更处理函数。

滚动到可见区域

如果列表可以滚动,选中选项卡时会在该列表内把它滚动到可见区域,无论是点击它、用方向键到达它,还是通过控制器或 URL 选中它。

自定义渲染

用 render snippet 改变部件的元素或往它的内容里添加内容,就像链接示例那样。部件与组合介绍了共用的渲染 API。每个部件的状态列在状态下。

<script lang="ts">
  import { Tabs, TabsList, TabsPanel, TabsTab } from "@ui-sdk/svelte/tabs"

  const folders = [
    {
      value: "inbox",
      label: "Inbox",
      count: 12,
      content: "12 conversations, 3 of them unread.",
    },
    {
      value: "unread",
      label: "Unread",
      count: 3,
      content: "Hollis Grant, Inès Moreau and Kofi Mensah wrote to you.",
    },
    {
      value: "archived",
      label: "Archived",
      count: 0,
      content: "Nothing archived yet. Archived mail stays searchable.",
    },
  ]
</script>

<Tabs defaultValue="inbox">
  <TabsList aria-label="Mail">
    {#each folders as folder (folder.value)}
      <TabsTab value={folder.value}>
        {#snippet render({ props, state, children })}
          <button {...props}>
            {@render children?.(state)}
            {#if folder.count > 0}
              <span data-slot="badge">{folder.count}</span>
            {/if}
          </button>
        {/snippet}
        {folder.label}
      </TabsTab>
    {/each}
  </TabsList>
  {#each folders as folder (folder.value)}
    <TabsPanel value={folder.value}>{folder.content}</TabsPanel>
  {/each}
</Tabs>
每个选项卡自己渲染按钮,并在标签后带一个未读数。选择 Unread 看看谁给你写了信。

样式

部件没有样式。用 data-selected 和 data-disabled 为选项卡设置样式,对正在显示的面板则用 data-selected。每个部件上的 data-orientation 让同一份样式表能布局水平与垂直选项卡。图标部件还会在选项卡上设置 data-has-icon、在列表上设置 data-has-icons,这有助于对齐混合了文字和图标的选项卡。

指示器的位置和尺寸会从选项卡列表测量到下面的变量里。用它们来做下划线、背景,或者垂直列表旁边的标记。

每个部件都有一个 data-slot,比如 tabs-tab,它的状态属性列在数据属性下。

TabsIndicator

变量内容
--active-tab-leftDistance from the tab list's left edge to the selected tab.
--active-tab-rightDistance from the tab list's right edge to the selected tab.
--active-tab-topDistance from the tab list's top edge to the selected tab.
--active-tab-bottomDistance from the tab list's bottom edge to the selected tab.
--active-tab-widthWidth of the selected tab.
--active-tab-heightHeight of the selected tab.

数据属性

Tabs

[data-slot="tabs"]

属性含义
data-orientationhorizontalverticalWhich arrow keys move between tabs.
data-activation-directionnoneleftrightupdownWhich way the last selection moved on screen. Use it to slide panels in from the right side.

TabsList

[data-slot="tabs-list"]

属性含义
data-orientationhorizontalverticalWhich arrow keys move between tabs.
data-activation-directionnoneleftrightupdownWhich way the last selection moved on screen. Use it to slide panels in from the right side.
data-has-iconsPresent while any tab inside holds an icon part, so items without one can line up.

TabsTab

[data-slot="tabs-tab"]

属性含义
data-selectedPresent on the selected tab and its panel.
data-orientationhorizontalverticalWhich arrow keys move between tabs.
data-activation-directionnoneleftrightupdownWhich way the last selection moved on screen. Use it to slide panels in from the right side.
data-disabledPresent when the tab can't be selected.
data-has-iconPresent on a tab while it holds an icon part.

TabsTabIcon

[data-slot="tabs-tab-icon"]

属性含义
data-mirrorPresent on an icon that flips in right-to-left text, with mirror.

TabsIndicator

[data-slot="tabs-indicator"]

属性含义
data-orientationhorizontalverticalWhich arrow keys move between tabs.
data-activation-directionnoneleftrightupdownWhich way the last selection moved on screen. Use it to slide panels in from the right side.
data-visiblePresent once the indicator has a position. Its variables are unset until then.

TabsPanel

[data-slot="tabs-panel"]

属性含义
data-selectedPresent on the selected tab and its panel.
data-orientationhorizontalverticalWhich arrow keys move between tabs.
data-activation-directionnoneleftrightupdownWhich way the last selection moved on screen. Use it to slide panels in from the right side.
data-starting-stylePresent for a panel's first frame. Style the state you animate from.
data-ending-stylePresent while the previous panel animates out. Style the state you animate to.

API 参考

属性(props)和回调与下面相同,以 Svelte props 的形式提供。value 可以用 bind:value 绑定。

Tabs

value?T | null
The selected tab's value. Pass it to control the tabs. null selects nothing.
defaultValue?T | null
The tab selected at first, when uncontrolled. Defaults to the first enabled tab, which never calls onValueChange.
onValueChange?((value: T | null, details: ChangeDetails<TabsValueChangeReason>) => void)
Runs when the selection wants to change. details.reason says why, and details.cancel() stops it.
orientation?TabsOrientation
Which arrow keys move between tabs: left and right, or up and down.
activation?"automatic" | "manual"
"automatic" selects a tab as soon as arrow keys focus it. "manual" waits for Enter or Space.
loop?boolean
Whether arrow keys wrap from the last tab to the first.
hiddenUntilFound?boolean
Keeps hidden panels in the page as hidden="until-found", so the browser's find in page can match their text and select their tab. Implies keepMounted.
controller?{ getValue: () => T | null; setValue: (value: T | null, options?: TabsChangeOptions) => boolean; select: (value: T, options?: TabsChangeOptions) => boolean; focus: () => void; }
Selects tabs from anywhere. Create one with createTabsController().
debug?boolean
Logs every state change with its reason to the console, in development builds.

TabsList

列表本身不接受任何选项,只有它渲染出来的元素的 props。

TabsTab

valuestring
Identifies the tab and pairs it with the panel of the same value.
disabled?boolean
Keeps the tab focusable but stops it from being selected, as the tabs pattern asks.

TabsTabIcon

mirror?boolean
Flips the icon horizontally in right-to-left text, for icons that point a way, like arrows and chevrons. Icons that picture a thing, like a clock or a check, stay as they are.

TabsIndicator

followHover?boolean
Whether it follows the tab under the pointer, and goes back to the selected one when the pointer leaves the list.

它的 CSS 变量保存选中选项卡的盒子。

TabsPanel

valuestring
The value of the tab this panel belongs to.
keepMounted?boolean
Whether the panel stays in the page, hidden, while its tab isn't selected.
hiddenUntilFound?boolean
Whether the panel stays findable with hidden="until-found" while its tab isn't selected. Overrides the tabs'.

状态

每个部件的渲染函数、基于状态的类名和槽位分别收到什么。

Tabs:

valueT | null
The selected tab's value.
orientationTabsOrientation
The tabs' orientation option, or "horizontal" when it's unset or invalid.
directionDirection
Which way the last selection moved.

TabsList:

orientationTabsOrientation
The tabs' orientation option, or "horizontal" when it's unset or invalid.

TabsTab:

selectedboolean
Whether this tab's value is the tabs' value.
disabledboolean
Whether this tab can't be selected.

TabsTabIcon:

mirrorboolean
Whether it flips in right-to-left text.

TabsPanel:

selectedboolean
Whether this panel's tab is selected. False while it animates out.

TabsIndicator:

orientationTabsOrientation
The tabs' orientation option, or "horizontal" when it's unset or invalid.
directionDirection
Which way the last selection moved.

原因

details.reason 说明选择为什么变化。

item-pressMouseEvent | KeyboardEvent
A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
list-navigationKeyboardEvent
Arrow, Home or End keys moved the selection, typing picked an item, or Ctrl or ⌘ with A selected every item of a listbox.
find-in-pageEvent
The browser's find in page matched hidden content.
item-removednone
The selected item left the page, and another was picked.
imperativenone
A controller or api call.

控制器

用 createTabsController() 创建一个控制器,并作为 controller 传入。

每个写入方法都接受可选的 { reason, event },像一次按压那样运行 onValueChange,并在变更被取消时返回 false。

getValue()() => T | null
The selected tab's value, or null when nothing is selected.
setValue(value, options?)(value: T | null, options?: TabsChangeOptions | undefined) => boolean
Selects a tab, or nothing with null. Disabled tabs never select. Returns false when canceled.
select(value, options?)(value: T, options?: TabsChangeOptions | undefined) => boolean
Selects a tab, the same as setValue.
focus()() => void
Moves focus to the selected tab, or the tab that holds the tab stop.

事件

回调先收到新值,再收到变更详情。绑定的 value 只在 onValueChange 未被取消时更新。onValueChange 在挂载时从不运行。

属性所在组件接收
bind:valueTabs选中的选项卡的值
onValueChangeTabs(value, details):新值,以及原因

无障碍

Tabs 遵循 WAI-ARIA tabs 模式。列表是 tablist,每个选项卡控制它的面板,每个面板的名称来自它的选项卡。

键盘

Tab 从选中的选项卡进入列表,再按一次 Tab 离开。左、右方向键在选项卡之间移动并选中它们;使用 activation="manual" 时只移动焦点,由 Enter 或 Space 选中。在垂直列表里,上、下方向键做同样的事。Home 和 End 移动到第一个和最后一个选项卡。列表从页面或任意祖先元素读取 dir="rtl",左、右方向键跟随阅读方向,不需要 provider。

经过测试的行为

下面每一行都是一条自动化测试。

Selection
  • The default tab is selected and shows its panel.
  • Clicking a tab selects it and shows its panel.
  • Clicking a disabled tab does nothing.
  • Clicking the selected tab keeps it selected.
  • A change can be cancelled.
  • Without a default value, the first enabled tab is selected.
  • Without a default value, the first render already selects the first enabled tab.
Keyboard navigation
  • Tab moves focus to the selected tab.
  • ArrowRight and ArrowLeft move focus and select the tab.
  • ArrowRight and ArrowLeft skip tabs the page hides.
  • Disabled tabs are focusable but never selected.
  • Focus wraps at both ends.
  • Home and End move to the first and last tabs.
  • ArrowUp and ArrowDown do nothing in a horizontal tab list.
  • Arrow keys with a modifier are left to the browser.
  • Keys pressed in quick succession are never lost.
  • Tab moves focus from the tab list into the selected panel.
  • Shift+Tab from the panel returns to the selected tab.
Manual activation
  • Tab leaves the list from a focused tab before the selected one.
  • Shift+Tab leaves the list from a focused tab after the selected one.
  • Arrow keys move focus without selecting.
  • Enter selects the focused tab.
  • Space selects the focused tab.
  • Enter on a disabled tab does nothing.
Vertical
  • The tab list reports its orientation.
  • ArrowDown and ArrowUp move between tabs.
  • ArrowLeft and ArrowRight do nothing in a vertical tab list.
Panels
  • The selected tab controls its panel, and the panel is labelled by its tab.
  • With keepMounted, hidden panels stay in the page.
  • With keepMounted, a class that sets display doesn't show hidden panels.

运行于 React、Vue 和 web components。

在模式基线之外:

Enhancements
  • In manual mode, re-entering the tab list focuses the selected tab.
  • A panel that holds a field is not a tab stop of its own.
  • A controller selects a tab from anywhere.
  • An infinite exit animation still unmounts the panel.

运行于 React、Vue 和 web components。

在每个测试过的框架里,屏幕阅读器听到的内容相同,由虚拟屏幕阅读器录制:

  • Announcements while using the tabs with a keyboard.

运行于 React、Vue 和 web components。