穿行于列表和网格之间,通过输入查找条目,在页面变化时保持焦点,并给字段配上合适的键盘。

一组部件只有一个 Tab 停靠点、需要用方向键导航时,用 createRovingFocus;按行和列移动时,用 createGridFocus。其他辅助函数通过输入查找条目、选择附近的目标、在条目移动或消失时恢复焦点,并通过 inputHints 给字段配上合适的键盘。

从 @ui-sdk/core 导入它们。组合行为演示如何把游走焦点(roving focus)接到部件上。聚焦的条目做什么由你的组件决定;选择涵盖选中条目和范围。

游走焦点

一个 Tab 停靠点

星级评分用的是 orientation: () => "both",四个方向键都启用。一排按钮只需要 Left 和 Right:

const roving = createRovingFocus(context, {
  slot: "item",
  key: "focused",
  orientation: () => "horizontal",
})

这会处理 Left、Right、Home 和 End。竖向列表用 Up 和 Down,省略 orientation 即可。Left 和 Right 遵循页面的文字方向。

import * as React from "react"
import { createRovingFocus, definePrimitive, selects } from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type ToolbarState = { focused: string | null }

const toolbar = definePrimitive({
  name: "toolbar",
  state: (): ToolbarState => ({ focused: null }),
  api: (context) => ({
    roving: createRovingFocus<ToolbarState, { value: string }>(context, {
      slot: "item",
      key: "focused",
      orientation: () => "horizontal",
    }),
  }),
  slots: (slot) => ({
    root: slot({ attrs: () => ({ role: "toolbar" }) }),
    item: slot<{ value: string }>({
      props: { value: "string" },
      selects: selects({ focused: ({ key }) => [key, null] }),
      attrs: (state, part) => ({
        type: "button",
        tabindex: part.api.roving.tabIndex(state, part),
      }),
      on: { keydown: (event, { el, api }) => api.roving.keydown(event, el!) },
      bind: (el, part) => part.api.roving.bind(el, part),
    }),
  }),
})

const parts = createParts(toolbar, { root: "div", item: "button" })

const Toolbar = parts.Root

const ToolbarItem = parts.Item

function Example() {
  return (
    <Toolbar aria-label="Formatting">
      {["Bold", "Italic", "Underline", "Strike"].map((label) => (
        <ToolbarItem key={label} value={label}>
          {label}
        </ToolbarItem>
      ))}
    </Toolbar>
  )
}

export { Example, toolbar, Toolbar, ToolbarItem, type ToolbarState }
按 Tab 进入工具栏。用 Left、Right、Home 或 End 在按钮之间移动;按 Tab 离开这一组。

默认情况下,最后聚焦的条目保留 Tab 停靠点。如果想改为回到选中的条目,就用 remember: false、preferred 和 claims,就像我们在评分指南里做的那样。

禁用条目与循环

不可用的动作有时仍然值得找到。传入 disabled,选择 Tab 停靠点时优先选启用的条目,同时让方向键仍能到达每一个动作:

const roving = createRovingFocus(context, {
  slot: "item",
  key: "focused",
  disabled: (item) => !!item.props.disabled,
  loop: () => true,
})

loop 让焦点从最后一个条目绕回第一个,也能再绕回来。

import * as React from "react"
import { createRovingFocus, definePrimitive, selects } from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type ToolbarState = { focused: string | null }

type ToolProps = { value: string; disabled?: boolean }

const toolbar = definePrimitive({
  name: "vertical-toolbar",
  state: (): ToolbarState => ({ focused: null }),
  api: (context) => ({
    roving: createRovingFocus<ToolbarState, ToolProps>(context, {
      slot: "item",
      key: "focused",
      orientation: () => "vertical",
      loop: () => true,
      disabled: (item) => !!item.props.disabled,
    }),
  }),
  slots: (slot) => ({
    root: slot({
      attrs: () => ({ role: "toolbar", "aria-orientation": "vertical" }),
    }),
    item: slot<ToolProps>({
      props: { value: "string", disabled: "boolean" },
      selects: selects({ focused: ({ key }) => [key, null] }),
      attrs: (state, part) => ({
        type: "button",
        tabindex: part.api.roving.tabIndex(state, part),
        "aria-disabled": part.props.disabled ? "true" : undefined,
      }),
      on: { keydown: (event, { el, api }) => api.roving.keydown(event, el!) },
      bind: (el, part) => part.api.roving.bind(el, part),
    }),
  }),
})

const parts = createParts(toolbar, { root: "div", item: "button" })

const Toolbar = parts.Root

const ToolbarItem = parts.Item

function Example() {
  return (
    <Toolbar aria-label="Edit">
      {["Undo", "Redo", "Cut", "Copy", "Paste"].map((label) => (
        <ToolbarItem
          key={label}
          value={label}
          disabled={label === "Undo" || label === "Redo"}
        >
          {label}
        </ToolbarItem>
      ))}
    </Toolbar>
  )
}

export {
  Example,
  toolbar,
  Toolbar,
  ToolbarItem,
  type ToolbarState,
  type ToolProps,
}
按 Tab 到 Cut,然后按 Up 到达已禁用的 Redo 动作。继续按 Up 或 Down 可以循环绕回。

条目仍需要 aria-disabled 和一个忽略它的按压处理函数。原生 disabled 按钮无法获得焦点。如果所有条目都已禁用,这一组仍然可以把 Tab 停靠点给其中一个。

无法获得焦点的条目

如果某个条目应该被完全跳过,就用 focusable。这些嵌套文件夹在所在分支关闭时仍保持渲染:

focusable: (item) => !item.props.nested || context.store.get().open,
import * as React from "react"
import { createRovingFocus, definePrimitive, selects } from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"
import { ChevronRight } from "lucide-react"

type FoldersState = { focused: string | null; open: boolean }

type FolderProps = { value: string; nested?: boolean }

const folders = definePrimitive({
  name: "folders",
  state: (): FoldersState => ({ focused: null, open: false }),
  api: (context) => ({
    roving: createRovingFocus<FoldersState, FolderProps>(context, {
      slot: "item",
      key: "focused",
      focusable: (item) => !item.props.nested || context.store.get().open,
    }),
    toggle: () => context.store.set({ open: !context.store.get().open }),
  }),
  slots: (slot) => ({
    root: slot({}),
    item: slot<FolderProps>({
      props: { value: "string", nested: "boolean" },
      selects: selects({ focused: ({ key }) => [key, null] }),
      attrs: (state, part) => ({
        type: "button",
        tabindex: part.api.roving.tabIndex(state, part),
        hidden: part.props.nested && !state.open ? "" : undefined,
      }),
      on: { keydown: (event, { el, api }) => api.roving.keydown(event, el!) },
      bind: (el, part) => part.api.roving.bind(el, part),
    }),
    toggle: slot<{ value: string }>({
      props: { value: "string" },
      selects: selects({ focused: ({ key }) => [key, null] }),
      attrs: (state, part) => ({
        type: "button",
        tabindex: part.api.roving.tabIndex(state, part),
        "aria-expanded": String(state.open),
      }),
      press: ({ api }) => api.toggle(),
      on: { keydown: (event, { el, api }) => api.roving.keydown(event, el!) },
      bind: (el, part) => part.api.roving.bind(el, part),
    }),
  }),
})

