Page MenuHomeSealhub

monaco.stimulus.ts
No OneTemporary

Authored By
Unknown
Size
12 KB
Referenced Files
None
Subscribers
None

monaco.stimulus.ts

/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/consistent-type-assertions */
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-call */
import { Controller } from "stimulus";
import { debounce } from "throttle-debounce";
import { addJS } from "@sealcode/add-to-head";
const FONT_FAMILY =
"Menlo, Consolas, Monaco, Adwaita Mono, Liberation Mono, Lucida Console, monospace";
const BORDER_STYLE = "1px solid black";
declare global {
interface Window {
monaco: typeof import("monaco-editor");
}
interface HTMLTextAreaElement {
setHTML: (s: string) => void;
}
}
declare const require: any;
type MonacoEditor =
import("monaco-editor/esm/vs/editor/editor.api").editor.IStandaloneCodeEditor;
export default class extends Controller<HTMLDivElement> {
editor: MonacoEditor | null = null;
resizeObserver: ResizeObserver | null = null;
textareaObserver: MutationObserver | null = null;
static targets = ["languageInput", "textarea", "wrapper"];
declare textareaTarget: HTMLTextAreaElement;
declare languageInputTarget: HTMLInputElement;
declare wrapperTarget: HTMLDivElement;
defaultRowsNumber = 20;
private lastWidth = 0; // track last width
private language = "markdown";
private scripts_ready = false;
private hideTimeout: number | null = null;
activateEditor() {
if (!this.scripts_ready) {
return;
}
if (this.editor) {
return;
}
this.activateToolbar();
this.textareaTarget.style.display = "none";
this.preventScroll();
const container = this.wrapperTarget;
const monacoEditor = window.monaco.editor;
this.editor = monacoEditor.create(container, {
value: this.textareaTarget?.textContent?.trim() || "",
language: this.element.getAttribute("data-language") || "markdown",
automaticLayout: true,
minimap: { enabled: false },
scrollbar: {
vertical: "hidden",
useShadows: false,
verticalScrollbarSize: 0,
horizontalScrollbarSize: 0,
},
scrollBeyondLastLine: false,
lineNumbers: "off",
wordWrap: "on",
glyphMargin: false,
folding: false,
lineDecorationsWidth: 0,
lineNumbersMinChars: 0,
overviewRulerLanes: 0,
hideCursorInOverviewRuler: true,
padding: {
top: 0,
bottom: 0,
},
fontFamily: FONT_FAMILY,
wordWrapColumn: 0,
wrappingIndent: "none",
});
this.editor.onDidBlurEditorText(this.maybeDeactivateEditor);
this.editor.onDidFocusEditorText(() => {
if (this.hideTimeout) {
window.clearTimeout(this.hideTimeout);
}
this.hideTimeout = null;
});
const inner_container: HTMLDivElement =
container.querySelector(".monaco-editor")!;
inner_container.setAttribute("data-turbo-permanent", "");
const updateTextareaValue = debounce(30, () => {
if (this.textareaTarget && this.editor) {
const editorValue = this.editor.getValue();
if (editorValue == this.textareaTarget.innerHTML) {
return;
}
if (this.textareaTarget.setHTML) {
// https://developer.mozilla.org/en-US/docs/Web/API/Element/setHTML
this.textareaTarget.setHTML(this.editor.getValue());
} else {
this.textareaTarget.innerHTML = this.editor.getValue();
}
// for some reason it's necessary, because value can be different than inner html????
this.textareaTarget.value = this.editor.getValue();
}
});
this.editor?.onDidChangeModelContent(() => {
updateTextareaValue();
this.updateHeight();
});
this.lastWidth = container.clientWidth;
this.resizeObserver = new ResizeObserver(() => {
const currentWidth = container.clientWidth;
if (currentWidth !== this.lastWidth) {
this.lastWidth = currentWidth;
this.editor?.layout();
}
this.updateHeight();
});
this.resizeObserver.observe(container);
this.textareaObserver = new MutationObserver(this.onTextareaChange.bind(this));
this.textareaObserver.observe(this.textareaTarget, {
childList: true,
characterData: true,
subtree: true,
});
this.editor.focus();
this.editor.getContainerDomNode().focus();
(
this.editor
.getContainerDomNode()
.querySelector(".overflow-guard") as HTMLDivElement
)?.style.setProperty("border", BORDER_STYLE);
/* the below two listeners are necessary to preseve monaco behavior while Turbo is morhping */
this.element.addEventListener("turbo:before-morph-attribute", (event) => {
if ((event as any).detail.attributeName == "data-keybinding-context") {
return event.preventDefault();
}
if (event.target == this.textareaTarget) {
return event.preventDefault();
}
});
this.element.addEventListener("turbo:before-morph-element", (event) => {
const classList = (event.target as HTMLDivElement).classList;
if (classList.contains("toolbar")) {
return event.preventDefault();
}
});
this.element.addEventListener("turbo:morph-element", (event) => {
if (event.target == this.textareaTarget) {
// because the innerhtml may have been morphed and we need to sync the .value into the textarea.
// innerHTML is only the initial state, not the actual value
this.onTextareaChange();
}
});
}
updateHeight() {
if (this.editor) {
const lineHeight = this.editor.getOption(
window.monaco.editor.EditorOption.lineHeight
);
const contentHeight = this.editor.getContentHeight();
const lines_count = Math.round(contentHeight / lineHeight);
this.wrapperTarget.style.height = `${(lines_count + 1) * lineHeight}px`;
this.editor.layout();
}
}
onTextareaChange() {
// again, sometimes the value and innerhtml can get desynced and we need to bring them into sync
this.textareaTarget.value = this.textareaTarget.innerHTML;
if (this.textareaTarget && this.editor) {
const editorValue = this.editor.getValue();
if (editorValue == this.textareaTarget.innerHTML) {
return;
}
this.editor.setValue(this.textareaTarget.innerHTML);
this.editor?.layout();
}
}
preventScroll() {
// monaco captures scroll events and it's annoying when we want to scroll the
// entire sidebar. We don't use internal scrolling within monaco (it autogrows) so
// let's just disable the wheel event before it's added to the dom node by monaco
this.wrapperTarget.addEventListener(
"wheel",
(e) => {
e.stopImmediatePropagation();
},
true // capture phase
);
}
wrapSelection(event: MouseEvent) {
const target = event.currentTarget;
if (!(target instanceof HTMLElement)) return;
const dataset = target.dataset;
if (dataset.wrap) {
this.wrapSelectedText(dataset.wrap);
}
if (dataset.wrapBefore || dataset.wrapAfter) {
this.wrapSelectedText(dataset.wrapBefore ?? "", dataset.wrapAfter ?? "");
}
if (dataset.prefix) {
this.prefixSelectedText(dataset.prefix);
}
// in order to cancel the editor deactivation timeout:
this.editor?.focus();
}
wrapSelectedText(before: string, after = before) {
if (!this.editor) return;
const model = this.editor?.getModel();
if (!model) return;
let selection = this.editor.getSelection();
if (!selection) return;
let startLine = selection.startLineNumber;
let endLine = selection.endLineNumber;
if (selection.isEmpty()) {
while (startLine > 1 && model.getLineContent(startLine - 1).trim() !== "") {
startLine--;
}
const lineCount = model.getLineCount();
while (
endLine < lineCount &&
model.getLineContent(endLine + 1).trim() !== ""
) {
endLine++;
}
const firstLineContent = model.getLineContent(startLine);
const prefixMatch = firstLineContent.match(/^(\s*(?:>|#+|-)\s*)/);
const startColumn = prefixMatch ? prefixMatch[0].length + 1 : 1;
selection = new window.monaco.Selection(
startLine,
startColumn,
endLine,
model.getLineMaxColumn(endLine)
);
}
const selectedText = model.getValueInRange(selection);
const newText = before + selectedText + after;
this.editor.executeEdits("wrap", [
{
range: selection,
text: newText,
forceMoveMarkers: true,
},
]);
const pos = selection.getStartPosition();
if (after == "]()") {
this.editor.setPosition({
lineNumber: pos.lineNumber,
column: pos.column + (before + selectedText).length + 2,
});
}
this.editor.focus();
}
prefixSelectedText(prefix: string) {
if (!this.editor) return;
const model = this.editor?.getModel();
if (!model) return;
let selection = this.editor.getSelection();
if (!selection) return;
let startLine = selection.startLineNumber;
let endLine = selection.endLineNumber;
if (selection.isEmpty()) {
while (startLine > 1 && model.getLineContent(startLine - 1).trim() !== "") {
startLine--;
}
const lineCount = model.getLineCount();
while (
endLine < lineCount &&
model.getLineContent(endLine + 1).trim() !== ""
) {
endLine++;
}
selection = new window.monaco.Selection(
startLine,
1,
endLine,
model.getLineMaxColumn(endLine)
);
}
const selectedText = model.getValueInRange(selection);
let newText;
if (prefix == "#") {
const lines = selectedText.split("\n");
newText = lines
.map((line) =>
line.trim() === "" ? line : this.insertQuotePrefix(line, prefix)
)
.join("\n");
} else {
let atParagraphStart = true;
newText = selectedText
.split("\n")
.map((line) => {
if (line.trim() === "") {
atParagraphStart = true;
return line;
}
if (atParagraphStart) {
atParagraphStart = false;
if (this.isIntegerOrIntegerString(prefix)) {
const old_prefix = prefix;
prefix = String(parseInt(prefix) + 1);
return this.insertQuotePrefix(line, old_prefix + ". ");
} else {
return this.insertQuotePrefix(line, prefix);
}
}
return line;
})
.join("\n");
}
this.editor.executeEdits("wrap", [
{
range: selection,
text: newText,
forceMoveMarkers: true,
},
]);
this.editor.focus();
}
insertQuotePrefix(line: string, prefix: string): string {
const match = line.match(/^(\s*(?:>\s*)+)(.*)$/);
if (!match) {
return prefix + " " + line;
}
const quotePart = match[1];
const textPart = match[2];
return quotePart + prefix + " " + textPart;
}
isIntegerOrIntegerString(value: unknown): boolean {
if (typeof value === "number" && Number.isInteger(value)) {
return true;
}
if (typeof value === "string" && /^[+-]?\d+$/.test(value.trim())) {
return true;
}
return false;
}
setTextareaStyles() {
this.textareaTarget.style.fontSize = "14px";
this.textareaTarget.style.paddingTop = "1px";
this.textareaTarget.style.paddingBottom = "16px";
this.textareaTarget.style.paddingRight = "5px";
this.textareaTarget.style.display = "block";
this.textareaTarget.style.fontFamily = `${FONT_FAMILY}`;
this.textareaTarget.style.margin = "0";
this.textareaTarget.style.border = BORDER_STYLE;
this.textareaTarget.style.lineHeight = "19px";
this.textareaTarget.style.height = "100%";
this.textareaTarget.style.fieldSizing = "content";
}
async connect() {
this.setTextareaStyles();
this.activateEditor = this.activateEditor.bind(this);
this.deactivateEditor = this.deactivateEditor.bind(this);
this.maybeDeactivateEditor = this.maybeDeactivateEditor.bind(this);
this.textareaTarget.addEventListener("focus", this.activateEditor);
this.textareaTarget.addEventListener("mouseenter", this.activateEditor);
await addJS(`${location.origin}/dist/monaco-editor/min/vs/loader.js`);
this.deactivateToolbar();
if (!window.monaco?.editor) {
require.config({
paths: {
vs: `${location.origin}/dist/monaco-editor/min/vs`,
},
});
require(["vs/editor/editor.main"], () => {
this.scripts_ready = true;
});
return;
} else {
this.scripts_ready = true;
}
}
deactivateToolbar() {
(this.element.querySelector(".toolbar") as HTMLDivElement).style.opacity = "0.5";
(this.element.querySelector(".toolbar") as HTMLDivElement).style.pointerEvents =
"none";
}
activateToolbar() {
(this.element.querySelector(".toolbar") as HTMLDivElement).style.opacity = "1";
(this.element.querySelector(".toolbar") as HTMLDivElement).style.pointerEvents =
"all";
}
deactivateEditor() {
this.textareaTarget.style.display = "block";
this.textareaTarget.style.paddingTop = "0.5px";
this.editor?.dispose();
this.editor = null;
this.deactivateToolbar();
this.setTextareaStyles();
}
maybeDeactivateEditor() {
this.hideTimeout = window.setTimeout(() => this.deactivateEditor(), 100);
}
disconnect() {
this.deactivateEditor();
this.textareaTarget.removeEventListener("focus", this.activateEditor);
this.textareaTarget.removeEventListener("mouseenter", this.activateEditor);
if (this.resizeObserver) {
this.resizeObserver.disconnect();
this.resizeObserver = null;
}
}
languageChange() {
const model = this?.editor?.getModel();
if (!model) return;
const language = this.languageInputTarget.value;
window.monaco.editor.setModelLanguage(model, language);
}
}

File Metadata

Mime Type
application/javascript
Expires
Fri, Nov 27, 17:12 (1 d, 20 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1229198
Default Alt Text
monaco.stimulus.ts (12 KB)

Event Timeline