@opencode/ui 0.0.0-dev-750 → 0.0.0-dev-784

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.
Files changed (48) hide show
  1. package/dist/components/animated-number-machine.d.ts +95 -0
  2. package/dist/components/popover-machine.d.ts +96 -0
  3. package/dist/components/popover.d.ts +2 -2
  4. package/dist/components/resize-handle-machine.d.ts +71 -0
  5. package/dist/components/scroll-view-machine.d.ts +66 -0
  6. package/dist/components/scroll-view.d.ts +2 -2
  7. package/dist/components/text-field-machine.d.ts +62 -0
  8. package/dist/components/text-reveal-machine.d.ts +90 -0
  9. package/dist/data-display/line-comment/machine.d.ts +157 -0
  10. package/dist/data-display/project-avatar/animation-machine.d.ts +62 -0
  11. package/dist/data-display/project-avatar/animation.d.ts +1 -1
  12. package/dist/feedback/toast/machine.d.ts +57 -0
  13. package/dist/feedback/toast/toast.d.ts +1 -1
  14. package/dist/forms/select/machine.d.ts +45 -0
  15. package/dist/forms/typeahead/machine.d.ts +85 -0
  16. package/dist/navigation/menu/machine.d.ts +49 -0
  17. package/dist/navigation/segmented-control/machine.d.ts +46 -0
  18. package/dist/theme/context.d.ts +20 -9
  19. package/dist/theme/machine.d.ts +174 -0
  20. package/package.json +2 -2
  21. package/src/components/animated-number-machine.ts +214 -0
  22. package/src/components/animated-number.tsx +134 -83
  23. package/src/components/popover-machine.ts +198 -0
  24. package/src/components/popover.tsx +157 -89
  25. package/src/components/resize-handle-machine.ts +174 -0
  26. package/src/components/resize-handle.tsx +113 -83
  27. package/src/components/scroll-view-machine.ts +231 -0
  28. package/src/components/scroll-view.tsx +163 -116
  29. package/src/components/text-field-machine.ts +102 -0
  30. package/src/components/text-field.tsx +78 -24
  31. package/src/components/text-reveal-machine.ts +184 -0
  32. package/src/components/text-reveal.tsx +96 -93
  33. package/src/data-display/line-comment/line-comment.tsx +154 -178
  34. package/src/data-display/line-comment/machine.ts +392 -0
  35. package/src/data-display/project-avatar/animation-machine.ts +182 -0
  36. package/src/data-display/project-avatar/animation.ts +67 -38
  37. package/src/feedback/toast/machine.ts +115 -0
  38. package/src/feedback/toast/toast.tsx +55 -59
  39. package/src/forms/select/machine.ts +81 -0
  40. package/src/forms/select/select.tsx +49 -27
  41. package/src/forms/typeahead/machine.ts +253 -0
  42. package/src/forms/typeahead/typeahead.tsx +70 -62
  43. package/src/navigation/menu/machine.ts +109 -0
  44. package/src/navigation/menu/menu.tsx +118 -20
  45. package/src/navigation/segmented-control/machine.ts +72 -0
  46. package/src/navigation/segmented-control/segmented-control.tsx +46 -46
  47. package/src/theme/context.tsx +134 -240
  48. package/src/theme/machine.ts +508 -0
@@ -1,8 +1,18 @@
1
+ import { observeReducedMotion, prefersReducedMotion } from "../../motion/reduced"
2
+ import {
3
+ AVATAR_DISPOSED,
4
+ AVATAR_POINTER_LEFT,
5
+ AVATAR_REFRESH,
6
+ createAvatarClock,
7
+ INITIAL_AVATAR_ANIMATION_STATE,
8
+ selectAvatarPaintTime,
9
+ selectAvatarRunning,
10
+ transitionAvatarAnimation,
11
+ type AvatarAnimationEvent,
12
+ type AvatarAnimationState,
13
+ } from "./animation-machine"
1
14
  import { drawProjectIcon, type GeneratedProjectIcon } from "./generated"
2
15
 
