为原语设置选项,把状态暴露给它的部件,并处理元素。
definePrimitive 把一个组件的选项、状态、方法和部件整合到一起。用它提供的槽位来暴露属性和状态、处理事件,以及操作已经挂载的元素。
在 构建一个组件 里,你定义了一个静音按钮。本页用一个复制按钮,逐个讲解定义里的每个字段。每个演示的代码标签页里都有完整示例。
下面是本页要构建的复制按钮,写成一份定义。下面的每一节都会更详细地讲解它的一个字段。
import { definePrimitive } from "@ui-sdk/core"
type CopyButtonOptions = { text?: string; onCopy?: (text: string) => void }
const copyButton = definePrimitive({
name: "copy-button",
options: { text: "string", onCopy: "callback" },
state: (options: CopyButtonOptions) => ({ copied: false }),
api: (context) => ({
async copy() {
const { text = "", onCopy } = context.options()
await navigator.clipboard.writeText(text)
context.store.set({ copied: true })
onCopy?.(text)
},
}),
slots: (slot) => ({
root: slot<{}, { copied: boolean }>({
state: (state) => ({ copied: state.copied }),
attrs: () => ({ type: "button" }),
press: ({ api }) => api.copy(),
}),
}),
})
export { copyButton }选项
让我们给复制按钮加上要复制的文本。用一个类型描述选项,在 options 里列出每个选项的种类,并用这个类型标注 state 的参数:
type CopyButtonOptions = { text?: string; onCopy?: (text: string) => void }options: { text: "string", onCopy: "callback" },
state: (options: CopyButtonOptions) => ({ copied: false }),state 的参数用这个类型标注后,api 里的 context.options() 也就有了类型,所以类型只需要写一次。种类告诉适配器如何处理每个值。比如,Web Components 会从属性读取 text,并把 onCopy 变成一个事件。TypeScript 会检查每个选项都有种类。如果你的原语(primitive)没有选项,就不写 options。
用 context.options() 读取当前值。这里,copy 在按钮被按压时读取文本:
api: (context) => {
return {
async copy() {
const { text = "", onCopy } = context.options()
await navigator.clipboard.writeText(text)
context.store.set({ copied: true })
onCopy?.(text)
},
}
},api 对每个实例只运行一次,所以在方法内部读取选项可以避免拿着旧值不放。
选项变化时
如果某个变化需要额外处理,就用 context.onOptions。对复制按钮来说,新的文本应该清掉之前的“Copied”状态。在 api 里、返回它的方法之前加上这段:
let text = context.options().text
context.onOptions((options) => {
if (options.text === text) return
text = options.text
context.store.set({ copied: false })
})如果想改为让一个受控值保持同步,就用 sync,处理变更 里有示例。
选项种类
同样的种类也适用于槽位的 props schema,它让每个部件拥有自己的值,比如 组合行为 里星星的 value。
| 种类 | 用途 |
|---|---|
"string", "number", "boolean" | 可以从属性读取的值。 |
"list" | 一个字符串或一个字符串列表。属性里用逗号分隔各值。 |
"value" | 其他值,比如对象、元素或函数。在 Web Components 上作为 property 设置。 |
"callback" | 报告某事的回调。Vue 把它当作 emit;Web Components 触发事件。 |
"action" | 返回值有意义的函数,比如 Promise。Vue 把它保留为函数 prop。 |
"id" | 省略时由适配器生成的字符串。 |
"key" | 列表项的值,类型不限。部件以它为键,里面的部件能看到这个键。 |
对于嵌套在另一个部件里的部件,{ kind: "string", from: "item" } 在省略时从外层的 item 继承同一个 prop。要继承不同的 prop,就用 from: "group.id";如果部件只有放在父级里才有意义,再加上 required: true,这样在别处使用就会抛错。内置种类都不合适时,可以用函数 (attribute) => value 解析 Web Component 的属性。
部件展示什么
只做样式的话,属性就够了。如果想让组件的内容也能读取状态,就在它的槽位里加上 state:
root: slot<{}, { copied: boolean }>({
state: (state) => ({ copied: state.copied }),
attrs: () => ({ type: "button" }),
press: ({ api }) => api.copy(),
}),第一个类型参数描述部件的 props;第二个描述它的 state 返回什么。在 React 里,复制按钮的子内容现在可以读取 copied:
<CopyButton text="npm add @ui-sdk/core">
{({ copied }) => (copied ? "Copied" : "Copy")}
</CopyButton>试试看。这个版本还会在短暂超时后重置。
import { definePrimitive } from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"
type CopyButtonOptions = {
text?: string
timeout?: number
onCopy?: (text: string) => void
}
type CopyButtonState = { copied: boolean }
const copyButton = definePrimitive({
name: "copy-button",
options: { text: "string", timeout: "number", onCopy: "callback" },
state: (options: CopyButtonOptions): CopyButtonState => ({ copied: false }),
api: (context) => {
let timer: ReturnType<typeof setTimeout> | undefined
let text = context.options().text
context.onOptions((options) => {
if (options.text === text) {
return
}
text = options.text
clearTimeout(timer)
context.store.set({ copied: false })
})
context.onDestroy(() => clearTimeout(timer))
return {
async copy() {
const { text = "", timeout = 1500, onCopy } = context.options()
await navigator.clipboard?.writeText(text).catch(() => {})
context.store.set({ copied: true })
onCopy?.(text)
clearTimeout(timer)
timer = setTimeout(() => context.store.set({ copied: false }), timeout)
},
}
},
slots: (slot) => ({
root: slot<{}, { copied: boolean }>({
state: (state) => ({ copied: state.copied }),
attrs: (state) => ({
type: "button",
"data-copied": state.copied ? "" : undefined,
}),
press: ({ api }) => api.copy(),
}),
}),
})
const parts = createParts(copyButton, { root: "button" })
const CopyButton = parts.Root
function Example() {
return (
<div data-slot="row">
<code data-slot="copy-command">npm install @ui-sdk/core</code>
<CopyButton text="npm install @ui-sdk/core">
{({ copied }) => (copied ? "Copied" : "Copy")}
</CopyButton>
</div>
)
}
export {
copyButton,
CopyButton,
type CopyButtonOptions,
type CopyButtonState,
Example,
}来来去去的部件
如果部件只在某些状态下出现,就用 present。这个面板在 open 为 true 时保持呈现:
panel: slot({
present: (state) => state.open,
attrs: (_state, part) => ({ id: `${part.id}-panel` }),
}),触发器用 aria-controls 指向面板:
trigger: slot({
attrs: (state, part) => ({
type: "button",
"aria-expanded": String(state.open),
"aria-controls": `${part.id}-panel`,
}),
press: ({ api }) => api.toggle(),
}),part.id 是实例的唯一 id。两个部件都用它来构成同一个面板 id。如果 id 里包含某个项的值,就用 @ui-sdk/core 的 idPart(value) 转义空格和百分号。
作者在部件元素上写的 id,会胜过槽位生成的那个 id,每个框架和 Web Components 都是如此。在它之后渲染的部件,从首次渲染起就指向作者的 id,在服务器上也是如此;元素绑定后,所有部件都会这样:aria-controls、aria-labelledby、aria-describedby、aria-activedescendant、for 以及其他指向所生成 id 的引用都会指向它。所以从 part.id 构建引用,核心会让它们保持正确。
一直在的部件就不用写 present。框架适配器会移除不存在的部件;Web Components 会保留标记,并随着呈现状态的变化绑定或解绑它的行为。
事件
按钮激活用 press。其他 DOM 事件用 on。下面是一个按 Escape 就清空的搜索框:
input: slot({
attrs: (state) => ({ type: "search", value: state.query }),
on: {
input: (event, { api }) => api.search((event.target as HTMLInputElement).value),
keydown: (event, { api }) => {
if (event.key !== "Escape") return
event.preventDefault()
api.search("")
},
},
}),每个处理函数都会收到事件和部件的上下文:el、id、key、props、store 和 api。组件使用者传入的处理函数会先运行。它可以调用 event.preventDefault() 跳过原语的处理函数。
import * as React from "react"
import { definePrimitive } from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"
import { XIcon } from "lucide-react"
type SearchFieldOptions = {
onQueryChange?: (query: string) => void
}
type SearchFieldState = { query: string }
const searchField = definePrimitive({
name: "search-field",
options: { onQueryChange: "callback" },
state: (_options: SearchFieldOptions): SearchFieldState => ({ query: "" }),
api: (context) => ({
search(query: string) {
context.store.set({ query })
context.options().onQueryChange?.(query)
},
}),
slots: (slot) => ({
root: slot({ attrs: () => ({ role: "search" }) }),
input: slot({
attrs: (state) => ({ type: "search", value: state.query }),
on: {
input: (event, { api }) =>
api.search((event.target as HTMLInputElement).value),
keydown: (event, { api }) => {
if (event.key !== "Escape") {
return
}
event.preventDefault()
api.search("")
},
},
}),
clear: slot({
present: (state) => state.query !== "",
attrs: () => ({ type: "button", "aria-label": "Clear" }),
press: ({ api }) => api.search(""),
}),
}),
})
const parts = createParts(searchField, {
root: "div",
input: "input",
clear: "button",
})
const SearchField = parts.Root
const SearchFieldInput = parts.Input
const SearchFieldClear = parts.Clear
const fruits = [
"Apple",
"Apricot",
"Banana",
"Cherry",
"Grape",
"Mango",
"Peach",
"Pear",
"Plum",
]
function Example() {
const [query, setQuery] = React.useState("")
const matches = fruits.filter((fruit) =>
fruit.toLowerCase().includes(query.toLowerCase())
)
return (
<div data-slot="stack">
<SearchField onQueryChange={setQuery}>
<SearchFieldInput
aria-label="Search fruit"
placeholder="Search fruit…"
/>
<SearchFieldClear>
<XIcon aria-hidden="true" />
</SearchFieldClear>
</SearchField>
<p data-slot="hint">{matches.join(", ") || "No fruit matches."}</p>
</div>
)
}
export {
Example,
searchField,
SearchField,
SearchFieldClear,
SearchFieldInput,
type SearchFieldOptions,
type SearchFieldState,
}角色、焦点和按键
在每个部件的槽位上声明角色,不要写在 attrs 里。角色由核心写入;如果角色要获取焦点、被激活或随按键移动,槽位就必须说明怎么做。下面是一个选项:
item: slot({
role: "option",
focus: "roving",
press: ({ api, key }) => api.choose(key),
attrs: (state, part) => ({
"aria-selected": String(state.value === part.key),
}),
}),漏掉一个,TypeScript 会点出来:没有 focus 的选项会报 “Property 'focus' is missing”。角色决定哪些字段是必需的:
focus用于要获取焦点的角色,比如option、tab或menuitem:"roving"、"tab-stop"、"active-descendant"或"native"。开发构建会检查绑定的元素能否以这种方式获取焦点,比如渲染成<div>的"native"部件。press用于会被激活的角色,比如button、option或tab。keys用于其模式随按键移动的角色,比如listbox、menu或slider:它的on.keydown处理的按键,或者当这些按键取决于状态时,用状态函数返回它们。
list: slot({
role: "listbox",
keys: (state) => [...(state.orientation === "horizontal" ? ["ArrowLeft", "ArrowRight"] : ["ArrowUp", "ArrowDown"]), "Home", "End", "typeahead"],
on: { keydown: (event, { api }) => api.navigate(event) },
}),列出了按键,却没有处理它们的 on.keydown,在任何槽位上都编译不过。如果另一个元素满足了某个需要,就用 { none: "why" } 说明是哪一个,比如 keys: { none: "The combobox's input handles them." }。随状态变化的角色是一个函数,它可能选到的每个角色都放在 roles 里:
root: slot({
role: (state) => (state.decorative ? "none" : "separator"),
roles: ["none", "separator"],
}),角色也决定部件的 ARIA。它的 attrs 要返回该角色离不开的状态,比如复选框的 aria-checked 或选项的 aria-selected,而且不能返回角色不接受的属性:组上的 aria-orientation 会报 “aria-orientation isn't allowed on a group”。
box: slot({
role: "checkbox",
focus: "native",
press: ({ api }) => api.toggle(),
attrs: (state) => ({ "aria-checked": String(state.checked) }),
}),由 live 保持最新的状态,在 attrs 里是 undefined,所以 attrs 仍然要写出它。类型看不到的东西,开发构建会发出警告,比如展开写法的槽位或 JavaScript;没有值却渲染的必需状态也会警告。在测试设置里设置 globalThis.__UI_SDK_STRICT__ = true,就能让每个警告都变成错误。
操作元素
需要元素才能做的工作就用 bind,比如测量元素或挂上观察器。它在部件绑定后于浏览器里运行。返回一个清理函数:
root: slot({
attrs: () => ({ rows: "1" }),
bind: (el) => {
const fit = () => {
el.style.height = "auto"
el.style.height = `${el.scrollHeight}px`
}
fit()
el.addEventListener("input", fit)
return () => el.removeEventListener("input", fit)
},
}),这个 textarea 会在每次输入后测量内容并调整高度。
import * as React from "react"
import { definePrimitive } from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"
const autosize = definePrimitive({
name: "autosize",
state: () => ({}),
api: () => ({}),
slots: (slot) => ({
root: slot({
attrs: () => ({ rows: "1" }),
bind: (el) => {
const fit = () => {
el.style.height = "auto"
el.style.height = `${el.scrollHeight}px`
}
fit()
el.addEventListener("input", fit)
return () => el.removeEventListener("input", fit)
},
}),
}),
})
const parts = createParts(autosize, { root: "textarea" })
const Autosize = parts.Root
function Example() {
return (
<Autosize
aria-label="Message"
placeholder="Write a message. Press Enter for a new line."
/>
)
}
export { autosize, Autosize, Example }让 attrs 和槽位的 state 保持纯净:它们也会在服务器上运行。从状态和部件的 props 读取;DOM 操作放在 bind 里。槽位的 state 每次调用都可以返回新的对象和数组,因为部件会按值比较它们;但其他值,比如 Date 或 Map,在变化之前应保持同一个对象。
bind 还会把部件作为第二个参数传进来。它的 props 会保持最新,part.store.subscribe 可以让你跟踪状态变化。如果某项工作必须在元素留在页面期间一直保持活动,即使部件没有呈现,比如隐藏的自定义元素,就用 connect。
清理实例
所有部件共享的工作放在 api 里。用 context.onDestroy 在实例销毁时清理它。比如,复制按钮会清掉它的重置定时器:
let timer: ReturnType<typeof setTimeout> | undefined
context.onDestroy(() => clearTimeout(timer))另外,在启动下一个定时器之前,也要清掉上一个。
在 API 中读取部件
有时方法需要找到某个部件。elements(context, slot) 会按页面顺序返回已绑定的部件,以及它们的元素、键和 props:
import { elements } from "@ui-sdk/core"
api: (context) => ({
next() {
const fields = elements<{ value: string }>(context, "field")
const empty = fields.find((field) => (field.el as HTMLInputElement).value === "")
empty?.el.focus()
},
}),试着留空一个字段。按钮会按当前的页面顺序找到它,所以不需要单独维护一份索引。
import * as React from "react"
import { definePrimitive, elements } from "@ui-sdk/core"
import { Field, FieldControl, FieldLabel } from "@ui-sdk/react/field"
import { createParts } from "@ui-sdk/react/primitive"
type CheckoutState = { missing: string | null }
const checkout = definePrimitive({
name: "checkout",
state: (): CheckoutState => ({ missing: null }),
api: (context) => ({
next() {
const fields = elements<{ value: string }>(context, "field")
const empty = fields.find(
(field) => (field.el as HTMLInputElement).value === ""
)
empty?.el.focus()
context.store.set({ missing: empty ? empty.props.value : null })
},
}),
slots: (slot) => ({
field: slot<{ value: string }>({
props: { value: "string" },
attrs: (_state, part) => ({ name: part.props.value }),
}),
next: slot<{}, CheckoutState>({
state: (state) => ({ missing: state.missing }),
attrs: () => ({ type: "button" }),
press: ({ api }) => api.next(),
}),
}),
})
const parts = createParts(checkout, { field: "input", next: "button" })
const Checkout = parts.Root
const CheckoutField = parts.Field
const CheckoutNext = parts.Next
const fields = [
{ value: "name", label: "Name", defaultValue: "Hollis Grant" },
{ value: "email", label: "Email" },
{ value: "address", label: "Address" },
]
function Example() {
return (
<Checkout>
<div data-slot="stack">
{fields.map(({ value, label, defaultValue }) => (
<Field key={value}>
<FieldLabel>{label}</FieldLabel>
<FieldControl
render={<CheckoutField value={value} />}
defaultValue={defaultValue}
/>
</Field>
))}
<CheckoutNext data-variant="solid">
{({ missing }) =>
missing
? `Fill In ${missing[0].toUpperCase()}${missing.slice(1)}`
: "Find Empty Field"
}
</CheckoutNext>
</div>
</Checkout>
)
}
export {
checkout,
Checkout,
CheckoutField,
CheckoutNext,
type CheckoutState,
Example,
}要拿单个部件,用 context.element(slot, key)。要读取它最新的 props,用 context.props(slot, key),命名方式相同:context.props<{ title: string }>("window", key)。这个 key 是部件的 id prop,或者它的 value,就像 组合行为 里的星星那样。
Agent 能做什么
agent 键告诉 Agent 桥接层 一个 Agent 可以调用哪些 api 方法,以及组件的一些信息,比如它的值是否必须是某个项:
agent: { actions: ["setValue", "clear"], closed: true },把它放在 api 后面,这样它的 items 函数就能读到 api 的类型。没有它的话,桥接层会挑选名字听起来像变更的方法,比如 setValue 或 toggle。Agent 键 展示了一个 Agent 可以使用的评分,以及这个键的每个部分。
命名
原语的 name 会作为每个部件 data-slot 的前缀,比如标签页的 list 槽位得到 tabs-list。root 槽位只拿到名字本身,所以 name: "copy-button" 会让它的根变成 data-slot="copy-button"。
警告和 devtools 也使用这个名字。如果希望它们显示别的名字,就设置 label;它不会改变 data-slot。
对于状态属性,openAttrs(open) 返回 data-open 或 data-closed。checkedAttrs(checked) 返回 data-checked、data-unchecked 或 data-indeterminate。两者都是 @ui-sdk/core 里的辅助函数。
API 参考
definePrimitive
namestring- Prefixes
data-slot, and names the component in warnings and the devtools. Kebab case. - 示例: Naming
state(options: Options) => State- The starting state, from the first options. Read
default<Key>here. - 示例: Define a Primitive
live?(keyof State)[]- State keys that change often and never affect rendering, like a highlighted item.
- 示例: Live State
asleep?((options: object) => boolean)- Whether an instance with these options starts asleep: its parts render and run
asleep, while its api and each part'sbindwait for the first event a part handles or the first read ofinstance.api, or ofapiin a slot's render. Like a closed tooltip, which costs little until its trigger is hovered or focused. sync?(options: Options) => Partial<State>- Maps controlled options onto state. Runs whenever options change.
- 示例: State a User Controls
controlled?(keyof State)[]- State keys a user can control with
<key>,default<Key>andon<Key>Change. Development builds warn when one starts with both<key>anddefault<Key>, or was controlled and becomes undefined. Defaults to whichever ofopen,valueandcheckedthe state has. - 示例: State a User Controls
commits?(keyof State)[]- State keys an interaction changes in steps and then commits, through
createCommit, like a slider'svaluewhile it's dragged.observereports each of them once per commit rather than per step. - 示例: Commits
api(context: PrimitiveContext) => Api- Runs once per instance and returns its api, which slots, adapters and a controller call.
- 示例: Define a Primitive
slots(slot: SlotFactory) => Record<string, SlotDefinition>- The parts, built with
slot.slot<Props, State>({ ... })types a slot's props and the state its render functions get. - 示例: Define a Primitive
label?string- What warnings,
debugand the devtools call it, when that isn'tname, which prefixesdata-slot. Like a checkbox group's parts incheckbox. - 示例: Naming
agent?object: actions, closed, items, reveals, shown, secret- What
@ui-sdk/core/agentoffers an agent. Without it, the agent takes the api's methods that change something by their names, likesetValue. - 示例: What Agents Can Do
options?PropSchema<Options>- Each option, with its kind, for renderers to read. A primitive without options leaves it out.
- 示例: Options
槽位
present?((state: State, context: { id: string; key: string; props: Props; api: Api; }) => boolean)- Whether the slot's element should exist. Adapters that cannot unmount markup, like custom elements, bind and unbind on it. Defaults to always. Keyed parts, like one panel among many, decide from their own props. May read live state: adapters check presence on every change.
- 示例: Parts That Come and Go
attrs?((state: State, context: { id: string; key: string; props: Props; api: Api; }) => Attrs)- Pure. Runs on the server and on every render. Never reads live state.
- 示例: Define a Primitive
state?((state: State, context: { id: string; key: string; props: Props; api: Api; }) => Public)- What
renderfunctions and state-based class names see, like { highlighted, disabled }. May read live state: adapters only re-render a part for live changes when its render function actually read them. - 示例: What a Part Shows
live?Live<State, Api, Props>- Attributes written straight to the element on every change, built by
live(). - 示例: Live State
direct?{ names: readonly string[]; attach: (part: Part, el: HTMLElement) => () => void; }- Attributes of
attrscore keeps current on a framework's element, built bydirect(). - 示例: Live State
selects?Selects<State, Api, Props>- Narrows which changes reach the slot's parts, built by
selects(). - 示例: Live State
press?(context: { el, id, key, props, store, api }, event?: Event) => void- Activation: a click, which keys and screen readers send too.
{ none: "why" }for a role that activates when another handler does it, like the author's own click. - 示例: Define a Primitive
on?Partial<Record<keyof HTMLElementEventMap, (event: Event, context: { el, id, key, props, store, api }) => void>>- DOM events. Adapters attach these so user handlers run first and can call preventDefault() to skip them.
- 示例: Events
bind?((el: HTMLElement, part: Part<State, Api, Props>) => (() => void) | void)- Client only, web only. Focus, positioning, observers. Gets the part, whose
propsare its newest render's. Return a cleanup. Follow state withpart.store.subscribe, or write attributes that change often withdirect. - 示例: Working with the Element
asleep?((el: HTMLElement, part: Part<State, Api, Props>) => (() => void) | void)- Client only, web only. Like
bind, but runs at once while the instance is asleep, for what a part can't wait for, like naming its trigger. Itspart.apiis undefined until the instance wakes. connect?((el: HTMLElement) => () => void)- Client only. Runs while the element is in the page, present or not, for adapters that keep parts that aren't present, like custom elements. A popup's content registers here, so shortcuts inside a closed one don't run.
- 示例: Working with the Element
props?PropSchema<Props>- Each prop the slot's parts take, with its kind, like
{ value: "string" }. - 示例: Add a Star
角色
role?Role | ((state, context) => Role | undefined)- The part's WAI-ARIA role, which core writes. A role that takes focus, activates or moves with keys makes the slot say how, with
focus,pressandkeys. A function picks the role from state, with every role it can pick inroles. Never putroleinattrs. - 示例: Roles, Focus and Keys
roles?array- Every role a
rolefunction can pick. Development builds check what each one needs. - 示例: Roles, Focus and Keys
focus?"roving" | "tab-stop" | "active-descendant" | "native" | { none: string }- How the part gets focus, for a role that takes it, like an option or a tab.
{ none: "why" }when another element takes it instead. - 示例: Roles, Focus and Keys
keys?HandledKey[] | ((state) => HandledKey[]) | { none: string }- The keys the part's
on.keydownhandles, for a role whose pattern moves with keys, or a function of state when they depend on it, like the arrows of an orientation.{ none: "why" }when another element handles them, like a combobox's input for its listbox. - 示例: Roles, Focus and Keys
下一步
复制按钮需要的东西都齐了。接下来,渲染原语 会把它放到你所用框架的页面上。