fix(search): keep recent find and replace values readable

Цей коміт міститься в:
l0ng-ai committed 2026-11-23 00:30:46 +08:00
1 джерело 81dd5f0dd2
коміт b864646c2d
15 files changed
+146 -54

No files matched your search

+78
Переглянути файл
@@ -0,0 +1,78 @@
import type { Locator, Page } from "@playwright/test";
import { expect, openFromTree, test } from "./fixtures";
const latest = "regional-order-reconciliation-endpoints-for-sandbox-environments/".repeat(3) + "checkout\nText to find";
async function seedHistory(page: Page, kind: "find" | "replace") {
await page.evaluate(
async ({ kind, latest }) => {
const searchModule = "/src/platform/search.ts";
const { rememberSearch } = await import(/* @vite-ignore */ searchModule);
for (let i = 0; i < 19; i++) rememberSearch(kind, `Order rule ${i}`);
rememberSearch(kind, latest);
},
{ kind, latest },
);
}
async function openHistory(field: Locator, menu: Locator) {
await field.focus();
await field.press("Alt+ArrowDown");
await expect(menu).toBeVisible();
}
test("editor find history grows with the field and restores the original query", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1040, height: 700 });
await openFromTree(page, "build.gradle.kts");
await page.keyboard.press("Meta+f");
await seedHistory(page, "find");
const field = page.getByRole("textbox", { name: "Find", exact: true });
const menu = page.getByRole("menu", { name: "Recent Searches", exact: true });
await openHistory(field, menu);
const newest = menu.getByRole("menuitem").first();
await expect(newest).toHaveText(latest.replace("\n", " ⏎ "));
await expect(newest).toHaveAttribute("title", latest);
await expect.poll(async () => (await menu.boundingBox())!.width).toBeGreaterThan(420);
await newest.press("Enter");
await expect(menu).toBeHidden();
await expect(field).toHaveValue(latest);
await expect(field).toBeFocused();
});
test("project replacement history stays inside a narrow window and keeps its heading visible", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 440, height: 520 });
await page.keyboard.press("Meta+Shift+r");
await seedHistory(page, "replace");
const field = page.getByRole("textbox", { name: "Replace with" });
const menu = page.getByRole("menu", { name: "Recent Replacements" });
await openHistory(field, menu);
const popup = menu.locator("..");
const heading = popup.getByText("Recent Replacements", { exact: true });
const newest = menu.getByRole("menuitem").first();
await expect(newest).toHaveText(latest.replace("\n", " ⏎ "));
await expect
.poll(async () => {
const { x, width } = (await popup.boundingBox())!;
return x >= 0 && x + width <= 440;
})
.toBe(true);
await newest.press("End");
const oldest = menu.getByRole("menuitem").last();
await expect(oldest).toBeFocused();
await expect.poll(async () => popup.evaluate((node) => node.scrollTop)).toBeGreaterThan(0);
await expect(heading).toBeInViewport();
await oldest.press("Home");
await expect(newest).toBeFocused();
await newest.press("Enter");
await expect(menu).toBeHidden();
await expect(field).toHaveValue(latest);
await expect(field).toBeFocused();
});
+5 -19
Переглянути файл
@@ -8,12 +8,13 @@
* Exclude with Preserve Case, Esc closes. `FindPanel` is the bar itself, for
* any CodeMirror view (the diff viewer's sides); `FindBar` is it on an editor pane.
*/
import { SearchHistoryMenu } from "@/ui/SearchHistoryMenu";
import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent } from "react";
import { create } from "zustand";
import clsx from "clsx";
import type { EditorView } from "@codemirror/view";
import { Button, IconButton, Menu, SearchField, T, type MenuItem } from "@/ui";
import { SEARCH_CONTEXTS, rememberSearch, searchHistory } from "@/platform/search";
import { SEARCH_CONTEXTS, rememberSearch } from "@/platform/search";
import { editorController, useFindBars, useTabs } from "../controller";
import {
countMatches,
@@ -557,19 +558,6 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
? "0 results"
: `${count.current || "?"}/${count.total}${count.capped ? "+" : ""}`;
const historyItems = (kind: "find" | "replace"): MenuItem[] => {
const h = searchHistory(kind);
return h.length
? [
{ kind: "header", label: kind === "find" ? "Recent Searches" : "Recent Replacements" },
...h.map((q) => ({
label: q.replace(/\n/g, "⏎"),
verbatim: true,
run: () => setOpts(kind === "find" ? { search: q } : { replace: q }),
})),
]
: [{ label: kind === "find" ? "No recent searches" : "No recent replacements", disabled: true }];
};
const filterItems: MenuItem[] = [
{
label: "Search In Selection",
@@ -765,12 +753,10 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
</div>
</>
)}
<Menu
open={historyMenu !== null}
<SearchHistoryMenu
kind={historyMenu}
anchor={historyMenu === "replace" ? replaceBoxRef : findBoxRef}
items={historyMenu ? historyItems(historyMenu) : []}
placement="bottom-start"
aria-label="Recent searches"
onSelect={(value) => setOpts(historyMenu === "replace" ? { replace: value } : { search: value })}
onClose={() => setHistoryMenu(null)}
/>
<Menu
+4 -19
Переглянути файл
@@ -1,3 +1,4 @@
import { SearchHistoryMenu } from "@/ui/SearchHistoryMenu";
import {
useEffect,
useId,
@@ -74,7 +75,6 @@ import {
customScopeName,
customScopeValue,
describeQuery,
findHistory,
hideFindPopup,
recentMasks,
rememberFindString,
@@ -563,19 +563,6 @@ function FindInFilesDialog() {
checked: m === s.mask ? true : undefined,
run: () => set({ mask: m, maskEnabled: true }),
}));
const historyItems = (kind: "find" | "replace"): MenuItem[] => {
const h = findHistory(kind);
return h.length
? [
{ kind: "header", label: kind === "find" ? "Recent Searches" : "Recent Replacements" },
...h.map((q) => ({
label: q,
verbatim: true,
run: () => set(kind === "find" ? { pattern: q } : { replacement: q }),
})),
]
: [{ label: kind === "find" ? "No recent searches" : "No recent replacements", disabled: true }];
};
const contextItems: MenuItem[] = SEARCH_CONTEXTS.map((c) => ({
label: c.label,
checked: c.value === s.context ? true : undefined,
@@ -974,12 +961,10 @@ function FindInFilesDialog() {
placement="bottom-end"
onClose={() => setMaskMenu(false)}
/>
<Menu
open={historyMenu !== null}
<SearchHistoryMenu
kind={historyMenu}
anchor={historyMenu === "replace" ? replaceBoxRef : patternBoxRef}
items={historyMenu ? historyItems(historyMenu) : []}
placement="bottom-start"
aria-label="Recent searches"
onSelect={(value) => set(historyMenu === "replace" ? { replacement: value } : { pattern: value })}
onClose={() => setHistoryMenu(null)}
/>
<Menu
-1
Переглянути файл
@@ -2731,7 +2731,6 @@
"Replace All ({key})": "Reemplazar todo ({key})",
"Include ({key})": "Incluir ({key})",
"Exclude ({key})": "Excluir ({key})",
"Recent searches": "Búsquedas recientes",
"New Line": "Nueva línea",
"New Line in Search Field": "Nueva línea en el campo de búsqueda",
"Quick Type Definition": "Definición rápida de tipo",
-1
Переглянути файл
@@ -2632,7 +2632,6 @@
"Replace All ({key})": "Tout remplacer ({key})",
"Include ({key})": "Inclure ({key})",
"Exclude ({key})": "Exclure ({key})",
"Recent searches": "Recherches récentes",
"New Line": "Nouvelle ligne",
"New Line in Search Field": "Nouvelle ligne dans le champ de recherche",
"Quick Type Definition": "Définition rapide du type",
-1
Переглянути файл
@@ -2781,7 +2781,6 @@
"Replace All ({key})": "모두 바꾸기({key})",
"Include ({key})": "포함({key})",
"Exclude ({key})": "제외({key})",
"Recent searches": "최근 검색",
"New Line": "새 줄",
"New Line in Search Field": "검색 필드에 새 줄",
"Quick Type Definition": "빠른 타입 정의",
-1
Переглянути файл
@@ -2703,7 +2703,6 @@
"Search Scope": "Zakres wyszukiwania",
"Filter Search Results": "Filtruj wyniki wyszukiwania",
"Filter search results": "Filtruj wyniki wyszukiwania",
"Recent searches": "Niedawne wyszukiwania",
"New Line": "Nowy wiersz",
"New Line in Search Field": "Nowy wiersz w polu wyszukiwania",
"Quick Type Definition": "Szybka definicja typu",
-1
Переглянути файл
@@ -2704,7 +2704,6 @@
"Search Scope": "Escopo de pesquisa",
"Filter Search Results": "Filtrar resultados da pesquisa",
"Filter search results": "Filtrar resultados da pesquisa",
"Recent searches": "Pesquisas recentes",
"New Line": "Nova linha",
"New Line in Search Field": "Nova linha no campo de pesquisa",
"Quick Type Definition": "Definição rápida de tipo",
-1
Переглянути файл
@@ -5445,7 +5445,6 @@
"Replace All ({key})": "Tümünü Değiştir ({key})",
"Include ({key})": "Dahil Et ({key})",
"Exclude ({key})": "Hariç Tut ({key})",
"Recent searches": "Son aramalar",
"New Line": "Yeni Satır",
"New Line in Search Field": "Arama Alanında Yeni Satır",
"Quick Type Definition": "Hızlı Tür Tanımı",
-1
Переглянути файл
@@ -3592,7 +3592,6 @@
"Replace All ({key})": "全部取代 ({key})",
"Include ({key})": "包括 ({key})",
"Exclude ({key})": "排除 ({key})",
"Recent searches": "最近的搜尋",
"New Line": "新行",
"New Line in Search Field": "在搜尋欄位中插入新行",
"Quick Type Definition": "快速型別定義",
-1
Переглянути файл
@@ -4031,7 +4031,6 @@
"Replace All ({key})": "全部替换 ({key})",
"Include ({key})": "包括 ({key})",
"Exclude ({key})": "排除 ({key})",
"Recent searches": "最近的搜索",
"New Line": "新行",
"New Line in Search Field": "在搜索字段中插入新行",
"Quick Type Definition": "快速类型定义",
+1 -1
Переглянути файл
@@ -4,7 +4,7 @@
min-width: 180px;
overflow-x: hidden;
}
.popup .menu {
.popup:not(.anchorWidthPopup) .menu {
max-width: 420px;
}
.titledPopup {
+8 -1
Переглянути файл
@@ -479,6 +479,7 @@ export interface MenuProps {
title?: string;
iconColumn?: boolean;
placement?: Placement;
maxWidthOverAnchor?: number;
"aria-label"?: string;
/** Numeric mnemonics on the first nine rows; see `MenuList`. */
numbers?: boolean;
@@ -492,6 +493,7 @@ export function Menu({
items,
title,
placement = "bottom-start",
maxWidthOverAnchor,
iconColumn,
numbers,
...aria
@@ -505,7 +507,12 @@ export function Menu({
placement={placement}
role="presentation"
autoFocus={false}
className={clsx(styles.popup, heading && styles.titledPopup)}
maxWidthOverAnchor={maxWidthOverAnchor}
className={clsx(
styles.popup,
heading && styles.titledPopup,
maxWidthOverAnchor !== undefined && styles.anchorWidthPopup,
)}
>
{heading && <div className={styles.menuHeading}>{heading}</div>}
<MenuList
+13 -6
Переглянути файл
@@ -67,6 +67,8 @@ export interface PopupProps {
closeOnDeactivate?: boolean;
/** Match the anchor's width (dropdowns). */
matchWidth?: boolean;
/** Limit an anchored popup to its anchor's width plus this many pixels. */
maxWidthOverAnchor?: number;
/** Plain surface without border/shadow styling. */
unstyled?: boolean;
/**
@@ -91,12 +93,13 @@ const measureNaturalHeight: Middleware = {
fn({ elements, middlewareData }) {
// Keep the new cap through internal flip/size restarts, not through the next update.
if (middlewareData.measureNaturalHeight) return {};
const scrollTop = elements.floating.scrollTop;
const previousLimit = elements.floating.style.removeProperty("max-height");
return { data: { measured: true }, reset: previousLimit ? { rects: true } : undefined };
return { data: { scrollTop }, reset: previousLimit ? { rects: true } : undefined };
},
};
function watchResizablePopup(reference: Element | VirtualElement, floating: HTMLElement, update: () => void) {
function watchPopupSize(reference: Element | VirtualElement, floating: HTMLElement, update: () => void) {
// Positioning writes the popup's size limits. Defer those writes outside the resize observer's delivery.
let frame = 0;
let placed = false;
@@ -149,6 +152,7 @@ function PopupInner({
closeOnOutsideClick = true,
closeOnDeactivate = true,
matchWidth = false,
maxWidthOverAnchor,
unstyled = false,
resizable,
minWidth = 200,
@@ -168,19 +172,22 @@ function PopupInner({
shift({ padding: 6 }),
sizeMw({
padding: 6,
apply({ rects, elements, availableHeight, availableWidth }) {
apply({ rects, elements, availableHeight, availableWidth, middlewareData }) {
const floatingStyle = elements.floating.style;
const maxHeight = Math.max(120, availableHeight);
if (!hasInlineMaxHeight && (rects.floating.height > maxHeight || floatingStyle.maxHeight)) {
floatingStyle.maxHeight = `${maxHeight}px`;
const scrollTop = middlewareData.measureNaturalHeight?.scrollTop;
if (scrollTop) elements.floating.scrollTop = scrollTop;
}
const width = Math.max(0, availableWidth);
const anchorLimit = maxWidthOverAnchor === undefined ? Infinity : rects.reference.width + maxWidthOverAnchor;
const width = Math.max(0, Math.min(availableWidth, anchorLimit));
floatingStyle.maxWidth = `${width}px`;
if (matchWidth) floatingStyle.minWidth = `${Math.min(rects.reference.width, width)}px`;
},
}),
],
[hasInlineMaxHeight, offset, matchWidth],
[hasInlineMaxHeight, offset, matchWidth, maxWidthOverAnchor],
);
const { refs, floatingStyles, isPositioned } = useFloating({
placement,
@@ -188,7 +195,7 @@ function PopupInner({
transform: false,
middleware,
elements: { reference },
whileElementsMounted: resizable ? watchResizablePopup : autoUpdate,
whileElementsMounted: resizable || maxWidthOverAnchor !== undefined ? watchPopupSize : autoUpdate,
});
const elRef = useRef<HTMLDivElement | null>(null);
const onCloseRef = useRef(onClose);
+37
Переглянути файл
@@ -0,0 +1,37 @@
import { Menu, type MenuItem } from "./Menu";
import type { PopupAnchor } from "./Popup";
import { searchHistory } from "@/platform/search";
interface SearchHistoryMenuProps {
kind: "find" | "replace" | null;
anchor: PopupAnchor;
onSelect: (value: string) => void;
onClose: () => void;
}
export function SearchHistoryMenu({ kind, anchor, onSelect, onClose }: SearchHistoryMenuProps) {
if (kind === null) return null;
const replace = kind === "replace";
const entries = searchHistory(kind);
const items: MenuItem[] = entries.length
? entries.map((value) => ({
label: value.replace(/\r\n?|\n/g, " ⏎ "),
hint: value,
verbatim: true,
run: () => onSelect(value),
}))
: [{ label: replace ? "No recent replacements" : "No recent searches", disabled: true }];
return (
<Menu
open
anchor={anchor}
title={replace ? "Recent Replacements" : "Recent Searches"}
items={items}
iconColumn={false}
maxWidthOverAnchor={200}
onClose={onClose}
/>
);
}