const parts = createParts(folders, {
  root: "div",
  item: "button",
  toggle: "button",
})

const Folders = parts.Root

const FoldersItem = parts.Item

const FoldersToggle = parts.Toggle

function Example() {
  return (
    <Folders role="group" aria-label="Folders">
      <FoldersItem value="Inbox">Inbox</FoldersItem>
      <FoldersItem value="Drafts">Drafts</FoldersItem>
      <FoldersToggle value="Labels">
        Labels
        <ChevronRight aria-hidden="true" />
      </FoldersToggle>
      {["Work", "Family", "Travel"].map((label) => (
        <FoldersItem key={label} value={label} nested>
          {label}
        </FoldersItem>
      ))}
      <FoldersItem value="Trash">Trash</FoldersItem>
    </Folders>
  )
}

export {
  Example,
  folders,
  Folders,
  FoldersItem,
  type FoldersState,
  FoldersToggle,
}
用方向键到达 Labels。按 Enter 打开它,然后按 Down 到达 Work。

状态变化时,这一组会重新检查 focusable。如果它依赖状态之外的东西,就在那个东西变化后调用 roving.check()。

来来去去的条目

roving.focus(key) 把焦点移到一个条目上。你也可以在条目渲染之前就调用它:

function add(tag: string) {
  context.options().onAdd?.(tag)
  roving.focus(tag)
}
控制台
import * as React from "react"
import { createRovingFocus, definePrimitive, selects } from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"
import { useLog } from "./log"

type TagListOptions = {
  onAdd?: (tag: string) => void
  onCountChange?: (count: number) => void
}

type TagListState = { focused: string | null }

const tagList = definePrimitive({
  name: "tag-list",
  options: { onAdd: "callback", onCountChange: "callback" },
  state: (_options: TagListOptions): TagListState => ({ focused: null }),
  api: (context) => {
    const roving = createRovingFocus<TagListState, { value: string }>(context, {
      slot: "tag",
      key: "focused",
      orientation: () => "horizontal",
      onItemsChange: () =>
        context.options().onCountChange?.(roving.items().length),
    })
    return {
      roving,
      add(input: HTMLInputElement) {
        const tag = input.value.trim()
        if (!tag) {
          return
        }
        context.options().onAdd?.(tag)
        input.value = ""
        roving.focus(tag)
      },
    }
  },
  slots: (slot) => ({
    root: slot({}),
    input: slot({
      on: {
        keydown: (event, { el, api }) => {
          if (event.key !== "Enter") {
            return
          }
          event.preventDefault()
          api.add(el as HTMLInputElement)
        },
      },
    }),
    list: slot({}),
    tag: slot<{ value: string }>({
      props: { value: "string" },
      selects: selects({ focused: ({ key }) => [key, null] }),
      attrs: (state, part) => ({
        type: "button",
        tabindex: part.api.roving.tabIndex(state, part),
      }),
      on: { keydown: (event, { el, api }) => api.roving.keydown(event, el!) },
      bind: (el, part) => part.api.roving.bind(el, part),
    }),
  }),
})

const parts = createParts(tagList, {
  root: "div",
  input: "input",
  list: "div",
  tag: "button",
})

const TagList = parts.Root

const TagListInput = parts.Input

const TagListList = parts.List

const TagListTag = parts.Tag

function Example() {
  const log = useLog()
  const [tags, setTags] = React.useState(["design", "docs"])
  return (
    <TagList
      onAdd={(tag: string) =>
        setTags((tags) => (tags.includes(tag) ? tags : [...tags, tag]))
      }
      onCountChange={(count: number) =>
        log(`${count} ${count === 1 ? "tag" : "tags"}`)
      }
    >
      <TagListInput
        aria-label="New tag"
        placeholder="Type a tag and press Enter"
      />
      <TagListList role="group" aria-label="Tags">
        {tags.map((tag) => (
          <TagListTag data-size="sm" key={tag} value={tag}>
            {tag}
          </TagListTag>
        ))}
      </TagListList>
    </TagList>
  )
}

export {
  Example,
  tagList,
  TagList,
  TagListInput,
  TagListList,
  type TagListOptions,
  TagListTag,
}
输入一个标签并按 Enter。新标签会获得焦点,控制台会记录数量。

roving.items() 按文档顺序返回可获得焦点的条目,每项带有 key、props 和 el。这个演示用 onItemsChange 在条目加入或离开后更新计数。

当新条目作为本次更新的一部分渲染时,这样可行。对于之后才加载的数据,等条目就绪后再调用 focus(key)。如果用户在此期间把焦点移到了别处,焦点就留在那里。

只移动 Tab 停靠点,不移动焦点

快捷键可以在焦点留在编辑器里时使用工具栏动作。在这个快捷键的处理函数里调用 remember,下次进入工具栏时就会落在那个动作上:

api.roving.remember("Underline")
import * as React from "react"
import { createRovingFocus, definePrimitive, selects } from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type EditorState = { focused: string | null }

const shortcuts: Record<string, string> = {
  b: "Bold",
  i: "Italic",
  u: "Underline",
}

const editor = definePrimitive({
  name: "editor",
  state: (): EditorState => ({ focused: null }),
  api: (context) => ({
    roving: createRovingFocus<EditorState, { value: string }>(context, {
      slot: "button",
      key: "focused",
      orientation: () => "horizontal",
    }),
  }),
  slots: (slot) => ({
    root: slot({}),
    toolbar: slot({ attrs: () => ({ role: "toolbar" }) }),
    button: slot<{ value: string }>({
      props: { value: "string" },
      selects: selects({ focused: ({ key }) => [key, null] }),
      attrs: (state, part) => ({
        type: "button",
        tabindex: part.api.roving.tabIndex(state, part),
      }),
      on: { keydown: (event, { el, api }) => api.roving.keydown(event, el!) },
      bind: (el, part) => part.api.roving.bind(el, part),
    }),
    field: slot({
      on: {
        keydown: (event, { api }) => {
          const button = shortcuts[event.key.toLowerCase()]
          if (!button || !(event.ctrlKey || event.metaKey)) {
            return
          }
          event.preventDefault()
          api.roving.remember(button)
        },
      },
    }),
  }),
})

const parts = createParts(editor, {
  root: "div",
  toolbar: "div",
  button: "button",
  field: "textarea",
})

const Editor = parts.Root

const EditorToolbar = parts.Toolbar

const EditorButton = parts.Button

const EditorField = parts.Field

function Example() {
  return (
    <Editor>
      <EditorToolbar aria-label="Format">
        {Object.values(shortcuts).map((label) => (
          <EditorButton key={label} value={label}>
            {label}
          </EditorButton>
        ))}
      </EditorToolbar>
      <EditorField
        aria-label="Notes"
        rows={3}
        defaultValue="Press Control or Command with U, then Shift+Tab."
      />
    </Editor>
  )
}

export {
  Editor,
  EditorButton,
  EditorField,
  type EditorState,
  EditorToolbar,
  editor,
  Example,
}
在 Notes 里,按 Control 或 Command 加 U,再按 Shift+Tab。焦点回到 Underline。

remember(key) 改变 Tab 停靠点,但不移动焦点。设置了 remember: false 的组会忽略它。

任意布局

move 决定每个按键去往哪里。小键盘可以用它让 Up 和 Down 一次移动三个条目:

