dialog-select.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. import { InputRenderable, RGBA, ScrollBoxRenderable, TextAttributes } from "@opentui/core"
  2. import { useTheme, selectedForeground } from "@tui/context/theme"
  3. import { entries, filter, flatMap, groupBy, pipe, take } from "remeda"
  4. import { batch, createEffect, createMemo, For, Show, type JSX, on } from "solid-js"
  5. import { createStore } from "solid-js/store"
  6. import { useKeyboard, useTerminalDimensions } from "@opentui/solid"
  7. import * as fuzzysort from "fuzzysort"
  8. import { isDeepEqual } from "remeda"
  9. import { useDialog, type DialogContext } from "@tui/ui/dialog"
  10. import { useKeybind } from "@tui/context/keybind"
  11. import { Keybind } from "@/util/keybind"
  12. import { Locale } from "@/util/locale"
  13. export interface DialogSelectProps<T> {
  14. title: string
  15. placeholder?: string
  16. options: DialogSelectOption<T>[]
  17. ref?: (ref: DialogSelectRef<T>) => void
  18. onMove?: (option: DialogSelectOption<T>) => void
  19. onFilter?: (query: string) => void
  20. onSelect?: (option: DialogSelectOption<T>) => void
  21. skipFilter?: boolean
  22. keybind?: {
  23. keybind: Keybind.Info
  24. title: string
  25. disabled?: boolean
  26. onTrigger: (option: DialogSelectOption<T>) => void
  27. }[]
  28. current?: T
  29. }
  30. export interface DialogSelectOption<T = any> {
  31. title: string
  32. value: T
  33. description?: string
  34. footer?: JSX.Element | string
  35. category?: string
  36. disabled?: boolean
  37. bg?: RGBA
  38. gutter?: JSX.Element
  39. onSelect?: (ctx: DialogContext, trigger?: "prompt") => void
  40. }
  41. export type DialogSelectRef<T> = {
  42. filter: string
  43. filtered: DialogSelectOption<T>[]
  44. }
  45. export function DialogSelect<T>(props: DialogSelectProps<T>) {
  46. const dialog = useDialog()
  47. const { theme } = useTheme()
  48. const [store, setStore] = createStore({
  49. selected: 0,
  50. filter: "",
  51. })
  52. createEffect(
  53. on(
  54. () => props.current,
  55. (current) => {
  56. if (current) {
  57. const currentIndex = flat().findIndex((opt) => isDeepEqual(opt.value, current))
  58. if (currentIndex >= 0) {
  59. setStore("selected", currentIndex)
  60. }
  61. }
  62. },
  63. ),
  64. )
  65. let input: InputRenderable
  66. const filtered = createMemo(() => {
  67. const needle = store.filter.toLowerCase()
  68. const result = pipe(
  69. props.options,
  70. filter((x) => x.disabled !== true),
  71. (x) =>
  72. !needle || props.skipFilter ? x : fuzzysort.go(needle, x, { keys: ["title", "category"] }).map((x) => x.obj),
  73. )
  74. return result
  75. })
  76. const grouped = createMemo(() => {
  77. const result = pipe(
  78. filtered(),
  79. groupBy((x) => x.category ?? ""),
  80. // mapValues((x) => x.sort((a, b) => a.title.localeCompare(b.title))),
  81. entries(),
  82. )
  83. return result
  84. })
  85. const flat = createMemo(() => {
  86. return pipe(
  87. grouped(),
  88. flatMap(([_, options]) => options),
  89. )
  90. })
  91. const dimensions = useTerminalDimensions()
  92. const height = createMemo(() =>
  93. Math.min(flat().length + grouped().length * 2 - 1, Math.floor(dimensions().height / 2) - 6),
  94. )
  95. const selected = createMemo(() => flat()[store.selected])
  96. createEffect(
  97. on([() => store.filter, () => props.current], ([filter, current]) => {
  98. if (filter.length > 0) {
  99. setStore("selected", 0)
  100. } else if (current) {
  101. const currentIndex = flat().findIndex((opt) => isDeepEqual(opt.value, current))
  102. if (currentIndex >= 0) {
  103. setStore("selected", currentIndex)
  104. }
  105. }
  106. scroll?.scrollTo(0)
  107. }),
  108. )
  109. function move(direction: number) {
  110. if (flat().length === 0) return
  111. let next = store.selected + direction
  112. if (next < 0) next = flat().length - 1
  113. if (next >= flat().length) next = 0
  114. moveTo(next)
  115. }
  116. function moveTo(next: number) {
  117. setStore("selected", next)
  118. props.onMove?.(selected()!)
  119. if (!scroll) return
  120. const target = scroll.getChildren().find((child) => {
  121. return child.id === JSON.stringify(selected()?.value)
  122. })
  123. if (!target) return
  124. const y = target.y - scroll.y
  125. if (y >= scroll.height) {
  126. scroll.scrollBy(y - scroll.height + 1)
  127. }
  128. if (y < 0) {
  129. scroll.scrollBy(y)
  130. if (isDeepEqual(flat()[0].value, selected()?.value)) {
  131. scroll.scrollTo(0)
  132. }
  133. }
  134. }
  135. const keybind = useKeybind()
  136. useKeyboard((evt) => {
  137. if (evt.name === "up" || (evt.ctrl && evt.name === "p")) move(-1)
  138. if (evt.name === "down" || (evt.ctrl && evt.name === "n")) move(1)
  139. if (evt.name === "pageup") move(-10)
  140. if (evt.name === "pagedown") move(10)
  141. if (evt.name === "return") {
  142. const option = selected()
  143. if (option) {
  144. // evt.preventDefault()
  145. if (option.onSelect) option.onSelect(dialog)
  146. props.onSelect?.(option)
  147. }
  148. }
  149. for (const item of props.keybind ?? []) {
  150. if (item.disabled) continue
  151. if (Keybind.match(item.keybind, keybind.parse(evt))) {
  152. const s = selected()
  153. if (s) {
  154. evt.preventDefault()
  155. item.onTrigger(s)
  156. }
  157. }
  158. }
  159. })
  160. let scroll: ScrollBoxRenderable | undefined
  161. const ref: DialogSelectRef<T> = {
  162. get filter() {
  163. return store.filter
  164. },
  165. get filtered() {
  166. return filtered()
  167. },
  168. }
  169. props.ref?.(ref)
  170. const keybinds = createMemo(() => props.keybind?.filter((x) => !x.disabled) ?? [])
  171. return (
  172. <box gap={1} paddingBottom={1}>
  173. <box paddingLeft={4} paddingRight={4}>
  174. <box flexDirection="row" justifyContent="space-between">
  175. <text fg={theme.text} attributes={TextAttributes.BOLD}>
  176. {props.title}
  177. </text>
  178. <text fg={theme.textMuted}>esc</text>
  179. </box>
  180. <box paddingTop={1} paddingBottom={1}>
  181. <input
  182. onInput={(e) => {
  183. batch(() => {
  184. setStore("filter", e)
  185. props.onFilter?.(e)
  186. })
  187. }}
  188. focusedBackgroundColor={theme.backgroundPanel}
  189. cursorColor={theme.primary}
  190. focusedTextColor={theme.textMuted}
  191. ref={(r) => {
  192. input = r
  193. setTimeout(() => input.focus(), 1)
  194. }}
  195. placeholder={props.placeholder ?? "Search"}
  196. />
  197. </box>
  198. </box>
  199. <Show
  200. when={grouped().length > 0}
  201. fallback={
  202. <box paddingLeft={4} paddingRight={4} paddingTop={1}>
  203. <text fg={theme.textMuted}>No results found</text>
  204. </box>
  205. }
  206. >
  207. <scrollbox
  208. paddingLeft={1}
  209. paddingRight={1}
  210. scrollbarOptions={{ visible: false }}
  211. ref={(r: ScrollBoxRenderable) => (scroll = r)}
  212. maxHeight={height()}
  213. >
  214. <For each={grouped()}>
  215. {([category, options], index) => (
  216. <>
  217. <Show when={category}>
  218. <box paddingTop={index() > 0 ? 1 : 0} paddingLeft={3}>
  219. <text fg={theme.accent} attributes={TextAttributes.BOLD}>
  220. {category}
  221. </text>
  222. </box>
  223. </Show>
  224. <For each={options}>
  225. {(option) => {
  226. const active = createMemo(() => isDeepEqual(option.value, selected()?.value))
  227. const current = createMemo(() => isDeepEqual(option.value, props.current))
  228. return (
  229. <box
  230. id={JSON.stringify(option.value)}
  231. flexDirection="row"
  232. onMouseUp={() => {
  233. option.onSelect?.(dialog)
  234. props.onSelect?.(option)
  235. }}
  236. onMouseOver={() => {
  237. const index = filtered().findIndex((x) => isDeepEqual(x.value, option.value))
  238. if (index === -1) return
  239. moveTo(index)
  240. }}
  241. backgroundColor={active() ? (option.bg ?? theme.primary) : RGBA.fromInts(0, 0, 0, 0)}
  242. paddingLeft={current() || option.gutter ? 1 : 3}
  243. paddingRight={3}
  244. gap={1}
  245. >
  246. <Option
  247. title={option.title}
  248. footer={option.footer}
  249. description={option.description !== category ? option.description : undefined}
  250. active={active()}
  251. current={current()}
  252. gutter={option.gutter}
  253. />
  254. </box>
  255. )
  256. }}
  257. </For>
  258. </>
  259. )}
  260. </For>
  261. </scrollbox>
  262. </Show>
  263. <Show when={keybinds().length} fallback={<box flexShrink={0} />}>
  264. <box paddingRight={2} paddingLeft={4} flexDirection="row" gap={2} flexShrink={0} paddingTop={1}>
  265. <For each={keybinds()}>
  266. {(item) => (
  267. <text>
  268. <span style={{ fg: theme.text }}>
  269. <b>{item.title}</b>{" "}
  270. </span>
  271. <span style={{ fg: theme.textMuted }}>{Keybind.toString(item.keybind)}</span>
  272. </text>
  273. )}
  274. </For>
  275. </box>
  276. </Show>
  277. </box>
  278. )
  279. }
  280. function Option(props: {
  281. title: string
  282. description?: string
  283. active?: boolean
  284. current?: boolean
  285. footer?: JSX.Element | string
  286. gutter?: JSX.Element
  287. onMouseOver?: () => void
  288. }) {
  289. const { theme } = useTheme()
  290. const fg = selectedForeground(theme)
  291. return (
  292. <>
  293. <Show when={props.current}>
  294. <text flexShrink={0} fg={props.active ? fg : props.current ? theme.primary : theme.text} marginRight={0.5}>
  295. </text>
  296. </Show>
  297. <Show when={!props.current && props.gutter}>
  298. <box flexShrink={0} marginRight={0.5}>
  299. {props.gutter}
  300. </box>
  301. </Show>
  302. <text
  303. flexGrow={1}
  304. fg={props.active ? fg : props.current ? theme.primary : theme.text}
  305. attributes={props.active ? TextAttributes.BOLD : undefined}
  306. overflow="hidden"
  307. paddingLeft={3}
  308. >
  309. {Locale.truncate(props.title, 61)}
  310. <Show when={props.description}>
  311. <span style={{ fg: props.active ? fg : theme.textMuted }}> {props.description}</span>
  312. </Show>
  313. </text>
  314. <Show when={props.footer}>
  315. <box flexShrink={0}>
  316. <text fg={props.active ? fg : theme.textMuted}>{props.footer}</text>
  317. </box>
  318. </Show>
  319. </>
  320. )
  321. }