diff --git a/packages/app/component-tests/composer.spec.ts b/packages/app/component-tests/composer.spec.ts index 267ebbde96b..c8f697d856f 100644 --- a/packages/app/component-tests/composer.spec.ts +++ b/packages/app/component-tests/composer.spec.ts @@ -611,7 +611,7 @@ story("renders a draft once and supports editing, caret restoration, and failure await component.locator('[data-action="composer-model"]').click() await page .getByRole("dialog", { name: "Select model", exact: true }) - .getByRole("searchbox", { name: "Search models", exact: true }) + .getByRole("combobox", { name: "Search models", exact: true }) .press("Escape") await expect(input).toBeFocused() await input.pressSequentially("!") diff --git a/packages/app/e2e/regression/command-palette.spec.ts b/packages/app/e2e/regression/command-palette.spec.ts index de7684b75f8..b7ccba66a37 100644 --- a/packages/app/e2e/regression/command-palette.spec.ts +++ b/packages/app/e2e/regression/command-palette.spec.ts @@ -60,7 +60,7 @@ test("finds a setting and opens Settings with its row in view and highlighted", await input.fill("model") await searched - const titles = dialog.locator(".command-palette-group-title") + const titles = dialog.locator('[data-slot="search-list-header"]') await expect(titles.first()).toHaveText("Commands") await expect(titles.last()).toHaveText("Settings") const options = dialog.getByRole("option") @@ -148,9 +148,13 @@ test("appends search results without resetting the selected command", async ({ p }) await page.route("**/api/session?*", async (route) => { await sessions.promise + // Like the server, only a matching title answers, so the session leaves the results for "copy session". + const search = new URL(route.request().url()).searchParams.get("search") ?? "" await route.fulfill({ json: { - data: [{ ...paletteSession, location: { directory: paletteSession.directory }, title: "Copy fixture" }], + data: "copy fixture".includes(search.toLowerCase()) + ? [{ ...paletteSession, location: { directory: paletteSession.directory }, title: "Copy fixture" }] + : [], }, }) }) @@ -175,6 +179,36 @@ test("appends search results without resetting the selected command", async ({ p await expect(dialog.getByRole("option", { name: "Copy Project ID", exact: true })).toHaveCount(0) }) +test("lists matching sessions above commands and jumps between sections with Alt and the arrows", async ({ page }) => { + const { dialog, input } = await openCommandPalette(page) + await page.route("**/api/session?*", (route) => + route.fulfill({ + json: { + data: [ + { + ...paletteSession, + id: "ses_palette_copy", + location: { directory: paletteSession.directory }, + title: "Copy fixture", + }, + ], + }, + }), + ) + await input.fill("copy") + const session = dialog.getByRole("option", { name: /Copy fixture/ }) + await expect(session).toHaveAttribute("aria-selected", "true") + await expect(dialog.locator('[data-slot="search-list-header"]').first()).toHaveText("Session") + const commands = dialog.getByRole("group", { name: "Commands", exact: true }).getByRole("option") + await input.press("Alt+ArrowDown") + await expect(commands.first()).toHaveAttribute("aria-selected", "true") + await input.press("ArrowDown") + await input.press("Alt+ArrowUp") + await expect(commands.first()).toHaveAttribute("aria-selected", "true") + await input.press("Alt+ArrowUp") + await expect(session).toHaveAttribute("aria-selected", "true") +}) + test("selects the first session when it arrives above automatically selected files", async ({ page }) => { const { dialog, input } = await openCommandPalette(page) const sessions = Promise.withResolvers() @@ -370,7 +404,7 @@ test("keeps matching session and file results steady across keystrokes while sea await expect(sessionOption).toBeVisible() const probe = await page.evaluateHandle(() => { - const results = document.querySelector(".command-palette-results")! + const results = document.querySelector('[role="dialog"] [data-slot="search-list-scroll"]')! const state = { emptyFrames: 0, @@ -384,7 +418,10 @@ test("keeps matching session and file results steady across keystrokes while sea } const observer = new MutationObserver(() => { - if (results.querySelectorAll('[role="option"]').length === 0 || results.querySelector(".command-palette-state")) { + if ( + results.querySelectorAll('[role="option"]').length === 0 || + results.querySelector('[data-slot="search-list-empty"]') + ) { state.emptyFrames++ } }) diff --git a/packages/app/e2e/regression/composer.spec.ts b/packages/app/e2e/regression/composer.spec.ts index 329118875fd..c536cb98798 100644 --- a/packages/app/e2e/regression/composer.spec.ts +++ b/packages/app/e2e/regression/composer.spec.ts @@ -333,7 +333,7 @@ test("a catalog refresh cannot replace an existing session's model", async ({ pa await control.click() await page .getByRole("dialog", { name: "Select model" }) - .getByRole("button", { name: "Beta Free", exact: true }) + .getByRole("option", { name: "Beta Free", exact: true }) .click() await expect(control).toHaveText("OpenCode / Beta") await view.editor.fill("Use the replacement I chose") @@ -767,7 +767,7 @@ test("keeps a narrow session composer contained when invoking a built-in", async await page.locator('[data-suggestion-id="model.choose"]').click() const dialog = page.getByRole("dialog", { name: "Select model", exact: true }) - const search = dialog.getByRole("searchbox", { name: "Search models", exact: true }) + const search = dialog.getByRole("combobox", { name: "Search models", exact: true }) await expect(search).toBeFocused() await expect(editor).toHaveText("keep me") await page.keyboard.press("Escape") @@ -797,7 +797,7 @@ test("keeps focus in a dialog that replaces the model dialog and returns it to t await page.locator('[data-component="composer"] [data-action="composer-model"]').click() const models = page.getByRole("dialog", { name: "Select model", exact: true }) - await expect(models.getByRole("searchbox", { name: "Search models", exact: true })).toBeFocused() + await expect(models.getByRole("combobox", { name: "Search models", exact: true })).toBeFocused() await models.getByRole("button", { name: "Manage models", exact: true }).click() await expect(models).toBeHidden() @@ -926,8 +926,8 @@ test("marks a Console provider with its workspace only when it is also connected await expect(details.getByText(/Anomaly \//)).toHaveCount(0) await trigger.click() const menu = page.getByRole("dialog", { name: "Select model", exact: true }) - await expect(menu.getByRole("button", { name: "Direct Gemini", exact: true })).toBeVisible() - const headings = menu.locator('[data-slot="model-dialog-group-title"]') + await expect(menu.getByRole("option", { name: "Direct Gemini", exact: true })).toBeVisible() + const headings = menu.locator('[data-slot="search-list-header"]') await expect(headings).toHaveCount(4) await expect(headings.filter({ hasText: /^GoogleAnomaly$/ })).toHaveCount(1) await expect(headings.filter({ hasText: /^Google$/ })).toHaveCount(1) diff --git a/packages/app/e2e/regression/mobile-model-pickers.spec.ts b/packages/app/e2e/regression/mobile-model-pickers.spec.ts index 3fd14cb4d6f..53df5e76587 100644 --- a/packages/app/e2e/regression/mobile-model-pickers.spec.ts +++ b/packages/app/e2e/regression/mobile-model-pickers.spec.ts @@ -129,7 +129,7 @@ for (const direction of ["ltr", "rtl"] as const) { await expect(variant).toHaveText("high") await expect(model).toHaveAttribute("data-control-type", "dialog") await model.click() - await expect(dialog.getByRole("searchbox", { name: "Search models", exact: true })).toBeFocused() + await expect(dialog.getByRole("combobox", { name: "Search models", exact: true })).toBeFocused() await expect(page.getByRole("menu")).toHaveCount(0) await dialog.locator('[data-option-key="opencode:mobile-b"]').click() await expect(dialog).toBeHidden() @@ -158,7 +158,7 @@ for (const direction of ["ltr", "rtl"] as const) { test(`model dialog arrow keys stage a variant in ${direction}`, async ({ page }) => { const { composer, model, variant, dialog } = await openDesktopPicker(page, direction) - const search = dialog.getByRole("searchbox", { name: "Search models", exact: true }) + const search = dialog.getByRole("combobox", { name: "Search models", exact: true }) const rowA = dialog.locator('[data-option-key="opencode:mobile-a"]') const next = direction === "rtl" ? "ArrowLeft" : "ArrowRight" await model.click() @@ -190,7 +190,7 @@ for (const direction of ["ltr", "rtl"] as const) { const prompt = composer.getByRole("textbox", { name: "Prompt", exact: true }) await prompt.fill("keep me") await prompt.press("ControlOrMeta+Quote") - const search = dialog.getByRole("searchbox", { name: "Search models", exact: true }) + const search = dialog.getByRole("combobox", { name: "Search models", exact: true }) await expect(search).toBeFocused() await search.press(direction === "rtl" ? "ArrowLeft" : "ArrowRight") await expect(dialog.locator('[data-option-key="opencode:mobile-a"]')).toContainText("high") @@ -226,8 +226,8 @@ test("model dialog toggles a favorite from the keyboard and leads with favorite page, }) => { const { model, dialog } = await openDesktopPicker(page, "ltr") - const sections = dialog.locator('[data-slot="model-dialog-group-title"]') - const search = dialog.getByRole("searchbox", { name: "Search models", exact: true }) + const sections = dialog.locator('[data-slot="search-list-header"]') + const search = dialog.getByRole("combobox", { name: "Search models", exact: true }) await model.click() await expect(sections).toHaveText(["OpenCode"]) await search.press("ArrowDown") @@ -240,7 +240,7 @@ test("model dialog toggles a favorite from the keyboard and leads with favorite await model.click() await expect(sections).toHaveText(["Favorites", "Recent", "OpenCode"]) - await expect(dialog.locator('[data-option-key="recent:opencode:mobile-b"]')).toHaveAttribute("aria-pressed", "true") + await expect(dialog.locator('[data-option-key="recent:opencode:mobile-b"]')).toHaveAttribute("aria-current", "true") await search.fill("Mobile") await expect(sections).toHaveText(["OpenCode"]) await search.press("Escape") @@ -258,7 +258,7 @@ test("model dialog toggles a favorite from the keyboard and leads with favorite test("model dialog opens Manage models from its search row with Enter", async ({ page }) => { const { model, dialog } = await openDesktopPicker(page, "ltr") await model.click() - await expect(dialog.getByRole("searchbox", { name: "Search models", exact: true })).toBeFocused() + await expect(dialog.getByRole("combobox", { name: "Search models", exact: true })).toBeFocused() const manage = dialog.getByRole("button", { name: "Manage models", exact: true }) await manage.focus() await manage.press("Enter") diff --git a/packages/app/src/composer/model.ts b/packages/app/src/composer/model.ts index 8571b449db2..004625b8d35 100644 --- a/packages/app/src/composer/model.ts +++ b/packages/app/src/composer/model.ts @@ -211,7 +211,7 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue? known: createKnownServerSessions(server.ctx), projects: server.ctx.projects.list, load: async (search, signal) => { - const page = await serverSDK.api.session.list({ parentID: null, search, limit: 50 }, { signal }) + const page = await serverSDK.api.session.list({ parentID: null, search, archived: false, limit: 50 }, { signal }) page.data.forEach(data.session.remember) return page diff --git a/packages/app/src/home/start/command-palette.tsx b/packages/app/src/home/start/command-palette.tsx index 853b2b03a56..0b81687e939 100644 --- a/packages/app/src/home/start/command-palette.tsx +++ b/packages/app/src/home/start/command-palette.tsx @@ -36,7 +36,8 @@ export function HomeCommandPalette(props: { server: ServerConnection.key(props.server), known: createKnownServerSessions(server), projects: server.projects.list, - load: (search, signal) => server.sdk.api.session.list({ parentID: null, search, limit: 50 }, { signal }), + load: (search, signal) => + server.sdk.api.session.list({ parentID: null, search, archived: false, limit: 50 }, { signal }), get: (sessionID, signal) => server.sdk.api.session.get({ sessionID }, { signal }), untitled: () => language.t("command.session.new"), category: () => language.t("command.category.session"), diff --git a/packages/app/src/providers/models/select-dialog.css b/packages/app/src/providers/models/select-dialog.css index 5bf9c6ee9dd..76ecc8d0aa4 100644 --- a/packages/app/src/providers/models/select-dialog.css +++ b/packages/app/src/providers/models/select-dialog.css @@ -43,82 +43,26 @@ } .model-dialog { - /* Arrow keys scroll the active row clear of the sticky group title. */ - .scroll-view__viewport { - scroll-padding-top: 28px; - } - - [data-slot="model-dialog-results"] { - display: flex; - flex-direction: column; - gap: 6px; + /* The model list is denser than the palette: tighter sections and quieter, heavier headers. */ + [data-component="search-list"] [data-slot="search-list-results"] { padding: 0 6px 6px; } - [data-slot="model-dialog-group"] { - display: flex; - flex-direction: column; - gap: 1px; + [data-component="search-list"] [data-slot="search-list-section"]:not(:last-child) { + padding-bottom: 6px; } - [data-slot="model-dialog-group-title"] { - position: sticky; - top: 0; - z-index: 1; - display: flex; - flex-shrink: 0; - align-items: center; - gap: 6px; - height: 28px; - margin-inline: -6px; - padding: 0 18px; - background: var(--v2-background-bg-base); - container-type: scroll-state; + [data-component="search-list"] [data-slot="search-list-header"] { color: var(--v2-text-text-faint); - font-size: 13px; font-weight: 530; - line-height: var(--line-height-compact); letter-spacing: -0.25px; - user-select: none; - - &::after { - position: absolute; - inset: auto 0 0; - border-bottom: 0.5px solid var(--v2-border-border-base); - content: ""; - opacity: 0; - } - - @container scroll-state(stuck: top) { - &::after { - opacity: 1; - } - } } - [data-slot="model-dialog-row"] { - display: flex; - width: 100%; - height: 28px; - flex-shrink: 0; - align-items: center; - gap: 8px; - padding: 0 12px; - border: 0; - border-radius: 6px; - background: transparent; - color: var(--v2-text-text-base); + [data-component="search-list"] [data-slot="search-list-row"] { font-size: 13px; font-weight: 440; line-height: var(--line-height-base); letter-spacing: -0.04px; - text-align: start; - cursor: default; - scroll-margin: 6px 0; - - &[data-active] { - background: var(--v2-overlay-simple-overlay-hover); - } } [data-slot="model-dialog-variant"] { @@ -147,7 +91,3 @@ } } } - -[data-color-scheme="dark"] .model-dialog [data-slot="model-dialog-row"][data-active] { - background: var(--v2-alpha-light-10); -} diff --git a/packages/app/src/providers/models/select-dialog.tsx b/packages/app/src/providers/models/select-dialog.tsx index dc4dd7dfdec..9f0ec152e2b 100644 --- a/packages/app/src/providers/models/select-dialog.tsx +++ b/packages/app/src/providers/models/select-dialog.tsx @@ -23,7 +23,7 @@ import { Dialog, DialogBody, DialogTitle } from "@opencode/ui/dialog" import { Icon } from "@opencode/ui/icon" import { IconButton } from "@opencode/ui/icon-button" import { Keybind } from "@opencode/ui/keybind" -import { ScrollView } from "@opencode/ui/scroll-view" +import { SearchHighlight, SearchList, type SearchListHandle, type SearchListRow } from "@opencode/ui/search-list" import { Tooltip } from "@opencode/ui/tooltip" import { TextInput } from "@opencode/ui/text-input" import { ModelTooltip } from "./tooltip" @@ -46,7 +46,6 @@ import { import { consoleProviderName } from "@/providers/catalog/console" import "@/settings/settings.css" import "@/shell/commands/dialog.css" -import "@/shell/palette-menu.css" import "./select-dialog.css" const MobilePanelDrawer = lazy(async () => { @@ -561,22 +560,7 @@ function withSections(input: { const rowKey = (group: ModelGroup, item: ModelItem) => group.title ? `${group.category}:${modelKey(item)}` : modelKey(item) -// Steps to the next row for a different model, so a section copy never hands the arrow keys to its twin. -function nextRow(rows: { id: string; item: ModelItem }[], active: string, delta: number) { - const start = Math.max( - rows.findIndex((row) => row.id === active), - 0, - ) - - const model = rows[start] ? modelKey(rows[start].item) : undefined - - return ( - Array.from( - { length: rows.length }, - (_, step) => rows[(start + (delta + rows.length) * (step + 1)) % rows.length], - ).find((row) => modelKey(row.item) !== model)?.id ?? active - ) -} +type ModelRow = { id: string; item: ModelItem; group: ModelGroup } function createChatgptPlan(current: () => string | undefined) { const data = useData() @@ -629,7 +613,6 @@ export function DialogSelectModel(props: { provider?: string; model?: ModelState const [store, setStore] = createStore({ search: "", - active: "", flyout: "", keyboard: true, navigated: false, @@ -639,7 +622,7 @@ export function DialogSelectModel(props: { provider?: string; model?: ModelState const [staged, setStaged] = createStore>({}) - let container: HTMLElement | undefined + let list: SearchListHandle | undefined let flyoutRef: HTMLDivElement | undefined let timer: ReturnType | undefined onCleanup(() => clearTimeout(timer)) @@ -660,16 +643,13 @@ export function DialogSelectModel(props: { provider?: string; model?: ModelState }) const rows = createMemo(() => - groups().flatMap((group) => group.items.map((item) => ({ id: rowKey(group, item), item }))), + groups().flatMap((group) => group.items.map((item): ModelRow => ({ id: rowKey(group, item), item, group }))), ) const rowItem = (id: string) => rows().find((row) => row.id === id)?.item - const activeItem = () => rowItem(store.active) const flyoutItem = () => (store.flyout ? rowItem(store.flyout) : undefined) const variantsOf = (item: ModelItem) => Object.keys(item.variants ?? {}) - setStore("active", rows()[0]?.id ?? "") - const variant = (item: ModelItem) => modelKey(item) in staged ? (staged[modelKey(item)] ?? undefined) : controller.variant(item) @@ -688,10 +668,7 @@ export function DialogSelectModel(props: { provider?: string; model?: ModelState void dialog.show(() => ) } - const setSearch = (value: string) => { - setStore({ search: value, flyout: "", keyboard: true, navigated: false }) - setStore("active", rows()[0]?.id ?? "") - } + const setSearch = (value: string) => setStore({ search: value, flyout: "", keyboard: true, navigated: false }) const triangle = createSafeTriangle({ flyout: () => (flyoutItem() && flyoutRef?.isConnected ? flyoutRef : undefined), @@ -720,8 +697,9 @@ export function DialogSelectModel(props: { provider?: string; model?: ModelState } const hover = (id: string, row: HTMLElement) => { - if (store.active === id && !store.keyboard) return - setStore({ active: id, keyboard: false }) + if (list?.active()?.id === id && !store.keyboard) return + list?.setActive(id) + setStore("keyboard", false) clearTimeout(timer) if (store.warm) { @@ -757,7 +735,7 @@ export function DialogSelectModel(props: { provider?: string; model?: ModelState createEventListener(document, "pointermove", (event: PointerEvent) => { const target = event.target - if (target instanceof Element && target.closest('[data-slot="model-dialog-row"]')) return + if (target instanceof Element && target.closest('[data-slot="search-list-row"]')) return if (target instanceof Node && flyoutRef?.contains(target)) return @@ -768,45 +746,29 @@ export function DialogSelectModel(props: { provider?: string; model?: ModelState // The flyout is placed once when it opens, so moving the rows under it closes it instead. createEventListener(window, "resize", close) - const onKeyDown = (event: KeyboardEvent) => { - if (event.isComposing) return - + const onKeyDown = (event: KeyboardEvent, active: ModelRow | undefined) => { if (matchKeybind(favoriteKeybind, event)) { - const item = activeItem() - - if (!item) return + if (!active) return event.preventDefault() - controller.toggleFavorite(item) + controller.toggleFavorite(active.item) // Unfavoriting removes the Favorites row that was highlighted, so keep the model highlighted in its group. - setStore({ flyout: "", keyboard: true, active: rowItem(store.active) ? store.active : modelKey(item) }) + list?.setActive(rowItem(active.id) ? active.id : modelKey(active.item)) + setStore({ flyout: "", keyboard: true }) + + return + } + + if (event.key === "ArrowDown" || event.key === "ArrowUp" || event.key === "Home" || event.key === "End") { + setStore({ keyboard: true, navigated: true, flyout: "" }) return } if (event.metaKey || event.altKey || event.ctrlKey) return - if (event.key === "ArrowDown" || event.key === "ArrowUp") { - event.preventDefault() - - if (rows().length === 0) return - setStore({ - active: nextRow(rows(), store.active, event.key === "ArrowDown" ? 1 : -1), - keyboard: true, - navigated: true, - flyout: "", - }) - queueMicrotask(() => - container - ?.querySelector(`[data-option-key="${CSS.escape(store.active)}"]`) - ?.scrollIntoView({ block: "nearest" }), - ) - - return - } - // While searching, left and right edit the query until the arrows have moved through the results. if ((event.key === "ArrowLeft" || event.key === "ArrowRight") && (!store.search || store.navigated)) { - const item = activeItem() + const item = active?.item if (!item || variantsOf(item).length === 0) return event.preventDefault() @@ -815,64 +777,57 @@ export function DialogSelectModel(props: { provider?: string; model?: ModelState const index = options.indexOf(variant(item)) setStaged(modelKey(item), options[(index + direction + options.length) % options.length] ?? null) setStore({ keyboard: true, flyout: "" }) - - return } - - if (event.key !== "Enter") return - const item = activeItem() - - if (!item) return - event.preventDefault() - choose(item) } - const Row = (row: { id: string; item: ModelItem; section: boolean }) => { - const selected = () => controller.current() === modelKey(row.item) - const active = () => store.active === row.id + const Row = (row: { model: ModelRow; attrs: SearchListRow }) => { + const item = () => row.model.item + const selected = () => controller.current() === modelKey(item()) + const active = () => row.attrs["data-active"] !== undefined return ( + )} + + + ) +} + +export default { + title: "UI/Search List", + id: "ui-search-list", + component: SearchListStory, + args: { sections: 4, rows: 6, sticky: true, query: "" }, + argTypes: { + sections: { control: { type: "range", min: 1, max: 8, step: 1 } }, + rows: { control: { type: "range", min: 1, max: 200, step: 1 } }, + }, +} + +export const Palette = {} + +export const LongLists = { args: { sections: 6, rows: 120 } } + +export const Searching = { args: { query: "desk" } } + +export const WithoutStickyHeaders = { args: { sticky: false } } diff --git a/packages/ui/src/forms/search-list/search-list.tsx b/packages/ui/src/forms/search-list/search-list.tsx new file mode 100644 index 00000000000..7fcd2b3fd0d --- /dev/null +++ b/packages/ui/src/forms/search-list/search-list.tsx @@ -0,0 +1,338 @@ +import { createContext, createEffect, createMemo, For, type JSX, on, onCleanup, Show, useContext } from "solid-js" +import { createResizeObserver } from "@solid-primitives/resize-observer" +import { Icon } from "@opencode/ui/icon" +import { ScrollView } from "../../components/scroll-view" +import { TextInput } from "../text-input/text-input" +import { createTypeahead } from "../typeahead/controller" +import { searchListMove, searchListTarget } from "./navigation" +import "./search-list.css" + +/** Attributes for a row's element: spread them, then override a handler to change what the pointer does. */ +export type SearchListRow = { + id: string + role: "option" + "aria-selected": boolean + "data-slot": "search-list-row" + "data-active": "" | undefined + onMouseMove: (event: MouseEvent) => void + onMouseDown: (event: MouseEvent) => void + onClick: () => void +} + +export type SearchListHandle = { + active: () => T | undefined + setActive: (key: string | undefined) => void +} + +const QueryContext = createContext<() => string>(() => "") + +/** + * A search field over sectioned results. Rows that share a `section` key list together under one header, which sticks + * while its rows scroll beneath it until the next header pushes it away. The first row is active until the user picks + * another: ↑/↓ wrap, ⌘ or ⌥ with ↑/↓ jump between sections, Home/End go to the ends, Enter selects and Escape closes. + */ +export function SearchList(props: { + query: string + onQuery: (query: string) => void + placeholder: string + /** Controls after the field, such as icon buttons. */ + trailing?: JSX.Element + items: T[] + key: (item: T) => string + section?: (item: T) => string + /** Rows that show the same thing in two sections. ↑/↓ step past a copy, so the highlight always lands somewhere new. */ + same?: (a: T, b: T) => boolean + /** A section's header, from its first row. */ + header?: (item: T) => JSX.Element + /** Shown in place of the rows when there are none. */ + empty: JSX.Element + onSelect: (item: T) => void + onActive?: (item: T | undefined) => void + /** Runs before the list's own keys; call `preventDefault` to claim one. */ + onKeyDown?: (event: KeyboardEvent, active: T | undefined) => void + onClose?: () => void + ref?: (handle: SearchListHandle) => void + class?: string + /** A row. `item` stays current while results with the same key replace it, so the row keeps its element. */ + children: (item: () => T, row: SearchListRow) => JSX.Element +}) { + let viewport: HTMLDivElement | undefined + let results: HTMLDivElement | undefined + + const sectionOf = (item: T) => props.section?.(item) ?? "" + + // Sections in the order their first row arrives; rows then list section by section, which is also the arrow order. + const groups = createMemo(() => { + const all = new Map() + + props.items.forEach((item) => { + const list = all.get(sectionOf(item)) + + if (list) list.push(item) + else all.set(sectionOf(item), [item]) + }) + + return all + }) + + const rows = createMemo(() => [...groups().values()].flat()) + const byKey = createMemo(() => new Map(rows().map((item) => [props.key(item), item] as const))) + const sectionKeys = createMemo((previous) => stable(previous, [...groups().keys()])) + + const typeahead = createTypeahead({ + items: rows, + key: (item) => props.key(item), + onSelect: (item) => props.onSelect(item), + onClose: props.onClose && (() => props.onClose?.()), + }) + + const activeKey = createMemo(() => { + const item = typeahead.activeItem() + + return item === undefined ? undefined : props.key(item) + }) + + // The first row shows from the top, so its header is never hidden; any other row scrolls in only as far as needed. + const reveal = () => { + const item = typeahead.activeItem() + + if (!viewport) return + + if (item === undefined || item === rows()[0]) return viewport.scrollTo({ top: 0 }) + document.getElementById(typeahead.optionID(item))?.scrollIntoView({ block: "nearest" }) + } + + // Rows fade out where they run under the top header or past the bottom edge. Each fade reaches full strength once + // 15 px is hidden, so it eases in with the scroll. The top fade follows the header over the topmost section and + // measures what that section has hidden, so a header that pushes the last one away starts clear again. Sections are + // measured when the list lays out, so scrolling only does arithmetic. + let sections: { top: number; bottom: number; header: number }[] = [] + + const edges = () => { + if (!viewport) return + const scroll = viewport.scrollTop + const strength = (hidden: number) => String(Math.min(1, Math.max(0, hidden / 15))) + const current = sections.findLast((section) => section.top - scroll < section.header) + + // A stuck header sits at the top until its section's end pushes it up. + const offset = current?.header + ? Math.min(Math.max(current.top - scroll, 0) + current.header, current.bottom - scroll) + : 0 + + viewport.style.setProperty("--search-list-fade-offset", `${Math.max(0, offset)}px`) + viewport.style.setProperty("--search-list-fade-top", strength(current ? scroll - current.top : 0)) + viewport.style.setProperty( + "--search-list-fade-bottom", + strength(viewport.scrollHeight - viewport.clientHeight - scroll), + ) + } + + const measure = () => { + if (!viewport) return + const origin = viewport.getBoundingClientRect().top - viewport.scrollTop + + sections = [...viewport.querySelectorAll('[data-slot="search-list-section"]')].map((section) => { + const rect = section.getBoundingClientRect() + + // A sticky header stays inside its section's content box, so the section's bottom padding is out of its reach. + return { + top: rect.top - origin, + bottom: rect.bottom - origin - parseFloat(getComputedStyle(section).paddingBottom), + header: section.querySelector('[data-slot="search-list-header"]')?.offsetHeight ?? 0, + } + }) + edges() + } + + createResizeObserver(() => [viewport, results], measure) + createEffect(on(rows, measure, { defer: true })) + + createEffect(() => props.onActive?.(typeahead.activeItem())) + + // A new query starts from the top. Results that arrive later for the same query bring a chosen row back into view, + // but leave the list where the wheel put it while the first row is still the default. + let revealed = props.query + + createEffect( + on( + rows, + (all) => { + const fresh = props.query !== revealed + revealed = props.query + + if (!fresh && typeahead.activeItem() === all[0]) return + const frame = requestAnimationFrame(reveal) + onCleanup(() => cancelAnimationFrame(frame)) + }, + { defer: true }, + ), + ) + + props.ref?.({ active: typeahead.activeItem, setActive: typeahead.setActive }) + + const onKeyDown = (event: KeyboardEvent) => { + if (event.isComposing) return + props.onKeyDown?.(event, typeahead.activeItem()) + + if (event.defaultPrevented) return + const move = searchListMove(event) + + if (!move) return typeahead.onKeyDown(event) + event.preventDefault() + event.stopPropagation() + const all = rows() + const sections = all.map(sectionOf) + const active = typeahead.activeItem() + const from = active === undefined ? -1 : all.indexOf(active) + + const step = (index: number): number => { + const next = searchListTarget(sections, index, move) + const copy = (move === "next" || move === "previous") && active !== undefined && next !== from + + return copy && props.same?.(all[next]!, active) ? step(next) : next + } + + const target = all[step(from)] + + if (target === undefined) return + typeahead.setActive(props.key(target)) + reveal() + } + + const row = (key: string, item: () => T): SearchListRow => ({ + get id() { + return typeahead.optionID(item()) + }, + role: "option", + get "aria-selected"() { + return activeKey() === key + }, + "data-slot": "search-list-row", + get "data-active"() { + return activeKey() === key ? ("" as const) : undefined + }, + onMouseMove: (event) => { + // A static cursor must not take the active row while the keyboard scrolls rows beneath it. + if (event.movementX !== 0 || event.movementY !== 0) typeahead.setActive(key) + }, + // Focus stays in the field. + onMouseDown: (event) => event.preventDefault(), + onClick: () => props.onSelect(item()), + }) + + return ( + props.query}> +
+
+ } + trailing={props.trailing} + role="combobox" + aria-expanded="true" + aria-autocomplete="list" + aria-controls={typeahead.listID} + aria-activedescendant={typeahead.activeID()} + onInput={(event) => { + // A new query starts again from its first row. + typeahead.setActive(undefined) + props.onQuery(event.currentTarget.value) + }} + onKeyDown={onKeyDown} + /> +
+ (viewport = element)} onScroll={edges}> + + + ) +} + +/** Text with its first match for the list's query marked. One mark per row keeps short queries from speckling the list. */ +export function SearchHighlight(props: { text: string }) { + const query = useContext(QueryContext) + + const match = createMemo(() => { + const needle = query().trim().toLowerCase() + const haystack = props.text.toLowerCase() + const at = needle ? haystack.indexOf(needle) : -1 + + // Lower-casing a few scripts changes the length, and then offsets no longer line up with the text. + if (at === -1 || haystack.length !== props.text.length) return + + return { at, end: at + needle.length } + }) + + return ( + + {(range) => ( + <> + {props.text.slice(0, range().at)} + {props.text.slice(range().at, range().end)} + {props.text.slice(range().end)} + + )} + + ) +} + +function stable(previous: string[] | undefined, next: string[]) { + return previous && previous.length === next.length && previous.every((value, index) => value === next[index]) + ? previous + : next +}