move: (event, { from, items, rtl }) => {
  if (event.ctrlKey || event.metaKey) {
    return
  }

  const index = items.findIndex((item) => item.key === from.key)
  const by = {
    ArrowDown: 3,
    ArrowUp: -3,
    ArrowRight: rtl ? -1 : 1,
    ArrowLeft: rtl ? 1 : -1,
  }[event.key]

  return by === undefined ? undefined : items[index + by]?.key
},
import * as React from "react"
import { createRovingFocus, definePrimitive, selects } from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type KeypadState = { focused: string | null }

const columns = 3

const keypad = definePrimitive({
  name: "keypad",
  state: (): KeypadState => ({ focused: null }),
  api: (context) => ({
    roving: createRovingFocus<KeypadState, { value: string }>(context, {
      slot: "digit",
      key: "focused",
      move: (event, { from, items, rtl }) => {
        if (event.ctrlKey || event.metaKey) {
          return
        }
        const index = items.findIndex((item) => item.key === from.key)
        const by = {
          ArrowDown: columns,
          ArrowUp: -columns,
          ArrowRight: rtl ? -1 : 1,
          ArrowLeft: rtl ? 1 : -1,
        }[event.key]
        return by === undefined ? undefined : items[index + by]?.key
      },
    }),
  }),
  slots: (slot) => ({
    root: slot({ attrs: () => ({ role: "group" }) }),
    digit: slot<{ value: string }>({
      props: { value: "string" },
      selects: selects({ focused: ({ key }) => [key, null] }),
      attrs: (state, part) => ({
        type: "button",
        tabindex: part.api.roving.tabIndex(state, part),
      }),
      on: { keydown: (event, { el, api }) => api.roving.keydown(event, el!) },
      bind: (el, part) => part.api.roving.bind(el, part),
    }),
  }),
})

const parts = createParts(keypad, { root: "div", digit: "button" })

const Keypad = parts.Root

const KeypadDigit = parts.Digit

function Example() {
  return (
    <Keypad aria-label="Keypad">
      {["1", "2", "3", "4", "5", "6", "7", "8", "9"].map((digit) => (
        <KeypadDigit key={digit} value={digit}>
          {digit}
        </KeypadDigit>
      ))}
    </Keypad>
  )
}

export { Example, keypad, Keypad, KeypadDigit, type KeypadState }
聚焦一个数字。用 Up 和 Down 移动一行,用 Left 和 Right 移动一项。

move 接收聚焦的条目、按文档顺序排列的可获得焦点的条目,以及文字方向。返回一个键就移动到那里,返回 undefined 则不干预这次按键。它会替换内置的方向键、Home、End 和循环规则,所以你的组件需要哪些规则就自己包含哪些。

和 focus(key) 一样,它可以返回一个即将渲染的条目的键。日历可以用它从一个月的最后一天移到下个月。

沿环排列

动作沿圆圈排列时,Left 和 Right 可以按它们在环上的顺序移动。使用内置的横向按键并加上循环:

const roving = createRovingFocus(context, {
  slot: "action",
  key: "focused",
  orientation: () => "horizontal",
  loop: () => true,
})

按动作在圆圈上的顺序渲染它们。它们的位置不会改变下一个动作是谁。

import * as React from "react"
import { createRovingFocus, definePrimitive, selects } from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type RingState = { focused: string | null }

const actions = ["Reply", "Forward", "Archive", "Snooze", "Delete", "Label"]

function place(action: string) {
  const angle =
    (actions.indexOf(action) / actions.length) * 2 * Math.PI - Math.PI / 2
  return { x: Math.cos(angle), y: Math.sin(angle) }
}

const ring = definePrimitive({
  name: "ring",
  state: () => ({ focused: null as string | null }),
  api: (context) => ({
    roving: createRovingFocus<RingState, { value: string }>(context, {
      slot: "action",
      key: "focused",
      orientation: () => "horizontal",
      loop: () => true,
    }),
  }),
  slots: (slot) => ({
    root: slot({ attrs: () => ({ role: "toolbar" }) }),
    action: slot<{ value: string }>({
      props: { value: "string" },
      selects: selects({ focused: ({ key }) => [key, null] }),
      attrs: (state, part) => ({
        type: "button",
        tabindex: part.api.roving.tabIndex(state, part),
      }),
      on: { keydown: (event, { el, api }) => api.roving.keydown(event, el!) },
      bind: (el, part) => part.api.roving.bind(el, part),
    }),
  }),
})

const parts = createParts(ring, { root: "div", action: "button" })

const Ring = parts.Root

const RingAction = parts.Action

function Example() {
  return (
    <Ring aria-label="Message">
      {actions.map((action) => {
        const { x, y } = place(action)
        return (
          <RingAction
            data-size="sm"
            key={action}
            value={action}
            style={
              {
                "--x": `${50 + x * 36}%`,
                "--y": `${50 + y * 36}%`,
              } as React.CSSProperties
            }
          >
            {action}
          </RingAction>
        )
      })}
    </Ring>
  )
}

export { Example, ring, Ring, RingAction, type RingState }
聚焦一个动作,然后不断按 Left 或 Right 在环上循环。Home 和 End 跳到第一个和最后一个动作。

空间焦点

跟随布局

在看板上,文档里的下一个条目未必是右边的那一个。用 spatialMove() 按方向键的方向选择附近的条目:

