搜索选项列表、渲染长列表、跟随新消息、滚动选取,以及就地编辑值。

用 createListbox 处理可以移动和搜索的选项,用 createVirtualizer 处理长列表,用 createStickToBottom 处理聊天和日志,用 bindScrollPicker 处理滚动选取的转轮,用 createInlineEdit 处理可编辑的标签。

每个辅助函数都可以单独工作,也可以在组件里与 焦点 和 选择 配合使用。

在选项之间移动

createListbox 保持一个选项高亮,并用方向键移动高亮,就像列表框或组合框那样。在状态里保留高亮选项的键,初始值为 null,并在 api 中创建这个行为:

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

const listbox = createListbox(context, {
  key: "highlighted",
  focus: "virtual",
})

使用 focus: "virtual" 时,焦点留在原处,比如在搜索框里,由输入框把 aria-activedescendant 指向高亮的选项。省略 focus,高亮则会改为把真实焦点从一个选项移到另一个选项。

每个选项在自己的槽位 bind 里接入,attrs 给它一个 id、data-highlighted 和 aria-disabled:

option: slot<{ value: string }>({
  role: "option",
  focus: "active-descendant",
  props: { value: "string" },
  selects: selects({ highlighted: ({ key }) => [key, null] }),
  attrs: (state, part) => ({
    ...part.api.listbox.attrs(state, part),
    "aria-selected": String(state.value === part.key),
  }),
  press: ({ key, api }, event) => api.choose(key, event),
  on: {
    pointerdown: (event) => event.preventDefault(),
    pointermove: (event, { key, api }) => api.listbox.highlight(key, { event }),
  },
  bind: (el, part) => part.api.listbox.bind(el, part),
}),

selects 让一次移动只到达它离开的选项和它落到的选项。在输入框上,把 aria-activedescendant 设为 api.listbox.activeId(state),并把 keydown 传给 api.listbox.keydown(event)。方向键、PageUp 和 PageDown 移动高亮。使用真实焦点时,Home、End 和输入选项名称也会移动它。越过任一端时会绕回,除非 loop 返回 false。

选择一个选项由你决定。按 Enter 时,从状态里读取高亮的键,并用 createChange 写入你的值;如果人们可以选择多个,则用 createSelection。

输入时过滤

把用于过滤的文本作为 query 传入。在上面这种组合列表里,选项只在匹配时才渲染,所以给选项槽位加上 present:

const listbox = createListbox(context, {
  key: "highlighted",
  focus: "virtual",
  query: () => context.store.get().query,
})
present: (_state, part) => part.api.listbox.shows(part),

选项按 label 属性匹配;没有 label 时按它们的文本匹配,忽略大小写和变音符号。查询变化时,调用 listbox.move("first") 高亮最匹配的选项,就像这个搜索:

