fix(ui): keep the list filter query in one state machine (#61661)

This commit is contained in:
Luke Parker
2026-11-04 10:46:36 -06:00
committed by GitHub
Unverified
parent dbdb30b40f
commit 7ebb13eda3
4 changed files with 631 additions and 251 deletions
+40 -137
View File
@@ -1,8 +1,9 @@
import { type FilteredListProps, useFilteredList } from "@opencode/ui/hooks"
import { createEffect, For, type JSX, on, Show } from "solid-js"
import { createEffect, createMemo, createSignal, For, type JSX, on, Show } from "solid-js"
import { createStore } from "solid-js/store"
import { makeEventListener } from "@solid-primitives/event-listener"
import { useI18n } from "../context/i18n"
import { listActive, listScrollTarget } from "../hooks/list-machine"
import { Icon, type IconProps } from "@opencode/ui/icon"
import { IconButton } from "@opencode/ui/icon-button"
import { TextField } from "./text-field"
@@ -28,11 +29,6 @@ export interface ListAddProps {
render: () => JSX.Element
}
export interface ListAddProps {
class?: string
render: () => JSX.Element
}
export interface ListProps<T> extends FilteredListProps<T> {
class?: string
children: (item: T) => JSX.Element
@@ -40,9 +36,7 @@ export interface ListProps<T> extends FilteredListProps<T> {
loadingMessage?: string
onKeyEvent?: (event: KeyboardEvent, item: T | undefined) => void
onMove?: (item: T | undefined) => void
onFilter?: (value: string) => void
activeIcon?: IconProps["name"]
filter?: string
search?: ListSearchProps | boolean
itemWrapper?: (item: T, node: JSX.Element) => JSX.Element
divider?: boolean
@@ -60,16 +54,7 @@ export function List<T>(props: ListProps<T> & { ref?: (ref: ListRef) => void })
const i18n = useI18n()
let inputRef: HTMLInputElement | HTMLTextAreaElement | undefined
const [store, setStore] = createStore({
mouseActive: false,
scrollRef: undefined as HTMLDivElement | undefined,
internalFilter: "",
})
const scrollRef = () => store.scrollRef
const setScrollRef = (el: HTMLDivElement | undefined) => setStore("scrollRef", el)
const internalFilter = () => store.internalFilter
const setInternalFilter = (value: string) => setStore("internalFilter", value)
const [scrollRef, setScrollRef] = createSignal<HTMLDivElement>()
const scrollIntoView = (container: HTMLDivElement, node: HTMLElement, block: "center" | "nearest") => {
const containerRect = container.getBoundingClientRect()
@@ -92,121 +77,43 @@ export function List<T>(props: ListProps<T> & { ref?: (ref: ListRef) => void })
container.scrollTop = Math.max(0, Math.min(target, max))
}
const { filter, grouped, flat, active, setActive, onKeyDown, onInput, refetch } = useFilteredList<T>(props)
const list = useFilteredList<T>(props)
const keys = createMemo(() => list.state().keys)
const highlight = createMemo(() => list.state().highlight)
const searchProps = () => (typeof props.search === "object" ? props.search : {})
const searchProps = () => (props.search && props.search !== true ? props.search : {})
const searchAction = () => searchProps().action
const addProps = () => props.add
const showAdd = () => !!addProps()
const moved = (event: MouseEvent) => event.movementX !== 0 || event.movementY !== 0
const applyFilter = (value: string, options?: { ref?: boolean }) => {
const prev = filter()
setInternalFilter(value)
onInput(value)
props.onFilter?.(value)
if (!options?.ref) return
// Force a refetch even if the value is unchanged.
// This is important for programmatic changes like Tab completion.
if (prev === value) {
void refetch()
return
}
queueMicrotask(() => refetch())
}
createEffect(on(list.filter, () => scrollRef()?.scrollTo(0, 0), { defer: true }))
createEffect(() => {
if (props.filter === undefined) return
if (props.filter === internalFilter()) return
setInternalFilter(props.filter)
onInput(props.filter)
})
createEffect(
on(
filter,
() => {
scrollRef()?.scrollTo(0, 0)
},
{ defer: true },
),
)
createEffect(() => {
const all = flat()
if (store.mouseActive || all.length === 0) return
const target = listScrollTarget({ keys: keys(), highlight: highlight() })
const scroll = scrollRef()
if (!scroll) return
if (!scroll || target.type === "none") return
if (active() === props.key(all[0])) {
scroll.scrollTo(0, 0)
if (target.type === "top") return scroll.scrollTo(0, 0)
const element = findByKey(scroll, target.key)
return
}
const key = active()
if (!key) return
const element = findByKey(scroll, key)
if (!element) return
scrollIntoView(scroll, element, "center")
if (element) scrollIntoView(scroll, element, "center")
})
createEffect(() => {
const all = flat()
const current = active()
const item = all.find((x) => props.key(x) === current)
props.onMove?.(item)
})
const activeItem = createMemo(() => listActive(list.state())?.item)
const handleSelect = (item: T | undefined, index: number) => {
props.onSelect?.(item, index)
}
createEffect(() => props.onMove?.(activeItem()))
const handleKey = (e: KeyboardEvent) => {
setStore("mouseActive", false)
if (e.key === "Escape") return
const all = flat()
const selected = all.find((x) => props.key(x) === active())
const index = selected ? all.indexOf(selected) : -1
props.onKeyEvent?.(e, selected)
if (e.defaultPrevented) return
if (e.key === "Enter" && !e.isComposing) {
e.preventDefault()
if (selected) handleSelect(selected, index)
} else if (props.search) {
if (e.ctrlKey && !e.metaKey && !e.altKey && !e.shiftKey && (e.key === "n" || e.key === "p")) {
onKeyDown(e)
return
}
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
onKeyDown(e)
}
} else {
onKeyDown(e)
}
if (e.key !== "Escape") props.onKeyEvent?.(e, activeItem())
list.onKeyDown(e, { search: !!props.search, claimed: e.key === "Escape" || e.defaultPrevented })
}
props.ref?.({
onKeyDown: handleKey,
setScrollRef,
setFilter: (value) => applyFilter(value, { ref: true }),
// Forces a reload even when the value is unchanged, for programmatic changes like Tab completion.
setFilter: (value) => list.dispatch({ type: "query.change", value, force: true }),
})
const renderAdd = () => {
@@ -222,10 +129,7 @@ export function List<T>(props: ListProps<T> & { ref?: (ref: ListRef) => void })
}
function GroupHeader(groupProps: { group: { category: string; items: T[] } }): JSX.Element {
const [state, setState] = createStore({
stuck: false,
header: undefined as HTMLDivElement | undefined,
})
const [state, setState] = createStore<{ stuck: boolean; header?: HTMLDivElement }>({ stuck: false })
createEffect(() => {
const scroll = scrollRef()
@@ -251,11 +155,11 @@ export function List<T>(props: ListProps<T> & { ref?: (ref: ListRef) => void })
}
const emptyMessage = () => {
if (grouped.loading) return props.loadingMessage ?? i18n.t("ui.list.loading")
if (list.grouped.loading) return props.loadingMessage ?? i18n.t("ui.list.loading")
if (props.emptyMessage) return props.emptyMessage
const query = filter()
const query = list.filter()
if (!query) return i18n.t("ui.list.empty")
@@ -304,8 +208,8 @@ export function List<T>(props: ListProps<T> & { ref?: (ref: ListRef) => void })
ref={(el: HTMLInputElement | HTMLTextAreaElement) => {
inputRef = el
}}
value={internalFilter()}
onChange={(value) => applyFilter(value)}
value={list.filter()}
onChange={(value) => list.onInput(value)}
onKeyDown={handleKey}
placeholder={searchProps().placeholder}
spellcheck={false}
@@ -314,12 +218,12 @@ export function List<T>(props: ListProps<T> & { ref?: (ref: ListRef) => void })
autocapitalize="off"
/>
</div>
<Show when={internalFilter()}>
<Show when={list.filter()}>
<IconButton
icon={<Icon name="circle-x" />}
variant="ghost"
onClick={() => {
setInternalFilter("")
list.clear()
queueMicrotask(() => inputRef?.focus())
}}
aria-label={i18n.t("ui.list.clearFilter")}
@@ -331,16 +235,16 @@ export function List<T>(props: ListProps<T> & { ref?: (ref: ListRef) => void })
</Show>
<div ref={setScrollRef} data-slot="list-scroll">
<Show
when={flat().length > 0 || showAdd()}
when={list.flat().length > 0 || showAdd()}
fallback={
<div data-slot="list-empty-state">
<div data-slot="list-message">{emptyMessage()}</div>
</div>
}
>
<For each={grouped.latest}>
<For each={list.grouped.latest}>
{(group, groupIndex) => {
const isLastGroup = () => groupIndex() === grouped.latest.length - 1
const isLastGroup = () => groupIndex() === list.grouped.latest.length - 1
return (
<div data-slot="list-group">
@@ -354,20 +258,19 @@ export function List<T>(props: ListProps<T> & { ref?: (ref: ListRef) => void })
<button
data-slot="list-item"
data-key={props.key(item)}
data-active={props.key(item) === active()}
data-active={props.key(item) === list.active()}
data-selected={item === props.current}
onClick={() => handleSelect(item, i())}
onClick={() => props.onSelect?.(item, i())}
onKeyDown={handleKey}
type="button"
onMouseMove={(event) => {
if (!moved(event)) return
setStore("mouseActive", true)
setActive(props.key(item))
}}
onMouseLeave={() => {
if (!store.mouseActive) return
setActive(null)
}}
onMouseMove={(event) =>
list.dispatch({
type: "pointer.move",
key: props.key(item),
moved: event.movementX !== 0 || event.movementY !== 0,
})
}
onMouseLeave={() => list.dispatch({ type: "pointer.leave" })}
>
{props.children(item)}
<Show when={item === props.current}>
@@ -401,7 +304,7 @@ export function List<T>(props: ListProps<T> & { ref?: (ref: ListRef) => void })
)
}}
</For>
<Show when={grouped.latest.length === 0 && showAdd()}>
<Show when={list.grouped.latest.length === 0 && showAdd()}>
<div data-slot="list-group">
<div data-slot="list-items">{renderAdd()}</div>
</div>
+200
View File
@@ -0,0 +1,200 @@
import { expect, test } from "bun:test"
import {
createListState,
listActive,
listScrollTarget,
transitionList,
type ListEffect,
type ListEvent,
type ListKeyDown,
type ListState,
} from "./list-machine"
const items = ["Alpha", "Beta", "Gamma"]
const config = { key: (item: string) => item }
function run(state: ListState<string>, ...events: ListEvent<string>[]) {
return events.reduce<{ state: ListState<string>; effects: ListEffect<string>[]; handled: boolean }>(
(result, event) => transitionList(result.state, event, config),
{ state, effects: [], handled: false },
)
}
// Answers the load a transition asked for, as the driver does for a synchronous `items` list.
function settle(result: { state: ListState<string>; effects: ListEffect<string>[] }) {
const load = result.effects.find((effect) => effect.type === "load")
if (!load) return result.state
const matches = items.filter((item) => item.toLowerCase().includes(load.query.toLowerCase()))
return transitionList(result.state, { type: "load.resolved", attempt: load.attempt, items: matches }, config).state
}
function loaded(filter?: string) {
return settle(run(createListState<string>(filter), { type: "items.reload" }))
}
function key(key: string, input: Partial<Omit<ListKeyDown, "type" | "key">> = {}): ListKeyDown {
return {
type: "key.down",
key,
ctrl: false,
alt: false,
meta: false,
shift: false,
composing: false,
search: false,
claimed: false,
...input,
}
}
test("the clear button shows every row again and tells the parent", () => {
const typed = settle(run(loaded(), { type: "query.change", value: "al" }))
expect(typed.rows).toEqual(["Alpha"])
const cleared = run(typed, { type: "query.change", value: "" })
expect(cleared.effects).toEqual([
{ type: "notify.filter", value: "" },
{ type: "load", attempt: 3, query: "" },
])
const state = settle(cleared)
expect(state.filter).toEqual({ type: "uncontrolled", query: "" })
expect(state.rows).toEqual(items)
expect(state.highlight.activeKey).toBe("Alpha")
})
test("a controlled list clears when the parent accepts and keeps rows and query together when it does not", () => {
const start = loaded("al")
expect(start.rows).toEqual(["Alpha"])
const cleared = run(start, { type: "query.change", value: "" })
expect(cleared.effects).toEqual([{ type: "notify.filter", value: "" }])
expect(cleared.state).toBe(start)
const accepted = run(cleared.state, { type: "filter.controlled", value: "" })
expect(accepted.effects).toEqual([{ type: "load", attempt: 2, query: "" }])
expect(settle(accepted).rows).toEqual(items)
expect(settle(accepted).filter).toEqual({ type: "controlled", query: "" })
})
test("a forced change reloads an unchanged query once", () => {
const start = loaded()
expect(run(start, { type: "query.change", value: "" }).effects).toEqual([])
expect(run(start, { type: "query.change", value: "", force: true }).effects).toEqual([
{ type: "notify.filter", value: "" },
{ type: "load", attempt: 2, query: "" },
])
expect(run(loaded("al"), { type: "query.change", value: "al", force: true }).effects).toEqual([
{ type: "notify.filter", value: "al" },
{ type: "load", attempt: 2, query: "al" },
])
})
test("switching between controlled and uncontrolled keeps the query and reloads only on a new one", () => {
const start = loaded()
const adopted = run(start, { type: "filter.controlled", value: "" })
expect(adopted.effects).toEqual([])
expect(adopted.state.filter).toEqual({ type: "controlled", query: "" })
expect(run(adopted.state, { type: "filter.uncontrolled" }).state.filter).toEqual({ type: "uncontrolled", query: "" })
expect(run(start, { type: "filter.controlled", value: "be" }).effects).toEqual([
{ type: "load", attempt: 2, query: "be" },
])
})
test("a superseded or late load result is ignored", () => {
const first = run(loaded(), { type: "query.change", value: "a" })
const second = run(first.state, { type: "query.change", value: "al" })
const stale = transitionList(second.state, { type: "load.resolved", attempt: 2, items }, config)
expect(stale.state).toBe(second.state)
const ready = transitionList(second.state, { type: "load.resolved", attempt: 3, items }, config).state
expect(ready).toMatchObject({ status: "ready", epoch: 3, rows: ["Alpha"] })
expect(transitionList(ready, { type: "load.failed", attempt: 3 }, config).state).toBe(ready)
})
test("a failed load settles with no rows and keeps the list usable", () => {
const loading = run(loaded(), { type: "items.reload" })
const failed = transitionList(loading.state, { type: "load.failed", attempt: 2 }, config).state
expect(failed).toMatchObject({ status: "ready", epoch: 2, rows: [], highlight: { activeKey: null } })
expect(settle(run(failed, { type: "items.reload" })).rows).toEqual(items)
})
test("the pointer takes the highlight without scrolling and any key gives it back", () => {
const start = loaded()
expect(run(start, { type: "pointer.move", key: "Beta", moved: false }).state).toBe(start)
const hovered = run(start, { type: "pointer.move", key: "Beta", moved: true }).state
expect(hovered.highlight).toEqual({ mode: "mouse", activeKey: "Beta" })
expect(listScrollTarget(hovered)).toEqual({ type: "none" })
const left = run(hovered, { type: "pointer.leave" }).state
expect(left.highlight).toEqual({ mode: "mouse", activeKey: null })
expect(run(start, { type: "pointer.leave" }).state).toBe(start)
const typed = run(hovered, key("Escape", { claimed: true }))
expect(typed.handled).toBe(false)
expect(typed.state.highlight).toEqual({ mode: "keyboard", activeKey: "Beta" })
expect(listScrollTarget(typed.state)).toEqual({ type: "item", key: "Beta" })
})
test.each<{ name: string; events: ListKeyDown[]; active: string | null; handled: boolean }>([
{ name: "ArrowDown moves to the next row", events: [key("ArrowDown")], active: "Beta", handled: true },
{ name: "ArrowUp wraps to the last row", events: [key("ArrowUp")], active: "Gamma", handled: true },
{
name: "Ctrl+N and Ctrl+P move like arrows",
events: [key("n", { ctrl: true }), key("n", { ctrl: true }), key("p", { ctrl: true })],
active: "Beta",
handled: true,
},
{ name: "ArrowDown wraps to the first row", events: [key("End"), key("ArrowDown")], active: "Alpha", handled: true },
{
name: "Option+Arrow is left to text editing",
events: [key("ArrowDown", { alt: true })],
active: "Alpha",
handled: false,
},
{
name: "Cmd+Arrow is left to text editing",
events: [key("ArrowDown", { meta: true })],
active: "Alpha",
handled: false,
},
{ name: "End jumps to the last row", events: [key("End")], active: "Gamma", handled: true },
{ name: "a search input keeps End", events: [key("End", { search: true })], active: "Alpha", handled: false },
{ name: "Tab moves to the next row", events: [key("Tab")], active: "Beta", handled: true },
{
name: "Shift+Tab on the first row leaves focus to the browser",
events: [key("Tab", { shift: true })],
active: "Alpha",
handled: false,
},
{
name: "a claimed key does not move",
events: [key("ArrowDown", { claimed: true })],
active: "Alpha",
handled: false,
},
])("$name", (input) => {
const result = run(loaded(), ...input.events)
expect(result.state.highlight.activeKey).toBe(input.active)
expect(result.handled).toBe(input.handled)
})
test("Enter selects the highlighted row and is handled even with none", () => {
const start = run(loaded(), key("ArrowDown")).state
expect(listActive(start)).toEqual({ item: "Beta", index: 1 })
expect(run(start, key("Enter"))).toMatchObject({
handled: true,
effects: [{ type: "select", item: "Beta", index: 1 }],
})
expect(run(start, key("Enter", { composing: true })).handled).toBe(false)
const empty = run(start, { type: "active.set", key: "" })
expect(empty.state.highlight.activeKey).toBeNull()
expect(run(empty.state, key("Enter"))).toMatchObject({ handled: true, effects: [] })
})
+301
View File
@@ -0,0 +1,301 @@
import fuzzysort from "fuzzysort"
export type ListGroup<T> = { category: string; items: T[] }
export type ListConfig<T> = {
readonly key: (item: T) => string
readonly filterKeys?: string[]
readonly skipFilter?: (item: T) => boolean
readonly groupBy?: (item: T) => string
readonly sortBy?: (a: T, b: T) => number
readonly sortGroupsBy?: (a: ListGroup<T>, b: ListGroup<T>) => number
}
/** The one copy of the query. A `controlled` list shows the parent's `filter` prop and only reports edits. */
export type ListFilter = { readonly type: "uncontrolled" | "controlled"; readonly query: string }
/** `mouse` while the pointer drives the highlight, so the list does not scroll under it. */
export type ListHighlight = { readonly mode: "keyboard" | "mouse"; readonly activeKey: string | null }
type ListData<T> = {
readonly filter: ListFilter
readonly groups: ListGroup<T>[]
readonly rows: T[]
readonly keys: string[]
readonly highlight: ListHighlight
}
/** `loading` keeps the last rows on screen; `epoch` is the last attempt that settled. */
export type ListState<T> =
| (ListData<T> & { readonly status: "ready"; readonly epoch: number })
| (ListData<T> & { readonly status: "loading"; readonly attempt: number })
export type ListKeyDown = {
readonly type: "key.down"
readonly key: string
readonly ctrl: boolean
readonly alt: boolean
readonly meta: boolean
readonly shift: boolean
readonly composing: boolean
/** A search input keeps Home, End and Tab for the text field. */
readonly search: boolean
/** Escape, or a key the caller's `onKeyEvent` already handled. */
readonly claimed: boolean
}
export type ListEvent<T> =
| { readonly type: "query.change"; readonly value: string; readonly force?: boolean }
| { readonly type: "filter.controlled"; readonly value: string }
| { readonly type: "filter.uncontrolled" }
| { readonly type: "items.reload" }
| { readonly type: "load.resolved"; readonly attempt: number; readonly items: T[] }
| { readonly type: "load.failed"; readonly attempt: number }
| { readonly type: "pointer.move"; readonly key: string; readonly moved: boolean }
| { readonly type: "pointer.leave" }
| { readonly type: "active.set"; readonly key: string | null }
| { readonly type: "active.reset" }
| ListKeyDown
export type ListEffect<T> =
| { readonly type: "load"; readonly attempt: number; readonly query: string }
| { readonly type: "notify.filter"; readonly value: string }
| { readonly type: "select"; readonly item: T; readonly index: number }
export type ListTransition<T> = {
readonly state: ListState<T>
readonly effects: ListEffect<T>[]
readonly handled: boolean
}
export function createListState<T>(filter?: string): ListState<T> {
return {
status: "ready",
epoch: 0,
filter: filter === undefined ? { type: "uncontrolled", query: "" } : { type: "controlled", query: filter },
groups: [],
rows: [],
keys: [],
highlight: { mode: "keyboard", activeKey: null },
}
}
export function transitionList<T>(state: ListState<T>, event: ListEvent<T>, config: ListConfig<T>): ListTransition<T> {
if (event.type === "query.change") return queryChanged(state, event.value, event.force === true)
if (event.type === "filter.controlled") {
if (event.value !== state.filter.query) return load(state, { type: "controlled", query: event.value })
if (state.filter.type === "controlled") return unchanged(state)
return changed({ ...state, filter: { type: "controlled", query: event.value } })
}
if (event.type === "filter.uncontrolled") {
if (state.filter.type === "uncontrolled") return unchanged(state)
return changed({ ...state, filter: { type: "uncontrolled", query: state.filter.query } })
}
if (event.type === "items.reload") return load(state, state.filter)
if (event.type === "load.resolved" || event.type === "load.failed") {
if (state.status !== "loading" || event.attempt !== state.attempt) return unchanged(state)
const groups = event.type === "load.resolved" ? filterItems(event.items, state.filter.query, config) : []
const rows = groups.flatMap((group) => group.items)
const keys = rows.map(config.key)
return changed({
status: "ready",
epoch: state.attempt,
filter: state.filter,
groups,
rows,
keys,
// Each result set opens on its first row; `current` only marks the selected item.
highlight: { mode: state.highlight.mode, activeKey: keys[0] ?? null },
})
}
if (event.type === "pointer.move") {
if (!event.moved || (state.highlight.mode === "mouse" && state.highlight.activeKey === event.key))
return unchanged(state)
return changed({ ...state, highlight: { mode: "mouse", activeKey: event.key } })
}
if (event.type === "pointer.leave") {
if (state.highlight.mode === "keyboard" || state.highlight.activeKey === null) return unchanged(state)
return changed({ ...state, highlight: { mode: "mouse", activeKey: null } })
}
if (event.type === "active.set") return highlight(state, event.key || null)
if (event.type === "active.reset") return state.keys.length ? highlight(state, state.keys[0]) : unchanged(state)
return keyDown(state, event)
}
/** The highlighted row and its index among all rows. */
export function listActive<T>(state: Pick<ListState<T>, "rows" | "keys" | "highlight">) {
const index = state.highlight.activeKey === null ? -1 : state.keys.indexOf(state.highlight.activeKey)
return index < 0 ? undefined : { item: state.rows[index], index }
}
/** Where the list scrolls to keep the keyboard highlight in view; the pointer never scrolls it. */
export function listScrollTarget<T>(
state: Pick<ListState<T>, "keys" | "highlight">,
): { type: "none" } | { type: "top" } | { type: "item"; key: string } {
const key = state.highlight.activeKey
if (state.highlight.mode === "mouse" || key === null || state.keys.length === 0) return { type: "none" }
if (key === state.keys[0]) return { type: "top" }
return { type: "item", key }
}
export function groupItems<T>(items: T[], config: Pick<ListConfig<T>, "groupBy" | "sortBy" | "sortGroupsBy">) {
// A plain object keeps the group order of `Object.entries`, where numeric-looking categories sort first.
const byCategory: Record<string, T[]> = {}
for (const item of items) {
const category = config.groupBy ? config.groupBy(item) : ""
byCategory[category] ??= []
byCategory[category].push(item)
}
const groups = Object.entries(byCategory).map(([category, group]) => ({
category,
items: config.sortBy ? group.sort(config.sortBy) : group,
}))
return config.sortGroupsBy ? groups.sort(config.sortGroupsBy) : groups
}
function queryChanged<T>(state: ListState<T>, value: string, force: boolean): ListTransition<T> {
const same = value === state.filter.query
if (same && !force) return unchanged(state)
const notify: ListEffect<T> = { type: "notify.filter", value }
// A controlled list waits for the parent to pass the new `filter` back.
if (state.filter.type === "controlled" && !same) return unchanged(state, [notify])
const next = load(state, { type: state.filter.type, query: value })
return { ...next, effects: [notify, ...next.effects] }
}
function load<T>(state: ListState<T>, filter: ListFilter): ListTransition<T> {
const attempt = (state.status === "loading" ? state.attempt : state.epoch) + 1
return changed(
{
status: "loading",
attempt,
filter,
groups: state.groups,
rows: state.rows,
keys: state.keys,
highlight: state.highlight,
},
[{ type: "load", attempt, query: filter.query }],
)
}
function highlight<T>(state: ListState<T>, activeKey: string | null): ListTransition<T> {
if (activeKey === state.highlight.activeKey) return unchanged(state)
return changed({ ...state, highlight: { mode: state.highlight.mode, activeKey } })
}
function keyDown<T>(state: ListState<T>, event: ListKeyDown): ListTransition<T> {
const next: ListState<T> =
state.highlight.mode === "keyboard" ? state : { ...state, highlight: { ...state.highlight, mode: "keyboard" } }
if (event.claimed) return changed(next)
if (event.key === "Enter" && !event.composing) {
const active = listActive(next)
return changed(next, active ? [{ type: "select", item: active.item, index: active.index }] : [], true)
}
const move = navigate(event, next.keys, next.highlight.activeKey)
if (!move) return changed(next)
if (move.key === undefined) return changed(next, [], true)
return changed({ ...next, highlight: { mode: "keyboard", activeKey: move.key } }, [], true)
}
function navigate(event: ListKeyDown, keys: string[], active: string | null): { key?: string } | undefined {
const index = active === null ? -1 : keys.indexOf(active)
if (event.ctrl && !event.meta && !event.alt && !event.shift) {
if (event.key !== "n" && event.key !== "p") return
return { key: step(keys, index, event.key === "n" ? 1 : -1) }
}
// Option+Arrow and Cmd+Arrow edit text on macOS.
if (event.alt || event.meta || keys.length === 0) return
if (event.key === "ArrowDown") return { key: step(keys, index, 1) }
if (event.key === "ArrowUp") return { key: step(keys, index, -1) }
if (event.search) return
if (event.key === "Home") return { key: keys[0] }
if (event.key === "End") return { key: keys[keys.length - 1] }
if (event.key !== "Tab" || index < 0) return
const next = index + (event.shift ? -1 : 1)
if (next < 0 || next >= keys.length) return
return { key: keys[next] }
}
function step(keys: string[], index: number, direction: 1 | -1) {
if (keys.length === 0) return
if (index < 0) return direction === 1 ? keys[0] : keys[keys.length - 1]
return keys[(index + direction + keys.length) % keys.length]
}
function filterItems<T>(items: T[], query: string, config: ListConfig<T>) {
const needle = query.toLowerCase()
return groupItems(needle ? search(items, needle, config) : items, config)
}
function search<T>(all: T[], needle: string, config: ListConfig<T>) {
const skipFilter = config.skipFilter
const filterable = skipFilter ? all.filter((item) => !skipFilter(item)) : all
const skipped = skipFilter ? all.filter(skipFilter) : []
// oxlint-disable-next-line anti-slop/no-runtime-typeof -- plain string lists have no keys to search by
const strings = !config.filterKeys && filterable.every((e) => typeof e === "string")
// SAFETY: when `strings` holds, every element is a string, so the matched targets are the items.
const filtered = strings
? (fuzzysort.go(needle, filterable as string[]).map((x) => x.target) as T[])
: fuzzysort.go(needle, filterable, { keys: config.filterKeys! }).map((x) => x.obj)
return skipped.length ? [...filtered, ...skipped] : filtered
}
function changed<T>(state: ListState<T>, effects: ListEffect<T>[] = [], handled = false): ListTransition<T> {
return { state, effects, handled }
}
function unchanged<T>(state: ListState<T>, effects: ListEffect<T>[] = []): ListTransition<T> {
return { state, effects, handled: false }
}
+90 -114
View File
@@ -1,7 +1,7 @@
import fuzzysort from "fuzzysort"
import { createEffect, createMemo, createResource, on } from "solid-js"
import { createStore } from "solid-js/store"
import { createList } from "solid-list"
import { batch, createComputed, createMemo, createReaction, createSignal, on, onCleanup, untrack } from "solid-js"
import { createListState, transitionList, type ListEvent, type ListGroup } from "./list-machine"
export { groupItems } from "./list-machine"
export interface FilteredListProps<T> {
items: T[] | ((filter: string) => T[] | Promise<T[]>)
@@ -10,134 +10,110 @@ export interface FilteredListProps<T> {
current?: T
groupBy?: (x: T) => string
sortBy?: (a: T, b: T) => number
sortGroupsBy?: (a: { category: string; items: T[] }, b: { category: string; items: T[] }) => number
sortGroupsBy?: (a: ListGroup<T>, b: ListGroup<T>) => number
skipFilter?: (item: T) => boolean
onSelect?: (value: T | undefined, index: number) => void
}
export function groupItems<T>(
items: T[],
props: Pick<FilteredListProps<T>, "groupBy" | "sortBy" | "sortGroupsBy">,
) {
// A plain object keeps the group order of `Object.entries`, where numeric-looking categories sort first.
const byCategory: Record<string, T[]> = {}
for (const item of items) {
const category = props.groupBy ? props.groupBy(item) : ""
byCategory[category] ??= []
byCategory[category].push(item)
}
const groups = Object.entries(byCategory).map(([category, group]) => ({
category,
items: props.sortBy ? group.sort(props.sortBy) : group,
}))
return props.sortGroupsBy ? groups.sort(props.sortGroupsBy) : groups
/** Makes the query parent-owned: the list shows this value and reports edits through `onFilter`. */
filter?: string
onFilter?: (value: string) => void
}
export function useFilteredList<T>(props: FilteredListProps<T>) {
const [store, setStore] = createStore<{ filter: string }>({ filter: "" })
const [state, setState] = createSignal(createListState<T>(props.filter))
const lifetime = new AbortController()
onCleanup(() => lifetime.abort())
type Group = { category: string; items: [T, ...T[]] }
const dispatch = (event: ListEvent<T>, keyboard?: KeyboardEvent) => {
const result = transitionList(untrack(state), event, props)
const empty: Group[] = []
if (result.handled) keyboard?.preventDefault()
const search = (all: T[], needle: string) => {
const skipFilter = props.skipFilter
const filterable = skipFilter ? all.filter((item) => !skipFilter(item)) : all
const skipped = skipFilter ? all.filter(skipFilter) : []
// A synchronous load settles inside the batch, so readers never see its `loading` step.
batch(() => {
setState(() => result.state)
result.effects.forEach((effect) => {
if (effect.type === "load") load(effect.attempt, effect.query)
})
})
result.effects.forEach((effect) => {
if (effect.type === "notify.filter") props.onFilter?.(effect.value)
// oxlint-disable-next-line anti-slop/no-runtime-typeof -- plain string lists have no keys to search by
const strings = !props.filterKeys && filterable.every((e) => typeof e === "string")
// SAFETY: when `strings` holds, every element is a string, so the matched targets are the items.
const filtered = strings
? (fuzzysort.go(needle, filterable as string[]).map((x) => x.target) as T[])
: fuzzysort.go(needle, filterable, { keys: props.filterKeys! }).map((x) => x.obj)
return skipped.length ? [...filtered, ...skipped] : filtered
if (effect.type === "select") props.onSelect?.(effect.item, effect.index)
})
}
const [grouped, { refetch }] = createResource(
() => ({
filter: store.filter,
// Tracks what the last load read (`props.items`, or the signals `items(query)` reads) and reloads when it changes.
const track = createReaction(() => dispatch({ type: "items.reload" }))
const load = (attempt: number, query: string) =>
track(() => {
// oxlint-disable-next-line anti-slop/no-runtime-typeof -- `items` is either a list or a loader for one
items: typeof props.items === "function" ? props.items(store.filter) : props.items,
}),
async ({ filter, items }) => {
const query = filter ?? ""
const needle = query.toLowerCase()
const all = (await Promise.resolve(items)) || []
const items = typeof props.items === "function" ? props.items(query) : props.items
untrack(() => settle(attempt, items))
})
const matched = needle ? search(all, needle) : all
const settle = (attempt: number, items: T[] | Promise<T[]>) => {
if (Array.isArray(items)) return dispatch({ type: "load.resolved", attempt, items })
return groupItems(matched, props)
},
{ initialValue: empty },
void items.then(
(items) => {
if (!lifetime.signal.aborted) dispatch({ type: "load.resolved", attempt, items: items ?? [] })
},
() => {
if (!lifetime.signal.aborted) dispatch({ type: "load.failed", attempt })
},
)
}
createComputed(
on(
() => props.filter,
(value) => dispatch(value === undefined ? { type: "filter.uncontrolled" } : { type: "filter.controlled", value }),
{ defer: true },
),
)
const flat = createMemo(() => (grouped.latest || []).flatMap((x) => x.items))
dispatch({ type: "items.reload" })
// Lists open on their first row; `current` only marks the selected item.
const list = createList({
items: () => flat().map(props.key),
initialActive: flat()[0] ? props.key(flat()[0]) : "",
loop: true,
})
const reset = () => {
const all = flat()
if (all.length === 0) return
list.setActive(props.key(all[0]))
}
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === "Enter" && !event.isComposing) {
event.preventDefault()
const selectedIndex = flat().findIndex((x) => props.key(x) === list.active())
const selected = flat()[selectedIndex]
if (selected) props.onSelect?.(selected, selectedIndex)
} else if (event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
if (event.key === "n" || event.key === "p") {
event.preventDefault()
const navEvent = new KeyboardEvent("keydown", {
key: event.key === "n" ? "ArrowDown" : "ArrowUp",
bubbles: true,
})
list.onKeyDown(navEvent)
}
} else {
// Skip list navigation for text editing shortcuts (e.g., Option+Arrow, Option+Backspace on macOS)
if (event.altKey || event.metaKey) return
list.onKeyDown(event)
}
}
createEffect(
on(grouped, () => {
reset()
}),
)
const onInput = (value: string) => {
setStore("filter", value)
}
const groups = createMemo(() => state().groups)
const loading = createMemo(() => state().status === "loading")
return {
grouped,
filter: () => store.filter,
flat,
reset,
refetch,
clear: () => setStore("filter", ""),
onKeyDown,
onInput,
active: list.active,
setActive: list.setActive,
state,
dispatch,
grouped: {
get latest() {
return groups()
},
get loading() {
return loading()
},
get state(): "ready" | "refreshing" {
return loading() ? "refreshing" : "ready"
},
},
filter: createMemo(() => state().filter.query),
flat: createMemo(() => state().rows),
active: createMemo(() => state().highlight.activeKey),
reset: () => dispatch({ type: "active.reset" }),
refetch: () => dispatch({ type: "items.reload" }),
clear: () => dispatch({ type: "query.change", value: "" }),
onInput: (value: string) => dispatch({ type: "query.change", value }),
setActive: (key: string | null) => dispatch({ type: "active.set", key }),
onKeyDown: (event: KeyboardEvent, options?: { search?: boolean; claimed?: boolean }) =>
dispatch(
{
type: "key.down",
key: event.key,
ctrl: event.ctrlKey,
alt: event.altKey,
meta: event.metaKey,
shift: event.shiftKey,
composing: event.isComposing,
search: options?.search === true,
claimed: options?.claimed === true,
},
event,
),
}
}