const roving = createRovingFocus(context, {
  slot: "note",
  key: "focused",
  move: spatialMove(),
})
import * as React from "react"
import {
  createRovingFocus,
  definePrimitive,
  selects,
  spatialMove,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type PinboardState = { focused: string | null }

const pinboard = definePrimitive({
  name: "pinboard",
  state: (): PinboardState => ({ focused: null }),
  api: (context) => ({
    roving: createRovingFocus<PinboardState, { value: string }>(context, {
      slot: "note",
      key: "focused",
      move: spatialMove(),
    }),
  }),
  slots: (slot) => ({
    root: slot({ attrs: () => ({ role: "group" }) }),
    note: slot<{ value: string }>({
      props: { value: "string" },
      selects: selects({ focused: ({ key }) => [key, null] }),
      attrs: (state, part) => ({
        type: "button",
        tabindex: part.api.roving.tabIndex(state, part),
      }),
      on: { keydown: (event, { el, api }) => api.roving.keydown(event, el!) },
      bind: (el, part) => part.api.roving.bind(el, part),
    }),
  }),
})

const parts = createParts(pinboard, { root: "div", note: "button" })

const Pinboard = parts.Root

const PinboardNote = parts.Note

const notes = [
  { text: "Call Hollis", x: 8, y: 12 },
  { text: "Ship docs", x: 62, y: 6 },
  { text: "Lunch", x: 36, y: 44 },
  { text: "Review", x: 4, y: 70 },
  { text: "Gym", x: 70, y: 64 },
]

function Example() {
  return (
    <Pinboard aria-label="Notes">
      {notes.map((note) => (
        <PinboardNote
          key={note.text}
          value={note.text}
          style={{ left: `${note.x}%`, top: `${note.y}%` }}
        >
          {note.text}
        </PinboardNote>
      ))}
    </Pinboard>
  )
}

export { Example, pinboard, Pinboard, PinboardNote, type PinboardState }
聚焦一张便签,然后用方向键移动到该方向上附近的便签。

spatialMove 测量元素的位置,并偏向正前方的条目。即使在从右到左的文字里,Left 也始终表示屏幕上的左边。Home 和 End 按文档顺序移动。Alt、Control 和 Command 组合留给其他快捷键。

提供你自己的位置

如果你的应用已经知道各个条目的位置,就传入一个 rect 函数。这对缩放过的画布,或按角度计算出来的布局很有用:

move: spatialMove({
  rect: (el, key) => {
    const { x, y } = place(key)
    return { left: x, right: x, top: y, bottom: y }
  },
}),

每个条目使用相同的单位,y 值越大越靠下。

选择目标而不移动焦点

nearestInDirection 在普通的矩形盒子上做同样的基于位置的搜索。它返回一个键,结果怎么用由你决定:

const next = nearestInDirection(
  { left: 0, right: 10, top: 0, bottom: 10 },
  [{ key: "next", rect: { left: 20, right: 30, top: 0, bottom: 10 } }],
  [1, 0]
)
// next is "next".

方向是 [x, y]:[1, 0] 表示右,[0, -1] 表示上。如果那个方向什么都没有,结果就是 undefined。

import * as React from "react"
import { definePrimitive, nearestInDirection } from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type CityMapState = { city: string }

const cities: Record<string, { x: number; y: number }> = {
  Lisbon: { x: 14, y: 78 },
  Paris: { x: 36, y: 40 },
  London: { x: 30, y: 18 },
  Berlin: { x: 64, y: 22 },
  Rome: { x: 62, y: 74 },
  Vienna: { x: 78, y: 46 },
}

const directions: Record<string, readonly [number, number]> = {
  ArrowUp: [0, -1],
  ArrowDown: [0, 1],
  ArrowLeft: [-1, 0],
  ArrowRight: [1, 0],
}

const box = (city: string) => {
  const { x, y } = cities[city]
  return { left: x, right: x, top: y, bottom: y }
}

const cityMap = definePrimitive({
  name: "city-map",
  state: (): CityMapState => ({ city: "Paris" }),
  api: (context) => ({
    go(direction: readonly [number, number]) {
      const { city } = context.store.get()
      const others = Object.keys(cities)
        .filter((other) => other !== city)
        .map((other) => ({ key: other, rect: box(other) }))
      const next = nearestInDirection(box(city), others, direction)
      if (next) {
        context.store.set({ city: next })
      }
    },
  }),
  slots: (slot) => ({
    map: slot({
      attrs: (state) => ({
        role: "img",
        tabindex: "0",
        "aria-label": `Map, ${state.city} chosen`,
      }),
      on: {
        keydown: (event, { api }) => {
          const direction = directions[event.key]
          if (!direction) {
            return
          }
          event.preventDefault()
          api.go(direction)
        },
      },
    }),
    city: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, part) => ({
        "data-chosen": state.city === part.key ? "" : undefined,
      }),
    }),
    arrow: slot<{ value: string }>({
      props: { value: "string" },
      attrs: () => ({ type: "button" }),
      press: ({ api, key }) => api.go(directions[key]),
    }),
  }),
})

const parts = createParts(cityMap, {
  map: "div",
  city: "span",
  arrow: "button",
})

const CityMap = parts.Root

const CityMapMap = parts.Map

const CityMapCity = parts.City

const CityMapArrow = parts.Arrow

const labels = {
  ArrowUp: "North",
  ArrowLeft: "West",
  ArrowRight: "East",
  ArrowDown: "South",
}

function Example() {
  return (
    <CityMap>
      <div data-slot="stack">
        <div data-slot="controls">
          {Object.entries(labels).map(([key, label]) => (
            <CityMapArrow key={key} value={key} data-size="sm">
              {label}
            </CityMapArrow>
          ))}
        </div>
        <CityMapMap>
          {Object.entries(cities).map(([city, { x, y }]) => (
            <CityMapCity
              key={city}
              value={city}
              aria-hidden="true"
              style={{ left: `${x}%`, top: `${y}%` }}
            >
              {city}
            </CityMapCity>
          ))}
        </CityMapMap>
      </div>
    </CityMap>
  )
}

export {
  CityMap,
  CityMapArrow,
  CityMapCity,
  CityMapMap,
  cityMap,
  type CityMapState,
  Example,
}
聚焦地图,用方向键选择城市。焦点仍留在地图上。

键入查找

文本涵盖根据输入的字符查找条目。要把焦点移到匹配项上,把它与 roving.items() 和 roving.focus() 结合使用:

const typeahead = createTypeahead()

function keydown(event: KeyboardEvent, el: HTMLElement) {
  if (
    event.defaultPrevented ||
    roving.keydown(event, el) ||
    !isTypeaheadKey(event)
  ) {
    return
  }
  if (event.key === " " && typeahead.active()) {
    event.preventDefault()
  }

  const items = roving.items()
  const index = typeahead(
    event.key,
    items.map((item) => labelOf(item.el)),
    items.findIndex((item) => item.el === el)
  )
  if (index !== -1) {
    roving.focus(items[index].key)
  }
}

在 api 里创建一次 typeahead,然后把这个处理函数接到条目的 keydown 上。

