TypeScript
feat(web): command palette search finds options inside submenus (#24709)
mariae9d61252f6fd
diff --git a/apps/web/src/components/CommandPalette.logic.test.ts b/apps/web/src/components/CommandPalette.logic.test.tsindex dfa8b1951c1..f37f5405c59 100644--- a/apps/web/src/components/CommandPalette.logic.test.ts+++ b/apps/web/src/components/CommandPalette.logic.test.ts@@ -3,6 +3,7 @@ import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3toolsimport type { Thread } from "../types";import { makeThreadFixture } from "../test-fixtures";import {+ buildNestedSearchItems,buildThreadActionItems,buildLinkedThreadActionItems,filterPinnedBrowseEntries,@@ -168,6 +169,56 @@ describe("buildThreadActionItems", () => {]);});+ it("searches submenu options from the root and from a submenu with no match", () => {+ const action = (value: string, title: string) => ({+ kind: "action" as const,+ value,+ searchTerms: [title],+ title,+ icon: null,+ run: async () => undefined,+ });+ const projects = [action("new-thread-in:t3code", "t3code"), action("new-thread-in:web", "web")];+ const newThreadIn = {+ kind: "submenu" as const,+ value: "action:new-thread-in",+ searchTerms: ["new thread"],+ title: "New thread in...",+ icon: null,+ addonIcon: null,+ groups: [{ value: "projects", label: "Projects", items: projects }],+ };+ const addProject = action("action:add-project", "Add project");+ const rootGroups = [{ value: "actions", label: "Actions", items: [newThreadIn, addProject] }];+ const search = (query: string, isInSubmenu: boolean) =>+ filterCommandPaletteGroups({+ activeGroups: isInSubmenu ? newThreadIn.groups : rootGroups,+ query,+ isInSubmenu,+ allOptions: {+ rootGroups,+ nestedItems: buildNestedSearchItems([newThreadIn, addProject], query),+ },+ projectSearchItems: [],+ threadSearchItems: [+ ...buildThreadActionItems({+ threads: [makeThread({ title: "Thread about t3code" })],+ projectByKey: new Map(),+ icon: null,+ runThread: async () => undefined,+ }),+ ],+ }).map((group) => [group.label, group.items.map((item) => item.title)]);++ expect(search("new thread in t3code", false)[0]).toEqual([+ "Suggestions",+ ["New thread in t3code"],+ ]);+ expect(search("new thread", false).map(([label]) => label)).not.toContain("Suggestions");+ expect(search("t3", true)).toEqual([["Projects", ["t3code"]]]);+ expect(search("add project", true)).toEqual([["Actions", ["Add project"]]]);+ });+it("lists message matches last, once, without moving the title matches above them", () => {const threads = [makeThread({ id: ThreadId.make("title"), title: "Disable Convex schema validation" }),diff --git a/apps/web/src/components/CommandPalette.logic.ts b/apps/web/src/components/CommandPalette.logic.tsindex 16db18f86fe..7ac1410b2c8 100644--- a/apps/web/src/components/CommandPalette.logic.ts+++ b/apps/web/src/components/CommandPalette.logic.ts@@ -168,8 +168,6 @@ export interface CommandPaletteItem {readonly timestamp?: string;/** Thread rows rank by this, with use history, instead of by `searchTerms`. */readonly threadSearch?: ThreadSearchSubject;- /** Title ranges the current query matched, for highlighting. */- readonly titleRanges?: ReadonlyArray<SearchRange>;/** Shown in place of the description when the match is not in the title. */readonly matchHint?: SearchMatchHint;readonly icon: ReactNode;@@ -508,6 +506,11 @@ export function filterCommandPaletteGroups(input: {activeGroups: ReadonlyArray<CommandPaletteGroup>;query: string;isInSubmenu: boolean;+ /** Submenu options join the root search, and a submenu with no match falls back to it. */+ allOptions?: {+ readonly rootGroups: ReadonlyArray<CommandPaletteGroup>;+ readonly nestedItems: ReadonlyArray<CommandPaletteActionItem>;+ };projectSearchItems: ReadonlyArray<CommandPaletteActionItem>;settingsSearchItems?: ReadonlyArray<CommandPaletteActionItem>;threadSearchItems: ReadonlyArray<CommandPaletteActionItem>;@@ -515,6 +518,17 @@ export function filterCommandPaletteGroups(input: {threadMessageItems?: ReadonlyArray<CommandPaletteActionItem>;now?: number;}): CommandPaletteGroup[] {+ if (input.allOptions && input.isInSubmenu) {+ const { allOptions, ...submenuInput } = input;+ const scoped = filterCommandPaletteGroups(submenuInput);+ if (scoped.length > 0 || input.query.trim().length === 0) return scoped;+ return filterCommandPaletteGroups({+ ...input,+ activeGroups: allOptions.rootGroups,+ isInSubmenu: false,+ });+ }+const isActionsFilter = input.query.startsWith(">");const searchQuery = isActionsFilter ? input.query.slice(1) : input.query;const normalizedQuery = foldSearchQuery(searchQuery);@@ -538,6 +552,13 @@ export function filterCommandPaletteGroups(input: {// On equal match classes, groups keep this order: threads, what people search// for most, right after commands.if (searchesEverything) {+ if (input.allOptions && input.allOptions.nestedItems.length > 0) {+ searchableGroups.push({+ value: "nested-search",+ label: "Suggestions",+ items: input.allOptions.nestedItems,+ });+ }if (input.threadSearchItems.length > 0) {searchableGroups.push({value: "threads-search",@@ -572,7 +593,7 @@ export function filterCommandPaletteGroups(input: {const limit =group.value === "threads-search"? PALETTE_THREAD_LIMIT- : searchesEverything && threadsMatch+ : group.value === "nested-search" || (searchesEverything && threadsMatch)? PALETTE_SECONDARY_LIMIT: ranked.length;// Hints are built only for the rows shown.@@ -583,7 +604,7 @@ export function filterCommandPaletteGroups(input: {).slice(0, limit).map(({ item, match }) => {- if (match.ranges.length > 0) return { ...item, titleRanges: match.ranges };+ if (match.ranges.length > 0) return item;// Built only for the rows shown.const matchHint = match.explain?.();return matchHint ? { ...item, matchHint } : item;@@ -600,6 +621,35 @@ export function filterCommandPaletteGroups(input: {: [...groups, { value: "threads-messages", label: "In messages", items: messageItems }];}+/** Every option inside a submenu as one row, e.g. "New thread in t3code" or "Change theme: Dracula". */+export function buildNestedSearchItems(+ items: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>,+ query: string,+): CommandPaletteActionItem[] {+ const nameOf = (item: CommandPaletteItem) =>+ typeof item.title === "string" ? item.title : item.searchTitle;+ const topLevelNames = new Set(items.map(nameOf));+ const foldedQuery = foldSearchQuery(query);+ return items.flatMap((parent) => {+ if (parent.kind !== "submenu" || typeof parent.title !== "string") return [];+ const stem = parent.title.replace(/(\.\.\.|…)$/u, "");+ // A query that only names the submenu ("new thread in") wants the submenu row itself.+ if (foldSearchQuery(stem).startsWith(foldedQuery)) return [];+ const prefix = stem === parent.title ? `${stem}: ` : `${stem.trimEnd()} `;+ return parent.groups.flatMap((group) =>+ group.items.flatMap((child) => {+ const name = nameOf(child);+ if (child.kind !== "action" || name === undefined) return [];+ const title = `${prefix}${name}`;+ if (topLevelNames.has(title)) return [];+ const { searchTitle: _searchTitle, ...rest } = child;+ // Only the combined title: child keywords like "theme" would list every theme.+ return [{ ...rest, title, searchTerms: [title] }];+ }),+ );+ });+}+export function buildBrowseGroups(input: {browseEntries: ReadonlyArray<FilesystemBrowseEntry>;browseQuery: string;diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsxindex 456a2289c81..7951655a2da 100644--- a/apps/web/src/components/CommandPalette.tsx+++ b/apps/web/src/components/CommandPalette.tsx@@ -167,6 +167,7 @@ import {type CommandPaletteSubmenuItem,type CommandPaletteView,filterCommandPaletteGroups,+ buildNestedSearchItems,filterPinnedBrowseEntries,getCommandPaletteInputPlaceholder,getCommandPaletteMode,@@ -1681,6 +1682,14 @@ function OpenCommandPaletteDialog(props: {activeGroups,query: deferredQuery,isInSubmenu: currentView !== null,+ ...(deferredQuery.trim().length > 0+ ? {+ allOptions: {+ rootGroups,+ nestedItems: buildNestedSearchItems(actionItems, deferredQuery),+ },+ }+ : {}),projectSearchItems: projectSearchItems,settingsSearchItems,threadSearchItems:diff --git a/apps/web/src/components/CommandPaletteResults.tsx b/apps/web/src/components/CommandPaletteResults.tsxindex e951be2135e..c481d57d5fc 100644--- a/apps/web/src/components/CommandPaletteResults.tsx+++ b/apps/web/src/components/CommandPaletteResults.tsx@@ -22,11 +22,7 @@ import {CommandShortcut,} from "./ui/command";import { getVirtualizedScrollFadeClassName } from "./ui/scroll-area";-import {- HighlightedSearchText,- SearchMatchHintLine,- ThreadSearchMatchExcerpt,-} from "./ThreadSearchMatch";+import { SearchMatchHintLine, ThreadSearchMatchExcerpt } from "./ThreadSearchMatch";interface CommandPaletteResultsProps {emptyStateMessage?: string;@@ -159,16 +155,12 @@ export function CommandPaletteTitleIcon(props: { children: ReactNode }) {function CommandPaletteTitle({item,}: {- item: Pick<CommandPaletteActionItem | CommandPaletteSubmenuItem, "title" | "titleRanges">;+ item: Pick<CommandPaletteActionItem | CommandPaletteSubmenuItem, "title">;}) {const { title } = item;return (<span className="truncate" dir={typeof title === "string" ? textDirection(title) : undefined}>- {typeof title === "string" && item.titleRanges ? (- <HighlightedSearchText text={title} ranges={item.titleRanges} />- ) : (- title- )}+ {title}</span>);}diff --git a/apps/web/src/components/ThreadSearchMatch.tsx b/apps/web/src/components/ThreadSearchMatch.tsxindex 1af7f281090..5f99304f6b8 100644--- a/apps/web/src/components/ThreadSearchMatch.tsx+++ b/apps/web/src/components/ThreadSearchMatch.tsx@@ -6,7 +6,7 @@ import {} from "@t3tools/shared/paletteSearch";/** `text` with each range in semibold foreground. */-export function HighlightedSearchText(props: { text: string; ranges: ReadonlyArray<SearchRange> }) {+function HighlightedSearchText(props: { text: string; ranges: ReadonlyArray<SearchRange> }) {if (props.ranges.length === 0) return props.text;return splitSearchText(props.text, props.ranges).map((part) =>part.highlighted ? (