mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-19 08:39:02 +03:00
feat(app): share one search list with sticky sections across Desktop (#58222)
This commit is contained in:
committed by
GitHub
Unverified
parent
e997d7b8a0
commit
077ccee1c3
@@ -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("!")
|
||||
|
||||
@@ -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<void>()
|
||||
@@ -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++
|
||||
}
|
||||
})
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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<Record<string, string | null>>({})
|
||||
|
||||
let container: HTMLElement | undefined
|
||||
let list: SearchListHandle<ModelRow> | undefined
|
||||
let flyoutRef: HTMLDivElement | undefined
|
||||
let timer: ReturnType<typeof setTimeout> | 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(() => <DialogConnectProvider directory={location().directory} selection={props.model} />)
|
||||
}
|
||||
|
||||
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 (
|
||||
<button
|
||||
type="button"
|
||||
data-slot="model-dialog-row"
|
||||
data-option-key={row.id}
|
||||
data-active={active() ? "" : undefined}
|
||||
aria-pressed={selected()}
|
||||
onMouseMove={(event) => move(row.id, event)}
|
||||
{...row.attrs}
|
||||
data-size="compact"
|
||||
data-option-key={row.model.id}
|
||||
aria-current={selected() ? "true" : undefined}
|
||||
onMouseMove={(event) => move(row.model.id, event)}
|
||||
onMouseLeave={(event) => {
|
||||
clearTimeout(timer)
|
||||
const target = event.relatedTarget
|
||||
|
||||
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
|
||||
|
||||
if (flyoutItem() && triangle.contains({ x: event.clientX, y: event.clientY })) return
|
||||
close()
|
||||
}}
|
||||
onClick={() => choose(row.item)}
|
||||
>
|
||||
<span class="flex min-w-0 flex-1 items-baseline gap-1.5">
|
||||
<span class="min-w-0 truncate">{row.item.name}</span>
|
||||
<Show when={row.section}>
|
||||
<span class="min-w-0 shrink-[999] truncate text-v2-text-text-faint">{labels.name(row.item.provider)}</span>
|
||||
<span class="min-w-0 truncate">
|
||||
<SearchHighlight text={item().name} />
|
||||
</span>
|
||||
<Show when={row.model.group.title}>
|
||||
<span class="min-w-0 shrink-[999] truncate text-v2-text-text-faint">{labels.name(item().provider)}</span>
|
||||
</Show>
|
||||
</span>
|
||||
<Show when={isFreeModel(row.item)}>
|
||||
<Show when={isFreeModel(item())}>
|
||||
<Badge class="shrink-0">{language.t("model.tag.free")}</Badge>
|
||||
</Show>
|
||||
<Show when={row.item.latest}>
|
||||
<Show when={item().latest}>
|
||||
<Badge class="shrink-0">{language.t("model.tag.latest")}</Badge>
|
||||
</Show>
|
||||
{/* The slot keeps its width while hidden, so hovering a row never shifts it. The selected row shows only an explicit variant. */}
|
||||
<Show when={variantsOf(row.item).length > 0}>
|
||||
<Show when={variantsOf(item()).length > 0}>
|
||||
<span
|
||||
data-slot="model-dialog-variant"
|
||||
data-default={variant(row.item) ? undefined : ""}
|
||||
data-default={variant(item()) ? undefined : ""}
|
||||
class="w-[72px] shrink-0 truncate text-end capitalize"
|
||||
classList={{ invisible: !active() && !(selected() && variant(row.item)) }}
|
||||
classList={{ invisible: !active() && !(selected() && variant(item())) }}
|
||||
>
|
||||
{variant(row.item) ?? language.t("common.default")}
|
||||
{variant(item()) ?? language.t("common.default")}
|
||||
</span>
|
||||
</Show>
|
||||
<span class="flex size-4 shrink-0 items-center justify-center">
|
||||
@@ -890,21 +845,13 @@ export function DialogSelectModel(props: { provider?: string; model?: ModelState
|
||||
<DialogTitle>{language.t("dialog.model.select.title")}</DialogTitle>
|
||||
</div>
|
||||
<DialogBody class="command-palette-body">
|
||||
<div class="palette-menu-search">
|
||||
<TextInput
|
||||
type="search"
|
||||
appearance="large"
|
||||
value={store.search}
|
||||
autofocus
|
||||
{/* Scrolling moves the flyout's row away without a pointer event, which would leave it detached. */}
|
||||
<div class="contents" ref={(element) => createEventListener(element, "scroll", close, { capture: true })}>
|
||||
<SearchList
|
||||
ref={(handle) => (list = handle)}
|
||||
query={store.search}
|
||||
onQuery={setSearch}
|
||||
placeholder={language.t("dialog.model.search.placeholder")}
|
||||
aria-label={language.t("dialog.model.search.placeholder")}
|
||||
spellcheck={false}
|
||||
autocorrect="off"
|
||||
autocomplete="off"
|
||||
autocapitalize="off"
|
||||
leadingIcon={<Icon name="magnifying-glass" />}
|
||||
onInput={(event) => setSearch(event.currentTarget.value)}
|
||||
onKeyDown={onKeyDown}
|
||||
trailing={
|
||||
<>
|
||||
<Show when={store.search.trim()}>
|
||||
@@ -941,49 +888,33 @@ export function DialogSelectModel(props: { provider?: string; model?: ModelState
|
||||
</Tooltip>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
items={rows()}
|
||||
key={(row) => row.id}
|
||||
section={(row) => row.group.category}
|
||||
same={(a, b) => modelKey(a.item) === modelKey(b.item)}
|
||||
header={(row) => (
|
||||
<Show
|
||||
when={row.group.title}
|
||||
fallback={
|
||||
<>
|
||||
<ProviderModelIcon provider={row.item.provider} class="!size-3.5 shrink-0" />
|
||||
<span class="min-w-0 truncate">{labels.name(row.item.provider)}</span>
|
||||
<Show when={labels.workspace(row.item.provider)}>
|
||||
{(workspace) => <Badge class="shrink-0">{workspace()}</Badge>}
|
||||
</Show>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{(title) => <span class="min-w-0 truncate">{title()}</span>}
|
||||
</Show>
|
||||
)}
|
||||
empty={language.t("dialog.model.empty")}
|
||||
onSelect={(row) => choose(row.item)}
|
||||
onKeyDown={onKeyDown}
|
||||
>
|
||||
{(row, attrs) => <Row model={row()} attrs={attrs} />}
|
||||
</SearchList>
|
||||
</div>
|
||||
<ScrollView
|
||||
class="command-palette-scroll"
|
||||
viewportRef={(element) => {
|
||||
container = element
|
||||
// Scrolling moves the flyout's row away without a pointer event, which would leave it detached.
|
||||
createEventListener(element, "scroll", close)
|
||||
}}
|
||||
>
|
||||
<div data-slot="model-dialog-results">
|
||||
<Show
|
||||
when={models().length > 0}
|
||||
fallback={<div class="command-palette-state">{language.t("dialog.model.empty")}</div>}
|
||||
>
|
||||
<For each={groups()}>
|
||||
{(group) => (
|
||||
<div data-slot="model-dialog-group">
|
||||
<div data-slot="model-dialog-group-title">
|
||||
<Show
|
||||
when={group.title}
|
||||
fallback={
|
||||
<>
|
||||
<ProviderModelIcon provider={group.items[0].provider} class="!size-3.5 shrink-0" />
|
||||
<span class="min-w-0 truncate">{labels.name(group.items[0].provider)}</span>
|
||||
<Show when={labels.workspace(group.items[0].provider)}>
|
||||
{(workspace) => <Badge class="shrink-0">{workspace()}</Badge>}
|
||||
</Show>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{(title) => <span class="min-w-0 truncate">{title()}</span>}
|
||||
</Show>
|
||||
</div>
|
||||
<For each={group.items}>
|
||||
{(item) => <Row id={rowKey(group, item)} item={item} section={!!group.title} />}
|
||||
</For>
|
||||
</div>
|
||||
)}
|
||||
</For>
|
||||
</Show>
|
||||
</div>
|
||||
</ScrollView>
|
||||
<Show when={chatgptPlan()}>
|
||||
<ChatgptPlanFooter />
|
||||
</Show>
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
import { getDirectory, getFilename } from "@opencode/util/path"
|
||||
import { FileIcon } from "@opencode/ui/file-icon"
|
||||
import { ScrollView } from "@opencode/ui/scroll-view"
|
||||
import { Dialog, DialogBody } from "@opencode/ui/dialog"
|
||||
import { Icon } from "@opencode/ui/icon"
|
||||
import { Keybind } from "@opencode/ui/keybind"
|
||||
import { TextInput } from "@opencode/ui/text-input"
|
||||
import { createTypeahead } from "@opencode/ui/typeahead"
|
||||
import { createEffect, createMemo, For, Match, onCleanup, Show, Switch } from "solid-js"
|
||||
import { SearchHighlight, SearchList, type SearchListRow } from "@opencode/ui/search-list"
|
||||
import { createMemo, Match, Show, Switch } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { formatKeybindParts } from "@/shell/commands/command"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
@@ -70,142 +67,54 @@ export function CommandPaletteView(props: {
|
||||
const tabs = useTabs()
|
||||
const [store, setStore] = createStore({ query: "" })
|
||||
|
||||
const search = createCommandPaletteSearch({ query: () => store.query, items: props.items, sources: props.sources })
|
||||
const visibleEntries = search.items
|
||||
const entryById = createMemo(() => new Map(visibleEntries().map((entry) => [entry.id, entry] as const)))
|
||||
|
||||
const groupKeys = createMemo<string[]>((prev) => {
|
||||
const next = [...new Set(visibleEntries().map(groupKey))]
|
||||
|
||||
return prev && prev.length === next.length && prev.every((key, index) => key === next[index]) ? prev : next
|
||||
})
|
||||
|
||||
// Follow the first result until the user explicitly chooses a row.
|
||||
const typeahead = createTypeahead<CommandPaletteEntry>({
|
||||
items: visibleEntries,
|
||||
key: (entry) => entry.id,
|
||||
onSelect: props.select,
|
||||
onClose: props.close,
|
||||
})
|
||||
|
||||
const activeEntry = typeahead.activeItem
|
||||
|
||||
const openSessions = createMemo(
|
||||
() => new Set(tabs.store.flatMap((tab) => (tab.type === "session" ? [`${tab.server}\0${tab.sessionId}`] : []))),
|
||||
)
|
||||
|
||||
createEffect(() => {
|
||||
props.highlight(activeEntry())
|
||||
})
|
||||
const sessionOpen = (entry: CommandPaletteEntry) =>
|
||||
!!entry.server && !!entry.sessionID && openSessions().has(`${entry.server}\0${entry.sessionID}`)
|
||||
|
||||
let resultsRef: HTMLDivElement | undefined
|
||||
|
||||
createEffect(() => {
|
||||
// Incoming results can move an explicitly selected row below the viewport.
|
||||
visibleEntries()
|
||||
|
||||
if (!activeEntry()) return
|
||||
|
||||
const frame = requestAnimationFrame(() => {
|
||||
resultsRef?.querySelector("[data-active]")?.scrollIntoView({ block: "nearest" })
|
||||
})
|
||||
|
||||
onCleanup(() => cancelAnimationFrame(frame))
|
||||
const search = createCommandPaletteSearch({
|
||||
query: () => store.query,
|
||||
items: props.items,
|
||||
sources: props.sources,
|
||||
open: sessionOpen,
|
||||
})
|
||||
|
||||
return (
|
||||
<Dialog class="command-palette" size="large">
|
||||
<DialogBody class="command-palette-body">
|
||||
<div class="palette-menu-search">
|
||||
<TextInput
|
||||
value={store.query}
|
||||
autofocus
|
||||
autocomplete="off"
|
||||
spellcheck={false}
|
||||
appearance="large"
|
||||
placeholder={props.placeholder}
|
||||
leadingIcon={<Icon name="magnifying-glass" />}
|
||||
role="combobox"
|
||||
aria-expanded="true"
|
||||
aria-controls={typeahead.listID}
|
||||
aria-activedescendant={typeahead.activeID()}
|
||||
onInput={(event) => setStore("query", event.currentTarget.value)}
|
||||
onKeyDown={typeahead.onKeyDown}
|
||||
/>
|
||||
</div>
|
||||
<ScrollView class="command-palette-scroll" viewportRef={(el) => (resultsRef = el)}>
|
||||
<div id={typeahead.listID} class="command-palette-results" role="listbox">
|
||||
<Show
|
||||
when={visibleEntries().length > 0}
|
||||
fallback={
|
||||
<div class="command-palette-state">
|
||||
{search.loading()
|
||||
? language.t("common.loading")
|
||||
: search.failed()
|
||||
? language.t("common.requestFailed")
|
||||
: language.t("palette.empty")}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<For each={groupKeys()}>
|
||||
{(key) => {
|
||||
const entries = createMemo(() => visibleEntries().filter((entry) => groupKey(entry) === key))
|
||||
const category = createMemo(() => entries()[0]?.category ?? "")
|
||||
|
||||
const ids = createMemo<string[]>((prev) => {
|
||||
const next = entries().map((entry) => entry.id)
|
||||
|
||||
return prev && prev.length === next.length && prev.every((id, index) => id === next[index])
|
||||
? prev
|
||||
: next
|
||||
})
|
||||
|
||||
return (
|
||||
<div class="command-palette-group">
|
||||
<Show when={category()}>
|
||||
<div class="command-palette-group-title">{category()}</div>
|
||||
</Show>
|
||||
<For each={ids()}>
|
||||
{(id) => {
|
||||
const item = () => entryById().get(id) ?? entries()[0]!
|
||||
|
||||
return (
|
||||
<PaletteRow
|
||||
id={typeahead.optionID(item())}
|
||||
item={item()}
|
||||
active={activeEntry()?.id === id}
|
||||
language={language}
|
||||
sessionOpen={
|
||||
item().server && item().sessionID
|
||||
? openSessions().has(`${item().server}\0${item().sessionID}`)
|
||||
: false
|
||||
}
|
||||
onActive={() => typeahead.setActive(id)}
|
||||
onSelect={() => props.select(item())}
|
||||
/>
|
||||
)
|
||||
}}
|
||||
</For>
|
||||
</div>
|
||||
)
|
||||
}}
|
||||
</For>
|
||||
</Show>
|
||||
</div>
|
||||
</ScrollView>
|
||||
<SearchList
|
||||
query={store.query}
|
||||
onQuery={(query) => setStore("query", query)}
|
||||
placeholder={props.placeholder}
|
||||
items={search.items()}
|
||||
key={(entry) => entry.id}
|
||||
section={groupKey}
|
||||
header={(entry) => entry.category || undefined}
|
||||
empty={
|
||||
search.loading()
|
||||
? language.t("common.loading")
|
||||
: search.failed()
|
||||
? language.t("common.requestFailed")
|
||||
: language.t("palette.empty")
|
||||
}
|
||||
onActive={props.highlight}
|
||||
onSelect={props.select}
|
||||
onClose={props.close}
|
||||
>
|
||||
{(item, row) => <PaletteRow row={row} item={item()} language={language} sessionOpen={sessionOpen(item())} />}
|
||||
</SearchList>
|
||||
</DialogBody>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function PaletteRow(props: {
|
||||
id: string
|
||||
row: SearchListRow
|
||||
item: CommandPaletteEntry
|
||||
active: boolean
|
||||
language: ReturnType<typeof useLanguage>
|
||||
sessionOpen: boolean
|
||||
onActive: () => void
|
||||
onSelect: () => void
|
||||
}) {
|
||||
const session = () =>
|
||||
props.item.server && props.item.directory && props.item.sessionID
|
||||
@@ -213,28 +122,18 @@ function PaletteRow(props: {
|
||||
: undefined
|
||||
|
||||
return (
|
||||
<button
|
||||
id={props.id}
|
||||
type="button"
|
||||
class="command-palette-row palette-menu-row group"
|
||||
role="option"
|
||||
aria-selected={props.active}
|
||||
data-active={props.active ? "" : undefined}
|
||||
onMouseMove={(event) => {
|
||||
// Ignore hover from a static cursor when keyboard scrolling moves rows underneath it.
|
||||
if (event.movementX === 0 && event.movementY === 0) return
|
||||
props.onActive()
|
||||
}}
|
||||
onMouseDown={(event) => event.preventDefault()}
|
||||
onClick={props.onSelect}
|
||||
>
|
||||
<button type="button" class="command-palette-row group" {...props.row}>
|
||||
<Switch
|
||||
fallback={
|
||||
<div class="command-palette-row-main">
|
||||
<FileIcon node={{ path: props.item.path ?? "", type: "file" }} class="command-palette-row-icon size-4" />
|
||||
<div class="command-palette-file-path">
|
||||
<span class="command-palette-file-dir">{getDirectory(props.item.path ?? "")}</span>
|
||||
<span class="command-palette-file-name">{getFilename(props.item.path ?? "")}</span>
|
||||
<span class="command-palette-file-dir">
|
||||
<SearchHighlight text={getDirectory(props.item.path ?? "")} />
|
||||
</span>
|
||||
<span class="command-palette-file-name">
|
||||
<SearchHighlight text={getFilename(props.item.path ?? "")} />
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@@ -242,9 +141,15 @@ function PaletteRow(props: {
|
||||
<Match when={props.item.type === "command" || props.item.type === "setting"}>
|
||||
<div class="command-palette-row-main">
|
||||
<div class="command-palette-row-text">
|
||||
<span class="command-palette-title palette-menu-title">{props.item.title}</span>
|
||||
<span class="command-palette-title palette-menu-title">
|
||||
<SearchHighlight text={props.item.title} />
|
||||
</span>
|
||||
<Show when={props.item.description}>
|
||||
<span class="command-palette-description">{props.item.description}</span>
|
||||
{(description) => (
|
||||
<span class="command-palette-description">
|
||||
<SearchHighlight text={description()} />
|
||||
</span>
|
||||
)}
|
||||
</Show>
|
||||
</div>
|
||||
</div>
|
||||
@@ -278,12 +183,14 @@ function PaletteRow(props: {
|
||||
class="command-palette-title palette-menu-title"
|
||||
classList={{ "opacity-70": !!props.item.archived }}
|
||||
>
|
||||
{props.item.title}
|
||||
<SearchHighlight text={props.item.title} />
|
||||
</span>
|
||||
<Show when={props.item.description}>
|
||||
<span class="command-palette-description" classList={{ "opacity-70": !!props.item.archived }}>
|
||||
{props.item.description}
|
||||
</span>
|
||||
{(description) => (
|
||||
<span class="command-palette-description" classList={{ "opacity-70": !!props.item.archived }}>
|
||||
<SearchHighlight text={description()} />
|
||||
</span>
|
||||
)}
|
||||
</Show>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -152,7 +152,8 @@ export function createCommandPaletteModel(props: { filesOnly?: () => boolean; on
|
||||
server: ServerConnection.key(serverSDK.server),
|
||||
known: createKnownServerSessions(serverCtx),
|
||||
projects: serverCtx.projects.list,
|
||||
load: (search, signal) => serverSDK.api.session.list({ parentID: null, search, limit: 50 }, { signal }),
|
||||
load: (search, signal) =>
|
||||
serverSDK.api.session.list({ parentID: null, search, archived: false, limit: 50 }, { signal }),
|
||||
get: (sessionID, signal) => serverSDK.api.session.get({ sessionID }, { signal }),
|
||||
untitled: () => language.t("command.session.new"),
|
||||
category: () => language.t("command.category.session"),
|
||||
@@ -363,9 +364,7 @@ export function createKnownServerSessions(server: ServerCtx) {
|
||||
queryClient.getQueryData<SessionInfo[]>(["home-sessions", ServerConnection.key(server.sdk.server)]) ??
|
||||
[]
|
||||
|
||||
const merged = new Map(
|
||||
[...cached, ...server.data.session.list()].map((session) => [session.id, session] as const),
|
||||
)
|
||||
const merged = new Map([...cached, ...server.data.session.list()].map((session) => [session.id, session] as const))
|
||||
|
||||
return server.data.session.apply(
|
||||
[...merged.values()].filter((session) => !session.parentID && !session.time.archived),
|
||||
|
||||
@@ -19,15 +19,36 @@ export function matchesCommandPaletteEntry(entry: CommandPaletteEntry, query: st
|
||||
|
||||
if (!value) return true
|
||||
|
||||
return [entry.title, entry.description, entry.category, entry.keywords, entry.path, entry.sessionID].some((text) =>
|
||||
// The server matches sessions by title, so their "Session" group name must not match every one of them here.
|
||||
const category = entry.type === "session" ? undefined : entry.category
|
||||
|
||||
return [entry.title, entry.description, category, entry.keywords, entry.path, entry.sessionID].some((text) =>
|
||||
text?.toLowerCase().includes(value),
|
||||
)
|
||||
}
|
||||
|
||||
const typeOrder = { session: 0, command: 1, setting: 2, file: 3 }
|
||||
|
||||
/** Search results: sessions lead, those open as tabs first and then the newest, then commands, settings and files. */
|
||||
export function rankCommandPaletteEntries(
|
||||
entries: CommandPaletteEntry[],
|
||||
open: (entry: CommandPaletteEntry) => boolean,
|
||||
) {
|
||||
return entries.toSorted(
|
||||
(a, b) =>
|
||||
typeOrder[a.type] - typeOrder[b.type] ||
|
||||
(a.type === "session" && b.type === "session"
|
||||
? Number(open(b)) - Number(open(a)) || (b.updated ?? 0) - (a.updated ?? 0)
|
||||
: 0),
|
||||
)
|
||||
}
|
||||
|
||||
export function createCommandPaletteSearch(props: {
|
||||
query: () => string
|
||||
items: (query: string) => CommandPaletteEntry[]
|
||||
sources: ((query: string, signal: AbortSignal) => Promise<CommandPaletteEntry[]>)[]
|
||||
/** Sessions open as tabs, which lead the matching sessions. */
|
||||
open?: (entry: CommandPaletteEntry) => boolean
|
||||
}) {
|
||||
const query = createMemo(() => props.query().trim())
|
||||
const local = createMemo(() => props.items(query()))
|
||||
@@ -91,13 +112,7 @@ export function createCommandPaletteSearch(props: {
|
||||
|
||||
if (!current) return entries
|
||||
|
||||
const order = { command: 0, setting: 1, session: 2, file: 3 }
|
||||
|
||||
return entries.toSorted(
|
||||
(a, b) =>
|
||||
order[a.type] - order[b.type] ||
|
||||
(a.type === "session" && b.type === "session" ? (b.updated ?? 0) - (a.updated ?? 0) : 0),
|
||||
)
|
||||
return rankCommandPaletteEntries(entries, props.open ?? (() => false))
|
||||
})
|
||||
|
||||
return {
|
||||
|
||||
@@ -27,7 +27,8 @@ export function DialogSessionSearch() {
|
||||
server: ServerConnection.key(conn),
|
||||
known: createKnownServerSessions(ctx),
|
||||
projects: ctx.projects.list,
|
||||
load: (search, signal) => ctx.sdk.api.session.list({ parentID: null, search, limit: 50 }, { signal }),
|
||||
load: (search, signal) =>
|
||||
ctx.sdk.api.session.list({ parentID: null, search, archived: false, limit: 50 }, { signal }),
|
||||
get: (sessionID, signal) => ctx.sdk.api.session.get({ sessionID }, { signal }),
|
||||
untitled: () => language.t("command.session.new"),
|
||||
category: () => language.t("command.category.session"),
|
||||
|
||||
@@ -24,8 +24,11 @@ const session: CommandPaletteEntry = {
|
||||
type: "session",
|
||||
title: "Copy session",
|
||||
category: "Sessions",
|
||||
updated: 2,
|
||||
}
|
||||
|
||||
const tab: CommandPaletteEntry = { ...session, id: "session:tab", title: "Copy tab", updated: 1 }
|
||||
|
||||
describe("command palette search", () => {
|
||||
test("matches commands synchronously and cancels obsolete requests", () => {
|
||||
const signals: AbortSignal[] = []
|
||||
@@ -59,7 +62,7 @@ describe("command palette search", () => {
|
||||
expect(signals[2].aborted).toBe(true)
|
||||
})
|
||||
|
||||
test("lists settings above sessions and files, publishes each source independently, and drops stale results on a new query", async () => {
|
||||
test("lists sessions first, open tabs leading, then commands, settings and files, publishes each source independently, and drops stale results on a new query", async () => {
|
||||
const files = Promise.withResolvers<CommandPaletteEntry[]>()
|
||||
const sessions = Promise.withResolvers<CommandPaletteEntry[]>()
|
||||
const fileVisible = Promise.withResolvers<void>()
|
||||
@@ -72,6 +75,7 @@ describe("command palette search", () => {
|
||||
query,
|
||||
items: () => [copy, setting],
|
||||
sources: [() => sessions.promise, () => files.promise],
|
||||
open: (entry) => entry.id === tab.id,
|
||||
})
|
||||
|
||||
createComputed(() => {
|
||||
@@ -88,9 +92,9 @@ describe("command palette search", () => {
|
||||
await fileVisible.promise
|
||||
expect(root.search.items()).toEqual([copy, setting, file])
|
||||
expect(root.search.loading()).toBe(true)
|
||||
sessions.resolve([session])
|
||||
sessions.resolve([session, tab])
|
||||
await sessionVisible.promise
|
||||
expect(root.search.items()).toEqual([copy, setting, session, file])
|
||||
expect(root.search.items()).toEqual([tab, session, copy, setting, file])
|
||||
expect(root.search.loading()).toBe(false)
|
||||
root.setQuery("new query")
|
||||
expect(root.search.items()).toEqual([copy, setting])
|
||||
|
||||
@@ -175,4 +175,11 @@ describe("command palette commands", () => {
|
||||
expect(matchesCommandPaletteEntry(entry, "Diagnostics")).toBe(true)
|
||||
expect(matchesCommandPaletteEntry(entry, "terminal")).toBe(false)
|
||||
})
|
||||
|
||||
test("match a session by its title, not by its group name, as the server does", () => {
|
||||
const entry = { id: "session:tabs", type: "session" as const, title: "Fix tabs", category: "Session" }
|
||||
|
||||
expect(matchesCommandPaletteEntry(entry, "tabs")).toBe(true)
|
||||
expect(matchesCommandPaletteEntry(entry, "session")).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -63,6 +63,7 @@
|
||||
"./progress-circle": "./src/feedback/progress-circle/progress-circle.tsx",
|
||||
"./project-avatar": "./src/data-display/project-avatar/project-avatar.tsx",
|
||||
"./radio": "./src/forms/radio/radio.tsx",
|
||||
"./search-list": "./src/forms/search-list/search-list.tsx",
|
||||
"./segmented-control": "./src/navigation/segmented-control/segmented-control.tsx",
|
||||
"./select": "./src/forms/select/select.tsx",
|
||||
"./split-button": "./src/actions/split-button/split-button.tsx",
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { searchListMove, searchListTarget, type SearchListMove } from "./navigation"
|
||||
|
||||
const key = (key: string, modifiers: { metaKey?: boolean; altKey?: boolean; shiftKey?: boolean } = {}) => ({
|
||||
key,
|
||||
ctrlKey: false,
|
||||
metaKey: false,
|
||||
altKey: false,
|
||||
shiftKey: false,
|
||||
...modifiers,
|
||||
})
|
||||
|
||||
test("⌘ and ⌥ arrows jump sections, Home and End reach the ends, and Shift stays with the input", () => {
|
||||
expect(searchListMove(key("ArrowDown"))).toBe("next")
|
||||
expect(searchListMove(key("ArrowDown", { metaKey: true }))).toBe("nextSection")
|
||||
expect(searchListMove(key("ArrowUp", { altKey: true }))).toBe("previousSection")
|
||||
expect(searchListMove(key("Home"))).toBe("first")
|
||||
expect(searchListMove(key("End", { shiftKey: true }))).toBeUndefined()
|
||||
expect(searchListMove(key("Home", { metaKey: true }))).toBeUndefined()
|
||||
})
|
||||
|
||||
// Sections a a | b | c c c, so rows 0–1, 2 and 3–5.
|
||||
const sections = ["a", "a", "b", "c", "c", "c"]
|
||||
|
||||
test.each<[number, SearchListMove, number]>([
|
||||
[0, "nextSection", 2],
|
||||
[1, "nextSection", 2],
|
||||
[2, "nextSection", 3],
|
||||
[4, "nextSection", 0],
|
||||
[4, "previousSection", 3],
|
||||
[3, "previousSection", 2],
|
||||
[2, "previousSection", 0],
|
||||
[0, "previousSection", 3],
|
||||
[5, "next", 0],
|
||||
[0, "previous", 5],
|
||||
[3, "first", 0],
|
||||
[1, "last", 5],
|
||||
])("from row %i, %s lands on row %i", (from, move, to) => {
|
||||
expect(searchListTarget(sections, from, move)).toBe(to)
|
||||
})
|
||||
@@ -0,0 +1,54 @@
|
||||
export type SearchListMove = "next" | "previous" | "nextSection" | "previousSection" | "first" | "last"
|
||||
|
||||
/** The move a key asks of a search list, or nothing when the key belongs to the input. */
|
||||
export function searchListMove(event: Pick<KeyboardEvent, "key" | "altKey" | "ctrlKey" | "metaKey" | "shiftKey">) {
|
||||
if (event.shiftKey || event.ctrlKey) return
|
||||
|
||||
const section = event.metaKey || event.altKey
|
||||
|
||||
if (event.key === "ArrowDown") return section ? "nextSection" : "next"
|
||||
|
||||
if (event.key === "ArrowUp") return section ? "previousSection" : "previous"
|
||||
|
||||
if (section) return
|
||||
|
||||
if (event.key === "Home") return "first"
|
||||
|
||||
if (event.key === "End") return "last"
|
||||
}
|
||||
|
||||
/**
|
||||
* The row a move lands on, given each row's section key. Arrows wrap. A section move lands on a section's first row:
|
||||
* up goes to the start of the current section first, as a paragraph jump does, then to the previous one.
|
||||
*/
|
||||
export function searchListTarget(sections: string[], index: number, move: SearchListMove) {
|
||||
const count = sections.length
|
||||
|
||||
if (count === 0) return -1
|
||||
|
||||
if (move === "first") return 0
|
||||
|
||||
if (move === "last") return count - 1
|
||||
|
||||
if (move === "next") return (index + 1) % count
|
||||
|
||||
if (move === "previous") return index <= 0 ? count - 1 : index - 1
|
||||
|
||||
const start = (at: number) => {
|
||||
const found = sections.slice(0, at + 1).findLastIndex((key, i) => i === 0 || sections[i - 1] !== key)
|
||||
|
||||
return Math.max(found, 0)
|
||||
}
|
||||
|
||||
const current = start(Math.max(index, 0))
|
||||
|
||||
if (move === "previousSection") {
|
||||
if (index > current) return current
|
||||
|
||||
return current === 0 ? start(count - 1) : start(current - 1)
|
||||
}
|
||||
|
||||
const next = sections.findIndex((key, i) => i > current && key !== sections[current])
|
||||
|
||||
return next === -1 ? 0 : next
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
[data-component="search-list"] {
|
||||
display: flex;
|
||||
min-height: 0;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
|
||||
[data-slot="search-list-search"] {
|
||||
flex-shrink: 0;
|
||||
padding: 6px;
|
||||
|
||||
[data-component="text-input-v2"] {
|
||||
width: 100%;
|
||||
height: 36px;
|
||||
padding-inline-end: 12px;
|
||||
border-radius: 6px;
|
||||
outline: 0;
|
||||
background: color-mix(in srgb, var(--v2-background-bg-layer-02) 60%, transparent);
|
||||
box-shadow: none;
|
||||
transition:
|
||||
background-color 120ms ease-in-out,
|
||||
box-shadow 120ms ease-in-out;
|
||||
}
|
||||
|
||||
[data-component="text-input-v2"]:where(:hover, :focus-within):not([data-disabled], [data-invalid]) {
|
||||
background: var(--v2-background-bg-layer-02);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
[data-slot="text-input-v2-value"] {
|
||||
gap: 8px;
|
||||
border-radius: 6px;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
[data-slot="text-input-v2-leading-icon"] {
|
||||
padding-inline-start: 12px;
|
||||
}
|
||||
|
||||
[data-slot="text-input-v2-input"] {
|
||||
border-radius: 6px;
|
||||
background: transparent;
|
||||
}
|
||||
}
|
||||
|
||||
[data-slot="search-list-scroll"] {
|
||||
min-height: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* 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"] > .scroll-view__viewport {
|
||||
--search-list-edge: linear-gradient(
|
||||
to bottom,
|
||||
#000 calc(100% - 24px),
|
||||
rgb(0 0 0 / calc(1 - var(--search-list-fade-bottom, 0)))
|
||||
);
|
||||
scroll-padding-top: 28px;
|
||||
-webkit-mask-image: var(--search-list-edge);
|
||||
mask-image: var(--search-list-edge);
|
||||
}
|
||||
|
||||
/* Rows fade out under the top section's header, or under the field when it has none. Headers stay above the fade. */
|
||||
[data-slot="search-list-fade"] {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 1;
|
||||
height: 0;
|
||||
pointer-events: none;
|
||||
|
||||
&::before {
|
||||
position: absolute;
|
||||
inset: var(--search-list-fade-offset, 0px) 0 auto;
|
||||
height: 24px;
|
||||
background: linear-gradient(var(--v2-background-bg-base), transparent);
|
||||
content: "";
|
||||
opacity: var(--search-list-fade-top, 0);
|
||||
}
|
||||
}
|
||||
|
||||
[data-slot="search-list-results"] {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 6px 6px 8px;
|
||||
}
|
||||
|
||||
[data-slot="search-list-section"] {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
|
||||
/* Space inside the section, not between sections, so the next header meets this one and pushes it up. */
|
||||
&:not(:last-child) {
|
||||
padding-bottom: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
/* The header bleeds to the list's edges so rows scroll under an opaque band, and its text stays on the rows' spine. */
|
||||
[data-slot="search-list-header"] {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 2;
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
height: 28px;
|
||||
margin-inline: -6px;
|
||||
padding-inline: 18px;
|
||||
background: var(--v2-background-bg-base);
|
||||
color: var(--v2-text-text-muted);
|
||||
font-size: 13px;
|
||||
font-weight: 440;
|
||||
line-height: var(--line-height-compact);
|
||||
letter-spacing: -0.04px;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
[data-slot="search-list-row"] {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
height: 36px;
|
||||
flex-shrink: 0;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
padding: 0 12px;
|
||||
border: 0;
|
||||
border-radius: 6px;
|
||||
background: transparent;
|
||||
color: var(--v2-text-text-base);
|
||||
text-align: start;
|
||||
cursor: default;
|
||||
scroll-margin-block: 0 24px;
|
||||
|
||||
&[data-active] {
|
||||
background: var(--v2-overlay-simple-overlay-hover);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
&[data-size="compact"] {
|
||||
height: 28px;
|
||||
}
|
||||
}
|
||||
|
||||
/* A row under the one above it keeps clear of the fade beneath the header; a section's first row sits right under it. */
|
||||
[data-slot="search-list-row"] + [data-slot="search-list-row"] {
|
||||
scroll-margin-top: 24px;
|
||||
}
|
||||
|
||||
[data-slot="search-list-match"] {
|
||||
background: transparent;
|
||||
color: var(--v2-text-text-accent);
|
||||
}
|
||||
|
||||
[data-slot="search-list-empty"] {
|
||||
display: grid;
|
||||
min-height: 120px;
|
||||
place-items: center;
|
||||
color: var(--v2-text-text-muted);
|
||||
font-size: 13px;
|
||||
font-weight: 440;
|
||||
line-height: var(--line-height-compact);
|
||||
letter-spacing: -0.04px;
|
||||
}
|
||||
}
|
||||
|
||||
[data-color-scheme="dark"] [data-component="search-list"] [data-slot="search-list-row"][data-active] {
|
||||
background: var(--v2-alpha-light-10);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
[data-component="search-list"] {
|
||||
[data-slot="search-list-search"] [data-component="text-input-v2"] {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { createMemo } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { Keybind } from "@opencode/ui/keybind"
|
||||
import { SearchHighlight, SearchList } from "./search-list"
|
||||
|
||||
type Row = { id: string; section: string; title: string; description: string; keybind?: string[] }
|
||||
|
||||
const names = ["Sessions", "Commands", "Settings", "Files", "Models", "Projects", "Servers", "Themes"]
|
||||
|
||||
const words = ["Desktop", "Palette", "Sticky headers", "Command menu", "Session search", "Model selector", "Theme"]
|
||||
|
||||
function SearchListStory(props: { sections: number; rows: number; sticky: boolean; query: string }) {
|
||||
const [store, setStore] = createStore({ query: props.query, selected: "" })
|
||||
|
||||
const rows = createMemo(() =>
|
||||
names.slice(0, Math.max(1, props.sections)).flatMap((section, s) =>
|
||||
Array.from(
|
||||
{ length: Math.max(1, props.rows) },
|
||||
(_, index): Row => ({
|
||||
id: `${section}-${index}`,
|
||||
section,
|
||||
title: `${words[(index + s) % words.length]} ${index + 1}`,
|
||||
description: section === "Sessions" ? "opencode" : section,
|
||||
keybind: section === "Commands" && index < 3 ? ["⌥", index % 2 ? "↓" : "↑"] : undefined,
|
||||
}),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
const visible = createMemo(() => {
|
||||
const query = store.query.trim().toLowerCase()
|
||||
|
||||
return query ? rows().filter((row) => `${row.title} ${row.description}`.toLowerCase().includes(query)) : rows()
|
||||
})
|
||||
|
||||
return (
|
||||
<div
|
||||
class="flex h-[480px] w-[640px] flex-col overflow-hidden rounded-xl bg-v2-background-bg-base shadow-[var(--v2-elevation-floating)]"
|
||||
data-static-headers={props.sticky ? undefined : ""}
|
||||
>
|
||||
<style>{`[data-static-headers] [data-slot="search-list-header"] { position: static; }`}</style>
|
||||
<SearchList
|
||||
query={store.query}
|
||||
onQuery={(query) => setStore("query", query)}
|
||||
placeholder="Search files, commands, and sessions"
|
||||
items={visible()}
|
||||
key={(row) => row.id}
|
||||
section={(row) => row.section}
|
||||
header={(row) => row.section}
|
||||
empty="No results"
|
||||
onSelect={(row) => setStore("selected", row.id)}
|
||||
>
|
||||
{(row, attrs) => (
|
||||
<button type="button" {...attrs}>
|
||||
<span class="flex min-w-0 items-center gap-1.5 text-[13px] leading-4 tracking-[-0.04px]">
|
||||
<span class="truncate font-[530] text-v2-text-text-base">
|
||||
<SearchHighlight text={row().title} />
|
||||
</span>
|
||||
<span class="truncate text-v2-text-text-muted">
|
||||
<SearchHighlight text={row().description} />
|
||||
</span>
|
||||
</span>
|
||||
{row().keybind && <Keybind keys={row().keybind!} variant="neutral" />}
|
||||
</button>
|
||||
)}
|
||||
</SearchList>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
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 } }
|
||||
@@ -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<T> = {
|
||||
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<T>(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<T>) => 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<string, T[]>()
|
||||
|
||||
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<string[]>((previous) => stable(previous, [...groups().keys()]))
|
||||
|
||||
const typeahead = createTypeahead<T>({
|
||||
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<HTMLElement>('[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<HTMLElement>('[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 (
|
||||
<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>
|
||||
<ScrollView data-slot="search-list-scroll" viewportRef={(element) => (viewport = element)} onScroll={edges}>
|
||||
<div data-slot="search-list-fade" aria-hidden="true" />
|
||||
<div
|
||||
ref={results}
|
||||
id={typeahead.listID}
|
||||
data-slot="search-list-results"
|
||||
role="listbox"
|
||||
aria-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 header = createMemo(() =>
|
||||
props.header && first() !== undefined ? props.header(first()!) : undefined,
|
||||
)
|
||||
|
||||
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 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>
|
||||
</ScrollView>
|
||||
</div>
|
||||
</QueryContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
/** 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 (
|
||||
<Show when={match()} fallback={props.text}>
|
||||
{(range) => (
|
||||
<>
|
||||
{props.text.slice(0, range().at)}
|
||||
<mark data-slot="search-list-match">{props.text.slice(range().at, range().end)}</mark>
|
||||
{props.text.slice(range().end)}
|
||||
</>
|
||||
)}
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
|
||||
function stable(previous: string[] | undefined, next: string[]) {
|
||||
return previous && previous.length === next.length && previous.every((value, index) => value === next[index])
|
||||
? previous
|
||||
: next
|
||||
}
|
||||
Reference in New Issue
Block a user