forked from msironi/expr-eval
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.js
More file actions
615 lines (537 loc) · 23.7 KB
/
app.js
File metadata and controls
615 lines (537 loc) · 23.7 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
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
// Theme management
const themeToggle = document.getElementById('themeToggle');
const html = document.documentElement;
let monacoReady = false;
function getSystemTheme() {
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
function getStoredTheme() {
return localStorage.getItem('expr-eval-theme');
}
function setTheme(theme) {
if (theme === 'dark') {
html.classList.add('dark');
} else {
html.classList.remove('dark');
}
localStorage.setItem('expr-eval-theme', theme);
if (monacoReady) {
updateMonacoTheme();
}
}
function initTheme() {
const stored = getStoredTheme();
const theme = stored || getSystemTheme();
setTheme(theme);
}
themeToggle.addEventListener('click', () => {
const isDark = html.classList.contains('dark');
setTheme(isDark ? 'light' : 'dark');
});
// Listen for system theme changes
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
if (!getStoredTheme()) {
setTheme(e.matches ? 'dark' : 'light');
}
});
initTheme();
// Copy example link to clipboard
function copyExampleLink(exampleId, button) {
const url = new URL(window.location.href);
url.search = '';
url.searchParams.set('example', exampleId);
navigator.clipboard.writeText(url.toString()).then(() => {
// Show checkmark briefly
const icon = button.querySelector('svg');
const originalPath = icon.innerHTML;
icon.innerHTML = '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />';
button.classList.add('text-green-500', 'dark:text-green-400');
setTimeout(() => {
icon.innerHTML = originalPath;
button.classList.remove('text-green-500', 'dark:text-green-400');
}, 1500);
});
}
// Render examples sidebar
function renderExamplesSidebar() {
const examplesList = document.getElementById('examplesList');
if (!examplesList) return;
examplesList.innerHTML = exampleCases.map(example => `
<div class="example-container relative group/container">
<button
class="example-item w-full text-left p-3 rounded-lg transition-all duration-200
hover:bg-white dark:hover:bg-[#2d2d2d]
hover:shadow-sm hover:border-indigo-200 dark:hover:border-[#3c3c3c]
border border-transparent
group"
data-example-id="${example.id}"
>
<div class="flex items-start gap-2">
<div class="flex-shrink-0 w-6 h-6 rounded bg-indigo-100 dark:bg-[#3c3c3c] flex items-center justify-center mt-0.5">
<svg class="w-3.5 h-3.5 text-indigo-600 dark:text-[#569cd6]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
</svg>
</div>
<div class="flex-1 min-w-0">
<p class="text-sm font-medium text-gray-800 dark:text-[#cccccc] truncate group-hover:text-indigo-600 dark:group-hover:text-[#569cd6]">
${example.title}
</p>
<p class="text-xs text-gray-500 dark:text-[#808080] mt-0.5 line-clamp-2">
${example.description}
</p>
</div>
</div>
</button>
<button
class="copy-link-btn absolute top-2 right-2 p-1.5 rounded-md
opacity-0 group-hover/container:opacity-100
bg-gray-100 dark:bg-[#3c3c3c] hover:bg-gray-200 dark:hover:bg-[#4c4c4c]
text-gray-500 dark:text-[#808080] hover:text-indigo-600 dark:hover:text-[#569cd6]
transition-all duration-200"
data-example-id="${example.id}"
title="Copy link to example"
>
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
</svg>
</button>
</div>
`).join('');
// Add click handlers for loading examples
examplesList.querySelectorAll('.example-item').forEach(button => {
button.addEventListener('click', () => {
const exampleId = button.dataset.exampleId;
const example = exampleCases.find(e => e.id === exampleId);
if (example) {
loadExample(example);
}
});
});
// Add click handlers for copy link buttons
examplesList.querySelectorAll('.copy-link-btn').forEach(button => {
button.addEventListener('click', (e) => {
e.stopPropagation();
const exampleId = button.dataset.exampleId;
copyExampleLink(exampleId, button);
});
});
}
// Load example into editors
function loadExample(example) {
if (typeof expressionEditor !== 'undefined' && expressionEditor) {
expressionEditor.getModel().setValue(example.expression);
}
if (typeof contextEditor !== 'undefined' && contextEditor) {
contextEditor.getModel().setValue(JSON.stringify(example.context, null, 2));
}
}
// Initialize sidebar
renderExamplesSidebar();
// Get example ID from URL query parameter
function getExampleFromUrl() {
const params = new URLSearchParams(window.location.search);
return params.get('example');
}
// Load example from URL if present (called after Monaco initializes)
function loadExampleFromUrl() {
const exampleId = getExampleFromUrl();
if (exampleId) {
const example = exampleCases.find(e => e.id === exampleId);
if (example) {
loadExample(example);
return true;
}
}
return false;
}
// Vertical resizing for bottom split (context/results)
(function() {
const resizer = document.getElementById('verticalResizer');
const contextPane = document.getElementById('contextPane');
const resultsPane = document.getElementById('resultsPane');
const bottomArea = document.getElementById('bottomArea');
let isResizing = false;
resizer.addEventListener('mousedown', (e) => {
e.preventDefault();
isResizing = true;
document.body.style.cursor = 'col-resize';
document.body.style.userSelect = 'none';
});
document.addEventListener('mousemove', (e) => {
if (!isResizing) return;
e.preventDefault();
const containerRect = bottomArea.getBoundingClientRect();
const containerWidth = containerRect.width;
const resizerWidth = 6;
let newLeftWidth = e.clientX - containerRect.left;
newLeftWidth = Math.max(containerWidth * 0.2, Math.min(containerWidth * 0.8, newLeftWidth));
const percentage = (newLeftWidth / containerWidth) * 100;
contextPane.style.width = percentage + '%';
});
document.addEventListener('mouseup', () => {
if (isResizing) {
isResizing = false;
document.body.style.cursor = '';
document.body.style.userSelect = '';
}
});
})();
// Monaco configuration and initialization
require.config({paths: {'vs': 'https://cdn.jsdelivr.net/npm/monaco-editor@0.49.0/min/vs'}});
let expressionEditor, contextEditor;
function updateMonacoTheme() {
const theme = html.classList.contains('dark') ? 'vs-dark' : 'vs';
monaco.editor.setTheme(theme);
}
require(['vs/editor/editor.main'], function () {
monacoReady = true;
const languageId = 'expr-eval';
monaco.languages.register({id: languageId});
// Set initial theme
const currentTheme = html.classList.contains('dark') ? 'vs-dark' : 'vs';
// Default values - showcasing nested path access and deeper objects
const defaultExpression = 'user.profile.score + config.timeout / 1000';
const defaultContext = JSON.stringify({
x: 42,
y: 100,
multiplier: 2,
user: {
name: "Ada",
profile: {
email: "ada@example.com",
score: 95,
level: 5
},
preferences: {
theme: "dark",
notifications: true
}
},
config: {
timeout: 5000,
retries: 3,
maxConnections: 10
},
items: [1, 2, 3, 4, 5]
}, null, 2);
// Load from localStorage or use defaults
const savedExpression = localStorage.getItem('expr-eval-expression') || defaultExpression;
const savedContext = localStorage.getItem('expr-eval-context') || defaultContext;
// Create context editor (JSON)
const contextModel = monaco.editor.createModel(savedContext, 'json');
contextEditor = monaco.editor.create(document.getElementById('contextEditor'), {
model: contextModel,
theme: currentTheme,
automaticLayout: true,
fontSize: 14,
minimap: {enabled: false},
lineNumbers: 'on',
scrollBeyondLastLine: false,
wordWrap: 'on',
tabSize: 2
});
// Create expression editor
const expressionModel = monaco.editor.createModel(savedExpression, languageId);
expressionEditor = monaco.editor.create(document.getElementById('expressionEditor'), {
model: expressionModel,
theme: currentTheme,
automaticLayout: true,
fontSize: 14,
minimap: {enabled: false},
lineNumbers: 'on',
scrollBeyondLastLine: false,
wordWrap: 'on'
});
// Access expr-eval UMD
const {createLanguageService, Parser} = window.exprEval || {};
if (!createLanguageService) {
console.error('expr-eval not found. Make sure /dist/bundle.js is built.');
showError({message: 'expr-eval library not loaded. Please run: npm run build'}, null);
return;
}
const ls = createLanguageService();
// Minimal lsp text document backed by Monaco model
function makeTextDocument(m) {
return {
uri: m.uri.toString(),
getText: () => m.getValue(),
positionAt: (offset) => {
const p = m.getPositionAt(offset);
return {line: p.lineNumber - 1, character: p.column - 1};
},
offsetAt: (pos) => m.getOffsetAt(new monaco.Position(pos.line + 1, pos.character + 1))
};
}
function toLspPosition(mp) {
return {line: mp.lineNumber - 1, character: mp.column - 1};
}
function fromLspPosition(lp) {
return new monaco.Position(lp.line + 1, lp.character + 1);
}
// Get context variables from JSON editor
function getContextVariables() {
try {
const contextText = contextModel.getValue().trim();
if (!contextText) return {};
return JSON.parse(contextText);
} catch (e) {
return null; // Invalid JSON
}
}
// Completions provider with trigger characters and snippet support
monaco.languages.registerCompletionItemProvider(languageId, {
triggerCharacters: ['.'],
provideCompletionItems: function (model, position) {
const doc = makeTextDocument(model);
const variables = getContextVariables() || {};
const items = ls.getCompletions({
textDocument: doc,
position: toLspPosition(position),
variables
}) || [];
function mapKind(k) {
const map = {
3: monaco.languages.CompletionItemKind.Function,
6: monaco.languages.CompletionItemKind.Variable,
21: monaco.languages.CompletionItemKind.Constant,
14: monaco.languages.CompletionItemKind.Keyword
};
return map[k] || monaco.languages.CompletionItemKind.Text;
}
const suggestions = items.map(it => {
// Handle textEdit.range if present
let range;
if (it.textEdit?.range) {
range = new monaco.Range(
it.textEdit.range.start.line + 1,
it.textEdit.range.start.character + 1,
it.textEdit.range.end.line + 1,
it.textEdit.range.end.character + 1
);
} else {
// Default range - word at position
const word = model.getWordUntilPosition(position);
range = new monaco.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn);
}
return {
label: it.label,
kind: mapKind(it.kind),
detail: it.detail,
documentation: it.documentation,
insertText: it.textEdit?.newText || it.insertText || it.label,
// Add snippet support when insertTextFormat is 2
insertTextRules: it.insertTextFormat === 2
? monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet
: undefined,
range
};
});
return {suggestions};
}
});
// Hover provider with MarkupContent support
monaco.languages.registerHoverProvider(languageId, {
provideHover: function (model, position) {
const doc = makeTextDocument(model);
const variables = getContextVariables() || {};
const hover = ls.getHover({textDocument: doc, position: toLspPosition(position), variables});
if (!hover || !hover.contents) return {contents: []};
// HoverV2 always returns MarkupContent format
let contents = [];
if (hover.contents && hover.contents.value) {
contents = [{value: hover.contents.value}];
}
let range = undefined;
if (hover.range) {
const start = fromLspPosition(hover.range.start);
const end = fromLspPosition(hover.range.end);
range = new monaco.Range(start.lineNumber, start.column, end.lineNumber, end.column);
}
return {contents, range};
}
});
// Syntax highlighting
let highlightDecorations = [];
function applyHighlighting() {
const doc = makeTextDocument(expressionModel);
const tokens = ls.getHighlighting(doc);
const decorations = tokens.map(t => {
const start = expressionModel.getPositionAt(t.start);
const end = expressionModel.getPositionAt(t.end);
return {
range: new monaco.Range(start.lineNumber, start.column, end.lineNumber, end.column),
options: { inlineClassName: 'tok-' + t.type }
};
});
// deltaDecorations replaces old decorations with new ones atomically
highlightDecorations = expressionEditor.deltaDecorations(highlightDecorations, decorations);
}
// Syntax highlight JSON
function syntaxHighlightJson(json) {
if (typeof json !== 'string') {
json = JSON.stringify(json, null, 2);
}
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("+[^"]*"+)(:)?/g, function(match, p1, p2) {
let cls = 'json-key';
if (!p2) {
cls = 'json-string';
}
return '<span class="' + cls + '">' + p1 + '</span>' + (p2 || '');
})
.replace(/: (true|false)/g, ': <span class="json-boolean">$1</span>')
.replace(/: (null)/g, ': <span class="json-null">$1</span>')
.replace(/: (-?\d+\.?\d*)/g, ': <span class="json-number">$1</span>');
}
// Result display functions
function showResult(result) {
const resultSuccess = document.getElementById('resultSuccess');
const resultError = document.getElementById('resultError');
const resultEmpty = document.getElementById('resultEmpty');
const resultValue = document.getElementById('resultValue');
const resultType = document.getElementById('resultType');
resultSuccess.classList.remove('hidden');
resultError.classList.add('hidden');
resultEmpty.classList.add('hidden');
// Format the result
let displayValue;
let typeInfo;
let isJson = false;
if (result === null) {
displayValue = '<span class="json-null">null</span>';
typeInfo = 'Type: null';
isJson = true;
} else if (result === undefined) {
displayValue = '<span class="json-null">undefined</span>';
typeInfo = 'Type: undefined';
isJson = true;
} else if (typeof result === 'object') {
displayValue = syntaxHighlightJson(result);
typeInfo = Array.isArray(result) ? `Type: array (${result.length} items)` : 'Type: object';
isJson = true;
} else if (typeof result === 'boolean') {
displayValue = `<span class="json-boolean">${result}</span>`;
typeInfo = 'Type: boolean';
isJson = true;
} else if (typeof result === 'number') {
displayValue = `<span class="json-number">${result}</span>`;
typeInfo = 'Type: number';
isJson = true;
} else if (typeof result === 'string') {
displayValue = `<span class="json-string">"${result}"</span>`;
typeInfo = 'Type: string';
isJson = true;
} else {
displayValue = String(result);
typeInfo = `Type: ${typeof result}`;
}
if (isJson) {
resultValue.innerHTML = displayValue;
} else {
resultValue.textContent = displayValue;
}
resultType.textContent = typeInfo;
}
function showError(error, contextError) {
const resultSuccess = document.getElementById('resultSuccess');
const resultError = document.getElementById('resultError');
const resultEmpty = document.getElementById('resultEmpty');
const errorMessage = document.getElementById('errorMessage');
const errorDetails = document.getElementById('errorDetails');
const resultsPane = document.getElementById('resultsPane');
resultSuccess.classList.add('hidden');
resultError.classList.remove('hidden');
resultEmpty.classList.add('hidden');
// Shake animation
if (resultsPane) {
resultsPane.classList.add('error-shake');
setTimeout(() => resultsPane.classList.remove('error-shake'), 300);
}
errorMessage.textContent = error.message;
// Build helpful error details
let details = [];
if (contextError) {
details.push(`<div class="p-2 bg-amber-50 dark:bg-amber-900/20 rounded border border-amber-200 dark:border-amber-800">
<p class="font-medium text-amber-700 dark:text-amber-400">⚠️ JSON Context Error</p>
<p class="text-amber-600 dark:text-amber-300 text-sm mt-1">${contextError}</p>
</div>`);
}
// Parse error for more context
const undefinedMatch = error.message.match(/undefined variable[:\s]*(\w+)/i);
if (undefinedMatch) {
const varName = undefinedMatch[1];
const contextVars = getContextVariables();
const availableVars = contextVars ? Object.keys(contextVars) : [];
details.push(`<div class="p-2 bg-blue-50 dark:bg-blue-900/20 rounded border border-blue-200 dark:border-blue-800">
<p class="font-medium text-blue-700 dark:text-blue-400">💡 Suggestion</p>
<p class="text-blue-600 dark:text-blue-300 text-sm mt-1">The variable <code class="bg-blue-100 dark:bg-blue-800 px-1 rounded">${varName}</code> is not defined in your context.</p>
${availableVars.length > 0 ?
`<p class="text-blue-600 dark:text-blue-300 text-sm mt-1">Available variables: <code class="bg-blue-100 dark:bg-blue-800 px-1 rounded">${availableVars.join('</code>, <code class="bg-blue-100 dark:bg-blue-800 px-1 rounded">')}</code></p>` :
'<p class="text-blue-600 dark:text-blue-300 text-sm mt-1">Add variables to the JSON context on the left.</p>'}
</div>`);
}
const syntaxMatch = error.message.match(/parse error|unexpected|expected/i);
if (syntaxMatch) {
details.push(`<div class="p-2 bg-purple-50 dark:bg-purple-900/20 rounded border border-purple-200 dark:border-purple-800">
<p class="font-medium text-purple-700 dark:text-purple-400">🔍 Syntax Help</p>
<p class="text-purple-600 dark:text-purple-300 text-sm mt-1">Check for missing parentheses, brackets, or operators.</p>
</div>`);
}
if (error.message.includes('is not a function')) {
details.push(`<div class="p-2 bg-orange-50 dark:bg-orange-900/20 rounded border border-orange-200 dark:border-orange-800">
<p class="font-medium text-orange-700 dark:text-orange-400">📚 Function Help</p>
<p class="text-orange-600 dark:text-orange-300 text-sm mt-1">Make sure you're using a valid built-in function. Try <code class="bg-orange-100 dark:bg-orange-800 px-1 rounded">sum</code>, <code class="bg-orange-100 dark:bg-orange-800 px-1 rounded">max</code>, <code class="bg-orange-100 dark:bg-orange-800 px-1 rounded">min</code>, <code class="bg-orange-100 dark:bg-orange-800 px-1 rounded">abs</code>, etc.</p>
</div>`);
}
errorDetails.innerHTML = details.join('');
}
function showEmpty() {
document.getElementById('resultSuccess').classList.add('hidden');
document.getElementById('resultError').classList.add('hidden');
document.getElementById('resultEmpty').classList.remove('hidden');
}
// Evaluation function
function evaluate() {
const expression = expressionModel.getValue().trim();
if (!expression) {
showEmpty();
return;
}
const contextVars = getContextVariables();
let contextError = null;
if (contextVars === null) {
contextError = 'Invalid JSON in context editor. Please fix the JSON syntax.';
}
try {
const parser = new Parser();
const evaluationResult = parser.evaluate(expression, contextVars || {});
showResult(evaluationResult);
} catch (error) {
showError(error, contextError);
}
}
// Save functionality
document.getElementById('saveBtn').addEventListener('click', () => {
localStorage.setItem('expr-eval-expression', expressionModel.getValue());
localStorage.setItem('expr-eval-context', contextModel.getValue());
// Show toast
const toast = document.getElementById('saveToast');
toast.classList.remove('translate-y-20', 'opacity-0');
setTimeout(() => {
toast.classList.add('translate-y-20', 'opacity-0');
}, 2000);
});
// Event listeners for changes
expressionModel.onDidChangeContent(() => {
applyHighlighting();
evaluate();
});
contextModel.onDidChangeContent(() => {
evaluate();
});
// Initialize - apply highlighting and evaluate for initial content
applyHighlighting();
evaluate();
// Load example from URL query parameter if present (after event handlers are set up)
loadExampleFromUrl();
});