feat(mongodb): complete fields in filter and sort bars

This commit is contained in:
onenewcode authored and GitHub committed 2026-09-18 20:05:26 +08:00
1 parent d2fd783592
commit 9788c20d3c
7 files changed
+1526 -14

No files matched your search

@@ -0,0 +1,147 @@
import { describe, expect, it } from "vitest";
import { buildMongoCompletionItemsFromContext, getMongoDocumentQueryCompletionContext, plainMongoCompletionInsertion, shouldAutoOpenMongoDocumentQueryCompletion, type MongoCompletionField } from "@/lib/mongo/mongoCompletion";
const FIELDS: MongoCompletionField[] = [
{ name: "_id", type: "objectId" },
{ name: "customerShippingAddress", type: "string" },
{ name: "customer.name", type: "string" },
{ name: "createdAt", type: "date" },
{ name: "中文字段", type: "string" },
{ name: "客户 名", type: "string" },
];
function contextAt(text: string, kind: "filter" | "sortKeys" = "filter", cursor = text.length) {
return getMongoDocumentQueryCompletionContext(text, cursor, kind);
}
function labelsAt(text: string, kind: "filter" | "sortKeys" = "filter", cursor = text.length) {
return buildMongoCompletionItemsFromContext(contextAt(text, kind, cursor), { fields: FIELDS }).map((item) => item.label);
}
describe("getMongoDocumentQueryCompletionContext", () => {
it("completes fields at the root of a filter document", () => {
expect(contextAt("{ ")).toMatchObject({ mode: "filterField", prefix: "", from: 2 });
expect(labelsAt("{ ")).toEqual(expect.arrayContaining(["_id", "customerShippingAddress", "createdAt"]));
});
it("narrows fields by the typed prefix and reports where to splice it", () => {
expect(contextAt("{ customerS")).toMatchObject({ mode: "filterField", prefix: "customerS", from: 2 });
expect(labelsAt("{ customerS")).toEqual(["customerShippingAddress"]);
});
it("keeps Unicode and quoted spaces in the field prefix and splice range", () => {
expect(contextAt("{ 中")).toMatchObject({ mode: "filterField", prefix: "中", from: 2 });
expect(labelsAt("{ 中")).toEqual(["中文字段"]);
expect(contextAt('{ "客户 名')).toMatchObject({ mode: "filterField", prefix: '"客户 名', from: 2 });
expect(labelsAt('{ "客户 名')).toEqual(["客户 名"]);
});
it("matches fields case-insensitively inside a quoted key", () => {
expect(contextAt('{ "created')).toMatchObject({ mode: "filterField", prefix: '"created', from: 2 });
const items = buildMongoCompletionItemsFromContext(contextAt('{ "created'), { fields: FIELDS });
expect(items.map((item) => item.apply)).toContain('"createdAt": ');
});
it("consumes an existing closing quote so a key is not double-quoted", () => {
expect(contextAt('{ "created"', "filter", 10)).toMatchObject({ prefix: '"created', replaceClosingQuote: '"' });
});
it("offers whole-filter operators once $ is typed", () => {
expect(labelsAt("{ $")).toEqual(expect.arrayContaining(["$and", "$or"]));
});
it("offers query operators inside a field constraint", () => {
expect(contextAt("{ createdAt: { $g")).toMatchObject({ mode: "queryOperator", prefix: "$g" });
expect(labelsAt("{ createdAt: { $g")).toEqual(expect.arrayContaining(["$gt", "$gte"]));
});
it("offers fields again inside an $and branch and after a comma", () => {
expect(contextAt("{ $and: [{ ")).toMatchObject({ mode: "filterField" });
expect(contextAt("{ _id: 1, ")).toMatchObject({ mode: "filterField" });
});
it("offers value constructors in value position", () => {
expect(contextAt("{ _id: ")).toMatchObject({ mode: "value" });
expect(labelsAt("{ _id: ")).toEqual(expect.arrayContaining(["ObjectId"]));
});
it("says nothing inside a string value", () => {
expect(contextAt('{ customerShippingAddress: "Beij')).toMatchObject({ mode: "none" });
});
it("says nothing outside the document", () => {
expect(contextAt("")).toMatchObject({ mode: "none" });
expect(contextAt("{ _id: 1 }")).toMatchObject({ mode: "none" });
expect(contextAt("{ _id: 1 } ")).toMatchObject({ mode: "none" });
expect(contextAt("}")).toMatchObject({ mode: "none" });
});
it("never offers shell snippets a filter bar cannot hold", () => {
// `db.` is a plain token here, not the start of a collection chain.
expect(labelsAt("{ db.")).not.toEqual(expect.arrayContaining(["db.getCollection", "find"]));
});
it("completes sort keys without value or operator noise", () => {
expect(contextAt("{ created", "sortKeys")).toMatchObject({ mode: "field", prefix: "created" });
expect(labelsAt("{ created", "sortKeys")).toEqual(["createdAt"]);
expect(contextAt("{ createdAt: ", "sortKeys")).toMatchObject({ mode: "none" });
expect(contextAt("{ createdAt: -1, ", "sortKeys")).toMatchObject({ mode: "field" });
});
});
describe("plainMongoCompletionInsertion", () => {
it("leaves a plain key completion untouched, caret at the end", () => {
expect(plainMongoCompletionInsertion("createdAt: ")).toEqual({ text: "createdAt: ", selectionStart: 11, selectionEnd: 11 });
});
it("drops an empty snippet marker and leaves the caret in its place", () => {
expect(plainMongoCompletionInsertion("$gt: ${}")).toEqual({ text: "$gt: ", selectionStart: 5, selectionEnd: 5 });
expect(plainMongoCompletionInsertion("$in: [${}]")).toEqual({ text: "$in: []", selectionStart: 6, selectionEnd: 6 });
});
it("selects a named placeholder so its default can be typed over", () => {
expect(plainMongoCompletionInsertion('$regex: "${pattern}"')).toEqual({ text: '$regex: "pattern"', selectionStart: 9, selectionEnd: 16 });
});
it("drops the key separator when the text it lands in already has one", () => {
expect(plainMongoCompletionInsertion('"createdAt": ', ": 1 }")).toEqual({ text: '"createdAt"', selectionStart: 11, selectionEnd: 11 });
expect(plainMongoCompletionInsertion("createdAt: ", " : 1 }")).toEqual({ text: "createdAt", selectionStart: 9, selectionEnd: 9 });
// Nothing to fold into: the separator is still the completion's job.
expect(plainMongoCompletionInsertion("createdAt: ", " }").text).toBe("createdAt: ");
expect(plainMongoCompletionInsertion("createdAt: ", "").text).toBe("createdAt: ");
// An operator snippet ends at its value, so its own colon must survive.
expect(plainMongoCompletionInsertion("$gt: ${}", ": 1 }").text).toBe("$gt: ");
});
it("expands every marker but only selects the first", () => {
expect(plainMongoCompletionInsertion("$mod: [${divisor}, ${remainder}]")).toEqual({ text: "$mod: [divisor, remainder]", selectionStart: 7, selectionEnd: 14 });
expect(plainMongoCompletionInsertion('$split: [${}, "${,}"]')).toEqual({ text: '$split: [, ","]', selectionStart: 9, selectionEnd: 9 });
});
it("renders every operator table entry without leaving a marker behind", () => {
const applies = buildMongoCompletionItemsFromContext(contextAt("{ createdAt: { "), { fields: FIELDS })
.concat(buildMongoCompletionItemsFromContext(contextAt("{ $"), { fields: FIELDS }))
.concat(buildMongoCompletionItemsFromContext(contextAt("{ createdAt: "), { fields: FIELDS }))
.map((item) => item.apply ?? item.label);
expect(applies.length).toBeGreaterThan(20);
for (const apply of applies) {
const insertion = plainMongoCompletionInsertion(apply);
expect(insertion.text, apply).not.toContain("${");
expect(insertion.selectionEnd, apply).toBeLessThanOrEqual(insertion.text.length);
}
});
});
describe("shouldAutoOpenMongoDocumentQueryCompletion", () => {
it("opens on the characters that start a key, an operator, or a value", () => {
for (const text of ["{", "{ ", "{ cre", '{ "cre', "{ 中", '{ "客户 名', "{ $", "{ _id: 1,", "{ createdAt: {", "{ createdAt: "]) {
expect(shouldAutoOpenMongoDocumentQueryCompletion(text, text.length, "filter"), text).toBe(true);
}
});
it("stays closed where there is nothing to say", () => {
for (const text of ["", "{ _id: 1 }", "{ _id: 1 } ", '{ name: "x']) {
expect(shouldAutoOpenMongoDocumentQueryCompletion(text, text.length, "filter"), text).toBe(false);
}
});
});
+157 -7
View File
@@ -247,7 +247,7 @@ export function getMongoCompletionContext(text: string, cursor: number): MongoCo
const safeCursor = Math.max(0, Math.min(cursor, text.length));
const beforeCursor = text.slice(0, safeCursor);
const collection = extractActiveCollection(text, safeCursor);
const { prefix, from } = readPropertyPrefix(text, safeCursor);
const { prefix, from } = readMongoPropertyPrefix(text, safeCursor);
const replaceClosingQuote = closingQuoteAtCursor(prefix, text, safeCursor);
const at = (mode: MongoCompletionMode, stage?: string): MongoCompletionContext => ({ mode, prefix, from, replaceClosingQuote, collection, stage });
@@ -399,6 +399,106 @@ export function shouldAutoOpenMongoCompletion(text: string, cursor: number): boo
return false;
}
/* ------------------------------------------------------------------ *
* Standalone document inputs
* ------------------------------------------------------------------ */
/**
* Which bare document an input holds, and therefore how its keys read: the
* document browser's filter bar is a query document, its sort bar a key map.
*/
export type MongoDocumentQueryKind = "filter" | "sortKeys";
/**
* Completion for an input holding one bare document rather than a shell
* command — the document browser's filter and sort bars.
*
* There is no `db.coll.find(…)` here to locate the cursor within, so the text is
* scanned as if it *were* that call's argument list: `{ na` lands in the query
* document's root object exactly as it would inside `find({ na`. Everything the
* shell path reaches by walking the `db.…` chain (collection names, helper
* methods, cursor methods) is unreachable by construction, which is what we
* want — none of it could be pasted into a filter bar.
*/
export function getMongoDocumentQueryCompletionContext(text: string, cursor: number, kind: MongoDocumentQueryKind): MongoCompletionContext {
const safeCursor = Math.max(0, Math.min(cursor, text.length));
const nothing: MongoCompletionContext = { mode: "none", prefix: "", from: safeCursor };
if (isInsideMongoComment(text, safeCursor)) return nothing;
// Scanning from 0 treats the input as the argument list itself. A `}` that
// closes more than the text opened returns null — the cursor has left the
// document, e.g. it trails a finished `{ a: 1 }`.
const scan = scanMongoCallArguments(text, 0, safeCursor);
if (!scan) return nothing;
const mode = kind === "filter" ? classifyFilter(scan, 0) : classifyKeyMap(scan, 0);
if (mode === "none") return nothing;
const { prefix, from } = readMongoPropertyPrefix(text, safeCursor);
return { mode, prefix, from, replaceClosingQuote: closingQuoteAtCursor(prefix, text, safeCursor) };
}
/** Text to splice into a plain input for a chosen completion, and where to leave the selection. */
export interface MongoPlainCompletionInsertion {
text: string;
/** Start of the selection within `text`, relative to its first character. */
selectionStart: number;
/** End of that selection; equal to the start when the placeholder was empty. */
selectionEnd: number;
}
/**
* Renders an item's `apply` string for a plain `<input>`/`<textarea>`.
*
* Most operator completions are authored as CodeMirror snippets (`$in: [${}]`,
* `$regex: "${pattern}"`), and CodeMirror expands the `${…}` markers itself.
* Nothing does that outside the editor, so strip the markers and hand back the
* span of the first placeholder: an empty one becomes the caret position, a
* named one is selected so its default can be typed straight over.
*
* Key completions carry their own `: ` because they are only offered in key
* position. Pass `followingText` — whatever the input holds after the replaced
* range — so re-picking the key of an existing `{ "name": 1 }` entry replaces
* the key instead of leaving `{ "other": : 1 }` behind.
*/
export function plainMongoCompletionInsertion(apply: string, followingText = ""): MongoPlainCompletionInsertion {
let text = "";
let selection: { start: number; end: number } | null = null;
let rest = apply;
for (;;) {
const match = /\$\{([^{}]*)\}/.exec(rest);
if (!match) break;
const placeholder = match[1] ?? "";
text += rest.slice(0, match.index);
if (!selection) selection = { start: text.length, end: text.length + placeholder.length };
text += placeholder;
rest = rest.slice(match.index + match[0].length);
}
text += rest;
// 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.
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) };
}
/**
* Whether typing the character before the cursor should pop the menu open on its
* own. Mirrors `shouldAutoOpenMongoCompletion` minus the `db.` chain, and
* confirms the position has something to say so a space or a closing brace does
* not reopen an empty menu.
*/
export function shouldAutoOpenMongoDocumentQueryCompletion(text: string, cursor: number, kind: MongoDocumentQueryKind): boolean {
const previousChar = text[cursor - 1];
if (!previousChar) return false;
const context = getMongoDocumentQueryCompletionContext(text, cursor, kind);
if (context.mode === "none") return false;
return context.prefix.length > 0 || /[{[,:]\s*$/.test(text.slice(0, cursor));
}
/**
* How far the editor may keep re-filtering a result before it has to ask us
* again. In the `db.…` chain every `.` moves the cursor to a different item
@@ -910,11 +1010,47 @@ function finalizeQuotedMongoCompletionItems(context: MongoCompletionContext, ite
* Text helpers
* ------------------------------------------------------------------ */
function readPropertyPrefix(text: string, cursor: number): { prefix: string; from: number } {
let from = cursor;
while (from > 0 && /[\w_$.-]/.test(text[from - 1] ?? "")) from--;
if (text[from - 1] === '"' || text[from - 1] === "'") from--;
return { prefix: text.slice(from, cursor), from };
const MONGO_PROPERTY_PREFIX_CHARACTER = /[$.\p{ID_Continue}-]/u;
export function readMongoPropertyPrefix(text: string, cursor: number): { prefix: string; from: number } {
const safeCursor = Math.max(0, Math.min(cursor, text.length));
const quoteStart = findOpenMongoQuoteStart(text, safeCursor);
if (quoteStart !== null) return { prefix: text.slice(quoteStart, safeCursor), from: quoteStart };
let from = safeCursor;
while (from > 0) {
let candidateFrom = from - 1;
const trailingUnit = text.charCodeAt(candidateFrom);
if (trailingUnit >= 0xdc00 && trailingUnit <= 0xdfff && candidateFrom > 0) {
const leadingUnit = text.charCodeAt(candidateFrom - 1);
if (leadingUnit >= 0xd800 && leadingUnit <= 0xdbff) candidateFrom--;
}
const candidate = text.slice(candidateFrom, from);
if (!MONGO_PROPERTY_PREFIX_CHARACTER.test(candidate)) break;
from = candidateFrom;
}
return { prefix: text.slice(from, safeCursor), from };
}
function findOpenMongoQuoteStart(text: string, cursor: number): number | null {
for (let index = 0; index < cursor; index++) {
const char = text[index];
if ((char === "/" && (text[index + 1] === "/" || text[index + 1] === "*")) || (char === "-" && text[index + 1] === "-")) {
const skipped = skipMongoStringOrComment(text, index, cursor);
if (skipped >= cursor) return null;
index = skipped - 1;
continue;
}
if (char !== '"' && char !== "'") continue;
const quoteStart = index;
for (index++; index < cursor; index++) {
if (text[index] === "\\") index++;
else if (text[index] === char) break;
}
if (index >= cursor) return quoteStart;
}
return null;
}
function closingQuoteAtCursor(prefix: string, text: string, cursor: number): '"' | "'" | undefined {
@@ -1116,9 +1252,23 @@ function describeMongoValueType(value: unknown): string {
return mongoExtendedJsonValueType(value) ?? (typeof value === "object" ? "object" : typeof value);
}
/**
* Keys that may be written bare. Anything else has to carry quotes: a nested
* path (`customer.name`) is the common case, but a hyphen or a leading digit
* does it too. `inferMongoCompletionFields` emits a path per nesting level, so
* a collection of nested documents offers mostly non-bare keys.
*/
const BARE_MONGO_KEY = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
/**
* Renders a field name in key position. An unquoted prefix keeps the key bare
* only while the name allows it — `{ customer.name: 1 }` parses neither as a
* shell document nor as the JSON the document browser's query bars are read
* as, so a path is quoted even though the user typed no quote.
*/
function quoteMongoFieldName(field: string, prefix: string): string {
if (prefix.startsWith('"')) return `"${escapeDoubleQuoted(field)}"`;
if (prefix.startsWith("'")) return `'${escapeSingleQuoted(field)}'`;
if (prefix.startsWith('"') || !BARE_MONGO_KEY.test(field)) return `"${escapeDoubleQuoted(field)}"`;
return field;
}