list.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. import { type FilteredListProps, useFilteredList } from "@opencode-ai/ui/hooks"
  2. import { createEffect, For, type JSX, on, Show } from "solid-js"
  3. import { createStore } from "solid-js/store"
  4. import { makeEventListener } from "@solid-primitives/event-listener"
  5. import { useI18n } from "../context/i18n"
  6. import { Icon, type IconProps } from "./icon"
  7. import { IconButton } from "./icon-button"
  8. import { TextField } from "./text-field"
  9. function findByKey(container: HTMLElement, key: string) {
  10. const nodes = container.querySelectorAll<HTMLElement>('[data-slot="list-item"][data-key]')
  11. for (const node of nodes) {
  12. if (node.getAttribute("data-key") === key) return node
  13. }
  14. }
  15. export interface ListSearchProps {
  16. placeholder?: string
  17. autofocus?: boolean
  18. hideIcon?: boolean
  19. class?: string
  20. action?: JSX.Element
  21. }
  22. export interface ListAddProps {
  23. class?: string
  24. render: () => JSX.Element
  25. }
  26. export interface ListAddProps {
  27. class?: string
  28. render: () => JSX.Element
  29. }
  30. export interface ListProps<T> extends FilteredListProps<T> {
  31. class?: string
  32. children: (item: T) => JSX.Element
  33. emptyMessage?: string
  34. loadingMessage?: string
  35. onKeyEvent?: (event: KeyboardEvent, item: T | undefined) => void
  36. onMove?: (item: T | undefined) => void
  37. onFilter?: (value: string) => void
  38. activeIcon?: IconProps["name"]
  39. filter?: string
  40. search?: ListSearchProps | boolean
  41. itemWrapper?: (item: T, node: JSX.Element) => JSX.Element
  42. divider?: boolean
  43. add?: ListAddProps
  44. groupHeader?: (group: { category: string; items: T[] }) => JSX.Element
  45. }
  46. export interface ListRef {
  47. onKeyDown: (e: KeyboardEvent) => void
  48. setScrollRef: (el: HTMLDivElement | undefined) => void
  49. setFilter: (value: string) => void
  50. }
  51. export function List<T>(props: ListProps<T> & { ref?: (ref: ListRef) => void }) {
  52. const i18n = useI18n()
  53. let inputRef: HTMLInputElement | HTMLTextAreaElement | undefined
  54. const [store, setStore] = createStore({
  55. mouseActive: false,
  56. scrollRef: undefined as HTMLDivElement | undefined,
  57. internalFilter: "",
  58. })
  59. const scrollRef = () => store.scrollRef
  60. const setScrollRef = (el: HTMLDivElement | undefined) => setStore("scrollRef", el)
  61. const internalFilter = () => store.internalFilter
  62. const setInternalFilter = (value: string) => setStore("internalFilter", value)
  63. const scrollIntoView = (container: HTMLDivElement, node: HTMLElement, block: "center" | "nearest") => {
  64. const containerRect = container.getBoundingClientRect()
  65. const nodeRect = node.getBoundingClientRect()
  66. const top = nodeRect.top - containerRect.top + container.scrollTop
  67. const bottom = top + nodeRect.height
  68. const viewTop = container.scrollTop
  69. const viewBottom = viewTop + container.clientHeight
  70. const target =
  71. block === "center"
  72. ? top - container.clientHeight / 2 + nodeRect.height / 2
  73. : top < viewTop
  74. ? top
  75. : bottom > viewBottom
  76. ? bottom - container.clientHeight
  77. : viewTop
  78. const max = Math.max(0, container.scrollHeight - container.clientHeight)
  79. container.scrollTop = Math.max(0, Math.min(target, max))
  80. }
  81. const { filter, grouped, flat, active, setActive, onKeyDown, onInput, refetch } = useFilteredList<T>(props)
  82. const searchProps = () => (typeof props.search === "object" ? props.search : {})
  83. const searchAction = () => searchProps().action
  84. const addProps = () => props.add
  85. const showAdd = () => !!addProps()
  86. const moved = (event: MouseEvent) => event.movementX !== 0 || event.movementY !== 0
  87. const applyFilter = (value: string, options?: { ref?: boolean }) => {
  88. const prev = filter()
  89. setInternalFilter(value)
  90. onInput(value)
  91. props.onFilter?.(value)
  92. if (!options?.ref) return
  93. // Force a refetch even if the value is unchanged.
  94. // This is important for programmatic changes like Tab completion.
  95. if (prev === value) {
  96. void refetch()
  97. return
  98. }
  99. queueMicrotask(() => refetch())
  100. }
  101. createEffect(() => {
  102. if (props.filter === undefined) return
  103. if (props.filter === internalFilter()) return
  104. setInternalFilter(props.filter)
  105. onInput(props.filter)
  106. })
  107. createEffect(
  108. on(
  109. filter,
  110. () => {
  111. scrollRef()?.scrollTo(0, 0)
  112. },
  113. { defer: true },
  114. ),
  115. )
  116. createEffect(() => {
  117. const scroll = scrollRef()
  118. if (!scroll) return
  119. if (!props.current) return
  120. const key = props.key(props.current)
  121. requestAnimationFrame(() => {
  122. const element = findByKey(scroll, key)
  123. if (!element) return
  124. scrollIntoView(scroll, element, "center")
  125. })
  126. })
  127. createEffect(() => {
  128. const all = flat()
  129. if (store.mouseActive || all.length === 0) return
  130. const scroll = scrollRef()
  131. if (!scroll) return
  132. if (active() === props.key(all[0])) {
  133. scroll.scrollTo(0, 0)
  134. return
  135. }
  136. const key = active()
  137. if (!key) return
  138. const element = findByKey(scroll, key)
  139. if (!element) return
  140. scrollIntoView(scroll, element, "center")
  141. })
  142. createEffect(() => {
  143. const all = flat()
  144. const current = active()
  145. const item = all.find((x) => props.key(x) === current)
  146. props.onMove?.(item)
  147. })
  148. const handleSelect = (item: T | undefined, index: number) => {
  149. props.onSelect?.(item, index)
  150. }
  151. const handleKey = (e: KeyboardEvent) => {
  152. setStore("mouseActive", false)
  153. if (e.key === "Escape") return
  154. const all = flat()
  155. const selected = all.find((x) => props.key(x) === active())
  156. const index = selected ? all.indexOf(selected) : -1
  157. props.onKeyEvent?.(e, selected)
  158. if (e.defaultPrevented) return
  159. if (e.key === "Enter" && !e.isComposing) {
  160. e.preventDefault()
  161. if (selected) handleSelect(selected, index)
  162. } else if (props.search) {
  163. if (e.ctrlKey && !e.metaKey && !e.altKey && !e.shiftKey && (e.key === "n" || e.key === "p")) {
  164. onKeyDown(e)
  165. return
  166. }
  167. if (e.key === "ArrowDown" || e.key === "ArrowUp") {
  168. onKeyDown(e)
  169. }
  170. } else {
  171. onKeyDown(e)
  172. }
  173. }
  174. props.ref?.({
  175. onKeyDown: handleKey,
  176. setScrollRef,
  177. setFilter: (value) => applyFilter(value, { ref: true }),
  178. })
  179. const renderAdd = () => {
  180. const add = addProps()
  181. if (!add) return null
  182. return (
  183. <div data-slot="list-item-add" classList={{ [add.class ?? ""]: !!add.class }}>
  184. {add.render()}
  185. </div>
  186. )
  187. }
  188. function GroupHeader(groupProps: { group: { category: string; items: T[] } }): JSX.Element {
  189. const [state, setState] = createStore({
  190. stuck: false,
  191. header: undefined as HTMLDivElement | undefined,
  192. })
  193. createEffect(() => {
  194. const scroll = scrollRef()
  195. const node = state.header
  196. if (!scroll || !node) return
  197. const handler = () => {
  198. const rect = node.getBoundingClientRect()
  199. const scrollRect = scroll.getBoundingClientRect()
  200. setState("stuck", rect.top <= scrollRect.top + 1 && scroll.scrollTop > 0)
  201. }
  202. makeEventListener(scroll, "scroll", handler, { passive: true })
  203. handler()
  204. })
  205. return (
  206. <div data-slot="list-header" data-stuck={state.stuck} ref={(el) => setState("header", el)}>
  207. {props.groupHeader?.(groupProps.group) ?? groupProps.group.category}
  208. </div>
  209. )
  210. }
  211. const emptyMessage = () => {
  212. if (grouped.loading) return props.loadingMessage ?? i18n.t("ui.list.loading")
  213. if (props.emptyMessage) return props.emptyMessage
  214. const query = filter()
  215. if (!query) return i18n.t("ui.list.empty")
  216. const suffix = i18n.t("ui.list.emptyWithFilter.suffix")
  217. return (
  218. <>
  219. <span>{i18n.t("ui.list.emptyWithFilter.prefix")}</span>
  220. <span data-slot="list-filter">&quot;{query}&quot;</span>
  221. <Show when={suffix}>
  222. <span>{suffix}</span>
  223. </Show>
  224. </>
  225. )
  226. }
  227. return (
  228. <div data-component="list" classList={{ [props.class ?? ""]: !!props.class }}>
  229. <Show when={!!props.search}>
  230. <div data-slot="list-search-wrapper">
  231. <div
  232. data-slot="list-search"
  233. classList={{ [searchProps().class ?? ""]: !!searchProps().class }}
  234. onPointerDown={(event) => {
  235. const container = event.currentTarget
  236. if (!(container instanceof HTMLElement)) return
  237. const node = container.querySelector("input, textarea")
  238. const input = node instanceof HTMLInputElement || node instanceof HTMLTextAreaElement ? node : inputRef
  239. input?.focus()
  240. // Prevent global listeners (e.g. dnd sensors) from cancelling focus.
  241. event.stopPropagation()
  242. }}
  243. >
  244. <div data-slot="list-search-container">
  245. <Show when={!searchProps().hideIcon}>
  246. <Icon name="magnifying-glass" />
  247. </Show>
  248. <TextField
  249. autofocus={searchProps().autofocus}
  250. variant="ghost"
  251. data-slot="list-search-input"
  252. type="text"
  253. ref={(el: HTMLInputElement | HTMLTextAreaElement) => {
  254. inputRef = el
  255. }}
  256. value={internalFilter()}
  257. onChange={(value) => applyFilter(value)}
  258. onKeyDown={handleKey}
  259. placeholder={searchProps().placeholder}
  260. spellcheck={false}
  261. autocorrect="off"
  262. autocomplete="off"
  263. autocapitalize="off"
  264. />
  265. </div>
  266. <Show when={internalFilter()}>
  267. <IconButton
  268. icon="circle-x"
  269. variant="ghost"
  270. onClick={() => {
  271. setInternalFilter("")
  272. queueMicrotask(() => inputRef?.focus())
  273. }}
  274. aria-label={i18n.t("ui.list.clearFilter")}
  275. />
  276. </Show>
  277. </div>
  278. {searchAction()}
  279. </div>
  280. </Show>
  281. <div ref={setScrollRef} data-slot="list-scroll">
  282. <Show
  283. when={flat().length > 0 || showAdd()}
  284. fallback={
  285. <div data-slot="list-empty-state">
  286. <div data-slot="list-message">{emptyMessage()}</div>
  287. </div>
  288. }
  289. >
  290. <For each={grouped.latest}>
  291. {(group, groupIndex) => {
  292. const isLastGroup = () => groupIndex() === grouped.latest.length - 1
  293. return (
  294. <div data-slot="list-group">
  295. <Show when={group.category}>
  296. <GroupHeader group={group} />
  297. </Show>
  298. <div data-slot="list-items">
  299. <For each={group.items}>
  300. {(item, i) => {
  301. const node = (
  302. <button
  303. data-slot="list-item"
  304. data-key={props.key(item)}
  305. data-active={props.key(item) === active()}
  306. data-selected={item === props.current}
  307. onClick={() => handleSelect(item, i())}
  308. onKeyDown={handleKey}
  309. type="button"
  310. onMouseMove={(event) => {
  311. if (!moved(event)) return
  312. setStore("mouseActive", true)
  313. setActive(props.key(item))
  314. }}
  315. onMouseLeave={() => {
  316. if (!store.mouseActive) return
  317. setActive(null)
  318. }}
  319. >
  320. {props.children(item)}
  321. <Show when={item === props.current}>
  322. <span data-slot="list-item-selected-icon">
  323. <Icon name="check-small" />
  324. </span>
  325. </Show>
  326. <Show when={props.activeIcon}>
  327. {(icon) => (
  328. <span data-slot="list-item-active-icon">
  329. <Icon name={icon()} />
  330. </span>
  331. )}
  332. </Show>
  333. {props.divider && (i() !== group.items.length - 1 || (showAdd() && isLastGroup())) && (
  334. <span data-slot="list-item-divider" />
  335. )}
  336. </button>
  337. )
  338. if (props.itemWrapper) return props.itemWrapper(item, node)
  339. return node
  340. }}
  341. </For>
  342. <Show when={showAdd() && isLastGroup()}>{renderAdd()}</Show>
  343. </div>
  344. </div>
  345. )
  346. }}
  347. </For>
  348. <Show when={grouped.latest.length === 0 && showAdd()}>
  349. <div data-slot="list-group">
  350. <div data-slot="list-items">{renderAdd()}</div>
  351. </div>
  352. </Show>
  353. </Show>
  354. </div>
  355. </div>
  356. )
  357. }