@neurocode-ai/tui 1.18.8

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 (241) hide show
  1. package/bunfig.toml +4 -0
  2. package/package.json +72 -0
  3. package/src/app.tsx +1134 -0
  4. package/src/attention.ts +260 -0
  5. package/src/audio.d.ts +9 -0
  6. package/src/audio.ts +53 -0
  7. package/src/clipboard.ts +124 -0
  8. package/src/component/bg-pulse-render.ts +436 -0
  9. package/src/component/bg-pulse.tsx +99 -0
  10. package/src/component/command-palette.tsx +79 -0
  11. package/src/component/dialog-agent.tsx +31 -0
  12. package/src/component/dialog-console-org.tsx +135 -0
  13. package/src/component/dialog-debug.tsx +90 -0
  14. package/src/component/dialog-mcp.tsx +85 -0
  15. package/src/component/dialog-model.tsx +197 -0
  16. package/src/component/dialog-move-session.tsx +353 -0
  17. package/src/component/dialog-provider.tsx +469 -0
  18. package/src/component/dialog-retry-action.tsx +160 -0
  19. package/src/component/dialog-session-delete-failed.tsx +99 -0
  20. package/src/component/dialog-session-list.tsx +364 -0
  21. package/src/component/dialog-session-rename.tsx +31 -0
  22. package/src/component/dialog-skill.tsx +70 -0
  23. package/src/component/dialog-stash.tsx +87 -0
  24. package/src/component/dialog-status.tsx +168 -0
  25. package/src/component/dialog-tag.tsx +47 -0
  26. package/src/component/dialog-theme-list.tsx +50 -0
  27. package/src/component/dialog-variant.tsx +39 -0
  28. package/src/component/dialog-workspace-create.tsx +308 -0
  29. package/src/component/dialog-workspace-file-changes.tsx +144 -0
  30. package/src/component/dialog-workspace-list.tsx +112 -0
  31. package/src/component/dialog-workspace-unavailable.tsx +69 -0
  32. package/src/component/error-component.tsx +240 -0
  33. package/src/component/logo.tsx +61 -0
  34. package/src/component/plugin-route-missing.tsx +14 -0
  35. package/src/component/prompt/autocomplete.tsx +781 -0
  36. package/src/component/prompt/cwd.ts +0 -0
  37. package/src/component/prompt/frecency.tsx +1 -0
  38. package/src/component/prompt/history.tsx +1 -0
  39. package/src/component/prompt/index.tsx +1713 -0
  40. package/src/component/prompt/local-attachment.ts +48 -0
  41. package/src/component/prompt/move.tsx +205 -0
  42. package/src/component/prompt/stash.tsx +1 -0
  43. package/src/component/prompt/workspace.tsx +137 -0
  44. package/src/component/register-spinner.ts +6 -0
  45. package/src/component/spinner.tsx +26 -0
  46. package/src/component/startup-loading.tsx +63 -0
  47. package/src/component/todo-item.tsx +32 -0
  48. package/src/component/use-connected.tsx +12 -0
  49. package/src/component/workspace-label.tsx +19 -0
  50. package/src/config/index.tsx +129 -0
  51. package/src/config/keybind.ts +471 -0
  52. package/src/context/args.tsx +16 -0
  53. package/src/context/clipboard.tsx +18 -0
  54. package/src/context/data.tsx +569 -0
  55. package/src/context/directory.ts +17 -0
  56. package/src/context/editor.ts +408 -0
  57. package/src/context/epilogue.tsx +6 -0
  58. package/src/context/event.ts +36 -0
  59. package/src/context/exit.tsx +8 -0
  60. package/src/context/helper.tsx +26 -0
  61. package/src/context/kv.tsx +66 -0
  62. package/src/context/local.tsx +542 -0
  63. package/src/context/location.tsx +14 -0
  64. package/src/context/path-format.tsx +24 -0
  65. package/src/context/permission.tsx +26 -0
  66. package/src/context/project.tsx +115 -0
  67. package/src/context/prompt.tsx +18 -0
  68. package/src/context/route.tsx +60 -0
  69. package/src/context/runtime.tsx +62 -0
  70. package/src/context/sdk.tsx +151 -0
  71. package/src/context/sync.tsx +666 -0
  72. package/src/context/theme.tsx +332 -0
  73. package/src/context/thinking.ts +67 -0
  74. package/src/editor-zed.ts +286 -0
  75. package/src/editor.ts +101 -0
  76. package/src/feature-plugins/builtins.ts +36 -0
  77. package/src/feature-plugins/home/footer.tsx +100 -0
  78. package/src/feature-plugins/home/tips-view.tsx +287 -0
  79. package/src/feature-plugins/home/tips.tsx +59 -0
  80. package/src/feature-plugins/sidebar/context.tsx +65 -0
  81. package/src/feature-plugins/sidebar/files.tsx +70 -0
  82. package/src/feature-plugins/sidebar/footer.tsx +98 -0
  83. package/src/feature-plugins/sidebar/lsp.tsx +65 -0
  84. package/src/feature-plugins/sidebar/mcp.tsx +97 -0
  85. package/src/feature-plugins/sidebar/todo.tsx +49 -0
  86. package/src/feature-plugins/system/diff-viewer-file-tree-utils.ts +232 -0
  87. package/src/feature-plugins/system/diff-viewer-file-tree.tsx +162 -0
  88. package/src/feature-plugins/system/diff-viewer-ui.tsx +103 -0
  89. package/src/feature-plugins/system/diff-viewer.tsx +1077 -0
  90. package/src/feature-plugins/system/notifications.ts +94 -0
  91. package/src/feature-plugins/system/plugins.tsx +269 -0
  92. package/src/feature-plugins/system/which-key.tsx +608 -0
  93. package/src/index.tsx +1 -0
  94. package/src/keymap.tsx +290 -0
  95. package/src/logo.ts +11 -0
  96. package/src/parsers-config.ts +386 -0
  97. package/src/plugin/adapters.tsx +355 -0
  98. package/src/plugin/api.ts +52 -0
  99. package/src/plugin/command-shim.ts +109 -0
  100. package/src/plugin/runtime.tsx +81 -0
  101. package/src/plugin/slots.tsx +65 -0
  102. package/src/prompt/display.ts +48 -0
  103. package/src/prompt/frecency.tsx +80 -0
  104. package/src/prompt/history.tsx +111 -0
  105. package/src/prompt/part.ts +29 -0
  106. package/src/prompt/stash.tsx +89 -0
  107. package/src/prompt/traits.ts +29 -0
  108. package/src/routes/home/session-destination.tsx +41 -0
  109. package/src/routes/home.tsx +95 -0
  110. package/src/routes/session/dialog-fork-from-timeline.tsx +76 -0
  111. package/src/routes/session/dialog-message.tsx +109 -0
  112. package/src/routes/session/dialog-subagent.tsx +26 -0
  113. package/src/routes/session/dialog-timeline.tsx +47 -0
  114. package/src/routes/session/footer.tsx +91 -0
  115. package/src/routes/session/index.tsx +2710 -0
  116. package/src/routes/session/permission.tsx +718 -0
  117. package/src/routes/session/question.tsx +514 -0
  118. package/src/routes/session/sidebar.tsx +103 -0
  119. package/src/routes/session/subagent-footer.tsx +132 -0
  120. package/src/runtime.tsx +9 -0
  121. package/src/terminal-win32.ts +130 -0
  122. package/src/theme/assets/aura.json +69 -0
  123. package/src/theme/assets/ayu.json +80 -0
  124. package/src/theme/assets/carbonfox.json +248 -0
  125. package/src/theme/assets/catppuccin-frappe.json +230 -0
  126. package/src/theme/assets/catppuccin-macchiato.json +230 -0
  127. package/src/theme/assets/catppuccin.json +112 -0
  128. package/src/theme/assets/cobalt2.json +225 -0
  129. package/src/theme/assets/cursor.json +249 -0
  130. package/src/theme/assets/dracula.json +219 -0
  131. package/src/theme/assets/everforest.json +241 -0
  132. package/src/theme/assets/flexoki.json +237 -0
  133. package/src/theme/assets/github.json +233 -0
  134. package/src/theme/assets/gruvbox.json +242 -0
  135. package/src/theme/assets/kanagawa.json +77 -0
  136. package/src/theme/assets/lucent-orng.json +234 -0
  137. package/src/theme/assets/material.json +235 -0
  138. package/src/theme/assets/matrix.json +77 -0
  139. package/src/theme/assets/mercury.json +252 -0
  140. package/src/theme/assets/monokai.json +221 -0
  141. package/src/theme/assets/nightowl.json +221 -0
  142. package/src/theme/assets/nord.json +223 -0
  143. package/src/theme/assets/one-dark.json +84 -0
  144. package/src/theme/assets/opencode.json +245 -0
  145. package/src/theme/assets/orng.json +249 -0
  146. package/src/theme/assets/osaka-jade.json +93 -0
  147. package/src/theme/assets/palenight.json +222 -0
  148. package/src/theme/assets/rosepine.json +234 -0
  149. package/src/theme/assets/solarized.json +223 -0
  150. package/src/theme/assets/synthwave84.json +226 -0
  151. package/src/theme/assets/tokyonight.json +243 -0
  152. package/src/theme/assets/vercel.json +245 -0
  153. package/src/theme/assets/vesper.json +218 -0
  154. package/src/theme/assets/zenburn.json +223 -0
  155. package/src/theme/index.ts +1089 -0
  156. package/src/ui/border.ts +21 -0
  157. package/src/ui/dialog-alert.tsx +66 -0
  158. package/src/ui/dialog-confirm.tsx +108 -0
  159. package/src/ui/dialog-export-options.tsx +217 -0
  160. package/src/ui/dialog-help.tsx +40 -0
  161. package/src/ui/dialog-prompt.tsx +126 -0
  162. package/src/ui/dialog-select.tsx +790 -0
  163. package/src/ui/dialog.tsx +231 -0
  164. package/src/ui/link.tsx +34 -0
  165. package/src/ui/spinner.ts +368 -0
  166. package/src/ui/toast.tsx +102 -0
  167. package/src/util/collapse-tool-output.ts +19 -0
  168. package/src/util/error.ts +182 -0
  169. package/src/util/filetype.ts +130 -0
  170. package/src/util/format.ts +20 -0
  171. package/src/util/layout.ts +25 -0
  172. package/src/util/locale.ts +86 -0
  173. package/src/util/model.ts +28 -0
  174. package/src/util/path.ts +12 -0
  175. package/src/util/persistence.ts +33 -0
  176. package/src/util/presentation.ts +38 -0
  177. package/src/util/provider-origin.ts +7 -0
  178. package/src/util/record.ts +3 -0
  179. package/src/util/renderer.ts +7 -0
  180. package/src/util/revert-diff.ts +18 -0
  181. package/src/util/scroll.ts +27 -0
  182. package/src/util/selection.ts +79 -0
  183. package/src/util/session.ts +3 -0
  184. package/src/util/signal.ts +51 -0
  185. package/src/util/system.ts +20 -0
  186. package/src/util/tool-display.ts +13 -0
  187. package/src/util/transcript.ts +112 -0
  188. package/sst-env.d.ts +10 -0
  189. package/test/app-lifecycle.test.tsx +128 -0
  190. package/test/cli/cmd/tui/dialog-workspace-create.test.ts +28 -0
  191. package/test/cli/cmd/tui/model-options.test.ts +32 -0
  192. package/test/cli/cmd/tui/notifications.test.ts +267 -0
  193. package/test/cli/cmd/tui/provider-options.test.ts +41 -0
  194. package/test/cli/cmd/tui/sync-fixture.tsx +70 -0
  195. package/test/cli/cmd/tui/sync-live-hydration.test.tsx +262 -0
  196. package/test/cli/cmd/tui/sync-undefined-messages.test.tsx +43 -0
  197. package/test/cli/cmd/tui/sync.test.tsx +65 -0
  198. package/test/cli/tui/__snapshots__/inline-tool-wrap-snapshot.test.tsx.snap +92 -0
  199. package/test/cli/tui/data.test.tsx +486 -0
  200. package/test/cli/tui/dialog-prompt.test.tsx +147 -0
  201. package/test/cli/tui/diff-viewer-file-tree.test.tsx +200 -0
  202. package/test/cli/tui/diff-viewer.test.tsx +268 -0
  203. package/test/cli/tui/inline-tool-wrap-snapshot.test.tsx +351 -0
  204. package/test/cli/tui/prompt-submit-race.test.ts +98 -0
  205. package/test/cli/tui/thinking.test.ts +36 -0
  206. package/test/cli/tui/use-event.test.tsx +148 -0
  207. package/test/clipboard.test.ts +19 -0
  208. package/test/component/dialog-session-list.test.ts +46 -0
  209. package/test/config.test.tsx +127 -0
  210. package/test/context/local.test.ts +22 -0
  211. package/test/editor.test.ts +32 -0
  212. package/test/feature-plugins/diff-viewer-file-tree-utils.test.ts +323 -0
  213. package/test/fixture/fixture.ts +13 -0
  214. package/test/fixture/tui-environment.tsx +32 -0
  215. package/test/fixture/tui-plugin.ts +36 -0
  216. package/test/fixture/tui-runtime.ts +12 -0
  217. package/test/fixture/tui-sdk.ts +109 -0
  218. package/test/index.test.tsx +6 -0
  219. package/test/keymap.test.tsx +141 -0
  220. package/test/plugin/runtime.test.ts +50 -0
  221. package/test/plugin/slots.test.tsx +38 -0
  222. package/test/prompt/display.test.ts +33 -0
  223. package/test/prompt/history.test.ts +39 -0
  224. package/test/prompt/jsonl.test.ts +24 -0
  225. package/test/prompt/local-attachment.test.ts +43 -0
  226. package/test/prompt/part.test.ts +53 -0
  227. package/test/prompt/persistence.test.ts +23 -0
  228. package/test/prompt/traits.test.ts +25 -0
  229. package/test/runtime.test.tsx +37 -0
  230. package/test/theme.test.ts +81 -0
  231. package/test/util/error.test.ts +49 -0
  232. package/test/util/filetype.test.ts +16 -0
  233. package/test/util/format.test.ts +59 -0
  234. package/test/util/model.test.ts +9 -0
  235. package/test/util/presentation.test.ts +8 -0
  236. package/test/util/renderer.test.ts +30 -0
  237. package/test/util/revert-diff.test.ts +35 -0
  238. package/test/util/session.test.ts +10 -0
  239. package/test/util/tool-display.test.ts +40 -0
  240. package/test/util/transcript.test.ts +421 -0
  241. package/tsconfig.json +10 -0
