|
| 1 | +import { Controller } from "@hotwired/stimulus" |
| 2 | +import CodeMirror from "codemirror" |
| 3 | +import "codemirror/mode/ruby/ruby" |
| 4 | +import "codemirror/mode/yaml/yaml" |
| 5 | +import "codemirror/lib/codemirror.css" |
| 6 | +import "codemirror/theme/monokai.css" |
| 7 | + |
| 8 | +export default class extends Controller { |
| 9 | + static values = { |
| 10 | + mode: String, |
| 11 | + readonly: { type: Boolean, default: false } |
| 12 | + } |
| 13 | + |
| 14 | + connect() { |
| 15 | + const config = { |
| 16 | + mode: this.modeValue || "ruby", |
| 17 | + theme: "monokai", |
| 18 | + lineNumbers: true, |
| 19 | + lineWrapping: true, |
| 20 | + readOnly: this.readonlyValue, |
| 21 | + tabSize: 2, |
| 22 | + indentWithTabs: false, |
| 23 | + viewportMargin: Infinity, |
| 24 | + scrollbarStyle: null, |
| 25 | + fixedGutter: true, |
| 26 | + gutters: ["CodeMirror-linenumbers"] |
| 27 | + } |
| 28 | + |
| 29 | + if (!this.readonlyValue) { |
| 30 | + config.autofocus = true |
| 31 | + config.extraKeys = { |
| 32 | + "Tab": (cm) => { |
| 33 | + if (cm.somethingSelected()) { |
| 34 | + cm.indentSelection("add") |
| 35 | + } else { |
| 36 | + cm.replaceSelection(" ", "end") |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + // For read-only mode, we need to create a new div and set its content |
| 43 | + if (this.readonlyValue) { |
| 44 | + const content = this.element.textContent.trim() |
| 45 | + this.element.textContent = "" |
| 46 | + this.editor = CodeMirror(this.element, { |
| 47 | + ...config, |
| 48 | + value: content |
| 49 | + }) |
| 50 | + } else { |
| 51 | + this.editor = CodeMirror.fromTextArea(this.element, config) |
| 52 | + } |
| 53 | + |
| 54 | + if (!this.readonlyValue) { |
| 55 | + this.editor.on("change", () => { |
| 56 | + this.element.value = this.editor.getValue() |
| 57 | + this.element.dispatchEvent(new Event("input")) |
| 58 | + }) |
| 59 | + } |
| 60 | + |
| 61 | + // Refresh after initialization to ensure proper rendering |
| 62 | + setTimeout(() => this.editor.refresh(), 1) |
| 63 | + } |
| 64 | + |
| 65 | + disconnect() { |
| 66 | + if (this.editor) { |
| 67 | + if (!this.readonlyValue) { |
| 68 | + this.editor.toTextArea() |
| 69 | + } |
| 70 | + this.editor = null |
| 71 | + } |
| 72 | + } |
| 73 | +} |
0 commit comments