-
Notifications
You must be signed in to change notification settings - Fork 30k
/
contentHover.ts
708 lines (596 loc) · 25.5 KB
/
contentHover.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as dom from 'vs/base/browser/dom';
import { HoverAction, HoverWidget } from 'vs/base/browser/ui/hover/hoverWidget';
import { coalesce } from 'vs/base/common/arrays';
import { CancellationToken } from 'vs/base/common/cancellation';
import { KeyCode } from 'vs/base/common/keyCodes';
import { Disposable, DisposableStore, toDisposable } from 'vs/base/common/lifecycle';
import { ContentWidgetPositionPreference, IActiveCodeEditor, ICodeEditor, IContentWidget, IContentWidgetPosition, IEditorMouseEvent, MouseTargetType } from 'vs/editor/browser/editorBrowser';
import { ConfigurationChangedEvent, EditorOption } from 'vs/editor/common/config/editorOptions';
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { IModelDecoration, PositionAffinity } from 'vs/editor/common/model';
import { ModelDecorationOptions } from 'vs/editor/common/model/textModel';
import { TokenizationRegistry } from 'vs/editor/common/languages';
import { HoverOperation, HoverStartMode, IHoverComputer } from 'vs/editor/contrib/hover/browser/hoverOperation';
import { HoverAnchor, HoverAnchorType, HoverParticipantRegistry, HoverRangeAnchor, IEditorHoverColorPickerWidget, IEditorHoverAction, IEditorHoverParticipant, IEditorHoverRenderContext, IEditorHoverStatusBar, IHoverPart } from 'vs/editor/contrib/hover/browser/hoverTypes';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { Context as SuggestContext } from 'vs/editor/contrib/suggest/browser/suggest';
import { AsyncIterableObject } from 'vs/base/common/async';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { Constants } from 'vs/base/common/uint';
const $ = dom.$;
export class ContentHoverController extends Disposable {
private readonly _participants: IEditorHoverParticipant[];
private readonly _widget = this._register(this._instantiationService.createInstance(ContentHoverWidget, this._editor));
private readonly _computer: ContentHoverComputer;
private readonly _hoverOperation: HoverOperation<IHoverPart>;
private _currentResult: HoverResult | null = null;
constructor(
private readonly _editor: ICodeEditor,
@IInstantiationService private readonly _instantiationService: IInstantiationService,
@IKeybindingService private readonly _keybindingService: IKeybindingService,
) {
super();
// Instantiate participants and sort them by `hoverOrdinal` which is relevant for rendering order.
this._participants = [];
for (const participant of HoverParticipantRegistry.getAll()) {
this._participants.push(this._instantiationService.createInstance(participant, this._editor));
}
this._participants.sort((p1, p2) => p1.hoverOrdinal - p2.hoverOrdinal);
this._computer = new ContentHoverComputer(this._editor, this._participants);
this._hoverOperation = this._register(new HoverOperation(this._editor, this._computer));
this._register(this._hoverOperation.onResult((result) => {
if (!this._computer.anchor) {
// invalid state, ignore result
return;
}
const messages = (result.hasLoadingMessage ? this._addLoadingMessage(result.value) : result.value);
this._withResult(new HoverResult(this._computer.anchor, messages, result.isComplete));
}));
this._register(dom.addStandardDisposableListener(this._widget.getDomNode(), 'keydown', (e) => {
if (e.equals(KeyCode.Escape)) {
this.hide();
}
}));
this._register(TokenizationRegistry.onDidChange(() => {
if (this._widget.position && this._currentResult) {
this._widget.clear();
this._setCurrentResult(this._currentResult); // render again
}
}));
}
/**
* Returns true if the hover shows now or will show.
*/
public maybeShowAt(mouseEvent: IEditorMouseEvent): boolean {
const anchorCandidates: HoverAnchor[] = [];
for (const participant of this._participants) {
if (participant.suggestHoverAnchor) {
const anchor = participant.suggestHoverAnchor(mouseEvent);
if (anchor) {
anchorCandidates.push(anchor);
}
}
}
const target = mouseEvent.target;
if (target.type === MouseTargetType.CONTENT_TEXT) {
anchorCandidates.push(new HoverRangeAnchor(0, target.range, mouseEvent.event.posx, mouseEvent.event.posy));
}
if (target.type === MouseTargetType.CONTENT_EMPTY) {
const epsilon = this._editor.getOption(EditorOption.fontInfo).typicalHalfwidthCharacterWidth / 2;
if (!target.detail.isAfterLines && typeof target.detail.horizontalDistanceToText === 'number' && target.detail.horizontalDistanceToText < epsilon) {
// Let hover kick in even when the mouse is technically in the empty area after a line, given the distance is small enough
anchorCandidates.push(new HoverRangeAnchor(0, target.range, mouseEvent.event.posx, mouseEvent.event.posy));
}
}
if (anchorCandidates.length === 0) {
return this._startShowingOrUpdateHover(null, HoverStartMode.Delayed, false, mouseEvent);
}
anchorCandidates.sort((a, b) => b.priority - a.priority);
return this._startShowingOrUpdateHover(anchorCandidates[0], HoverStartMode.Delayed, false, mouseEvent);
}
public startShowingAtRange(range: Range, mode: HoverStartMode, focus: boolean): void {
this._startShowingOrUpdateHover(new HoverRangeAnchor(0, range, undefined, undefined), mode, focus, null);
}
/**
* Returns true if the hover shows now or will show.
*/
private _startShowingOrUpdateHover(anchor: HoverAnchor | null, mode: HoverStartMode, focus: boolean, mouseEvent: IEditorMouseEvent | null): boolean {
if (!this._widget.position || !this._currentResult) {
// The hover is not visible
if (anchor) {
this._startHoverOperationIfNecessary(anchor, mode, focus, false);
return true;
}
return false;
}
// The hover is currently visible
const hoverIsSticky = this._editor.getOption(EditorOption.hover).sticky;
const isGettingCloser = (hoverIsSticky && mouseEvent && this._widget.isMouseGettingCloser(mouseEvent.event.posx, mouseEvent.event.posy));
if (isGettingCloser) {
// The mouse is getting closer to the hover, so we will keep the hover untouched
// But we will kick off a hover update at the new anchor, insisting on keeping the hover visible.
if (anchor) {
this._startHoverOperationIfNecessary(anchor, mode, focus, true);
}
return true;
}
if (!anchor) {
this._setCurrentResult(null);
return false;
}
if (anchor && this._currentResult.anchor.equals(anchor)) {
// The widget is currently showing results for the exact same anchor, so no update is needed
return true;
}
if (!anchor.canAdoptVisibleHover(this._currentResult.anchor, this._widget.position)) {
// The new anchor is not compatible with the previous anchor
this._setCurrentResult(null);
this._startHoverOperationIfNecessary(anchor, mode, focus, false);
return true;
}
// We aren't getting any closer to the hover, so we will filter existing results
// and keep those which also apply to the new anchor.
this._setCurrentResult(this._currentResult.filter(anchor));
this._startHoverOperationIfNecessary(anchor, mode, focus, false);
return true;
}
private _startHoverOperationIfNecessary(anchor: HoverAnchor, mode: HoverStartMode, focus: boolean, insistOnKeepingHoverVisible: boolean): void {
if (this._computer.anchor && this._computer.anchor.equals(anchor)) {
// We have to start a hover operation at the exact same anchor as before, so no work is needed
return;
}
this._hoverOperation.cancel();
this._computer.anchor = anchor;
this._computer.shouldFocus = focus;
this._computer.insistOnKeepingHoverVisible = insistOnKeepingHoverVisible;
this._hoverOperation.start(mode);
}
private _setCurrentResult(hoverResult: HoverResult | null): void {
if (this._currentResult === hoverResult) {
// avoid updating the DOM to avoid resetting the user selection
return;
}
if (hoverResult && hoverResult.messages.length === 0) {
hoverResult = null;
}
this._currentResult = hoverResult;
if (this._currentResult) {
this._renderMessages(this._currentResult.anchor, this._currentResult.messages);
} else {
this._widget.hide();
}
}
public hide(): void {
this._computer.anchor = null;
this._hoverOperation.cancel();
this._setCurrentResult(null);
}
public isColorPickerVisible(): boolean {
return this._widget.isColorPickerVisible;
}
public containsNode(node: Node): boolean {
return this._widget.getDomNode().contains(node);
}
private _addLoadingMessage(result: IHoverPart[]): IHoverPart[] {
if (this._computer.anchor) {
for (const participant of this._participants) {
if (participant.createLoadingMessage) {
const loadingMessage = participant.createLoadingMessage(this._computer.anchor);
if (loadingMessage) {
return result.slice(0).concat([loadingMessage]);
}
}
}
}
return result;
}
private _withResult(hoverResult: HoverResult): void {
if (this._widget.position && this._currentResult && this._currentResult.isComplete) {
// The hover is visible with a previous complete result.
if (!hoverResult.isComplete) {
// Instead of rendering the new partial result, we wait for the result to be complete.
return;
}
if (this._computer.insistOnKeepingHoverVisible && hoverResult.messages.length === 0) {
// The hover would now hide normally, so we'll keep the previous messages
return;
}
}
this._setCurrentResult(hoverResult);
}
private _renderMessages(anchor: HoverAnchor, messages: IHoverPart[]): void {
const { showAtPosition, showAtRange, highlightRange } = ContentHoverController.computeHoverRanges(this._editor, anchor.range, messages);
const disposables = new DisposableStore();
const statusBar = disposables.add(new EditorHoverStatusBar(this._keybindingService));
const fragment = document.createDocumentFragment();
let colorPicker: IEditorHoverColorPickerWidget | null = null;
const context: IEditorHoverRenderContext = {
fragment,
statusBar,
setColorPicker: (widget) => colorPicker = widget,
onContentsChanged: () => this._widget.onContentsChanged(),
hide: () => this.hide()
};
for (const participant of this._participants) {
const hoverParts = messages.filter(msg => msg.owner === participant);
if (hoverParts.length > 0) {
disposables.add(participant.renderHoverParts(context, hoverParts));
}
}
const isBeforeContent = messages.some(m => m.isBeforeContent);
if (statusBar.hasContent) {
fragment.appendChild(statusBar.hoverElement);
}
if (fragment.hasChildNodes()) {
if (highlightRange) {
const highlightDecoration = this._editor.createDecorationsCollection();
highlightDecoration.set([{
range: highlightRange,
options: ContentHoverController._DECORATION_OPTIONS
}]);
disposables.add(toDisposable(() => {
highlightDecoration.clear();
}));
}
this._widget.showAt(fragment, new ContentHoverVisibleData(
colorPicker,
showAtPosition,
showAtRange,
this._editor.getOption(EditorOption.hover).above,
this._computer.shouldFocus,
isBeforeContent,
anchor.initialMousePosX,
anchor.initialMousePosY,
disposables
));
} else {
disposables.dispose();
}
}
private static readonly _DECORATION_OPTIONS = ModelDecorationOptions.register({
description: 'content-hover-highlight',
className: 'hoverHighlight'
});
public static computeHoverRanges(editor: ICodeEditor, anchorRange: Range, messages: IHoverPart[]) {
let startColumnBoundary = 1;
let endColumnBoundary = Constants.MAX_SAFE_SMALL_INTEGER;
if (editor.hasModel()) {
// Ensure the range is on the current view line
const viewModel = editor._getViewModel();
const coordinatesConverter = viewModel.coordinatesConverter;
const anchorViewRange = coordinatesConverter.convertModelRangeToViewRange(anchorRange);
const anchorViewRangeStart = new Position(anchorViewRange.startLineNumber, viewModel.getLineMinColumn(anchorViewRange.startLineNumber));
const anchorViewRangeEnd = new Position(anchorViewRange.endLineNumber, viewModel.getLineMaxColumn(anchorViewRange.endLineNumber));
startColumnBoundary = coordinatesConverter.convertViewPositionToModelPosition(anchorViewRangeStart).column;
endColumnBoundary = coordinatesConverter.convertViewPositionToModelPosition(anchorViewRangeEnd).column;
}
// The anchor range is always on a single line
const anchorLineNumber = anchorRange.startLineNumber;
let renderStartColumn = anchorRange.startColumn;
let renderEndColumn = anchorRange.endColumn;
let highlightRange: Range = messages[0].range;
let forceShowAtRange: Range | null = null;
for (const msg of messages) {
highlightRange = Range.plusRange(highlightRange, msg.range);
if (msg.range.startLineNumber === anchorLineNumber && msg.range.endLineNumber === anchorLineNumber) {
// this message has a range that is completely sitting on the line of the anchor
renderStartColumn = Math.max(Math.min(renderStartColumn, msg.range.startColumn), startColumnBoundary);
renderEndColumn = Math.min(Math.max(renderEndColumn, msg.range.endColumn), endColumnBoundary);
}
if (msg.forceShowAtRange) {
forceShowAtRange = msg.range;
}
}
return {
showAtPosition: forceShowAtRange ? forceShowAtRange.getStartPosition() : new Position(anchorRange.startLineNumber, renderStartColumn),
showAtRange: forceShowAtRange ? forceShowAtRange : new Range(anchorLineNumber, renderStartColumn, anchorLineNumber, renderEndColumn),
highlightRange
};
}
}
class HoverResult {
constructor(
public readonly anchor: HoverAnchor,
public readonly messages: IHoverPart[],
public readonly isComplete: boolean
) { }
public filter(anchor: HoverAnchor): HoverResult {
const filteredMessages = this.messages.filter((m) => m.isValidForHoverAnchor(anchor));
if (filteredMessages.length === this.messages.length) {
return this;
}
return new FilteredHoverResult(this, this.anchor, filteredMessages, this.isComplete);
}
}
class FilteredHoverResult extends HoverResult {
constructor(
private readonly original: HoverResult,
anchor: HoverAnchor,
messages: IHoverPart[],
isComplete: boolean
) {
super(anchor, messages, isComplete);
}
public override filter(anchor: HoverAnchor): HoverResult {
return this.original.filter(anchor);
}
}
class ContentHoverVisibleData {
public closestMouseDistance: number | undefined = undefined;
constructor(
public readonly colorPicker: IEditorHoverColorPickerWidget | null,
public readonly showAtPosition: Position,
public readonly showAtRange: Range,
public readonly preferAbove: boolean,
public readonly stoleFocus: boolean,
public readonly isBeforeContent: boolean,
public initialMousePosX: number | undefined,
public initialMousePosY: number | undefined,
public readonly disposables: DisposableStore
) { }
}
export class ContentHoverWidget extends Disposable implements IContentWidget {
static readonly ID = 'editor.contrib.contentHoverWidget';
public readonly allowEditorOverflow = true;
private readonly _hoverVisibleKey = EditorContextKeys.hoverVisible.bindTo(this._contextKeyService);
private readonly _hover: HoverWidget = this._register(new HoverWidget());
private _visibleData: ContentHoverVisibleData | null = null;
/**
* Returns `null` if the hover is not visible.
*/
public get position(): Position | null {
return this._visibleData?.showAtPosition ?? null;
}
public get isColorPickerVisible(): boolean {
return Boolean(this._visibleData?.colorPicker);
}
constructor(
private readonly _editor: ICodeEditor,
@IContextKeyService private readonly _contextKeyService: IContextKeyService,
) {
super();
this._register(this._editor.onDidLayoutChange(() => this._layout()));
this._register(this._editor.onDidChangeConfiguration((e: ConfigurationChangedEvent) => {
if (e.hasChanged(EditorOption.fontInfo)) {
this._updateFont();
}
}));
this._setVisibleData(null);
this._layout();
this._editor.addContentWidget(this);
}
public override dispose(): void {
this._editor.removeContentWidget(this);
if (this._visibleData) {
this._visibleData.disposables.dispose();
}
super.dispose();
}
public getId(): string {
return ContentHoverWidget.ID;
}
public getDomNode(): HTMLElement {
return this._hover.containerDomNode;
}
public getPosition(): IContentWidgetPosition | null {
if (!this._visibleData) {
return null;
}
let preferAbove = this._visibleData.preferAbove;
if (!preferAbove && this._contextKeyService.getContextKeyValue<boolean>(SuggestContext.Visible.key)) {
// Prefer rendering above if the suggest widget is visible
preferAbove = true;
}
// :before content can align left of the text content
const affinity = this._visibleData.isBeforeContent ? PositionAffinity.LeftOfInjectedText : undefined;
return {
position: this._visibleData.showAtPosition,
range: this._visibleData.showAtRange,
preference: (
preferAbove
? [ContentWidgetPositionPreference.ABOVE, ContentWidgetPositionPreference.BELOW]
: [ContentWidgetPositionPreference.BELOW, ContentWidgetPositionPreference.ABOVE]
),
positionAffinity: affinity
};
}
public isMouseGettingCloser(posx: number, posy: number): boolean {
if (!this._visibleData) {
return false;
}
if (typeof this._visibleData.initialMousePosX === 'undefined' || typeof this._visibleData.initialMousePosY === 'undefined') {
this._visibleData.initialMousePosX = posx;
this._visibleData.initialMousePosY = posy;
return false;
}
const widgetRect = dom.getDomNodePagePosition(this.getDomNode());
if (typeof this._visibleData.closestMouseDistance === 'undefined') {
this._visibleData.closestMouseDistance = computeDistanceFromPointToRectangle(this._visibleData.initialMousePosX, this._visibleData.initialMousePosY, widgetRect.left, widgetRect.top, widgetRect.width, widgetRect.height);
}
const distance = computeDistanceFromPointToRectangle(posx, posy, widgetRect.left, widgetRect.top, widgetRect.width, widgetRect.height);
if (distance > this._visibleData.closestMouseDistance + 4 /* tolerance of 4 pixels */) {
// The mouse is getting farther away
return false;
}
this._visibleData.closestMouseDistance = Math.min(this._visibleData.closestMouseDistance, distance);
return true;
}
private _setVisibleData(visibleData: ContentHoverVisibleData | null): void {
if (this._visibleData) {
this._visibleData.disposables.dispose();
}
this._visibleData = visibleData;
this._hoverVisibleKey.set(!!this._visibleData);
this._hover.containerDomNode.classList.toggle('hidden', !this._visibleData);
}
private _layout(): void {
const height = Math.max(this._editor.getLayoutInfo().height / 4, 250);
const { fontSize, lineHeight } = this._editor.getOption(EditorOption.fontInfo);
this._hover.contentsDomNode.style.fontSize = `${fontSize}px`;
this._hover.contentsDomNode.style.lineHeight = `${lineHeight / fontSize}`;
this._hover.contentsDomNode.style.maxHeight = `${height}px`;
this._hover.contentsDomNode.style.maxWidth = `${Math.max(this._editor.getLayoutInfo().width * 0.66, 500)}px`;
}
private _updateFont(): void {
const codeClasses: HTMLElement[] = Array.prototype.slice.call(this._hover.contentsDomNode.getElementsByClassName('code'));
codeClasses.forEach(node => this._editor.applyFontInfo(node));
}
public showAt(node: DocumentFragment, visibleData: ContentHoverVisibleData): void {
this._setVisibleData(visibleData);
this._hover.contentsDomNode.textContent = '';
this._hover.contentsDomNode.appendChild(node);
this._hover.contentsDomNode.style.paddingBottom = '';
this._updateFont();
this.onContentsChanged();
// Simply force a synchronous render on the editor
// such that the widget does not really render with left = '0px'
this._editor.render();
// See https://github.com/microsoft/vscode/issues/140339
// TODO: Doing a second layout of the hover after force rendering the editor
this.onContentsChanged();
if (visibleData.stoleFocus) {
this._hover.containerDomNode.focus();
}
visibleData.colorPicker?.layout();
}
public hide(): void {
if (this._visibleData) {
const stoleFocus = this._visibleData.stoleFocus;
this._setVisibleData(null);
this._editor.layoutContentWidget(this);
if (stoleFocus) {
this._editor.focus();
}
}
}
public onContentsChanged(): void {
this._editor.layoutContentWidget(this);
this._hover.onContentsChanged();
const scrollDimensions = this._hover.scrollbar.getScrollDimensions();
const hasHorizontalScrollbar = (scrollDimensions.scrollWidth > scrollDimensions.width);
if (hasHorizontalScrollbar) {
// There is just a horizontal scrollbar
const extraBottomPadding = `${this._hover.scrollbar.options.horizontalScrollbarSize}px`;
if (this._hover.contentsDomNode.style.paddingBottom !== extraBottomPadding) {
this._hover.contentsDomNode.style.paddingBottom = extraBottomPadding;
this._editor.layoutContentWidget(this);
this._hover.onContentsChanged();
}
}
}
public clear(): void {
this._hover.contentsDomNode.textContent = '';
}
}
class EditorHoverStatusBar extends Disposable implements IEditorHoverStatusBar {
public readonly hoverElement: HTMLElement;
private readonly actionsElement: HTMLElement;
private _hasContent: boolean = false;
public get hasContent() {
return this._hasContent;
}
constructor(
@IKeybindingService private readonly _keybindingService: IKeybindingService,
) {
super();
this.hoverElement = $('div.hover-row.status-bar');
this.actionsElement = dom.append(this.hoverElement, $('div.actions'));
}
public addAction(actionOptions: { label: string; iconClass?: string; run: (target: HTMLElement) => void; commandId: string }): IEditorHoverAction {
const keybinding = this._keybindingService.lookupKeybinding(actionOptions.commandId);
const keybindingLabel = keybinding ? keybinding.getLabel() : null;
this._hasContent = true;
return this._register(HoverAction.render(this.actionsElement, actionOptions, keybindingLabel));
}
public append(element: HTMLElement): HTMLElement {
const result = dom.append(this.actionsElement, element);
this._hasContent = true;
return result;
}
}
class ContentHoverComputer implements IHoverComputer<IHoverPart> {
private _anchor: HoverAnchor | null = null;
public get anchor(): HoverAnchor | null { return this._anchor; }
public set anchor(value: HoverAnchor | null) { this._anchor = value; }
private _shouldFocus: boolean = false;
public get shouldFocus(): boolean { return this._shouldFocus; }
public set shouldFocus(value: boolean) { this._shouldFocus = value; }
private _insistOnKeepingHoverVisible: boolean = false;
public get insistOnKeepingHoverVisible(): boolean { return this._insistOnKeepingHoverVisible; }
public set insistOnKeepingHoverVisible(value: boolean) { this._insistOnKeepingHoverVisible = value; }
constructor(
private readonly _editor: ICodeEditor,
private readonly _participants: readonly IEditorHoverParticipant[]
) {
}
private static _getLineDecorations(editor: IActiveCodeEditor, anchor: HoverAnchor): IModelDecoration[] {
if (anchor.type !== HoverAnchorType.Range) {
return [];
}
const model = editor.getModel();
const lineNumber = anchor.range.startLineNumber;
if (lineNumber > model.getLineCount()) {
// invalid line
return [];
}
const maxColumn = model.getLineMaxColumn(lineNumber);
return editor.getLineDecorations(lineNumber).filter((d) => {
if (d.options.isWholeLine) {
return true;
}
const startColumn = (d.range.startLineNumber === lineNumber) ? d.range.startColumn : 1;
const endColumn = (d.range.endLineNumber === lineNumber) ? d.range.endColumn : maxColumn;
if (d.options.showIfCollapsed) {
// Relax check around `showIfCollapsed` decorations to also include +/- 1 character
if (startColumn > anchor.range.startColumn + 1 || anchor.range.endColumn - 1 > endColumn) {
return false;
}
} else {
if (startColumn > anchor.range.startColumn || anchor.range.endColumn > endColumn) {
return false;
}
}
return true;
});
}
public computeAsync(token: CancellationToken): AsyncIterableObject<IHoverPart> {
const anchor = this._anchor;
if (!this._editor.hasModel() || !anchor) {
return AsyncIterableObject.EMPTY;
}
const lineDecorations = ContentHoverComputer._getLineDecorations(this._editor, anchor);
return AsyncIterableObject.merge(
this._participants.map((participant) => {
if (!participant.computeAsync) {
return AsyncIterableObject.EMPTY;
}
return participant.computeAsync(anchor, lineDecorations, token);
})
);
}
public computeSync(): IHoverPart[] {
if (!this._editor.hasModel() || !this._anchor) {
return [];
}
const lineDecorations = ContentHoverComputer._getLineDecorations(this._editor, this._anchor);
let result: IHoverPart[] = [];
for (const participant of this._participants) {
result = result.concat(participant.computeSync(this._anchor, lineDecorations));
}
return coalesce(result);
}
}
function computeDistanceFromPointToRectangle(pointX: number, pointY: number, left: number, top: number, width: number, height: number): number {
const x = (left + width / 2); // x center of rectangle
const y = (top + height / 2); // y center of rectangle
const dx = Math.max(Math.abs(pointX - x) - width / 2, 0);
const dy = Math.max(Math.abs(pointY - y) - height / 2, 0);
return Math.sqrt(dx * dx + dy * dy);
}