fix(grid): merge condition bar typing into one undo step

This commit is contained in:
zipg authored and GitHub committed 2026-09-27 10:44:05 +08:00
1 parent e092e5bae9
commit 1b6017b9c5
2 files changed
+160 -6

No files matched your search

@@ -58,10 +58,22 @@ const editorFocused = ref(false);
const conditionUndoStack = ref<string[]>([]);
const conditionRedoStack = ref<string[]>([]);
let conditionLastValue = modelValue.value;
// Chromium groups a continuous typing run into a single native undo step, but
// this editor replaces native undo with its own stack, so without grouping the
// user needs one Ctrl+Z per character. Keystrokes within this window keep the
// run's opening value on top of the stack; apply/blur/programmatic edits close
// the run so the next keystroke starts a fresh undo step.
const CONDITION_TYPING_UNDO_GROUP_MS = 700;
let conditionUndoGroupOpen = false;
let conditionUndoGroupAt = 0;
let collapseTimer: ReturnType<typeof setTimeout> | undefined;
let resizeObserver: ResizeObserver | undefined;
let expandAfterComposition = false;
function closeConditionUndoGroup() {
conditionUndoGroupOpen = false;
}
const editor = useDataGridConditionEditor({
kind: props.kind,
value: modelValue,
@@ -271,8 +283,7 @@ function resizeEditor(forceExpand = false) {
void nextTick(() => {
const overlay = overlayRef.value;
if (!overlay || composing.value) return;
const start = selectionStart.value;
const end = selectionEnd.value;
const { start, end } = selectionToRestore(input.value);
overlay.setSelectionRange(start, end);
overlay.focus({ preventScroll: true });
overlay.setSelectionRange(start, end);
@@ -283,8 +294,7 @@ function resizeEditor(forceExpand = false) {
}
if (!nextExpanded && overlayFocused && !composing.value) {
void nextTick(() => {
const start = selectionStart.value;
const end = selectionEnd.value;
const { start, end } = selectionToRestore(input.value);
input.focus({ preventScroll: true });
input.setSelectionRange(start, end);
selectionStart.value = start;
@@ -381,6 +391,16 @@ function syncSelection(target: HTMLTextAreaElement) {
selectionEnd.value = target.selectionEnd;
}
// A range captured before the text shrank (for example select-all followed by a
// replacement) is longer than the value that is actually there. Clamping it
// would select the whole condition, so the next keystroke would drop the input;
// leave the caret at the end of the shorter text instead.
function selectionToRestore(currentValue: string) {
const valueLength = currentValue.length;
if (selectionStart.value > valueLength || selectionEnd.value > valueLength) return { start: valueLength, end: valueLength };
return { start: selectionStart.value, end: selectionEnd.value };
}
function onFocus(event: FocusEvent) {
editorFocused.value = true;
syncSelection(event.currentTarget as HTMLTextAreaElement);
@@ -400,7 +420,11 @@ function scheduleCollapse() {
if (collapseTimer) clearTimeout(collapseTimer);
collapseTimer = setTimeout(() => {
const active = document.activeElement;
// Expanding/collapsing swaps focus between the two textareas, which fires a
// blur on the element being left; only a real exit from the editor ends the
// typing run.
if (active === inputRef.value || active === overlayRef.value) return;
closeConditionUndoGroup();
editorFocused.value = false;
editor.dismiss();
expanded.value = false;
@@ -424,6 +448,7 @@ function isConditionRedoShortcut(event: KeyboardEvent) {
}
function applyConditionHistoryValue(value: string) {
closeConditionUndoGroup();
conditionLastValue = value;
modelValue.value = value;
void nextTick(() => {
@@ -452,12 +477,14 @@ function handleConditionUndoRedo(event: KeyboardEvent) {
}
async function applyCondition() {
closeConditionUndoGroup();
editor.dismiss();
const applied = props.apply ? await props.apply(modelValue.value) : emit("apply", modelValue.value);
if (applied !== false && modelValue.value.trim()) editor.rememberHistory();
}
async function clearCondition() {
closeConditionUndoGroup();
modelValue.value = "";
editor.dismiss();
expanded.value = false;
@@ -468,6 +495,7 @@ async function clearCondition() {
function onKeydown(event: KeyboardEvent) {
if (handleConditionUndoRedo(event)) return;
if (completeQuote(event)) return;
if (event.key === "Enter" || event.key === "Tab") closeConditionUndoGroup();
const action = editor.handleKeydown(event);
if (action === "apply") void applyCondition();
if (action === "accept") focusAfterAccept();
@@ -497,6 +525,7 @@ function openHistory() {
}
function acceptSuggestion(index: number) {
closeConditionUndoGroup();
editor.accept(index);
focusAfterAccept();
}
@@ -555,8 +584,14 @@ function hideHistoryPreview() {
watch(modelValue, (value) => {
if (value !== conditionLastValue) {
conditionUndoStack.value.push(conditionLastValue);
conditionRedoStack.value = [];
const now = Date.now();
const continuesTypingRun = conditionUndoGroupOpen && now - conditionUndoGroupAt <= CONDITION_TYPING_UNDO_GROUP_MS;
if (!continuesTypingRun) {
conditionUndoStack.value.push(conditionLastValue);
conditionRedoStack.value = [];
}
conditionUndoGroupOpen = true;
conditionUndoGroupAt = now;
conditionLastValue = value;
}
resizeEditor();
@@ -53,6 +53,8 @@ function mockTextareaMetrics(input: HTMLTextAreaElement, options: { clientWidth:
}
afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();
for (const { app, host } of mountedApps.splice(0)) {
app.unmount();
host.remove();
@@ -157,6 +159,123 @@ describe("DataGridConditionEditor quote completion", () => {
expect(orderBy.value.value).toBe("id DESC");
});
it("collapses a continuous typing run into a single undo step", async () => {
const { value, input } = mountEditor("where", "id = 123");
input.focus();
for (const next of ["id = 1", "id = 12", "id = 124"]) {
input.value = next;
input.dispatchEvent(new Event("input", { bubbles: true }));
}
await nextTick();
expect(value.value).toBe("id = 124");
input.dispatchEvent(new KeyboardEvent("keydown", { key: "z", metaKey: true, bubbles: true, cancelable: true }));
await nextTick();
expect(value.value).toBe("id = 123");
});
it("starts a new undo step once the condition is applied", async () => {
const { value, input } = mountEditor("where", "id = 123");
input.focus();
input.value = "id = 124";
input.dispatchEvent(new Event("input", { bubbles: true }));
await nextTick();
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
await nextTick();
input.value = "id = 125";
input.dispatchEvent(new Event("input", { bubbles: true }));
await nextTick();
input.dispatchEvent(new KeyboardEvent("keydown", { key: "z", metaKey: true, bubbles: true, cancelable: true }));
await nextTick();
expect(value.value).toBe("id = 124");
input.dispatchEvent(new KeyboardEvent("keydown", { key: "z", metaKey: true, bubbles: true, cancelable: true }));
await nextTick();
expect(value.value).toBe("id = 123");
});
it("keeps one undo step across the expanded/collapsed focus swap", async () => {
vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {
const textWidth = (this.textContent?.length ?? 0) * 8;
const width = this.classList.contains("data-grid-topbar-condition-pane--expanded") ? 160 : textWidth;
return { x: 0, y: 0, left: 0, top: 0, right: width, bottom: 24, width, height: 24, toJSON: () => ({}) } as DOMRect;
});
vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);
vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
callback(0);
return 1;
});
const start = "abcdefghijklmnopqrstuvwxyz0123456789";
const { value, input } = mountEditor("where", start);
mockTextareaMetrics(input, { clientWidth: 80, scrollWidth: 320 });
input.focus();
input.dispatchEvent(new Event("focus", { bubbles: true }));
await nextTick();
await nextTick();
const overlay = document.body.querySelector(".data-grid-topbar-condition-input--expanded") as HTMLTextAreaElement | null;
expect(overlay).toBeTruthy();
input.value = `${start}x`;
input.setSelectionRange(37, 37);
input.dispatchEvent(new Event("input", { bubbles: true }));
// Swapping focus to the teleported overlay blurs the collapsed textarea
// mid-run; that must not split the typing run into a second undo step.
overlay!.dispatchEvent(new Event("blur", { bubbles: true }));
await new Promise((resolve) => setTimeout(resolve, 0));
const activeOverlay = document.body.querySelector(".data-grid-topbar-condition-input--expanded") as HTMLTextAreaElement;
activeOverlay.value = `${start}xy`;
activeOverlay.setSelectionRange(38, 38);
activeOverlay.dispatchEvent(new Event("input", { bubbles: true }));
await nextTick();
await nextTick();
expect(value.value).toBe(`${start}xy`);
activeOverlay.dispatchEvent(new KeyboardEvent("keydown", { key: "z", metaKey: true, bubbles: true, cancelable: true }));
await nextTick();
expect(value.value).toBe(start);
});
it("keeps the caret at the end when the text shrinks below the expanded selection", async () => {
vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {
const textWidth = (this.textContent?.length ?? 0) * 8;
const width = this.classList.contains("data-grid-topbar-condition-pane--expanded") ? 160 : textWidth;
return { x: 0, y: 0, left: 0, top: 0, right: width, bottom: 24, width, height: 24, toJSON: () => ({}) } as DOMRect;
});
vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);
vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
callback(0);
return 1;
});
const { value, input } = mountEditor("where", "abcdefghijklmnopqrstuvwxyz0123456789");
mockTextareaMetrics(input, { clientWidth: 80, scrollWidth: 320 });
input.focus();
input.dispatchEvent(new Event("focus", { bubbles: true }));
await nextTick();
await nextTick();
const overlay = document.body.querySelector(".data-grid-topbar-condition-input--expanded") as HTMLTextAreaElement | null;
expect(overlay).toBeTruthy();
overlay!.focus();
overlay!.setSelectionRange(0, 36);
overlay!.dispatchEvent(new Event("select", { bubbles: true }));
await nextTick();
// The whole selected text is replaced by a much shorter value without a
// fresh caret sync, and the editor collapses again.
mockTextareaMetrics(input, { clientWidth: 320, scrollWidth: 80 });
value.value = "i";
await nextTick();
await nextTick();
await nextTick();
expect(input.selectionStart).toBe(1);
expect(input.selectionEnd).toBe(1);
});
it("passes the textarea caret range through when accepting a suggestion", async () => {
const { value, input } = mountEditor("where", "status = cus AND enabled = 1", { columns: ["customer_id"] });
input.focus();