import * as React from "react"
import {
  createRovingFocus,
  createTypeahead,
  definePrimitive,
  isTypeaheadKey,
  labelOf,
  selects,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type FruitListState = { focused: string | null }

const fruitList = definePrimitive({
  name: "fruit-list",
  state: (): FruitListState => ({ focused: null }),
  api: (context) => {
    const roving = createRovingFocus<FruitListState, { value: string }>(
      context,
      {
        slot: "item",
        key: "focused",
      }
    )
    const typeahead = createTypeahead()
    return {
      roving,
      keydown(event: KeyboardEvent, el: HTMLElement) {
        if (
          event.defaultPrevented ||
          roving.keydown(event, el) ||
          !isTypeaheadKey(event)
        ) {
          return
        }
        if (event.key === " " && typeahead.active()) {
          event.preventDefault()
        }
        const items = roving.items()
        const index = typeahead(
          event.key,
          items.map((item) => labelOf(item.el)),
          items.findIndex((item) => item.el === el)
        )
        if (index !== -1) {
          roving.focus(items[index].key)
        }
      },
    }
  },
  slots: (slot) => ({
    root: slot({ attrs: () => ({ role: "listbox" }) }),
    item: slot<{ value: string }>({
      props: { value: "string" },
      selects: selects({ focused: ({ key }) => [key, null] }),
      attrs: (state, part) => ({
        role: "option",
        tabindex: part.api.roving.tabIndex(state, part),
      }),
      on: { keydown: (event, { el, api }) => api.keydown(event, el!) },
      bind: (el, part) => part.api.roving.bind(el, part),
    }),
  }),
})

const parts = createParts(fruitList, { root: "div", item: "div" })

const FruitList = parts.Root

const FruitListItem = parts.Item

const fruits = ["Apple", "Banana", "Cherry", "Peach", "Pear", "Plum", "Quince"]

function Example() {
  return (
    <FruitList aria-label="Fruit">
      {fruits.map((fruit) => (
        <FruitListItem key={fruit} value={fruit}>
          {fruit}
        </FruitListItem>
      ))}
    </FruitList>
  )
}

export { Example, fruitList, FruitList, FruitListItem, type FruitListState }
聚焦 Apple,反复按 P 在匹配项之间循环。停顿一下,然后快速输入 PL 到达 Plum。

焦点恢复

聚焦的行被移除时,浏览器可能把焦点留在页面上。createFocusRecovery 让你选择焦点该去哪里:

const recovery = createFocusRecovery<{ value: string; index: number }>({
  fallback: (lost) => {
    const items = roving.items()
    return (items[lost.props.index] ?? items.at(-1))?.el
  },
})

这会选中取代旧行位置的那一行;如果移除的是末尾,就选最后一行。从 api 返回 recovery,然后把它和游走焦点一起绑定:

bind: (el, part) => {
  const unbindFocus = part.api.roving.bind(el, part)
  const unbindRecovery = part.api.recovery.bind(el, part)
  return () => {
    unbindFocus()
    unbindRecovery()
  }
},
import * as React from "react"
import {
  createFocusRecovery,
  createRovingFocus,
  definePrimitive,
  selects,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type TasksState = { focused: string | null }

type TaskProps = { value: string; index: number }

const tasks = definePrimitive({
  name: "tasks",
  state: (): TasksState => ({ focused: null }),
  api: (context) => {
    const roving = createRovingFocus<TasksState, TaskProps>(context, {
      slot: "task",
      key: "focused",
    })
    const recovery = createFocusRecovery<TaskProps>({
      fallback: (lost) => {
        const items = roving.items()
        return (items[lost.props.index] ?? items.at(-1))?.el
      },
    })
    return { roving, recovery }
  },
  slots: (slot) => ({
    root: slot({ attrs: () => ({ role: "list" }) }),
    task: slot<TaskProps>({
      props: { value: "string", index: "number" },
      selects: selects({ focused: ({ key }) => [key, null] }),
      attrs: (state, part) => ({
        role: "listitem",
        tabindex: part.api.roving.tabIndex(state, part),
      }),
      on: { keydown: (event, { el, api }) => api.roving.keydown(event, el!) },
      bind: (el, part) => {
        const cleanups = [
          part.api.roving.bind(el, part),
          part.api.recovery.bind(el, part),
        ]
        return () => cleanups.forEach((cleanup) => cleanup?.())
      },
    }),
  }),
})

const parts = createParts(tasks, { root: "div", task: "div" })

const Tasks = parts.Root

const TasksItem = parts.Task

function Example() {
  const [list, setList] = React.useState([
    "Write the intro",
    "Add examples",
    "Fix the links",
    "Ship it",
  ])
  const done = (task: string) =>
    setList((current) => current.filter((other) => other !== task))
  return (
    <Tasks aria-label="Tasks">
      {list.map((task, index) => (
        <TasksItem
          key={task}
          value={task}
          index={index}
          onKeyDown={(event) => event.key === "Delete" && done(task)}
        >
          {task}
          <button
            type="button"
            tabIndex={-1}
            data-variant="ghost"
            data-size="sm"
            onClick={() => done(task)}
          >
            Done
          </button>
        </TasksItem>
      ))}
      {!list.length && <p data-slot="hint">All done.</p>}
    </Tasks>
  )
}

export { Example, tasks, Tasks, TasksItem, type TaskProps, type TasksState }
聚焦一个任务并按 Delete,或点击 Done。焦点会移到一个仍然存在的任务上。

fallback 接收被移除部件的键、最后的 props 和元素。什么都不返回时,焦点留在原处。恢复会在部件解绑时运行,并等待渲染完成;它不会把焦点从别处(比如对话框)抢回来。

跟随移动的焦点

有时条目会移到另一个列表,并渲染成新的元素。在改变状态之后调用 keepFocus,传入一个能找到新元素的函数:

move(task: string) {
  const { done } = context.store.get()
  context.store.set({ done: [...done, task] })
  keepFocus(() => context.element("task", task))
},
import * as React from "react"
import { definePrimitive, keepFocus } from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type ChecklistOptions = {
  keep?: boolean
}

type ChecklistState = { done: string[] }

const checklist = definePrimitive({
  name: "checklist",
  options: { keep: "boolean" },
  state: (_options: ChecklistOptions): ChecklistState => ({ done: [] }),
  api: (context) => ({
    toggle(task: string) {
      const { done } = context.store.get()
      context.store.set({
        done: done.includes(task)
          ? done.filter((other) => other !== task)
          : [...done, task],
      })
      if (context.options().keep) {
        keepFocus(() => context.element("task", task))
      }
    },
  }),
  slots: (slot) => ({
    root: slot<{}, ChecklistState>({
      state: (state) => ({ done: state.done }),
    }),
    list: slot({ attrs: () => ({ role: "list" }) }),
    task: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, part) => ({
        type: "button",
        "aria-pressed": String(state.done.includes(part.key)),
      }),
      press: ({ api, key }) => api.toggle(key),
    }),
  }),
})

const parts = createParts(checklist, {
  root: "div",
  list: "ul",
  task: "button",
})

const Checklist = parts.Root

const ChecklistList = parts.List

const ChecklistTask = parts.Task

const tasks = ["Write the intro", "Add examples", "Fix the links"]

function Example() {
  const [keep, setKeep] = React.useState(true)
  return (
    <div data-slot="stack">
      <div data-slot="controls">
        <label data-slot="label">
          <input
            type="checkbox"
            checked={keep}
            onChange={(event) => setKeep(event.target.checked)}
          />
          Keep focus on the task
        </label>
      </div>
      <Checklist keep={keep}>
        {({ done }) =>
          [false, true].map((finished) => (
            <section key={String(finished)} data-slot="keep-focus-column">
              <h4>{finished ? "Done" : "To do"}</h4>
              <ChecklistList aria-label={finished ? "Done" : "To do"}>
                {tasks
                  .filter((task) => done.includes(task) === finished)
                  .map((task) => (
                    <li key={task}>
                      <ChecklistTask value={task}>{task}</ChecklistTask>
                    </li>
                  ))}
              </ChecklistList>
            </section>
          ))
        }
      </Checklist>
    </div>
  )
}

export {
  Checklist,
  checklist,
  ChecklistList,
  type ChecklistOptions,
  type ChecklistState,
  ChecklistTask,
  Example,
}
聚焦一个任务并按 Enter。焦点会在列表之间跟着它走。关掉任务上的 Keep focus 来对比。

keepFocus 会在更新后重试,让新元素有时间渲染。如果用户在此期间把焦点移到了别处,它不会打扰那个焦点。

网格

网格中的一个 Tab 停靠点

对于按行和列定位的单元格,用 createGridFocus。从 @ui-sdk/core 导入 GridCell 类型,把活动单元格初始化为 null,然后在 api 里创建这个行为:

state: () => ({ active: null as GridCell | null }),
api: (context) => ({
  grid: createGridFocus(context, {
    key: "active",
    rows: () => 3,
    cols: () => 6,
  }),
}),

每个单元格都有从零开始的 row 和 col。把它的 Tab 停靠点、按键和元素接到这个行为上:

seat: slot<{ id: string; row: number; col: number }>({
  props: { id: "string", row: "number", col: "number" },
  selects: selects({ active: byCell }),
  attrs: (state, { props, api }) => ({
    role: "gridcell",
    tabindex: api.grid.tabIndex(state, props),
  }),
  on: {
    keydown: (event, { api }) => api.grid.keydown(event),
    pointerdown: (event, { api, props }) => api.grid.focus(props, { reason: "item-press", event }),
  },
  bind: (el, { api, props }) => api.grid.bind(el, props),
}),

