forked from openhab/openhab-webui
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathscript-editor.vue
337 lines (309 loc) · 11.4 KB
/
script-editor.vue
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
<template>
<codemirror :value="value" @input="onCmCodeChange" ref="cm" class="code-editor-fit" :options="cmOptions" @ready="onCmReady" />
</template>
<style lang="stylus">
.code-editor-fit
position absolute
left 0
top var(--f7-navbar-height)
height calc(100% - var(--f7-navbar-height))
width 100%
display flex
background white
align-items center
justify-content center
.CodeMirror
height 100%
width 100%
.CodeMirror-line
line-height 1.3
.cm-lkcampbell-indent-guides:not(.CodeMirror-lint-mark-error)
margin-top -5px
background-repeat repeat-y
background-image url("data:image/svg+xml;utf8,<?xml version='1.0' encoding='UTF-8'?><svg xmlns='http://www.w3.org/2000/svg' version='1.1' width='1px' height='2px'><rect width='1' height='1' style='fill:%2377777777' /></svg>")
position relative
.CodeMirror-hints
z-index 999999
.CodeMirror-Tern-tooltip
z-index 999998
opacity 1 !important
position absolute
.CodeMirror-lint-tooltip
z-index 999998
opacity 1 !important
position absolute
</style>
<script>
// require component
import { codemirror } from 'vue-codemirror'
import _CodeMirror from 'codemirror'
// require styles
import 'codemirror/lib/codemirror.css'
// language js
import 'codemirror/mode/clike/clike.js'
import 'codemirror/mode/groovy/groovy.js'
import 'codemirror/mode/jinja2/jinja2.js'
import 'codemirror/mode/javascript/javascript.js'
import 'codemirror/mode/properties/properties.js'
import 'codemirror/mode/python/python.js'
import 'codemirror/mode/ruby/ruby.js'
import 'codemirror/mode/shell/shell.js'
import 'codemirror/mode/xml/xml.js'
import 'codemirror/mode/yaml/yaml.js'
// theme css
import 'codemirror/theme/gruvbox-dark.css'
import 'codemirror/addon/edit/matchbrackets.js'
import 'codemirror/addon/edit/closebrackets.js'
// for autocomplete
import 'codemirror/addon/hint/show-hint.js'
import 'codemirror/addon/hint/show-hint.css'
import 'codemirror/addon/hint/anyword-hint.js'
import 'codemirror/addon/dialog/dialog.js'
import 'codemirror/addon/dialog/dialog.css'
import 'codemirror/addon/tern/tern.js'
import 'codemirror/addon/tern/tern.css'
// for folding
import 'codemirror/addon/fold/foldgutter.css'
import 'codemirror/addon/fold/foldcode.js'
import 'codemirror/addon/fold/foldgutter.js'
import 'codemirror/addon/fold/indent-fold.js'
// for linting
import 'codemirror/addon/lint/lint.js'
import 'codemirror/addon/lint/lint.css'
import YAML from 'yaml'
import tern from 'tern'
import infer from 'tern/lib/infer'
// import 'tern/lib/signal.js'
// import * as Tern from 'tern/lib/tern.js'
// import 'tern/lib/def.js'
// import 'tern/lib/comment.js'
// import 'tern/lib/infer.js'
// import 'tern/plugin/doc_comment.js'
import EcmascriptDefs from 'tern/defs/ecmascript.json'
import NashornDefs from '@/assets/nashorn-tern-defs.json'
import OpenhabJsDefs from '@/assets/openhab-js-tern-defs.json'
import componentsHint from '../editor/hint-components'
import itemsHint from '../editor/hint-items'
import rulesHint from '../editor/hint-rules'
import thingsHint from '../editor/hint-things'
import pythonHint from '../editor/hint-python'
// Adapted from https://github.com/lkcampbell/brackets-indent-guides (MIT)
let indentGuidesOverlay = {
token: function (stream, state) {
let char = '',
colNum = 0,
spaceUnits = 0,
isTabStart = false
char = stream.next()
colNum = stream.column()
if (colNum === 0) {
return null
}
if (char === '\t') {
return 'lkcampbell-indent-guides'
}
if (char !== ' ') {
stream.skipToEnd()
return null
}
spaceUnits = 2
isTabStart = !(colNum % spaceUnits)
if ((char === ' ') && (isTabStart)) {
return 'lkcampbell-indent-guides'
} else {
return null
}
},
flattenSpans: false
}
export default {
components: {
codemirror
},
props: ['value', 'mode', 'hintContext', 'ternAutocompletionHook', 'readOnly'],
data () {
return {
code: this.value,
itemsCache: [],
cmOptions: {
// codemirror options
tabSize: 4,
mode: this.translateMode(this.mode),
theme: (this.$f7.data.themeOptions.dark === 'dark') ? 'gruvbox-dark' : 'default',
lineNumbers: true,
line: true,
readOnly: this.readOnly,
matchBrackets: true,
autoCloseBrackets: true,
viewportMargin: Infinity,
foldGutter: true,
lint: false,
gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter', 'CodeMirror-lint-markers']
}
}
},
beforeDestroy () {
if (this.codemirror && this.codemirror.closeHint) {
this.codemirror.closeHint()
}
},
methods: {
translateMode (mode) {
// Translations required for some special modes used in MainUI
// See https://codemirror.net/5/mode/index.html for supported language names & MIME types
if (!mode) return mode
if (mode.indexOf('yaml') >= 0) return 'text/x-yaml'
if (mode.indexOf('application/javascript') === 0 || mode === 'js') return 'text/javascript'
if (mode === 'application/vnd.openhab.dsl.rule') return 'text/x-java'
if (mode === 'py') return 'text/x-python'
if (mode === 'rb') return 'text/x-ruby'
if (mode.indexOf('jinja') >= 0) return 'text/jinja2'
return mode
},
ternComplete (file, query) {
let pos = tern.resolvePos(file, query.end)
let lit = infer.findExpressionAround(file.ast, null, pos, file.scope, 'Literal')
if (!lit || !lit.node) return
let call = infer.findExpressionAround(file.ast, null, lit.node.start - 2, file.scope)
if (!call || !call.node) return
if (call.node.type !== 'MemberExpression' || (!call.node.object && !call.node.property)) return
if ((call.node.object.name === 'events' && call.node.property.name === 'postUpdate') ||
(call.node.object.name === 'events' && call.node.property.name === 'sendCommand') ||
(call.node.object.name === 'itemRegistry' && call.node.property.name === 'getItem') ||
(call.node.object.name === 'ir' && call.node.property.name === 'getItem') ||
(call.node.object.name === 'items' && call.node.property.name === 'getItem')) {
console.debug('Completing item names!')
let before = lit.node.value.slice(0, pos - lit.node.start - 1)
let matches = []
this.itemsCache.sort((a, b) => a.name.localeCompare(b.name)).forEach((item) => {
if (item.name.length > before.length && item.name.toLowerCase().indexOf(before.toLowerCase()) >= 0) {
if (query.types || query.docs || query.urls || query.origins) {
let rec = {
name: JSON.stringify(item.name),
displayName: item.name,
doc: (item.label ? item.label + ' ' : '') + '[' + item.type + ']'
}
matches.push(rec)
if (query.types) rec.type = 'string'
if (query.origins) rec.origin = item.name
}
}
})
return {
start: tern.outputPos(query, file, lit.node.start),
end: tern.outputPos(query, file, pos + (file.text.charAt(pos) === file.text.charAt(lit.node.start) ? 1 : 0)),
isProperty: false,
completions: matches
}
}
},
onCmReady (cm) {
const self = this
let extraKeys = {}
if (this.mode.indexOf('application/javascript') === 0) {
window.tern = tern
if (this.ternAutocompletionHook) {
tern.registerPlugin('openhab-tern-hook', (server, options) => {
server.mod.completeStrings = {
maxLen: (options && options.maxLength) || 15,
seen: Object.create(null)
}
server.on('completion', this.ternComplete)
})
this.$oh.api.get('/rest/items?staticDataOnly=true').then((data) => { this.$set(this, 'itemsCache', data) })
}
const server = new _CodeMirror.TernServer({
defs: (this.mode.indexOf('version=ECMAScript-5.1') > 0) ? [EcmascriptDefs, NashornDefs] : [EcmascriptDefs, OpenhabJsDefs],
plugins: (this.ternAutocompletionHook) ? { 'openhab-tern-hook': {} } : undefined,
ecmaVersion: (this.mode.indexOf('version=ECMAScript-5.1') > 0) ? 5 : 6
})
extraKeys = {
'Ctrl-Space': function (cm) { server.complete(cm) },
'Ctrl-Q': function (cm) { server.showDocs(cm) },
'\'.\'': function (cm) {
setTimeout(function () { server.complete(cm) }, 100)
return _CodeMirror.Pass // tell CodeMirror we didn't handle the key
}
}
cm.on('cursorActivity', function (cm) {
server.updateArgHints(cm)
})
} else {
const autocomplete = function (cm) {
setTimeout(function () { _CodeMirror.commands.autocomplete(cm) }, 250)
return _CodeMirror.Pass // tell CodeMirror we didn't handle the key
}
extraKeys = {
'Ctrl-Space': 'autocomplete',
'\'.\'': autocomplete,
'\'=\'': autocomplete,
'Space': autocomplete,
'\'@\'': autocomplete
}
cm.state.$oh = this.$oh
cm.state.originalMode = this.mode
if (this.hintContext) cm.state.hintContext = Object.assign({}, this.hintContext)
cm.setOption('hintOptions', {
closeOnUnfocus: false,
completeSingle: self.mode && self.mode.indexOf('yaml') > 0,
hint (cm, option) {
if (self.mode.indexOf('application/vnd.openhab.uicomponent') === 0) {
return componentsHint(cm, option, self.mode)
} else if (self.mode === 'application/vnd.openhab.item+yaml') {
return itemsHint(cm, option, self.mode)
} else if (self.mode === 'application/vnd.openhab.rule+yaml') {
return rulesHint(cm, option, self.mode)
} else if (self.mode === 'application/vnd.openhab.thing+yaml') {
return thingsHint(cm, option, self.mode)
} else if (self.mode === 'application/python') {
return pythonHint(cm, option, self.mode)
} else {
return _CodeMirror.hint.anyword(cm, option, self.mode)
}
}
})
_CodeMirror.registerHelper('lint', 'yaml', function (text) {
const found = []
const parsed = YAML.parseDocument(text)
if (parsed.errors.length > 0) {
parsed.errors.forEach((e) => {
const message = e.message
e.makePretty()
found.push({
message: message,
from: (e.linePos.end) ? { line: e.linePos.start.line - 1, ch: e.linePos.start.col - 1 } : undefined,
to: (e.linePos.end) ? { line: e.linePos.end.line - 1, ch: e.linePos.end.col - 1 } : undefined
})
})
}
return found
})
this.cmOptions.gutters.push('CodeMirror-lint-markers')
this.cmOptions.lint = true
}
extraKeys.Tab = function (cm) {
if (cm.somethingSelected()) {
cm.indentSelection('add')
} else {
cm.replaceSelection(cm.getOption('indentWithTabs') ? '\t'
: Array(cm.getOption('indentUnit') + 1).join(' '), 'end', '+input')
}
}
extraKeys['Shift-Tab'] = 'indentLess'
cm.setOption('extraKeys', extraKeys)
cm.addOverlay(indentGuidesOverlay)
cm.refresh()
},
onCmCodeChange (newCode) {
this.$emit('input', newCode)
}
},
computed: {
codemirror () {
return this.$refs.cm.codemirror
}
},
mounted () {
}
}
</script>