@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
@@ -0,0 +1,214 @@
1
+ export const ANIMATED_NUMBER_TRACK_LENGTH = 30
2
+
3
+ /** Added to the measured transition time before a roll or resize that never reported its end settles anyway. */
4
+ export const ANIMATED_NUMBER_FALLBACK_PAD_MS = 100
5
+
6
+ /**
7
+ * `resizing` eases the width to `targetDigits` while extra leading places stay mounted to roll in or out. `attempt`
8
+ * names each eased change, so a fallback timer from an earlier one cannot cut the current one short.
9
+ */
10
+ export type AnimatedNumberState =
11
+ | {
12
+ readonly status: "static"
13
+ readonly attempt: number
14
+ readonly value: number
15
+ readonly direction: 1 | -1
16
+ readonly places: number
17
+ }
18
+ | {
19
+ readonly status: "resizing"
20
+ readonly attempt: number
21
+ readonly value: number
22
+ readonly direction: 1 | -1
23
+ readonly places: number
24
+ readonly targetDigits: number
25
+ }
26
+ | { readonly status: "disposed" }
27
+
28
+ /** `canAnimate` is false while detached or under reduced motion, where no transition runs to report its end. */
29
+ export type AnimatedNumberEvent =
30
+ | { readonly type: "value.changed"; readonly value: number; readonly canAnimate: boolean }
31
+ | { readonly type: "resize.ended" }
32
+ | { readonly type: "resize.timed-out"; readonly attempt: number }
33
+ | { readonly type: "disposed" }
34
+
35
+ export type AnimatedDigitState =
36
+ | { readonly status: "static"; readonly attempt: number; readonly digit: number; readonly step: number }
37
+ | { readonly status: "rolling"; readonly attempt: number; readonly digit: number; readonly step: number }
38
+ | { readonly status: "disposed" }
39
+
40
+ export type AnimatedDigitEvent =
41
+ | { readonly type: "digit.changed"; readonly digit: number; readonly direction: 1 | -1; readonly canAnimate: boolean }
42
+ | { readonly type: "roll.ended" }
43
+ | { readonly type: "roll.timed-out"; readonly attempt: number }
44
+ | { readonly type: "disposed" }
45
+
46
+ /** `watch` arms the fallback for an eased change; `clear` drops it once the change has settled. */
47
+ export type AnimatedNumberEffect = { readonly type: "watch"; readonly attempt: number } | { readonly type: "clear" }
48
+
49
+ export type AnimatedNumberTransition<State> = {
50
+ readonly state: State
51
+ readonly effects: readonly AnimatedNumberEffect[]
52
+ }
53
+
54
+ const NONE: readonly AnimatedNumberEffect[] = Object.freeze([])
55
+
56
+ const CLEAR: readonly AnimatedNumberEffect[] = Object.freeze([Object.freeze({ type: "clear" })])
57
+
58
+ const DISPOSED = Object.freeze({ status: "disposed" as const })
59
+
60
+ export function createAnimatedNumberState(value: number): AnimatedNumberState {
61
+ return { status: "static", attempt: 0, value, direction: 1, places: digits(value) + 1 }
62
+ }
63
+
64
+ export function transitionAnimatedNumber(
65
+ state: AnimatedNumberState,
66
+ event: AnimatedNumberEvent,
67
+ ): AnimatedNumberTransition<AnimatedNumberState> {
68
+ if (state.status === "disposed") return { state, effects: NONE }
69
+
70
+ switch (event.type) {
71
+ case "disposed":
72
+ return { state: DISPOSED, effects: state.status === "resizing" ? CLEAR : NONE }
73
+ case "value.changed": {
74
+ if (event.value === state.value) return { state, effects: NONE }
75
+ const direction = event.value > state.value ? 1 : -1
76
+ const count = digits(event.value)
77
+
78
+ if (!event.canAnimate)
79
+ return {
80
+ state: { status: "static", attempt: state.attempt, value: event.value, direction, places: count + 1 },
81
+ effects: state.status === "resizing" ? CLEAR : NONE,
82
+ }
83
+
84
+ // Only a change to the digit count eases the width, so a late font swap or zoom never animates it.
85
+ if (count === (state.status === "resizing" ? state.targetDigits : digits(state.value)))
86
+ return { state: { ...state, value: event.value, direction }, effects: NONE }
87
+
88
+ const attempt = state.attempt + 1
89
+
90
+ return {
91
+ state: {
92
+ status: "resizing",
93
+ attempt,
94
+ value: event.value,
95
+ direction,
96
+ places: Math.max(state.places, count + 1),
97
+ targetDigits: count,
98
+ },
99
+ effects: [{ type: "watch", attempt }],
100
+ }
101
+ }
102
+
103
+ case "resize.ended":
104
+ return settleNumber(state)
105
+ case "resize.timed-out":
106
+ if (state.status !== "resizing" || event.attempt !== state.attempt) return { state, effects: NONE }
107
+
108
+ return settleNumber(state)
109
+ }
110
+ }
111
+
112
+ export function createAnimatedDigitState(digit: number): AnimatedDigitState {
113
+ return { status: "static", attempt: 0, digit, step: digit + 10 }
114
+ }
115
+
116
+ export function transitionAnimatedDigit(
117
+ state: AnimatedDigitState,
118
+ event: AnimatedDigitEvent,
119
+ ): AnimatedNumberTransition<AnimatedDigitState> {
120
+ if (state.status === "disposed") return { state, effects: NONE }
121
+
122
+ switch (event.type) {
123
+ case "disposed":
124
+ return { state: DISPOSED, effects: state.status === "rolling" ? CLEAR : NONE }
125
+ case "digit.changed": {
126
+ const delta = spin(state.digit, event.digit, event.direction)
127
+
128
+ // An unchanged digit keeps any roll it is in the middle of.
129
+ if (!delta) return { state, effects: NONE }
130
+ const target = state.step + delta
131
+
132
+ // Rapid changes can run off the track, so they settle at once like a digit that cannot animate.
133
+ if (!event.canAnimate || target < 0 || target >= ANIMATED_NUMBER_TRACK_LENGTH)
134
+ return {
135
+ state: { status: "static", attempt: state.attempt, digit: event.digit, step: event.digit + 10 },
136
+ effects: state.status === "rolling" ? CLEAR : NONE,
137
+ }
138
+
139
+ const attempt = state.attempt + 1
140
+
141
+ return {
142
+ state: { status: "rolling", attempt, digit: event.digit, step: target },
143
+ effects: [{ type: "watch", attempt }],
144
+ }
145
+ }
146
+
147
+ case "roll.ended":
148
+ return settleDigit(state)
149
+ case "roll.timed-out":
150
+ if (state.status !== "rolling" || event.attempt !== state.attempt) return { state, effects: NONE }
151
+
152
+ return settleDigit(state)
153
+ }
154
+ }
155
+
156
+ export function selectAnimatedNumberValue(state: AnimatedNumberState) {
157
+ return state.status === "disposed" ? 0 : state.value
158
+ }
159
+
160
+ export function selectAnimatedNumberDirection(state: AnimatedNumberState) {
161
+ return state.status === "disposed" ? 1 : state.direction
162
+ }
163
+
164
+ export function selectAnimatedNumberPlaces(state: AnimatedNumberState) {
165
+ return state.status === "disposed" ? 1 : state.places
166
+ }
167
+
168
+ export function selectAnimatedNumberResizing(state: AnimatedNumberState) {
169
+ return state.status === "resizing"
170
+ }
171
+
172
+ export function selectAnimatedDigitRolling(state: AnimatedDigitState) {
173
+ return state.status === "rolling"
174
+ }
175
+
176
+ export function selectAnimatedDigitStep(state: AnimatedDigitState) {
177
+ return state.status === "disposed" ? 10 : state.step
178
+ }
179
+
180
+ function settleNumber(state: Exclude<AnimatedNumberState, { status: "disposed" }>) {
181
+ if (state.status !== "resizing") return { state, effects: NONE }
182
+
183
+ return {
184
+ state: {
185
+ status: "static" as const,
186
+ attempt: state.attempt,
187
+ value: state.value,
188
+ direction: state.direction,
189
+ places: state.targetDigits + 1,
190
+ },
191
+ effects: CLEAR,
192
+ }
193
+ }
194
+
195
+ function settleDigit(state: Exclude<AnimatedDigitState, { status: "disposed" }>) {
196
+ if (state.status !== "rolling") return { state, effects: NONE }
197
+
198
+ return {
199
+ state: { status: "static" as const, attempt: state.attempt, digit: state.digit, step: state.digit + 10 },
200
+ effects: CLEAR,
201
+ }
202
+ }
203
+
204
+ function digits(value: number) {
205
+ return String(value).length
206
+ }
207
+
208
+ function spin(from: number, to: number, direction: 1 | -1) {
209
+ if (from === to) return 0
210
+
211
+ if (direction > 0) return (to - from + 10) % 10
212
+
213
+ return -((from - to + 10) % 10)
214
+ }
@@ -1,70 +1,73 @@
1
- import { For, createEffect, createMemo, on } from "solid-js"
2
- import { createStore } from "solid-js/store"
3
-
4
- const TRACK = Array.from({ length: 30 }, (_, index) => index % 10)
1
+ import { For, createEffect, createMemo, createSignal, on, onCleanup, untrack } from "solid-js"
2
+ import { prefersReducedMotion } from "../motion/reduced"
3
+ import {
4
+ ANIMATED_NUMBER_FALLBACK_PAD_MS,
5
+ ANIMATED_NUMBER_TRACK_LENGTH,
6
+ createAnimatedDigitState,
7
+ createAnimatedNumberState,
8
+ selectAnimatedDigitRolling,
9
+ selectAnimatedDigitStep,
10
+ selectAnimatedNumberDirection,
11
+ selectAnimatedNumberPlaces,
12
+ selectAnimatedNumberResizing,
13
+ selectAnimatedNumberValue,
14
+ transitionAnimatedDigit,
15
+ transitionAnimatedNumber,
16
+ type AnimatedDigitEvent,
17
+ type AnimatedNumberEffect,
18
+ type AnimatedNumberEvent,
19
+ } from "./animated-number-machine"
20
+
21
+ const TRACK = Array.from({ length: ANIMATED_NUMBER_TRACK_LENGTH }, (_, index) => index % 10)
5
22
 
