fix(mongodb): keep one colon when a key completion lands before an existing one

This commit is contained in:
Loc Nguyen authored and GitHub committed 2026-09-29 13:41:11 +08:00
1 parent 6ffc462790
commit 43f502332e
3 files changed
+41 -6

No files matched your search

@@ -255,6 +255,26 @@ describe("QueryEditor completion provider ownership", () => {
expect(await pending).toBeNull(); expect(await pending).toBeNull();
}); });
it("does not double the separator when a Mongo key is re-picked in front of an existing colon", async () => {
const accept = async (doc: string, cursor: number) => {
const { store, provide, currentView } = createHarness({ databaseType: "mongodb", modelValue: doc });
store.listMongoCompletionFields.mockResolvedValue([{ name: "name", type: "string" }]);
currentView.dispatch({ selection: { anchor: cursor } });
const result = await provide();
const option = result?.options.find((candidate) => candidate.label === "name");
expect(option, "the field is offered").toBeDefined();
(option!.apply as (view: EditorView, completion: unknown, from: number, to: number) => void)(currentView, option, result!.from, cursor);
return { doc: currentView.state.doc.toString(), cursor: currentView.state.selection.main.head };
};
// Editing the key of an existing entry: the colon already there is kept, not doubled.
expect(await accept("db.users.find({ na: 1 })", 18)).toEqual({ doc: "db.users.find({ name: 1 })", cursor: 20 });
expect(await accept("db.users.find({ na : 1 })", 18)).toEqual({ doc: "db.users.find({ name : 1 })", cursor: 20 });
// A fresh key still gets its separator.
expect(await accept("db.users.find({ na", 18)).toEqual({ doc: "db.users.find({ name: ", cursor: 22 });
expect(await accept("db.users.find({ na })", 18)).toEqual({ doc: "db.users.find({ name: })", cursor: 22 });
});
it.each(["redis", "mongodb", "mysql"] as const)("does not query %s metadata without a connection", async (databaseType) => { it.each(["redis", "mongodb", "mysql"] as const)("does not query %s metadata without a connection", async (databaseType) => {
const { store, provide } = createHarness({ databaseType, connectionId: undefined }); const { store, provide } = createHarness({ databaseType, connectionId: undefined });
expect(await provide()).toBeNull(); expect(await provide()).toBeNull();
@@ -20,7 +20,7 @@ import {
import { originForSqlCompletionProvider, originForTypedSqlCompletionStart, shouldAllowSqlCompletionTrigger, type SqlCompletionTriggerFacts, type SqlCompletionTriggerOrigin } from "@/lib/sql/sqlCompletionTriggerPolicy"; import { originForSqlCompletionProvider, originForTypedSqlCompletionStart, shouldAllowSqlCompletionTrigger, type SqlCompletionTriggerFacts, type SqlCompletionTriggerOrigin } from "@/lib/sql/sqlCompletionTriggerPolicy";
import { driverProfileHasCompletionCandidates } from "@/lib/database/driverProfileExtensions"; import { driverProfileHasCompletionCandidates } from "@/lib/database/driverProfileExtensions";
import { buildElasticsearchCompletionItemsFromContext, elasticsearchCompletionNeedsFields, getElasticsearchCompletionContext, getElasticsearchCompletionResultValidFor, shouldAutoOpenElasticsearchCompletion, type ElasticsearchCompletionField } from "@/lib/elasticsearch/elasticsearchCompletion"; import { buildElasticsearchCompletionItemsFromContext, elasticsearchCompletionNeedsFields, getElasticsearchCompletionContext, getElasticsearchCompletionResultValidFor, shouldAutoOpenElasticsearchCompletion, type ElasticsearchCompletionField } from "@/lib/elasticsearch/elasticsearchCompletion";
import { buildMongoCompletionItemsFromContext, getMongoCompletionContext, getMongoCompletionResultValidFor, mongoCompletionNeedsCollections, mongoCompletionNeedsDatabases, mongoCompletionNeedsFields, shouldAutoOpenMongoCompletion } from "@/lib/mongo/mongoCompletion"; import { buildMongoCompletionItemsFromContext, foldMongoKeySeparator, getMongoCompletionContext, getMongoCompletionResultValidFor, mongoCompletionNeedsCollections, mongoCompletionNeedsDatabases, mongoCompletionNeedsFields, shouldAutoOpenMongoCompletion } from "@/lib/mongo/mongoCompletion";
import { buildSoqlCompletionItems, getSoqlCompletionContext, getSoqlCompletionResultValidFor, resolveSoqlFieldCandidates, resolveSoqlValueField, shouldAutoOpenSoqlCompletion, soqlCompletionNeedsObjects, type SoqlCompletionField, type SoqlCompletionObject } from "@/lib/soql/soqlCompletion"; import { buildSoqlCompletionItems, getSoqlCompletionContext, getSoqlCompletionResultValidFor, resolveSoqlFieldCandidates, resolveSoqlValueField, shouldAutoOpenSoqlCompletion, soqlCompletionNeedsObjects, type SoqlCompletionField, type SoqlCompletionObject } from "@/lib/soql/soqlCompletion";
import { import {
buildSqlServerUseDatabaseCompletionItems, buildSqlServerUseDatabaseCompletionItems,
@@ -466,11 +466,15 @@ export function useQueryEditorCompletion(options: QueryEditorCompletionOptions)
replaceClosingQuote: "replaceClosingQuote" in item ? item.replaceClosingQuote : undefined, replaceClosingQuote: "replaceClosingQuote" in item ? item.replaceClosingQuote : undefined,
replaceSelectWildcard: "replaceSelectWildcard" in item ? item.replaceSelectWildcard : undefined, replaceSelectWildcard: "replaceSelectWildcard" in item ? item.replaceSelectWildcard : undefined,
}); });
const insert = appendSqlCompletionSpace(item.apply ?? item.label, { let insert = appendSqlCompletionSpace(item.apply ?? item.label, {
enabled: ("appendSpace" in item && item.appendSpace === true) || (shouldInsertSqlCompletionSpace() && settingsStore.editorSettings.insertSpaceAfterCompletion), enabled: ("appendSpace" in item && item.appendSpace === true) || (shouldInsertSqlCompletionSpace() && settingsStore.editorSettings.insertSpaceAfterCompletion),
itemType: item.type, itemType: item.type,
nextCharacter: view.state.sliceDoc(replaceTo, replaceTo + 1), nextCharacter: view.state.sliceDoc(replaceTo, replaceTo + 1),
}); });
if (props.databaseType === "mongodb") {
// A key completion writes its own `: `; re-picking a key in front of an existing one must not double it.
insert = foldMongoKeySeparator(insert, view.state.sliceDoc(replaceTo, view.state.doc.lineAt(replaceTo).to));
}
if (runtime.codeMirrorInsertCompletionText) { if (runtime.codeMirrorInsertCompletionText) {
view.dispatch(runtime.codeMirrorInsertCompletionText(view.state, insert, from, replaceTo)); view.dispatch(runtime.codeMirrorInsertCompletionText(view.state, insert, from, replaceTo));
} else { } else {
+15 -4
View File
@@ -500,6 +500,20 @@ export function getMongoDocumentQueryCompletionContext(text: string, cursor: num
return { ...classified, prefix, from, replaceClosingQuote: closingQuoteAtCursor(prefix, text, safeCursor) }; return { ...classified, prefix, from, replaceClosingQuote: closingQuoteAtCursor(prefix, text, safeCursor) };
} }
/**
* Drops the `: ` a key completion carries when the text after the replaced range
* already starts with the separator, so re-picking the key of an existing
* `{ name: 1 }` entry yields `{ other: 1 }` rather than `{ other: : 1 }`.
*
* Only a plain key completion may fold its separator away. A snippet's colon
* introduces the placeholder that follows it (`$gt: ${}`), so it is never the
* same colon as one already in the text.
*/
export function foldMongoKeySeparator(insert: string, followingText: string): string {
if (insert.includes("${") || !insert.endsWith(": ") || !/^\s*:/.test(followingText)) return insert;
return insert.slice(0, -2);
}
/** Text to splice into a plain input for a chosen completion, and where to leave the selection. */ /** Text to splice into a plain input for a chosen completion, and where to leave the selection. */
export interface MongoPlainCompletionInsertion { export interface MongoPlainCompletionInsertion {
text: string; text: string;
@@ -539,10 +553,7 @@ export function plainMongoCompletionInsertion(apply: string, followingText = "")
} }
text += rest; text += rest;
// Only a plain key completion may fold its separator away. A snippet's colon if (!selection) text = foldMongoKeySeparator(text, followingText);
// introduces the placeholder that follows it (`$gt: ${}`), so it is never the
// same colon as one already in the text.
if (!selection && text.endsWith(": ") && /^\s*:/.test(followingText)) text = text.slice(0, -2);
return { text, selectionStart: Math.min(selection?.start ?? text.length, text.length), selectionEnd: Math.min(selection?.end ?? text.length, text.length) }; return { text, selectionStart: Math.min(selection?.start ?? text.length, text.length), selectionEnd: Math.min(selection?.end ?? text.length, text.length) };
} }