-
Notifications
You must be signed in to change notification settings - Fork 28.9k
/
accessibleDiffViewer.ts
734 lines (629 loc) · 26.9 KB
/
accessibleDiffViewer.ts
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { addDisposableListener, addStandardDisposableListener, reset } from 'vs/base/browser/dom';
import { createTrustedTypesPolicy } from 'vs/base/browser/trustedTypes';
import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';
import { DomScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement';
import { Action } from 'vs/base/common/actions';
import { forEachAdjacent, groupAdjacentBy } from 'vs/base/common/arrays';
import { Codicon } from 'vs/base/common/codicons';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { Disposable, DisposableStore, toDisposable } from 'vs/base/common/lifecycle';
import { IObservable, ITransaction, autorun, autorunWithStore, derived, derivedWithStore, observableValue, subtransaction, transaction } from 'vs/base/common/observable';
import { ThemeIcon } from 'vs/base/common/themables';
import { applyFontInfo } from 'vs/editor/browser/config/domFontInfo';
import { applyStyle } from 'vs/editor/browser/widget/diffEditor/utils';
import { EditorFontLigatures, EditorOption, IComputedEditorOptions } from 'vs/editor/common/config/editorOptions';
import { LineRange } from 'vs/editor/common/core/lineRange';
import { OffsetRange } from 'vs/editor/common/core/offsetRange';
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { DetailedLineRangeMapping, LineRangeMapping } from 'vs/editor/common/diff/rangeMapping';
import { ILanguageIdCodec } from 'vs/editor/common/languages';
import { ILanguageService } from 'vs/editor/common/languages/language';
import { ITextModel, TextModelResolvedOptions } from 'vs/editor/common/model';
import { LineTokens } from 'vs/editor/common/tokens/lineTokens';
import { RenderLineInput, renderViewLine2 } from 'vs/editor/common/viewLayout/viewLineRenderer';
import { ViewLineRenderingData } from 'vs/editor/common/viewModel';
import { localize } from 'vs/nls';
import { AccessibilitySignal, IAccessibilitySignalService } from 'vs/platform/accessibilitySignal/browser/accessibilitySignalService';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { registerIcon } from 'vs/platform/theme/common/iconRegistry';
import 'vs/css!./accessibleDiffViewer';
import { DiffEditorEditors } from 'vs/editor/browser/widget/diffEditor/components/diffEditorEditors';
const accessibleDiffViewerInsertIcon = registerIcon('diff-review-insert', Codicon.add, localize('accessibleDiffViewerInsertIcon', 'Icon for \'Insert\' in accessible diff viewer.'));
const accessibleDiffViewerRemoveIcon = registerIcon('diff-review-remove', Codicon.remove, localize('accessibleDiffViewerRemoveIcon', 'Icon for \'Remove\' in accessible diff viewer.'));
const accessibleDiffViewerCloseIcon = registerIcon('diff-review-close', Codicon.close, localize('accessibleDiffViewerCloseIcon', 'Icon for \'Close\' in accessible diff viewer.'));
export interface IAccessibleDiffViewerModel {
getOriginalModel(): ITextModel;
getOriginalOptions(): IComputedEditorOptions;
/**
* Should do: `setSelection`, `revealLine` and `focus`
*/
originalReveal(range: Range): void;
getModifiedModel(): ITextModel;
getModifiedOptions(): IComputedEditorOptions;
/**
* Should do: `setSelection`, `revealLine` and `focus`
*/
modifiedReveal(range?: Range): void;
modifiedSetSelection(range: Range): void;
modifiedFocus(): void;
getModifiedPosition(): Position | undefined;
}
export class AccessibleDiffViewer extends Disposable {
public static _ttPolicy = createTrustedTypesPolicy('diffReview', { createHTML: value => value });
constructor(
private readonly _parentNode: HTMLElement,
private readonly _visible: IObservable<boolean>,
private readonly _setVisible: (visible: boolean, tx: ITransaction | undefined) => void,
private readonly _canClose: IObservable<boolean>,
private readonly _width: IObservable<number>,
private readonly _height: IObservable<number>,
private readonly _diffs: IObservable<DetailedLineRangeMapping[] | undefined>,
private readonly _models: IAccessibleDiffViewerModel,
@IInstantiationService private readonly _instantiationService: IInstantiationService,
) {
super();
}
private readonly _state = derivedWithStore(this, (reader, store) => {
const visible = this._visible.read(reader);
this._parentNode.style.visibility = visible ? 'visible' : 'hidden';
if (!visible) {
return null;
}
const model = store.add(this._instantiationService.createInstance(ViewModel, this._diffs, this._models, this._setVisible, this._canClose));
const view = store.add(this._instantiationService.createInstance(View, this._parentNode, model, this._width, this._height, this._models));
return { model, view, };
}).recomputeInitiallyAndOnChange(this._store);
next(): void {
transaction(tx => {
const isVisible = this._visible.get();
this._setVisible(true, tx);
if (isVisible) {
this._state.get()!.model.nextGroup(tx);
}
});
}
prev(): void {
transaction(tx => {
this._setVisible(true, tx);
this._state.get()!.model.previousGroup(tx);
});
}
close(): void {
transaction(tx => {
this._setVisible(false, tx);
});
}
}
class ViewModel extends Disposable {
private readonly _groups = observableValue<ViewElementGroup[]>(this, []);
private readonly _currentGroupIdx = observableValue(this, 0);
private readonly _currentElementIdx = observableValue(this, 0);
public readonly groups: IObservable<ViewElementGroup[]> = this._groups;
public readonly currentGroup: IObservable<ViewElementGroup | undefined>
= this._currentGroupIdx.map((idx, r) => this._groups.read(r)[idx]);
public readonly currentGroupIndex: IObservable<number> = this._currentGroupIdx;
public readonly currentElement: IObservable<ViewElement | undefined>
= this._currentElementIdx.map((idx, r) => this.currentGroup.read(r)?.lines[idx]);
constructor(
private readonly _diffs: IObservable<DetailedLineRangeMapping[] | undefined>,
private readonly _models: IAccessibleDiffViewerModel,
private readonly _setVisible: (visible: boolean, tx: ITransaction | undefined) => void,
public readonly canClose: IObservable<boolean>,
@IAccessibilitySignalService private readonly _accessibilitySignalService: IAccessibilitySignalService,
) {
super();
this._register(autorun(reader => {
/** @description update groups */
const diffs = this._diffs.read(reader);
if (!diffs) {
this._groups.set([], undefined);
return;
}
const groups = computeViewElementGroups(
diffs,
this._models.getOriginalModel().getLineCount(),
this._models.getModifiedModel().getLineCount()
);
transaction(tx => {
const p = this._models.getModifiedPosition();
if (p) {
const nextGroup = groups.findIndex(g => p?.lineNumber < g.range.modified.endLineNumberExclusive);
if (nextGroup !== -1) {
this._currentGroupIdx.set(nextGroup, tx);
}
}
this._groups.set(groups, tx);
});
}));
this._register(autorun(reader => {
/** @description play audio-cue for diff */
const currentViewItem = this.currentElement.read(reader);
if (currentViewItem?.type === LineType.Deleted) {
this._accessibilitySignalService.playSignal(AccessibilitySignal.diffLineDeleted, { source: 'accessibleDiffViewer.currentElementChanged' });
} else if (currentViewItem?.type === LineType.Added) {
this._accessibilitySignalService.playSignal(AccessibilitySignal.diffLineInserted, { source: 'accessibleDiffViewer.currentElementChanged' });
}
}));
this._register(autorun(reader => {
/** @description select lines in editor */
// This ensures editor commands (like revert/stage) work
const currentViewItem = this.currentElement.read(reader);
if (currentViewItem && currentViewItem.type !== LineType.Header) {
const lineNumber = currentViewItem.modifiedLineNumber ?? currentViewItem.diff.modified.startLineNumber;
this._models.modifiedSetSelection(Range.fromPositions(new Position(lineNumber, 1)));
}
}));
}
private _goToGroupDelta(delta: number, tx?: ITransaction): void {
const groups = this.groups.get();
if (!groups || groups.length <= 1) { return; }
subtransaction(tx, tx => {
this._currentGroupIdx.set(OffsetRange.ofLength(groups.length).clipCyclic(this._currentGroupIdx.get() + delta), tx);
this._currentElementIdx.set(0, tx);
});
}
nextGroup(tx?: ITransaction): void { this._goToGroupDelta(1, tx); }
previousGroup(tx?: ITransaction): void { this._goToGroupDelta(-1, tx); }
private _goToLineDelta(delta: number): void {
const group = this.currentGroup.get();
if (!group || group.lines.length <= 1) { return; }
transaction(tx => {
this._currentElementIdx.set(OffsetRange.ofLength(group.lines.length).clip(this._currentElementIdx.get() + delta), tx);
});
}
goToNextLine(): void { this._goToLineDelta(1); }
goToPreviousLine(): void { this._goToLineDelta(-1); }
goToLine(line: ViewElement): void {
const group = this.currentGroup.get();
if (!group) { return; }
const idx = group.lines.indexOf(line);
if (idx === -1) { return; }
transaction(tx => {
this._currentElementIdx.set(idx, tx);
});
}
revealCurrentElementInEditor(): void {
if (!this.canClose.get()) { return; }
this._setVisible(false, undefined);
const curElem = this.currentElement.get();
if (curElem) {
if (curElem.type === LineType.Deleted) {
this._models.originalReveal(Range.fromPositions(new Position(curElem.originalLineNumber, 1)));
} else {
this._models.modifiedReveal(
curElem.type !== LineType.Header
? Range.fromPositions(new Position(curElem.modifiedLineNumber, 1))
: undefined
);
}
}
}
close(): void {
if (!this.canClose.get()) { return; }
this._setVisible(false, undefined);
this._models.modifiedFocus();
}
}
const viewElementGroupLineMargin = 3;
function computeViewElementGroups(diffs: DetailedLineRangeMapping[], originalLineCount: number, modifiedLineCount: number): ViewElementGroup[] {
const result: ViewElementGroup[] = [];
for (const g of groupAdjacentBy(diffs, (a, b) => (b.modified.startLineNumber - a.modified.endLineNumberExclusive < 2 * viewElementGroupLineMargin))) {
const viewElements: ViewElement[] = [];
viewElements.push(new HeaderViewElement());
const origFullRange = new LineRange(
Math.max(1, g[0].original.startLineNumber - viewElementGroupLineMargin),
Math.min(g[g.length - 1].original.endLineNumberExclusive + viewElementGroupLineMargin, originalLineCount + 1)
);
const modifiedFullRange = new LineRange(
Math.max(1, g[0].modified.startLineNumber - viewElementGroupLineMargin),
Math.min(g[g.length - 1].modified.endLineNumberExclusive + viewElementGroupLineMargin, modifiedLineCount + 1)
);
forEachAdjacent(g, (a, b) => {
const origRange = new LineRange(a ? a.original.endLineNumberExclusive : origFullRange.startLineNumber, b ? b.original.startLineNumber : origFullRange.endLineNumberExclusive);
const modifiedRange = new LineRange(a ? a.modified.endLineNumberExclusive : modifiedFullRange.startLineNumber, b ? b.modified.startLineNumber : modifiedFullRange.endLineNumberExclusive);
origRange.forEach(origLineNumber => {
viewElements.push(new UnchangedLineViewElement(origLineNumber, modifiedRange.startLineNumber + (origLineNumber - origRange.startLineNumber)));
});
if (b) {
b.original.forEach(origLineNumber => {
viewElements.push(new DeletedLineViewElement(b, origLineNumber));
});
b.modified.forEach(modifiedLineNumber => {
viewElements.push(new AddedLineViewElement(b, modifiedLineNumber));
});
}
});
const modifiedRange = g[0].modified.join(g[g.length - 1].modified);
const originalRange = g[0].original.join(g[g.length - 1].original);
result.push(new ViewElementGroup(new LineRangeMapping(modifiedRange, originalRange), viewElements));
}
return result;
}
enum LineType {
Header,
Unchanged,
Deleted,
Added,
}
class ViewElementGroup {
constructor(
public readonly range: LineRangeMapping,
public readonly lines: readonly ViewElement[],
) { }
}
type ViewElement = HeaderViewElement | UnchangedLineViewElement | DeletedLineViewElement | AddedLineViewElement;
class HeaderViewElement {
public readonly type = LineType.Header;
}
class DeletedLineViewElement {
public readonly type = LineType.Deleted;
public readonly modifiedLineNumber = undefined;
constructor(
public readonly diff: DetailedLineRangeMapping,
public readonly originalLineNumber: number,
) {
}
}
class AddedLineViewElement {
public readonly type = LineType.Added;
public readonly originalLineNumber = undefined;
constructor(
public readonly diff: DetailedLineRangeMapping,
public readonly modifiedLineNumber: number,
) {
}
}
class UnchangedLineViewElement {
public readonly type = LineType.Unchanged;
constructor(
public readonly originalLineNumber: number,
public readonly modifiedLineNumber: number,
) {
}
}
class View extends Disposable {
public readonly domNode: HTMLElement;
private readonly _content: HTMLElement;
private readonly _scrollbar: DomScrollableElement;
private readonly _actionBar: ActionBar;
constructor(
private readonly _element: HTMLElement,
private readonly _model: ViewModel,
private readonly _width: IObservable<number>,
private readonly _height: IObservable<number>,
private readonly _models: IAccessibleDiffViewerModel,
@ILanguageService private readonly _languageService: ILanguageService,
) {
super();
this.domNode = this._element;
this.domNode.className = 'monaco-component diff-review monaco-editor-background';
const actionBarContainer = document.createElement('div');
actionBarContainer.className = 'diff-review-actions';
this._actionBar = this._register(new ActionBar(
actionBarContainer
));
this._register(autorun(reader => {
/** @description update actions */
this._actionBar.clear();
if (this._model.canClose.read(reader)) {
this._actionBar.push(new Action(
'diffreview.close',
localize('label.close', "Close"),
'close-diff-review ' + ThemeIcon.asClassName(accessibleDiffViewerCloseIcon),
true,
async () => _model.close()
), { label: false, icon: true });
}
}));
this._content = document.createElement('div');
this._content.className = 'diff-review-content';
this._content.setAttribute('role', 'code');
this._scrollbar = this._register(new DomScrollableElement(this._content, {}));
reset(this.domNode, this._scrollbar.getDomNode(), actionBarContainer);
this._register(autorun(r => {
this._height.read(r);
this._width.read(r);
this._scrollbar.scanDomNode();
}));
this._register(toDisposable(() => { reset(this.domNode); }));
this._register(applyStyle(this.domNode, { width: this._width, height: this._height }));
this._register(applyStyle(this._content, { width: this._width, height: this._height }));
this._register(autorunWithStore((reader, store) => {
/** @description render */
this._model.currentGroup.read(reader);
this._render(store);
}));
// TODO@hediet use commands
this._register(addStandardDisposableListener(this.domNode, 'keydown', (e) => {
if (
e.equals(KeyCode.DownArrow)
|| e.equals(KeyMod.CtrlCmd | KeyCode.DownArrow)
|| e.equals(KeyMod.Alt | KeyCode.DownArrow)
) {
e.preventDefault();
this._model.goToNextLine();
}
if (
e.equals(KeyCode.UpArrow)
|| e.equals(KeyMod.CtrlCmd | KeyCode.UpArrow)
|| e.equals(KeyMod.Alt | KeyCode.UpArrow)
) {
e.preventDefault();
this._model.goToPreviousLine();
}
if (
e.equals(KeyCode.Escape)
|| e.equals(KeyMod.CtrlCmd | KeyCode.Escape)
|| e.equals(KeyMod.Alt | KeyCode.Escape)
|| e.equals(KeyMod.Shift | KeyCode.Escape)
) {
e.preventDefault();
this._model.close();
}
if (
e.equals(KeyCode.Space)
|| e.equals(KeyCode.Enter)
) {
e.preventDefault();
this._model.revealCurrentElementInEditor();
}
}));
}
private _render(store: DisposableStore): void {
const originalOptions = this._models.getOriginalOptions();
const modifiedOptions = this._models.getModifiedOptions();
const container = document.createElement('div');
container.className = 'diff-review-table';
container.setAttribute('role', 'list');
container.setAttribute('aria-label', localize('ariaLabel', 'Accessible Diff Viewer. Use arrow up and down to navigate.'));
applyFontInfo(container, modifiedOptions.get(EditorOption.fontInfo));
reset(this._content, container);
const originalModel = this._models.getOriginalModel();
const modifiedModel = this._models.getModifiedModel();
if (!originalModel || !modifiedModel) {
return;
}
const originalModelOpts = originalModel.getOptions();
const modifiedModelOpts = modifiedModel.getOptions();
const lineHeight = modifiedOptions.get(EditorOption.lineHeight);
const group = this._model.currentGroup.get();
for (const viewItem of group?.lines || []) {
if (!group) {
break;
}
let row: HTMLDivElement;
if (viewItem.type === LineType.Header) {
const header = document.createElement('div');
header.className = 'diff-review-row';
header.setAttribute('role', 'listitem');
const r = group.range;
const diffIndex = this._model.currentGroupIndex.get();
const diffsLength = this._model.groups.get().length;
const getAriaLines = (lines: number) =>
lines === 0 ? localize('no_lines_changed', "no lines changed")
: lines === 1 ? localize('one_line_changed', "1 line changed")
: localize('more_lines_changed', "{0} lines changed", lines);
const originalChangedLinesCntAria = getAriaLines(r.original.length);
const modifiedChangedLinesCntAria = getAriaLines(r.modified.length);
header.setAttribute('aria-label', localize({
key: 'header',
comment: [
'This is the ARIA label for a git diff header.',
'A git diff header looks like this: @@ -154,12 +159,39 @@.',
'That encodes that at original line 154 (which is now line 159), 12 lines were removed/changed with 39 lines.',
'Variables 0 and 1 refer to the diff index out of total number of diffs.',
'Variables 2 and 4 will be numbers (a line number).',
'Variables 3 and 5 will be "no lines changed", "1 line changed" or "X lines changed", localized separately.'
]
}, "Difference {0} of {1}: original line {2}, {3}, modified line {4}, {5}",
(diffIndex + 1),
diffsLength,
r.original.startLineNumber,
originalChangedLinesCntAria,
r.modified.startLineNumber,
modifiedChangedLinesCntAria
));
const cell = document.createElement('div');
cell.className = 'diff-review-cell diff-review-summary';
// e.g.: `1/10: @@ -504,7 +517,7 @@`
cell.appendChild(document.createTextNode(`${diffIndex + 1}/${diffsLength}: @@ -${r.original.startLineNumber},${r.original.length} +${r.modified.startLineNumber},${r.modified.length} @@`));
header.appendChild(cell);
row = header;
} else {
row = this._createRow(viewItem, lineHeight,
this._width.get(), originalOptions, originalModel, originalModelOpts, modifiedOptions, modifiedModel, modifiedModelOpts,
);
}
container.appendChild(row);
const isSelectedObs = derived(reader => /** @description isSelected */ this._model.currentElement.read(reader) === viewItem);
store.add(autorun(reader => {
/** @description update tab index */
const isSelected = isSelectedObs.read(reader);
row.tabIndex = isSelected ? 0 : -1;
if (isSelected) {
row.focus();
}
}));
store.add(addDisposableListener(row, 'focus', () => {
this._model.goToLine(viewItem);
}));
}
this._scrollbar.scanDomNode();
}
private _createRow(
item: DeletedLineViewElement | AddedLineViewElement | UnchangedLineViewElement,
lineHeight: number,
width: number,
originalOptions: IComputedEditorOptions, originalModel: ITextModel, originalModelOpts: TextModelResolvedOptions,
modifiedOptions: IComputedEditorOptions, modifiedModel: ITextModel, modifiedModelOpts: TextModelResolvedOptions,
): HTMLDivElement {
const originalLayoutInfo = originalOptions.get(EditorOption.layoutInfo);
const originalLineNumbersWidth = originalLayoutInfo.glyphMarginWidth + originalLayoutInfo.lineNumbersWidth;
const modifiedLayoutInfo = modifiedOptions.get(EditorOption.layoutInfo);
const modifiedLineNumbersWidth = 10 + modifiedLayoutInfo.glyphMarginWidth + modifiedLayoutInfo.lineNumbersWidth;
let rowClassName: string = 'diff-review-row';
let lineNumbersExtraClassName: string = '';
const spacerClassName: string = 'diff-review-spacer';
let spacerIcon: ThemeIcon | null = null;
switch (item.type) {
case LineType.Added:
rowClassName = 'diff-review-row line-insert';
lineNumbersExtraClassName = ' char-insert';
spacerIcon = accessibleDiffViewerInsertIcon;
break;
case LineType.Deleted:
rowClassName = 'diff-review-row line-delete';
lineNumbersExtraClassName = ' char-delete';
spacerIcon = accessibleDiffViewerRemoveIcon;
break;
}
const row = document.createElement('div');
row.style.minWidth = width + 'px';
row.className = rowClassName;
row.setAttribute('role', 'listitem');
row.ariaLevel = '';
const cell = document.createElement('div');
cell.className = 'diff-review-cell';
cell.style.height = `${lineHeight}px`;
row.appendChild(cell);
const originalLineNumber = document.createElement('span');
originalLineNumber.style.width = (originalLineNumbersWidth + 'px');
originalLineNumber.style.minWidth = (originalLineNumbersWidth + 'px');
originalLineNumber.className = 'diff-review-line-number' + lineNumbersExtraClassName;
if (item.originalLineNumber !== undefined) {
originalLineNumber.appendChild(document.createTextNode(String(item.originalLineNumber)));
} else {
originalLineNumber.innerText = '\u00a0';
}
cell.appendChild(originalLineNumber);
const modifiedLineNumber = document.createElement('span');
modifiedLineNumber.style.width = (modifiedLineNumbersWidth + 'px');
modifiedLineNumber.style.minWidth = (modifiedLineNumbersWidth + 'px');
modifiedLineNumber.style.paddingRight = '10px';
modifiedLineNumber.className = 'diff-review-line-number' + lineNumbersExtraClassName;
if (item.modifiedLineNumber !== undefined) {
modifiedLineNumber.appendChild(document.createTextNode(String(item.modifiedLineNumber)));
} else {
modifiedLineNumber.innerText = '\u00a0';
}
cell.appendChild(modifiedLineNumber);
const spacer = document.createElement('span');
spacer.className = spacerClassName;
if (spacerIcon) {
const spacerCodicon = document.createElement('span');
spacerCodicon.className = ThemeIcon.asClassName(spacerIcon);
spacerCodicon.innerText = '\u00a0\u00a0';
spacer.appendChild(spacerCodicon);
} else {
spacer.innerText = '\u00a0\u00a0';
}
cell.appendChild(spacer);
let lineContent: string;
if (item.modifiedLineNumber !== undefined) {
let html: string | TrustedHTML = this._getLineHtml(modifiedModel, modifiedOptions, modifiedModelOpts.tabSize, item.modifiedLineNumber, this._languageService.languageIdCodec);
if (AccessibleDiffViewer._ttPolicy) {
html = AccessibleDiffViewer._ttPolicy.createHTML(html as string);
}
cell.insertAdjacentHTML('beforeend', html as string);
lineContent = modifiedModel.getLineContent(item.modifiedLineNumber);
} else {
let html: string | TrustedHTML = this._getLineHtml(originalModel, originalOptions, originalModelOpts.tabSize, item.originalLineNumber, this._languageService.languageIdCodec);
if (AccessibleDiffViewer._ttPolicy) {
html = AccessibleDiffViewer._ttPolicy.createHTML(html as string);
}
cell.insertAdjacentHTML('beforeend', html as string);
lineContent = originalModel.getLineContent(item.originalLineNumber);
}
if (lineContent.length === 0) {
lineContent = localize('blankLine', "blank");
}
let ariaLabel: string = '';
switch (item.type) {
case LineType.Unchanged:
if (item.originalLineNumber === item.modifiedLineNumber) {
ariaLabel = localize({ key: 'unchangedLine', comment: ['The placeholders are contents of the line and should not be translated.'] }, "{0} unchanged line {1}", lineContent, item.originalLineNumber);
} else {
ariaLabel = localize('equalLine', "{0} original line {1} modified line {2}", lineContent, item.originalLineNumber, item.modifiedLineNumber);
}
break;
case LineType.Added:
ariaLabel = localize('insertLine', "+ {0} modified line {1}", lineContent, item.modifiedLineNumber);
break;
case LineType.Deleted:
ariaLabel = localize('deleteLine', "- {0} original line {1}", lineContent, item.originalLineNumber);
break;
}
row.setAttribute('aria-label', ariaLabel);
return row;
}
private _getLineHtml(model: ITextModel, options: IComputedEditorOptions, tabSize: number, lineNumber: number, languageIdCodec: ILanguageIdCodec): string {
const lineContent = model.getLineContent(lineNumber);
const fontInfo = options.get(EditorOption.fontInfo);
const lineTokens = LineTokens.createEmpty(lineContent, languageIdCodec);
const isBasicASCII = ViewLineRenderingData.isBasicASCII(lineContent, model.mightContainNonBasicASCII());
const containsRTL = ViewLineRenderingData.containsRTL(lineContent, isBasicASCII, model.mightContainRTL());
const r = renderViewLine2(new RenderLineInput(
(fontInfo.isMonospace && !options.get(EditorOption.disableMonospaceOptimizations)),
fontInfo.canUseHalfwidthRightwardsArrow,
lineContent,
false,
isBasicASCII,
containsRTL,
0,
lineTokens,
[],
tabSize,
0,
fontInfo.spaceWidth,
fontInfo.middotWidth,
fontInfo.wsmiddotWidth,
options.get(EditorOption.stopRenderingLineAfter),
options.get(EditorOption.renderWhitespace),
options.get(EditorOption.renderControlCharacters),
options.get(EditorOption.fontLigatures) !== EditorFontLigatures.OFF,
null
));
return r.html;
}
}
export class AccessibleDiffViewerModelFromEditors implements IAccessibleDiffViewerModel {
constructor(private readonly editors: DiffEditorEditors) { }
getOriginalModel(): ITextModel {
return this.editors.original.getModel()!;
}
getOriginalOptions(): IComputedEditorOptions {
return this.editors.original.getOptions();
}
originalReveal(range: Range): void {
this.editors.original.revealRange(range);
this.editors.original.setSelection(range);
this.editors.original.focus();
}
getModifiedModel(): ITextModel {
return this.editors.modified.getModel()!;
}
getModifiedOptions(): IComputedEditorOptions {
return this.editors.modified.getOptions();
}
modifiedReveal(range?: Range | undefined): void {
if (range) {
this.editors.modified.revealRange(range);
this.editors.modified.setSelection(range);
}
this.editors.modified.focus();
}
modifiedSetSelection(range: Range): void {
this.editors.modified.setSelection(range);
}
modifiedFocus(): void {
this.editors.modified.focus();
}
getModifiedPosition(): Position | undefined {
return this.editors.modified.getPosition() ?? undefined;
}
}