-
-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathcode_editor_controller.js
More file actions
241 lines (204 loc) · 7.19 KB
/
code_editor_controller.js
File metadata and controls
241 lines (204 loc) · 7.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import { Controller } from "@hotwired/stimulus"
import { EditorView, basicSetup } from "codemirror"
import { EditorState, StateField, StateEffect, Compartment } from "@codemirror/state"
import { Decoration } from "@codemirror/view"
import { keymap } from "@codemirror/view"
import { php } from "@codemirror/lang-php"
import { autocompletion, snippetKeymap, acceptCompletion } from "@codemirror/autocomplete"
import { indentWithTab } from "@codemirror/commands"
import { flowThemeExtension, flowLightThemeExtension } from "../codemirror/themes/theme-flow.js"
import { flowCompletions } from "../codemirror/completions/flow.js"
import { dslCompletions } from "../codemirror/completions/dsl.js"
import { dataframeCompletions } from "../codemirror/completions/dataframe.js"
import { scalarFunctionChainCompletions } from "../codemirror/completions/scalarfunctionchain.js"
import Violation from "../models/Violation.js"
export default class extends Controller {
#editor
#debug = false
#textarea
#errorEffect
#editorReady = false
#themeCompartment = new Compartment()
#onThemeChanged = null
#log(...args) {
if (this.#debug) {
console.log('[CodeEditor]', ...args)
}
}
#initializeEditor() {
this.#textarea = this.element
const initialValue = this.#textarea.value
const editorDiv = document.createElement('div')
editorDiv.style.width = '100%'
editorDiv.style.height = this.#textarea.style.height || '600px'
this.#textarea.style.display = 'none'
this.#textarea.parentNode.insertBefore(editorDiv, this.#textarea)
this.#errorEffect = StateEffect.define()
const errorEffect = this.#errorEffect
const errorField = StateField.define({
create() {
return Decoration.none
},
update(errors, tr) {
errors = errors.map(tr.changes)
for (const effect of tr.effects) {
if (effect.is(errorEffect)) {
errors = effect.value
}
}
return errors
},
provide: f => EditorView.decorations.from(f)
})
const state = EditorState.create({
doc: initialValue,
extensions: [
basicSetup,
php(),
this.#themeCompartment.of(this.#currentThemeExtension()),
errorField,
keymap.of(snippetKeymap),
keymap.of([indentWithTab]),
autocompletion({
override: [flowCompletions, dataframeCompletions, scalarFunctionChainCompletions, dslCompletions],
activateOnTyping: true,
maxRenderedOptions: 20
}),
EditorView.updateListener.of((update) => {
if (update.docChanged) {
this.#textarea.value = update.state.doc.toString()
this.dispatch('code-changed', { bubbles: true })
}
})
]
})
this.#editor = new EditorView({
state,
parent: editorDiv
})
this.#editorReady = true
this.#log('Code editor initialized')
}
connect() {
this.#debug = this.application.debug
this.#log('Connecting Code editor controller')
this.#initializeEditor()
this.#onThemeChanged = this.#handleThemeChange.bind(this)
document.addEventListener('theme:changed', this.#onThemeChanged)
}
#currentThemeExtension() {
return document.documentElement.getAttribute('data-theme') === 'dark'
? flowThemeExtension
: flowLightThemeExtension
}
#handleThemeChange() {
if (!this.#editor) return
this.#editor.dispatch({
effects: this.#themeCompartment.reconfigure(this.#currentThemeExtension())
})
}
isReady() {
return this.#editorReady && this.#editor !== null
}
isLoaded() {
return this.#editorReady && this.#editor !== null
}
async onLoad() {
if (this.isLoaded()) return Promise.resolve()
return new Promise(resolve => {
const check = setInterval(() => {
if (this.isLoaded()) {
clearInterval(check)
resolve()
}
}, 50)
})
}
disconnect() {
if (this.#onThemeChanged) {
document.removeEventListener('theme:changed', this.#onThemeChanged)
}
if (this.#editor) {
this.#editor.destroy()
this.#editor = null
}
}
getCode() {
return this.#editor ? this.#editor.state.doc.toString() : ''
}
setCode(code) {
this.#log('setCode called with code length:', code?.length)
if (this.#editor) {
this.#log('Setting code immediately')
this.#editor.dispatch({
changes: {
from: 0,
to: this.#editor.state.doc.length,
insert: code
}
})
}
}
setValue(code) {
this.setCode(code)
}
highlightError(errorInfo) {
this.#log('highlightError called with:', errorInfo)
if (!this.#editor || !errorInfo) {
this.#log('No editor or errorInfo:', { hasEditor: !!this.#editor, errorInfo })
return
}
this.clearErrors()
const { line, type, message } = errorInfo
if (!line) {
this.#log('No line number in errorInfo')
return
}
this.#log('Highlighting line:', line, 'with message:', message)
const violation = Violation.create({
message: `${type}: ${message}`,
line: line,
column: 0,
startLine: line,
endLine: line,
startColumn: 0,
endColumn: Number.MAX_SAFE_INTEGER
})
const decorations = []
const doc = this.#editor.state.doc
try {
const from = violation.getStartPosition(doc)
const to = violation.getEndPosition(doc)
if (from < to && from >= 0 && to <= doc.length) {
decorations.push(
Decoration.mark({
class: 'cm-error',
attributes: { title: violation.message }
}).range(from, to)
)
}
} catch (error) {
console.warn('Failed to highlight error:', violation, error)
}
if (decorations.length > 0) {
this.#editor.dispatch({
effects: this.#errorEffect.of(Decoration.set(decorations))
})
const editorLine = line - 1
const lineObj = doc.line(editorLine + 1)
this.#editor.dispatch({
selection: { anchor: lineObj.from },
scrollIntoView: true
})
}
}
clearErrors() {
if (!this.#editor) {
return
}
this.#log('Clearing errors')
this.#editor.dispatch({
effects: this.#errorEffect.of(Decoration.none)
})
}
}