控制台
import * as React from "react"
import {
  createChange,
  createListbox,
  definePrimitive,
  selects,
  type ChangeDetails,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"
import { useLog } from "./log"

type FruitPickerState = {
  value: string | null
  query: string
  highlighted: string | null
}

type FruitPickerOptions = {
  onValueChange?: (
    value: string | null,
    details: ChangeDetails<"item-press">
  ) => void
}

type FruitProps = { value: string; label?: string }

const fruitPicker = definePrimitive({
  name: "fruit-picker",
  options: { onValueChange: "callback" },
  state: (_options: FruitPickerOptions): FruitPickerState => ({
    value: null,
    query: "",
    highlighted: null,
  }),
  api: (context) => {
    const change = createChange(context)
    const listbox = createListbox(context, {
      key: "highlighted",
      focus: "virtual",
      query: () => context.store.get().query,
    })
    const choose = (key: string, event?: Event) =>
      change("value", key, { reason: "item-press", event })
    return {
      listbox,
      choose,
      search(query: string) {
        context.store.set({ query })
        listbox.move("first")
      },
      keydown(event: KeyboardEvent) {
        const { highlighted } = context.store.get()
        if (event.key === "Enter" && highlighted !== null) {
          event.preventDefault()
          choose(highlighted, event)
          return
        }
        listbox.keydown(event)
      },
    }
  },
  slots: (slot) => ({
    root: slot({}),
    input: slot({
      attrs: (state, { id, api }) => ({
        role: "combobox",
        "aria-expanded": "true",
        "aria-controls": `${id}-list`,
        "aria-autocomplete": "list",
        "aria-activedescendant": api.listbox.activeId(state),
      }),
      on: {
        input: (event, { api }) =>
          api.search((event.target as HTMLInputElement).value),
        keydown: (event, { api }) => api.keydown(event),
      },
    }),
    list: slot({
      attrs: (_state, { id }) => ({ id: `${id}-list`, role: "listbox" }),
    }),
    option: slot<FruitProps>({
      role: "option",
      focus: "active-descendant",
      props: { value: "string", label: "string" },
      selects: selects({ highlighted: ({ key }) => [key, null] }),
      present: (_state, part) => part.api.listbox.shows(part),
      attrs: (state, part) => ({
        ...part.api.listbox.attrs(state, part),
        "aria-selected": String(state.value === part.key),
      }),
      press: ({ key, api }, event) => api.choose(key, event),
      on: {
        pointerdown: (event) => event.preventDefault(),
        pointermove: (event, { key, api }) =>
          api.listbox.highlight(key, { event }),
      },
      bind: (el, part) => part.api.listbox.bind(el, part),
    }),
  }),
})

const parts = createParts(fruitPicker, {
  root: "div",
  input: "input",
  list: "div",
  option: "div",
})

const FruitPicker = parts.Root

const FruitPickerInput = parts.Input

const FruitPickerList = parts.List

const FruitPickerOption = parts.Option

const fruits = [
  "Apple",
  "Apricot",
  "Banana",
  "Blueberry",
  "Cherry",
  "Grape",
  "Mango",
  "Peach",
  "Pear",
  "Plum",
]

function Example() {
  const log = useLog()
  return (
    <FruitPicker
      onValueChange={(value: string | null) => log(`Chose ${value}`)}
    >
      <FruitPickerInput aria-label="Fruit" placeholder="Search fruit" />
      <FruitPickerList aria-label="Fruit">
        {fruits.map((fruit) => (
          <FruitPickerOption key={fruit} value={fruit}>
            {fruit}
          </FruitPickerOption>
        ))}
      </FruitPickerList>
    </FruitPicker>
  )
}

export {
  Example,
  fruitPicker,
  FruitPicker,
  FruitPickerInput,
  FruitPickerList,
  FruitPickerOption,
  type FruitPickerOptions,
  type FruitPickerState,
}
输入内容来过滤水果。用 Up 和 Down 移动高亮,按 Enter 或点击来选择一个。

filter 决定什么算匹配:默认是 "contains",也可以是 "startsWith",或一个返回 true、false 或分数的函数。分数会给选项排名,最优在前,0 会隐藏某个选项。listbox.count() 说明有多少选项匹配,用于一个都没匹配时的提示。

以数据形式提供的选项

对于来自数据的选项,把它们作为 items 传入:字符串、带 value 和 label 的条目、分组和分隔符。listbox.items() 按顺序返回匹配查询的内容,所以渲染它而不是完整列表:

const listbox = createListbox(context, {
  key: "highlighted",
  items: () => context.options().items,
  query: () => context.store.get().query,
})

传入 onHighlight 来获知高亮移动到了哪里,并带上它的索引,供 虚拟化器 滚动到;传入 onEnd,在到达最后一个选项时加载下一页。

选项

keykeyof State & string
The state key that holds the highlighted option's key. Start it at null.
示例: Move Through the Options
focus?"real" | "virtual"
"real" moves focus to the highlighted option. "virtual" keeps it where it is, like in an input that points aria-activedescendant at activeId(state). Defaults to "real".
示例: Move Through the Options
items?(() => ListData<T>)
The options as data: items, plain strings, groups and separators. Without it, the bound parts are the options, in document order.
示例: Options as Data
query?(() => string)
The text options are filtered by. Empty shows every option.
示例: Filter as You Type
filter?(() => ListFilter<T>)
How query narrows the options. A function that returns a number ranks them too, best first. Defaults to "contains".
示例: Filter as You Type
loop?(() => boolean)
Whether moving past either end wraps around. Defaults to true.
示例: Move Through the Options
onHighlight?((key: string | null, details: ListHighlightDetails) => void)
Runs when the highlight moves, with the option's index among those that match, for a virtualizer to scroll to.
示例: Options as Data
onEnd?(() => void)
Runs when the highlight reaches the last option, so the next page can load.
示例: Options as Data

长列表

只渲染视图内的内容

createVirtualizer 告诉你要渲染哪些行,以及把它们放在哪里。先提供行数和以像素为单位的估算高度:

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

const virtual = createVirtualizer({
  count: () => entries.length,
  estimate: () => 32,
})

滚动容器挂载后,连接它并订阅变更:

const disconnect = virtual.connect(scroller)
const unsubscribe = virtual.subscribe(render)

在一个相对定位、高度为 virtual.size() 像素的盒子里渲染 virtual.items()。每个条目给出它的 index、key、start 和 size。把它的元素绝对定位到 start,让占满高度的盒子提供滚动条。

import * as React from "react"
import {
  createVirtualizer,
  css,
  definePrimitive,
  type VirtualItem,
} from "@ui-sdk/core"
import {
  createParts,
  mergeProps,
  renderElement,
  usePart,
  usePrimitive,
  type PartProps,
} from "@ui-sdk/react/primitive"

type LedgerOptions = {
  count: number
}

type LedgerRootState = {
  items: VirtualItem[]
}

type LedgerRowProps = { value: string; index: number; start: number }

const rowHeight = 32

const ledger = definePrimitive({
  name: "ledger",
  options: { count: "number" },
  state: (options: LedgerOptions) => ({ count: options.count }),
  sync: (options) => ({ count: options.count }),
  api: (context) => {
    const virtual = createVirtualizer({
      count: () => context.store.get().count,
      estimate: () => rowHeight,
    })
    context.onDestroy(context.store.subscribe(() => virtual.refresh()))
    return { virtual }
  },
  slots: (slot) => ({
    root: slot({
      attrs: () => ({ tabindex: "0", style: css({ overflow: "auto" }) }),
      bind: (el, { api }) => api.virtual.connect(el),
    }),
    body: slot({
      attrs: (state) => ({
        role: "list",
        style: css({
          position: "relative",
          height: `${state.count * rowHeight}px`,
        }),
      }),
    }),
    row: slot<LedgerRowProps>({
      props: { value: "string", index: "number", start: "number" },
      attrs: (state, { props }) => ({
        role: "listitem",
        "aria-setsize": String(state.count),
        "aria-posinset": String(props.index + 1),
        style: css({
          position: "absolute",
          top: "0",
          left: "0",
          right: "0",
          height: `${rowHeight}px`,
          transform: `translateY(${props.start}px)`,
        }),
      }),
    }),
  }),
})

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

function Ledger({
  count,
  className,
  style,
  children,
  render,
  ...props
}: LedgerOptions & PartProps<"div", LedgerRootState>) {
  const handle = usePrimitive(ledger, { count })
  const { virtual } = handle.api
  const items = React.useSyncExternalStore(
    virtual.subscribe,
    virtual.items,
    virtual.items
  )
  const own = { className, style, children }
  return usePart(
    handle,
    "root",
    {},
    {
      ...props,
      render: (merged) =>
        renderElement("div", mergeProps(own, merged), render, { items }),
    }
  )
}

const LedgerBody = parts.Body

function LedgerRow({
  item,
  ...props
}: { item: VirtualItem } & PartProps<"div">) {
  return usePart(
    ledger,
    "row",
    { value: item.key, index: item.index, start: item.start },
    props,
    "div"
  )
}

const money = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
})
const amount = (index: number) => ((index * 7919) % 100000) / 100

function Example() {
  return (
    <Ledger count={10000}>
      {({ items }) => (
        <>
          <LedgerBody aria-label="Ledger">
            {items.map((item) => (
              <LedgerRow key={item.key} item={item}>
                <span data-slot="hint">Entry {item.index + 1}</span>
                <span>{money.format(amount(item.index))}</span>
              </LedgerRow>
            ))}
          </LedgerBody>
          <p data-rendered={items.length} data-slot="output">
            {items.length} of 10,000 rows in the page
          </p>
        </>
      )}
    </Ledger>
  )
}

export {
  Example,
  ledger,
  Ledger,
  LedgerBody,
  LedgerRow,
  type LedgerOptions,
  type LedgerRootState,
  type LedgerRowProps,
}
滚动浏览账目。计数显示了它的 10,000 行中一次只渲染了多少行。

视图卸载时调用 disconnect() 和 unsubscribe()。在原语里,从滚动容器槽位的 bind 返回 virtual.connect(el)。行数或顺序变化后,调用 virtual.refresh()。

items() 在内容变化之前返回同一个数组,所以它能配合 React 的 useSyncExternalStore 这类订阅。给每一行设置 aria-setsize 和 aria-posinset,或者在网格里使用 aria-rowcount 和 aria-rowindex,让辅助技术知道它位于完整列表的哪里。

任意高度的行

对于会换行的行,先估算它们的高度,渲染之后再测量。给每一行一个稳定的数据键,这样排序时测量出的尺寸会跟着它走:

const virtual = createVirtualizer({
  count: () => notes.length,
  key: (index) => notes[index].id,
  estimate: () => 52,
  overscan: 2,
})

在行槽位里,返回测量的清理函数:

bind: (el, { api, props }) => api.virtual.measure(props.index, el),

measure 还会观察之后的尺寸变化。让每个测量绑定与它的索引保持关联;这个演示用索引给渲染的行设键,而虚拟化器按数据键跟踪尺寸。

