-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
333 lines (293 loc) · 8.4 KB
/
index.js
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
import * as ns from '@tpluscode/rdf-ns-builders'
import { html, css, LitElement } from 'lit'
import '@vanillawc/wc-codemirror'
import { debounce } from 'throttle-debounce'
const Value = Symbol('Initial value')
const Dirty = Symbol('Editor dirty')
const ParseHandler = Symbol('ParseHandler')
function whenDefined(getter) {
const interval = 10
const maxWaits = 100
let counter = 0
return new Promise((resolve, reject) => {
const awaiter = setInterval(() => {
const value = getter()
if (value) {
clearInterval(awaiter)
resolve()
return
}
counter += 1
if (counter === maxWaits) {
clearInterval(awaiter)
reject(new Error('Value did not become truthy in time'))
}
}, interval)
})
}
/**
* A base ("abstract") class, used to implement other text editor `@rdfjs-elements/*`.
*
* @prop {Promise<void>} ready - a one-time promise which resolves when CodeMirror has been initialized
*
* @prop {string} prefixes - a comma-separated list of prefixes to use for serializing. Any prefix included in the [`@zazuko/vocabularies` package](https://github.com/zazuko/rdf-vocabularies/tree/master/ontologies) can be used
*
* @prop {boolean} isParsing - set to true while the elements parses data when the code has changed
*
* @prop {boolean} autoParse - if set to true, parses the contents automatically when typing. Otherwise, parses on `blur` event
*
* @prop {Number} parseDelay - time in milliseconds after which parsing will begin while typing. Only applies when `autoParse` is set
*
* @attr {Boolean} ready - set when editor is initialized
*
* @prop {Record<string, string>} customPrefixes - a map of custom prefixes or overrides
*
* @csspart error - Line or part of line highlighted as result of parsing error. By default style is red wavy underline
* @csspart CodeMirror - The main CodeMirror wrapper element. This and other parts are directly generated from CSS classes set by CodeMirror and should be fairly self-explanatory but not equally useful 😉
* @csspart CodeMirror-vscrollbar
* @csspart CodeMirror-hscrollbar
* @csspart CodeMirror-scrollbar-filler
* @csspart CodeMirror-gutter-filler
* @csspart CodeMirror-scroll
* @csspart CodeMirror-sizer
* @csspart CodeMirror-lines
* @csspart CodeMirror-measure
* @csspart CodeMirror-measure
* @csspart CodeMirror-cursors
* @csspart CodeMirror-code
* @csspart CodeMirror-gutters
* @csspart CodeMirror-linenumbers
*/
export default class Editor extends LitElement {
static get styles() {
return css`
:host {
display: block;
text-align: left;
}
[part='error'] {
text-decoration: underline;
text-decoration-color: red;
text-decoration-style: wavy;
}
wc-codemirror,
#wrapper {
width: 100%;
height: 100%;
}
:host(:not([ready])) #wrapper {
display: none;
}
`
}
static get properties() {
return {
value: { type: String, noAccessor: true },
readonly: { type: Boolean, reflect: true },
prefixes: { type: String, attribute: 'prefixes' },
isParsing: { type: Boolean, attribute: 'is-parsing', reflect: true },
autoParse: { type: Boolean, attribute: 'auto-parse' },
parseDelay: { type: Number },
customPrefixes: { type: Object },
}
}
constructor() {
super()
this.parseDelay = 250
this[Value] = ''
this.customPrefixes = {}
if (navigator.onLine) {
this.__style = document.createElement('link')
this.__style.rel = 'stylesheet'
this.__style.href =
'https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.61.1/codemirror.min.css'
}
}
connectedCallback() {
const styleLoaded = new Promise(resolve => {
this.__style.onload = resolve
})
super.connectedCallback()
this.ready = Promise.resolve().then(async () => {
await styleLoaded
await this.requestUpdate()
await whenDefined(
() =>
this.codeMirror &&
this.codeMirror.editor &&
this.codeMirror.__initialized
)
await this._initializeCodeMirror()
;[...this.renderRoot.querySelectorAll('[class^=CodeMirror]')].forEach(
el => {
el.classList.forEach(clas => {
if (clas.match(/^CodeMirror/)) {
el.setAttribute('part', clas)
}
})
}
)
this.setAttribute('ready', '')
this.codeMirror.editor.refresh()
if (this[Value]) {
this.codeMirror.editor.setValue(this[Value])
}
})
}
get _prefixes() {
return async () => {
const prefixes = (this.prefixes || '')
.split(',')
.map(prefix => prefix.trim())
return prefixes.reduce((map, prefix) => {
if (prefix in ns) {
return { ...map, [prefix]: ns[prefix]().value }
}
return map
}, {})
}
}
/**
* The underlying `<wc-codemirror>` element
*/
get codeMirror() {
return this.renderRoot.querySelector('wc-codemirror')
}
/**
* Gets the text contents of the underlying editor
* @returns {string}
*/
get value() {
if (this.hasAttribute('ready')) {
return this.codeMirror.editor.getValue()
}
return this[Value] || ''
}
set value(value) {
if (typeof value !== 'string') return
if (this.hasAttribute('ready')) {
if (this.value !== value) {
this.codeMirror.editor.setValue(value)
this[ParseHandler]()
}
} else {
this[Value] = value
}
}
async firstUpdated(_changedProperties) {
super.firstUpdated(_changedProperties)
if (this[Value]) {
await this.ready
this.codeMirror.editor.setValue(this[Value])
this[ParseHandler]()
this[Value] = undefined
}
}
updated(_changedProperties) {
super.updated(_changedProperties)
if (
_changedProperties.has('autoParse') ||
_changedProperties.has('parseDelay')
) {
this.__setParseHandler()
}
}
render() {
return html`${this.__style}
<div id="wrapper">
<wc-codemirror mode="${this.format}" ?readonly="${this.readonly}">
</wc-codemirror>
</div>`
}
async parse() {
if (this.isParsing) {
return
}
if (this.__errorMarker) {
this.__errorMarker.clear()
}
this.isParsing = true
try {
await this._parse()
} catch (error) {
if (typeof this._errorLine === 'function') {
await this.__highlightError(this._errorLine(error))
}
this.dispatchEvent(
new CustomEvent('parsing-failed', {
detail: { error },
})
)
} finally {
this.isParsing = false
}
}
async _initializeCodeMirror() {
this.codeMirror.editor.setSize('100%', '100%')
this.__setParseHandler()
this.codeMirror.editor.on('change', () => {
this[Dirty] = true
})
}
__setParseHandler() {
if (!this.codeMirror.editor) {
return
}
if (this[ParseHandler]) {
this.codeMirror.editor.off('blur', this[ParseHandler])
this.codeMirror.editor.off('change', this[ParseHandler])
}
if (this.autoParse) {
this[ParseHandler] = debounce(
this.parseDelay,
this.__beginParse.bind(this)
)
this.codeMirror.editor.on('change', this[ParseHandler])
} else {
this[ParseHandler] = this.__beginParse.bind(this)
this.codeMirror.editor.on('blur', this[ParseHandler])
}
}
async __beginParse() {
if (this[Dirty]) {
await this.parse()
}
this[Dirty] = false
}
async __highlightError(range) {
if (!this.ready) return
let from = { line: 0, ch: 0 }
let to = { line: 0, ch: Number.MAX_SAFE_INTEGER }
if (range && range.from) {
from = range.from
this.codeMirror.editor.scrollIntoView(from)
}
if (range && range.to) {
to = range.to
}
const title = range ? range.message : ''
await this.ready
this.__errorMarker = this.codeMirror.editor.getDoc().markText(from, to, {
attributes: { part: 'error', title },
})
}
async _combinePrefixes() {
return Object.entries(this.customPrefixes).reduce(
(clean, [prefix, namespace]) => {
if (
!namespace ||
!prefix ||
typeof namespace !== 'string' ||
typeof prefix !== 'string'
) {
return clean
}
return {
...clean,
[prefix]: namespace,
}
},
await this._prefixes()
)
}
}