dialog-select.tsx 11 KB

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