fix(mongodb): use line comments in editor

This commit is contained in:
Võ Văn Thành (Jay) authored and GitHub committed 2026-08-18 23:17:24 +08:00
1 parent 6cbb10439e
commit fa4238c5d3
8 files changed
+370 -4

No files matched your search

@@ -0,0 +1,60 @@
// @vitest-environment happy-dom
import { HighlightStyle, highlightingFor, syntaxHighlighting, syntaxTree } from "@codemirror/language";
import { sql } from "@codemirror/lang-sql";
import { EditorState } from "@codemirror/state";
import { Decoration, EditorView, ViewPlugin } from "@codemirror/view";
import { tags } from "@lezer/highlight";
import { afterEach, describe, expect, it } from "vitest";
import { SHELL_LINE_COMMENT_CLASS, createShellLineCommentHighlight, shellLineCommentClass } from "@/lib/editor/codemirrorShellLineCommentHighlight";
const commentHighlightStyle = HighlightStyle.define([{ tag: tags.lineComment, color: "#6c7086", fontStyle: "italic" }]);
let view: EditorView | null = null;
afterEach(() => {
view?.destroy();
view = null;
});
function mount(doc: string, extensions: import("@codemirror/state").Extension[] = []) {
view = new EditorView({
state: EditorState.create({
doc,
extensions: [sql(), ...extensions, createShellLineCommentHighlight({ ViewPlugin, Decoration, highlightingFor, syntaxTree })],
}),
parent: document.body,
});
return view;
}
describe("createShellLineCommentHighlight", () => {
it("decorates // comments that the SQL grammar leaves untokenized", () => {
const editor = mount('// list users\ndb.sites.insertOne({ url: "https://example.com" })');
const decorated = Array.from(editor.dom.querySelectorAll(`.${SHELL_LINE_COMMENT_CLASS}`)).map((node) => node.textContent);
expect(decorated).toEqual(["// list users"]);
});
it("does not decorate // inside parsed block comments or strings", () => {
const editor = mount('/* hidden // marker */\nSELECT "https://example.com";\n// shown');
const decorated = Array.from(editor.dom.querySelectorAll(`.${SHELL_LINE_COMMENT_CLASS}`)).map((node) => node.textContent);
expect(decorated).toEqual(["// shown"]);
});
it("carries the active theme's comment class so // matches SQL --", () => {
const editor = mount("// list users", [syntaxHighlighting(commentHighlightStyle)]);
const themeClass = highlightingFor(editor.state, [tags.lineComment]);
const node = editor.dom.querySelector(`.${SHELL_LINE_COMMENT_CLASS}`);
expect(themeClass).toBeTruthy();
expect(node?.className.split(" ")).toContain(themeClass?.split(" ")[0]);
});
it("falls back to the bare class when the theme styles no comments", () => {
const state = EditorState.create({ doc: "// list users", extensions: [sql()] });
expect(shellLineCommentClass(state, highlightingFor)).toBe(SHELL_LINE_COMMENT_CLASS);
});
});
@@ -0,0 +1,87 @@
import { readFileSync } from "node:fs";
import { toggleLineComment } from "@codemirror/commands";
import { sql } from "@codemirror/lang-sql";
import { EditorState, Prec, type Transaction } from "@codemirror/state";
import { describe, expect, it, vi } from "vitest";
import { queryEditorCommentTokens, queryEditorLineCommentToken } from "@/lib/editor/queryEditorLineComment";
const queryEditorSource = readFileSync(new URL("../../../components/editor/QueryEditor.vue", import.meta.url), "utf8");
const editorThemesSource = readFileSync(new URL("../../editor/editorThemes.ts", import.meta.url), "utf8");
const shellHighlightSource = readFileSync(new URL("../../editor/codemirrorShellLineCommentHighlight.ts", import.meta.url), "utf8");
function runToggleLineComment(doc: string, commentToken: string) {
let state = EditorState.create({
doc,
selection: { anchor: 0 },
extensions: [sql(), Prec.highest(EditorState.languageData.of(() => [{ commentTokens: { line: commentToken } }]))],
});
const dispatch = vi.fn((transaction: Transaction) => {
state = transaction.state;
});
const handled = toggleLineComment({
get state() {
return state;
},
dispatch,
} as never);
return { handled, state };
}
describe("queryEditorLineCommentToken", () => {
it("uses the MongoDB shell line comment marker", () => {
expect(queryEditorLineCommentToken("mongodb")).toBe("//");
});
it("keeps block comment tokens while overriding MongoDB line comments", () => {
expect(queryEditorCommentTokens("mongodb")).toEqual({
line: "//",
block: { open: "/*", close: "*/" },
});
});
it("keeps the SQL line comment marker elsewhere", () => {
expect(queryEditorLineCommentToken(undefined)).toBe("--");
expect(queryEditorLineCommentToken("mysql")).toBe("--");
expect(queryEditorLineCommentToken("postgres")).toBe("--");
});
});
describe("QueryEditor line comment", () => {
it("overrides the language comment tokens in the SQL language compartment", () => {
expect(queryEditorSource).toContain("Prec.highest(EditorState.languageData.of(() => [{ commentTokens: queryEditorCommentTokens(props.databaseType) }]))");
});
it("highlights // comments with the theme's comment style", () => {
expect(queryEditorSource).toContain('queryEditorLineCommentToken(props.databaseType) === "//" ? shellLineCommentHighlightPlugin : []');
expect(queryEditorSource).toContain("const shellLineCommentHighlightPlugin = createShellLineCommentHighlight({ ViewPlugin, Decoration, highlightingFor, syntaxTree });");
expect(queryEditorSource).toContain("shellLineCommentTheme(EditorView),");
expect(editorThemesSource).toContain('".cm-shell-line-comment *"');
expect(editorThemesSource).toContain('color: "inherit !important"');
});
it("bounds shell comment scanning to syntax-aware visible lines", () => {
expect(shellHighlightSource).toContain("view.state.doc.lineAt(visibleRange.from).from");
expect(shellHighlightSource).toContain("tree.resolveInner(absoluteFrom, 1)");
expect(shellHighlightSource).not.toContain("sliceString(0, end)");
});
it("comments a MongoDB line with //", () => {
const result = runToggleLineComment("db.users.find({})", "//");
expect(result.handled).toBe(true);
expect(result.state.doc.toString()).toBe("// db.users.find({})");
});
it("uncomments a MongoDB line commented with //", () => {
const result = runToggleLineComment("// db.users.find({})", "//");
expect(result.state.doc.toString()).toBe("db.users.find({})");
});
it("still comments SQL with --", () => {
const result = runToggleLineComment("SELECT 1", "--");
expect(result.state.doc.toString()).toBe("-- SELECT 1");
});
});
@@ -0,0 +1,43 @@
import { describe, expect, it } from "vitest";
import { shellLineCommentRanges } from "@/lib/editor/shellLineCommentRanges";
function commentTexts(doc: string): string[] {
return shellLineCommentRanges(doc).map((range) => doc.slice(range.from, range.to));
}
describe("shellLineCommentRanges", () => {
it("finds a whole-line comment", () => {
expect(commentTexts("// list users\ndb.users.find({})")).toEqual(["// list users"]);
});
it("finds a trailing comment and stops at the line end", () => {
expect(commentTexts("db.users.find({}) // only active\ndb.users.count()")).toEqual(["// only active"]);
});
it("ignores // inside quoted strings", () => {
expect(commentTexts('db.sites.insertOne({ url: "https://example.com" })')).toEqual([]);
expect(commentTexts("db.sites.insertOne({ url: 'https://example.com' })")).toEqual([]);
expect(commentTexts("db.sites.insertOne({ url: `https://example.com` })")).toEqual([]);
});
it("ignores // inside block comments", () => {
expect(commentTexts("/* db.users.find({}) // stale */\ndb.users.count()")).toEqual([]);
});
it("handles escaped quotes without swallowing the rest of the document", () => {
expect(commentTexts('db.t.find({ a: "x\\"y" }) // note')).toEqual(["// note"]);
});
it("does not let an unterminated quote hide later comments", () => {
expect(commentTexts('db.t.find({ a: "oops\n// note')).toEqual(["// note"]);
});
it("keeps carriage returns out of the range", () => {
expect(commentTexts("// note\r\ndb.users.count()")).toEqual(["// note"]);
});
it("respects the scan limit", () => {
const doc = "db.a.find()\n// second line";
expect(shellLineCommentRanges(doc, doc.indexOf("//"))).toEqual([]);
});
});