import * as React from "react"
import {
  createVirtualizer,
  css,
  definePrimitive,
  type VirtualItem,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type Note = { id: string; text: string }

type NotesState = {
  notes: Note[]
  newest: boolean
  large: boolean
  items: VirtualItem[]
  size: number
}

const sentences = [
  "Moved the launch review to Thursday.",
  "Hollis wants the pricing page copy by Friday.",
  "Inès shared the onboarding survey; week-two retention is up.",
  "Kofi is pairing on the billing migration.",
  "Wren flagged two broken links in the help center.",
  "Tomasz will draft the release notes.",
  "Ship the dark mode fixes before the freeze.",
]
const notes: Note[] = Array.from({ length: 500 }, (_, index) => ({
  id: `note-${index + 1}`,
  text: `${index + 1}. ${Array.from({ length: 1 + ((index * 5) % 4) }, (_, k) => sentences[(index + k) % sentences.length]).join(" ")}`,
}))

const notebook = definePrimitive({
  name: "notebook",
  state: (): NotesState => ({
    notes,
    newest: false,
    large: false,
    items: [],
    size: 0,
  }),
  api: (context) => {
    const { store } = context
    let order = notes
    const virtual = createVirtualizer({
      count: () => order.length,
      estimate: () => 52,
      key: (index) => order[index].id,
      overscan: 2,
    })
    const sync = () =>
      store.set({ items: virtual.items(), size: virtual.size() })
    context.onDestroy(virtual.subscribe(sync))
    return {
      virtual,
      note: (index: number) => order[index],
      flip() {
        const newest = !store.get().newest
        order = newest ? [...notes].reverse() : notes
        store.set({ newest })
        virtual.refresh()
      },
      enlarge() {
        store.set({ large: !store.get().large })
        virtual.reset()
      },
    }
  },
  slots: (slot) => ({
    root: slot<{}, { items: VirtualItem[]; newest: boolean; large: boolean }>({
      state: (state) => ({
        items: state.items,
        newest: state.newest,
        large: state.large,
      }),
    }),
    scroller: slot({
      attrs: () => ({ tabindex: "0", style: css({ overflow: "auto" }) }),
      bind: (el, { api }) => api.virtual.connect(el),
    }),
    body: slot({
      attrs: (state) => ({
        role: "list",
        "data-size": String(state.size),
        style: css({ position: "relative", height: `${state.size}px` }),
      }),
    }),
    row: slot<
      { value: string; index: number; start: number },
      { text: string }
    >({
      props: { value: "string", index: "number", start: "number" },
      state: (_state, { api, props }) => ({
        text: api.note(props.index)?.text ?? "",
      }),
      attrs: (state, { props }) => ({
        role: "listitem",
        "aria-setsize": String(state.notes.length),
        "aria-posinset": String(props.index + 1),
        style: css({
          position: "absolute",
          top: "0",
          left: "0",
          right: "0",
          transform: `translateY(${props.start}px)`,
        }),
      }),
      bind: (el, { api, props }) => api.virtual.measure(props.index, el),
    }),
    action: slot<{ value: string }>({
      props: { value: "string" },
      attrs: () => ({ type: "button" }),
      press: ({ api, key }) => (key === "flip" ? api.flip() : api.enlarge()),
    }),
  }),
})

const parts = createParts(notebook, {
  root: "div",
  scroller: "div",
  body: "div",
  row: "div",
  action: "button",
})

const Notebook = parts.Root

const NotebookScroller = parts.Scroller

const NotebookBody = parts.Body

const NotebookRow = parts.Row

const NotebookAction = parts.Action

function Example() {
  return (
    <Notebook>
      {({ items, newest, large }) => (
        <div data-slot="stack">
          <div data-slot="controls">
            <NotebookAction data-size="sm" value="flip">
              {newest ? "Oldest First" : "Newest First"}
            </NotebookAction>
            <NotebookAction data-size="sm" value="enlarge">
              {large ? "Smaller Text" : "Larger Text"}
            </NotebookAction>
          </div>
          <NotebookScroller>
            <NotebookBody
              aria-label="Notes"
              data-large={large ? "" : undefined}
            >
              {items.map((item) => (
                <NotebookRow
                  key={item.index}
                  value={item.key}
                  index={item.index}
                  start={item.start}
                >
                  {({ text }) => text}
                </NotebookRow>
              ))}
            </NotebookBody>
          </NotebookScroller>
        </div>
      )}
    </Notebook>
  )
}

export {
  Example,
  notebook,
  Notebook,
  NotebookAction,
  NotebookBody,
  NotebookRow,
  NotebookScroller,
  type Note,
  type NotesState,
}
滚动浏览笔记,然后试试 Newest First 和 Larger Text。行的位置会按测量出的高度调整。

在影响每一行的变更之后,比如更改文字大小,调用 virtual.reset() 丢弃缓存的测量值。overscan 会在每一端之外多保留几行;默认是四行。固定高度的行可以跳过测量。

跳转与加载更多

用 scrollToIndex 把某一行带入视图。索引从零开始:

virtual.scrollToIndex(49, { align: "center" })
virtual.scrollToIndex(79)

align 可以是 "start"、"center"、"end" 或 "auto"。默认值 "auto" 只滚动到刚好能显示该行。

import * as React from "react"
import {
  createVirtualizer,
  css,
  definePrimitive,
  type VirtualItem,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type ContactsState = {
  count: number
  focused: number | null
  items: VirtualItem[]
  size: number
}

const rowHeight = 32
const headerHeight = 32

const contacts = definePrimitive({
  name: "contacts",
  state: (): ContactsState => ({
    count: 100,
    focused: null,
    items: [],
    size: 0,
  }),
  api: (context) => {
    const { store } = context
    const virtual = createVirtualizer({
      count: () => store.get().count,
      estimate: () => rowHeight,
      scrollMargin: headerHeight,
      keep: () => {
        const { focused } = store.get()
        return focused === null ? [] : [focused]
      },
      onEnd: () => {
        const { count } = store.get()
        if (count < 300) {
          store.set({ count: count + 100 })
          virtual.refresh()
        }
      },
      endThreshold: 5,
    })
    context.onDestroy(
      virtual.subscribe(() =>
        store.set({ items: virtual.items(), size: virtual.size() })
      )
    )
    return {
      virtual,
      focus: (index: number) => store.set({ focused: index }),
      act(action: string) {
        const { count } = store.get()
        if (action === "first") {
          virtual.scrollToIndex(0, { align: "start" })
        } else if (action === "middle") {
          virtual.scrollToIndex(49, { align: "center" })
        } else if (action === "last") {
          virtual.scrollToIndex(count - 1, { align: "end" })
        } else if (action === "eighty") {
          virtual.scrollToIndex(79)
        }
      },
    }
  },
  slots: (slot) => ({
    root: slot<{}, { items: VirtualItem[]; count: number }>({
      state: (state) => ({ items: state.items, count: state.count }),
    }),
    scroller: slot({
      attrs: () => ({ style: css({ overflow: "auto" }) }),
      bind: (el, { api }) => api.virtual.connect(el),
    }),
    body: slot({
      attrs: (state) => ({
        role: "list",
        style: css({ position: "relative", height: `${state.size}px` }),
      }),
    }),
    row: slot<{ value: string; index: number; start: number }>({
      props: { value: "string", index: "number", start: "number" },
      attrs: (state, { props }) => ({
        role: "listitem",
        tabindex: "-1",
        "aria-setsize": String(state.count),
        "aria-posinset": String(props.index + 1),
        style: css({
          position: "absolute",
          top: "0",
          left: "0",
          right: "0",
          height: `${rowHeight}px`,
          transform: `translateY(${props.start}px)`,
        }),
      }),
      on: { focus: (_event, { api, props }) => api.focus(props.index) },
    }),
    action: slot<{ value: string }>({
      props: { value: "string" },
      attrs: () => ({ type: "button" }),
      press: ({ api, key }) => api.act(key),
    }),
  }),
})

const parts = createParts(contacts, {
  root: "div",
  scroller: "div",
  body: "div",
  row: "div",
  action: "button",
})

const Contacts = parts.Root

const ContactsScroller = parts.Scroller

const ContactsBody = parts.Body

const ContactsRow = parts.Row

const ContactsAction = parts.Action

const names = ["Hollis", "Inès", "Kofi", "Wren", "Tomasz"]

function Example() {
  return (
    <Contacts>
      {({ items, count }) => (
        <div data-slot="stack">
          <div data-slot="controls">
            {[
              ["first", "First"],
              ["middle", "Center 50"],
              ["eighty", "Show 80"],
              ["last", "Last"],
            ].map(([value, text]) => (
              <ContactsAction data-size="sm" key={value} value={value}>
                {text}
              </ContactsAction>
            ))}
          </div>
          <ContactsScroller>
            <div data-slot="virtualizer-header">{count} contacts</div>
            <ContactsBody aria-label="Contacts">
              {items.map((item) => (
                <ContactsRow
                  key={item.key}
                  value={item.key}
                  index={item.index}
                  start={item.start}
                >
                  {names[item.index % names.length]} {item.index + 1}
                </ContactsRow>
              ))}
            </ContactsBody>
          </ContactsScroller>
        </div>
      )}
    </Contacts>
  )
}

export {
  Contacts,
  contacts,
  ContactsAction,
  ContactsBody,
  ContactsRow,
  ContactsScroller,
  type ContactsState,
  Example,
}
试试 Center 50 和 Last。接近末尾时会加载更多联系人。点击一个联系人然后滚开;它聚焦的元素会保持渲染。

对于吸顶的表头,把 scrollMargin 设成它的高度。要加载更多,提供 onEnd,并可选地提供 endThreshold:

scrollMargin: 32,
onEnd: () => loadMore(),
endThreshold: 5,
keep: () => (focusedIndex === null ? [] : [focusedIndex]),

当可见范围接近末尾时,onEnd 在每个行数下运行一次。加载之后,更新行数并调用 refresh()。keep() 添加必须保持渲染的索引,比如持有焦点的那一行。

横向

对于横向列表,设置 horizontal: true:

const virtual = createVirtualizer({
  count: () => 365,
  estimate: () => 56,
  horizontal: true,
})

现在 start 和 size 描述横向位置。用一个宽度为 virtual.size() 像素的占位元素,并用 translateX 定位条目。

import * as React from "react"
import {
  createVirtualizer,
  css,
  definePrimitive,
  type VirtualItem,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type StripState = { items: VirtualItem[]; size: number }

const dayWidth = 56

const strip = definePrimitive({
  name: "strip",
  state: (): StripState => ({ items: [], size: 0 }),
  api: (context) => {
    const virtual = createVirtualizer({
      count: () => 365,
      estimate: () => dayWidth,
      horizontal: true,
    })
    context.onDestroy(
      virtual.subscribe(() =>
        context.store.set({ items: virtual.items(), size: virtual.size() })
      )
    )
    return { virtual }
  },
  slots: (slot) => ({
    root: slot<{}, { items: VirtualItem[] }>({
      state: (state) => ({ items: state.items }),
      attrs: () => ({ tabindex: "0", style: css({ overflow: "auto" }) }),
      bind: (el, { api }) => api.virtual.connect(el),
    }),
    body: slot({
      attrs: (state) => ({
        role: "list",
        style: css({
          position: "relative",
          width: `${state.size}px`,
          height: "100%",
        }),
      }),
    }),
    day: slot<{ value: string; start: number }>({
      props: { value: "string", start: "number" },
      attrs: (_state, { props }) => ({
        role: "listitem",
        style: css({
          position: "absolute",
          top: "0",
          bottom: "0",
          left: "0",
          width: `${dayWidth}px`,
          transform: `translateX(${props.start}px)`,
        }),
      }),
    }),
  }),
})

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

const Strip = parts.Root

const StripBody = parts.Body

const StripDay = parts.Day

const date = new Intl.DateTimeFormat("en-US", {
  month: "short",
  day: "numeric",
  timeZone: "UTC",
})

function Example() {
  return (
    <Strip>
      {({ items }) => (
        <StripBody aria-label="Days">
          {items.map((item) => (
            <StripDay key={item.key} value={item.key} start={item.start}>
              {date.format(Date.UTC(2026, 0, item.index + 1))}
            </StripDay>
          ))}
        </StripBody>
      )}
    </Strip>
  )
}

export { Example, strip, Strip, StripBody, StripDay, type StripState }
横向滚动浏览这些日期。只有可见的日期和附近的几个会被渲染。

在页面中查找

在页面中查找(⌘F 或 Ctrl+F)只能看到虚拟化器已渲染的行。用 findable 把每一行的文本交给它,并通过可查找层连接,这样它能找到每一行,列表也会滚动到匹配的那一行:

const virtual = createVirtualizer({
  count: () => invoices.length,
  estimate: () => 36,
  findable: (index) => [invoices[index].id, invoices[index].customer],
})

virtual.connect(scroller, { findable: true })

让 findable 保持为行所显示的文本,这样无论是否已渲染,行都能以同样的方式被找到。只传值得查找的文本,比如标题而不是时间戳。

然后通过 ref,用 findableText 渲染那段文本,每个片段用一个空元素:

<span ref={(el) => virtual.findableText(item.index, el, 0)} />
<span ref={(el) => virtual.findableText(item.index, el, 1)} />

离开 items() 的行会自己交还它的文本,因此那些不运行 ref 的返回值、而是用 null 调用 ref 的框架,行为也一样。

这个元素承载的正是在页面中查找所搜索的文本,所以浏览器会在行本身、用行自己的样式高亮匹配项,并且只计一次。最后一个参数 part 在 findable 返回多个片段时选择其中一个。

"use client"

import * as React from "react"
import { createVirtualizer } from "@ui-sdk/core"

const customers = [
  "Acme",
  "Globex",
  "Initech",
  "Umbrella",
  "Hooli",
  "Stark",
  "Wayne",
  "Tyrell",
]

const invoices = Array.from({ length: 10_000 }, (_, index) => ({
  id: `INV-${String(index + 1).padStart(5, "0")}`,
  customer: customers[index % customers.length],
}))

const virtual = createVirtualizer({
  count: () => invoices.length,
  estimate: () => 36,
  findable: (index) => [invoices[index].id, invoices[index].customer],
})

function Example() {
  const items = React.useSyncExternalStore(
    virtual.subscribe,
    virtual.items,
    virtual.items
  )
  const scroller = React.useRef<HTMLDivElement>(null)
  React.useEffect(
    () => virtual.connect(scroller.current!, { findable: true }),
    []
  )

  return (
    <div
      ref={scroller}
      role="list"
      aria-label="Invoices"
      data-slot="virtualizer-scroller"
    >
      <div data-slot="virtualizer-body" style={{ height: virtual.size() }}>
        {items.map((item) => (
          <div
            key={item.key}
            ref={(el) => virtual.measure(item.index, el)}
            role="listitem"
            aria-setsize={invoices.length}
            aria-posinset={item.index + 1}
            data-slot="virtualizer-row"
            style={{ transform: `translateY(${item.start}px)` }}
          >
            <span
              ref={(el) => virtual.findableText(item.index, el, 0)}
              data-slot="virtualizer-id"
            />{" "}
            <span
              ref={(el) => virtual.findableText(item.index, el, 1)}
              data-slot="hint"
            />
          </div>
        ))}
      </div>
    </div>
  )
}

export { Example }
按 ⌘F 或 Ctrl+F,搜索 Acme。查找栏会计入每一张 Acme 发票,无论是否已渲染;按 Enter 逐个浏览,列表会滚动到每一个。

它找到的那一行

在页面中查找匹配到的行会在 items() 中标记为 found,直到下一个匹配、直到它滚出视图,或直到有人在列表里按压或输入。不用 findableText 渲染文本的行仍然会滚动到视图中,但浏览器的突出显示无法显示在它上面,所以你自己标记它:

<div data-found={item.found ? "" : undefined} className="data-found:bg-neutral-100">

工作原理

可查找层是两个不占空间的元素,一个在滚动容器的开头,一个在末尾。它们为每一个未渲染的行保存一个替身:一个只包含该行文本的元素,hidden="until-found",在页面中查找可以搜索它,而它不会被渲染出来。

  1. 顺序: 在页面中查找按页面顺序遍历匹配项,所以视图内行上方的那些行的替身放在第一层,其余放在最后一层。已渲染的行在页面中没有替身,所以它们的文本只在显示的位置被找到一次。
  2. 匹配项 会在浏览器滚动到它之前触发替身的 beforematch。列表先滚动到该行并渲染它,替身则平铺在该行上方,所以浏览器自己的滚动无事可做。
  3. 在下一帧, 匹配的文本会移入该行的 findableText 元素,于是浏览器的突出显示出现在那里,查找栏的 Enter 继续处理它之后的行。没有这些元素的行则改用那个透明的替身,查找栏会把它计两次,直到它滚出视图。
  4. 替身分组 同样带有 hidden="until-found",所以浏览器会跳过它们全部的样式和布局,直到其中一个匹配。

每一行要花费一个替身,以及每个片段一个文本节点,片段之间还有一个空格:单个字符串是两个 DOM 节点,两个片段则是四个。它们几乎不产生布局开销,因为浏览器只布局这些分组。行发生变化后调用 virtual.refresh():它只就地更新变化了的文本,并且只在数量变化时重建替身。

替身的代码在列表第一次带 findable 连接时加载,所以没有它的列表不会下载这段代码。

不支持 hidden="until-found" 的浏览器不会得到这些层,在页面中查找只能看到屏幕上的行,就像没有 findable 一样;supportsHiddenUntilFound() 会告诉你。关闭的标签页、手风琴、可折叠区域、树和导航菜单也用同样的方式变得可查找,通过它们的 hiddenUntilFound 选项或 findableText;关闭面板里的列表会先打开该面板。

选项

count() => number
How many rows the list has. Read on every update, so it can grow, like a list that loads more.
示例: Render What's in View
estimate(index: number) => number
The size of a row before it's measured, in pixels. A close guess keeps the scrollbar steady.
示例: Render What's in View
key?((index: number) => string)
A stable key for each row, so a measured size follows its row when the list sorts or filters. Defaults to the index.
示例: Rows of Any Height
overscan?number
How many rows to render past each edge, so a fast scroll or Tab doesn't show a gap.
示例: Rows of Any Height
horizontal?boolean
Whether the list scrolls sideways.
示例: Sideways
scrollMargin?number
Pixels in the scroller before the first row, like a sticky header.
示例: Jumping and Loading More
keep?(() => readonly number[])
Rows rendered wherever the scroller is, like the one with focus, so scrolling it away doesn't drop focus to the page.
示例: Jumping and Loading More
onEnd?(() => void)
Runs when the rendered rows come within endThreshold rows of the last, to load more. Runs once per count, so it doesn't ask again before the list grows.
示例: Jumping and Loading More
endThreshold?number
How close to the end onEnd runs, in rows.
示例: Jumping and Loading More
findable?((index: number) => string | readonly string[])
The text the browser's find in page should find in a row, like its title, so it finds rows that aren't rendered too. Keep it what the row shows. Return a list of pieces to give each its own findableText.
示例: Find in Page

跟随末尾的日志

跟随最新一行

createStickToBottom 在读者位于底部时跟随新内容。向上滚动可以让他们阅读而不被拉走:

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

const stick = createStickToBottom()
const disconnect = stick.connect(scroller)

这个辅助函数观察内容尺寸的变化,包括一次只到达一个词的文本。卸载时调用 disconnect(),或者从槽位的 bind 返回 stick.connect(el)。

import * as React from "react"
import {
  createStickToBottom,
  css,
  definePrimitive,
  type StickToBottomState,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type BuildLogJumpState = {
  away: boolean
  unseen: boolean
}

const buildLog = definePrimitive({
  name: "build-log",
  state: (): StickToBottomState => ({
    following: true,
    unseen: false,
    atBottom: true,
  }),
  api: (context) => {
    const stick = createStickToBottom({
      onChange: (state) => context.store.set(state),
    })
    return { stick }
  },
  slots: (slot) => ({
    root: slot({}),
    log: slot({
      attrs: () => ({
        role: "log",
        tabindex: "0",
        style: css({ overflow: "auto" }),
      }),
      bind: (el, { api }) => api.stick.connect(el),
    }),
    jump: slot<{}, BuildLogJumpState>({
      state: (state) => ({
        away: !state.following && !state.atBottom,
        unseen: state.unseen,
      }),
      attrs: (state) => ({
        type: "button",
        hidden: !state.following && !state.atBottom ? undefined : "",
        "data-unseen": state.unseen ? "" : undefined,
      }),
      press: ({ api }) => api.stick.scrollToBottom({ behavior: "smooth" }),
    }),
  }),
})

const parts = createParts(buildLog, { root: "div", log: "div", jump: "button" })

const BuildLog = parts.Root

const BuildLogLines = parts.Log

const BuildLogJump = parts.Jump

const steps = [
  "Resolving packages",
  "Compiling",
  "Bundling",
  "Checking types",
  "Running tests",
]

function Example() {
  const [lines, setLines] = React.useState<string[]>([])
  React.useEffect(() => {
    const timer = setInterval(() => {
      setLines((current) => {
        if (current.length >= 80) {
          clearInterval(timer)
          return [...current, "Done in 24s."]
        }
        return [
          ...current,
          `${steps[current.length % steps.length]} (${current.length + 1}/80)`,
        ]
      })
    }, 250)
    return () => clearInterval(timer)
  }, [])
  return (
    <BuildLog>
      <BuildLogLines aria-label="Build output">
        {lines.map((line, index) => (
          <div key={index}>{line}</div>
        ))}
      </BuildLogLines>
      <BuildLogJump data-size="sm">Jump to latest</BuildLogJump>
    </BuildLog>
  )
}

export {
  buildLog,
  BuildLog,
  BuildLogJump,
  BuildLogLines,
  Example,
  type BuildLogJumpState,
}
新行不断到达时,向上滚动可以暂停跟随。Jump to latest 会带你回到末尾。

用 stick.get() 读取日志是否正在 following、当前是否 atBottom,或者下方是否有 unseen 内容。stick.subscribe(listener) 上报变更并返回一个清理函数。这些值可以驱动一个跳转按钮:

stick.scrollToBottom({ behavior: "smooth" })

当新条目需要由屏幕阅读器播报时,给内容设置 role="log"。

较早的消息与放手

要让对话打开时停在当前位置而不是跳到末尾,使用 initial: false:

const stick = createStickToBottom({ initial: false, threshold: 48 })

threshold 是以像素为单位的距离,在这个范围内仍算位于底部。加在当前消息上方的较早消息会自行保持读者的位置,不需要调用任何东西。

控制台
import * as React from "react"
import {
  createStickToBottom,
  css,
  definePrimitive,
  type StickToBottomState,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"
import { useLog } from "./log"

type ThreadOptions = { onStickChange?: (state: StickToBottomState) => void }

type ThreadState = StickToBottomState & { messages: string[]; older: number }

const thread = definePrimitive({
  name: "thread",
  options: { onStickChange: "callback" },
  state: (_options: ThreadOptions): ThreadState => ({
    messages: Array.from({ length: 12 }, (_, index) => `Message ${index + 1}`),
    older: 0,
    following: false,
    atBottom: false,
    unseen: false,
  }),
  api: (context) => {
    const { store } = context
    const stick = createStickToBottom({ initial: false, threshold: 48 })
    context.onDestroy(
      stick.subscribe(() => {
        store.set(stick.get())
        context.options().onStickChange?.(stick.get())
      })
    )
    return {
      stick,
      act(action: string) {
        const { messages, older } = store.get()
        if (action === "send") {
          store.set({
            messages: [...messages, `Message ${messages.length + 1 - older}`],
          })
        } else if (action === "older") {
          store.set({
            older: older + 5,
            messages: [
              ...Array.from(
                { length: 5 },
                (_, index) => `Older ${older + 5 - index}`
              ),
              ...messages,
            ],
          })
        } else if (action === "release") {
          stick.release()
        }
      },
    }
  },
  slots: (slot) => ({
    root: slot<{}, { messages: string[] }>({
      state: (state) => ({ messages: state.messages }),
    }),
    log: slot({
      attrs: () => ({
        role: "log",
        tabindex: "0",
        style: css({ overflow: "auto" }),
      }),
      bind: (el, { api }) => api.stick.connect(el),
    }),
    action: slot<{ value: string }>({
      props: { value: "string" },
      attrs: () => ({ type: "button" }),
      press: ({ api, key }) => api.act(key),
    }),
  }),
})

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

const Thread = parts.Root

const ThreadLog = parts.Log

const ThreadAction = parts.Action

function Example() {
  const log = useLog()
  const last = React.useRef("")
  const report = ({ following, atBottom, unseen }: StickToBottomState) => {
    const text = `${following ? "Following" : "Not following"}${atBottom ? ", at the end" : ""}${unseen ? ", new below" : ""}`
    if (text !== last.current) {
      log(text)
    }
    last.current = text
  }
  return (
    <Thread onStickChange={report}>
      {({ messages }) => (
        <div data-slot="stack">
          <div data-slot="controls">
            {[
              ["send", "Send"],
              ["older", "Load Older"],
              ["release", "Let Go"],
            ].map(([value, text]) => (
              <ThreadAction data-size="sm" key={value} value={value}>
                {text}
              </ThreadAction>
            ))}
          </div>
          <ThreadLog aria-label="Thread">
            {messages.map((message) => (
              <div key={message} data-slot="stick-message">
                {message}
              </div>
            ))}
          </ThreadLog>
        </div>
      )}
    </Thread>
  )
}

export {
  Example,
  thread,
  Thread,
  ThreadAction,
  ThreadLog,
  type ThreadOptions,
  type ThreadState,
}
滚动到末尾并点击 Send。Load Older 会在上方添加消息而不移动你的视图。Let Go 会停止跟随新消息。控制台会记录会话是否正在跟随。

stick.release() 从代码里停止跟随。滚回末尾或调用 scrollToBottom() 会恢复跟随。连接期间,这个辅助函数会管理滚动锚定,这样浏览器不会再做第二次调整。

选项

threshold?number
How close to the end, in pixels, still counts as at the bottom.
示例: Older Messages and Letting Go
initial?boolean
Whether it follows from the start.
示例: Older Messages and Letting Go
onChange?((state: StickToBottomState) => void)
Runs when get() changes.
示例: Follow the Newest Line

滚动选取的转轮

滚动选取

从 @ui-sdk/core 导入 bindScrollPicker。它把可滚动的列表框变成一个转轮,就像时间选择器的小时和分钟滚轮:位于中心的选项就是值。列表进入页面后,把它绑定到一个 Listbox,并选择它上报的选项。它返回一个清理函数,供列表离开时使用:

const list = React.useRef<HTMLDivElement>(null)
const select = React.useEffectEvent((index: number) => setHour(hours[index]))

React.useLayoutEffect(
  () => bindScrollPicker(list.current!, { onSelect: (index) => select(index) }),
  []
)

<Listbox ref={list} keepInView={false} value={hour} onValueChange={setHour}>

index 计入列表里的每个选项,包括禁用的选项,所以它与你的数组对应。选择器自己不选任何东西,所以 onSelect 才是只读表单或你自己的检查做决定的地方。

列表仍然是一个单选的列表框。滚动、触摸屏上的轻扫以及鼠标拖动,会在选项经过中心时选择它;列表停止后会停在最近的已启用选项上。当列表框自己选中一个选项时,比如通过点击、方向键、Home、End 或输入选项名称,选择器会平滑地滚动到那里,而不选择中间的选项。Page Up 和 Page Down 会移动一屏的选项。

把列表框的 keepInView 选项设为 false,这样它不会跳到一个转轮即将滑过去的选项。给列表一个高度、scroll-snap-type,并在两端留出空间,让第一个和最后一个选项也能到达中心;再给每个选项设置 scroll-snap-align: center:

[role="listbox"] {
  height: 180px;
  padding-block: 72px;
  overflow-y: auto;
  scroll-snap-type: y mandatory;
}

[role="option"] {
  height: 36px;
  scroll-snap-align: center;
}

吸附由浏览器自己完成,所以列表在你的 JavaScript 加载之前就会吸附。选项可以是任意尺寸:选择器会测量它们,并在它们或列表尺寸变化时重新测量。

用 CSS 绘制转轮

每个选项都会得到 --picker-offset,即它到中心的距离,以选项为单位:中心是 0,下一个选项是 1,往前两个是 -2。当列表在选项之间移动时,它是小数,并且每帧更新,所以 CSS 可以不用你自己的代码就画出转轮:

[role="option"] {
  transform: rotateX(calc(var(--picker-offset, 0) * -24deg));
  opacity: calc(1 - abs(var(--picker-offset, 0)) * 0.25);
}

0 这个回退值覆盖选择器绑定之前的服务端 HTML。给列表设置 perspective,让旋转看起来是圆形的,并用 mask-image 让两端淡出:

控制台
import * as React from "react"
import { bindScrollPicker } from "@ui-sdk/core"
import { Listbox, ListboxItem } from "@ui-sdk/react/listbox"
import { useLog } from "./log"

const hours = Array.from({ length: 12 }, (_, index) => String(index + 1))

const minutes = Array.from({ length: 12 }, (_, index) =>
  String(index * 5).padStart(2, "0")
)

function Wheel({
  label,
  options,
  value,
  onValueChange,
}: {
  label: string
  options: string[]
  value: string
  onValueChange: (value: string) => void
}) {
  const list = React.useRef<HTMLDivElement>(null)
  const select = React.useEffectEvent((index: number) =>
    onValueChange(options[index])
  )

  React.useLayoutEffect(
    () =>
      bindScrollPicker(list.current!, { onSelect: (index) => select(index) }),
    []
  )

  return (
    <div data-slot="wheel">
      <Listbox
        ref={list}
        aria-label={label}
        keepInView={false}
        value={value}
        onValueChange={(next) => next && onValueChange(next)}
      >
        {options.map((option) => (
          <ListboxItem key={option} value={option}>
            {option}
          </ListboxItem>
        ))}
      </Listbox>
    </div>
  )
}

function Example() {
  const log = useLog()
  const [hour, setHour] = React.useState("9")
  const [minute, setMinute] = React.useState("30")
  return (
    <div data-slot="wheels">
      <Wheel
        label="Hour"
        options={hours}
        value={hour}
        onValueChange={(next) => {
          setHour(next)
          log(`${next}:${minute}`)
        }}
      />
      <Wheel
        label="Minute"
        options={minutes}
        value={minute}
        onValueChange={(next) => {
          setMinute(next)
          log(`${hour}:${next}`)
        }}
      />
    </div>
  )
}

export { Example }
滚动或拖动转轮,或在触摸屏上轻扫。点击一个小时,或聚焦一个转轮并使用 Up、Down、Home 和 End。控制台会记录时间。

在减少动态效果的情况下,转轮会直接跳到选项,而不是滑过去。

横向

对于横向的转轮,比如一条页码横带,把列表框的 orientation 设为 "horizontal"。选择器从 aria-orientation 读取它,所以会横向滚动和测量;在从右到左的文本中,这条横带从右侧开始:

控制台
import * as React from "react"
import { bindScrollPicker } from "@ui-sdk/core"
import { Listbox, ListboxItem } from "@ui-sdk/react/listbox"
import { useLog } from "./log"

const pages = Array.from({ length: 40 }, (_, index) => String(index + 1))

function Example() {
  const log = useLog()
  const list = React.useRef<HTMLDivElement>(null)
  const [page, setPage] = React.useState("1")
  const choose = (next: string) => {
    setPage(next)
    log(`Page ${next}`)
  }
  const select = React.useEffectEvent((index: number) => choose(pages[index]))

  React.useLayoutEffect(
    () =>
      bindScrollPicker(list.current!, { onSelect: (index) => select(index) }),
    []
  )

  return (
    <div data-slot="thumbwheel">
      <Listbox
        ref={list}
        aria-label="Page"
        orientation="horizontal"
        keepInView={false}
        value={page}
        onValueChange={(next) => next && choose(next)}
      >
        {pages.map((option) => (
          <ListboxItem key={option} value={option}>
            {option}
          </ListboxItem>
        ))}
      </Listbox>
    </div>
  )
}

export { Example }
滚动或拖动这条横带,或聚焦它并使用 Left 和 Right。中间的页码就是当前页,控制台会记录它。

选项

orientation?"horizontal" | "vertical"
Which way the list scrolls. A horizontal list runs from the right in right-to-left text.
示例: Sideways
onSelect?((index: number, details: ScrollPickerSelectDetails) => void)
Runs when someone's scroll, drag, or Page Up or Page Down brings another enabled option to the center, with its index among all the options. Select it here. Clicks and arrow keys select through the list itself.
示例: Pick by Scrolling

就地编辑

在显示的位置重命名

createInlineEdit 管理编辑会话。你的状态保存条目的 id,没有任何内容在编辑时为 null。你的 commit 回调保存新文本:

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

const edit = createInlineEdit(context, {
  key: "editing",
  value: (id) => nameOf(id),
  commit: (id, text, details) => {
    if (!text.trim()) {
      return false
    }
    return rename(id, text, details)
  },
})

返回 false 会让编辑器保持打开。文本没有变化时,结束编辑而不调用 commit。

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

type Playlist = { id: string; name: string }

type PlaylistsState = {
  items: Playlist[]
  editing: string | null
  focused: string | null
}

type PlaylistsOptions = {
  defaultItems: Playlist[]
  onItemsChange?: (
    items: Playlist[],
    details: ChangeDetails<InlineEditReason>
  ) => void
}

type PlaylistsItemState = { name: string; editing: boolean }

const playlists = definePrimitive({
  name: "playlists",
  options: { defaultItems: "value", onItemsChange: "callback" },
  state: (options: PlaylistsOptions): PlaylistsState => ({
    items: options.defaultItems,
    editing: null,
    focused: null,
  }),
  api: (context) => {
    const { store } = context
    const change = createChange(context)
    const roving = createRovingFocus<PlaylistsState, { value: string }>(
      context,
      {
        slot: "item",
        key: "focused",
      }
    )
    const edit = createInlineEdit<PlaylistsState>(context, {
      key: "editing",
      value: (id) =>
        store.get().items.find((item) => item.id === id)?.name ?? "",
      commit: (id, text, details) =>
        !!text.trim() &&
        change(
          "items",
          store
            .get()
            .items.map((item) =>
              item.id === id ? { ...item, name: text.trim() } : item
            ),
          details
        ),
    })
    return { roving, edit }
  },
  slots: (slot) => ({
    root: slot({ attrs: () => ({ role: "list" }) }),
    item: slot<{ value: string }, PlaylistsItemState>({
      props: { value: "string" },
      selects: selects({ focused: ({ key }) => [key, null] }),
      state: (state, { key }) => ({
        name: state.items.find((item) => item.id === key)?.name ?? "",
        editing: state.editing === key,
      }),
      attrs: (state, part) => ({
        role: "listitem",
        tabindex: part.api.roving.tabIndex(state, part),
      }),
      on: {
        keydown: (event, { el, api, key }) => {
          if (event.target !== el || api.edit.keydown(event, key)) {
            return
          }
          api.roving.keydown(event, el!)
        },
        dblclick: (event, { api, key }) => api.edit.dblclick(event, key),
      },
      bind: (el, part) => part.api.roving.bind(el, part),
    }),
    input: slot({
      attrs: () => ({ "aria-label": "Playlist name" }),
      on: {
        keydown: (event, { api }) => api.edit.inputKeydown(event),
        focusout: (event, { api }) => api.edit.end("focus-out", event),
      },
      bind: (el, { api }) => api.edit.bindInput(el as HTMLInputElement),
    }),
  }),
})

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

const Playlists = parts.Root

const PlaylistsItem = parts.Item

const PlaylistsInput = parts.Input

const mixes = [
  { id: "a", name: "Morning run" },
  { id: "b", name: "Deep focus" },
  { id: "c", name: "Road trip" },
  { id: "d", name: "Rainy Sunday" },
]

function Example() {
  return (
    <Playlists aria-label="Playlists" defaultItems={mixes}>
      {mixes.map((mix) => (
        <PlaylistsItem key={mix.id} value={mix.id}>
          {({ name, editing }) => (editing ? <PlaylistsInput /> : name)}
        </PlaylistsItem>
      ))}
    </Playlists>
  )
}

export {
  Example,
  playlists,
  Playlists,
  PlaylistsInput,
  PlaylistsItem,
  type Playlist,
  type PlaylistsItemState,
  type PlaylistsOptions,
  type PlaylistsState,
}
聚焦一个播放列表,按 Enter 或 F2,或双击它。Enter 保存名称;Escape 取消。输入一个字母会开始替换。

在条目上,把 keydown 传给 edit.keydown(event, key),把 dblclick 传给 edit.dblclick(event, key)。为 edit.editing(state) 返回的 id 渲染一个输入框,然后连接它:

input: slot({
  on: {
    keydown: (event, { api }) => api.edit.inputKeydown(event),
    focusout: (event, { api }) => api.edit.end("focus-out", event),
  },
  bind: (el, { api }) => api.edit.bindInput(el as HTMLInputElement),
}),

bindInput 填充并聚焦输入框。Enter 保存;Escape 取消。焦点离开时,focusout 处理函数会保存。编辑结束后,如果移除输入框会让焦点丢失,这个辅助函数会恢复焦点。

继续前进与从代码开始

Tab 也会保存,但焦点下一步去哪里由你的组件决定。inputKeydown 成功处理按键时返回 true:

if (event.key === "Tab" && edit.inputKeydown(event)) {
  nextField.focus()
}

把校验放在 commit 里。对于不能编辑的值,使用 disabled(id);用 edit.start(id) 从单独的按钮或菜单开始编辑。如果编辑结束时那个按钮或菜单已经不在了,焦点会改为转移到输入框周围最近的可聚焦元素,比如它所在的行。

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

type Product = { name: string; price: string; sku: string }

type ProductState = { product: Product; editing: string | null }

const order = ["name", "price", "sku"] as const

const product = definePrimitive({
  name: "product",
  state: (): ProductState => ({
    product: { name: "Desk lamp", price: "49", sku: "LMP-204" },
    editing: null,
  }),
  api: (context) => {
    const { store } = context
    const change = createChange(context)
    const fields = new Map<string, HTMLElement>()
    const edit = createInlineEdit<ProductState>(context, {
      key: "editing",
      value: (id) => store.get().product[id as keyof Product],
      commit: (id, text, details) => {
        if (id === "price" && !Number.isFinite(Number(text))) {
          return false
        }
        return change(
          "product",
          { ...store.get().product, [id]: text.trim() },
          details
        )
      },
      disabled: (id) => id === "sku",
    })
    return {
      edit,
      bindField(el: HTMLElement, id: string) {
        fields.set(id, el)
        return () => void fields.delete(id)
      },
      inputKeydown(event: KeyboardEvent) {
        const id = store.get().editing
        if (event.key === "Tab" && id && edit.inputKeydown(event)) {
          const next =
            order[
              order.indexOf(id as (typeof order)[number]) +
                (event.shiftKey ? -1 : 1)
            ]
          if (next) {
            fields.get(next)?.focus()
          }
          return
        }
        edit.inputKeydown(event)
      },
    }
  },
  slots: (slot) => ({
    root: slot({}),
    list: slot({ attrs: () => ({ role: "list" }) }),
    field: slot<{ value: string }, { text: string; editing: boolean }>({
      props: { value: "string" },
      state: (state, { key }) => ({
        text: state.product[key as keyof Product],
        editing: state.editing === key,
      }),
      attrs: (_state, { key }) => ({
        role: "listitem",
        tabindex: "0",
        "aria-readonly": key === "sku" ? "true" : undefined,
      }),
      on: {
        keydown: (event, { el, api, key }) =>
          event.target === el && api.edit.keydown(event, key),
        dblclick: (event, { api, key }) => api.edit.dblclick(event, key),
      },
      bind: (el, { api, key }) => api.bindField(el, key),
    }),
    input: slot({
      attrs: () => ({ "aria-label": "Value" }),
      on: {
        keydown: (event, { api }) => api.inputKeydown(event),
        focusout: (event, { api }) => api.edit.end("focus-out", event),
      },
      bind: (el, { api }) => api.edit.bindInput(el as HTMLInputElement),
    }),
    rename: slot({
      attrs: () => ({ type: "button" }),
      press: ({ api }) => api.edit.start("name"),
    }),
  }),
})

const parts = createParts(product, {
  root: "div",
  list: "div",
  field: "div",
  input: "input",
  rename: "button",
})

const ProductDetails = parts.Root

const ProductList = parts.List

const ProductField = parts.Field

const ProductInput = parts.Input

const ProductRename = parts.Rename

const labels: Record<string, string> = {
  name: "Name",
  price: "Price",
  sku: "SKU",
}

function Example() {
  return (
    <ProductDetails>
      <div data-slot="stack">
        <div data-slot="controls">
          <ProductRename data-size="sm">Rename</ProductRename>
        </div>
        <ProductList aria-label="Product">
          {order.map((id) => (
            <ProductField key={id} value={id} aria-label={labels[id]}>
              {({ text, editing }) => (
                <>
                  <span data-slot="inline-edit-label">{labels[id]}</span>
                  {editing ? (
                    <ProductInput />
                  ) : (
                    <span data-value>{id === "price" ? `$${text}` : text}</span>
                  )}
                </>
              )}
            </ProductField>
          ))}
        </ProductList>
      </div>
    </ProductDetails>
  )
}

export {
  Example,
  product,
  ProductDetails,
  ProductField,
  ProductInput,
  ProductList,
  ProductRename,
  type Product,
  type ProductState,
}
编辑一个产品值,按 Tab 保存并继续。Price 要求数字,SKU 保持只读,Rename 开始编辑名称。

选项

keykeyof State & string
The state key that holds the id being edited, or null.
示例: Rename Where It Shows
value(id: string) => string
The text an id shows now, put in the input when editing starts.
示例: Rename Where It Shows
commit(id: string, text: string, details: { reason: InlineEditReason; event?: Event; }) => boolean
Saves the text and returns whether it went through. Return false to keep editing, like when the text isn't valid.
示例: Rename Where It Shows
disabled?((id: string) => boolean)
Whether an id can't be edited.
示例: Moving on and Starting from Code