@opencode/ui 0.0.0-dev-800 → 0.0.0-dev-821

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,5 +1,17 @@
1
- import type { Component, JSX } from "solid-js"
2
- import { createEffect, createMemo, createUniqueId, splitProps, Show } from "solid-js"
1
+ import type { Accessor, Component, JSX, Setter } from "solid-js"
2
+ import { createEffect, createMemo, createSignal, createUniqueId, splitProps, Show, untrack } from "solid-js"
3
+ import {
4
+ chooseFallbackIconName,
5
+ FILE_ICON_LOAD_TIMEOUT_MS,
6
+ FILE_ICON_REQUESTED,
7
+ INITIAL_FILE_ICON_SYMBOL_STATE,
8
+ READY_FILE_ICON_SYMBOL_STATE,
9
+ selectFileIconSymbol,
10
+ transitionFileIconSymbol,
11
+ type FileIconSymbolEffect,
12
+ type FileIconSymbolEvent,
13
+ type FileIconSymbolState,
14
+ } from "./file-icon-machine"
3
15
  import type { IconName } from "./file-icons/types"
4
16
 
5
17
  export type FileIconProps = JSX.GSVGAttributes<SVGSVGElement> & {
@@ -11,8 +23,13 @@ export type FileIconProps = JSX.GSVGAttributes<SVGSVGElement> & {
11
23
  export const FileIcon: Component<FileIconProps> = (props) => {
12
24
  const [local, rest] = splitProps(props, ["node", "class", "classList", "expanded", "mono"])
13
25
  const name = createMemo(() => chooseIconName(local.node.path, local.node.type, local.expanded || false))
26
+ const fallback = createMemo(() => chooseFallbackIconName(local.node.type, local.expanded || false))
27
+ const shown = createMemo(() => selectFileIconSymbol(symbol(name()).state(), name(), fallback()))
14
28
  const id = `file-icon-mono-${createUniqueId()}`
15
- createEffect(() => loadSymbol(name()))
29
+ createEffect(() => {
30
+ sprite()
31
+ dispatchSymbol(name(), FILE_ICON_REQUESTED)
32
+ })
16
33
 
17
34
  return (
18
35
  <svg
@@ -23,10 +40,10 @@ export const FileIcon: Component<FileIconProps> = (props) => {
23
40
  [local.class ?? ""]: !!local.class,
24
41
  }}
25
42
  >
26
- <Show when={local.mono} fallback={<use href={`#${symbolID(name())}`} />}>
43
+ <Show when={local.mono} fallback={<use href={`#${symbolID(shown())}`} />}>
27
44
  <defs>
28
45
  <mask id={id} mask-type="alpha">
29
- <use href={`#${symbolID(name())}`} />
46
+ <use href={`#${symbolID(shown())}`} />
30
47
  </mask>
31
48
  </defs>
32
49
  <rect width="100%" height="100%" fill="currentColor" mask={`url(#${id})`} />
@@ -39,23 +56,73 @@ export const FileIcon: Component<FileIconProps> = (props) => {
39
56
  // sprite cost several MB per copy. Each icon is instead a lazy chunk, copied once into a hidden in-document sprite.
40
57
  const spriteID = "file-icon-sprite"
41
58
 
42
- const symbolID = (name: IconName) => `file-icon-${name}`
59
+ const symbolID = (name: string) => `file-icon-${name}`
43
60
 
44
- const requested = new Set<IconName>()
61
+ const FALLBACK_ICONS = new Set<IconName>(["Document", "Folder", "FolderOpen"])
62
+
63
+ type SymbolEntry = {
64
+ state: Accessor<FileIconSymbolState>
65
+ setState: Setter<FileIconSymbolState>
66
+ timer?: ReturnType<typeof setTimeout>
67
+ }
68
+
69
+ const symbols = new Map<IconName, SymbolEntry>()
45
70
 
46
71
  let sources: Partial<Record<IconName, () => Promise<string>>> | undefined
47
72
 
48
- function loadSymbol(name: IconName) {
49
- if (requested.has(name)) return
50
- requested.add(name)
73
+ function symbol(name: IconName) {
74
+ const existing = symbols.get(name)
75
+
76
+ if (existing) return existing
77
+
78
+ const [state, setState] = createSignal(
79
+ FALLBACK_ICONS.has(name) ? READY_FILE_ICON_SYMBOL_STATE : INITIAL_FILE_ICON_SYMBOL_STATE,
80
+ )
81
+
82
+ const entry: SymbolEntry = { state, setState }
83
+ symbols.set(name, entry)
84
+
85
+ return entry
86
+ }
87
+
88
+ function dispatchSymbol(name: IconName, event: FileIconSymbolEvent) {
89
+ const entry = symbol(name)
90
+ const prev = untrack(entry.state)
91
+ const next = transitionFileIconSymbol(prev, event)
92
+
93
+ if (next.state !== prev) entry.setState(next.state)
94
+ // A `<use>` follows its target once the symbol appears, so mounted icons may switch before the insert.
95
+ next.effects.forEach((effect) => runSymbolEffect(name, entry, effect))
96
+ }
97
+
98
+ function runSymbolEffect(name: IconName, entry: SymbolEntry, effect: FileIconSymbolEffect) {
99
+ if (effect.type === "insert-symbol") return insertSymbol(name, effect.svg)
100
+
101
+ if (effect.type === "cancel-timeout") return clearTimeout(entry.timer)
102
+
103
+ // The fallbacks are bundled, so they never load lazily.
51
104
  sources ??= Object.fromEntries(
52
105
  Object.entries(
53
- import.meta.glob<string>("../assets/icons/file-types/*.svg", { query: "?raw", import: "default" }),
106
+ import.meta.glob<string>(
107
+ [
108
+ "../assets/icons/file-types/*.svg",
109
+ "!../assets/icons/file-types/document.svg",
110
+ "!../assets/icons/file-types/folder.svg",
111
+ "!../assets/icons/file-types/folder-open.svg",
112
+ ],
113
+ { query: "?raw", import: "default" },
114
+ ),
54
115
  ).map(([path, load]) => [toIconName(path), load]),
55
116
  )
56
- sources[name]?.()
57
- .then((text) => insertSymbol(name, text))
58
- .catch(() => requested.delete(name))
117
+ const load = sources[name]
118
+
119
+ if (!load) return dispatchSymbol(name, { type: "load.failed" })
120
+ // A dynamic import has no timeout of its own and can stall on a slow or dropped connection.
121
+ entry.timer = setTimeout(() => dispatchSymbol(name, { type: "load.timed-out" }), FILE_ICON_LOAD_TIMEOUT_MS)
122
+ load().then(
123
+ (svg) => dispatchSymbol(name, { type: "load.succeeded", svg }),
124
+ () => dispatchSymbol(name, { type: "load.failed" }),
125
+ )
59
126
  }
60
127
 
61
128
  // Mirrors the file name to icon name rule of the spritesheet generator that writes `file-icons/types.ts`.
@@ -67,8 +134,9 @@ function toIconName(path: string) {
67
134
  .join("")
68
135
  }
69
136
 
70
- function insertSymbol(name: IconName, text: string) {
137
+ function insertSymbol(name: string, text: string) {
71
138
  const id = symbolID(name)
139
+
72
140
  // Icons share the document now, so scope their internal ids (gradients, clip paths) and drop their unstyled
73
141
  // classes, which app CSS such as Tailwind utilities would otherwise match.
74
142
  const scoped = text
@@ -76,6 +144,7 @@ function insertSymbol(name: IconName, text: string) {
76
144
  .replace(/\sid="([^"]*)"/g, ` id="${id}-$1"`)
77
145
  .replace(/url\(#([^)]*)\)/g, `url(#${id}-$1)`)
78
146
  .replace(/href="#([^"]*)"/g, `href="#${id}-$1"`)
147
+
79
148
  const svg = new DOMParser().parseFromString(scoped, "image/svg+xml").documentElement
80
149
  const symbol = document.createElementNS("http://www.w3.org/2000/svg", "symbol")
81
150
  Array.from(svg.attributes)
@@ -100,6 +169,17 @@ function sprite() {
100
169
  svg.style.position = "absolute"
101
170
  svg.style.overflow = "hidden"
102
171
  document.body.insertBefore(svg, document.body.firstChild)
172
+ // The fallbacks ship with the component, so an icon whose own symbol fails to load always has one to show.
173
+ Object.entries(
174
+ import.meta.glob<string>(
175
+ [
176
+ "../assets/icons/file-types/document.svg",
177
+ "../assets/icons/file-types/folder.svg",
178
+ "../assets/icons/file-types/folder-open.svg",
179
+ ],
180
+ { query: "?raw", import: "default", eager: true },
181
+ ),
182
+ ).forEach(([path, text]) => insertSymbol(toIconName(path), text))
103
183
 
104
184
  return svg
105
185
  }
@@ -613,9 +693,15 @@ const ICON_MAPS: IconMaps = {
613
693
  const toOpenVariant = (icon: IconName): IconName => {
614
694
  if (!icon.startsWith("Folder")) return icon
615
695
 
616
- if (icon.endsWith("_light")) return icon.replace("_light", "Open_light") as IconName
696
+ if (icon.endsWith("_light")) {
697
+ // SAFETY: the icon generator writes an `Open` variant for every folder icon, light ones included.
698
+ return icon.replace("_light", "Open_light") as IconName
699
+ }
617
700
 
618
- if (!icon.endsWith("Open")) return (icon + "Open") as IconName
701
+ if (!icon.endsWith("Open")) {
702
+ // SAFETY: the icon generator writes an `Open` variant for every folder icon.
703
+ return (icon + "Open") as IconName
704
+ }
619
705
 
620
706
  return icon
621
707
  }
@@ -3,7 +3,7 @@ import { createEffect, createMemo, createSignal, For, type JSX, on, Show } from
3
3
  import { createStore } from "solid-js/store"
4
4
  import { makeEventListener } from "@solid-primitives/event-listener"
5
5
  import { useI18n } from "../context/i18n"
6
- import { listActive, listScrollTarget } from "../hooks/list-machine"
6
+ import { listActive, listScrollTarget, selectListEmptyState } from "../hooks/list-machine"
7
7
  import { Icon, type IconProps } from "@opencode/ui/icon"
8
8
  import { IconButton } from "@opencode/ui/icon-button"
9
9
  import { TextField } from "./text-field"
@@ -34,6 +34,8 @@ export interface ListProps<T> extends FilteredListProps<T> {
34
34
  children: (item: T) => JSX.Element
35
35
  emptyMessage?: string
36
36
  loadingMessage?: string
37
+ /** Shown when an async `items` loader rejects or times out. */
38
+ errorMessage?: string
37
39
  onKeyEvent?: (event: KeyboardEvent, item: T | undefined) => void
38
40
  onMove?: (item: T | undefined) => void
39
41
  activeIcon?: IconProps["name"]
@@ -155,11 +157,15 @@ export function List<T>(props: ListProps<T> & { ref?: (ref: ListRef) => void })
155
157
  }
156
158
 
157
159
  const emptyMessage = () => {
158
- if (list.grouped.loading) return props.loadingMessage ?? i18n.t("ui.list.loading")
160
+ const empty = selectListEmptyState(list.state())
161
+
162
+ if (empty.type === "loading") return props.loadingMessage ?? i18n.t("ui.list.loading")
163
+
164
+ if (empty.type === "failed") return props.errorMessage ?? i18n.t("ui.list.failed")
159
165
 
160
166
  if (props.emptyMessage) return props.emptyMessage
161
167
 
162
- const query = list.filter()
168
+ const query = empty.query
163
169
 
164
170
  if (!query) return i18n.t("ui.list.empty")
165
171
 
@@ -1,6 +1,20 @@
1
1
  import { createResizeObserver } from "@solid-primitives/resize-observer"
2
- import { onCleanup, onMount, Show, splitProps, type ComponentProps, type JSX } from "solid-js"
2
+ import { createSignal, onCleanup, onMount, Show, splitProps, untrack, type ComponentProps, type JSX } from "solid-js"
3
3
  import { createStore } from "solid-js/store"
4
+ import {
5
+ INITIAL_SCROLL_THUMB_STATE,
6
+ overflowChanged,
7
+ SCROLL_IDLE_ELAPSED,
8
+ SCROLL_IDLE_MS,
9
+ SCROLL_THUMB_DISPOSED,
10
+ SCROLLED,
11
+ selectDraggingAxis,
12
+ selectShowVerticalThumb,
13
+ selectThumbScrolling,
14
+ transitionScrollThumb,
15
+ type ScrollThumbEvent,
16
+ type ScrollThumbState,
17
+ } from "./scroll-view-machine"
4
18
  import "./menu-scroll.css"
5
19
 
6
20
  /**
@@ -17,24 +31,40 @@ export function MenuScroll(
17
31
  ) {
18
32
  const [local, rest] = splitProps(props, ["class", "children", "viewportClass", "viewportRef", "onScroll"])
19
33
 
20
- const [state, setState] = createStore<{
21
- size: number
22
- start: number
23
- overflow: boolean
24
- scrolling: boolean
25
- grab?: number
26
- }>({
27
- size: 0,
28
- start: 4,
29
- overflow: false,
30
- scrolling: false,
31
- })
34
+ const [geometry, setGeometry] = createStore({ size: 0, start: 4 })
35
+
36
+ const [thumbState, setThumbState] = createSignal<ScrollThumbState>(INITIAL_SCROLL_THUMB_STATE)
32
37
 
33
38
  let viewport!: HTMLDivElement
34
39
 
35
40
  let content!: HTMLDivElement
36
41
 
37
- let idle: ReturnType<typeof setTimeout> | undefined
42
+ let thumb: HTMLDivElement | undefined
43
+
44
+ let idleTimer: ReturnType<typeof setTimeout> | undefined
45
+
46
+ const onIdleElapsed = () => {
47
+ idleTimer = undefined
48
+ dispatch(SCROLL_IDLE_ELAPSED)
49
+ }
50
+
51
+ const dispatch = (event: ScrollThumbEvent) => {
52
+ const prev = untrack(thumbState)
53
+ const next = transitionScrollThumb(prev, event)
54
+
55
+ if (next.state !== prev) setThumbState(next.state)
56
+
57
+ for (const effect of next.effects) {
58
+ if (effect === "release-capture") {
59
+ if (prev.status === "dragging" && thumb?.hasPointerCapture(prev.pointerId))
60
+ thumb.releasePointerCapture(prev.pointerId)
61
+ continue
62
+ }
63
+
64
+ clearTimeout(idleTimer)
65
+ idleTimer = effect === "reset-idle-timer" ? setTimeout(onIdleElapsed, SCROLL_IDLE_MS) : undefined
66
+ }
67
+ }
38
68
 
39
69
  const measure = () => {
40
70
  const track = Math.max(0, viewport.clientHeight - 8)
@@ -43,20 +73,22 @@ export function MenuScroll(
43
73
 
44
74
  const max = viewport.scrollHeight - viewport.clientHeight
45
75
 
46
- setState({ size, start: 4 + (max > 0 ? (viewport.scrollTop / max) * (track - size) : 0), overflow: max > 0 })
47
-
48
- if (max <= 0) setState("grab", undefined)
76
+ setGeometry("size", size)
77
+ setGeometry("start", 4 + (max > 0 ? (viewport.scrollTop / max) * (track - size) : 0))
78
+ dispatch(overflowChanged(max > 0, false))
49
79
  }
50
80
 
81
+ const onPointerEnd = (event: PointerEvent) => dispatch({ type: "drag.ended", pointerId: event.pointerId })
82
+
51
83
  onMount(() => createResizeObserver([viewport, content], measure))
52
84
 
53
- onCleanup(() => clearTimeout(idle))
85
+ onCleanup(() => dispatch(SCROLL_THUMB_DISPOSED))
54
86
 
55
87
  return (
56
88
  <div
57
89
  data-component="menu-scroll"
58
- data-scrolling={state.scrolling ? "" : undefined}
59
- data-dragging={state.grab !== undefined ? "" : undefined}
90
+ data-scrolling={selectThumbScrolling(thumbState()) ? "" : undefined}
91
+ data-dragging={selectDraggingAxis(thumbState()) === "vertical" ? "" : undefined}
60
92
  class={local.class}
61
93
  >
62
94
  <div
@@ -71,9 +103,7 @@ export function MenuScroll(
71
103
  onScroll={(event) => {
72
104
  measure()
73
105
  // Keyboard navigation scrolls without hovering, so the thumb also shows while the list scrolls.
74
- setState("scrolling", true)
75
- clearTimeout(idle)
76
- idle = setTimeout(() => setState("scrolling", false), 800)
106
+ dispatch(SCROLLED)
77
107
  local.onScroll?.(event)
78
108
  }}
79
109
  // Kobalte menus focus items without scrolling and scroll their own content, which no longer overflows here.
@@ -85,32 +115,45 @@ export function MenuScroll(
85
115
  {local.children}
86
116
  </div>
87
117
  </div>
88
- <Show when={state.overflow}>
118
+ <Show when={selectShowVerticalThumb(thumbState())}>
89
119
  <div
120
+ ref={thumb}
90
121
  data-slot="menu-scroll-thumb"
91
122
  aria-hidden="true"
92
- style={{ height: `${state.size}px`, transform: `translateY(${state.start}px)` }}
123
+ style={{ height: `${geometry.size}px`, transform: `translateY(${geometry.start}px)` }}
93
124
  onPointerDown={(event) => {
94
125
  if (event.button !== 0) return
95
126
  event.preventDefault()
96
127
  event.stopPropagation()
97
- setState("grab", event.clientY - event.currentTarget.getBoundingClientRect().top)
98
- event.currentTarget.setPointerCapture(event.pointerId)
128
+ dispatch({
129
+ type: "drag.started",
130
+ axis: "vertical",
131
+ pointerId: event.pointerId,
132
+ grabOffset: event.clientY - event.currentTarget.getBoundingClientRect().top,
133
+ rtl: false,
134
+ })
135
+
136
+ if (event.isTrusted && selectDraggingAxis(untrack(thumbState)) === "vertical")
137
+ event.currentTarget.setPointerCapture(event.pointerId)
99
138
  }}
100
139
  onPointerMove={(event) => {
101
- if (state.grab === undefined) return
102
- const travel = viewport.clientHeight - 8 - state.size
140
+ const drag = untrack(thumbState)
141
+
142
+ if (drag.status !== "dragging" || drag.pointerId !== event.pointerId) return
143
+
144
+ // A drag whose capture never started or was dropped without a `pointerup` ends at the first move without
145
+ // the button, instead of scrolling under a hovering pointer.
146
+ if (event.isTrusted && (event.buttons & 1) === 0) return onPointerEnd(event)
147
+ const travel = viewport.clientHeight - 8 - geometry.size
103
148
 
104
149
  if (travel <= 0) return
105
150
  viewport.scrollTop =
106
- ((event.clientY - viewport.getBoundingClientRect().top - 4 - state.grab) / travel) *
151
+ ((event.clientY - viewport.getBoundingClientRect().top - 4 - drag.grabOffset) / travel) *
107
152
  (viewport.scrollHeight - viewport.clientHeight)
108
153
  }}
109
- onPointerUp={(event) => {
110
- if (state.grab === undefined) return
111
- event.currentTarget.releasePointerCapture(event.pointerId)
112
- }}
113
- onLostPointerCapture={() => setState("grab", undefined)}
154
+ onPointerUp={onPointerEnd}
155
+ onPointerCancel={onPointerEnd}
156
+ onLostPointerCapture={onPointerEnd}
114
157
  />
115
158
  </Show>
116
159
  </div>
@@ -97,7 +97,8 @@ const RELEASE_AND_RESET: readonly ScrollThumbEffect[] = Object.freeze(["release-
97
97
 
98
98
  const RELEASE_AND_CLEAR: readonly ScrollThumbEffect[] = Object.freeze(["release-capture", "clear-idle-timer"])
99
99
 
100
- const KEEP = new Map<ScrollThumbState, ScrollThumbTransition>(
100
+ // A drag's state is built per drag, so its no-op transition is cached on first use; pointer moves then allocate nothing.
101
+ const KEEP = new WeakMap<ScrollThumbState, ScrollThumbTransition>(
101
102
  [...RESTING, DISPOSED].map((state) => [state, Object.freeze({ state, effects: NONE })]),
102
103
  )
103
104
 
@@ -128,6 +129,11 @@ export function selectShowHorizontalThumb(state: ScrollThumbState) {
128
129
  return state.status !== "disposed" && state.horizontalOverflow
129
130
  }
130
131
 
132
+ /** Scroll-only reveal: a drag shows the thumb through `selectDraggingAxis` instead. */
133
+ export function selectThumbScrolling(state: ScrollThumbState) {
134
+ return state.status === "scrolling"
135
+ }
136
+
131
137
  export function selectDraggingAxis(state: ScrollThumbState) {
132
138
  return state.status === "dragging" ? state.axis : undefined
133
139
  }
@@ -221,9 +227,16 @@ function release(state: Dragging, vertical: boolean, horizontal: boolean) {
221
227
  }
222
228
 
223
229
  function to(state: ScrollThumbState, effects: readonly ScrollThumbEffect[]): ScrollThumbTransition {
224
- const cached = effects === NONE ? KEEP.get(state) : effects === RESET ? RESTART.get(state) : undefined
230
+ if (effects === NONE) return KEEP.get(state) ?? keep(state)
231
+
232
+ return (effects === RESET ? RESTART.get(state) : undefined) ?? { state, effects }
233
+ }
234
+
235
+ function keep(state: ScrollThumbState) {
236
+ const transition = Object.freeze({ state, effects: NONE })
237
+ KEEP.set(state, transition)
225
238
 
226
- return cached ?? { state, effects }
239
+ return transition
227
240
  }
228
241
 
229
242
  function resting(status: Resting["status"], hovered: boolean, vertical: boolean, horizontal: boolean) {
@@ -0,0 +1,134 @@
1
+ export const TYPEWRITER_INITIAL_DELAY_MS = 200
2
+
3
+ export const TYPEWRITER_LINGER_MS = 2_000
4
+
5
+ export type TypewriterCursor = "none" | "solid" | "blinking"
6
+
7
+ /**
8
+ * `typing` shows the first `index` characters behind a solid cursor; `index` 0 is the pause before the first one.
9
+ * `lingering` shows the whole text behind a blinking cursor, then `done` hides the cursor.
10
+ */
11
+ export type TypewriterState =
12
+ | { readonly status: "empty"; readonly attempts: number }
13
+ | {
14
+ readonly status: "typing"
15
+ readonly attempt: number
16
+ readonly text: string
17
+ /** Code points, so a step never shows half of a surrogate pair. */
18
+ readonly chars: readonly string[]
19
+ readonly index: number
20
+ }
21
+ | { readonly status: "lingering"; readonly attempt: number; readonly text: string }
22
+ | { readonly status: "done"; readonly attempts: number; readonly text: string }
23
+ | { readonly status: "disposed" }
24
+
25
+ export type TypewriterEvent =
26
+ | { readonly type: "sync"; readonly text: string | undefined; readonly reducedMotion: boolean }
27
+ | { readonly type: "typing.step"; readonly attempt: number }
28
+ | { readonly type: "linger.ended"; readonly attempt: number }
29
+ | { readonly type: "disposed" }
30
+
31
+ export type TypewriterEffect =
32
+ | { readonly type: "none" }
33
+ | { readonly type: "clear" }
34
+ | { readonly type: "schedule"; readonly kind: "initial" | "step" | "linger"; readonly attempt: number }
35
+
36
+ export type TypewriterTransition = {
37
+ readonly state: TypewriterState
38
+ readonly effect: TypewriterEffect
39
+ }
40
+
41
+ export const INITIAL_EMPTY_TYPEWRITER_STATE: TypewriterState = Object.freeze({ status: "empty", attempts: 0 })
42
+
43
+ export const DISPOSED_TYPEWRITER_STATE: TypewriterState = Object.freeze({ status: "disposed" })
44
+
45
+ export const DISPOSED_TYPEWRITER_EVENT: TypewriterEvent = Object.freeze({ type: "disposed" })
46
+
47
+ const NONE: TypewriterEffect = Object.freeze({ type: "none" })
48
+
49
+ const CLEAR: TypewriterEffect = Object.freeze({ type: "clear" })
50
+
51
+ /** Mostly quick keystrokes, with an occasional hesitation. `roll` and `jitter` are uniform in [0, 1). */
52
+ export function typingStepDelayMs(roll: number, jitter: number) {
53
+ if (roll < 0.05) return 150 + jitter * 100
54
+
55
+ if (roll < 0.15) return 80 + jitter * 60
56
+
57
+ return 30 + jitter * 50
58
+ }
59
+
60
+ export function transitionTypewriter(state: TypewriterState, event: TypewriterEvent): TypewriterTransition {
61
+ if (state.status === "disposed") return { state, effect: NONE }
62
+ const timed = state.status === "typing" || state.status === "lingering"
63
+
64
+ if (event.type === "disposed") return { state: DISPOSED_TYPEWRITER_STATE, effect: timed ? CLEAR : NONE }
65
+
66
+ if (event.type === "sync") return sync(state, event)
67
+
68
+ if (event.type === "typing.step") {
69
+ if (state.status !== "typing" || event.attempt !== state.attempt) return { state, effect: NONE }
70
+
71
+ if (state.index + 1 < state.chars.length)
72
+ return {
73
+ state: { ...state, index: state.index + 1 },
74
+ effect: { type: "schedule", kind: "step", attempt: state.attempt },
75
+ }
76
+
77
+ return {
78
+ state: { status: "lingering", attempt: state.attempt, text: state.text },
79
+ effect: { type: "schedule", kind: "linger", attempt: state.attempt },
80
+ }
81
+ }
82
+
83
+ if (state.status !== "lingering" || event.attempt !== state.attempt) return { state, effect: NONE }
84
+
85
+ return { state: { status: "done", attempts: state.attempt, text: state.text }, effect: NONE }
86
+ }
87
+
88
+ function sync(
89
+ state: Exclude<TypewriterState, { status: "disposed" }>,
90
+ event: Extract<TypewriterEvent, { type: "sync" }>,
91
+ ): TypewriterTransition {
92
+ const timed = state.status === "typing" || state.status === "lingering"
93
+ const attempts = timed ? state.attempt : state.attempts
94
+ const text = event.text ?? ""
95
+
96
+ if (text === "") {
97
+ if (state.status === "empty") return { state, effect: NONE }
98
+
99
+ return {
100
+ state: attempts === 0 ? INITIAL_EMPTY_TYPEWRITER_STATE : { status: "empty", attempts },
101
+ effect: timed ? CLEAR : NONE,
102
+ }
103
+ }
104
+
105
+ // Reduced motion shows the whole text at once, without a cursor.
106
+ if (event.reducedMotion) {
107
+ if (state.status === "done" && state.text === text) return { state, effect: NONE }
108
+
109
+ return { state: { status: "done", attempts, text }, effect: timed ? CLEAR : NONE }
110
+ }
111
+
112
+ if (state.status !== "empty" && state.text === text) return { state, effect: NONE }
113
+
114
+ return {
115
+ state: { status: "typing", attempt: attempts + 1, text, chars: Array.from(text), index: 0 },
116
+ effect: { type: "schedule", kind: "initial", attempt: attempts + 1 },
117
+ }
118
+ }
119
+
120
+ export function selectTypewriterDisplayed(state: TypewriterState) {
121
+ if (state.status === "empty" || state.status === "disposed") return ""
122
+
123
+ if (state.status === "typing") return state.chars.slice(0, state.index).join("")
124
+
125
+ return state.text
126
+ }
127
+
128
+ export function selectTypewriterCursor(state: TypewriterState): TypewriterCursor {
129
+ if (state.status === "typing") return "solid"
130
+
131
+ if (state.status === "lingering") return "blinking"
132
+
133
+ return "none"
134
+ }
@@ -1,58 +1,69 @@
1
- import { createEffect, onCleanup, Show, type ValidComponent } from "solid-js"
2
- import { createStore } from "solid-js/store"
1
+ import { createEffect, createMemo, createSignal, onCleanup, Show, untrack, type ValidComponent } from "solid-js"
3
2
  import { Dynamic } from "solid-js/web"
3
+ import { observeReducedMotion, prefersReducedMotion } from "../motion/reduced"
4
+ import {
5
+ DISPOSED_TYPEWRITER_EVENT,
6
+ INITIAL_EMPTY_TYPEWRITER_STATE,
7
+ selectTypewriterCursor,
8
+ selectTypewriterDisplayed,
9
+ transitionTypewriter,
10
+ TYPEWRITER_INITIAL_DELAY_MS,
11
+ TYPEWRITER_LINGER_MS,
12
+ typingStepDelayMs,
13
+ type TypewriterEvent,
14
+ } from "./typewriter-machine"
4
15
 
5
16
  export const Typewriter = <T extends ValidComponent = "p">(props: { text?: string; class?: string; as?: T }) => {
6
- const [store, setStore] = createStore({
7
- typing: false,
8
- displayed: "",
9
- cursor: true,
10
- })
17
+ const [state, setState] = createSignal(INITIAL_EMPTY_TYPEWRITER_STATE)
18
+ let timer: ReturnType<typeof setTimeout> | undefined
11
19
 
12
- createEffect(() => {
13
- const text = props.text
20
+ const dispatch = (event: TypewriterEvent) => {
21
+ const previous = untrack(state)
22
+ const next = transitionTypewriter(previous, event)
14
23
 
15
- if (!text) return
24
+ if (next.effect.type !== "none") {
25
+ clearTimeout(timer)
26
+ timer = undefined
27
+ }
16
28
 
17
- let i = 0
18
- const timeouts: ReturnType<typeof setTimeout>[] = []
19
- setStore("typing", true)
20
- setStore("displayed", "")
21
- setStore("cursor", true)
29
+ if (next.state !== previous && next.state.status !== "disposed") setState(next.state)
22
30
 
23
- const getTypingDelay = () => {
24
- const random = Math.random()
31
+ if (next.effect.type !== "schedule") return
32
+ const effect = next.effect
25
33
 
26
- if (random < 0.05) return 150 + Math.random() * 100
34
+ const timeout: TypewriterEvent =
35
+ effect.kind === "linger"
36
+ ? { type: "linger.ended", attempt: effect.attempt }
37
+ : { type: "typing.step", attempt: effect.attempt }
27
38
 
28
- if (random < 0.15) return 80 + Math.random() * 60
39
+ timer = setTimeout(
40
+ () => {
41
+ timer = undefined
42
+ dispatch(timeout)
43
+ },
44
+ effect.kind === "initial"
45
+ ? TYPEWRITER_INITIAL_DELAY_MS
46
+ : effect.kind === "linger"
47
+ ? TYPEWRITER_LINGER_MS
48
+ : typingStepDelayMs(Math.random(), Math.random()),
49
+ )
50
+ }
29
51
 
30
- return 30 + Math.random() * 50
31
- }
52
+ const sync = () => dispatch({ type: "sync", text: props.text, reducedMotion: prefersReducedMotion() })
32
53
 
33
- const type = () => {
34
- if (i < text.length) {
35
- setStore("displayed", text.slice(0, i + 1))
36
- i++
37
- timeouts.push(setTimeout(type, getTypingDelay()))
38
- } else {
39
- setStore("typing", false)
40
- timeouts.push(setTimeout(() => setStore("cursor", false), 2000))
41
- }
42
- }
54
+ createEffect(sync)
55
+
56
+ onCleanup(observeReducedMotion(() => untrack(sync)))
43
57
 
44
- timeouts.push(setTimeout(type, 200))
58
+ onCleanup(() => dispatch(DISPOSED_TYPEWRITER_EVENT))
45
59
 
46
- onCleanup(() => {
47
- for (const timeout of timeouts) clearTimeout(timeout)
48
- })
49
- })
60
+ const cursor = createMemo(() => selectTypewriterCursor(state()))
50
61
 
51
62
  return (
52
63
  <Dynamic component={props.as || "p"} class={props.class}>
53
- {store.displayed}
54
- <Show when={store.cursor}>
55
- <span classList={{ "blinking-cursor": !store.typing }}>│</span>
64
+ {selectTypewriterDisplayed(state())}
65
+ <Show when={cursor() !== "none"}>
66
+ <span classList={{ "blinking-cursor": cursor() === "blinking" }}>│</span>
56
67
  </Show>
57
68
  </Dynamic>
58
69
  )