3
- // The animation starts once the pointer rests on the avatar's row, so passing over a list does no drawing.
4
- const REST_MS = 150
5
-
6
16
  const HOVER_TARGET = 'a, button, [role="menuitem"], [role="option"], [data-titlebar-tab]'
7
17
 
8
18
  // Paints a generated avatar into `canvas`. The static frame is drawn once per icon and pixel size and copied into every
@@ -10,11 +20,14 @@ const HOVER_TARGET = 'a, button, [role="menuitem"], [role="option"], [data-title
10
20
  // row animates only that row's icon even when other rows show the same project. Only a hovered avatar runs an
11
21
  // animation loop, and it stops once the icon has eased back to its static frame.
12
22
  export function attachGeneratedAvatar(canvas: HTMLCanvasElement, icon: () => GeneratedProjectIcon) {
23
+ let state: AvatarAnimationState = INITIAL_AVATAR_ANIMATION_STATE
24
+ const clock = createAvatarClock()
13
25
  let frame = 0
14
- let time = 0
15
- let hovering = false
16
- let last = 0
17
- let entered = 0
26
+ let stopMotionObserver: (() => void) | undefined
27
+ // Reused every frame, so the loop allocates nothing.
28
+ const enterEvent = { type: "pointer.entered" as const, now: 0, reduced: false }
29
+ const frameEvent = { type: "frame" as const, now: 0 }
30
+ const motionEvent = { type: "motion.changed" as const, reduced: false }
18
31
 
19
32
  const paint = (draw: (ctx: CanvasRenderingContext2D, px: number) => void) => {
20
33
  const px = Math.max(1, Math.round((canvas.clientWidth || 16) * (window.devicePixelRatio || 1)))
@@ -25,60 +38,76 @@ export function attachGeneratedAvatar(canvas: HTMLCanvasElement, icon: () => Gen
25
38
  if (ctx) draw(ctx, px)
26
39
  }
27
40
 
28
- const paintStatic = () =>
29
- paint((ctx, px) => {
30
- ctx.clearRect(0, 0, px, px)
31
- const still = staticFrame(icon(), px)
41
+ const drawStatic = (ctx: CanvasRenderingContext2D, px: number) => {
42
+ ctx.clearRect(0, 0, px, px)
43
+ const still = staticFrame(icon(), px)
32
44
 
33
- if (still) ctx.drawImage(still, 0, 0)
34
- })
45
+ if (still) ctx.drawImage(still, 0, 0)
46
+ }
35
47
 
36
- const tick = (now: number) => {
37
- if (hovering && time === 0 && now - entered < REST_MS) {
38
- last = now
39
- frame = requestAnimationFrame(tick)
48
+ const drawAnimated = (ctx: CanvasRenderingContext2D, px: number) =>
49
+ drawProjectIcon(ctx, px, icon(), selectAvatarPaintTime(state, clock))
40
50
 
41
- return
42
- }
51
+ const dispatch = (event: AvatarAnimationEvent) => {
52
+ const prev = state
53
+ const next = transitionAvatarAnimation(prev, clock, event)
54
+ state = next.state
55
+
56
+ if (selectAvatarRunning(prev) !== selectAvatarRunning(state)) reconcile()
43
57
 
44
- const seconds = Math.min((now - last) / 1000, 0.1)
45
- last = now
46
- time = hovering ? time + seconds : time * Math.pow(0.002, seconds)
58
+ if (next.effect === "paint-static") paint(drawStatic)
47
59
 
48
- if (!hovering && time < 0.01) {
49
- time = 0
50
- frame = 0
51
- paintStatic()
60
+ if (next.effect === "paint-frame") paint(drawAnimated)
61
+ }
62
+
63
+ const reconcile = () => {
64
+ if (selectAvatarRunning(state)) {
65
+ stopMotionObserver = observeReducedMotion(onMotionChange)
66
+ frame = requestAnimationFrame(tick)
52
67
 
53
68
  return
54
69
  }
55
70
 
56
- paint((ctx, px) => drawProjectIcon(ctx, px, icon(), time))
57
- frame = requestAnimationFrame(tick)
71
+ cancelAnimationFrame(frame)
72
+ frame = 0
73
+ stopMotionObserver?.()
74
+ stopMotionObserver = undefined
58
75
  }
59
76
 
60
- const enter = () => {
61
- if (window.matchMedia?.("(prefers-reduced-motion: reduce)").matches) return
62
- hovering = true
77
+ const tick = (now: number) => {
78
+ frame = 0
79
+ frameEvent.now = now
80
+ dispatch(frameEvent)
81
+
82
+ if (selectAvatarRunning(state) && !frame) frame = requestAnimationFrame(tick)
83
+ }
63
84
 
64
- if (frame) return
65
- entered = last = performance.now()
66
- frame = requestAnimationFrame(tick)
85
+ const enter = () => {
86
+ enterEvent.now = performance.now()
87
+ enterEvent.reduced = prefersReducedMotion()
88
+ dispatch(enterEvent)
67
89
  }
68
90
 
69
- const leave = () => (hovering = false)
91
+ const leave = () => dispatch(AVATAR_POINTER_LEFT)
92
+
93
+ const onMotionChange = () => {
94
+ motionEvent.reduced = prefersReducedMotion()
95
+ dispatch(motionEvent)
96
+ }
70
97
 
71
98
  const target =
72
- canvas.closest<HTMLElement>(HOVER_TARGET) ?? canvas.closest<HTMLElement>('[data-component="project-avatar-v2"]') ?? canvas
99
+ canvas.closest<HTMLElement>(HOVER_TARGET) ??
100
+ canvas.closest<HTMLElement>('[data-component="project-avatar-v2"]') ??
101
+ canvas
73
102
 
74
103
  target.addEventListener("pointerenter", enter)
75
104
  target.addEventListener("pointerleave", leave)
76
105
 
77
106
  return {
78
107
  /** Repaints the static frame unless the avatar is animating, e.g. after the icon changed. */
79
- refresh: () => !frame && paintStatic(),
108
+ refresh: () => dispatch(AVATAR_REFRESH),
80
109
  dispose: () => {
81
- cancelAnimationFrame(frame)
110
+ dispatch(AVATAR_DISPOSED)
82
111
  target.removeEventListener("pointerenter", enter)
83
112
  target.removeEventListener("pointerleave", leave)
84
113
  },
@@ -0,0 +1,115 @@
1
+ export type ToastRegistryEntry<O> = {
2
+ readonly id: number
3
+ /** Same title, description, variant, timing and action labels coalesce into one toast. */
4
+ readonly key: string
5
+ readonly options: O
6
+ }
7
+
8
+ /**
9
+ * The toasts `showToast` and `toaster` have published and not yet seen close. Each entry lives from its publish
10
+ * until solid-sonner reports it closed (`onDismiss`, `onAutoClose`), `toaster.dismiss` closes it, or a later show
11
+ * finds it missing from solid-sonner's live toasts.
12
+ */
13
+ export type ToastRegistryState<O> = {
14
+ /** Last allocated id. IDs count down from `-1`: solid-sonner treats a falsy id as "dismiss every toast". */
15
+ readonly nextId: number
16
+ readonly entries: readonly ToastRegistryEntry<O>[]
17
+ }
18
+
19
+ export type ToastShownEvent<O> = {
20
+ readonly type: "toast.shown"
21
+ readonly key: string
22
+ readonly options: O
23
+ /** IDs solid-sonner still holds, from `toast.getToasts()`, which also lists toasts other code shows. */
24
+ readonly liveIds: ReadonlySet<number | string>
25
+ /** The newest of them, shown in front. */
26
+ readonly topmostLiveId: number | string | undefined
27
+ }
28
+
29
+ export type ToastRegistryEvent<O> =
30
+ | { readonly type: "custom.shown" }
31
+ | ToastShownEvent<O>
32
+ | { readonly type: "toast.released"; readonly id: number }
33
+ | { readonly type: "toast.dismissed"; readonly id?: number }
34
+
35
+ export type ToastRegistryEffect<O> =
36
+ | { readonly type: "sonner.publish"; readonly id: number; readonly options: O }
37
+ | { readonly type: "sonner.dismiss"; readonly id?: number }
38
+ | { readonly type: "dom.pulse"; readonly id: number }
39
+
40
+ export type ToastRegistryTransition<O> = {
41
+ readonly state: ToastRegistryState<O>
42
+ /** The toast a `toast.shown` event showed. */
43
+ readonly id?: number
44
+ readonly effects: readonly ToastRegistryEffect<O>[]
45
+ }
46
+
47
+ export function createToastRegistryState<O>(): ToastRegistryState<O> {
48
+ return { nextId: 0, entries: [] }
49
+ }
50
+
51
+ export function transitionToastRegistry<O>(
52
+ state: ToastRegistryState<O>,
53
+ event: ToastShownEvent<O>,
54
+ ): ToastRegistryTransition<O> & { readonly id: number }
55
+ export function transitionToastRegistry<O>(
56
+ state: ToastRegistryState<O>,
57
+ event: ToastRegistryEvent<O>,
58
+ ): ToastRegistryTransition<O>
59
+ export function transitionToastRegistry<O>(
60
+ state: ToastRegistryState<O>,
61
+ event: ToastRegistryEvent<O>,
62
+ ): ToastRegistryTransition<O> {
63
+ // A custom toast only takes an id: its caller owns its content and dismisses it through `toaster.dismiss`.
64
+ if (event.type === "custom.shown") return { state: { ...state, nextId: state.nextId - 1 }, effects: [] }
65
+
66
+ if (event.type === "toast.released") return { state: remove(state, event.id), effects: [] }
67
+
68
+ if (event.type === "toast.dismissed") {
69
+ const next = event.id === undefined ? { nextId: state.nextId, entries: [] } : remove(state, event.id)
70
+
71
+ return { state: next, effects: [{ type: "sonner.dismiss", id: event.id }] }
72
+ }
73
+
74
+ // An entry solid-sonner no longer holds was dismissed behind the registry's back.
75
+ const live = state.entries.filter((entry) => event.liveIds.has(entry.id))
76
+ const match = live.find((entry) => entry.key === event.key)
77
+
78
+ // The same toast is still in front: update it in place and pulse it rather than stacking a copy.
79
+ if (match && match.id === event.topmostLiveId) {
80
+ return {
81
+ state: {
82
+ nextId: state.nextId,
83
+ entries: live.map((entry) => (entry === match ? { ...entry, options: event.options } : entry)),
84
+ },
85
+ id: match.id,
86
+ effects: [
87
+ { type: "sonner.publish", id: match.id, options: event.options },
88
+ { type: "dom.pulse", id: match.id },
89
+ ],
90
+ }
91
+ }
92
+
93
+ // A buried copy moves to the front as a new toast.
94
+ const id = state.nextId - 1
95
+ const rest = match ? live.filter((entry) => entry !== match) : live
96
+
97
+ return {
98
+ state: { nextId: id, entries: [...rest, { id, key: event.key, options: event.options }] },
99
+ id,
100
+ effects: [
101
+ ...(match ? [{ type: "sonner.dismiss", id: match.id } as const] : []),
102
+ { type: "sonner.publish", id, options: event.options },
103
+ ],
104
+ }
105
+ }
106
+
107
+ export function selectToastOptions<O>(state: ToastRegistryState<O>, id: number) {
108
+ return state.entries.find((entry) => entry.id === id)?.options
109
+ }
110
+
111
+ function remove<O>(state: ToastRegistryState<O>, id: number) {
112
+ if (!state.entries.some((entry) => entry.id === id)) return state
113
+
114
+ return { nextId: state.nextId, entries: state.entries.filter((entry) => entry.id !== id) }
115
+ }
@@ -8,6 +8,13 @@ import { useI18n } from "../../context/i18n"
8
8
  import "../../actions/button/button.css"
9
9
  import "./toast.css"
10
10
  import { prefersReducedMotion } from "../../motion"
11
+ import {
12
+ createToastRegistryState,
13
+ selectToastOptions,
14
+ transitionToastRegistry,
15
+ type ToastRegistryEvent,
16
+ type ToastRegistryTransition,
17
+ } from "./machine"
11
18
 
12
19
  export interface ToastRegionProps extends ToasterProps {}
13
20
 
@@ -127,8 +134,6 @@ export const Toast = Object.assign(ToastRoot, {
127
134
  CloseButton: ToastCloseButton,
128
135
  })
129
136
 
130
- let toastV2Id = 0
131
-
132
137
  export const toaster = {
133
138
  show(
134
139
  render: (props: { toastId: number }) => JSX.Element,
@@ -139,7 +144,8 @@ export const toaster = {
139
144
  resize?: () => void
140
145
  },
141
146
  ) {
142
- const toastId = --toastV2Id
147
+ dispatchRegistry({ type: "custom.shown" })
148
+ const toastId = registry.nextId
143
149
  toast.custom((id) => render({ toastId: Number(id) }), {
144
150
  id: toastId,
145
151
  className: "toast-v2",
@@ -160,14 +166,9 @@ export const toaster = {
160
166
  return toastId
161
167
  },
162
168
  dismiss(toastId?: number) {
163
- if (toastId === undefined) {
164
- activeToastByKey.clear()
165
- activeToastById.clear()
166
- } else {
167
- releaseToast(activeToastById.get(toastId))
168
- }
169
+ dispatchRegistry({ type: "toast.dismissed", id: toastId })
169
170
 
170
- return toast.dismiss(toastId)
171
+ return toastId
171
172
  },
172
173
  }
173
174
 
@@ -188,16 +189,23 @@ export interface ToastOptions {
188
189
  actions?: ToastAction[]
189
190
  }
190
191
 
191
- interface ActiveToast {
192
- id: number
193
- key: string
194
- options: ToastOptions
195
- actions?: JSX.Element
192
+ let registry = createToastRegistryState<ToastOptions>()
193
+
194
+ function dispatchRegistry(event: ToastRegistryEvent<ToastOptions>) {
195
+ applyRegistry(transitionToastRegistry(registry, event))
196
196
  }
197
197
 
198
- const activeToastByKey = new Map<string, ActiveToast>()
198
+ function applyRegistry<T extends ToastRegistryTransition<ToastOptions>>(transition: T) {
199
+ registry = transition.state
200
+ transition.effects.forEach((effect) => {
201
+ if (effect.type === "sonner.publish") return publishToast(effect.id, effect.options)
199
202
 
200
- const activeToastById = new Map<number, ActiveToast>()
203
+ if (effect.type === "sonner.dismiss") return toast.dismiss(effect.id)
204
+ pulseToast(effect.id)
205
+ })
206
+
207
+ return transition
208
+ }
201
209
 
202
210
  export function showToast(options: ToastOptions | string) {
203
211
  // SAFETY: `options` is declared `ToastOptions | string`; `typeof` separates the string shorthand from the object.
@@ -213,56 +221,48 @@ export function showToast(options: ToastOptions | string) {
213
221
  actions: opts.actions?.map((action) => [action.label, action.variant]),
214
222
  })
215
223
 
216
- const active = activeToastByKey.get(key)
217
224
  const toasts = toast.getToasts()
218
225
 
219
- if (active && toasts.at(-1)?.id === active.id) {
220
- active.options = opts
221
- publishToast(active)
222
- pulseToast(active.id)
223
-
224
- return active.id
225
- }
226
-
227
- if (active && toasts.some((item) => item.id === active.id)) toaster.dismiss(active.id)
228
- releaseToast(active)
229
-
230
- const entry: ActiveToast = { id: --toastV2Id, key, options: opts }
231
- entry.actions = createToastActions(entry)
232
- activeToastByKey.set(key, entry)
233
- activeToastById.set(entry.id, entry)
234
- publishToast(entry)
235
-
236
- return entry.id
226
+ return applyRegistry(
227
+ transitionToastRegistry(registry, {
228
+ type: "toast.shown",
229
+ key,
230
+ options: opts,
231
+ liveIds: new Set(toasts.map((item) => item.id)),
232
+ topmostLiveId: toasts.at(-1)?.id,
233
+ }),
234
+ ).id
237
235
  }
238
236
 
239
- function publishToast(entry: ActiveToast) {
240
- const release = () => releaseToast(entry)
241
- toast(entry.options.title ?? "", {
242
- id: entry.id,
243
- description: entry.options.description,
237
+ function publishToast(id: number, options: ToastOptions) {
238
+ // solid-sonner calls these as the toast starts to leave, 200ms before it drops the toast from `getToasts()`.
239
+ const release = () => void dispatchRegistry({ type: "toast.released", id })
240
+ // `toast.message` updates a toast with the same id in place; `toast()` would append a duplicate record.
241
+ toast.message(options.title ?? "", {
242
+ id,
243
+ description: options.description,
244
244
  // SAFETY: solid-sonner inserts `icon` as a JSX child, and Solid calls a function child under the toast's render
245
245
  // owner; solid-sonner's type omits function children.
246
- icon: entry.options.icon as JSX.Element,
247
- action: entry.actions,
246
+ icon: options.icon as JSX.Element,
247
+ action: createToastActions(id, options.actions),
248
248
  closeButton: true,
249
- duration: entry.options.persistent ? Number.POSITIVE_INFINITY : entry.options.duration,
250
- className: `toast-v2 toast-v2--${entry.options.variant ?? "default"}`,
251
- testId: `toast-v2-${entry.id}`,
249
+ duration: options.persistent ? Number.POSITIVE_INFINITY : options.duration,
250
+ className: `toast-v2 toast-v2--${options.variant ?? "default"}`,
251
+ testId: `toast-v2-${id}`,
252
252
  unstyled: true,
253
253
  onDismiss: release,
254
254
  onAutoClose: release,
255
255
  })
256
256
  }
257
257
 
258
- function createToastActions(entry: ActiveToast) {
259
- if (!entry.options.actions?.length) return undefined
258
+ function createToastActions(id: number, actions: ToastAction[] | undefined) {
259
+ if (!actions?.length) return undefined
260
260
 
261
261
  return (
262
262
  <Toast.Actions>
263
263
  {/* Static map, not <For>: this JSX is created imperatively outside any Solid
264
264
  root, where a <For> computation would never be disposed. */}
265
- {entry.options.actions.map((action, index) => (
265
+ {actions.map((action, index) => (
266
266
  <button
267
267
  type="button"
268
268
  data-component="button-v2"
@@ -270,10 +270,14 @@ function createToastActions(entry: ActiveToast) {
270
270
  data-size="small"
271
271
  data-action-variant={action.variant ?? "primary"}
272
272
  onClick={() => {
273
- const onClick = entry.options.actions?.[index]?.onClick
273
+ // A toast that already closed, such as on a second click during its exit animation, runs nothing.
274
+ const options = selectToastOptions(registry, id)
275
+
276
+ if (!options) return
277
+ const onClick = options.actions?.[index]?.onClick
274
278
 
275
279
  if (onClick && onClick !== "dismiss") onClick()
276
- toaster.dismiss(entry.id)
280
+ toaster.dismiss(id)
277
281
  }}
278
282
  >
279
283
  {action.label}
@@ -293,14 +297,6 @@ function pulseToast(toastId: number) {
293
297
  })
294
298
  }
295
299
 
296
- function releaseToast(entry: ActiveToast | undefined) {
297
- if (!entry) return
298
-
299
- if (activeToastByKey.get(entry.key) === entry) activeToastByKey.delete(entry.key)
300
-
301
- if (activeToastById.get(entry.id) === entry) activeToastById.delete(entry.id)
302
- }
303
-
304
300
  export interface ToastPromiseOptions<T, U = unknown> {
305
301
  loading?: JSX.Element
306
302
  success?: (data: T) => JSX.Element
@@ -0,0 +1,81 @@
1
+ /**
2
+ * The preview a `<Select>` shows for its highlighted option (`onHighlight`, which may return an undo). Unlike a one-shot
3
+ * palette, a select opens and closes repeatedly: choosing the previewed option keeps its preview, choosing another
4
+ * reverts it first, and closing without a choice reverts it. Nothing previews while the menu is closed or closing.
5
+ */
6
+ export type SelectHighlightState =
7
+ | { readonly status: "closed" }
8
+ | { readonly status: "idle" }
9
+ | { readonly status: "previewing"; readonly key: string }
10
+ | { readonly status: "committed" }
11
+ | { readonly status: "disposed" }
12
+
13
+ export type SelectHighlightEvent =
14
+ | { readonly type: "open.changed"; readonly open: boolean }
15
+ | { readonly type: "highlight.changed"; readonly key: string; readonly previewable: boolean }
16
+ /** `closing` is whether the menu closes on this choice (`closeOnSelection`). */
17
+ | { readonly type: "option.selected"; readonly key: string | undefined; readonly closing: boolean }
18
+ | { readonly type: "disposed" }
19
+
20
+ export type SelectHighlightEffect =
21
+ | { readonly type: "preview.apply"; readonly key: string }
22
+ | { readonly type: "preview.revert" }
23
+
24
+ export type SelectHighlightTransition = {
25
+ readonly state: SelectHighlightState
26
+ readonly effects: readonly SelectHighlightEffect[]
27
+ }
28
+
29
+ const CLOSED: SelectHighlightState = Object.freeze({ status: "closed" })
30
+
31
+ const IDLE: SelectHighlightState = Object.freeze({ status: "idle" })
32
+
33
+ const COMMITTED: SelectHighlightState = Object.freeze({ status: "committed" })
34
+
35
+ const DISPOSED: SelectHighlightState = Object.freeze({ status: "disposed" })
36
+
37
+ const NONE: readonly SelectHighlightEffect[] = Object.freeze([])
38
+
39
+ const REVERT: readonly SelectHighlightEffect[] = Object.freeze([{ type: "preview.revert" }])
40
+
41
+ export function createSelectHighlightState(open: boolean): SelectHighlightState {
42
+ return open ? IDLE : CLOSED
43
+ }
44
+
45
+ export function transitionSelectHighlight(
46
+ state: SelectHighlightState,
47
+ event: SelectHighlightEvent,
48
+ ): SelectHighlightTransition {
49
+ if (state.status === "disposed") return { state, effects: NONE }
50
+ const previewing = state.status === "previewing"
51
+
52
+ if (event.type === "disposed") return { state: DISPOSED, effects: previewing ? REVERT : NONE }
53
+
54
+ if (event.type === "open.changed") {
55
+ if (event.open)
56
+ return { state: state.status === "closed" || state.status === "committed" ? IDLE : state, effects: NONE }
57
+
58
+ return { state: CLOSED, effects: previewing ? REVERT : NONE }
59
+ }
60
+
61
+ if (event.type === "option.selected") {
62
+ // The chosen option's preview is the committed value; any other preview reverts before the caller commits.
63
+ const effects = previewing && (event.key === undefined || state.key !== event.key) ? REVERT : NONE
64
+
65
+ if (!event.closing) return { state: IDLE, effects }
66
+
67
+ return { state: state.status === "closed" ? CLOSED : COMMITTED, effects }
68
+ }
69
+
70
+ // A closed or closing menu still delivers focus and pointer events to its items (forceMount, exit animation).
71
+ if (state.status === "closed" || state.status === "committed") return { state, effects: NONE }
72
+
73
+ if (!event.previewable) return previewing ? { state: IDLE, effects: REVERT } : { state, effects: NONE }
74
+
75
+ if (previewing && state.key === event.key) return { state, effects: NONE }
76
+
77
+ return {
78
+ state: { status: "previewing", key: event.key },
79
+ effects: [...(previewing ? REVERT : NONE), { type: "preview.apply", key: event.key }],
80
+ }
81
+ }
@@ -10,8 +10,19 @@ import {
10
10
  Trigger,
11
11
  Value,
12
12
  } from "@kobalte/core/select"
13
- import { Show, createMemo, onCleanup, splitProps, type ComponentProps, type JSX } from "solid-js"
13
+ import {
14
+ Show,
15
+ createComputed,
16
+ createMemo,
17
+ on,
18
+ onCleanup,
19
+ splitProps,
20
+ untrack,
21
+ type ComponentProps,
22
+ type JSX,
23
+ } from "solid-js"
14
24
  import { MenuScroll } from "../../components/menu-scroll"
25
+ import { createSelectHighlightState, transitionSelectHighlight, type SelectHighlightEvent } from "./machine"
15
26
  import "./select.css"
16
27
 
17
28
  function groupOptions<T>(options: T[], groupBy?: (x: T) => string): { category: string; options: T[] }[] {
@@ -80,8 +91,6 @@ export type SelectProps<T> = Omit<
80
91
  contentClass?: string
81
92
  }
82
93
 
83
- type HighlightState = { key?: string; cleanup?: void | (() => void) }
84
-
85
94
  export function Select<T>(props: SelectProps<T>) {
86
95
  const [local, others] = splitProps(props, [
87
96
  "class",
@@ -111,36 +120,46 @@ export function Select<T>(props: SelectProps<T>) {
111
120
  "fitViewport",
112
121
  ])
113
122
 
114
- const state: HighlightState = {}
123
+ let highlight = createSelectHighlightState(untrack(() => others.open ?? others.defaultOpen ?? false))
124
+ // The highlighted item and the undo its preview returned; the machine decides when each runs.
125
+ let highlighted: T | undefined
126
+ let revert: void | (() => void)
115
127
 
116
128
  let scroller: HTMLDivElement | undefined
117
129
 
118
- const stop = () => {
119
- state.cleanup?.()
120
- state.cleanup = undefined
121
- state.key = undefined
122
- }
123
-
124
- const keyFor = (item: T) => (local.value ? local.value(item) : String(item))
125
-
126
- const move = (item: T | undefined) => {
127
- if (!local.onHighlight) return
130
+ const dispatch = (event: SelectHighlightEvent) => {
131
+ const next = transitionSelectHighlight(highlight, event)
132
+ highlight = next.state
133
+ next.effects.forEach((effect) => {
134
+ if (effect.type === "preview.revert") {
135
+ const undo = revert
136
+ revert = undefined
128
137
 
129
- if (!item) {
130
- stop()
138
+ return undo?.()
139
+ }
131
140
 
132
- return
133
- }
141
+ revert = highlighted === undefined ? undefined : local.onHighlight?.(highlighted)
142
+ })
143
+ }
134
144
 
135
- const key = keyFor(item)
145
+ const keyFor = (item: T) => (local.value ? local.value(item) : String(item))
136
146
 
137
- if (state.key === key) return
138
- state.cleanup?.()
139
- state.cleanup = local.onHighlight(item)
140
- state.key = key
147
+ const move = (item: T) => {
148
+ highlighted = item
149
+ dispatch({ type: "highlight.changed", key: keyFor(item), previewable: !!local.onHighlight })
141
150
  }
142
151
 
143
- onCleanup(stop)
152
+ // A controlled menu closed by its owner does not call onOpenChange.
153
+ createComputed(
154
+ on(
155
+ () => others.open,
156
+ (open) => {
157
+ if (open !== undefined) dispatch({ type: "open.changed", open })
158
+ },
159
+ ),
160
+ )
161
+
162
+ onCleanup(() => dispatch({ type: "disposed" }))
144
163
 
145
164
  const grouped = createMemo(() => groupOptions(local.options, local.groupBy))
146
165
 
@@ -192,13 +211,16 @@ export function Select<T>(props: SelectProps<T>) {
192
211
  )}
193
212
  onChange={(next) => {
194
213
  const v = next == null ? null : Array.isArray(next) ? (next[0] ?? null) : next
214
+ dispatch({
215
+ type: "option.selected",
216
+ key: v === null ? undefined : keyFor(v),
217
+ closing: others.closeOnSelection ?? true,
218
+ })
195
219
  local.onSelect?.(v)
196
- stop()
197
220
  }}
198
221
  onOpenChange={(open) => {
222
+ if (others.open === undefined) dispatch({ type: "open.changed", open })
199
223
  local.onOpenChange?.(open)
200
-
201
- if (!open) stop()
202
224
  }}
203
225
  >
204
226
  <Trigger