fix(grid): stop filter autocomplete inserting column names

This commit is contained in:
高桥凉介 authored and GitHub committed 2026-09-29 21:06:14 +08:00
1 parent f6d2077561
commit aff43d7ba9
3 files changed
+193 -44

No files matched your search

@@ -21,8 +21,8 @@ describe("useDataGridConditionEditor", () => {
vi.useRealTimers();
});
it("replaces the active token and supports clamped keyboard navigation", async () => {
const value = ref("status = cus");
it("replaces the active field token and supports clamped keyboard navigation", async () => {
const value = ref("status = 1 AND cus");
const editor = useDataGridConditionEditor({
kind: "where",
value,
@@ -30,16 +30,94 @@ describe("useDataGridConditionEditor", () => {
historyScope: {},
});
value.value = "status = cust";
value.value = "status = 1 AND cust";
await nextTick();
await vi.waitFor(() => expect(editor.suggestions.value.map((item) => item.value)).toEqual(["customer_id", "customer_name"]));
// 不再默认高亮第一条建议:必须显式导航/接受,避免回车应用筛选时改写输入(issue #10595)
expect(editor.highlightedIndex.value).toBe(-1);
expect(editor.navigate(1)).toBe(true);
expect(editor.highlightedIndex.value).toBe(0);
expect(editor.navigate(1)).toBe(true);
expect(editor.highlightedIndex.value).toBe(1);
expect(editor.navigate(1)).toBe(true);
expect(editor.highlightedIndex.value).toBe(1);
expect(editor.accept()).toBe(true);
expect(value.value).toBe("status = customer_name");
expect(value.value).toBe("status = 1 AND customer_name");
});
it("does not suggest column names while typing a value after a comparison operator", async () => {
const value = ref("");
const editor = useDataGridConditionEditor({
kind: "where",
value,
columns: ["v_id", "v_name"],
historyScope: {},
suggestionDebounceMs: 1,
});
// 用户场景:`v_id = v` 时正在输入值,不应该看到列名补全(issue #10595)
value.value = "v_id = v";
await nextTick();
await new Promise((resolve) => setTimeout(resolve, 5));
expect(editor.suggestions.value).toEqual([]);
value.value = "v_id <> v";
await nextTick();
await new Promise((resolve) => setTimeout(resolve, 5));
expect(editor.suggestions.value).toEqual([]);
// AND 之后是字段位置,仍然提示列名
value.value = "v_id = 'x' AND v";
await nextTick();
await vi.waitFor(() => expect(editor.suggestions.value.map((item) => item.value)).toEqual(["v_id", "v_name"]));
});
it("does not suggest column names inside an IN value list", async () => {
const value = ref("");
const editor = useDataGridConditionEditor({
kind: "where",
value,
columns: ["mi_id", "model_name"],
historyScope: {},
suggestionDebounceMs: 1,
});
// 用户场景:`v_id = v AND mi_id in (v` —— 正在输入 IN 列表里的值(issue #10595)
value.value = "v_id = v AND mi_id in (v";
await nextTick();
await new Promise((resolve) => setTimeout(resolve, 5));
expect(editor.suggestions.value).toEqual([]);
// 列表里的第二个值同样不应提示列名
value.value = "mi_id in ('a', m";
await nextTick();
await new Promise((resolve) => setTimeout(resolve, 5));
expect(editor.suggestions.value).toEqual([]);
// 括号闭合后的新条件仍应提示列名
value.value = "mi_id in (1, 2) AND m";
await nextTick();
await vi.waitFor(() => expect(editor.suggestions.value.map((item) => item.value)).toEqual(["mi_id", "model_name"]));
// 裸括号(表达式开头)仍属于字段位置
value.value = "(m";
await nextTick();
await vi.waitFor(() => expect(editor.suggestions.value.map((item) => item.value)).toEqual(["mi_id", "model_name"]));
});
it("only suggests sort direction after an ORDER BY column", async () => {
const value = ref("");
const editor = useDataGridConditionEditor({ kind: "orderBy", value, columns: ["create_time", "create_by"], historyScope: {}, suggestionDebounceMs: 1 });
// 输入 `asc` 时不应提示列名(否则按 Tab 会把列名写进输入框)
value.value = "create_time a";
await nextTick();
await vi.waitFor(() => expect(editor.suggestions.value).toEqual([{ value: "ASC", kind: "keyword" }]));
// 逗号之后是新的排序列位置,提示列名
value.value = "create_time ASC, c";
await nextTick();
await vi.waitFor(() => expect(editor.suggestions.value.map((item) => item.value)).toEqual(["create_time", "create_by"]));
});
it.each(["where", "orderBy"] as const)("searches %s fields by camel-case initials and any-position text", async (kind) => {
@@ -108,16 +186,16 @@ describe("useDataGridConditionEditor", () => {
historyScope: {},
});
value.value = "status = cus AND enabled = 1";
selectionStart.value = 12;
selectionEnd.value = 12;
value.value = "status = 1 AND cus AND enabled = 2";
selectionStart.value = 18;
selectionEnd.value = 18;
await nextTick();
await vi.waitFor(() => expect(editor.suggestions.value.map((item) => item.value)).toEqual(["customer_id", "customer_name"]));
expect(editor.accept(0)).toBe(true);
expect(value.value).toBe("status = customer_id AND enabled = 1");
expect(selectionStart.value).toBe(20);
expect(selectionEnd.value).toBe(20);
expect(value.value).toBe("status = 1 AND customer_id AND enabled = 2");
expect(selectionStart.value).toBe(26);
expect(selectionEnd.value).toBe(26);
});
it("uses the current selection as an explicit replacement range", async () => {
@@ -126,14 +204,14 @@ describe("useDataGridConditionEditor", () => {
const selectionEnd = ref(0);
const editor = useDataGridConditionEditor({ kind: "where", value, selectionStart, selectionEnd, columns: ["old_value"], historyScope: {} });
value.value = "status = old AND enabled = 1";
selectionStart.value = 9;
selectionEnd.value = 12;
value.value = "old = 1";
selectionStart.value = 0;
selectionEnd.value = 3;
await nextTick();
await vi.waitFor(() => expect(editor.suggestions.value.map((item) => item.value)).toEqual(["old_value"]));
expect(editor.accept()).toBe(true);
expect(value.value).toBe("status = old_value AND enabled = 1");
expect(value.value).toBe("old_value = 1");
});
it("suggests WHERE connectors after a completed expression", async () => {
@@ -168,7 +246,7 @@ describe("useDataGridConditionEditor", () => {
expect(value.value).toBe("status = 'active' AND owner_id");
});
it("does not offer connectors inside quoted values or in ORDER BY", async () => {
it("does not offer connectors inside quoted values, and offers only sort direction after an ORDER BY column", async () => {
const whereValue = ref("");
const whereEditor = useDataGridConditionEditor({ kind: "where", value: whereValue, columns: ["name"], historyScope: {} });
whereValue.value = "name = 'Alice a";
@@ -179,7 +257,8 @@ describe("useDataGridConditionEditor", () => {
const orderByEditor = useDataGridConditionEditor({ kind: "orderBy", value: orderByValue, columns: ["amount"], historyScope: {} });
orderByValue.value = "created_at a";
await nextTick();
await vi.waitFor(() => expect(orderByEditor.suggestions.value).toEqual([]));
// ORDER BY 的排序列之后是排序方向位置:只提示 ASC/DESC,绝不插入列名(issue #10595)
await vi.waitFor(() => expect(orderByEditor.suggestions.value).toEqual([{ value: "ASC", kind: "keyword" }]));
});
it.each(["deleted_at IS ", "deleted_at IS a", "deleted_at IS NOT o", "name LIKE o", "id IN a", "score BETWEEN o"])("does not offer connectors while the keyword operator is incomplete: %s", async (condition) => {
@@ -282,12 +361,12 @@ describe("useDataGridConditionEditor", () => {
historyScope: {},
});
value.value = kind === "where" ? "status = Order" : "created_at DESC, Order";
value.value = kind === "where" ? "status = 1 AND Order" : "created_at DESC, Order";
await nextTick();
await vi.waitFor(() => expect(editor.suggestions.value).toEqual([{ value: "OrderId", insertText: '"OrderId"', kind: "column", comment: "Mixed-case identifier" }]));
expect(editor.accept()).toBe(true);
expect(value.value).toBe(kind === "where" ? 'status = "OrderId"' : 'created_at DESC, "OrderId"');
expect(value.value).toBe(kind === "where" ? 'status = 1 AND "OrderId"' : 'created_at DESC, "OrderId"');
});
it("restores quoted history verbatim instead of quoting it again", () => {
@@ -371,21 +450,21 @@ describe("useDataGridConditionEditor", () => {
const suggestionProvider = vi.fn(() => ["customer_id"]);
useDataGridConditionEditor({ kind: "where", value, selectionStart, selectionEnd, historyScope: {}, suggestionProvider });
value.value = "status = cus AND enabled = 1";
selectionStart.value = 12;
selectionEnd.value = 12;
value.value = "status = 1 AND cus";
selectionStart.value = 18;
selectionEnd.value = 18;
await nextTick();
await vi.waitFor(() => expect(suggestionProvider).toHaveBeenCalledOnce());
expect(suggestionProvider).toHaveBeenCalledWith(
expect.objectContaining({
value: "status = cus AND enabled = 1",
valueBeforeCursor: "status = cus",
value: "status = 1 AND cus",
valueBeforeCursor: "status = 1 AND cus",
token: "cus",
from: 9,
to: 12,
selectionStart: 12,
selectionEnd: 12,
from: 15,
to: 18,
selectionStart: 18,
selectionEnd: 18,
}),
);
});
@@ -54,6 +54,13 @@ const WHERE_TOKEN_FORWARD_PATTERN = /^([^\s,()><=!&|]+)/;
const ORDER_BY_TOKEN_FORWARD_PATTERN = /^([^\s,()]+)/;
const WHERE_CONNECTOR_KEYWORDS = ["AND", "OR"] as const;
const WHERE_VALUE_OPERATOR_PATTERN = /(?:^|[\s(])(?:IS(?:\s+NOT)?|(?:NOT\s+)?(?:LIKE|ILIKE|IN|BETWEEN)|SIMILAR\s+TO|REGEXP|RLIKE|GLOB|MATCH)\s*$/i;
/**
* 比较类符号运算符。它们后面同样是「值」位置,不应再提示列名,
* 否则用户输入值时会看到列名补全、回车/接受后输入被改写(issue #10595)。
*/
const WHERE_SYMBOLIC_COMPARISON_PATTERN = /(?:<>|!=|<=|>=|=|<|>)$/;
/** ORDER BY 中排序列之后的位置只应提示排序方向。 */
const ORDER_BY_DIRECTION_KEYWORDS = ["ASC", "DESC"] as const;
interface DataGridConditionCompletionTarget {
value: string;
@@ -173,15 +180,71 @@ function conditionCompletionTarget(kind: DataGridConditionHistoryKind, value: st
};
}
function whereSuggestionRole(target: DataGridConditionCompletionTarget): "field" | "connector" | "none" {
/**
* 判断光标是否位于 `IN (...)` 的值列表里(括号由 IN / NOT IN 打开且尚未闭合)。
*
* `IN (` 之后要输入的是值列表而不是列名;但裸括号(`WHERE (v`)和函数参数里的逗号
* 仍然属于"表达式/字段"位置,所以必须区分括号是谁打开的(issue #10595)。
*/
function insideInValueList(value: string, cursor: number, identifierQuote: string | undefined): boolean {
const identifierOpen = normalizedIdentifierQuote(identifierQuote);
const identifierClose = identifierOpen ? identifierCloseQuote(identifierOpen) : undefined;
let stringQuote: string | undefined;
const openParens: number[] = [];
for (let index = 0; index < cursor; index += 1) {
const character = value[index];
if (stringQuote) {
if (character === "\\") {
index += 1;
} else if (value.startsWith(stringQuote + stringQuote, index)) {
index += 1;
} else if (character === stringQuote) {
stringQuote = undefined;
}
continue;
}
if (identifierOpen && value.startsWith(identifierOpen, index)) {
index += identifierClose!.length - 1;
continue;
}
if (character === "'" || character === '"') {
stringQuote = character;
} else if (character === "(") {
openParens.push(index);
} else if (character === ")") {
openParens.pop();
}
}
const openIndex = openParens[openParens.length - 1];
if (openIndex === undefined) return false;
const before = value.slice(0, openIndex).trimEnd();
return /(?:^|[\s(])IN$/i.test(before) || /(?:^|[\s(])NOT\s+IN$/i.test(before);
}
function whereSuggestionRole(target: DataGridConditionCompletionTarget, identifierQuote: string | undefined): "field" | "connector" | "none" {
if (target.insideString) return "none";
if (target.quotedIdentifier) return "field";
const prefix = target.value.slice(0, target.from).trimEnd();
if (WHERE_VALUE_OPERATOR_PATTERN.test(prefix)) return "none";
if (!prefix || /(?:^|\s)(?:AND|OR|NOT)$/i.test(prefix) || /[,(<>=!~+\-*/]$/.test(prefix)) return "field";
// 符号比较运算符之后是值位置:`v_id = v` 时不提示列名,只在 AND/OR 等字段位置提示
if (WHERE_SYMBOLIC_COMPARISON_PATTERN.test(prefix)) return "none";
// `mi_id IN (v` / `mi_id IN ('a', v` 同样是值列表,不能提示列名
if (insideInValueList(target.value, target.from, identifierQuote)) return "none";
if (!prefix || /(?:^|\s)(?:AND|OR|NOT)$/i.test(prefix) || /[,(+\-*/~]$/.test(prefix)) return "field";
return "connector";
}
/**
* ORDER BY 的角色判定:开头或逗号之后是排序列位置(提示列名),
* 已经写出排序列之后是排序方向位置(提示 ASC/DESC)。
* 否则在输入 `asc` 时按 Tab 会把列名插进输入框(issue #10595)。
*/
function orderBySuggestionRole(target: DataGridConditionCompletionTarget): "field" | "direction" {
const prefix = target.value.slice(0, target.from).trimEnd();
return !prefix || prefix.endsWith(",") ? "field" : "direction";
}
export interface DataGridConditionQuoteCompletion {
value: string;
selectionStart: number;
@@ -234,7 +297,7 @@ export function useDataGridConditionEditor(options: UseDataGridConditionEditorOp
}
function defaultSuggestions(target: DataGridConditionCompletionTarget): DataGridConditionSuggestion[] {
const role = options.kind === "where" ? whereSuggestionRole(target) : "field";
const role = options.kind === "where" ? whereSuggestionRole(target, toValue(options.identifierQuote)) : orderBySuggestionRole(target);
if (role === "none") return [];
const normalizedToken = target.token.toLowerCase();
const seen = new Set<string>();
@@ -260,7 +323,9 @@ export function useDataGridConditionEditor(options: UseDataGridConditionEditorOp
scored.sort((a, b) => b.score - a.score || a.index - b.index);
return scored.map((entry) => entry.suggestion);
} else {
for (const keyword of WHERE_CONNECTOR_KEYWORDS) {
// WHERE 已写完一个表达式时提示连接符;ORDER BY 已写出排序列时提示排序方向。
const keywords = options.kind === "where" ? WHERE_CONNECTOR_KEYWORDS : ORDER_BY_DIRECTION_KEYWORDS;
for (const keyword of keywords) {
if (!keyword.toLowerCase().startsWith(normalizedToken) || keyword.toLowerCase() === normalizedToken) continue;
suggestions.push({ value: keyword, kind: "keyword" });
}
@@ -272,7 +337,7 @@ export function useDataGridConditionEditor(options: UseDataGridConditionEditorOp
if (!target.token && (options.kind !== "where" || !target.value.trim())) return;
suggestionsLoading.value = true;
try {
const role = options.kind === "where" ? whereSuggestionRole(target) : "field";
const role = options.kind === "where" ? whereSuggestionRole(target, toValue(options.identifierQuote)) : orderBySuggestionRole(target);
const values =
options.suggestionProvider && target.token && role === "field"
? await options.suggestionProvider({ kind: options.kind, value: target.value, valueBeforeCursor: target.valueBeforeCursor, token: target.token, from: target.from, to: target.to, selectionStart: target.selectionStart, selectionEnd: target.selectionEnd, signal: controller.signal })
@@ -283,7 +348,9 @@ export function useDataGridConditionEditor(options: UseDataGridConditionEditorOp
const providerValues = values ? [...new Set(values)] : undefined;
suggestions.value = providerValues ? (providerValues.some((value) => value.toLowerCase() === target.token.toLowerCase()) ? [] : providerValues.slice(0, limit).map((suggestion) => ({ value: suggestion, kind: "column" }))) : defaultSuggestions(target).slice(0, limit);
replacementRange.value = { from: target.from, to: target.to };
highlightedIndex.value = options.kind === "where" && suggestions.value[0]?.kind === "column" ? 0 : -1;
// 不再默认高亮第一条建议:否则用户按回车«应用筛选»时会先把高亮项写进输入框(issue #10595)。
// 接受补全需要显式操作(↓/↑ 后回车、Tab 或点击)。
highlightedIndex.value = -1;
} catch (error) {
if (!controller.signal.aborted && requestId === suggestionRequestId) {
suggestions.value = [];