-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
335 lines (300 loc) · 11.2 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
334
335
import YAML, { YAMLMap, YAMLSeq, LineCounter } from 'yaml'
import * as monaco from 'monaco-editor'
import { Elm } from './src/Main.elm'
import { setDiagnosticsOptions } from 'monaco-yaml'
const version = '0.3.5'
const app = Elm.Main.init({
node: document.getElementById('root'),
flags: [window.showOpenFilePicker !== undefined, version]
})
let editor
let model
let decorations = []
let currentElements = []
function initMonaco(initialValue) {
if (editor != null) {
model.dispose()
editor.dispose()
}
const modelUri = monaco.Uri.parse('internal.yaml');
setDiagnosticsOptions({
enableSchemaRequest: true,
hover: true,
completion: true,
validate: true,
format: true,
schemas: [{
uri: 'https://raw.githubusercontent.com/RDBModel/rdbmodel.github.io/master/schema.json',
fileMatch: [String(modelUri)],
}],
});
model = monaco.editor.createModel(modifyYamlValue(initialValue), 'yaml', modelUri)
editor = monaco.editor.create(document.getElementById('monaco'), {
// theme: 'vs-dark',
automaticLayout: true,
model: model,
//value: modifyYamlValue(initialValue),
language: 'yaml',
wordWrap: 'on',
automaticLayout: true,
lineNumbers: 'off',
glyphMargin: false,
minimap: {
enabled: false
},
scrollbar: {
vertical: 'auto'
}
})
editor.addCommand(
monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS,
function () {
app.ports.monacoEditorSavedValue.send(editor.getValue())
}
)
editor.onMouseDown(function (e) {
const position = e.target.position;
const lineContent = editor.getModel().getLineContent(position.lineNumber);
const foundElement = currentElements.find(el => lineContent.trim() === el + ':')
if (foundElement) {
app.ports.focusContainerInView.send(foundElement)
}
});
editor.onMouseUp(function () {
app.ports.unfocusContainerInView.send(null)
})
// remove editor focus if we clicked outside of it
document.getElementById('main-graph').parentNode.parentNode.addEventListener('click', (ev) => {
if (editor.hasWidgetFocus()) {
// TODO cover clicks on button
document.activeElement.blur()
app.ports.monacoEditorSavedValue.send(editor.getValue())
}
if (ev.target.className !== 'elm-select-input') {
document.querySelectorAll('.elm-select-input').forEach(el => el.blur())
}
})
}
app.ports.zoomMsgReceived.subscribe(() => {
app.ports.onWheel.send(null)
})
app.ports.focusContainerInEditor.subscribe((viewElementKey) => {
// Get the editor's model
const model = editor.getModel()
if (model) {
// Search for the text within the model
const matches = model.findMatches(viewElementKey + ":", true, false, true, null, true)
if (matches.length > 0) {
const match = matches[0] // Assuming you want to focus on the first match
const position = match.range.getStartPosition()
// Use the revealPosition method to focus on the specified position
editor.revealPosition(position, monaco.editor.ScrollType.Immediate)
// Create a decoration range using the match range
const decorationRange = {
startLineNumber: match.range.startLineNumber,
startColumn: match.range.startColumn,
endLineNumber: match.range.endLineNumber,
endColumn: match.range.endColumn
};
// Define the decoration options (e.g., background color)
const decorationOptions = {
isWholeLine: false,
className: 'highlighted-text' // CSS class for styling
};
// Add the decoration to the editor's model
editor.deltaDecorations(decorations, [{
range: decorationRange,
options: decorationOptions
}]);
}
}
})
app.ports.openFileOpenDialog.subscribe(async () => await showFilePicker())
app.ports.openSaveFileDialog.subscribe(() => app.ports.requestValueToSave.send(null))
app.ports.saveValueToFile.subscribe(async (value) => await showFileSaveDialog(value))
app.ports.initMonacoResponse.subscribe((message) => initMonaco(message))
app.ports.tryToSaveCurrentEditorValue.subscribe(() => app.ports.monacoEditorSavedValue.send(editor.getValue()))
app.ports.updateMonacoValue.subscribe((message) => updateMonacoValue(message))
app.ports.validationErrors.subscribe((message) => {
const newDecorators = []
if (message !== '') showErrors(message, newDecorators)
decorations = editor.deltaDecorations(
decorations,
newDecorators
)
})
app.ports.saveToLocalStorage.subscribe((value) => saveToLocalStorage(value))
app.ports.getFromLocalStorage.subscribe(() => getFromLocalStorage())
app.ports.shareElementsAtCurrentView.subscribe((message) => currentElements = message)
// delay monaco initialization (via Elm) test
// TODO: remove?
// app.ports.initMonacoRequest.send(null)
// TODO: import from ELM
const domainErrorKeys = ['Elements with empty name', 'Not existing target', 'Duplicated element key']
const viewsErrorKeys = ['Not existing element in domain', 'Not existing relation in domain']
const yamlParseError = ['Non-unique keys in record']
function showErrors(message, newDecorators) {
const allErrors = []
console.error(message)
if (message.includes(yamlParseError)) {
const elementName = message.split(`${yamlParseError}:`)[1].trim()
allErrors.push([yamlParseError, elementName])
} else {
const parsedMessage = JSON.parse(message)
for (const key in parsedMessage) {
if (domainErrorKeys.includes(key)) {
for (const error of parsedMessage[key]) {
allErrors.push([key, error])
}
} else {
const viewName = key
for (const viewError of parsedMessage[viewName]) {
for (const viewErrorKey in viewError) {
if (viewErrorKey === 'Not existing element in domain') {
for (const error of viewError[viewErrorKey]) {
allErrors.push([viewErrorKey, error])
}
} else if (viewErrorKey === 'Not existing relation in domain') {
for (const containerKey in viewError[viewErrorKey]) {
console.log(viewError[viewErrorKey])
for (const relation of viewError[viewErrorKey][containerKey]) {
allErrors.push([viewErrorKey, relation])
}
}
}
}
}
}
}
}
const value = editor.getValue()
const lineCounter = new LineCounter()
const currentDocument = YAML.parseDocument(value, { lineCounter: lineCounter, keepSourceTokens: true })
console.dir(allErrors, {depth: null})
console.dir(currentDocument, {depth: null})
const content = currentDocument.contents
populateAnalyzers(content, 0)
function populateAnalyzers (value, isDomainOrView) {
if ('items' in value) {
for (const subValue of value.items) {
if ('key' in subValue && subValue.key.type === 'PLAIN') {
if (subValue.key.value === 'domain') {
isDomainOrView = 1
} else if (subValue.key.value === 'views') {
isDomainOrView = 2
}
for (const [name, error] of allErrors) {
const domainError = domainErrorKeys.indexOf(name) > -1
if (subValue.key.value === error && domainError && isDomainOrView === 1) {
pushDecorator(subValue.key.srcToken.offset, error, name)
}
const viewsError = viewsErrorKeys.indexOf(name) > -1
if (subValue.key.value === error && viewsError && isDomainOrView === 2) {
pushDecorator(subValue.key.srcToken.offset, error, name)
}
if (subValue.key.value === error && !viewsError && !domainError) {
pushDecorator(subValue.key.srcToken.offset, error, name)
}
}
}
if (subValue instanceof YAMLMap) {
populateAnalyzers(subValue, isDomainOrView)
} else if ('type' in subValue && subValue.type === 'PLAIN') {
for (const [name, error] of allErrors) {
const domainError = domainErrorKeys.indexOf(name) > -1
if (subValue.value === error && domainError && isDomainOrView === 1) {
pushDecorator(subValue.srcToken.offset, error, name)
}
const viewsError = viewsErrorKeys.indexOf(name) > -1
if (subValue.value === error && viewsError && isDomainOrView === 2) {
pushDecorator(subValue.srcToken.offset, error, name)
}
if (subValue.value === error && !viewsError && !domainError) {
pushDecorator(subValue.srcToken.offset, error, name)
}
}
} else if (subValue.value instanceof YAMLMap || subValue.value instanceof YAMLSeq) {
populateAnalyzers(subValue.value, isDomainOrView)
}
}
}
}
function pushDecorator (offset, error, name) {
const { line, col } = lineCounter.linePos(offset)
newDecorators.push({
range: new monaco.Range(line, col, line, col + error.length + 1),
options: {
inlineClassName: 'error',
hoverMessage: { value: name }
}
})
}
}
function updateMonacoValue(message) {
editor.setValue(modifyYamlValue(message))
}
async function showFilePicker() {
const file = await window.showOpenFilePicker({
types: [
{
description: 'Yaml',
accept: {
'yaml/*': ['.yaml', '.yml']
}
},
],
excludeAcceptAllOption: true,
multiple: false
})
// Track the dir in history.state
const state = history.state || {}
state.currentFile = file[0]
history.replaceState(state, '')
const content = (await readFileAsync(await state.currentFile.getFile())).replace(/\r/g, '')
editor.setValue(content)
app.ports.monacoEditorSavedValue.send(content)
}
function readFileAsync(file) {
return new Promise((resolve, reject) => {
let reader = new FileReader()
reader.onload = () => {
resolve(reader.result)
};
reader.onerror = reject
reader.readAsText(file)
})
}
function modifyYamlValue(value) {
// temp fix - https://github.com/MaybeJustJames/yaml/issues/28
return value
// .replace(/relations:\n\s+\n/g, 'relations: []\n')
// .replace(/relations:\n\s+$/, 'relations: []\n')
// .replace(/containers:\n\s+\n/g, 'containers: {}\n')
// .replace(/containers:\n\s+$/, 'containers: {}\n')
// .replace(/elements:\n\s+\n/, 'elements: {}\n')
// .replace(/elements:\n\s+$/, 'elements: {}\n')
// .replace(/views:\n\s+$/, 'views: {}\n')
// .replace(/:\n\s+\n/g, ': []\n')
// .replace(/:\n\s+$/, ': []\n')
// .replace(/-\n\s+x:/g, '- x:')
}
async function showFileSaveDialog(value) {
const newHandle = await window.showSaveFilePicker()
const writableStream = await newHandle.createWritable({types: [{
description: 'Yaml',
accept: {'text/plain': ['.yaml']},
}]});
const blob = new Blob([modifyYamlValue(value)], {
type: 'text/plain',
});
await writableStream.write(blob)
await writableStream.close()
}
const localStorageKey = 'rdb-model-current-domain'
function saveToLocalStorage(value) {
localStorage.setItem(localStorageKey, value)
}
function getFromLocalStorage() {
const value = localStorage.getItem(localStorageKey)
app.ports.receivedFromLocalStorage.send(value)
}