World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
Knowledge bases named owner/name are grouped under their owner in the base switcher, the chat scope chip, the token picker and My knowledge bases (#1250)
Szabo Bogdane3e5cdedcc3e
diff --git a/web/src/pages/Chat.tsx b/web/src/pages/Chat.tsxindex 9e74be29..5abe02f1 100644--- a/web/src/pages/Chat.tsx+++ b/web/src/pages/Chat.tsx@@ -11,7 +11,6 @@ import remend from "remend";import {ArrowUp,BookOpen,- Check,ChevronDown,ChevronRight,Database,@@ -75,6 +74,7 @@ import {import { NodCard } from "./PendingFacts";import { stepDetail, stepLabel } from "../steps";import { NextStep, nextStep, useReadiness } from "./NextStep";+import { KbMenuList } from "./KbMenuList";import { DRAFT_KEY, fetchMe, lastKey } from "../authSession";/* `Turn` 定义在 liveAnswer 里:进行中的那一次也是一串 Turn,@@ -220,7 +220,10 @@ export function Chat() {useEffect(() => {if (!scopeOpen) return;const onDoc = (e: MouseEvent) => {- if (!scopeRef.current?.contains(e.target as Node)) setScopeOpen(false);+ const target = e.target as Element;+ // 组的子菜单挂在 body 上,不在 scopeRef 里——点它不算点外面(KbMenuList)+ if (!scopeRef.current?.contains(target) && !target.closest?.("[data-kb-submenu]"))+ setScopeOpen(false);};const onKey = (e: KeyboardEvent) => {if (e.key === "Escape") setScopeOpen(false);@@ -606,26 +609,14 @@ export function Chat() {{S.ask.scopeLabel}</div><div className="u-scroll max-h-60 overflow-y-auto">- {kbs.map((k) => (- <Row- key={k.id}- density="menu"- active={k.id === kb?.id}- /* 对勾走 `trailing` 槽。**塞进 children 的 svg 会掉到第二行**:- Row 把 children 整个包进一个 `flex-1 truncate` 的 span,- 那个 span 不是 flex 容器,preflight 又把 svg 设成块级,- 于是勾自己占一行、整行跟着变高(顶栏的库切换器早就这么写的) */- trailing={- k.id === kb?.id ? <Check size={12} className="text-ink-2" /> : undefined- }- onClick={() => {- setScopeOpen(false);- if (k.id !== kb?.id) { claimView(null); setKb(k.id); }- }}- >- <span className="truncate">{k.name}</span>- </Row>- ))}+ <KbMenuList+ kbs={kbs}+ currentId={kb?.id}+ onPick={(id) => {+ setScopeOpen(false);+ if (id !== kb?.id) { claimView(null); setKb(id); }+ }}+ /></div></div>)}diff --git a/web/src/pages/KbMenuList.tsx b/web/src/pages/KbMenuList.tsxnew file mode 100644index 00000000..12e017d6--- /dev/null+++ b/web/src/pages/KbMenuList.tsx@@ -0,0 +1,263 @@+/* 库菜单的那一列:顶栏切换器与提问框的作用域芯片共用。名字带 `/` 的库收进+ 一个组(`re-cinq ›`),指针停上去或点一下,右边弹出组里的库(#1249)。++ 子菜单走 Popover 的 Portal,挂在 body 上——所以它**不在**宿主菜单的 DOM 里。+ 宿主若是自己判「点在外面就关」,要放过带 `data-kb-submenu` 的元素,否则+ mousedown 先把整个菜单关掉,点击落空。++ 键盘:组那一行上 Enter / 空格 / → 打开并把焦点送进第一项,↑↓ 在子菜单里走,+ Esc / ← 关上并把焦点还给那一行(kbMenuKeys)。没用 DropdownMenuSub:它只能+ 长在 DropdownMenu 里,而两个宿主一个是带查找框的 Popover(菜单的 typeahead+ 与焦点管理会跟查找框抢键),一个是手写的 div。 */+import { useEffect, useRef, useState, useSyncExternalStore, type KeyboardEvent } from "react";+import { Check, ChevronRight } from "lucide-react";+import type { Kb } from "../api";+import { Row, cn } from "../ui";+import { Popover, PopoverAnchor, PopoverContent } from "@/components/ui/popover";+import { kbGroups, type KbGroupItem } from "./kbGroups";+import { groupRowKey, submenuKey } from "./kbMenuKeys";++const ROW = "gap-3 px-4 py-2 text-body";+/** 指针从组那一行移到子菜单要经过一道缝,关得太快就够不着 */+const CLOSE_DELAY_MS = 150;++const NARROW = "(max-width: 639px)";++/** 屏幕窄到放不下侧边子菜单(手机竖屏) */+function useNarrow() {+ return useSyncExternalStore(+ (changed) => {+ const query = window.matchMedia(NARROW);+ query.addEventListener("change", changed);+ return () => query.removeEventListener("change", changed);+ },+ () => window.matchMedia(NARROW).matches,+ );+}++export function KbMenuList({+ kbs,+ currentId,+ onPick,+ grouped = true,+}: {+ kbs: Kb[];+ currentId: string | undefined;+ onPick: (id: string) => void;+ /** 搜索时传 false:按全名平铺,`re-cinq/lo` 照样搜得到 */+ grouped?: boolean;+}) {+ if (!grouped)+ return kbs.map((k) => (+ <KbRow key={k.id} label={k.name} current={k.id === currentId} onClick={() => onPick(k.id)} />+ ));+ return kbGroups(kbs).map((entry) =>+ entry.kind === "kb" ? (+ <KbRow+ key={entry.kb.id}+ label={entry.kb.name}+ current={entry.kb.id === currentId}+ onClick={() => onPick(entry.kb.id)}+ />+ ) : (+ <KbGroupRow+ key={`group-${entry.name}`}+ name={entry.name}+ items={entry.items}+ currentId={currentId}+ onPick={onPick}+ />+ ),+ );+}++function KbRow({+ label,+ current,+ onClick,+ indent,+}: {+ label: string;+ current: boolean;+ onClick: () => void;+ indent?: number;+}) {+ return (+ /* 对勾走 `trailing` 槽。**塞进 children 的 svg 会掉到第二行**:+ Row 把 children 整个包进一个 `flex-1 truncate` 的 span,+ 那个 span 不是 flex 容器,preflight 又把 svg 设成块级,+ 于是勾自己占一行、整行跟着变高 */+ <Row+ density="menu"+ className={ROW}+ active={current}+ indent={indent}+ trailing={current ? <Check size={13} className="text-ink-2" /> : undefined}+ onClick={onClick}+ >+ <span className="truncate">{label}</span>+ </Row>+ );+}++function KbGroupRow({+ name,+ items,+ currentId,+ onPick,+}: {+ name: string;+ items: KbGroupItem[];+ currentId: string | undefined;+ onPick: (id: string) => void;+}) {+ const [open, setOpen] = useState(false);+ const narrow = useNarrow();+ const closing = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);+ const anchor = useRef<HTMLDivElement>(null);+ const submenu = useRef<HTMLDivElement>(null);+ /** 键盘打开的才把焦点送进子菜单;指针停上去的不抢(顶栏的查找框还在打字) */+ const focusInside = useRef(false);+ const show = (withFocus: boolean) => {+ clearTimeout(closing.current);+ focusInside.current = withFocus;+ setOpen(true);+ };+ const leave = () => {+ clearTimeout(closing.current);+ closing.current = setTimeout(() => setOpen(false), CLOSE_DELAY_MS);+ };+ /* 只有鼠标按悬停开合。触屏的一点会先模拟一次 enter 再来 click——+ 若 click 是开关,就刚开就关 */+ const byMouse = (run: () => void) => (e: { pointerType: string }) => {+ if (e.pointerType === "mouse") run();+ };+ const onRowKey = (e: KeyboardEvent) => {+ if (groupRowKey(e.key) !== "open") return;+ e.preventDefault();+ // 指针已经把它打开了:onOpenAutoFocus 不会再来,焦点自己送进去+ if (open) submenu.current?.querySelector("button")?.focus();+ else show(true);+ };+ useEffect(() => {+ if (!narrow || !open || !focusInside.current) return;+ submenu.current?.querySelector("button")?.focus();+ focusInside.current = false;+ }, [narrow, open]);+ const onSubmenuKey = (e: KeyboardEvent<HTMLDivElement>) => {+ const action = submenuKey(e.key);+ if (action === undefined) return;+ e.preventDefault();+ // 别让提问框那个宿主的 Esc(挂在 document 上)把整个菜单也关了+ e.stopPropagation();+ if (action === "close") {+ setOpen(false);+ anchor.current?.querySelector("button")?.focus();+ return;+ }+ const buttons = [...e.currentTarget.querySelectorAll("button")];+ const at = buttons.indexOf(document.activeElement as HTMLButtonElement);+ buttons[(at + action + buttons.length) % buttons.length]?.focus();+ };+ const holdsCurrent = items.some((i) => i.kb.id === currentId);+ const trailing = (+ <span className="flex items-center gap-2">+ {holdsCurrent && <Check size={13} className="text-ink-2" />}+ <ChevronRight+ size={13}+ className={cn("u-turn text-ink-2", narrow && open && "rotate-90")}+ />+ </span>+ );+ /* 窄屏(手机)上菜单几乎占满宽度,右边左边都放不下子菜单——Radix 只好把它+ 推到屏幕外。这里改成就地展开:组下面缩进一档列出它的库 */+ if (narrow)+ return (+ <>+ <div ref={anchor}>+ <Row+ density="menu"+ className={ROW}+ aria-expanded={open}+ trailing={trailing}+ onClick={() => setOpen((v) => !v)}+ onKeyDown={onRowKey}+ >+ <span className="truncate">{name}</span>+ </Row>+ </div>+ {open &&+ <div ref={submenu} onKeyDown={onSubmenuKey}>+ {items.map((item) => (+ <KbRow+ key={item.kb.id}+ label={item.label}+ indent={1}+ current={item.kb.id === currentId}+ onClick={() => {+ setOpen(false);+ onPick(item.kb.id);+ }}+ />+ ))}+ </div>+ }+ </>+ );+ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverAnchor asChild>+ <div ref={anchor} onPointerEnter={byMouse(() => show(false))} onPointerLeave={byMouse(leave)}>+ <Row+ density="menu"+ className={ROW}+ aria-haspopup="menu"+ aria-expanded={open}+ trailing={trailing}+ onClick={() => show(false)}+ onKeyDown={onRowKey}+ >+ <span className="truncate">{name}</span>+ </Row>+ </div>+ </PopoverAnchor>+ <PopoverContent+ data-kb-submenu+ side="right"+ align="start"+ sideOffset={2}+ collisionPadding={8}+ onOpenAutoFocus={(e) => {+ if (!focusInside.current) e.preventDefault();+ }}+ // 焦点在子菜单里时 Esc 交给 onSubmenuKey(它还要把焦点还给那一行);+ // 焦点还在搜索框里时照常关掉+ onEscapeKeyDown={(e) => {+ if (submenu.current?.contains(document.activeElement)) e.preventDefault();+ }}+ // 按在组那一行上不算外面:否则按下就关、松开的 click 又开,闪一下+ onInteractOutside={(e) => {+ if (anchor.current?.contains(e.target as Node)) e.preventDefault();+ }}+ onKeyDown={onSubmenuKey}+ onPointerEnter={byMouse(() => show(false))}+ onPointerLeave={byMouse(leave)}+ className="w-max min-w-48 max-w-80 overflow-hidden p-0"+ >+ <div ref={submenu} className="u-scroll max-h-80 overflow-y-auto">+ {items.map((item) => (+ <KbRow+ key={item.kb.id}+ label={item.label}+ current={item.kb.id === currentId}+ onClick={() => {+ setOpen(false);+ onPick(item.kb.id);+ }}+ />+ ))}+ </div>+ </PopoverContent>+ </Popover>+ );+}diff --git a/web/src/pages/KbSwitcher.tsx b/web/src/pages/KbSwitcher.tsxindex 6c0ce40d..9ce534f6 100644--- a/web/src/pages/KbSwitcher.tsx+++ b/web/src/pages/KbSwitcher.tsx@@ -9,7 +9,7 @@import { useState } from "react";import { useQuery } from "@tanstack/react-query";import { useNavigate } from "@tanstack/react-router";-import { Check, ChevronDown, Layers, Plus } from "lucide-react";+import { ChevronDown, Layers, Plus } from "lucide-react";import { api, type Kb } from "../api";import { S } from "../i18n";import { Button, Input, Row } from "../ui";@@ -18,6 +18,7 @@ import {PopoverContent,PopoverTrigger,} from "@/components/ui/popover";+import { KbMenuList } from "./KbMenuList";import { fetchMe } from "../authSession";export function KbSwitcher({@@ -92,22 +93,15 @@ export function KbSwitcher({/></div><div className="u-scroll max-h-80 overflow-y-auto">- {shown.map((k) => (- <Row- key={k.id}- density="menu"- className="gap-3 px-4 py-2 text-body"- trailing={- k.id === kb?.id ? <Check size={13} className="text-ink-2" /> : undefined- }- onClick={() => {- dismiss();- if (k.id !== kb?.id) onChange(k.id);- }}- >- <span className="truncate">{k.name}</span>- </Row>- ))}+ <KbMenuList+ kbs={shown}+ currentId={kb?.id}+ grouped={!needle}+ onPick={(id) => {+ dismiss();+ if (id !== kb?.id) onChange(id);+ }}+ />{shown.length === 0 && (<p className="px-4 py-3 text-body text-ink-2">{S.nav.noKbMatch}</p>)}diff --git a/web/src/pages/MyKbs.tsx b/web/src/pages/MyKbs.tsxindex 7e57bd7c..0eb32196 100644--- a/web/src/pages/MyKbs.tsx+++ b/web/src/pages/MyKbs.tsx@@ -9,6 +9,7 @@ import { Lock, Plus, Search } from "lucide-react";import { api, type MyKb } from "../api";import { S } from "../i18n";import { useKb } from "../kb";+import { kbGroups } from "./kbGroups";import {Button,Checkbox,@@ -75,6 +76,18 @@ export function MyKbs() {r.kb.name.toLowerCase().includes(q) ||(r.kb.description ?? "").toLowerCase().includes(q),);+ // 不筛选时按 `owner/` 归组:组名占一行,下面是短名(#1249);筛选时按全名平铺+ const rowById = new Map(rows.map((r) => [r.kb.id, r]));+ const lines: ({ heading: string } | { row: (typeof rows)[number]; label: string })[] = q+ ? rows.map((row) => ({ row, label: row.kb.name }))+ : kbGroups(rows.map((r) => r.kb)).flatMap((entry) =>+ entry.kind === "kb"+ ? [{ row: rowById.get(entry.kb.id)!, label: entry.kb.name }]+ : [+ { heading: entry.name },+ ...entry.items.map((item) => ({ row: rowById.get(item.kb.id)!, label: item.label })),+ ],+ );const openKb = (id: string) => {setKb(id);navigate({ to: "/kb/$kbId/graph", params: { kbId: id } });@@ -128,15 +141,28 @@ export function MyKbs() {</Tr></THead><TBody>- {rows.map((row) => {+ {lines.map((line) => {+ if ("heading" in line)+ return (+ <Tr key={`group-${line.heading}`}>+ <th+ scope="rowgroup"+ colSpan={6}+ className="px-3 pt-4 pb-2 text-left align-top text-small font-medium text-ink-2"+ >+ {line.heading}+ </th>+ </Tr>+ );+ const { row, label } = line;const canManage =row.my_role === "admin" || row.my_role === "owner";return (<Tr key={row.kb.id}><Td><div className="flex items-center gap-2">- <span className="truncate text-body text-ink">- {row.kb.name}+ <span className="truncate text-body text-ink" title={row.kb.name}>+ {label}</span>{/* 这两个是**库自己的性质**,不是一列数据:缺省库只有一个,受限的也少,单开一列会空掉大半,所以贴在名字旁边 */}diff --git a/web/src/pages/Tokens.tsx b/web/src/pages/Tokens.tsxindex 72eec852..e0d05e16 100644--- a/web/src/pages/Tokens.tsx+++ b/web/src/pages/Tokens.tsx@@ -32,6 +32,7 @@ import {} from "../ui";import { toast } from "../toast";import { copyAndSay } from "../clipboard";+import { kbOptions } from "./kbGroups";const EXPIRY_CHOICES = [30, 90, 365, 0] as const;@@ -373,7 +374,7 @@ export function Tokens() {<MultiSearchSelectclassName="w-full"values={Array.from(picked)}- options={kbs.map((k) => ({ value: k.id, label: k.name }))}+ options={kbOptions(kbs)}placeholder={S.account.pickBases}emptyHint={S.account.allBases}onToggle={(id) => {diff --git a/web/src/pages/kbGroups.test.ts b/web/src/pages/kbGroups.test.tsnew file mode 100644index 00000000..aaf322e8--- /dev/null+++ b/web/src/pages/kbGroups.test.ts@@ -0,0 +1,66 @@+import { expect, it } from "vitest";+import type { Kb } from "../api";+import { kbGroups, kbOptions } from "./kbGroups";++const kb = (name: string) => ({ id: name, name }) as Kb;++it("keeps bases without a slash as plain entries", () => {+ const mercedes = kb("mercedes");+ expect(kbGroups([mercedes])).toEqual([{ kind: "kb", kb: mercedes }]);+});++it("groups bases sharing the text before the slash under that name", () => {+ const [lore, floor] = [kb("re-cinq/lore"), kb("re-cinq/floor")];+ expect(kbGroups([lore, floor])).toEqual([+ {+ kind: "group",+ name: "re-cinq",+ items: [+ { kb: lore, label: "lore" },+ { kb: floor, label: "floor" },+ ],+ },+ ]);+});++it("places a group where its first member was and splits only on the first slash", () => {+ const [a, xy, b, xyz] = [kb("alpha"), kb("x/y"), kb("beta"), kb("x/y/z")];+ expect(kbGroups([a, xy, b, xyz])).toEqual([+ { kind: "kb", kb: a },+ { kind: "group", name: "x", items: [{ kb: xy, label: "y" }, { kb: xyz, label: "y/z" }] },+ { kind: "kb", kb: b },+ ]);+});++it("keeps CI/CD a plain row when no other base shares the CI prefix", () => {+ const [cicd, mercedes] = [kb("CI/CD"), kb("mercedes")];+ expect(kbGroups([cicd, mercedes])).toEqual([+ { kind: "kb", kb: cicd },+ { kind: "kb", kb: mercedes },+ ]);+});++it("keeps /foo, foo/ and / plain rows because one side of the slash is empty", () => {+ const names = ["/foo", "/bar", "foo/", "foo/ ", "/", " /x", " /y"].map(kb);+ expect(kbGroups(names)).toEqual(names.map((k) => ({ kind: "kb", kb: k })));+});++it("puts re-cinq /lore and re-cinq/floor in one re-cinq group with trimmed labels", () => {+ const [lore, floor] = [kb("re-cinq /lore"), kb("re-cinq/ floor")];+ expect(kbGroups([lore, floor])).toEqual([+ { kind: "group", name: "re-cinq", items: [{ kb: lore, label: "lore" }, { kb: floor, label: "floor" }] },+ ]);+});++it("gives a lone A/B tests base a plain option with its full name", () => {+ expect(kbOptions([kb("A/B tests")])).toEqual([{ value: "A/B tests", label: "A/B tests" }]);+});++it("turns bases into select options with the group's members side by side", () => {+ const [lore, mercedes, floor] = [kb("re-cinq/lore"), kb("mercedes"), kb("re-cinq/floor")];+ expect(kbOptions([lore, mercedes, floor])).toEqual([+ { value: "re-cinq/lore", label: "re-cinq/lore", group: "re-cinq", short: "lore" },+ { value: "re-cinq/floor", label: "re-cinq/floor", group: "re-cinq", short: "floor" },+ { value: "mercedes", label: "mercedes" },+ ]);+});diff --git a/web/src/pages/kbGroups.ts b/web/src/pages/kbGroups.tsnew file mode 100644index 00000000..d33790c1--- /dev/null+++ b/web/src/pages/kbGroups.ts@@ -0,0 +1,51 @@+import type { Kb } from "../api";++export type KbGroupItem = { kb: Kb; label: string };+export type KbEntry =+ | { kind: "kb"; kb: Kb }+ | { kind: "group"; name: string; items: KbGroupItem[] };++/** 名字带 `/` 的库按第一个 `/` 之前的部分归组(`re-cinq/lore` → 组 `re-cinq`、+ * 标签 `lore`)。两边去掉空白后都得有字,且同组至少两个库才成组——`/foo`、+ * `foo/`、只此一家的 `CI/CD` 照旧是一行全名。组落在它第一个成员原来的位置,+ * 其余库的顺序不动 */+export function kbGroups(kbs: Kb[]): KbEntry[] {+ const groups = new Map<string, KbGroupItem[]>();+ const owners = kbs.map((kb) => {+ const split = ownerAndLabel(kb.name);+ if (!split) return undefined;+ groups.set(split.owner, [...(groups.get(split.owner) ?? []), { kb, label: split.label }]);+ return split.owner;+ });+ const placed = new Set<string>();+ return kbs.flatMap((kb, index): KbEntry[] => {+ const owner = owners[index];+ const items = owner === undefined ? undefined : groups.get(owner)!;+ if (!items || items.length < 2) return [{ kind: "kb", kb }];+ if (placed.has(owner!)) return [];+ placed.add(owner!);+ return [{ kind: "group", name: owner!, items }];+ });+}++function ownerAndLabel(name: string) {+ const slash = name.indexOf("/");+ const owner = name.slice(0, slash).trim();+ const label = name.slice(slash + 1).trim();+ return slash >= 0 && owner && label ? { owner, label } : undefined;+}++/** 给多选下拉用的选项:同组的挨在一起,`label` 留全名(搜索与已选的芯片都用它),+ * `short` 是组名下面那一行显示的名字 */+export function kbOptions(kbs: Kb[]) {+ return kbGroups(kbs).flatMap((entry) =>+ entry.kind === "kb"+ ? [{ value: entry.kb.id, label: entry.kb.name }]+ : entry.items.map((item) => ({+ value: item.kb.id,+ label: item.kb.name,+ group: entry.name,+ short: item.label,+ })),+ );+}diff --git a/web/src/pages/kbMenuKeys.test.ts b/web/src/pages/kbMenuKeys.test.tsnew file mode 100644index 00000000..39138296--- /dev/null+++ b/web/src/pages/kbMenuKeys.test.ts@@ -0,0 +1,20 @@+import { expect, it } from "vitest";+import { groupRowKey, submenuKey } from "./kbMenuKeys";++it.each(["Enter", " ", "ArrowRight"])("opens the submenu on the group row's %j key", (key) => {+ expect(groupRowKey(key)).toBe("open");+});++it.each(["ArrowLeft", "ArrowDown", "Tab", "a"])("leaves the group row's %j key alone", (key) => {+ expect(groupRowKey(key)).toBeUndefined();+});++it.each([+ ["Escape", "close"],+ ["ArrowLeft", "close"],+ ["ArrowDown", 1],+ ["ArrowUp", -1],+ ["Enter", undefined],+] as const)("maps %j inside the submenu to %j", (key, action) => {+ expect(submenuKey(key)).toBe(action);+});diff --git a/web/src/pages/kbMenuKeys.ts b/web/src/pages/kbMenuKeys.tsnew file mode 100644index 00000000..e0ed3e9b--- /dev/null+++ b/web/src/pages/kbMenuKeys.ts@@ -0,0 +1,17 @@+/* 组那一行与它的子菜单认哪些键(KbMenuList)。与菜单的惯例一致:+ Enter / 空格 / → 打开并进到第一项;Esc / ← 退回那一行;↑↓ 在子菜单里走 */+const OPENS = new Set(["Enter", " ", "ArrowRight"]);+const IN_SUBMENU: Record<string, "close" | 1 | -1> = {+ Escape: "close",+ ArrowLeft: "close",+ ArrowDown: 1,+ ArrowUp: -1,+};++export function groupRowKey(key: string): "open" | undefined {+ return OPENS.has(key) ? "open" : undefined;+}++export function submenuKey(key: string): "close" | 1 | -1 | undefined {+ return IN_SUBMENU[key];+}diff --git a/web/src/ui/index.tsx b/web/src/ui/index.tsxindex 7055d24b..f7f3a011 100644--- a/web/src/ui/index.tsx+++ b/web/src/ui/index.tsx@@ -389,6 +389,9 @@ export interface SearchSelectOption {hint?: string;/** 树形缩进的层级(父类选择器用它) */indent?: number;+ /** 同组的选项不在搜索时排在一个组名下面,显示 `short`;搜索时照旧显示 `label` */+ group?: string;+ short?: string;}export function SearchSelect({@@ -584,7 +587,22 @@ export function MultiSearchSelect({</div>{open && (<div className="u-menu-glass u-pop-in u-pop-in-tl absolute z-50 mt-1 w-full rounded-overlay u-lift-strong overflow-hidden">- {visible.map((o, i) => (+ {(q+ ? visible.map((option, index) => ({ kind: "option" as const, option, index }))+ : withGroupHeadings(visible)+ ).map((row) => {+ if (row.kind === "heading")+ return (+ <div+ key={`heading-${row.name}`}+ className="px-2.5 pt-2 pb-0.5 text-fine font-medium text-ink-2"+ >+ {row.name}+ </div>+ );+ const { option: o, index: i } = row;+ const indent = q ? 0 : (o.indent ?? 0) + (o.group ? 1 : 0);+ return (<buttonkey={o.value}type="button"@@ -598,11 +616,11 @@ export function MultiSearchSelect({: "text-ink-2",)}>- {!q && !!o.indent && (- <span className="shrink-0" style={{ width: o.indent * 14 }} />+ {indent > 0 && (+ <span className="shrink-0" style={{ width: indent * 14 }} />)}<span className="min-w-0 flex-1 truncate">- {o.label}+ {!q && o.short ? o.short : o.label}{o.hint && (<span className="ml-2 text-ink-2">{o.hint}</span>)}@@ -611,7 +629,8 @@ export function MultiSearchSelect({<Check size={12} className="shrink-0 text-ink-2" />)}</button>- ))}+ );+ })}{visible.length === 0 && (<p className="px-2.5 py-1 text-small text-ink-2">{S.ui.noMatches}@@ -629,6 +648,7 @@ export function MultiSearchSelect({}import { ENTITY_PALETTE } from "../palette";+import { withGroupHeadings } from "./withGroupHeadings";export { ENTITY_PALETTE, colorForKey } from "../palette";export function ColorPicker({diff --git a/web/src/ui/withGroupHeadings.test.ts b/web/src/ui/withGroupHeadings.test.tsnew file mode 100644index 00000000..05ab7df0--- /dev/null+++ b/web/src/ui/withGroupHeadings.test.ts@@ -0,0 +1,15 @@+import { expect, it } from "vitest";+import { withGroupHeadings } from "./withGroupHeadings";++const lore = { value: "1", label: "re-cinq/lore", group: "re-cinq", short: "lore" };+const floor = { value: "2", label: "re-cinq/floor", group: "re-cinq", short: "floor" };+const mercedes = { value: "3", label: "mercedes" };++it("puts one heading before each run of a group and none before ungrouped options", () => {+ expect(withGroupHeadings([mercedes, lore, floor])).toEqual([+ { kind: "option", option: mercedes, index: 0 },+ { kind: "heading", name: "re-cinq" },+ { kind: "option", option: lore, index: 1 },+ { kind: "option", option: floor, index: 2 },+ ]);+});diff --git a/web/src/ui/withGroupHeadings.ts b/web/src/ui/withGroupHeadings.tsnew file mode 100644index 00000000..c93f5c94--- /dev/null+++ b/web/src/ui/withGroupHeadings.ts@@ -0,0 +1,15 @@+type Grouped = { value: string; group?: string };++export type HeadedRow<T> =+ | { kind: "heading"; name: string }+ | { kind: "option"; option: T; index: number };++/** 选项列表里,组变了的地方插一行组名。`index` 是选项在原列表里的位置——+ * 键盘的上下键按它走,组名行不占位置,选不中 */+export function withGroupHeadings<T extends Grouped>(options: T[]): HeadedRow<T>[] {+ return options.flatMap((option, index) => {+ const opensGroup = !!option.group && option.group !== options[index - 1]?.group;+ const row: HeadedRow<T> = { kind: "option", option, index };+ return opensGroup ? [{ kind: "heading", name: option.group! }, row] : [row];+ });+}