把单元格渲染在带 role="row" 的行里,再放进带 role="grid" 的根元素里。给每个单元格一个稳定的 id,比如 "1:2",好让原语(primitive)区分它们。

selects({ active: byCell }) 让一次移动只触达焦点离开的单元格和落到的单元格,所以有几千个单元格的网格依然很快。

import * as React from "react"
import {
  byCell,
  createGridFocus,
  definePrimitive,
  selects,
  type GridCell,
} from "@ui-sdk/core"
import { createParts, usePart, type PartProps } from "@ui-sdk/react/primitive"

type SeatMapState = { active: GridCell | null }

type SeatMapOptions = { rows: number; cols: number }

const seatMap = definePrimitive({
  name: "seat-map",
  options: { rows: "number", cols: "number" },
  state: (_options: SeatMapOptions): SeatMapState => ({ active: null }),
  api: (context) => ({
    grid: createGridFocus<SeatMapState>(context, {
      key: "active",
      rows: () => context.options().rows,
      cols: () => context.options().cols,
    }),
  }),
  slots: (slot) => ({
    root: slot({ attrs: () => ({ role: "grid" }) }),
    row: slot<{ id: string }>({
      props: { id: "string" },
      attrs: () => ({ role: "row" }),
    }),
    seat: slot<{ id: string; row: number; col: number }>({
      props: { row: "number", col: "number" },
      selects: selects({ active: byCell }),
      attrs: (state, { props, api }) => ({
        role: "gridcell",
        tabindex: api.grid.tabIndex(state, props),
      }),
      on: {
        keydown: (event, { api }) => api.grid.keydown(event),
        pointerdown: (event, { api, props }) =>
          api.grid.focus(props, { reason: "item-press", event }),
      },
      bind: (el, { api, props }) => api.grid.bind(el, props),
    }),
  }),
})

const parts = createParts(seatMap, { root: "div", row: "div" })

const SeatMap = parts.Root

const SeatMapRow = parts.Row

function SeatMapSeat({
  row,
  col,
  ...props
}: { row: number; col: number } & PartProps<"div">) {
  return usePart(
    seatMap,
    "seat",
    { id: `${row}:${col}`, row, col },
    props,
    "div"
  )
}

const letters = "ABCD"

function Example() {
  return (
    <SeatMap rows={3} cols={6} aria-label="Seats">
      {[0, 1, 2].map((row) => (
        <SeatMapRow key={row} id={String(row)}>
          {[0, 1, 2, 3, 4, 5].map((col) => (
            <SeatMapSeat
              key={col}
              row={row}
              col={col}
              aria-label={`Seat ${letters[row]}${col + 1}`}
            >
              {letters[row]}
              {col + 1}
            </SeatMapSeat>
          ))}
        </SeatMapRow>
      ))}
    </SeatMap>
  )
}

export {
  Example,
  seatMap,
  SeatMap,
  SeatMapRow,
  SeatMapSeat,
  type SeatMapOptions,
  type SeatMapState,
}
聚焦一个座位,用方向键移动。Home 和 End 到达本行的两端;按住 Control 或在 Mac 上按 Command,可到达网格的四角。

Left 和 Right 遵循文字方向。要从别的交互(比如点击)移动到某个单元格,调用 grid.focus({ row, col })。

无法获得焦点的单元格

传入 disabled 跳过不可用的单元格:

disabled: (cell) => context.options().taken.includes(`${cell.row}:${cell.col}`),

和游走焦点的 disabled 选项不同,这里会在导航时跳过该单元格。进入网格之前,Tab 会逐行落在第一个未禁用的单元格上。

import * as React from "react"
import {
  byCell,
  createGridFocus,
  definePrimitive,
  selects,
  type GridCell,
} from "@ui-sdk/core"
import { createParts, usePart, type PartProps } from "@ui-sdk/react/primitive"

type TheaterState = { active: GridCell | null }

type TheaterOptions = {
  taken: string[]
}

const theater = definePrimitive({
  name: "theater",
  options: { taken: "list" },
  state: (_options: TheaterOptions): TheaterState => ({ active: null }),
  api: (context) => ({
    grid: createGridFocus<TheaterState>(context, {
      key: "active",
      rows: () => 3,
      cols: () => 6,
      disabled: (cell) =>
        context.options().taken.includes(`${cell.row}:${cell.col}`),
    }),
  }),
  slots: (slot) => ({
    root: slot({ attrs: () => ({ role: "grid" }) }),
    row: slot<{ id: string }>({
      props: { id: "string" },
      attrs: () => ({ role: "row" }),
    }),
    seat: slot<{ id: string; row: number; col: number }>({
      props: { row: "number", col: "number" },
      selects: selects({ active: byCell }),
      attrs: (state, { props, api }) => ({
        role: "gridcell",
        tabindex: api.grid.tabIndex(state, props),
        "data-active": api.grid.isActive(state, props) ? "" : undefined,
      }),
      on: {
        keydown: (event, { api }) => api.grid.keydown(event),
        pointerdown: (event, { api, props }) =>
          api.grid.focus(props, { reason: "item-press", event }),
      },
      bind: (el, { api, props }) => api.grid.bind(el, props),
    }),
  }),
})

const parts = createParts(theater, { root: "div", row: "div" })

const Theater = parts.Root

const TheaterRow = parts.Row

function TheaterSeat({
  row,
  col,
  ...props
}: { row: number; col: number } & PartProps<"div">) {
  return usePart(
    theater,
    "seat",
    { id: `${row}:${col}`, row, col },
    props,
    "div"
  )
}

const letters = "ABC"
const taken = ["0:1", "0:2", "1:3", "2:0", "2:4"]

function Example() {
  return (
    <Theater taken={taken} aria-label="Theater">
      {[0, 1, 2].map((row) => (
        <TheaterRow key={row} id={String(row)}>
          {[0, 1, 2, 3, 4, 5].map((col) => {
            const isTaken = taken.includes(`${row}:${col}`)
            return (
              <TheaterSeat
                key={col}
                row={row}
                col={col}
                aria-label={`Seat ${letters[row]}${col + 1}${isTaken ? ", taken" : ""}`}
                aria-disabled={isTaken || undefined}
              >
                {letters[row]}
                {col + 1}
              </TheaterSeat>
            )
          })}
        </TheaterRow>
      ))}
    </Theater>
  )
}

export {
  Example,
  theater,
  Theater,
  TheaterRow,
  TheaterSeat,
  type TheaterOptions,
  type TheaterState,
}
用方向键越过已被占用的座位。按 Tab 离开网格;当前座位仍保持标记。

用 grid.isActive(state, cell) 在焦点离开时让活动单元格保持标记:

"data-active": api.grid.isActive(state, props) ? "" : undefined,

选择范围

onMove 会告诉你焦点移到了哪里、从哪里来,以及是否按住了 Shift。用它来记住选择的起点:

onMove: (cell, { from, shift }) => {
  const anchor = context.store.get().anchor ?? from
  context.store.set({ anchor: shift && anchor ? anchor : cell })
},
import * as React from "react"
import { createGridFocus, definePrimitive, type GridCell } from "@ui-sdk/core"
import { createParts, usePart, type PartProps } from "@ui-sdk/react/primitive"

