Repository navigation
Expand file tree
/
Copy pathscript.ts
More file actions
557 lines (495 loc) · 24.3 KB
/
Copy pathscript.ts
File metadata and controls
557 lines (495 loc) · 24.3 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
import { handleVCImplicationStepClick } from "./views/diagnostics/vc-implications";
import { renderLoading } from "./views/loading";
import { renderStopped } from "./views/stopped";
import { renderStateMachineView } from "./views/fsm/fsm";
import { orderStateMachines } from "./diagram-focus";
import { createMermaidDiagram, renderMermaidDiagram, resetZoom, zoomIn, zoomOut, copyDiagramToClipboard } from "./diagram";
import type { LJDiagnostic, RefinementMismatchError, StateRefinementError } from "../types/diagnostics";
import type { Range } from "../types/context";
import type { LJStateMachine } from "../types/fsm";
import type { ExtensionStatus } from "../state";
import { setHintOpen, type NavTab } from "./views/sections";
import { copyDiagnosticToClipboard, getCurrentFileErrorCount, getDisplayDiagnostics, renderDiagnosticsView } from "./views/diagnostics/diagnostics";
import type { LJContext } from "../types/context";
import { ContextSectionState, renderContextView } from "./views/context/context";
import type { DiagnosticRevealTarget } from "../types/diagnostics";
import { getDiagnosticRevealTarget, getDiagnosticRevealTargetFromKey, getDiagnosticRevealTargetKey } from "./diagnostic-reveal";
import { findStateError, getAllStateErrors, getStateErrorKey, getStateErrors } from "./state-errors";
type VSCodeApi = {
postMessage(message: unknown): void;
};
/**
* Initializes the webview script
* @param vscode
* @param document
* @param window
*/
export function getScript(vscode: VSCodeApi, document: Document, window: Window) {
const root = document.getElementById('root')!;
if (!root) return;
let diagnostics: LJDiagnostic[] | undefined;
let showAllDiagnostics = false;
let currentFile: string;
let stateMachines: LJStateMachine[] = [];
// the last state error shown, kept while switching tabs
let selectedStateError: StateRefinementError | undefined;
let cursorStateErrorKey: string | undefined;
let context: LJContext;
let errorAtCursor: RefinementMismatchError;
let selectedTab: NavTab = 'diagnostics';
let status: ExtensionStatus = 'loading';
let diagramOrientation: "LR" | "TB" = "TB";
// the pre and postconditions of the transitions are shown unless collapsed
let showDiagramConditions = true;
let focusDiagramOnError = true;
let currentDiagram: string = '';
let renderedStateMachineView: string | undefined;
let revealTimeout: ReturnType<typeof setTimeout> | undefined;
const contextSectionState: ContextSectionState = {
aliases: false,
ghosts: false,
vars: true,
};
// initial state
root.innerHTML = renderLoading();
vscode.postMessage({ type: 'ready' });
// on click
// toggle does not bubble, so it is caught on its way down
root.addEventListener('toggle', (e: Event) => {
const details = e.target as HTMLDetailsElement;
const key = details.getAttribute?.('data-hint-key');
if (key !== null && key !== undefined) setHintOpen(key, details.open);
}, true);
root.addEventListener('click', (e: MouseEvent) => {
const target = e.target instanceof Element ? e.target : null;
if (!target) return;
const iconButton = target.closest?.('.icon-button');
if (iconButton && !(iconButton as HTMLButtonElement).disabled) {
iconButton.classList.remove('icon-button-pop');
void (iconButton as HTMLElement).offsetWidth;
iconButton.classList.add('icon-button-pop');
}
// context section toggle
const contextToggleButton = target.closest?.('.context-toggle-btn');
if (contextToggleButton) {
e.preventDefault();
e.stopPropagation();
const sectionId = contextToggleButton.getAttribute('data-context-toggle');
if (!sectionId) return;
const content = document.getElementById(sectionId);
if (!content) return;
const isExpanded = contextToggleButton.getAttribute('aria-expanded') !== 'false';
const nextExpanded = !isExpanded;
if (sectionId === 'context-vars') contextSectionState.vars = nextExpanded;
if (sectionId === 'context-ghosts') contextSectionState.ghosts = nextExpanded;
if (sectionId === 'context-aliases') contextSectionState.aliases = nextExpanded;
contextToggleButton.setAttribute('aria-expanded', nextExpanded ? 'true' : 'false');
content.classList.toggle('collapsed', !nextExpanded);
const icon = contextToggleButton.querySelector('.context-toggle-icon');
if (icon) {
icon.classList.toggle('codicon-triangle-down', nextExpanded);
icon.classList.toggle('codicon-triangle-right', !nextExpanded);
}
return;
}
// location link click
const locationTarget = target.closest?.('.location-link');
if (locationTarget) {
e.preventDefault();
e.stopPropagation();
const filePath = locationTarget.getAttribute('data-file');
const lineAttr = locationTarget.getAttribute('data-line');
const columnAttr = locationTarget.getAttribute('data-column');
if (filePath && lineAttr !== null && columnAttr !== null) {
vscode.postMessage({
type: 'openFile',
filePath,
line: parseInt(lineAttr, 10),
character: parseInt(columnAttr, 10)
});
}
return;
}
// reveal failing refinement diagnostic
if (target.classList.contains('diagnostic-reveal-btn')) {
e.preventDefault();
e.stopPropagation();
const revealTarget = getDiagnosticRevealTargetFromKey(target.getAttribute('data-diagnostic-target'));
if (!revealTarget) return;
revealDiagnostic(revealTarget);
return;
}
const diagnosticContextButton = target.closest?.('.diagnostic-context-btn');
if (diagnosticContextButton) {
e.preventDefault();
e.stopPropagation();
const revealTarget = getDiagnosticRevealTargetFromKey(diagnosticContextButton.getAttribute('data-diagnostic-target'));
if (!revealTarget) return;
revealContextForDiagnostic(revealTarget);
return;
}
const diagnosticStateMachineButton = target.closest?.('.diagnostic-state-machine-btn');
if (diagnosticStateMachineButton) {
e.preventDefault();
e.stopPropagation();
const errorIndex = parseInt(diagnosticStateMachineButton.getAttribute('data-error-index') || '-1', 10);
const diagnostic = getDisplayDiagnostics(diagnostics ?? [], showAllDiagnostics, currentFile)
.filter(d => d.category === 'error')[errorIndex];
if (diagnostic?.type !== 'state-refinement-error' || diagnostic.stateMachines.length === 0) return;
showStateError(diagnostic);
return;
}
// step through the state errors of the current file
const stateErrorStepButton = target.closest?.('.state-error-step-btn');
if (stateErrorStepButton) {
e.stopPropagation();
if ((stateErrorStepButton as HTMLButtonElement).disabled) return;
const errors = getCurrentStateErrors();
const index = getShownStateError(errors).index + parseInt(stateErrorStepButton.getAttribute('data-step') || '0', 10);
if (errors[index]) showStateError(errors[index]);
return;
}
// go back to the shown state error in the Verification tab
if (target.closest?.('#state-error-reveal-btn')) {
e.stopPropagation();
const { error } = getShownStateError(getCurrentStateErrors());
const revealTarget = error && getDiagnosticRevealTarget(error);
if (revealTarget) revealDiagnostic(revealTarget);
return;
}
// VC implication simplification step buttons
const vcImplicationStepButton = target.closest?.('.vc-step-btn');
if (vcImplicationStepButton) {
e.stopPropagation();
handleVCImplicationStepClick(vcImplicationStepButton, () => {
root.querySelector<HTMLElement>('.highlight-var-btn.selected')?.classList.remove('selected');
vscode.postMessage({ type: 'highlight', range: null });
});
return;
}
// toggle show all diagnostics
if (target.id === 'show-all-button') {
e.stopPropagation();
showAllDiagnostics = !showAllDiagnostics;
updateView();
return;
}
// switch between file and workspace diagnostics
const scopeButton = target.closest?.('[data-diagnostics-scope]') as HTMLElement | null;
if (scopeButton) {
e.stopPropagation();
showAllDiagnostics = scopeButton.dataset.diagnosticsScope === 'workspace';
updateView();
return;
}
// toggle diagram orientation
if (target.closest?.('#diagram-orientation-btn')) {
e.stopPropagation();
diagramOrientation = diagramOrientation === "TB" ? "LR" : "TB";
resetZoom(document);
updateView();
return;
}
// toggle diagram conditions
const diagramConditionsButton = target.closest?.('#diagram-conditions-btn');
if (diagramConditionsButton) {
e.stopPropagation();
if ((diagramConditionsButton as HTMLButtonElement).disabled) return;
showDiagramConditions = !showDiagramConditions;
updateView();
return;
}
// toggle the dimming of the diagram parts unrelated to the selected state error
if (target.closest?.('#diagram-focus-btn')) {
e.stopPropagation();
focusDiagramOnError = !focusDiagramOnError;
updateView();
return;
}
// zoom in
if (target.closest?.('#zoom-in-btn')) {
e.stopPropagation();
zoomIn(document);
return;
}
// zoom out
if (target.closest?.('#zoom-out-btn')) {
e.stopPropagation();
zoomOut(document);
return;
}
// reset zoom
if (target.closest?.('#zoom-reset-btn')) {
e.stopPropagation();
resetZoom(document);
return;
}
// copy diagram source
const copyDiagramButton = target.closest?.('#copy-diagram-btn');
if (copyDiagramButton) {
e.stopPropagation();
if (!currentDiagram) return;
copyDiagramToClipboard(copyDiagramButton, currentDiagram);
return;
}
// highlight variable
const highlightButton = target.closest?.('.highlight-var-btn');
if (highlightButton) {
e.stopPropagation();
const previousSelected = root.querySelector<HTMLElement>('.highlight-var-btn.selected');
if (previousSelected) {
// unselect previous
previousSelected.classList.remove('selected');
if (previousSelected === highlightButton) {
// remove highlight
vscode.postMessage({ type: 'highlight', range: null });
return;
}
}
highlightButton.classList.add('selected');
(highlightButton as HTMLElement).focus();
highlightButton.scrollIntoView({ block: 'nearest' });
const file = highlightButton.getAttribute('data-file');
const lineStart = parseInt(highlightButton.getAttribute('data-start-line') || '', 10);
const colStart = parseInt(highlightButton.getAttribute('data-start-column') || '', 10);
const lineEnd = parseInt(highlightButton.getAttribute('data-end-line') || '', 10);
const colEnd = parseInt(highlightButton.getAttribute('data-end-column') || '', 10);
if (!file || [lineStart, colStart, lineEnd, colEnd].some(Number.isNaN)) return;
const range: Range = { lineStart, colStart, lineEnd, colEnd };
if (file !== currentFile) {
vscode.postMessage({ type: 'openFile', filePath: file, line: lineStart, character: colStart, highlightRange: range });
} else {
vscode.postMessage({ type: 'highlight', range });
}
return;
}
// nav tab click
if (target.classList.contains('nav-tab')) {
e.stopPropagation();
const tab = target.getAttribute('data-tab') as NavTab;
if (tab && tab !== selectedTab) {
vscode.postMessage({ type: 'highlight', range: null });
selectedTab = tab;
updateView();
}
return;
}
// copy diagnostic
const diagnosticCopyBtn = target.closest?.('.copy-diagnostic-btn');
if (diagnosticCopyBtn) {
e.preventDefault();
e.stopPropagation();
copyDiagnosticToClipboard(diagnosticCopyBtn, getDisplayDiagnostics(diagnostics || [], showAllDiagnostics, currentFile));
return;
}
});
// navigate context variables with the keyboard
window.addEventListener('keydown', (e: KeyboardEvent) => {
if (selectedTab !== 'context' || (e.key !== 'ArrowUp' && e.key !== 'ArrowDown')) return;
const buttons = Array.from(root.querySelectorAll<HTMLElement>('#context-vars:not(.collapsed) .highlight-var-btn'));
if (buttons.length === 0) return;
const selected = root.querySelector<HTMLElement>('.highlight-var-btn.selected');
const active = document.activeElement instanceof HTMLElement ? document.activeElement.closest<HTMLElement>('.highlight-var-btn') : null;
const current = selected || active;
const currentIndex = current ? buttons.indexOf(current) : -1;
const fallbackIndex = e.key === 'ArrowDown' ? 0 : buttons.length - 1;
const nextIndex = currentIndex === -1
? fallbackIndex
: Math.max(0, Math.min(buttons.length - 1, currentIndex + (e.key === 'ArrowDown' ? 1 : -1)));
e.preventDefault();
e.stopPropagation();
const highlightButton = buttons[nextIndex];
const previousSelected = root.querySelector<HTMLElement>('.highlight-var-btn.selected');
if (previousSelected) previousSelected.classList.remove('selected');
highlightButton.classList.add('selected');
highlightButton.focus();
highlightButton.scrollIntoView({ block: 'nearest' });
const file = highlightButton.getAttribute('data-file');
const lineStart = parseInt(highlightButton.getAttribute('data-start-line') || '', 10);
const colStart = parseInt(highlightButton.getAttribute('data-start-column') || '', 10);
const lineEnd = parseInt(highlightButton.getAttribute('data-end-line') || '', 10);
const colEnd = parseInt(highlightButton.getAttribute('data-end-column') || '', 10);
if (!file || [lineStart, colStart, lineEnd, colEnd].some(Number.isNaN)) return;
const range: Range = { lineStart, colStart, lineEnd, colEnd };
if (file !== currentFile) {
vscode.postMessage({ type: 'openFile', filePath: file, line: lineStart, character: colStart, highlightRange: range });
} else {
vscode.postMessage({ type: 'highlight', range });
}
});
// message event listener from extension
window.addEventListener('message', event => {
const msg = event.data;
switch (msg.type) {
case 'status':
status = msg.status as ExtensionStatus;
updateView();
break;
case 'diagnostics': {
const previousErrors = getAllStateErrors(diagnostics);
diagnostics = msg.diagnostics as LJDiagnostic[];
selectedStateError = findStateError(getAllStateErrors(diagnostics), selectedStateError, previousErrors);
if (selectedTab === 'fsm') updateStateMachineViewIfChanged();
else updateView();
break;
}
case 'file':
currentFile = msg.file;
// the view shows the first error of the new file instead
if (selectedStateError && selectedStateError.file.toLowerCase() !== currentFile?.toLowerCase()) selectedStateError = undefined;
if (diagnostics && !showAllDiagnostics && selectedTab === 'diagnostics') updateView();
stateMachines = [];
if (selectedTab === 'fsm') updateStateMachineViewIfChanged();
break;
case 'fsm':
stateMachines = (msg.sms as LJStateMachine[] | null) ?? [];
if (selectedTab === 'fsm') updateStateMachineViewIfChanged();
break;
case 'context':
context = msg.context as LJContext;
errorAtCursor = msg.errorAtCursor as RefinementMismatchError;
followCursorStateError(msg.errorAtCursor as LJDiagnostic | undefined);
if (selectedTab === 'context') updateView();
break;
case 'revealDiagnostic': {
const revealTarget = msg.diagnostic as DiagnosticRevealTarget;
const stateError = msg.tab === 'fsm' ? findStateErrorAt(revealTarget) : undefined;
if (stateError) showStateError(stateError);
else revealDiagnostic(revealTarget);
break;
}
}
});
/**
* Updates the webview content based on the current state
*/
function updateView() {
if (status === 'stopped' || status === 'crashed') {
currentDiagram = '';
root.innerHTML = renderStopped(status);
return;
}
if (status === 'loading') {
currentDiagram = '';
root.innerHTML = renderLoading();
return;
}
const stateErrors = getCurrentStateErrors();
const badges = { errors: getCurrentFileErrorCount(diagnostics, currentFile), stateErrors: stateErrors.length };
renderedStateMachineView = undefined;
switch (selectedTab) {
case 'diagnostics':
root.innerHTML = diagnostics
? renderDiagnosticsView(diagnostics, showAllDiagnostics, currentFile, badges)
: renderLoading();
break;
case 'fsm': {
const { error: shownError, index: shownIndex } = getShownStateError(stateErrors);
const displayedStateMachines = orderStateMachines(shownError?.stateMachines ?? stateMachines);
const focusOnError = focusDiagramOnError && !!shownError;
const diagrams = displayedStateMachines.map(sm =>
createMermaidDiagram(sm, diagramOrientation, showDiagramConditions, focusOnError, displayedStateMachines));
// copy the diagrams without the error overlay
currentDiagram = displayedStateMachines
.map(sm => createMermaidDiagram({ ...sm, errorContext: null }, diagramOrientation, showDiagramConditions, false, displayedStateMachines))
.join('\n\n');
renderStateMachineView(root, displayedStateMachines, diagrams, diagramOrientation, showDiagramConditions, focusOnError,
{ index: shownIndex, count: stateErrors.length, line: getStateErrorLine(shownError) }, badges);
renderedStateMachineView = getStateMachineViewKey();
if (displayedStateMachines.length > 0) renderMermaidDiagram(document, window);
break;
}
case 'context':
root.innerHTML = renderContextView(context, currentFile, contextSectionState, errorAtCursor, badges);
break;
}
}
// the 1-based line of the shown error, null without a position, undefined when no error is shown
function getStateErrorLine(error: StateRefinementError | undefined): number | null | undefined {
if (!error) return undefined;
return error.position ? error.position.lineStart + 1 : null;
}
function getCurrentStateErrors(): StateRefinementError[] {
return getStateErrors(diagnostics, currentFile);
}
/**
* Gets the state error the view shows and its index among the state errors of the current file
* This is the selected error, which is outside them when chosen from another file, or else the first one
*/
function getShownStateError(errors: StateRefinementError[]): { error: StateRefinementError | undefined; index: number } {
if (!selectedStateError) return { error: errors[0], index: errors.length > 0 ? 0 : -1 };
const key = getStateErrorKey(selectedStateError);
return { error: selectedStateError, index: errors.findIndex(error => getStateErrorKey(error) === key) };
}
function findStateErrorAt(target: DiagnosticRevealTarget): StateRefinementError | undefined {
const key = getDiagnosticRevealTargetKey(target);
return getAllStateErrors(diagnostics).find(error => getStateErrorKey(error) === key);
}
function showStateError(error: StateRefinementError) {
selectedTab = 'fsm';
selectedStateError = error;
showDiagramConditions = true;
focusDiagramOnError = true;
resetZoom(document);
currentDiagram = '';
updateView();
}
// shows the state error at the cursor once the cursor reaches it, without overriding later choices in the view
function followCursorStateError(error: LJDiagnostic | undefined) {
const stateError = error?.type === 'state-refinement-error' && error.stateMachines.length > 0 ? error : undefined;
const key = stateError ? getStateErrorKey(stateError) : undefined;
if (key === cursorStateErrorKey) return;
cursorStateErrorKey = key;
if (!stateError || (selectedStateError && getStateErrorKey(selectedStateError) === key)) return;
if (selectedTab === 'fsm') {
showStateError(stateError);
} else {
selectedStateError = stateError;
focusDiagramOnError = true;
}
}
// a new verification or file only re-renders the diagram when what it shows changed, so panning and focus are kept
function updateStateMachineViewIfChanged() {
if (status !== 'loading' && status !== 'stopped' && status !== 'crashed'
&& renderedStateMachineView === getStateMachineViewKey()) return;
currentDiagram = '';
updateView();
}
function getStateMachineViewKey(): string {
const stateErrors = getCurrentStateErrors();
const { error: shownError } = getShownStateError(stateErrors);
return JSON.stringify([shownError?.stateMachines ?? stateMachines, shownError ? getStateErrorKey(shownError) : null, stateErrors.length,
getCurrentFileErrorCount(diagnostics, currentFile)]);
}
function revealDiagnostic(target: DiagnosticRevealTarget) {
selectedTab = 'diagnostics';
const isVisibleInCurrentFile = showAllDiagnostics || !target.file || target.file.toLowerCase() === currentFile?.toLowerCase();
if (!isVisibleInCurrentFile) {
showAllDiagnostics = true;
}
updateView();
const element = Array.from(root.querySelectorAll<HTMLElement>('.diagnostic-item')).find(item =>
item.getAttribute('data-diagnostic-target') === getDiagnosticRevealTargetKey(target)
);
if (!element) return;
const previousRevealed = root.querySelector('.diagnostic-item.revealed');
if (previousRevealed) previousRevealed.classList.remove('revealed');
if (revealTimeout) clearTimeout(revealTimeout);
element.classList.add('revealed');
element.scrollIntoView({ block: 'center', behavior: 'smooth' });
revealTimeout = setTimeout(() => {
element.classList.remove('revealed');
revealTimeout = undefined;
}, 1800);
}
function revealContextForDiagnostic(target: DiagnosticRevealTarget) {
selectedTab = 'context';
vscode.postMessage({
type: 'openFile',
filePath: target.file,
line: target.position.lineEnd,
character: target.position.colEnd,
});
updateView();
}
}