fix(app): build settings search on the shared typeahead (#59412)

This commit is contained in:
Kit Langton
2026-10-26 16:20:12 -07:00
committed by GitHub
Unverified
parent 59542dae3c
commit 48432428d9
7 changed files with 422 additions and 468 deletions
@@ -37,7 +37,7 @@ async function open(page: Page, input: { count?: number; seed?: SeedInput } = {}
settings,
search: settings.getByRole("combobox", { name: "Search", exact: true }),
results: settings.getByRole("listbox", { name: "Settings results", exact: true }),
viewport: settings.locator(".settings-search-scroll"),
viewport: settings.locator('.settings-search [data-slot="search-list-scroll"]'),
}
// Readiness includes the server-backed project inventory, not just the settings shell.
@@ -67,20 +67,25 @@ test("pointer selection, keyboard navigation, the empty state, and the local fin
"Terminal FontAppearance",
"UI FontAppearance",
])
// Keys stay with the field, as in every shared search list.
await code.click()
await expect(code).toBeFocused()
await expect(view.search).toBeFocused()
await expect(code).toHaveAttribute("aria-selected", "true")
await expect(view.settings.getByRole("textbox", { name: "Code Font", exact: true })).toBeInViewport()
await code.press("ArrowDown")
await expect(terminal).toBeFocused()
await view.search.press("ArrowDown")
await expect(terminal).toHaveAttribute("aria-selected", "true")
await terminal.press("Enter")
await expect(terminal).toBeFocused()
// Shift+arrows select text in the field instead of moving through the results.
await view.search.press("Shift+ArrowUp")
await expect(view.search).toHaveJSProperty("selectionStart", 0)
await expect(terminal).toHaveAttribute("aria-selected", "true")
await view.search.press("Enter")
await expect(view.search).toBeFocused()
await expect(view.settings.getByRole("textbox", { name: "Terminal Font", exact: true })).toBeInViewport()
await expect(view.settings.locator('[data-search-target="row"]')).toContainText("Terminal Font")
await terminal.press("End")
await expect(font).toBeFocused()
await font.press("Home")
await expect(code).toBeFocused()
await view.search.press("End")
await expect(font).toHaveAttribute("aria-selected", "true")
await view.search.press("Home")
await expect(code).toHaveAttribute("aria-selected", "true")
await findShortcut(page)
await expect(view.search).toBeFocused()
expect(await view.search.evaluate((input: HTMLInputElement) => [input.selectionStart, input.selectionEnd])).toEqual([
@@ -112,6 +117,63 @@ test("pointer selection, keyboard navigation, the empty state, and the local fin
await expect(page.getByRole("textbox", { name: /Search sessions/ })).toBeFocused()
})
test("the narrow layout floats the results in the shared search list popover", async ({ page }) => {
const view = await open(page, { count: 30 })
await page.setViewportSize({ width: 390, height: 844 })
await view.search.fill("e")
const popover = view.settings.locator('.settings-search [data-component="search-list"][data-popover]')
const body = popover.locator('[data-slot="search-list-body"]')
await expect(body).toBeVisible()
await expect(body).toHaveCSS("position", "absolute")
await expect(body.locator('[data-slot="search-list-header"]').first()).toHaveText("Pages")
await expect(view.results.getByRole("option").first()).toHaveAttribute("data-slot", "search-list-row")
await expect(body.locator('[data-slot="search-list-footer"]')).toHaveText(en["settings.search.refine"])
await view.search.fill("zzzzzzzzzz")
await expect(body.locator('[data-slot="search-list-empty"]').getByRole("status")).toHaveText(
'No results for "zzzzzzzzzz"',
)
// The message's text, not just its box, sits in the middle of the popover.
const offset = await body.evaluate((element) => {
const range = document.createRange()
range.selectNodeContents(element.querySelector('[role="status"]')!)
const text = range.getBoundingClientRect()
const box = element.getBoundingClientRect()
return {
x: text.left + text.width / 2 - (box.left + box.width / 2),
y: text.top + text.height / 2 - (box.top + box.height / 2),
}
})
expect(Math.abs(offset.x)).toBeLessThan(1)
expect(Math.abs(offset.y)).toBeLessThan(1)
})
test("a category's results stay under one run of headers when its groups interleave by rank", async ({ page }) => {
await mockOpenCodeServer(page, {
server: REMOTE_SERVER,
directory: "/remote/opencode",
project: project({ id: "proj_search_remote", directory: "/remote/opencode", name: "Remote app" }),
provider: NO_PROVIDER,
sessions: [],
pageMessages: () => ({ items: [] }),
})
const view = await open(page, { seed: { servers: [{ url: REMOTE_SERVER, name: "Build server" }] } })
// With two servers, "e" ranks a This computer setting between unscoped settings and the project results.
await view.search.fill("e")
const headers = view.results.locator('[data-slot="search-list-header"]')
await expect(headers.filter({ hasText: "This computer" })).not.toHaveCount(0)
const categories = await headers.evaluateAll((elements) =>
elements.map((element) => element.firstElementChild?.textContent ?? ""),
)
const runs = categories.filter((category, index) => category !== categories[index - 1])
expect(categories.filter((category) => category === "Settings")).toHaveLength(2)
expect(runs).toEqual([...new Set(runs)])
})
test("a long empty-state query keeps its closing quote beside the ellipsis while typing and resizing", async ({
page,
}) => {
@@ -121,8 +183,11 @@ test("a long empty-state query keeps its closing quote beside the ellipsis while
const status = view.settings.getByRole("status")
const quoted = status.locator("bdi")
// Rects, not clientWidth: the centred quote is exactly as wide as its text, and clientWidth rounds.
const fits = () =>
quoted.evaluate((element) => element.getBoundingClientRect().width <= element.parentElement!.clientWidth)
quoted.evaluate(
(element) => element.getBoundingClientRect().width <= element.parentElement!.getBoundingClientRect().width + 0.5,
)
await expect(status).toHaveAccessibleName(`No results for "${query}"`)
await expect(quoted).toHaveText(/^".+…"$/)
@@ -145,10 +210,11 @@ test("the search input tracks overflow through typing, caret moves, resizing, an
await expect(view.search).toHaveAttribute("data-overflow-end", end)
}
// Bare Home and End move through the results, so the caret moves with Shift.
await view.search.fill("zzzz ".repeat(30))
await view.search.press("End")
await view.search.press("Shift+End")
await overflow("true", "false")
await view.search.press("Home")
await view.search.press("Shift+Home")
await overflow("false", "true")
await view.search.evaluate((input: HTMLInputElement) => {
input.scrollLeft = (input.scrollWidth - input.clientWidth) / 2
@@ -287,6 +353,7 @@ test("all indexed client controls resolve to visible production controls", async
const view = await open(page)
for (const entry of clientSettings.filter((entry) => entry.target && !entry.available)) {
// SAFETY: catalog labels are typed as i18n keys, and English holds every key.
await view.search.fill(en[entry.label as keyof typeof en])
const result = view.results.locator(`[data-setting-target="${entry.target}"]`)
await expect(result).toHaveCount(1)
+18 -162
View File
@@ -1,16 +1,9 @@
.settings-search,
.settings-search-matches {
.settings-search {
display: flex;
flex-direction: column;
gap: 8px;
min-height: 0;
}
.settings-search {
position: relative;
gap: 0;
}
.settings-search[data-empty="true"] [data-slot="text-input-v2-icon-button"] {
visibility: hidden;
}
@@ -26,15 +19,15 @@
color: var(--v2-icon-icon-base);
}
.settings-search > [data-component="text-input-v2"] {
.settings-search [data-component="text-input-v2"] {
width: 100%;
flex-shrink: 0;
background: transparent;
box-shadow: none;
}
.settings-search > [data-component="text-input-v2"]:is(:hover, :focus-within):not([data-disabled]),
.settings-search > [data-component="text-input-v2"]:has(input:not(:placeholder-shown)):not([data-disabled]) {
.settings-search [data-component="text-input-v2"]:is(:hover, :focus-within):not([data-disabled]),
.settings-search [data-component="text-input-v2"]:has(input:not(:placeholder-shown)):not([data-disabled]) {
background: var(--v2-overlay-simple-overlay-hover);
}
@@ -68,12 +61,23 @@
white-space: pre;
}
/* Centred like every search list's empty state, with even insets on the rows' text spine. */
.settings-search [data-slot="search-list-empty"] .settings-search-empty {
justify-content: center;
margin-block-start: 0;
padding-inline: 18px;
}
.settings-search-empty-quoted {
flex: 1;
min-width: 0;
color: var(--v2-text-text-base);
}
.settings-search [data-slot="search-list-empty"] .settings-search-empty-quoted {
flex: 0 1 auto;
}
.settings-search-empty-measure {
position: absolute;
visibility: hidden;
@@ -89,68 +93,14 @@
width: max-content;
}
.settings-search-category,
.settings-search-group,
.settings-search-detail,
.settings-search-note {
color: var(--v2-text-text-muted);
.settings-search-empty,
.settings-search-empty-measure {
font-size: 13px;
font-weight: 440;
line-height: var(--line-height-compact);
letter-spacing: -0.04px;
}
.settings-search-results {
display: flex;
flex-direction: column;
gap: 4px;
min-height: 0;
padding: 0;
/* Keep the first and last results clear of the fades when scrolling to either end. */
padding-block: 16px 32px;
}
.settings-search-scroll {
min-height: 0;
overflow-y: auto;
/* The reserved scrollbar and this padding keep 16px between the edge and the rows, scrolling or not. */
padding-inline-end: calc(16px - var(--scrollbar-size, 0px));
scrollbar-gutter: stable;
overscroll-behavior: contain;
scroll-padding-block: 16px 32px;
-webkit-mask-image: linear-gradient(to bottom, transparent, black 16px, black calc(100% - 32px), transparent);
mask-image: linear-gradient(to bottom, transparent, black 16px, black calc(100% - 32px), transparent);
}
@container settings-screen (min-width: 800px) {
.settings-search-scroll {
width: calc(100% + 16px);
margin-inline-end: -16px;
}
}
.settings-search-scroll[data-empty="true"] {
display: none;
}
.settings-search-category {
padding: 16px 6px 4px;
padding-inline-start: 8px;
overflow-wrap: anywhere;
font-weight: 530;
}
.settings-search-category:first-child {
padding-block: 6px;
}
.settings-search-group {
padding: 8px 6px 4px;
padding-inline-start: 8px;
overflow-wrap: anywhere;
font-weight: 440;
}
.settings-search-result,
.settings-search-empty {
display: flex;
align-items: center;
@@ -162,100 +112,6 @@
color: var(--v2-text-text-muted);
}
.settings-search-result {
gap: 8px;
border: 0;
border-radius: 4px;
background: transparent;
text-align: start;
cursor: default;
}
.settings-search-result:has(.settings-search-detail) {
flex-direction: column;
align-items: stretch;
justify-content: center;
gap: 3px;
height: auto;
min-height: 48px;
padding-block: 6px;
}
.settings-search-title,
.settings-search-empty,
.settings-search-empty-measure {
font-size: 13px;
font-weight: 440;
line-height: var(--line-height-compact);
letter-spacing: -0.04px;
}
.settings-search-title {
color: var(--v2-text-text-base);
grid-column: 2;
justify-self: start;
max-width: 100%;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.settings-search-detail {
min-width: 0;
padding-inline-start: 24px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.settings-search-label {
display: grid;
grid-template-columns: 16px minmax(0, 1fr);
width: 100%;
min-width: 0;
align-items: center;
gap: 8px;
}
.settings-search-result[data-icons="false"] .settings-search-label {
grid-template-columns: 0 minmax(0, 1fr);
gap: 0;
}
.settings-search-result[data-icons="false"] .settings-search-detail {
padding-inline-start: 0;
}
.settings-search-project-icon[data-component="project-avatar-v2"] {
width: 16px;
height: 16px;
flex-shrink: 0;
}
.settings-search-result[data-highlighted="true"],
.settings-search-result[aria-current="location"],
.settings-search-result:active {
background: var(--v2-background-bg-layer-03);
color: var(--v2-text-text-base);
}
.settings-search-result:focus-visible {
outline: none;
background: var(--v2-background-bg-layer-03);
color: var(--v2-text-text-base);
}
@media (hover: hover) {
.settings-search-result:hover:not([data-highlighted="true"]):not([aria-current="location"]):not(:active) {
background: var(--v2-background-bg-layer-03);
}
}
.settings-search-note {
padding: 12px 6px 0;
}
[data-component="settings-list"] {
--settings-search-inset: 20px;
}
+126 -206
View File
@@ -1,8 +1,10 @@
import { createEffect, createMemo, createUniqueId, For, on, onMount, Show } from "solid-js"
import { createEffect, createMemo, on, onMount, Show } from "solid-js"
import { createStore } from "solid-js/store"
import { createMediaQuery } from "@solid-primitives/media"
import { createResizeObserver } from "@solid-primitives/resize-observer"
import { Icon } from "@opencode/ui/icon"
import { SearchHighlight, SearchList, type SearchListHandle } from "@opencode/ui/search-list"
import { Slash } from "@opencode/ui/slash"
import { TextInput } from "@opencode/ui/text-input"
import { useLanguage } from "@/runtime/i18n/language"
import { usePlatform } from "@/runtime/platform/platform"
@@ -22,10 +24,9 @@ export function SettingsSearch() {
const surface = useSettingsSurface()
const search = surface.search
const [state, setState] = createStore({ narrow: false, overflow: { start: false, end: false } })
const listID = `settings-results-${createUniqueId()}`
let root: HTMLDivElement | undefined
let input: HTMLInputElement | undefined
let results: HTMLDivElement | undefined
let list: SearchListHandle<SettingsSearchResult> | undefined
const updateOverflow = () => {
if (!input) return
@@ -52,6 +53,8 @@ export function SettingsSearch() {
keybind: "mod+f",
hidden: true,
onSelect: () => {
// A root pick in a wide window closes the results but keeps focus, so focusing again would not reopen them.
search.expand()
input?.focus({ preventScroll: true })
input?.select()
},
@@ -71,19 +74,12 @@ export function SettingsSearch() {
? "settings.search.group.projects"
: "settings.search.group.servers"
// A category's rows stay together, whichever of its groups ranks first, so its header shows once.
const shown = createMemo(() => {
const groups = new Map<ReturnType<typeof category>, SettingsSearchResult[]>()
matches()
.slice(0, 60)
.forEach((item) => {
const key = category(item)
const items = groups.get(key)
const top = matches().slice(0, 60)
const order = [...new Set(top.map(category))]
if (items) return items.push(item)
groups.set(key, [item])
})
return Array.from(groups.values()).flat()
return order.flatMap((key) => top.filter((item) => category(item) === key))
})
const iconGroups = createMemo(
@@ -95,19 +91,6 @@ export function SettingsSearch() {
),
)
const expanded = () => !!search.state.query.trim() && (!state.narrow || search.state.expanded)
const highlighted = () => shown().find((item) => item.id === search.state.highlighted) ?? shown()[0]
const optionID = (id: string) => `${listID}-${encodeURIComponent(id)}`
createEffect(
on(
() => search.state.query,
() => {
if (results) results.scrollTop = 0
},
{ defer: true },
),
)
const group = (item: SettingsSearchResult) => {
if (item.entity && !item.project) return ""
@@ -116,7 +99,13 @@ export function SettingsSearch() {
return item.projectName ?? ""
}
const expanded = () => !!search.state.query.trim() && (!state.narrow || search.state.expanded)
const select = (item: SettingsSearchResult) => {
list?.setActive(item.id)
// A wide layout keeps the results beside the page, so the keys stay with them.
if (item.view.type === "root" && !state.narrow) input?.focus({ preventScroll: true })
surface.search.open(item.view, item.id)
if (state.narrow && item.view.type === "root") {
@@ -131,31 +120,43 @@ export function SettingsSearch() {
}
return (
<div
ref={root}
class="settings-search"
data-expanded={search.state.expanded}
data-empty={!search.state.query.trim()}
on:keydown={{
// Handle result navigation instead of the results list's native key scrolling.
capture: true,
handleEvent: (event) => {
if (
event.defaultPrevented ||
event.isComposing ||
event.altKey ||
event.ctrlKey ||
event.metaKey ||
event.shiftKey
)
return
if (
event.target !== input &&
!(event.target instanceof Element && event.target.closest(".settings-search-result"))
)
return
<div ref={root} class="settings-search" data-empty={!search.state.query.trim()}>
<SearchList
query={search.state.query}
onQuery={(query) => search.input(query)}
placeholder={language.t("settings.search.placeholder")}
label={language.t("settings.search.results")}
open={expanded()}
popover={state.narrow}
items={shown()}
key={(item) => item.id}
section={(item) => `${category(item)}\u0000${group(item)}`}
header={(item) => (
<>
<span class="shrink-0">{language.t(category(item))}</span>
<Show when={group(item)}>
{(name) => (
<>
<Slash gap={0} />
<bdi dir="auto" class="min-w-0 truncate">
{name()}
</bdi>
</>
)}
</Show>
</>
)}
empty={<SettingsSearchEmpty query={search.state.query} />}
footer={matches().length > shown().length ? language.t("settings.search.refine") : undefined}
scrollTop={search.state.scrollTop}
onScroll={(top) => search.scroll(top)}
ref={(handle) => {
list = handle
handle.setActive(search.state.highlighted || undefined)
}}
onActive={(item) => item && search.highlight(item.id)}
onSelect={select}
onKeyDown={(event) => {
if (event.key === "Escape" && search.state.query) {
event.preventDefault()
event.stopPropagation()
@@ -164,164 +165,83 @@ export function SettingsSearch() {
return
}
if (event.key === "Enter" && expanded() && highlighted()) {
if (
!expanded() &&
search.state.query.trim() &&
(event.key === "ArrowDown" || event.key === "ArrowUp") &&
!event.shiftKey &&
!event.ctrlKey &&
!event.altKey &&
!event.metaKey
) {
event.preventDefault()
event.stopPropagation()
select(highlighted()!)
return
search.expand()
}
if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return
if ((event.key === "Home" || event.key === "End") && event.target === input) return
event.preventDefault()
event.stopPropagation()
search.expand()
const index = shown().findIndex((item) => item.id === highlighted()?.id)
const last = shown().length - 1
const moves = { Home: 0, End: last, ArrowDown: Math.min(last, index + 1), ArrowUp: Math.max(0, index - 1) }
const move = Object.entries(moves).find(([key]) => key === event.key)
const next = move && shown()[move[1]]
if (!next) return
search.highlight(next.id)
const row = results?.querySelector<HTMLElement>(`#${CSS.escape(optionID(next.id))}`)
if (event.target !== input) row?.focus({ preventScroll: true })
row?.scrollIntoView({ block: "nearest", inline: "nearest" })
},
}}
>
<TextInput
ref={input}
type="search"
role="combobox"
aria-autocomplete="list"
aria-expanded={expanded()}
aria-activedescendant={expanded() && highlighted() ? optionID(highlighted()!.id) : undefined}
value={search.state.query}
leadingIcon={<Icon name="magnifying-glass" size="small" />}
placeholder={language.t("settings.search.placeholder")}
aria-label={language.t("settings.search.placeholder")}
aria-controls={search.state.query.trim() ? listID : undefined}
data-overflow-start={state.overflow.start}
data-overflow-end={state.overflow.end}
showClearButton
clearIcon="circle-xmark"
onClearClick={clear}
onFocus={() => search.expand()}
onScroll={updateOverflow}
onInput={(event) => {
search.input(event.currentTarget.value)
}}
spellcheck={false}
autocomplete="off"
/>
<Show when={search.state.query.trim()}>
<div class="settings-search-matches">
<div
class="settings-search-scroll"
data-scrollable
data-empty={!shown().length}
ref={(element) => {
results = element
queueMicrotask(() => {
if (element.isConnected) element.scrollTop = search.state.scrollTop
})
}}
onScroll={(event) => search.scroll(event.currentTarget.scrollTop)}
field={(field) => (
<TextInput
{...field}
ref={input}
type="search"
value={search.state.query}
leadingIcon={<Icon name="magnifying-glass" size="small" />}
placeholder={language.t("settings.search.placeholder")}
aria-label={language.t("settings.search.placeholder")}
data-overflow-start={state.overflow.start}
data-overflow-end={state.overflow.end}
showClearButton
clearIcon="circle-xmark"
onClearClick={clear}
onFocus={() => search.expand()}
onScroll={updateOverflow}
spellcheck={false}
autocomplete="off"
/>
)}
>
{(item, row) => (
<button
type="button"
{...row}
tabIndex={-1}
aria-label={
item().page === item().title && !item().owner
? item().title
: language.t(
item().page === item().title
? "settings.search.page"
: item().owner
? "settings.search.result"
: "settings.search.result.unscoped",
{ title: item().title, scope: item().owner, page: item().page },
)
}
aria-current={search.state.selected === item().id ? "location" : undefined}
data-setting-target={item().view.target}
data-result-id={item().id}
title={[item().owner, item().page].filter(Boolean).join(" › ")}
>
<div
id={listID}
class="settings-search-results"
role="listbox"
aria-label={language.t("settings.search.results")}
>
<For each={shown()}>
{(item, index) => (
<>
<Show when={index() === 0 || category(shown()[index() - 1]) !== category(item)}>
<div class="settings-search-category" role="presentation">
{language.t(category(item))}
</div>
</Show>
<Show
when={
group(item) &&
(index() === 0 ||
category(shown()[index() - 1]) !== category(item) ||
group(shown()[index() - 1]) !== group(item))
}
>
<div class="settings-search-group" role="presentation">
<bdi dir="auto">{group(item)}</bdi>
</div>
</Show>
<button
id={optionID(item.id)}
role="option"
aria-selected={highlighted()?.id === item.id}
aria-label={
item.page === item.title && !item.owner
? item.title
: language.t(
item.page === item.title
? "settings.search.page"
: item.owner
? "settings.search.result"
: "settings.search.result.unscoped",
{ title: item.title, scope: item.owner, page: item.page },
)
}
type="button"
class="settings-search-result"
data-icons={iconGroups().has(category(item))}
data-setting-target={item.view.target}
data-result-id={item.id}
data-highlighted={highlighted()?.id === item.id}
aria-current={search.state.selected === item.id ? "location" : undefined}
title={[item.owner, item.page].filter(Boolean).join(" › ")}
tabIndex={highlighted()?.id === item.id ? 0 : -1}
onFocus={() => search.highlight(item.id)}
onClick={(event) => {
if (item.view.type === "root" && !state.narrow)
event.currentTarget.focus({ preventScroll: true })
select(item)
}}
>
<span class="settings-search-label">
<Show
when={item.projectInfo}
fallback={<Show when={item.topLevel && item.icon}>{(icon) => <Icon name={icon()} />}</Show>}
>
{(project) => (
<ProjectIcon project={project()} class="settings-search-project-icon" aria-hidden="true" />
)}
</Show>
<bdi dir="auto" class="settings-search-title">
{item.title}
</bdi>
</span>
<Show when={item.page !== item.title && !(item.entity && item.project)}>
<span class="settings-search-detail">{item.page}</span>
</Show>
</button>
</>
)}
</For>
</div>
</div>
<Show when={!matches().length}>
<SettingsSearchEmpty query={search.state.query} />
</Show>
<Show when={matches().length > shown().length}>
<p class="settings-search-note">{language.t("settings.search.refine")}</p>
</Show>
</div>
</Show>
<span class="flex min-w-0 items-center gap-2 text-[13px] font-[440] leading-text-compact tracking-[-0.04px]">
<Show when={iconGroups().has(category(item()))}>
<span class="flex size-4 shrink-0 items-center justify-center text-v2-icon-icon-muted">
<Show
when={item().projectInfo}
fallback={<Show when={item().topLevel && item().icon}>{(icon) => <Icon name={icon()} />}</Show>}
>
{(project) => <ProjectIcon project={project()} class="shrink-0" aria-hidden="true" />}
</Show>
</span>
</Show>
<bdi dir="auto" class="min-w-0 truncate text-v2-text-text-base">
<SearchHighlight text={item().title} />
</bdi>
<Show when={item().page !== item().title && !(item().entity && item().project)}>
<span class="min-w-0 truncate text-v2-text-text-muted">{item().page}</span>
</Show>
</span>
</button>
)}
</SearchList>
</div>
)
}
-16
View File
@@ -874,22 +874,6 @@
display: none;
}
.settings-search[data-expanded="false"] .settings-search-matches {
display: none;
}
.settings-search-matches {
position: absolute;
inset-block-start: calc(100% + 8px);
inset-inline: 0;
z-index: 12;
max-height: 45vh;
padding-block: 8px;
border-radius: 8px;
background: var(--v2-background-bg-base);
box-shadow: var(--v2-elevation-raised);
}
.settings-screen > .settings > .settings-sidebar[data-searchable="false"] {
display: none;
}
@@ -1,4 +1,7 @@
[data-component="search-list"] {
/* Sticky headers and the top fade paint this, so rows scroll under an opaque band. */
--search-list-surface: var(--v2-background-bg-base);
display: flex;
min-height: 0;
flex: 1;
@@ -42,6 +45,17 @@
}
}
[data-slot="search-list-body"] {
display: flex;
min-height: 0;
flex: 1;
flex-direction: column;
&[hidden] {
display: none;
}
}
/* Arrow keys scroll the active row clear of the sticky header. Rows fade out past the bottom edge while more follow. */
[data-slot="search-list-scroll"] {
min-height: 0;
@@ -69,7 +83,7 @@
position: absolute;
inset: var(--search-list-fade-offset, 0px) 0 auto;
height: 24px;
background: linear-gradient(var(--v2-background-bg-base), transparent);
background: linear-gradient(var(--search-list-surface), transparent);
content: "";
opacity: var(--search-list-fade-top, 0);
}
@@ -79,6 +93,11 @@
display: flex;
flex-direction: column;
padding: 6px 6px 8px;
/* Its padding would sit above the empty state and push it below the centre. */
&[hidden] {
display: none;
}
}
[data-slot="search-list-section"] {
@@ -104,7 +123,7 @@
height: 28px;
margin-inline: -6px;
padding-inline: 18px;
background: var(--v2-background-bg-base);
background: var(--search-list-surface);
color: var(--v2-text-text-muted);
font-size: 13px;
font-weight: 440;
@@ -160,6 +179,40 @@
line-height: var(--line-height-compact);
letter-spacing: -0.04px;
}
/* On the rows' text spine, under the bottom fade rather than inside it. */
[data-slot="search-list-footer"] {
flex-shrink: 0;
padding: 4px 18px 12px;
color: var(--v2-text-text-muted);
font-size: 13px;
font-weight: 440;
line-height: var(--line-height-compact);
letter-spacing: -0.04px;
}
&[data-popover] {
--search-list-surface: var(--v2-background-bg-layer-01);
position: relative;
flex: none;
[data-slot="search-list-body"] {
position: absolute;
inset-block-start: calc(100% + 4px);
inset-inline: 0;
z-index: 12;
max-height: min(45vh, 480px);
overflow: hidden;
border-radius: 8px;
background: var(--search-list-surface);
box-shadow: var(--v2-elevation-floating);
}
[data-slot="search-list-scroll"] {
flex: 0 1 auto;
}
}
}
[data-color-scheme="dark"] [data-component="search-list"] [data-slot="search-list-row"][data-active] {
+140 -68
View File
@@ -1,4 +1,15 @@
import { createContext, createEffect, createMemo, For, type JSX, on, onCleanup, Show, useContext } from "solid-js"
import {
createContext,
createEffect,
createMemo,
For,
type JSX,
on,
onCleanup,
onMount,
Show,
useContext,
} from "solid-js"
import { createResizeObserver } from "@solid-primitives/resize-observer"
import { Icon } from "@opencode/ui/icon"
import { TextInput } from "../text-input/text-input"
@@ -18,6 +29,17 @@ export type SearchListRow = {
onClick: () => void
}
/** Attributes for the input of a field passed as `field`: spread them onto it. */
export type SearchListField = {
role: "combobox"
"aria-expanded": boolean
"aria-autocomplete": "list"
"aria-controls": string | undefined
"aria-activedescendant": string | undefined
onInput: (event: InputEvent & { currentTarget: HTMLInputElement }) => void
onKeyDown: (event: KeyboardEvent) => void
}
export type SearchListHandle<T> = {
active: () => T | undefined
setActive: (key: string | undefined) => void
@@ -29,13 +51,22 @@ 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.
* A page can keep its own field through `field` and float the results beneath it with `popover`.
*/
export function SearchList<T>(props: {
query: string
onQuery: (query: string) => void
placeholder: string
/** The results' accessible name; the placeholder by default. */
label?: string
/** Controls after the field, such as icon buttons. */
trailing?: JSX.Element
/** A search field of the page's own in place of the built-in one. */
field?: (field: SearchListField) => JSX.Element
/** Whether the results show. Closed, only the field remains and the list leaves keys to the page. On by default. */
open?: boolean
/** Float the results beneath the field on a raised surface, over what follows it. */
popover?: boolean
items: T[]
key: (item: T) => string
section?: (item: T) => string
@@ -45,6 +76,11 @@ export function SearchList<T>(props: {
header?: (item: T) => JSX.Element
/** Shown in place of the rows when there are none. */
empty: JSX.Element
/** A note beneath the rows, such as a hint that more results are hidden. */
footer?: JSX.Element
/** Where the results start scrolled each time they mount, such as a position kept from an earlier visit. */
scrollTop?: number
onScroll?: (scrollTop: number) => void
onSelect: (item: T) => void
onActive?: (item: T | undefined) => void
/** Runs before the list's own keys; call `preventDefault` to claim one. */
@@ -59,6 +95,7 @@ export function SearchList<T>(props: {
let results: HTMLDivElement | undefined
const sectionOf = (item: T) => props.section?.(item) ?? ""
const open = () => props.open ?? true
// Sections in the order their first row arrives; rows then list section by section, which is also the arrow order.
const groups = createMemo(() => {
@@ -173,7 +210,7 @@ export function SearchList<T>(props: {
if (event.isComposing) return
props.onKeyDown?.(event, typeahead.activeItem())
if (event.defaultPrevented) return
if (event.defaultPrevented || !open()) return
const move = searchListMove(event)
if (!move) return typeahead.onKeyDown(event)
@@ -198,6 +235,30 @@ export function SearchList<T>(props: {
reveal()
}
onMount(() => {
if (viewport && props.scrollTop) viewport.scrollTop = props.scrollTop
})
const field: SearchListField = {
role: "combobox",
get "aria-expanded"() {
return open()
},
"aria-autocomplete": "list",
get "aria-controls"() {
return open() ? typeahead.listID : undefined
},
get "aria-activedescendant"() {
return open() ? typeahead.activeID() : undefined
},
onInput: (event) => {
// A new query starts again from its first row.
typeahead.setActive(undefined)
props.onQuery(event.currentTarget.value)
},
onKeyDown,
}
const row = (key: string, item: () => T): SearchListRow => ({
get id() {
return typeahead.optionID(item())
@@ -221,80 +282,91 @@ export function SearchList<T>(props: {
return (
<QueryContext.Provider value={() => props.query}>
<div data-component="search-list" class={props.class}>
<div data-slot="search-list-search">
<TextInput
value={props.query}
autofocus
autocomplete="off"
autocorrect="off"
autocapitalize="off"
spellcheck={false}
appearance="large"
placeholder={props.placeholder}
aria-label={props.placeholder}
leadingIcon={<Icon name="magnifying-glass" />}
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}
/>
</div>
<div data-slot="search-list-scroll" data-scrollable ref={(element) => (viewport = element)} onScroll={edges}>
<div data-slot="search-list-fade" aria-hidden="true" />
<div data-component="search-list" data-popover={props.popover ? "" : undefined} class={props.class}>
<Show
when={props.field}
fallback={
<div data-slot="search-list-search">
<TextInput
{...field}
value={props.query}
autofocus
autocomplete="off"
autocorrect="off"
autocapitalize="off"
spellcheck={false}
appearance="large"
placeholder={props.placeholder}
aria-label={props.placeholder}
leadingIcon={<Icon name="magnifying-glass" />}
trailing={props.trailing}
/>
</div>
}
>
{(custom) => custom()(field)}
</Show>
<div data-slot="search-list-body" hidden={!open()}>
<div
ref={results}
id={typeahead.listID}
data-slot="search-list-results"
role="listbox"
aria-label={props.placeholder}
data-slot="search-list-scroll"
data-scrollable
ref={(element) => (viewport = element)}
onScroll={(event) => {
edges()
props.onScroll?.(event.currentTarget.scrollTop)
}}
>
<For each={sectionKeys()}>
{(section) => {
const keys = createMemo<string[]>((previous) =>
stable(previous, (groups().get(section) ?? []).map(props.key)),
)
<div data-slot="search-list-fade" aria-hidden="true" />
<div
ref={results}
id={typeahead.listID}
data-slot="search-list-results"
role="listbox"
hidden={rows().length === 0}
aria-label={props.label ?? props.placeholder}
>
<For each={sectionKeys()}>
{(section) => {
const keys = createMemo<string[]>((previous) =>
stable(previous, (groups().get(section) ?? []).map(props.key)),
)
const first = () => byKey().get(keys()[0] ?? "")
const first = () => byKey().get(keys()[0] ?? "")
const header = createMemo(() =>
props.header && first() !== undefined ? props.header(first()!) : undefined,
)
const header = createMemo(() =>
props.header && first() !== undefined ? props.header(first()!) : undefined,
)
const id = `${typeahead.listID}-section-${encodeURIComponent(section)}`
const id = `${typeahead.listID}-section-${encodeURIComponent(section)}`
return (
<div data-slot="search-list-section" role="group" aria-labelledby={header() ? id : undefined}>
<Show when={header()}>
{(content) => (
<div id={id} data-slot="search-list-header">
{content()}
</div>
)}
</Show>
<For each={keys()}>
{(key) => {
// A row that is leaving keeps its last item until it is removed.
const item = createMemo<T>((previous) => byKey().get(key) ?? previous, byKey().get(key)!)
return (
<div data-slot="search-list-section" role="group" aria-labelledby={header() ? id : undefined}>
<Show when={header()}>
{(content) => (
<div id={id} data-slot="search-list-header">
{content()}
</div>
)}
</Show>
<For each={keys()}>
{(key) => {
// A row that is leaving keeps its last item until it is removed.
const item = createMemo<T>((previous) => byKey().get(key) ?? previous, byKey().get(key)!)
return props.children(item, row(key, item))
}}
</For>
</div>
)
}}
</For>
return props.children(item, row(key, item))
}}
</For>
</div>
)
}}
</For>
</div>
<Show when={rows().length === 0}>
<div data-slot="search-list-empty">{props.empty}</div>
</Show>
</div>
<Show when={rows().length === 0}>
<div data-slot="search-list-empty">{props.empty}</div>
<Show when={props.footer}>
<div data-slot="search-list-footer">{props.footer}</div>
</Show>
</div>
</div>
@@ -35,7 +35,9 @@ export function createTypeahead<T>(props: {
onKeyDown: (event: KeyboardEvent) => {
if (event.isComposing) return
const items = props.items()
const delta = event.key === "ArrowDown" ? 1 : event.key === "ArrowUp" ? -1 : 0
// Modified arrows belong to the input: Shift selects text, Ctrl and the rest are the platform's.
const plain = !event.shiftKey && !event.ctrlKey && !event.altKey && !event.metaKey
const delta = !plain ? 0 : event.key === "ArrowDown" ? 1 : event.key === "ArrowUp" ? -1 : 0
if (delta !== 0 || event.key === "Enter" || (event.key === "Escape" && props.onClose)) {
event.preventDefault()