type SheetState = { active: GridCell | null; anchor: GridCell | null }

const sheet = definePrimitive({
  name: "sheet",
  state: (): SheetState => ({ active: null, anchor: null }),
  api: (context) => ({
    grid: createGridFocus<SheetState>(context, {
      key: "active",
      rows: () => 4,
      cols: () => 4,
      onMove: (cell, { from, shift }) => {
        const anchor = context.store.get().anchor ?? from
        context.store.set({ anchor: shift && anchor ? anchor : cell })
      },
    }),
  }),
  slots: (slot) => ({
    root: slot({
      attrs: () => ({ role: "grid", "aria-multiselectable": "true" }),
    }),
    row: slot<{ id: string }>({
      props: { id: "string" },
      attrs: () => ({ role: "row" }),
    }),
    cell: slot<{ id: string; row: number; col: number }>({
      props: { row: "number", col: "number" },
      attrs: (state, { props, api }) => {
        const { active, anchor } = state
        const inside =
          !!active &&
          !!anchor &&
          props.row >= Math.min(active.row, anchor.row) &&
          props.row <= Math.max(active.row, anchor.row) &&
          props.col >= Math.min(active.col, anchor.col) &&
          props.col <= Math.max(active.col, anchor.col)
        return {
          role: "gridcell",
          tabindex: api.grid.tabIndex(state, props),
          "aria-selected": String(inside),
        }
      },
      on: {
        keydown: (event, { api }) => api.grid.keydown(event),
        pointerdown: (event, { api, props }) =>
          api.grid.focus(props, {
            reason: "item-press",
            event,
            shift: event.shiftKey,
          }),
      },
      bind: (el, { api, props }) => api.grid.bind(el, props),
    }),
  }),
})

const parts = createParts(sheet, { root: "div", row: "div" })

const Sheet = parts.Root

const SheetRow = parts.Row

function SheetCell({
  row,
  col,
  ...props
}: { row: number; col: number } & PartProps<"div">) {
  return usePart(sheet, "cell", { id: `${row}:${col}`, row, col }, props, "div")
}

const columns = "ABCD"

function Example() {
  return (
    <Sheet aria-label="Sheet">
      {[0, 1, 2, 3].map((row) => (
        <SheetRow key={row} id={String(row)}>
          {[0, 1, 2, 3].map((col) => (
            <SheetCell key={col} row={row} col={col}>
              {columns[col]}
              {row + 1}
            </SheetCell>
          ))}
        </SheetRow>
      ))}
    </Sheet>
  )
}

export { Example, sheet, Sheet, SheetCell, SheetRow, type SheetState }
点击一个单元格,然后按住 Shift 用方向键或点击另一个单元格来扩展范围。不按 Shift 移动即可重新开始。

要支持 Shift 点击,把 shift: event.shiftKey 传给 grid.focus。回调还会收到 event 和一个 reason:按键对应 "list-navigation",按压对应 "item-press",命令式调用对应 "imperative",这些名字与 listbox 上报的一致。选择涵盖如何把锚点(anchor)和活动单元格变成范围。

未渲染的行

大型网格可能只渲染可见的行。加上 reveal,在焦点移到目标行之前先把它带入视野:

reveal: ({ row }) => {
  const { first } = context.store.get()
  if (row < first) {
    context.store.set({ first: row })
  } else if (row >= first + 6) {
    context.store.set({ first: row - 5 })
  }
},
pageSize: () => 6,

这个时刻表一次显示六行。

import * as React from "react"
import {
  byCell,
  createGridFocus,
  definePrimitive,
  selects,
  type GridCell,
} from "@ui-sdk/core"
import { createParts, usePart, type PartProps } from "@ui-sdk/react/primitive"

type TimetableState = { active: GridCell | null; first: number }

const count = 100
const shown = 6

const timetable = definePrimitive({
  name: "timetable",
  state: (): TimetableState => ({ active: null, first: 0 }),
  api: (context) => ({
    grid: createGridFocus<TimetableState>(context, {
      key: "active",
      rows: () => count,
      cols: () => 3,
      pageSize: () => shown,
      reveal: ({ row }) => {
        const { first } = context.store.get()
        if (row < first) {
          context.store.set({ first: row })
        } else if (row >= first + shown) {
          context.store.set({ first: row - shown + 1 })
        }
      },
    }),
  }),
  slots: (slot) => ({
    root: slot<{}, { first: number }>({
      state: (state) => ({ first: state.first }),
    }),
    body: slot({
      attrs: () => ({ role: "grid", "aria-rowcount": String(count) }),
    }),
    row: slot<{ id: string; index: number }>({
      props: { index: "number" },
      attrs: (_state, { props }) => ({
        role: "row",
        "aria-rowindex": String(props.index + 1),
      }),
    }),
    cell: slot<{ id: string; row: number; col: number }>({
      props: { row: "number", col: "number" },
      selects: selects({ active: byCell }),
      attrs: (state, { props, api }) => ({
        role: "gridcell",
        tabindex: api.grid.tabIndex(state, props),
      }),
      on: {
        keydown: (event, { api }) => api.grid.keydown(event),
        pointerdown: (event, { api, props }) =>
          api.grid.focus(props, { reason: "item-press", event }),
      },
      bind: (el, { api, props }) => api.grid.bind(el, props),
    }),
  }),
})

const parts = createParts(timetable, { root: "div", body: "div" })

const Timetable = parts.Root

const TimetableBody = parts.Body

function TimetableRow({
  index,
  ...props
}: { index: number } & PartProps<"div">) {
  return usePart(timetable, "row", { id: String(index), index }, props, "div")
}

function TimetableCell({
  row,
  col,
  ...props
}: { row: number; col: number } & PartProps<"div">) {
  return usePart(
    timetable,
    "cell",
    { id: `${row}:${col}`, row, col },
    props,
    "div"
  )
}

const places = ["Leeds", "York", "Bath", "Hull", "Ely"]
const time = (row: number) => {
  const minutes = 6 * 60 + row * 7
  return `${String(Math.floor(minutes / 60)).padStart(2, "0")}:${String(minutes % 60).padStart(2, "0")}`
}
const cellText = (row: number, col: number) =>
  col === 0
    ? time(row)
    : col === 1
      ? places[row % places.length]
      : `Platform ${(row % 4) + 1}`

function Example() {
  return (
    <Timetable>
      {({ first }) => (
        <TimetableBody aria-label="Departures">
          {Array.from({ length: shown }, (_, offset) => first + offset).map(
            (row) => (
              <TimetableRow key={row} index={row}>
                {[0, 1, 2].map((col) => (
                  <TimetableCell key={col} row={row} col={col}>
                    {cellText(row, col)}
                  </TimetableCell>
                ))}
              </TimetableRow>
            )
          )}
        </TimetableBody>
      )}
    </Timetable>
  )
}

export {
  Example,
  timetable,
  Timetable,
  TimetableBody,
  TimetableCell,
  TimetableRow,
  type TimetableState,
}
聚焦一个单元格,按 Down 越过最后一行可见的行,或按 Page Down,把接下来的行带入视野。

pageSize 设置 Page Up 和 Page Down 移动多远。配合虚拟列表时,reveal 可以改为调用 virtualizer.scrollToIndex(row)。单元格绑定时焦点落下。

