feat(grid): add find and replace for query results
This commit is contained in:
1 parent
d17ce46626
commit
8567e50887
19 files changed
+747
-81
No files matched your search
@@ -49,6 +49,7 @@ function createEditorWithResult(
|
||||
onCellValueChanged?: (rowId: number, columnIndex: number) => void,
|
||||
tableColumns?: Array<{ name: string; data_type: string; extra?: string; column_default?: string }>,
|
||||
mongoCollectionGrid = false,
|
||||
quickEntry = false,
|
||||
) {
|
||||
let editor: ReturnType<typeof useDataGridEditor>;
|
||||
const result = ref<{ columns: string[]; rows: CellValue[][] }>({
|
||||
@@ -77,6 +78,7 @@ function createEditorWithResult(
|
||||
onExecuteSql: computed(() => undefined),
|
||||
sql: computed(() => undefined),
|
||||
searchText: ref(""),
|
||||
dataGridQuickEntryEnabled: computed(() => quickEntry),
|
||||
whereFilterInput: ref(""),
|
||||
currentWhereInput: computed(() => undefined),
|
||||
orderByInput: ref(""),
|
||||
@@ -136,6 +138,122 @@ function createEditor(...args: Parameters<typeof createEditorWithResult>) {
|
||||
return createEditorWithResult(...args).editor;
|
||||
}
|
||||
|
||||
describe("useDataGridEditor searched replacements", () => {
|
||||
beforeEach(() => {
|
||||
mocks.prepareDataGridSave.mockReset();
|
||||
mocks.executeBatch.mockReset();
|
||||
mocks.getConfig.mockReturnValue(undefined);
|
||||
});
|
||||
|
||||
it("stages one undoable batch, keeps empty strings and preserves prior pending edits", () => {
|
||||
const editor = createEditor(undefined, true, undefined, undefined, [["hit", "keep", "hit"]]);
|
||||
editor.newRows.value = [];
|
||||
editor.applyCellValue(0, 1, "draft");
|
||||
expect(
|
||||
editor.stageCellReplacements([
|
||||
{ rowId: 0, col: 0, previousValue: "hit", value: "" },
|
||||
{ rowId: 0, col: 2, previousValue: "hit", value: "new" },
|
||||
]),
|
||||
).toBe(2);
|
||||
expect(editor.dirtyRows.value.get(0)).toEqual(
|
||||
new Map([
|
||||
[1, "draft"],
|
||||
[0, ""],
|
||||
[2, "new"],
|
||||
]),
|
||||
);
|
||||
expect(editor.manualSaveRequired.value).toBe(true);
|
||||
editor.undoPendingChange();
|
||||
expect(editor.dirtyRows.value.get(0)).toEqual(new Map([[1, "draft"]]));
|
||||
expect(editor.manualSaveRequired.value).toBe(false);
|
||||
editor.redoPendingChange();
|
||||
expect(editor.dirtyRows.value.get(0)?.get(0)).toBe("");
|
||||
expect(editor.manualSaveRequired.value).toBe(true);
|
||||
expect(mocks.executeBatch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects readonly, stale, deleted, non-string and out-of-range targets", () => {
|
||||
const editor = createEditor(
|
||||
["first", undefined, "last"],
|
||||
true,
|
||||
undefined,
|
||||
[2],
|
||||
[
|
||||
["hit", "hit", "hit"],
|
||||
[123, null, false],
|
||||
],
|
||||
);
|
||||
editor.newRows.value = [];
|
||||
editor.deletedRows.value.add(0);
|
||||
const changes = [
|
||||
{ rowId: 0, col: 0, previousValue: "hit", value: "x" },
|
||||
{ rowId: 1, col: 0, previousValue: "123", value: "x" },
|
||||
{ rowId: 9, col: 0, previousValue: "hit", value: "x" },
|
||||
];
|
||||
expect(editor.stageCellReplacements(changes)).toBe(0);
|
||||
editor.deletedRows.value.clear();
|
||||
expect(
|
||||
editor.stageCellReplacements([
|
||||
{ rowId: 0, col: 0, previousValue: "stale", value: "x" },
|
||||
{ rowId: 0, col: 1, previousValue: "hit", value: "x" },
|
||||
{ rowId: 0, col: 2, previousValue: "hit", value: "x" },
|
||||
{ rowId: -1, col: 0, previousValue: "hit", value: "x" },
|
||||
]),
|
||||
).toBe(0);
|
||||
expect(editor.dirtyRows.value.size).toBe(0);
|
||||
expect(editor.manualSaveRequired.value).toBe(false);
|
||||
});
|
||||
|
||||
it("blocks later quick-entry autosaves until explicit save or discard", async () => {
|
||||
const editor = createEditor(undefined, true, undefined, undefined, [["hit", "keep", "hit"]], undefined, undefined, false, true);
|
||||
editor.newRows.value = [];
|
||||
editor.stageCellReplacements([{ rowId: 0, col: 0, previousValue: "hit", value: "new" }]);
|
||||
editor.applyCellValue(0, 1, "later edit");
|
||||
await editor.saveChanges({ autoSave: true });
|
||||
expect(mocks.prepareDataGridSave).not.toHaveBeenCalled();
|
||||
expect(mocks.executeBatch).not.toHaveBeenCalled();
|
||||
expect(editor.hasPendingChanges.value).toBe(true);
|
||||
mocks.prepareDataGridSave.mockResolvedValue({ statements: ["UPDATE people SET first='new',hidden='later edit' WHERE last='hit'"], rollbackStatements: [] });
|
||||
mocks.executeBatch.mockResolvedValue([]);
|
||||
await editor.saveChanges();
|
||||
expect(mocks.executeBatch).toHaveBeenCalledOnce();
|
||||
expect(editor.manualSaveRequired.value).toBe(false);
|
||||
editor.stageCellReplacements([{ rowId: 0, col: 0, previousValue: "new", value: "other" }]);
|
||||
editor.discardChanges();
|
||||
expect(editor.manualSaveRequired.value).toBe(false);
|
||||
});
|
||||
|
||||
it("persists the manual-save interlock across a tab remount", async () => {
|
||||
const key = "replace-remount";
|
||||
const rows: CellValue[][] = [["hit", "keep", "hit"]];
|
||||
const first = createEditor(undefined, true, key, undefined, rows);
|
||||
first.newRows.value = [];
|
||||
first.stageCellReplacements([{ rowId: 0, col: 0, previousValue: "hit", value: "new" }]);
|
||||
first.savePendingSnapshot();
|
||||
const second = createEditor(undefined, true, key, undefined, rows);
|
||||
second.newRows.value = [];
|
||||
expect(second.manualSaveRequired.value).toBe(true);
|
||||
await second.saveChanges({ autoSave: true });
|
||||
expect(mocks.executeBatch).not.toHaveBeenCalled();
|
||||
second.discardChanges();
|
||||
clearDataGridPendingSnapshot(key);
|
||||
});
|
||||
|
||||
it("clears the manual-save interlock when replacement restores all original values", () => {
|
||||
const editor = createEditor(undefined, true, undefined, undefined, [["hit", "keep", "hit"]]);
|
||||
editor.newRows.value = [];
|
||||
editor.stageCellReplacements([{ rowId: 0, col: 0, previousValue: "hit", value: "new" }]);
|
||||
editor.stageCellReplacements([{ rowId: 0, col: 0, previousValue: "new", value: "hit" }]);
|
||||
expect(editor.hasPendingChanges.value).toBe(false);
|
||||
expect(editor.manualSaveRequired.value).toBe(false);
|
||||
editor.undoPendingChange();
|
||||
expect(editor.dirtyRows.value.get(0)?.get(0)).toBe("new");
|
||||
expect(editor.manualSaveRequired.value).toBe(true);
|
||||
editor.redoPendingChange();
|
||||
expect(editor.manualSaveRequired.value).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
function beforeTabSwitchEvent(fromTabId: string, tabId = "next-tab") {
|
||||
return new CustomEvent("dbx:before-tab-switch", { detail: { tabId, fromTabId } });
|
||||
}
|
||||
|
||||
@@ -15,6 +15,49 @@ async function flushSearchDebounce() {
|
||||
}
|
||||
|
||||
describe("useDataGridSearch", () => {
|
||||
it("supports literal case-sensitive replacement searches without column-name matches", async () => {
|
||||
vi.useFakeTimers();
|
||||
const sensitive = ref(true);
|
||||
const search = useDataGridSearch({
|
||||
columns: ["HIT", "value"],
|
||||
rows: [
|
||||
["HIT", "hit hit"],
|
||||
[" hit ", "hit"],
|
||||
],
|
||||
getCellSearchText: (row, col) => row[col].toLowerCase(),
|
||||
getCellRawSearchText: (row, col) => row[col],
|
||||
caseSensitive: sensitive,
|
||||
literalQuery: true,
|
||||
includeColumnMatches: false,
|
||||
isCellSearchable: (_row, col) => col === 0,
|
||||
});
|
||||
search.searchText.value = "HIT";
|
||||
await flushSearchDebounce();
|
||||
expect(search.matches.value).toEqual([{ kind: "cell", displayRow: 0, col: 0 }]);
|
||||
sensitive.value = false;
|
||||
await flushSearchDebounce();
|
||||
expect(search.matchCount.value).toBe(2);
|
||||
search.searchText.value = " hit ";
|
||||
await flushSearchDebounce();
|
||||
expect(search.matches.value).toEqual([{ kind: "cell", displayRow: 1, col: 0 }]);
|
||||
});
|
||||
it("degrades case-sensitive matching to case-insensitive without a raw-text provider", async () => {
|
||||
vi.useFakeTimers();
|
||||
const search = useDataGridSearch({
|
||||
columns: ["name"],
|
||||
rows: [["Alice"]],
|
||||
// No getCellRawSearchText: only the lowercase cache exists, so an
|
||||
// uppercase query must still match instead of never finding the cell.
|
||||
getCellSearchText: (row, col) => row[col].toLowerCase(),
|
||||
caseSensitive: true,
|
||||
literalQuery: false,
|
||||
includeColumnMatches: false,
|
||||
});
|
||||
search.searchText.value = "ALICE";
|
||||
await flushSearchDebounce();
|
||||
expect(search.matchCount.value).toBe(1);
|
||||
});
|
||||
|
||||
it("debounces matching across columns and cells", async () => {
|
||||
vi.useFakeTimers();
|
||||
// getCellSearchText 契约:返回小写文本(调用方负责缓存小写副本)
|
||||
|
||||
@@ -136,6 +136,7 @@ export interface UseDataGridEditorOptions {
|
||||
}
|
||||
|
||||
interface PendingChangesSnapshot {
|
||||
manualSaveRequired?: boolean;
|
||||
newRows: CellValue[][];
|
||||
newRowMeta: GridNewRowMeta[];
|
||||
quickEntryDraftRow?: CellValue[];
|
||||
@@ -173,7 +174,7 @@ interface QueuedAutoSaveChange {
|
||||
value: CellValue;
|
||||
}
|
||||
|
||||
type PendingChangesHistorySnapshot = Pick<PendingChangesSnapshot, "newRows" | "newRowMeta" | "quickEntryDraftRow" | "dirtyRows" | "deletedRows" | "transactionActive">;
|
||||
type PendingChangesHistorySnapshot = Pick<PendingChangesSnapshot, "newRows" | "newRowMeta" | "quickEntryDraftRow" | "dirtyRows" | "deletedRows" | "transactionActive" | "manualSaveRequired">;
|
||||
|
||||
const pendingChangesCache = new Map<string, PendingChangesSnapshot>();
|
||||
const closingPendingSnapshotTabs = new Set<string>();
|
||||
@@ -312,6 +313,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
const undoStack = ref<PendingChangesHistorySnapshot[]>([]);
|
||||
const redoStack = ref<PendingChangesHistorySnapshot[]>([]);
|
||||
const pendingChangesVersion = ref(0);
|
||||
const manualSaveRequired = ref(false);
|
||||
let restoredEditingCell = false;
|
||||
let restoredTransactionActive = false;
|
||||
let suppressNextBlurCommit = false;
|
||||
@@ -336,6 +338,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
quickEntryDraftRow.value = cached.quickEntryDraftRow ? [...cached.quickEntryDraftRow] : [];
|
||||
dirtyRows.value = cached.dirtyRows;
|
||||
deletedRows.value = cached.deletedRows;
|
||||
manualSaveRequired.value = cached.manualSaveRequired === true;
|
||||
editingCell.value = cached.editingCell ?? null;
|
||||
editValue.value = cached.editValue ?? "";
|
||||
restoredEditingCell = !!cached.editingCell;
|
||||
@@ -439,6 +442,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
|
||||
function pendingChangesSnapshot(): PendingChangesHistorySnapshot {
|
||||
return {
|
||||
manualSaveRequired: manualSaveRequired.value,
|
||||
newRows: newRows.value.map((row) => [...row]),
|
||||
newRowMeta: cloneNewRowMeta(newRowMeta.value),
|
||||
quickEntryDraftRow: quickEntryDraftRow.value.length > 0 ? [...quickEntryDraftRow.value] : undefined,
|
||||
@@ -455,6 +459,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
restoreNewRowMeta(snapshot.newRowMeta ?? []);
|
||||
quickEntryDraftRow.value = snapshot.quickEntryDraftRow ? [...snapshot.quickEntryDraftRow] : emptyDraftRow();
|
||||
dirtyRows.value = restoredDirtyRows;
|
||||
manualSaveRequired.value = snapshot.manualSaveRequired === true;
|
||||
deletedRows.value = new Set(snapshot.deletedRows);
|
||||
transactionActive.value = snapshot.transactionActive === true && useTransaction.value === true;
|
||||
queuedAutoSaveChanges.clear();
|
||||
@@ -957,8 +962,12 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
}
|
||||
|
||||
function applyCellValue(rowId: number, col: number, value: string | null, options: ApplyCellValueOptions = {}) {
|
||||
if (!canEditColumn(col)) return;
|
||||
const item = getRowItem(rowId);
|
||||
applyCellValueToItem(item, rowId, col, value, options);
|
||||
}
|
||||
|
||||
function applyCellValueToItem(item: RowItem | undefined, rowId: number, col: number, value: string | null, options: ApplyCellValueOptions = {}) {
|
||||
if (!canEditColumn(col)) return;
|
||||
if (!item || item.isDeleted) return;
|
||||
|
||||
if (item.isDraft) {
|
||||
@@ -1056,6 +1065,34 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
onCellValueChanged?.(rowId, col);
|
||||
}
|
||||
|
||||
function stageCellReplacements(changes: readonly import("@/lib/dataGrid/dataGridReplace").DataGridCellReplacement[]): number {
|
||||
if (!editable.value || !canEditExistingRows.value || isSaving.value || isConditionalUpdateActive.value) return 0;
|
||||
let changed = 0;
|
||||
beginBatch();
|
||||
try {
|
||||
for (const change of changes) {
|
||||
const { rowId, col, previousValue, value } = change;
|
||||
if (!Number.isInteger(rowId) || rowId < 0 || !Number.isInteger(col) || col < 0 || col >= result.value.columns.length || !canEditColumn(col) || deletedRows.value.has(rowId)) continue;
|
||||
const row = result.value.rows[rowId];
|
||||
if (!row) continue;
|
||||
const data = rowDataWithChanges(row, rowId);
|
||||
if (typeof data[col] !== "string" || data[col] !== previousValue || value === previousValue) continue;
|
||||
const item: RowItem = { id: rowId, sourceIndex: rowId, data, isNew: false, isDeleted: false, isDirtyCol: [], status: "clean" };
|
||||
applyCellValueToItem(item, rowId, col, value, { preserveEmptyString: true });
|
||||
const currentValue = rowDataWithChanges(row, rowId)[col];
|
||||
if (currentValue !== previousValue) {
|
||||
changed++;
|
||||
// Set after the first undo snapshot, so undo restores the prior policy.
|
||||
manualSaveRequired.value = true;
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
} finally {
|
||||
commitBatch();
|
||||
if (!hasPendingChanges.value) manualSaveRequired.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function restoreCellValue(rowId: number, col: number) {
|
||||
if (!canEditColumn(col)) return;
|
||||
const item = getRowItem(rowId);
|
||||
@@ -1501,6 +1538,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
|
||||
async function finishSaveChanges(savedSnapshot?: PendingSaveSnapshot) {
|
||||
isSaving.value = false;
|
||||
if (!hasPendingChanges.value) manualSaveRequired.value = false;
|
||||
if (pendingAutoSaveRequested && dataGridQuickEntryEnabled.value) {
|
||||
applyQueuedAutoSaveChanges(savedSnapshot);
|
||||
} else {
|
||||
@@ -1811,6 +1849,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
}
|
||||
|
||||
async function saveChanges(saveOptions: SaveChangesOptions = {}) {
|
||||
if (saveOptions.autoSave && manualSaveRequired.value) return;
|
||||
if (isSaving.value) {
|
||||
if (saveOptions.autoSave) pendingAutoSaveRequested = true;
|
||||
return;
|
||||
@@ -2016,6 +2055,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
|
||||
function discardChanges() {
|
||||
if (isConditionalUpdateActive.value) return;
|
||||
manualSaveRequired.value = false;
|
||||
dirtyRows.value = new Map();
|
||||
newRows.value = [];
|
||||
newRowMeta.value = [];
|
||||
@@ -2060,6 +2100,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
return;
|
||||
}
|
||||
pendingChangesCache.set(k, {
|
||||
manualSaveRequired: manualSaveRequired.value,
|
||||
newRows: newRows.value.map((r) => [...r]),
|
||||
newRowMeta: cloneNewRowMeta(newRowMeta.value),
|
||||
quickEntryDraftRow: quickEntryDraftRowSnapshot,
|
||||
@@ -2168,6 +2209,8 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
newRowCount,
|
||||
deletedRowCount,
|
||||
pendingChangesVersion,
|
||||
manualSaveRequired,
|
||||
stageCellReplacements,
|
||||
pendingChangeCount,
|
||||
hasPendingChanges,
|
||||
transactionActive,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { computed, getCurrentScope, nextTick, onScopeDispose, ref, toValue, watch, type MaybeRefOrGetter } from "vue";
|
||||
import { dataGridSearchMatchKey } from "@/lib/dataGrid/canvasDataGridRenderer";
|
||||
import { loadDataGridSearchState, saveDataGridSearchState } from "@/lib/dataGrid/dataGridSearchStatePersistence";
|
||||
import { dataGridReplacementPattern } from "@/lib/dataGrid/dataGridReplace";
|
||||
|
||||
export type DataGridSearchMatch = {
|
||||
kind: "cell" | "column";
|
||||
@@ -17,6 +18,11 @@ export type UseDataGridSearchOptions<Row> = {
|
||||
/** 必须返回小写文本(查询词已小写)。调用方可据此缓存小写副本,
|
||||
* 避免每次按键对全部单元格重新分配 toLowerCase 字符串。 */
|
||||
getCellSearchText: (row: Row, columnIndex: number) => string;
|
||||
getCellRawSearchText?: (row: Row, columnIndex: number) => string;
|
||||
caseSensitive?: MaybeRefOrGetter<boolean>;
|
||||
literalQuery?: MaybeRefOrGetter<boolean>;
|
||||
includeColumnMatches?: MaybeRefOrGetter<boolean>;
|
||||
isCellSearchable?: (row: Row, columnIndex: number) => boolean;
|
||||
debounceMs?: number;
|
||||
onNavigate?: (match: DataGridSearchMatch) => void;
|
||||
/** 按标签页键控的持久化键;不传则该宿主不参与搜索状态保留。 */
|
||||
@@ -38,6 +44,11 @@ export function useDataGridSearch<Row>(options: UseDataGridSearchOptions<Row>) {
|
||||
const suggestionIndex = ref(-1);
|
||||
let searchTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
// Case-sensitive matching needs the raw (non-lowercased) cell text. Without a
|
||||
// raw-text provider only the lowercase cache exists, so degrade to
|
||||
// case-insensitive instead of never matching uppercase input.
|
||||
const effectiveCaseSensitive = computed(() => !!toValue(options.caseSensitive) && (!!toValue(options.literalQuery) || !!options.getCellRawSearchText));
|
||||
|
||||
const matchState = computed(() => {
|
||||
const query = deferredSearchText.value;
|
||||
const keys: number[] = [];
|
||||
@@ -50,12 +61,23 @@ export function useDataGridSearch<Row>(options: UseDataGridSearchOptions<Row>) {
|
||||
matchSet.add(key);
|
||||
};
|
||||
const columns = toValue(options.columns);
|
||||
columns.forEach((column, col) => {
|
||||
if (column.toLowerCase().includes(query)) addMatch(-1, col);
|
||||
});
|
||||
const sensitive = effectiveCaseSensitive.value;
|
||||
const pattern = toValue(options.literalQuery) ? dataGridReplacementPattern(query, sensitive) : undefined;
|
||||
const includes = (value: string) => {
|
||||
if (!pattern) return (sensitive ? value : value.toLowerCase()).includes(query);
|
||||
pattern.lastIndex = 0;
|
||||
return pattern.test(value);
|
||||
};
|
||||
if (toValue(options.includeColumnMatches) !== false) {
|
||||
columns.forEach((column, col) => {
|
||||
if (includes(column)) addMatch(-1, col);
|
||||
});
|
||||
}
|
||||
toValue(options.rows).forEach((row, displayRow) => {
|
||||
columns.forEach((_, col) => {
|
||||
if (options.getCellSearchText(row, col).includes(query)) addMatch(displayRow, col);
|
||||
if (options.isCellSearchable && !options.isCellSearchable(row, col)) return;
|
||||
const text = (pattern || sensitive) && options.getCellRawSearchText ? options.getCellRawSearchText(row, col) : options.getCellSearchText(row, col);
|
||||
if (includes(text)) addMatch(displayRow, col);
|
||||
});
|
||||
});
|
||||
return { keys, matchSet };
|
||||
@@ -81,9 +103,10 @@ export function useDataGridSearch<Row>(options: UseDataGridSearchOptions<Row>) {
|
||||
// watcher flush and self-invalidates if the user types during the restore window.
|
||||
let restoreToken: { searchText: string; matchIndex: number } | null = null;
|
||||
|
||||
watch(searchText, (value) => {
|
||||
watch([searchText, () => toValue(options.caseSensitive), () => toValue(options.literalQuery)], ([value]) => {
|
||||
clearTimer();
|
||||
const query = value.trim().toLowerCase();
|
||||
const text = toValue(options.literalQuery) ? value : value.trim();
|
||||
const query = toValue(options.literalQuery) || effectiveCaseSensitive.value ? text : text.toLowerCase();
|
||||
const restoring = restoreToken !== null && restoreToken.searchText === value;
|
||||
if (!query) deferredSearchText.value = "";
|
||||
// Restoring is not typing: resolve the query now so the row set (and, in
|
||||
@@ -102,6 +125,12 @@ export function useDataGridSearch<Row>(options: UseDataGridSearchOptions<Row>) {
|
||||
// are writing keeps the normal debounce, index reset and auto-navigate.
|
||||
restoreToken = null;
|
||||
|
||||
if (toValue(options.literalQuery)) {
|
||||
suggestions.value = [];
|
||||
suggestionIndex.value = -1;
|
||||
return;
|
||||
}
|
||||
|
||||
const lastToken = value.trim().split(SEARCH_TOKEN_SEPARATOR).pop()?.toLowerCase() ?? "";
|
||||
suggestions.value = lastToken
|
||||
? toValue(options.suggestionColumns ?? options.columns)
|
||||
|
||||
Reference in new issue
Block a user