@ui-sdk/svelte 0.1.0-beta.12 → 0.1.0-beta.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { applyAttrs, attrs as partAttrs, createListSnapshots, directNames, followed, handlers as partHandlers, on, partState, present as isPresent, ref as partRef, renderVersion, sameSlotState, schemaOf, selectedKeys, subscribe, takeOwnId, touched, yieldToAuthor, } from "@ui-sdk/core/renderer";
1
+ import { applyAttrs, attrs as partAttrs, createListSnapshots, directNames, followed, handlers as partHandlers, noteEarlyText, on, partState, present as isPresent, ref as partRef, renderVersion, sameSlotState, schemaOf, selectedKeys, subscribe, takeOwnId, touched, yieldToAuthor, } from "@ui-sdk/core/renderer";
2
2
  import { onDestroy, untrack } from "svelte";
3
3
  import { createAttachmentKey } from "svelte/attachments";
4
4
  import { trackBindable } from "./bindable.svelte.js";
@@ -33,6 +33,7 @@ function usePrimitive(primitive, options) {
33
33
  // The first options go into the constructor, since effects never run on the server.
34
34
  const first = untrack(() => snapshot(options()));
35
35
  const prefixed = `ui-sdk-${first.id}`;
36
+ noteEarlyText();
36
37
  const instance = primitive({ ...first, id: prefixed });
37
38
  const bindable = trackBindable(primitive, instance.get(), first, options);
38
39
  const removals = [];
package/docs/agents.md CHANGED
@@ -479,19 +479,20 @@ Use these definitions when setting up your agent's tools. Route each tool call t
479
479
 
480
480
  What the tools return comes from the page, so it can include text your users wrote, like a name in a table row. Their descriptions tell the model to treat it as data. Before an agent changes something that matters, have a person confirm it with [Permissions](./agents.md#permissions).
481
481
 
482
- For a browser that supports WebMCP, [register the tools with the browser](./agents.md#webmcp).
482
+ When your model runs on your server, [send the calls to the page](./agents.md#run-the-model-on-your-server) and return the results. For a browser that supports WebMCP, [register the tools with the browser](./agents.md#webmcp).
483
483
 
484
484
  ## Your Own Components
485
485
 
486
486
  A component built with [`definePrimitive`](./core.md#define-a-primitive) joins the bridge too. Its `agent` key lists the API methods an agent can call, like `agent: { actions: ["setValue"] }`. Without one, methods named like changes, such as `setValue` or `toggle`, become its actions, and event handlers such as `keydown` stay internal.
487
487
 
488
- The snapshot reads the primitive's `controlled` state keys. If none are declared, it reads `open`, `value`, and `checked` when present. [Your Own Components](./agents.md#your-own-components) shows how to add the key and what each part of it does.
488
+ The snapshot reads the primitive's `controlled` state keys. If none are declared, it reads `open`, `value`, and `checked` when present. [The Agent Key](./agents.md#the-agent-key) shows how to add the key and what each part of it does.
489
489
 
490
490
  ## Next Steps
491
491
 
492
492
  - [Permissions](./agents.md#permissions): approve, refuse, or cancel an agent's changes.
493
493
  - [Observe Changes](./agents.md#observe-changes): keep the agent up to date with what the person changed.
494
494
  - [History and Undo](./agents.md#history-and-undo): record changes, undo them, and preview suggestions.
495
+ - [Run the Model on Your Server](./agents.md#run-the-model-on-your-server): keep the model on your server and run the tools in the browser.
495
496
  - [WebMCP](./agents.md#webmcp): make the tools available to a browser agent.
496
497
  - [Reference](./agents.md#reference): look up options, methods, and return values.
497
498
 
@@ -808,7 +809,7 @@ It should return `"function"` in a browser that supports registration. If it ret
808
809
  [Permissions](./agents.md#permissions) shows how to limit the actions an agent can run. [Observe Changes](./agents.md#observe-changes) keeps it informed when you change the UI. Use the [Reference](./agents.md#reference) to look up the bridge's options and results.
809
810
 
810
811
 
811
- # Your Own Components
812
+ # The Agent Key
812
813
 
813
814
  Let an agent use the components you build with definePrimitive, wherever they're rendered.
814
815
 
@@ -816,6 +817,8 @@ A component you build with [`definePrimitive`](./core.md#define-a-primitive) sho
816
817
 
817
818
  You write the key once, in the component. Anyone who renders the component gets it: an app that installs your rating from npm [creates the bridge](./agents.md#create-the-bridge), renders `<Rating>`, and its agent can rate, with no tool or schema to write.
818
819
 
820
+ ui-sdk's components use the same key. A Checkbox has `agent: { actions: ["setChecked"] }`. You'll find a few more [at the end of this page](#in-ui-sdks-components).
821
+
819
822
  ## Try It
820
823
 
821
824
  This rating has `agent: { actions: ["rate"] }`. Press **Read the page** to see what an agent sees, then **Ask for 4 stars** to send the step an agent would send.
@@ -845,9 +848,17 @@ const rating = definePrimitive({
845
848
  })
846
849
  ```
847
850
 
848
- `actions` lists the API methods an agent can call. Put `agent` last, after `slots`, so TypeScript has read your API by then.
851
+ `actions` lists the API methods an agent can call. Put `agent` after `api`.
852
+
853
+ Then give the rating a name where you render it:
849
854
 
850
- With the key, the snapshot lists `rate`:
855
+ ```tsx
856
+ <Rating aria-label="Your rating">
857
+ ```
858
+
859
+ The name is the rating's `label` in the snapshot, and a step can use it as its `ref`. A rating is a `group`, and a group doesn't take its name from the text inside it, so it needs `aria-label`, or `aria-labelledby` pointing at a visible label. A screen reader announces the same name.
860
+
861
+ With the key and the name, the snapshot lists `rate`:
851
862
 
852
863
  ```json
853
864
  [
@@ -865,18 +876,45 @@ And an agent can call it with the arguments the method takes:
865
876
 
866
877
  ```ts
867
878
  await agent.act({ steps: [{ ref: "Your rating", action: "rate", args: [4] }] })
868
- // { ok: true, steps: [{ ref: "c1", changes: [{ key: "value", value: 4, ... }] }], ... }
869
879
  ```
870
880
 
881
+ The step returns `ok: true` and what it changed: the rating's `value` is now `4`.
882
+
871
883
  The change goes through `createChange`, so the app's `onValueChange` sees `details.source === "agent"` and can cancel it, like any other change. [Permissions](./agents.md#permissions) covers that.
872
884
 
873
885
  ## Choose What an Agent Calls
874
886
 
875
- Only the methods in `actions` are offered. The rest of your API, like a `keydown` handler or a roving focus helper, stays private to your component, and a step that names one is refused.
887
+ Only the methods in `actions` are offered. The rest of your API, like a `keydown` handler or a roving focus helper, stays private to your component, and a step that names one is refused:
888
+
889
+ ```txt
890
+ rating c1 takes no keydown now. It takes: rate.
891
+ ```
876
892
 
877
893
  If `actions` names a method your API doesn't have, development builds warn, so a typo shows up right away.
878
894
 
879
- Without an `agent` key, the bridge guesses from method names: `set` followed by a capital letter, like `setValue`, and verbs like `open`, `toggle` or `clear`. It can't guess `rate`, so the rating would show `"actions": []`, and a step that asks for `rate` would get:
895
+ ## Without the Key
896
+
897
+ Without an `agent` key, the bridge guesses from method names: `set` followed by a capital letter, like `setValue`, and verbs like `open`, `toggle` or `clear`.
898
+
899
+ A popover built on `createPopup` gets `setOpen` from it:
900
+
901
+ ```ts
902
+ api: (context) => createPopup(context, { preset: popoverPreset }),
903
+ ```
904
+
905
+ It has no `agent` key, and an agent can open it:
906
+
907
+ ```json
908
+ {
909
+ "ref": "c1",
910
+ "component": "share",
911
+ "actions": ["setOpen", "press"],
912
+ "label": "Share",
913
+ "open": false
914
+ }
915
+ ```
916
+
917
+ The bridge can't guess `rate`. Without the key, the rating would show `"actions": []`, and a step that asks for `rate` would get:
880
918
 
881
919
  ```txt
882
920
  rating c1 takes no rate now. It takes: nothing.
@@ -884,6 +922,67 @@ rating c1 takes no rate now. It takes: nothing.
884
922
 
885
923
  Listing your actions makes the component say exactly what it does, whatever its methods are called.
886
924
 
925
+ ## Arguments
926
+
927
+ A step's `args` become the method's arguments. This board has two actions. `moveCard` takes a card and a column, and `addCard` takes a title:
928
+
929
+ ```ts title="board.ts"
930
+ const columns = ["todo", "doing", "done"]
931
+
932
+ const board = definePrimitive({
933
+ name: "board",
934
+ state: () => ({
935
+ value: { "Fix login": "todo", "Write docs": "doing" } as Record<
936
+ string,
937
+ string
938
+ >,
939
+ }),
940
+ api: (context) => {
941
+ const change = createChange(context)
942
+ const cards = () => context.store.get().value
943
+ return {
944
+ moveCard: (card: string, column: string) => {
945
+ if (!columns.includes(column)) {
946
+ throw new Error(
947
+ `No column "${column}". Columns: ${columns.join(", ")}.`
948
+ )
949
+ }
950
+ return change(
951
+ "value",
952
+ { ...cards(), [card]: column },
953
+ { reason: "drag" }
954
+ )
955
+ },
956
+ addCard: (card: string) =>
957
+ change("value", { ...cards(), [card]: "todo" }, { reason: "input" }),
958
+ }
959
+ },
960
+ slots: (slot) => ({
961
+ root: slot({ attrs: () => ({ role: "group" }) }),
962
+ }),
963
+ agent: { actions: ["moveCard", "addCard"] },
964
+ })
965
+ ```
966
+
967
+ An agent can move one card and add another in the same call:
968
+
969
+ ```ts
970
+ await agent.act({
971
+ steps: [
972
+ { ref: "Sprint board", action: "moveCard", args: ["Fix login", "done"] },
973
+ { ref: "Sprint board", action: "addCard", args: ["Write tests"] },
974
+ ],
975
+ })
976
+ ```
977
+
978
+ The bridge doesn't check the arguments of your own methods, so check them yourself, the way `moveCard` checks the column. When a method throws, the step fails with your message, and the steps after it don't run:
979
+
980
+ ```txt
981
+ No column "shipped". Columns: todo, doing, done.
982
+ ```
983
+
984
+ An action can also return a promise. The bridge doesn't wait for it to resolve, so the step's result is `"pending"`. If the promise rejects before the step ends, the step fails with its message.
985
+
887
986
  ## Lists
888
987
 
889
988
  When your component's value is always one of its items, like a size picker, add `closed: true`:
@@ -904,7 +1003,9 @@ The bridge reads the items from your state's `items`. If they live somewhere els
904
1003
  agent: { actions: ["setValue"], items: (api) => api.allItems() },
905
1004
  ```
906
1005
 
907
- The snapshot shows the items with the component when there are 10 or fewer and none are on the page. That works for any action, not only `setValue`, so a stepper's `goTo` shows its steps. Longer lists come back from `query({ within })`.
1006
+ `items` reads your API, which is why `agent` goes after `api`. Placed before it, TypeScript reports that `allItems` doesn't exist.
1007
+
1008
+ The snapshot lists the items with the component: the ones on the page, or the ones in your data when there are 10 or fewer. Longer lists come back from `query({ within })`. With an `items` function that works for any action, not only `setValue`, so a stepper's `goTo` shows its steps.
908
1009
 
909
1010
  ## Content Behind Items
910
1011
 
@@ -914,6 +1015,12 @@ Tabs and accordions hide other components behind their closed items. Add `reveal
914
1015
  agent: { actions: ["setValue"], closed: true, reveals: true },
915
1016
  ```
916
1017
 
1018
+ For a setup flow on its Account step, a step that asks for a field on another step gets:
1019
+
1020
+ ```txt
1021
+ No component "Card number" on the page. Its labels: Setup. It may be behind one of these, which a step can open first: Setup (c1): Billing, Team.
1022
+ ```
1023
+
917
1024
  ## Show It When It Matters
918
1025
 
919
1026
  `shown` decides whether an agent sees the component right now. A field wrapper, for example, only needs to show while it has errors, since its input already carries the label:
@@ -932,6 +1039,20 @@ agent: { actions: ["setValue", "clear"], secret: true },
932
1039
 
933
1040
  To hide one particular field instead, the app can mark it with `data-agent-secret`. See [Permissions](./agents.md#permissions).
934
1041
 
1042
+ ## In ui-sdk's Components
1043
+
1044
+ These are the `agent` keys of a few ui-sdk components, as they're written in `@ui-sdk/core`:
1045
+
1046
+ | Component | `agent` |
1047
+ | ------------ | ---------------------------------------------------------------------------------------------------------- |
1048
+ | Checkbox | `{ actions: ["setChecked"] }` |
1049
+ | Number Input | `{ actions: ["setValue", "increment", "decrement"] }` |
1050
+ | Select | `{ actions: ["setOpen", "setValue", "clear", "setQuery"], closed: true }` |
1051
+ | Tabs | `{ actions: ["setValue"], closed: true, reveals: true }` |
1052
+ | Accordion | `{ actions: ["setValue", "open", "close", "toggle", "openAll", "closeAll"], closed: true, reveals: true }` |
1053
+ | OTP Input | `{ actions: ["setValue", "clear"], secret: true }` |
1054
+ | Field | `{ shown: (state) => !!state.errors.length }` |
1055
+
935
1056
  ## API Reference
936
1057
 
937
1058
  | Key | Type | Description |
@@ -941,7 +1062,7 @@ To hide one particular field instead, the app can mark it with `data-agent-secre
941
1062
  | `items` | `(api) => unknown` | The items as data, when they aren't the state's `items`. |
942
1063
  | `reveals` | `boolean` | Closed items hide other components. A component the agent can't find is reported as maybe behind them. |
943
1064
  | `shown` | `(state) => boolean` | Whether an agent sees the component right now. |
944
- | `secret` | `boolean` | The value is always redacted, in the snapshot, in step results and in `observe`. |
1065
+ | `secret` | `boolean` | A filled value reads `"[redacted]"` in the snapshot, in step results and in `observe`. |
945
1066
 
946
1067
  The `agent` key is experimental.
947
1068
 
@@ -1053,6 +1174,8 @@ Two more marks change what the agent sees:
1053
1174
 
1054
1175
  Changes inside `data-agent-hidden` still reach [Observe](./agents.md#observe-changes), so your own logs see them, while `agent.subscribe` stays quiet. A secret value stays out of `snapshot`, `act` results and change events, and the field's error text reads `"[redacted]"` too. A secret File Input lists its files without their names. Password, card and one-time-code fields are treated as secret without a mark. A hidden input is left out without one.
1055
1176
 
1177
+ The agent reaches what a person can reach. A component hidden with CSS, the `hidden` attribute, a closed `<details>` or `aria-hidden="true"` is left out without a mark. A component in an `inert` region, like the page behind a modal dialog, is listed as disabled until the region is usable again.
1178
+
1056
1179
  In development, a misspelled mark such as `data-agent-confim` logs a warning with the name it meant.
1057
1180
 
1058
1181
  ## Cancel a Value Change
@@ -1299,6 +1422,167 @@ await staged.revert()
1299
1422
  To point at a suggested control, use `elementOf(ref)` from [Observe](./core.md#observe) with one of the refs in `staged.applied`.
1300
1423
 
1301
1424
 
1425
+ # Run the Model on Your Server
1426
+
1427
+ Keep the model and its keys on your server while the agent works with the page.
1428
+
1429
+ The bridge you created in [Get Started](./agents.md#get-started) reads and changes the components on the page, so it runs in the browser. The model can still run on your server, next to your API keys, usage limits, and other tools. Each time the model calls `snapshot`, `act`, or `query`, the call goes to the page, the bridge runs it, and the result goes back to the model.
1430
+
1431
+ This page uses the [AI SDK](https://ai-sdk.dev), where a tool without `execute` on the server is run by the browser. The examples use React.
1432
+
1433
+ ## Declare the Tools on the Server
1434
+
1435
+ Pass `agentTools` to `streamText` as tools without `execute`:
1436
+
1437
+ ```ts title="app/api/chat/route.ts"
1438
+ import { convertToModelMessages, jsonSchema, streamText, tool } from "ai"
1439
+ import { agentTools } from "@ui-sdk/react/agent"
1440
+
1441
+ const tools = Object.fromEntries(
1442
+ agentTools.map(({ name, description, inputSchema }) => [
1443
+ name,
1444
+ tool({ description, inputSchema: jsonSchema(inputSchema) }),
1445
+ ])
1446
+ )
1447
+
1448
+ async function POST(request: Request) {
1449
+ const { messages } = await request.json()
1450
+ const result = streamText({
1451
+ model: "anthropic/claude-sonnet-5.5",
1452
+ messages: await convertToModelMessages(messages),
1453
+ tools,
1454
+ })
1455
+ return result.toUIMessageStreamResponse()
1456
+ }
1457
+
1458
+ export { POST }
1459
+ ```
1460
+
1461
+ The model sees the same names, descriptions, and input schemas as any other agent. When it calls one, the response streams the call to the browser instead of running it on the server.
1462
+
1463
+ ## Run the Calls in the Browser
1464
+
1465
+ In the chat component, run each call on `agent` and add its result. The form sends what the person types, and each message shows its text:
1466
+
1467
+ ```tsx title="chat.tsx"
1468
+ import { useState } from "react"
1469
+ import { useChat } from "@ai-sdk/react"
1470
+ import { lastAssistantMessageIsCompleteWithToolCalls } from "ai"
1471
+ import { agent } from "./agent"
1472
+
1473
+ function Chat() {
1474
+ const [input, setInput] = useState("")
1475
+ const { messages, sendMessage, addToolOutput } = useChat({
1476
+ sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls,
1477
+ async onToolCall({ toolCall }) {
1478
+ const tool = toolCall.toolName as "snapshot" | "act" | "query"
1479
+ const output = await agent[tool](toolCall.input as never)
1480
+ addToolOutput({ tool, toolCallId: toolCall.toolCallId, output })
1481
+ },
1482
+ })
1483
+
1484
+ return (
1485
+ <form
1486
+ onSubmit={(event) => {
1487
+ event.preventDefault()
1488
+ sendMessage({ text: input })
1489
+ setInput("")
1490
+ }}
1491
+ >
1492
+ {messages.map((message) => (
1493
+ <p key={message.id}>
1494
+ {message.parts
1495
+ .map((part) => (part.type === "text" ? part.text : ""))
1496
+ .join("")}
1497
+ </p>
1498
+ ))}
1499
+ <input value={input} onChange={(event) => setInput(event.target.value)} />
1500
+ </form>
1501
+ )
1502
+ }
1503
+
1504
+ export { Chat }
1505
+ ```
1506
+
1507
+ `sendAutomaticallyWhen` sends the results back once every call in the message has one, and the model continues from there. Ask it to set a field and it calls `act`, the field changes on the page, and the model gets the steps it ran and every field's value.
1508
+
1509
+ The results are plain objects, so they travel as JSON without changes. A step that fails comes back in the result with `ok: false` and the reason, so the model can try again.
1510
+
1511
+ ## Refs Between Calls
1512
+
1513
+ A ref from `snapshot` stays with its component while it's on the page, including across re-renders. If the component is gone, the step fails and lists what's on the page now. Take a new snapshot after you reorder or rename components, since two components with the same kind, label, and row text can trade refs when they come back.
1514
+
1515
+ ## Stopping a Turn
1516
+
1517
+ A step that needs a person waits for your [`allow`](./agents.md#ask-first) callback, and later calls wait behind it. When the person stops the chat, pass a `signal` to `act` so that wait ends too. Here's `chat.tsx` again with one `AbortController` per turn and a **Stop** button:
1518
+
1519
+ ```tsx title="chat.tsx" {1,8-9,13-18,27,40-48}
1520
+ import { useRef, useState } from "react"
1521
+ import { useChat } from "@ai-sdk/react"
1522
+ import { lastAssistantMessageIsCompleteWithToolCalls } from "ai"
1523
+ import { agent } from "./agent"
1524
+
1525
+ function Chat() {
1526
+ const [input, setInput] = useState("")
1527
+ const turn = useRef(new AbortController())
1528
+ const { messages, sendMessage, addToolOutput, stop } = useChat({
1529
+ sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls,
1530
+ async onToolCall({ toolCall }) {
1531
+ const tool = toolCall.toolName as "snapshot" | "act" | "query"
1532
+ const output =
1533
+ tool === "act"
1534
+ ? await agent.act(toolCall.input as never, {
1535
+ signal: turn.current.signal,
1536
+ })
1537
+ : await agent[tool](toolCall.input as never)
1538
+ addToolOutput({ tool, toolCallId: toolCall.toolCallId, output })
1539
+ },
1540
+ })
1541
+
1542
+ return (
1543
+ <form
1544
+ onSubmit={(event) => {
1545
+ event.preventDefault()
1546
+ turn.current = new AbortController()
1547
+ sendMessage({ text: input })
1548
+ setInput("")
1549
+ }}
1550
+ >
1551
+ {messages.map((message) => (
1552
+ <p key={message.id}>
1553
+ {message.parts
1554
+ .map((part) => (part.type === "text" ? part.text : ""))
1555
+ .join("")}
1556
+ </p>
1557
+ ))}
1558
+ <input value={input} onChange={(event) => setInput(event.target.value)} />
1559
+ <button
1560
+ type="button"
1561
+ onClick={() => {
1562
+ turn.current.abort()
1563
+ stop()
1564
+ }}
1565
+ >
1566
+ Stop
1567
+ </button>
1568
+ </form>
1569
+ )
1570
+ }
1571
+
1572
+ export { Chat }
1573
+ ```
1574
+
1575
+ **Stop** aborts the turn's signal and stops the chat. The step that was waiting fails as cancelled, the steps after it don't run, and the `signal` passed to `allow` aborts so you can close your prompt. The result still goes back with the next message, so the model knows what didn't happen.
1576
+
1577
+ Without a signal, the step fails once `timeout` passes, 5 minutes by default.
1578
+
1579
+ ## Next Steps
1580
+
1581
+ - [Permissions](./agents.md#permissions): approve, refuse, or ask the person before a change.
1582
+ - [Observe Changes](./agents.md#observe-changes): tell the model what the person changed between turns.
1583
+ - [Reference](./agents.md#reference): look up what each tool returns.
1584
+
1585
+
1302
1586
  # WebMCP
1303
1587
 
1304
1588
  Let the agent built into a browser read and use your components.
@@ -1423,6 +1707,8 @@ const result = await agent.act({
1423
1707
  })
1424
1708
  ```
1425
1709
 
1710
+ Pass `{ signal }` as a second argument to stop it early. When the signal aborts, a step waiting on `allow` fails as cancelled, and the steps after it don't run.
1711
+
1426
1712
  ### Steps
1427
1713
 
1428
1714
  Each step is an `AgentStep`:
@@ -1571,9 +1857,9 @@ const sizePicker = definePrimitive({
1571
1857
  | `items` | A function from the api to its items, when they aren't in the state's `items`. |
1572
1858
  | `reveals` | Its closed items hide other components, like tabs. When a step names a component it can't find, the error lists them. |
1573
1859
  | `shown` | A function from the state that says whether the agent sees it now, like a field only while it has errors. |
1574
- | `secret` | Its value is always redacted, like a password's. |
1860
+ | `secret` | Its value reads `"[redacted]"` once it's filled, like a password's. |
1575
1861
 
1576
- [Your Own Components](./agents.md#your-own-components) walks through each key with examples.
1862
+ [The Agent Key](./agents.md#the-agent-key) walks through each key with examples.
1577
1863
 
1578
1864
  Without `actions`, the bridge picks methods by name: `set` followed by a capital letter, such as `setValue`, and these verbs alone or followed by a capital letter:
1579
1865
 
@@ -418,7 +418,7 @@ An `action` on a Close part runs before it closes the dialog. Return a Promise t
418
418
 
419
419
  Choose Delete Project, then Delete. The first attempt fails so you can try again. While Deleting… is shown, Cancel and Escape leave the dialog open. A successful retry closes it.
420
420
 
421
- While the action runs, its button stays focusable and gets `data-pending`, `aria-busy`, and `aria-disabled`. Other Close parts and dismissals cannot close the dialog until it settles. `onDismissAttempt` reports refused dismissals; a controller can still close it.
421
+ While the action runs, its button stays focusable and gets `data-pending`, `aria-busy`, and `aria-disabled`. Other Close parts get `aria-disabled` and `data-disabled`, and neither they nor dismissals can close the dialog until it settles. `onDismissAttempt` reports refused dismissals; a controller can still close it.
422
422
 
423
423
  The root's `pendingAnnouncement` sets what screen readers hear after a second of waiting. The error clears on the next attempt or when the dialog opens again. The action also receives `{ source }` after its event argument; [Changes After an Await](./button.md#changes-after-an-await) explains when to use it.
424
424
 
@@ -636,6 +636,7 @@ Each part has a `data-slot`, such as `alert-dialog-content`, and shows its state
636
636
  ### AlertDialogClose
637
637
  `[data-slot="alert-dialog-close"]`
638
638
 
639
+ - `data-disabled`
639
640
  - `data-pending`: Present on a Close part while its action runs.
640
641
 
641
642
  ## API Reference
@@ -1065,6 +1065,7 @@ Each part has a `data-slot`, such as `dialog-content`, and shows its state throu
1065
1065
  ### DialogClose
1066
1066
  `[data-slot="dialog-close"]`
1067
1067
 
1068
+ - `data-disabled`
1068
1069
  - `data-pending`: Present on a Close part while its action runs.
1069
1070
 
1070
1071
  ## API Reference
@@ -808,6 +808,7 @@ Leave the content's `translate` and the backdrop's opacity to the drawer. You ca
808
808
  ### DrawerClose
809
809
  `[data-slot="drawer-close"]`
810
810
 
811
+ - `data-disabled`
811
812
  - `data-pending`: Present on a Close part while its action runs.
812
813
 
813
814
  ### DrawerOutlet
@@ -459,6 +459,7 @@ Touch screens have no hover, so a tap follows the link without opening the card.
459
459
  **Keyboard**
460
460
 
461
461
  - Keyboard focus on the link opens the card after the delay.
462
+ - Keyboard focus on a link the pointer opened keeps the card open when the pointer leaves.
462
463
  - Escape closes the card and leaves focus on the link.
463
464
  - Enter follows the link.
464
465
 
@@ -87,7 +87,7 @@ Import the parts and put them together:
87
87
 
88
88
  ## Forms
89
89
 
90
- An ordinary form can save a value and then close the popover. Focus starts on the first field and returns to the trigger when the task finishes. A form with `method="dialog"` closes on submission and returns its submit button's value; the [row editor](#triggers-outside-the-popover) shows that version.
90
+ An ordinary form can save a value and then close the popover. Focus starts on the first field and returns to the trigger when the task finishes. A form with `method="dialog"` closes on submission and returns its submit button's value; the [row editor](#triggers-outside-the-popover) shows that version. Inside another form, pass `container` so the popover's form doesn't nest in it.
91
91
 
92
92
  ```svelte title="form.svelte"
93
93
  <script lang="ts">
@@ -1982,6 +1982,7 @@ Searching, with a search field in the list:
1982
1982
  - Opening focuses the search field and highlights the selected item.
1983
1983
  - The search field is a combobox that controls the listbox in the list.
1984
1984
  - Typing filters the list and highlights the first match.
1985
+ - A field whose onChange renders the filtered list at once still highlights the first match. React only.
1985
1986
  - Typing never jumps by first letter: the characters go into the field.
1986
1987
  - Arrow keys move the highlight while focus stays in the field.
1987
1988
  - Home and End are the field's, so the highlight stays.
@@ -623,7 +623,7 @@ When each tab is a route, render [links](#links) and derive the controlled value
623
623
 
624
624
  ## Scroll into View
625
625
 
626
- If the list scrolls, selecting a tab through a controller or the URL scrolls it into view inside that list. Pointer and arrow-key selection focus the tab, so the browser reveals it as part of focusing it.
626
+ If the list scrolls, selecting a tab scrolls it into view inside that list, whether you click it, reach it with an arrow key, or select it through a controller or the URL.
627
627
 
628
628
  ## Custom Rendering
629
629
 
@@ -1122,6 +1122,7 @@ Every line below is an automated test.
1122
1122
  **Opening**
1123
1123
 
1124
1124
  - Typing a trigger opens the list with every item.
1125
+ - A field controlled through onChange keeps the typed trigger and opens the list. React only.
1125
1126
  - Typing after the trigger filters the list.
1126
1127
  - Text an input method commits filters the list.
1127
1128
  - Queries match Unicode letters and ignore accents.
package/docs/core.md CHANGED
@@ -610,7 +610,7 @@ The `agent` key tells [the agent bridge](./agents.md#custom-primitives) which ap
610
610
  agent: { actions: ["setValue", "clear"], closed: true },
611
611
  ```
612
612
 
613
- Put it last, after `slots`, so TypeScript has read the api by then. Without it, the bridge picks methods named like changes, such as `setValue` or `toggle`. [Your Own Components](./agents.md#your-own-components) shows a rating an agent can use, and every part of the key.
613
+ Put it after `api`, so its `items` function can read the api's types. Without it, the bridge picks methods named like changes, such as `setValue` or `toggle`. [The Agent Key](./agents.md#the-agent-key) shows a rating an agent can use, and every part of the key.
614
614
 
615
615
  ## Naming
616
616
 
@@ -1473,6 +1473,7 @@ export { rating, type RatingOptions }
1473
1473
 
1474
1474
  Next, [Handle Changes](./core.md#handle-changes) goes further into the change pattern the rating uses: callbacks, controlled state, commits and undo.
1475
1475
 
1476
+ - [Customize a Behavior](./core.md#customize-a-behavior) adds keys to this rating and changes its rules.
1476
1477
  - [Focus](./core.md#focus-and-keys) covers grids and other ways to move through a group.
1477
1478
  - [Testing](./core.md#testing) checks the component's keyboard behavior and accessibility.
1478
1479
 
@@ -2031,7 +2032,375 @@ A controlled drag has one more timing concern: its draft may need to stay visibl
2031
2032
 
2032
2033
  ## Next
2033
2034
 
2034
- That covers the Core guides. [Reference](./core.md#reference) lists every export by the job it does, and [Behaviors](./core.md#all-behaviors) has the building blocks for focus, selection, popups and more.
2035
+ Next, [Customize a Behavior](./core.md#customize-a-behavior) changes the keys and rules of a behavior you imported. That's the last Core guide. [Reference](./core.md#reference) lists every export by the job it does, and [Behaviors](./core.md#all-behaviors) has the building blocks for focus, selection, popups and more.
2036
+
2037
+
2038
+ # Customize a Behavior
2039
+
2040
+ Change a rule, add or remove a key, refuse a change, and build your own behavior on top of one.
2041
+
2042
+ [Compose Behaviors](./core.md#compose-behaviors) built a rating from `createChange` and `createRovingFocus`. Each behavior came with rules of its own: roving focus decides which keys move focus, where each one goes, and which star Tab lands on. When your component needs something different, keep the behavior and change it in one of these places:
2043
+
2044
+ | You Want To | Where |
2045
+ | ----------------------------------------- | ---------------------------------------------------- |
2046
+ | Change one of its rules | [An option](#change-a-rule) |
2047
+ | Add a key, or take one away | [Your `api`, around the call](#add-a-key) |
2048
+ | Choose what happens after it runs | [What the call returns](#choose-what-a-move-does) |
2049
+ | Reuse your version in other components | [A function around the behavior](#extend-a-behavior) |
2050
+ | Change a behavior other than roving focus | [The same places, by behavior](#other-behaviors) |
2051
+ | Stop a change from outside | [The change callback](#refuse-a-change) |
2052
+ | Take a key from outside the component | [Your own event handler](#handle-an-event-first) |
2053
+
2054
+ We'll keep working on [that rating](./core.md#complete-primitive). Each step changes a few lines of `rating.ts` or the code that renders it.
2055
+
2056
+ ## Change a Rule
2057
+
2058
+ Each rule a behavior follows is an option. The rating wraps from the last star to the first because it passes `loop`. To stop at either end, change that option in `createRovingFocus`:
2059
+
2060
+ ```ts
2061
+ loop: () => false,
2062
+ ```
2063
+
2064
+ Most options are functions, so a rule can depend on state or on the component's own options. They run each time the behavior needs an answer.
2065
+
2066
+ Start here for any behavior: its options are listed with its guide, and [All Behaviors](./core.md#all-behaviors) links to each one. For roving focus, [Focus and Keys](./core.md#roving-focus) covers `orientation`, `loop`, `disabled`, `focusable`, `preferred` and `remember`.
2067
+
2068
+ One option goes further. `move` replaces every built-in key, which fits a layout the built-in keys don't describe, such as a [keypad](./core.md#any-layout). To add one key and keep the rest, wrap the call.
2069
+
2070
+ ## Add a Key
2071
+
2072
+ Roving focus doesn't listen for keys by itself. The star's `keydown` handler calls `api.keydown`, and that calls `roving.keydown`. The call is yours, so you can handle a key before the behavior sees it.
2073
+
2074
+ Let's make the number keys jump to a star. Update `keydown` in the object returned from `api`:
2075
+
2076
+ ```ts {2-14}
2077
+ keydown(event: KeyboardEvent, el: HTMLElement) {
2078
+ const modified = event.ctrlKey || event.metaKey || event.altKey
2079
+ const star = modified
2080
+ ? undefined
2081
+ : roving.items().find((item) => item.key === event.key)
2082
+ if (star) {
2083
+ event.preventDefault()
2084
+ roving.focus(star.key)
2085
+ change("value", Number(star.key), {
2086
+ reason: "list-navigation",
2087
+ event,
2088
+ })
2089
+ return
2090
+ }
2091
+
2092
+ const moved = roving.keydown(event, el)
2093
+ if (moved) {
2094
+ change("value", Number(moved.key), {
2095
+ reason: "list-navigation",
2096
+ event,
2097
+ })
2098
+ }
2099
+ },
2100
+ ```
2101
+
2102
+ - `roving.items()` returns the stars that can take focus. Each star's key is its value, so pressing 4 finds the fourth star.
2103
+ - `roving.focus(key)` moves focus to that star. The tab stop follows the new rating, as it did before.
2104
+ - Every other key still reaches `roving.keydown`, so the arrows, Home and End work as before.
2105
+
2106
+ Focus a star and press 4. The arrows, Home and End still work.
2107
+
2108
+ ## Take a Key Away
2109
+
2110
+ To drop a key, return before the call. Add this at the top of `keydown`, and Home and End no longer change the rating:
2111
+
2112
+ ```ts
2113
+ if (event.key === "Home" || event.key === "End") {
2114
+ return
2115
+ }
2116
+ ```
2117
+
2118
+ The behavior never sees the key, so the browser handles it as usual.
2119
+
2120
+ ## Choose What a Move Does
2121
+
2122
+ `roving.keydown` moves focus and tells you where it went. It returns `key`, the item it moved to, `from`, the item it left, and `shift`, whether Shift was held. For a key that isn't its own, it returns `undefined`.
2123
+
2124
+ What a move means is up to the component. The rating selects the star it lands on:
2125
+
2126
+ ```ts
2127
+ const moved = roving.keydown(event, el)
2128
+ if (moved) {
2129
+ change("value", Number(moved.key), { reason: "list-navigation", event })
2130
+ }
2131
+ ```
2132
+
2133
+ A row of buttons can ignore the result, so focus moves and nothing else changes. A file list uses `shift` to extend a selection, as [Ranges and Select All](./core.md#ranges-and-select-all) shows.
2134
+
2135
+ ## Extend a Behavior
2136
+
2137
+ The number keys now live inside the rating. To use them in other components, move them into a function that wraps the behavior and returns it with your `keydown` in place of the original:
2138
+
2139
+ ```ts title="number-keys.ts"
2140
+ import {
2141
+ createRovingFocus,
2142
+ type PrimitiveContext,
2143
+ type RovingFocusOptions,
2144
+ } from "@ui-sdk/core"
2145
+
2146
+ function createNumberKeys<State extends object>(
2147
+ context: PrimitiveContext<any, State, any>,
2148
+ options: RovingFocusOptions<State>
2149
+ ) {
2150
+ const roving = createRovingFocus(context, options)
2151
+
2152
+ return {
2153
+ ...roving,
2154
+ keydown(event: KeyboardEvent, el: HTMLElement) {
2155
+ const modified = event.ctrlKey || event.metaKey || event.altKey
2156
+ const items = roving.items()
2157
+ const from = items.find((item) => item.el === el)
2158
+ const to = modified
2159
+ ? undefined
2160
+ : items.find((item) => item.key === event.key)
2161
+ if (from && to) {
2162
+ event.preventDefault()
2163
+ roving.focus(to.key)
2164
+ return { key: to.key, from: from.key, shift: event.shiftKey }
2165
+ }
2166
+
2167
+ return roving.keydown(event, el)
2168
+ },
2169
+ }
2170
+ }
2171
+
2172
+ export { createNumberKeys }
2173
+ ```
2174
+
2175
+ - It takes the same `context` and options as `createRovingFocus`, so each component still passes its own rules.
2176
+ - `...roving` keeps `bind`, `tabIndex`, `items` and the rest.
2177
+ - Its `keydown` returns the same result as the original, so a component treats a number key like any other move.
2178
+
2179
+ In `rating.ts`, call `createNumberKeys` in place of `createRovingFocus` and leave its options as they are. `keydown` goes back to what it was in Compose Behaviors:
2180
+
2181
+ ```ts
2182
+ keydown(event: KeyboardEvent, el: HTMLElement) {
2183
+ const moved = roving.keydown(event, el)
2184
+ if (moved) {
2185
+ change("value", Number(moved.key), { reason: "list-navigation", event })
2186
+ }
2187
+ },
2188
+ ```
2189
+
2190
+ Any group whose keys are numbers can use it now. A row of page buttons passes its own slot and `orientation`, and gets the number keys with them.
2191
+
2192
+ Your `keydown` runs wherever your component calls it. You can replace `focus` or `tabIndex` the same way. Inside, the behavior keeps using its own methods: when focus lands on an item, it calls the original `remember`. To change what it does by itself, use its options.
2193
+
2194
+ ## Other Behaviors
2195
+
2196
+ The other behaviors change in the same places. Their rules are options too. Where roving focus returns each move from `keydown`, a behavior that changes a value hands you the value to write, through `set`.
2197
+
2198
+ A selection writes each new value through `set`, so a limit goes there. This one allows three toppings:
2199
+
2200
+ ```ts
2201
+ const selection = createSelection(context, {
2202
+ key: "value",
2203
+ set: (value, details) => value.length <= 3 && change("value", value, details),
2204
+ order: () => roving.items().map((item) => item.key),
2205
+ multiple: () => true,
2206
+ })
2207
+ ```
2208
+
2209
+ `set` returns whether the value went through. Returning `false` leaves the selection as it was.
2210
+
2211
+ Here's where to look in the behaviors you'll use most. Each name links to its guide:
2212
+
2213
+ | Behavior | Rules You Can Change | What It Hands You |
2214
+ | ------------------------------------------------------------------------ | ------------------------------------------------------ | ---------------------------------------------------------------------- |
2215
+ | [`createRovingFocus`](./core.md#roving-focus) | `orientation`, `loop`, `disabled`, `focusable`, `move` | Each move, returned from `keydown` |
2216
+ | [`createGridFocus`](./core.md#grids) | `disabled`, `pageSize` | Each move, in `onMove` |
2217
+ | [`createSelection`](./core.md#selecting-items) | `multiple`, `selectable` | Each selection, in `set` |
2218
+ | [`createListbox`](./core.md#options-you-search) | `filter`, `loop` | Each highlight, in `onHighlight` |
2219
+ | [`createReorder`](./core.md#reordering) | `orientation`, `group`, `disabled` | Each order, in `set`, and each announcement, in `message` |
2220
+ | [`createTransfer`](./core.md#moving-between-lists) | `accepts`, `order`, `disabled` | Each move between lists, in `set`, and each announcement, in `message` |
2221
+ | [`createMove`](./core.md#moving-in-two-dimensions) | `bounds`, `step`, `disabled` | Each position, in `set`, and each announcement, in `message` |
2222
+ | [`createResize`](./core.md#resizing-boxes) | `min`, `max`, `aspect`, `bounds` | Each size, in `set`, and each announcement, in `message` |
2223
+ | [`createPopup`](./core.md#pick-its-behavior) | A preset, and `role` | Each open and close, in `onOpenChange` |
2224
+
2225
+ A `message` can reword one announcement and keep the others, since each default is exported: `reorderMessage`, `transferMessage`, `moveMessage` and `resizeMessage`. [What's Read Out](./core.md#whats-read-out) shows one.
2226
+
2227
+ ## Refuse a Change
2228
+
2229
+ The next two steps need no changes to `rating.ts`. They're for whoever renders the rating.
2230
+
2231
+ Every change the rating makes goes through `change`, which calls `onValueChange` before it writes the value. The callback can refuse. Here a review form keeps the value as it is while it saves:
2232
+
2233
+ **React**
2234
+
2235
+ ```tsx
2236
+ <Rating
2237
+ aria-label="Rating"
2238
+ onValueChange={(value, details) => {
2239
+ if (saving) {
2240
+ details.cancel()
2241
+ }
2242
+ }}
2243
+ >
2244
+ {children}
2245
+ </Rating>
2246
+ ```
2247
+
2248
+ **Vue**
2249
+
2250
+ ```vue
2251
+ <Rating
2252
+ aria-label="Rating"
2253
+ @value-change="(value, details) => saving && details.cancel()"
2254
+ >
2255
+ <slot />
2256
+ </Rating>
2257
+ ```
2258
+
2259
+ **Svelte**
2260
+
2261
+ ```svelte
2262
+ <Rating
2263
+ aria-label="Rating"
2264
+ onValueChange={(value, details) => {
2265
+ if (saving) {
2266
+ details.cancel()
2267
+ }
2268
+ }}
2269
+ >
2270
+ {@render children()}
2271
+ </Rating>
2272
+ ```
2273
+
2274
+ **Solid**
2275
+
2276
+ ```tsx
2277
+ <Rating
2278
+ aria-label="Rating"
2279
+ onValueChange={(value, details) => {
2280
+ if (saving()) {
2281
+ details.cancel()
2282
+ }
2283
+ }}
2284
+ >
2285
+ {props.children}
2286
+ </Rating>
2287
+ ```
2288
+
2289
+ **Web Components**
2290
+
2291
+ ```ts
2292
+ const rating = document.querySelector<HTMLElement>("my-rating")!
2293
+
2294
+ rating.addEventListener("valuechange", (event) => {
2295
+ if (saving) {
2296
+ event.preventDefault()
2297
+ }
2298
+ })
2299
+ ```
2300
+
2301
+ It refuses a press, an arrow key and a number key alike, since they all ask through `change`. To refuse only some of them, check `details.reason`: the rating reports `item-press` and `list-navigation`. [What a Change Reports](./core.md#what-a-change-reports) lists everything a callback gets.
2302
+
2303
+ Focus still follows the keys while a change is refused. Only the value stays.
2304
+
2305
+ `cancel()` refuses a change the rating would write itself. If you pass `value`, you decide instead: keep the old value and the rating stays where it is.
2306
+
2307
+ ## Handle an Event First
2308
+
2309
+ An event handler you pass to a part runs before the part's own. Call `event.preventDefault()` and the part skips its handler for that event.
2310
+
2311
+ Say the rating sits in a table row, where Up and Down move between rows. Take those two keys and leave the others to the rating:
2312
+
2313
+ **React**
2314
+
2315
+ ```tsx
2316
+ <RatingStar
2317
+ value="3"
2318
+ onKeyDown={(event) => {
2319
+ if (event.key === "ArrowUp" || event.key === "ArrowDown") {
2320
+ event.preventDefault()
2321
+ moveRow(event.key)
2322
+ }
2323
+ }}
2324
+ />
2325
+ ```
2326
+
2327
+ **Vue**
2328
+
2329
+ ```vue
2330
+ <script setup lang="ts">
2331
+ function onKeydown(event: KeyboardEvent) {
2332
+ if (event.key === "ArrowUp" || event.key === "ArrowDown") {
2333
+ event.preventDefault()
2334
+ moveRow(event.key)
2335
+ }
2336
+ }
2337
+ </script>
2338
+
2339
+ <template>
2340
+ <RatingStar value="3" @keydown="onKeydown" />
2341
+ </template>
2342
+ ```
2343
+
2344
+ **Svelte**
2345
+
2346
+ ```svelte
2347
+ <RatingStar
2348
+ value="3"
2349
+ onkeydown={(event) => {
2350
+ if (event.key === "ArrowUp" || event.key === "ArrowDown") {
2351
+ event.preventDefault()
2352
+ moveRow(event.key)
2353
+ }
2354
+ }}
2355
+ />
2356
+ ```
2357
+
2358
+ **Solid**
2359
+
2360
+ ```tsx
2361
+ <RatingStar
2362
+ value="3"
2363
+ onKeyDown={(event) => {
2364
+ if (event.key === "ArrowUp" || event.key === "ArrowDown") {
2365
+ event.preventDefault()
2366
+ moveRow(event.key)
2367
+ }
2368
+ }}
2369
+ />
2370
+ ```
2371
+
2372
+ **Web Components**
2373
+
2374
+ ```ts
2375
+ const rating = document.querySelector<HTMLElement>("my-rating")!
2376
+
2377
+ rating.addEventListener(
2378
+ "keydown",
2379
+ (event) => {
2380
+ if (event.key === "ArrowUp" || event.key === "ArrowDown") {
2381
+ event.preventDefault()
2382
+ moveRow(event.key)
2383
+ }
2384
+ },
2385
+ { capture: true }
2386
+ )
2387
+ ```
2388
+
2389
+ Listen in the capture phase, on the rating or anything around it. The star's own listener is on its button, so a plain listener added to that button later runs after it.
2390
+
2391
+ Left, Right, Home, End and the number keys still belong to the rating. `preventDefault()` also stops what the browser would do with the key, such as scrolling the page.
2392
+
2393
+ Both work the same way on the ready-made components, since they're built from the same pieces. [Tabs](./components/tabs.md) takes `onValueChange` with `details.cancel()`, and a key handler on its list runs before the arrow keys do. With web components, listen in the capture phase there too.
2394
+
2395
+ ## Replace One Behavior
2396
+
2397
+ Behaviors don't know about each other. The rating's `createChange` and `createRovingFocus` meet only in your `api`. So when a component needs focus rules of its own, you can write that one piece yourself and keep the rest: changes, callbacks and controlled state stay as they are.
2398
+
2399
+ ## Keep Building
2400
+
2401
+ - [Focus and Keys](./core.md#focus-and-keys) has every roving focus option, with a demo for each.
2402
+ - [Handle Changes](./core.md#handle-changes) goes further into callbacks, reasons and controlled state.
2403
+ - [Testing](./core.md#testing) checks that the keyboard still matches the pattern after you change it.
2035
2404
 
2036
2405
 
2037
2406
  # Reference
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ui-sdk/svelte",
3
- "version": "0.1.0-beta.12",
3
+ "version": "0.1.0-beta.14",
4
4
  "description": "UI SDK for Svelte.",
5
5
  "keywords": [
6
6
  "svelte",
@@ -381,7 +381,7 @@
381
381
  ],
382
382
  "peerDependencies": {
383
383
  "svelte": ">=5.33",
384
- "@ui-sdk/core": "^0.1.0-beta.12"
384
+ "@ui-sdk/core": "^0.1.0-beta.14"
385
385
  },
386
386
  "devDependencies": {
387
387
  "@sveltejs/package": "^2.5.8",
@@ -393,7 +393,7 @@
393
393
  "typescript": "~5.9.3",
394
394
  "vite": "^8.3.3",
395
395
  "vitest": "^5.0.3",
396
- "@ui-sdk/core": "0.1.0-beta.12"
396
+ "@ui-sdk/core": "0.1.0-beta.14"
397
397
  },
398
398
  "scripts": {
399
399
  "build": "node ../../scripts/build/build-svelte-package.mjs",