输入提示

有几个属性会告诉浏览器字段里装的是什么:inputmode 选择手机的按键,比如邮箱地址用带 @ 的键盘,验证码用数字键盘;enterkeyhint 选择 Return 键。autocomplete 说明要自动填充什么,autocapitalize、autocorrect 和 spellcheck 说明是否要改动人们输入的内容。inputHints 会为一类字段填好这些属性:

import { inputHints } from "@ui-sdk/core"

const hints = inputHints("email", { enter: "next" })
// { inputMode: "email", enterKeyHint: "next", autoComplete: "email", autoCapitalize: "none", autoCorrect: "off", spellCheck: "false" }

把它们展开到 <input> 或 <textarea> 上。它们按 React 的拼写方式书写,而 HTML 读取属性名时不区分大小写,所以同一个对象在 Vue、Svelte、Solid 和 setAttribute 里都能用。enter 设置 Return 键,比如后面还有字段时用 "next",最后一个字段用 "done"。iPhone 的数字键盘(用于 "tel"、"numeric"、"decimal" 和 "one-time-code")没有 Return 键,所以在这些键盘上,enter 只会在其他手机上显示。

类型按键与 Return 键自动填充与更正
"email"、"url"地址键盘自动填充地址,不大写、不更正
"tel"、"one-time-code"数字键盘自动填充号码,或来自短信的验证码
"numeric"、"decimal"数字,"decimal" 带小数点不自动填充
"search"搜索用 Return 键不自动填充,也不大写或标记拼写
"name"、"username"、"postal-code"常用键盘自动填充,并让姓名和邮政编码首字母大写
"current-password"、"new-password"常用键盘提供已保存的密码,或建议一个新密码
"message"发送用 Return 键开启大写、更正和拼写标记
import * as React from "react"
import { inputHints, type EnterKeyHint, type InputHintKind } from "@ui-sdk/core"
import {
  Field,
  FieldControl,
  FieldDescription,
  FieldLabel,
} from "@ui-sdk/react/field"

const fields: { label: string; kind: InputHintKind; enter?: EnterKeyHint }[] = [
  { label: "Email", kind: "email", enter: "next" },
  { label: "Phone", kind: "tel", enter: "next" },
  { label: "Verification code", kind: "one-time-code", enter: "done" },
  { label: "Search", kind: "search" },
  { label: "Message", kind: "message" },
]

const keys: Record<string, string> = {
  text: "Letter keys",
  email: "Email keys",
  tel: "Phone pad with + * #",
  url: "Web address keys",
  numeric: "Number pad",
  decimal: "Number pad with a decimal point",
  search: "Search keys",
}

const pads = new Set(["tel", "numeric", "decimal"])

const returns: Record<EnterKeyHint, string> = {
  enter: "return or ⏎",
  next: "next or ›",
  previous: "previous or ‹",
  done: "done or ✓",
  go: "go or →",
  search: "search or →",
  send: "send or ↑",
}

function Example() {
  return (
    <form data-slot="stack" onSubmit={(event) => event.preventDefault()}>
      {fields.map(({ label, kind, enter }) => {
        const hints = inputHints(kind, { enter })
        return (
          <Field key={kind}>
            <FieldLabel>{label}</FieldLabel>
            <FieldControl {...hints} />
            <FieldDescription>
              {keys[hints.inputMode ?? "text"]}
              {pads.has(hints.inputMode ?? "")
                ? ""
                : ` · Return says ${returns[hints.enterKeyHint ?? "enter"]}`}
            </FieldDescription>
          </Field>
        )
      })}
    </form>
  )
}

export { Example }
在手机上点按每个字段:按键会变,Return 键也会变;iOS 26 把它画成符号,比如 next 显示为 ›,search 显示为 →。

它们只是提示:字段保留自己的 type 和校验,所以 type="email" 的字段仍会检查地址。展开之后写的属性会替换这些提示。

API 参考

游走焦点选项

slotstring
The slot whose parts are the group's items. Each joins in the slot's bind with roving.bind(el, part).
示例: One Tab Stop
keykeyof State & string
The state key that holds the key of the item with the tab stop. Start it at null, and set it back to null to forget the item focused last.
示例: One Tab Stop
orientation?(() => RovingOrientation | "both")
Which arrows move focus when there's no move: Up and Down, Left and Right, or "both" for all four, like a rating. Defaults to "vertical".
示例: One Tab Stop
loop?(() => boolean)
Whether moving past either end wraps around. Defaults to false.
示例: Disabled Items and Wrapping
remember?boolean
Whether the item focused last keeps the stop, like a toolbar, rather than the preferred one, like tabs. Defaults to true.
示例: One Tab Stop
disabled?((item: RovingFocusItem<Props>) => boolean)
Whether an item can't be activated. Enabled items take the stop first; disabled ones can still take focus.
示例: Disabled Items and Wrapping
focusable?((item: RovingFocusItem<Props>) => boolean)
Whether an item can take focus now. An item that can't stays in the group and is skipped, like a tree item under a collapsed branch. Defaults to every item.
示例: Items That Can't Take Focus
preferred?((item: RovingFocusItem<Props>) => boolean)
Whether an item takes the stop before focus has been in the group: the selected tab, the checked radio.
示例: One Tab Stop
claims?((state: State, item: RovingFocusItem<Props>) => boolean)
Whether an item rendering before any item binds, like on the server, may hold the stop. The first such item does, so server markup has exactly one stop. Defaults to enabled and focusable items. Pass it when the stop should start on a selected item, like (state, item) => state.value === null || item.key === state.value.
示例: One Tab Stop
move?((event: KeyboardEvent, context: RovingFocusMoveContext<Props>) => string | undefined)
The key focus moves to for a key press, or undefined to leave the press alone. Replaces the default, which moves along orientation with the arrows, Home and End. Use it for any other shape: a tree's visible order, or a grid's rows. Shift is never swallowed, so a list can extend a range. The key may be one that isn't rendered or focusable yet, like the first day of next month in a calendar: the stop moves to it at once, and focus follows when its item can take it, as long as focus is still where the press left it.
示例: Any Layout
onItemsChange?(() => void)
Runs once after items join or leave, however many did, once the stop has moved to where the rules put it.
示例: Items That Come and Go

网格焦点选项

keykeyof State & string
The state key that holds the active GridCell, or null before the grid is entered.
示例: One Tab Stop in a Grid
rows() => number
How many rows the grid has, header rows included when they hold cells.
示例: One Tab Stop in a Grid
cols() => number
How many columns.
示例: One Tab Stop in a Grid
pageSize?(() => number)
How many rows Page Up and Page Down move, usually how many show.
示例: Rows That Aren't Rendered
disabled?((cell: GridCell) => boolean)
Cells that can't take focus, skipped by the arrows and by the tab stop before the grid is entered.
示例: Cells That Can't Take Focus
reveal?((cell: GridCell) => void)
Shows a cell that may not be rendered, like virtualizer.scrollToIndex(cell.row), before focus moves to it.
示例: Rows That Aren't Rendered
onMove?((cell: GridCell, details: { from: GridCell | null; reason: GridFocusReason; event?: Event; shift: boolean; }) => void)
Runs after the active cell moves, with the cell it left.
示例: Selecting a Range