@@ -0,0 +1,231 @@
1
+ import { useRenderer, useTerminalDimensions } from "@opentui/solid"
2
+ import { batch, createContext, createEffect, onCleanup, Show, useContext, type JSX, type ParentProps } from "solid-js"
3
+ import { useTheme } from "../context/theme"
4
+ import { MouseButton, Renderable, RGBA } from "@opentui/core"
5
+ import { createStore } from "solid-js/store"
6
+ import { useToast } from "./toast"
7
+ import { Flag } from "@neurocode-ai/core/flag/flag"
8
+ import { useBindings, useNeurocodeModeStack } from "../keymap"
9
+ import { useClipboard } from "../context/clipboard"
10
+
11
+ export function Dialog(
12
+ props: ParentProps<{
13
+ size?: "medium" | "large" | "xlarge"
14
+ onClose: () => void
15
+ }>,
16
+ ) {
17
+ const dimensions = useTerminalDimensions()
18
+ const { theme } = useTheme()
19
+ const renderer = useRenderer()
20
+
21
+ let dismiss = false
22
+ const width = () => {
23
+ if (props.size === "xlarge") return 116
24
+ if (props.size === "large") return 88
25
+ return 60
26
+ }
27
+
28
+ return (
29
+ <box
30
+ onMouseDown={() => {
31
+ dismiss = !!renderer.getSelection()
32
+ }}
33
+ onMouseUp={() => {
34
+ if (dismiss) {
35
+ dismiss = false
36
+ return
37
+ }
38
+ props.onClose?.()
39
+ }}
40
+ width={dimensions().width}
41
+ height={dimensions().height}
42
+ alignItems="center"
43
+ position="absolute"
44
+ zIndex={3000}
45
+ paddingTop={dimensions().height / 4}
46
+ left={0}
47
+ top={0}
48
+ backgroundColor={RGBA.fromInts(0, 0, 0, 150)}
49
+ >
50
+ <box
51
+ onMouseUp={(e: { stopPropagation(): void }) => {
52
+ // A selection release must bubble up to the copy-on-select handler in
53
+ // DialogProvider; the backdrop's dismiss flag keeps it from closing the dialog.
54
+ if (renderer.getSelection()?.getSelectedText()) return
55
+ dismiss = false
56
+ e.stopPropagation()
57
+ }}
58
+ width={width()}
59
+ maxWidth={dimensions().width - 2}
60
+ backgroundColor={theme.backgroundPanel}
61
+ paddingTop={1}
62
+ >
63
+ {props.children}
64
+ </box>
65
+ </box>
66
+ )
67
+ }
68
+
69
+ function init() {
70
+ const [store, setStore] = createStore({
71
+ stack: [] as {
72
+ element: JSX.Element
73
+ onClose?: () => void
74
+ }[],
75
+ size: "medium" as "medium" | "large" | "xlarge",
76
+ })
77
+
78
+ const renderer = useRenderer()
79
+ const modeStack = useNeurocodeModeStack()
80
+
81
+ createEffect(() => {
82
+ if (store.stack.length === 0) return
83
+ const popMode = modeStack.push("modal")
84
+ onCleanup(popMode)
85
+ })
86
+
87
+ let focus: Renderable | null
88
+ function refocus() {
89
+ setTimeout(() => {
90
+ if (!focus) return
91
+ if (focus.isDestroyed) return
92
+ function find(item: Renderable) {
93
+ for (const child of item.getChildren()) {
94
+ if (child === focus) return true
95
+ if (find(child)) return true
96
+ }
97
+ return false
98
+ }
99
+ const found = find(renderer.root)
100
+ if (!found) return
101
+ focus.focus()
102
+ }, 1)
103
+ }
104
+
105
+ useBindings(() => ({
106
+ enabled: store.stack.length > 0 && !renderer.getSelection()?.getSelectedText(),
107
+ bindings: [
108
+ {
109
+ key: "escape",
110
+ desc: "Close dialog",
111
+ group: "Dialog",
112
+ cmd: () => {
113
+ if (renderer.getSelection()) {
114
+ renderer.clearSelection()
115
+ }
116
+ const current = store.stack.at(-1)
117
+ current?.onClose?.()
118
+ setStore("stack", store.stack.slice(0, -1))
119
+ refocus()
120
+ },
121
+ },
122
+ {
123
+ key: "ctrl+c",
124
+ desc: "Close dialog",
125
+ group: "Dialog",
126
+ cmd: () => {
127
+ if (renderer.getSelection()) {
128
+ renderer.clearSelection()
129
+ }
130
+ const current = store.stack.at(-1)
131
+ current?.onClose?.()
132
+ setStore("stack", store.stack.slice(0, -1))
133
+ refocus()
134
+ },
135
+ },
136
+ ],
137
+ }))
138
+
139
+ return {
140
+ clear() {
141
+ for (const item of store.stack) {
142
+ if (item.onClose) item.onClose()
143
+ }
144
+ batch(() => {
145
+ setStore("size", "medium")
146
+ setStore("stack", [])
147
+ })
148
+ refocus()
149
+ },
150
+ replace(input: any, onClose?: () => void) {
151
+ if (store.stack.length === 0) {
152
+ focus = renderer.currentFocusedRenderable
153
+ focus?.blur()
154
+ }
155
+ for (const item of store.stack) {
156
+ if (item.onClose) item.onClose()
157
+ }
158
+ setStore("size", "medium")
159
+ setStore("stack", [
160
+ {
161
+ element: input,
162
+ onClose,
163
+ },
164
+ ])
165
+ },
166
+ get stack() {
167
+ return store.stack
168
+ },
169
+ get size() {
170
+ return store.size
171
+ },
172
+ setSize(size: "medium" | "large" | "xlarge") {
173
+ setStore("size", size)
174
+ },
175
+ }
176
+ }
177
+
178
+ export type DialogContext = ReturnType<typeof init>
179
+
180
+ const ctx = createContext<DialogContext>()
181
+
182
+ export function DialogProvider(props: ParentProps) {
183
+ const value = init()
184
+ const renderer = useRenderer()
185
+ const toast = useToast()
186
+ const clipboard = useClipboard()
187
+
188
+ function copySelection() {
189
+ const text = renderer.getSelection()?.getSelectedText()
190
+ if (!text || !clipboard.write) return false
191
+ void clipboard.write(text).then(
192
+ () => toast.show({ message: "Copied to clipboard", variant: "info" }),
193
+ (error) => toast.error(error),
194
+ )
195
+ renderer.clearSelection()
196
+ return true
197
+ }
198
+
199
+ return (
200
+ <ctx.Provider value={value}>
201
+ {props.children}
202
+ <box
203
+ position="absolute"
204
+ zIndex={3000}
205
+ onMouseDown={(evt: { button: number; preventDefault(): void; stopPropagation(): void }) => {
206
+ if (!Flag.NEUROCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT) return
207
+ if (evt.button !== MouseButton.RIGHT) return
208
+
209
+ if (!copySelection()) return
210
+ evt.preventDefault()
211
+ evt.stopPropagation()
212
+ }}
213
+ onMouseUp={!Flag.NEUROCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT ? copySelection : undefined}
214
+ >
215
+ <Show when={value.stack.length}>
216
+ <Dialog onClose={() => value.clear()} size={value.size}>
217
+ {value.stack.at(-1)!.element}
218
+ </Dialog>
219
+ </Show>
220
+ </box>
221
+ </ctx.Provider>
222
+ )
223
+ }
224
+
225
+ export function useDialog() {
226
+ const value = useContext(ctx)
227
+ if (!value) {
228
+ throw new Error("useDialog must be used within a DialogProvider")
229
+ }
230
+ return value
231
+ }
@@ -0,0 +1,34 @@
1
+ import type { JSX } from "solid-js"
2
+ import type { RGBA } from "@opentui/core"
3
+ import open from "open"
4
+
5
+ export interface LinkProps {
6
+ href: string
7
+ children?: JSX.Element | string
8
+ fg?: RGBA
9
+ bg?: RGBA
10
+ width?: number | "auto" | `${number}%`
11
+ wrapMode?: "word" | "none"
12
+ }
13
+
14
+ /**
15
+ * Link component that renders clickable hyperlinks.
16
+ * Clicking anywhere on the link text opens the URL in the default browser.
17
+ */
18
+ export function Link(props: LinkProps) {
19
+ const displayText = props.children ?? props.href
20
+
21
+ return (
22
+ <text
23
+ fg={props.fg}
24
+ bg={props.bg}
25
+ width={props.width}
26
+ wrapMode={props.wrapMode}
27
+ onMouseUp={() => {
28
+ open(props.href).catch(() => {})
29
+ }}
30
+ >
31
+ {displayText}
32
+ </text>
33
+ )
34
+ }
@@ -0,0 +1,368 @@
1
+ import type { ColorInput } from "@opentui/core"
2
+ import { RGBA } from "@opentui/core"
3
+ import type { ColorGenerator } from "opentui-spinner"
4
+
5
+ interface AdvancedGradientOptions {
6
+ colors: ColorInput[]
7
+ trailLength: number
8
+ defaultColor?: ColorInput
9
+ direction?: "forward" | "backward" | "bidirectional"
10
+ holdFrames?: { start?: number; end?: number }
11
+ enableFading?: boolean
12
+ minAlpha?: number
13
+ }
14
+
15
+ interface ScannerState {
16
+ activePosition: number
17
+ isHolding: boolean
18
+ holdProgress: number
19
+ holdTotal: number
20
+ movementProgress: number
21
+ movementTotal: number
22
+ isMovingForward: boolean
23
+ }
24
+
25
+ function getScannerState(
26
+ frameIndex: number,
27
+ totalChars: number,
28
+ options: Pick<AdvancedGradientOptions, "direction" | "holdFrames">,
29
+ ): ScannerState {
30
+ const { direction = "forward", holdFrames = {} } = options
31
+
32
+ if (direction === "bidirectional") {
33
+ const forwardFrames = totalChars
34
+ const holdEndFrames = holdFrames.end ?? 0
35
+ const backwardFrames = totalChars - 1
36
+
37
+ if (frameIndex < forwardFrames) {
38
+ // Moving forward
39
+ return {
40
+ activePosition: frameIndex,
41
+ isHolding: false,
42
+ holdProgress: 0,
43
+ holdTotal: 0,
44
+ movementProgress: frameIndex,
45
+ movementTotal: forwardFrames,
46
+ isMovingForward: true,
47
+ }
48
+ } else if (frameIndex < forwardFrames + holdEndFrames) {
49
+ // Holding at end
50
+ return {
51
+ activePosition: totalChars - 1,
52
+ isHolding: true,
53
+ holdProgress: frameIndex - forwardFrames,
54
+ holdTotal: holdEndFrames,
55
+ movementProgress: 0,
56
+ movementTotal: 0,
57
+ isMovingForward: true,
58
+ }
59
+ } else if (frameIndex < forwardFrames + holdEndFrames + backwardFrames) {
60
+ // Moving backward
61
+ const backwardIndex = frameIndex - forwardFrames - holdEndFrames
62
+ return {
63
+ activePosition: totalChars - 2 - backwardIndex,
64
+ isHolding: false,
65
+ holdProgress: 0,
66
+ holdTotal: 0,
67
+ movementProgress: backwardIndex,
68
+ movementTotal: backwardFrames,
69
+ isMovingForward: false,
70
+ }
71
+ } else {
72
+ // Holding at start
73
+ return {
74
+ activePosition: 0,
75
+ isHolding: true,
76
+ holdProgress: frameIndex - forwardFrames - holdEndFrames - backwardFrames,
77
+ holdTotal: holdFrames.start ?? 0,
78
+ movementProgress: 0,
79
+ movementTotal: 0,
80
+ isMovingForward: false,
81
+ }
82
+ }
83
+ } else if (direction === "backward") {
84
+ return {
85
+ activePosition: totalChars - 1 - (frameIndex % totalChars),
86
+ isHolding: false,
87
+ holdProgress: 0,
88
+ holdTotal: 0,
89
+ movementProgress: frameIndex % totalChars,
90
+ movementTotal: totalChars,
91
+ isMovingForward: false,
92
+ }
93
+ } else {
94
+ return {
95
+ activePosition: frameIndex % totalChars,
96
+ isHolding: false,
97
+ holdProgress: 0,
98
+ holdTotal: 0,
99
+ movementProgress: frameIndex % totalChars,
100
+ movementTotal: totalChars,
101
+ isMovingForward: true,
102
+ }
103
+ }
104
+ }
105
+
106
+ function calculateColorIndex(
107
+ frameIndex: number,
108
+ charIndex: number,
109
+ totalChars: number,
110
+ options: Pick<AdvancedGradientOptions, "direction" | "holdFrames" | "trailLength">,
111
+ state?: ScannerState,
112
+ ): number {
113
+ const { trailLength } = options
114
+ const { activePosition, isHolding, holdProgress, isMovingForward } =
115
+ state ?? getScannerState(frameIndex, totalChars, options)
116
+
117
+ // Calculate directional distance (positive means trailing behind)
118
+ const directionalDistance = isMovingForward
119
+ ? activePosition - charIndex // For forward: trail is to the left (lower indices)
120
+ : charIndex - activePosition // For backward: trail is to the right (higher indices)
121
+
122
+ // Handle hold frame fading: keep the lead bright, fade the trail
123
+ if (isHolding) {
124
+ // Shift the color index by how long we've been holding
125
+ return directionalDistance + holdProgress
126
+ }
127
+
128
+ // Normal movement - show gradient trail only behind the movement direction
129
+ if (directionalDistance > 0 && directionalDistance < trailLength) {
130
+ return directionalDistance
131
+ }
132
+
133
+ // At the active position, show the brightest color
134
+ if (directionalDistance === 0) {
135
+ return 0
136
+ }
137
+
138
+ return -1
139
+ }
140
+
141
+ function createKnightRiderTrail(options: AdvancedGradientOptions): ColorGenerator {
142
+ const { colors, defaultColor, enableFading = true, minAlpha = 0 } = options
143
+
144
+ // Use the provided defaultColor if it's an RGBA instance, otherwise convert/default
145
+ // We use RGBA.fromHex for the fallback to ensure we have an RGBA object.
146
+ // Note: If defaultColor is a string, we convert it once here.
147
+ const defaultRgba = defaultColor instanceof RGBA ? defaultColor : RGBA.fromHex((defaultColor as string) || "#000000")
148
+
149
+ // Store the base alpha from the inactive factor
150
+ const baseInactiveAlpha = defaultRgba.a
151
+
152
+ let cachedFrameIndex = -1
153
+ let cachedState: ScannerState | null = null
154
+
155
+ return (frameIndex: number, charIndex: number, _totalFrames: number, totalChars: number) => {
156
+ if (frameIndex !== cachedFrameIndex) {
157
+ cachedFrameIndex = frameIndex
158
+ cachedState = getScannerState(frameIndex, totalChars, options)
159
+ }
160
+
161
+ const state = cachedState!
162
+
163
+ const index = calculateColorIndex(frameIndex, charIndex, totalChars, options, state)
164
+
165
+ // Calculate global fade for inactive dots during hold or movement
166
+ const { isHolding, holdProgress, holdTotal, movementProgress, movementTotal } = state
167
+
168
+ let fadeFactor = 1.0
169
+ if (enableFading) {
170
+ if (isHolding && holdTotal > 0) {
171
+ // Fade out linearly to minAlpha
172
+ const progress = Math.min(holdProgress / holdTotal, 1)
173
+ fadeFactor = Math.max(minAlpha, 1 - progress * (1 - minAlpha))
174
+ } else if (!isHolding && movementTotal > 0) {
175
+ // Fade in linearly from minAlpha during movement
176
+ const progress = Math.min(movementProgress / Math.max(1, movementTotal - 1), 1)
177
+ fadeFactor = minAlpha + progress * (1 - minAlpha)
178
+ }
179
+ }
180
+
181
+ // Combine base inactive alpha with the fade factor
182
+ // This ensures inactiveFactor is respected while still allowing fading animation
183
+ defaultRgba.a = baseInactiveAlpha * fadeFactor
184
+
185
+ if (index === -1) {
186
+ return defaultRgba
187
+ }
188
+
189
+ return colors[index] ?? defaultRgba
190
+ }
191
+ }
192
+
193
+ /**
194
+ * Derives a gradient of tail colors from a single bright color using alpha falloff
195
+ * @param brightColor The brightest color (center/head of the scanner)
196
+ * @param steps Number of gradient steps (default: 6)
197
+ * @returns Array of RGBA colors with alpha-based trail fade (background-independent)
198
+ */
199
+ export function deriveTrailColors(brightColor: ColorInput, steps: number = 6): RGBA[] {
200
+ const baseRgba = brightColor instanceof RGBA ? brightColor : RGBA.fromHex(brightColor as string)
201
+
202
+ const colors: RGBA[] = []
203
+
204
+ for (let i = 0; i < steps; i++) {
205
+ // Alpha-based falloff with optional bloom effect
206
+ let alpha: number
207
+ let brightnessFactor: number
208
+
209
+ if (i === 0) {
210
+ // Lead position: full brightness and opacity
211
+ alpha = 1.0
212
+ brightnessFactor = 1.0
213
+ } else if (i === 1) {
214
+ // Slight bloom/glare effect: brighten color but reduce opacity slightly
215
+ alpha = 0.9
216
+ brightnessFactor = 1.15
217
+ } else {
218
+ // Exponential alpha decay for natural-looking trail fade
219
+ alpha = Math.pow(0.65, i - 1)
220
+ brightnessFactor = 1.0
221
+ }
222
+
223
+ const r = Math.min(1.0, baseRgba.r * brightnessFactor)
224
+ const g = Math.min(1.0, baseRgba.g * brightnessFactor)
225
+ const b = Math.min(1.0, baseRgba.b * brightnessFactor)
226
+
227
+ colors.push(RGBA.fromValues(r, g, b, alpha))
228
+ }
229
+
230
+ return colors
231
+ }
232
+
233
+ /**
234
+ * Derives the inactive/default color from a bright color using alpha
235
+ * @param brightColor The brightest color (center/head of the scanner)
236
+ * @param factor Alpha factor for inactive color (default: 0.2, range: 0-1)
237
+ * @returns The same color with reduced alpha for background-independent dimming
238
+ */
239
+ export function deriveInactiveColor(brightColor: ColorInput, factor: number = 0.2): RGBA {
240
+ const baseRgba = brightColor instanceof RGBA ? brightColor : RGBA.fromHex(brightColor as string)
241
+
242
+ // Use the full color brightness but adjust alpha for background-independent dimming
243
+ return RGBA.fromValues(baseRgba.r, baseRgba.g, baseRgba.b, factor)
244
+ }
245
+
246
+ export type KnightRiderStyle = "blocks" | "diamonds"
247
+
248
+ export interface KnightRiderOptions {
249
+ width?: number
250
+ style?: KnightRiderStyle
251
+ holdStart?: number
252
+ holdEnd?: number
253
+ colors?: ColorInput[]
254
+ /** Single color to derive trail from (alternative to providing colors array) */
255
+ color?: ColorInput
256
+ /** Number of trail steps when using single color (default: 6) */
257
+ trailSteps?: number
258
+ defaultColor?: ColorInput
259
+ /** Alpha factor for inactive color when using single color (default: 0.2, range: 0-1) */
260
+ inactiveFactor?: number
261
+ /** Enable fading of inactive dots during hold and movement (default: true) */
262
+ enableFading?: boolean
263
+ /** Minimum alpha value when fading (default: 0, range: 0-1) */
264
+ minAlpha?: number
265
+ }
266
+
267
+ /**
268
+ * Creates frame strings for a Knight Rider style scanner animation
269
+ * @param options Configuration options for the Knight Rider effect
270
+ * @returns Array of frame strings
271
+ */
272
+ export function createFrames(options: KnightRiderOptions = {}): string[] {
273
+ const width = options.width ?? 8
274
+ const style = options.style ?? "diamonds"
275
+ const holdStart = options.holdStart ?? 30
276
+ const holdEnd = options.holdEnd ?? 9
277
+
278
+ const colors =
279
+ options.colors ??
280
+ (options.color
281
+ ? deriveTrailColors(options.color, options.trailSteps)
282
+ : [
283
+ RGBA.fromHex("#ff0000"), // Brightest Red (Center)
284
+ RGBA.fromHex("#ff5555"), // Glare/Bloom
285
+ RGBA.fromHex("#dd0000"), // Trail 1
286
+ RGBA.fromHex("#aa0000"), // Trail 2
287
+ RGBA.fromHex("#770000"), // Trail 3
288
+ RGBA.fromHex("#440000"), // Trail 4
289
+ ])
290
+
291
+ const defaultColor =
292
+ options.defaultColor ??
293
+ (options.color ? deriveInactiveColor(options.color, options.inactiveFactor) : RGBA.fromHex("#330000"))
294
+
295
+ const trailOptions = {
296
+ colors,
297
+ trailLength: colors.length,
298
+ defaultColor,
299
+ direction: "bidirectional" as const,
300
+ holdFrames: { start: holdStart, end: holdEnd },
301
+ enableFading: options.enableFading,
302
+ minAlpha: options.minAlpha,
303
+ }
304
+
305
+ // Bidirectional cycle: Forward (width) + Hold End + Backward (width-1) + Hold Start
306
+ const totalFrames = width + holdEnd + (width - 1) + holdStart
307
+
308
+ // Generate dynamic frames where inactive pixels are dots and active ones are blocks
309
+ const frames = Array.from({ length: totalFrames }, (_, frameIndex) => {
310
+ return Array.from({ length: width }, (_, charIndex) => {
311
+ const index = calculateColorIndex(frameIndex, charIndex, width, trailOptions)
312
+
313
+ if (style === "diamonds") {
314
+ const shapes = ["⬥", "◆", "⬩", "⬪"]
315
+ if (index >= 0 && index < trailOptions.colors.length) {
316
+ return shapes[Math.min(index, shapes.length - 1)]
317
+ }
318
+ return "·"
319
+ }
320
+
321
+ // Default to blocks
322
+ // It's active if we have a valid color index that is within our colors array
323
+ const isActive = index >= 0 && index < trailOptions.colors.length
324
+ return isActive ? "■" : "⬝"
325
+ }).join("")
326
+ })
327
+
328
+ return frames
329
+ }
330
+
331
+ /**
332
+ * Creates a color generator function for Knight Rider style scanner animation
333
+ * @param options Configuration options for the Knight Rider effect
334
+ * @returns ColorGenerator function
335
+ */
336
+ export function createColors(options: KnightRiderOptions = {}): ColorGenerator {
337
+ const holdStart = options.holdStart ?? 30
338
+ const holdEnd = options.holdEnd ?? 9
339
+
340
+ const colors =
341
+ options.colors ??
342
+ (options.color
343
+ ? deriveTrailColors(options.color, options.trailSteps)
344
+ : [
345
+ RGBA.fromHex("#ff0000"), // Brightest Red (Center)
346
+ RGBA.fromHex("#ff5555"), // Glare/Bloom
347
+ RGBA.fromHex("#dd0000"), // Trail 1
348
+ RGBA.fromHex("#aa0000"), // Trail 2
349
+ RGBA.fromHex("#770000"), // Trail 3
350
+ RGBA.fromHex("#440000"), // Trail 4
351
+ ])
352
+
353
+ const defaultColor =
354
+ options.defaultColor ??
355
+ (options.color ? deriveInactiveColor(options.color, options.inactiveFactor) : RGBA.fromHex("#330000"))
356
+
357
+ const trailOptions = {
358
+ colors,
359
+ trailLength: colors.length,
360
+ defaultColor,
361
+ direction: "bidirectional" as const,
362
+ holdFrames: { start: holdStart, end: holdEnd },
363
+ enableFading: options.enableFading,
364
+ minAlpha: options.minAlpha,
365
+ }
366
+
367
+ return createKnightRiderTrail(trailOptions)
368
+ }