6
23
  const DURATION = 600
7
24
 
8
- function normalize(value: number) {
9
- return ((value % 10) + 10) % 10
10
- }
25
+ const ROLL_ENDED: AnimatedDigitEvent = { type: "roll.ended" }
11
26
 
12
- function spin(from: number, to: number, direction: 1 | -1) {
13
- if (from === to) return 0
27
+ const RESIZE_ENDED: AnimatedNumberEvent = { type: "resize.ended" }
14
28
 
15
- if (direction > 0) return (to - from + 10) % 10
29
+ function Digit(props: { value: number; direction: 1 | -1 }) {
30
+ const [digit, setDigit] = createSignal(createAnimatedDigitState(props.value))
31
+ let strip: HTMLSpanElement | undefined
16
32
 
17
- return -((from - to + 10) % 10)
18
- }
33
+ const fallback = createFallback(
34
+ () => strip,
35
+ (attempt) => dispatch({ type: "roll.timed-out", attempt }),
36
+ )
19
37
 
20
- function Digit(props: { value: number; direction: 1 | -1 }) {
21
- const [state, setState] = createStore({
22
- step: props.value + 10,
23
- animating: false,
24
- })
38
+ const dispatch = (event: AnimatedDigitEvent) => {
39
+ const prev = untrack(digit)
40
+ const next = transitionAnimatedDigit(prev, event)
25
41
 
26
- const step = () => state.step
27
- const animating = () => state.animating
28
- let last = props.value
29
- let strip: HTMLSpanElement | undefined
42
+ if (next.state !== prev) setDigit(next.state)
43
+ next.effects.forEach(fallback)
44
+ }
30
45
 
31
46
  createEffect(
32
47
  on(
33
48
  () => props.value,
34
- (next) => {
35
- const delta = spin(last, next, props.direction)
36
- last = next
37
-
38
- // An unchanged digit keeps any roll it is in the middle of.
39
- if (!delta) return
40
-
41
- const target = step() + delta
42
-
43
- // A detached digit never finishes a roll, and rapid changes can run off the track, so both settle at once.
44
- if (!strip?.isConnected || target < 0 || target >= TRACK.length) {
45
- setState({ animating: false, step: next + 10 })
46
-
47
- return
48
- }
49
-
50
- setState({ animating: true, step: target })
51
- },
49
+ (value) =>
50
+ dispatch({ type: "digit.changed", digit: value, direction: props.direction, canAnimate: canAnimate(strip) }),
52
51
  { defer: true },
53
52
  ),
54
53
  )
55
54
 
55
+ onCleanup(() => dispatch({ type: "disposed" }))
56
+
57
+ const ended = (event: TransitionEvent) => {
58
+ if (transitionEnded(event, strip, "top")) dispatch(ROLL_ENDED)
59
+ }
60
+
56
61
  return (
57
- <span data-slot="animated-number-digit" data-animating={animating() ? "true" : "false"}>
62
+ <span data-slot="animated-number-digit" data-animating={selectAnimatedDigitRolling(digit()) ? "true" : "false"}>
58
63
  <span data-slot="animated-number-static" data-digit={props.value} />
59
64
  <span
60
65
  ref={strip}
61
66
  data-slot="animated-number-strip"
62
- onTransitionEnd={() => {
63
- setState("animating", false)
64
- setState("step", (value) => normalize(value) + 10)
65
- }}
67
+ onTransitionEnd={ended}
68
+ onTransitionCancel={ended}
66
69
  style={{
67
- "--animated-number-offset": `${step()}`,
70
+ "--animated-number-offset": `${selectAnimatedDigitStep(digit())}`,
68
71
  "--animated-number-duration": `var(--tool-motion-odometer-ms, ${DURATION}ms)`,
69
72
  }}
70
73
  >
@@ -83,50 +86,39 @@ export function AnimatedNumber(props: { value: number; class?: string }) {
83
86
 
84
87
  // A spare leading zero waits outside the clipped width to roll in. A digit that leaves stays until the width has
85
88
  // shrunk past it, so it rolls to zero instead of vanishing.
86
- const [state, setState] = createStore<{ value: number; direction: 1 | -1; places: number; resizing: boolean }>({
87
- value: target(),
88
- direction: 1,
89
- places: String(target()).length + 1,
90
- resizing: false,
91
- })
92
-
93
- const value = () => state.value
94
- const direction = () => state.direction
89
+ const [number, setNumber] = createSignal(createAnimatedNumberState(target()))
95
90
  let box: HTMLSpanElement | undefined
96
91
 
97
- createEffect(
98
- on(
99
- target,
100
- (next) => {
101
- const current = value()
102
-
103
- if (next === current) return
104
-
105
- const digits = String(next).length
92
+ const fallback = createFallback(
93
+ () => box,
94
+ (attempt) => dispatch({ type: "resize.timed-out", attempt }),
95
+ )
106
96
 
107
- // A detached number cannot ease its width and would never hear it end, so it settles at once.
108
- if (!box?.isConnected) {
109
- setState({ direction: next > current ? 1 : -1, value: next, places: digits + 1, resizing: false })
97
+ const dispatch = (event: AnimatedNumberEvent) => {
98
+ const prev = untrack(number)
99
+ const next = transitionAnimatedNumber(prev, event)
110
100
 
111
- return
112
- }
101
+ if (next.state !== prev) setNumber(next.state)
102
+ next.effects.forEach(fallback)
103
+ }
113
104
 
114
- // Only a change to the digit count eases the width, so a late font swap or zoom never animates it.
115
- setState({
116
- direction: next > current ? 1 : -1,
117
- value: next,
118
- places: Math.max(state.places, digits + 1),
119
- resizing: state.resizing || digits !== String(current).length,
120
- })
121
- },
122
- { defer: true },
123
- ),
105
+ createEffect(
106
+ on(target, (value) => dispatch({ type: "value.changed", value, canAnimate: canAnimate(box) }), { defer: true }),
124
107
  )
125
108
 
109
+ onCleanup(() => dispatch({ type: "disposed" }))
110
+
111
+ const value = () => selectAnimatedNumberValue(number())
112
+ const direction = () => selectAnimatedNumberDirection(number())
126
113
  const label = createMemo(() => value().toString())
114
+ const count = createMemo(() => selectAnimatedNumberPlaces(number()))
127
115
 
128
116
  // Place values, most significant first. Keying by place keeps each digit rolling as digits appear and leave.
129
- const places = createMemo(() => Array.from({ length: state.places }, (_, index) => state.places - 1 - index))
117
+ const places = createMemo(() => Array.from({ length: count() }, (_, index) => count() - 1 - index))
118
+
119
+ const ended = (event: TransitionEvent) => {
120
+ if (transitionEnded(event, box, "width")) dispatch(RESIZE_ENDED)
121
+ }
130
122
 
131
123
  return (
132
124
  <span data-component="animated-number" class={props.class}>
@@ -135,12 +127,11 @@ export function AnimatedNumber(props: { value: number; class?: string }) {
135
127
  <span
136
128
  ref={box}
137
129
  data-slot="animated-number-value"
138
- data-resizing={state.resizing ? "true" : "false"}
130
+ data-resizing={selectAnimatedNumberResizing(number()) ? "true" : "false"}
139
131
  aria-hidden="true"
140
132
  style={{ "--animated-number-width": `${label().length}ch` }}
141
- onTransitionEnd={(event) => {
142
- if (event.target === event.currentTarget) setState({ places: label().length + 1, resizing: false })
143
- }}
133
+ onTransitionEnd={ended}
134
+ onTransitionCancel={ended}
144
135
  >
145
136
  <For each={places()}>
146
137
  {(place) => <Digit value={Math.floor(value() / 10 ** place) % 10} direction={direction()} />}
@@ -149,3 +140,63 @@ export function AnimatedNumber(props: { value: number; class?: string }) {
149
140
  </span>
150
141
  )
151
142
  }
143
+
144
+ // A detached element never runs a transition, and reduced motion runs them in 0 ms, which reports no end.
145
+ function canAnimate(element: HTMLElement | undefined) {
146
+ return element?.isConnected === true && !prefersReducedMotion()
147
+ }
148
+
149
+ // A change that retargets a running transition cancels the old one while the new one keeps going; only a transition
150
+ // with nothing left running on the property has ended.
151
+ function transitionEnded(event: TransitionEvent, element: HTMLElement | undefined, property: string) {
152
+ if (!element || event.target !== element || event.propertyName !== property) return false
153
+
154
+ if (event.type !== "transitioncancel") return true
155
+
156
+ return !element
157
+ .getAnimations()
158
+ .some(
159
+ (animation) =>
160
+ animation instanceof CSSTransition &&
161
+ animation.transitionProperty === property &&
162
+ animation.playState === "running",
163
+ )
164
+ }
165
+
166
+ /** Settles an eased change whose end event never arrives, a little after its transition should have finished. */
167
+ function createFallback(element: () => HTMLElement | undefined, timeout: (attempt: number) => void) {
168
+ let timer: ReturnType<typeof setTimeout> | undefined
169
+
170
+ return (effect: AnimatedNumberEffect) => {
171
+ clearTimeout(timer)
172
+ timer = undefined
173
+
174
+ if (effect.type === "clear") return
175
+ // The change's transition styles apply when Solid flushes this update, so measure after it.
176
+ queueMicrotask(() => {
177
+ clearTimeout(timer)
178
+ timer = setTimeout(() => timeout(effect.attempt), transitionMs(element()) + ANIMATED_NUMBER_FALLBACK_PAD_MS)
179
+ })
180
+ }
181
+ }
182
+
183
+ function transitionMs(element: HTMLElement | undefined) {
184
+ if (!element?.isConnected) return 0
185
+ const style = getComputedStyle(element)
186
+ const delays = style.transitionDelay.split(",")
187
+
188
+ return Math.max(
189
+ 0,
190
+ ...style.transitionDuration
191
+ .split(",")
192
+ .map((duration, index) => milliseconds(duration) + milliseconds(delays[index % delays.length])),
193
+ )
194
+ }
195
+
196
+ function milliseconds(value: string) {
197
+ const time = Number.parseFloat(value)
198
+
199
+ if (!Number.isFinite(time)) return 0
200
+
201
+ return value.trim().endsWith("ms") ? time : time * 1000
202
+ }
@@ -0,0 +1,198 @@
1
+ export type PopoverCloseReason = "escape" | "outside" | "control"
2
+
3
+ /**
4
+ * One popover's open state. `controlled` follows the `open` prop; `uncontrolled` owns it. A controlled popover that
5
+ * asked its owner to close stays open with `pendingDismiss` until the owner answers, so a refused close leaves no
6
+ * reason behind for a later close to read.
7
+ */
8
+ export type PopoverState =
9
+ | {
10
+ readonly status: "closed"
11
+ readonly mode: "controlled" | "uncontrolled"
12
+ /** Why it closed, until Kobalte decides where focus returns. Focus stays put after an outside press. */
13
+ readonly closeReason: PopoverCloseReason | null
14
+ }
15
+ | { readonly status: "open"; readonly mode: "uncontrolled" }
16
+ | { readonly status: "open"; readonly mode: "controlled"; readonly pendingDismiss: PopoverCloseReason | null }
17
+ | { readonly status: "disposed" }
18
+
19
+ export type PopoverEvent =
20
+ /** The `open` prop, read again right after every `onOpenChange` call: a controlled `true` refuses a close. */
21
+ | { readonly type: "props.synced"; readonly open: boolean | undefined }
22
+ /** The shared listener dismissed this popover. */
23
+ | { readonly type: "dismiss"; readonly reason: "escape" | "outside" }
24
+ /** Kobalte asked to open or close, from the trigger or the close button. */
25
+ | { readonly type: "kobalte.changed"; readonly open: boolean }
26
+ | { readonly type: "close-auto-focus.handled" }
27
+ | { readonly type: "disposed" }
28
+
29
+ export type PopoverEffect = { readonly type: "notify.open"; readonly open: boolean }
30
+
31
+ export type PopoverTransition = {
32
+ readonly state: PopoverState
33
+ readonly effects: readonly PopoverEffect[]
34
+ }
35
+
36
+ const NO_EFFECTS: readonly PopoverEffect[] = Object.freeze([])
37
+
38
+ const NOTIFY_OPEN: readonly PopoverEffect[] = Object.freeze([Object.freeze({ type: "notify.open", open: true })])
39
+
40
+ const NOTIFY_CLOSED: readonly PopoverEffect[] = Object.freeze([Object.freeze({ type: "notify.open", open: false })])
41
+
42
+ export function createPopoverState(open: boolean | undefined, defaultOpen: boolean | undefined): PopoverState {
43
+ if (open === true) return { status: "open", mode: "controlled", pendingDismiss: null }
44
+
45
+ if (open === false) return { status: "closed", mode: "controlled", closeReason: null }
46
+
47
+ if (defaultOpen) return { status: "open", mode: "uncontrolled" }
48
+
49
+ return { status: "closed", mode: "uncontrolled", closeReason: null }
50
+ }
51
+
52
+ export function transitionPopover(state: PopoverState, event: PopoverEvent): PopoverTransition {
53
+ if (state.status === "disposed") return { state, effects: NO_EFFECTS }
54
+
55
+ if (event.type === "disposed") return { state: { status: "disposed" }, effects: NO_EFFECTS }
56
+
57
+ if (event.type === "props.synced") return { state: syncProps(state, event.open), effects: NO_EFFECTS }
58
+
59
+ if (event.type === "close-auto-focus.handled") {
60
+ if (state.status !== "closed" || state.closeReason === null) return { state, effects: NO_EFFECTS }
61
+
62
+ return { state: { status: "closed", mode: state.mode, closeReason: null }, effects: NO_EFFECTS }
63
+ }
64
+
65
+ if (event.type === "kobalte.changed" && event.open) {
66
+ if (state.status === "open") return { state, effects: NO_EFFECTS }
67
+
68
+ if (state.mode === "controlled") return { state, effects: NOTIFY_OPEN }
69
+
70
+ return { state: { status: "open", mode: "uncontrolled" }, effects: NOTIFY_OPEN }
71
+ }
72
+
73
+ // A dismiss or Kobalte close from here on.
74
+ if (state.status === "closed") return { state, effects: NO_EFFECTS }
75
+
76
+ const reason = event.type === "dismiss" ? event.reason : "control"
77
+
78
+ if (state.mode === "uncontrolled") {
79
+ return { state: { status: "closed", mode: "uncontrolled", closeReason: reason }, effects: NOTIFY_CLOSED }
80
+ }
81
+
82
+ // Kobalte echoes a close it caused; the owner hears about it once.
83
+ if (state.pendingDismiss !== null) return { state, effects: NO_EFFECTS }
84
+
85
+ return { state: { status: "open", mode: "controlled", pendingDismiss: reason }, effects: NOTIFY_CLOSED }
86
+ }
87
+
88
+ export function selectPopoverOpen(state: PopoverState) {
89
+ return state.status === "open"
90
+ }
91
+
92
+ /** An outside press already moved focus where the user wanted it, so closing does not pull it back to the trigger. */
93
+ export function selectPreventCloseAutoFocus(state: PopoverState) {
94
+ return state.status === "closed" && state.closeReason === "outside"
95
+ }
96
+
97
+ function syncProps(state: Exclude<PopoverState, { status: "disposed" }>, open: boolean | undefined): PopoverState {
98
+ if (open === undefined) {
99
+ if (state.mode === "uncontrolled") return state
100
+
101
+ if (state.status === "open") return { status: "open", mode: "uncontrolled" }
102
+
103
+ return { status: "closed", mode: "uncontrolled", closeReason: state.closeReason }
104
+ }
105
+
106
+ if (open) {
107
+ if (state.status === "open" && state.mode === "controlled" && state.pendingDismiss === null) return state
108
+
109
+ return { status: "open", mode: "controlled", pendingDismiss: null }
110
+ }
111
+
112
+ if (state.status === "closed") {
113
+ if (state.mode === "controlled") return state
114
+
115
+ return { status: "closed", mode: "controlled", closeReason: state.closeReason }
116
+ }
117
+
118
+ return {
119
+ status: "closed",
120
+ mode: "controlled",
121
+ closeReason: state.mode === "controlled" ? (state.pendingDismiss ?? "control") : "control",
122
+ }
123
+ }
124
+
125
+ /** One open popover, and the popover it opened inside (portaled content is outside its parent in the DOM). */
126
+ export type PopoverStackEntry = {
127
+ readonly id: number
128
+ readonly parentId: number | null
129
+ }
130
+
131
+ /** Every open popover, in the order they opened. One shared set of window listeners routes Escape and outside presses. */
132
+ export type PopoverStackState = { readonly entries: readonly PopoverStackEntry[] }
133
+
134
+ export type PopoverStackEvent =
135
+ | { readonly type: "layer.opened"; readonly id: number; readonly parentId: number | null }
136
+ | { readonly type: "layer.closed"; readonly id: number }
137
+ | { readonly type: "escape.pressed" }
138
+ /** A press or focus landed; `insideIds` are the open popovers whose trigger or content contains it. */
139
+ | { readonly type: "outside.interacted"; readonly insideIds: ReadonlySet<number> }
140
+
141
+ export type PopoverStackEffect = {
142
+ readonly type: "dismiss.layer"
143
+ readonly id: number
144
+ readonly reason: "escape" | "outside"
145
+ }
146
+
147
+ export type PopoverStackTransition = {
148
+ readonly state: PopoverStackState
149
+ readonly effects: readonly PopoverStackEffect[]
150
+ }
151
+
152
+ const NO_STACK_EFFECTS: readonly PopoverStackEffect[] = Object.freeze([])
153
+
154
+ export const EMPTY_POPOVER_STACK: PopoverStackState = Object.freeze({ entries: Object.freeze([]) })
155
+
156
+ export function transitionPopoverStack(state: PopoverStackState, event: PopoverStackEvent): PopoverStackTransition {
157
+ if (event.type === "layer.opened") {
158
+ if (state.entries.some((entry) => entry.id === event.id)) return { state, effects: NO_STACK_EFFECTS }
159
+
160
+ return {
161
+ state: { entries: [...state.entries, { id: event.id, parentId: event.parentId }] },
162
+ effects: NO_STACK_EFFECTS,
163
+ }
164
+ }
165
+
166
+ if (event.type === "layer.closed") {
167
+ if (!state.entries.some((entry) => entry.id === event.id)) return { state, effects: NO_STACK_EFFECTS }
168
+ const entries = state.entries.filter((entry) => entry.id !== event.id)
169
+
170
+ return { state: entries.length === 0 ? EMPTY_POPOVER_STACK : { entries }, effects: NO_STACK_EFFECTS }
171
+ }
172
+
173
+ const top = state.entries.at(-1)
174
+
175
+ if (!top) return { state, effects: NO_STACK_EFFECTS }
176
+
177
+ if (event.type === "escape.pressed")
178
+ return { state, effects: [{ type: "dismiss.layer", id: top.id, reason: "escape" }] }
179
+
180
+ // A press inside a child keeps its ancestors open, even when the child's content is portaled outside them.
181
+ const kept = new Set<number>()
182
+
183
+ const keep = (id: number | null): void => {
184
+ if (id === null || kept.has(id)) return
185
+ kept.add(id)
186
+ keep(state.entries.find((entry) => entry.id === id)?.parentId ?? null)
187
+ }
188
+
189
+ event.insideIds.forEach(keep)
190
+
191
+ return {
192
+ state,
193
+ effects: state.entries
194
+ .filter((entry) => !kept.has(entry.id))
195
+ .reverse()
196
+ .map((entry) => ({ type: "dismiss.layer", id: entry.id, reason: "outside" }) as const),
197
+ }
198
+ }