The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
import { metaKey } from "./e2e-browser-helpers";
type TypeOptions = {
delay?: number;
focus?: boolean;
allowFastSet?: boolean;
};
export function codeMirrorHelpers<T extends object>(testId: string, extra: T) {
const helpers = {
get() {
cy.findAllByTestId("loading-indicator").should("not.exist");
return cy.get(`[data-testid=${testId}] .cm-content`);
},
focus() {
helpers.get().should("be.visible").click("right", {
/**
* We want to click on the right, because we want the caret to be positioned at the end of the editor.
* Alternative approach with pressing End key for moving the caret to the end made
* repro for (metabase#49882-2, metabase#15892) fail in CI every time.
* Hence force: true.
*/
force: true,
});
helpers.get().get(".cm-editor").should("have.class", "cm-focused");
return helpers;
},
blur() {
helpers.get().get(".cm-content").blur();
return helpers;
},
selectAll() {
helpers.focus();
cy.realPress([metaKey, "A"]);
return helpers;
},
clear() {
helpers.selectAll();
cy.realPress(["Backspace"]);
return helpers;
},
type(
text: string,
{ focus = true, delay = 10, allowFastSet = false }: TypeOptions = {},
) {
if (focus) {
helpers.focus();
} else {
// The editor can be a lazily loaded chunk, so it may still be mounting.
// Wait for it to hold focus before typing, or the first keystroke goes
// nowhere. Do not click it: that would move the caret.
helpers.get().get(".cm-editor").should("have.class", "cm-focused");
}
if (allowFastSet) {
// Enter the formula in one go
// HACK: we do invoke("text") instead of type() because type() does not work on
// CodeMirror elements in Cypress. realType() would work but some of the formulas
// contain special characters that are not supported by realType().
helpers.get().invoke("text", text);
// invoke("text") does not trigger the validator, so we need to trigger it manually
// by typing something
helpers.type(" {backspace}");
return helpers;
}
const parts = text.replaceAll("{{", "{{}{{}").split(/(\{[^}]+\})/);
function insert(text: string) {
cy.realType(text, { pressDelay: delay });
}
// HACK: realType does not accept a lot of common escape sequences,
// so we implement them manually here for the native editor.
parts.forEach((part) => {
switch (part.toLowerCase()) {
case "":
return;
case "{clear}":
return helpers.clear();
case "{selectall}":
return helpers.selectAll();
case "{leftarrow}":
return cy.realPress(["ArrowLeft"]);
case "{rightarrow}":
return cy.realPress(["ArrowRight"]);
case "{downarrow}":
return cy.realPress(["ArrowDown"]);
case "{uparrow}":
return cy.realPress(["ArrowUp"]);
case "{enter}":
return cy.realPress(["Enter"]);
case "{home}":
case "{movetostart}":
return cy.realPress(["Home"]);
case "{end}":
case "{movetoend}":
return cy.realPress(["End"]);
case "{backspace}":
return cy.realPress(["Backspace"]);
case "{tab}":
return cy.realPress(["Tab"]);
case "{nextcompletion}":
cy.wait(50);
return cy.realPress([metaKey, "j"]);
case "{prevcompletion}":
cy.wait(50);
return cy.realPress([metaKey, "k"]);
case "{{}":
return cy.realType("{");
}
if (part.startsWith("{") && part.endsWith("}")) {
// unknown escape sequence, let's try typing it
insert("{");
insert(part.slice(1));
return;
}
// realType does not support → arrow, so we replace it with ->, which the editor
// expands into →
const unexpanded = part.replaceAll(/→/g, "->");
const alphabet =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789^[]()-,.;_!@#$%&*+=/<>\" ':;\\\n{}";
if (unexpanded.split("").some((char) => !alphabet.includes(char))) {
throw new Error(
`unknown character in codeMirrorHelpers.type in ${part}`,
);
}
insert(unexpanded);
});
return helpers;
},
textbox() {
return helpers.get().get("[role='textbox']");
},
value() {
// `invoke` chains are queries, so a chained assertion re-reads the text on every retry
return helpers
.get()
.invoke("find", ".cm-line")
.invoke("toArray")
.invoke("filter", (line) => !line.querySelector(".cm-placeholder"))
.invoke("map", (line) => line.textContent ?? "")
.invoke("join", "\n");
},
completions() {
return cy.get(".cm-tooltip-autocomplete").should("be.visible");
},
completion(label: string) {
return cy.get(".cm-completionLabel").contains(label).parent();
},
completionLabels(label: string) {
return cy
.get(".cm-completionLabel")
.filter((_, element) => element.textContent === label);
},
acceptCompletion(key: "enter" | "tab" = "enter") {
helpers.completions().should("be.visible");
// Avoid flakiness with CodeMirror not accepting the suggestion immediately
cy.wait(300);
helpers.type(`{${key}}`, { focus: false });
},
rejectCompletion() {
helpers.completions().should("be.visible");
// Avoid flakiness with CodeMirror not processing the escape immediately
cy.wait(300);
cy.realPress(["Escape"]);
},
selectCompletion(name: string) {
helpers.completions().should("be.visible");
// Avoid flakiness with CodeMirror not accepting the suggestion immediately
cy.wait(300);
helpers.completion(name).click();
},
paste(content: string) {
helpers.textbox().then((el) => {
const clipboardData = new DataTransfer();
clipboardData.setData("text/plain", content);
const pasteEvent = new ClipboardEvent("paste", {
bubbles: true,
cancelable: true,
clipboardData,
});
el[0].dispatchEvent(pasteEvent);
});
},
...extra,
};
return helpers;
}
export function codeMirrorEditor() {
return cy.get(".cm-content");
}
export function codeMirrorValue() {
// Get the multiline text content of the editor
return codeMirrorEditor()
.get("[role='textbox']")
.get(".cm-line")
.then((lines) => {
const text: string[] = [];
lines.each((_, line) => {
text.push(line.textContent ?? "");
});
const value = text.join("\n");
const placeholder = "SELECT * FROM TABLE_NAME";
if (value === placeholder) {
return "";
}
return value;
});
}