-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathLinkifier.ts
More file actions
422 lines (375 loc) · 16.2 KB
/
Copy pathLinkifier.ts
File metadata and controls
422 lines (375 loc) · 16.2 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
/**
* Copyright (c) 2019 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { IBufferCellPosition, ILink, ILinkDecorations, ILinkWithState, ILinkifier2, ILinkifierEvent } from 'browser/Types';
import { Disposable, dispose, toDisposable } from 'common/Lifecycle';
import { IDisposable } from 'common/Types';
import { IBufferService } from 'common/services/Services';
import { ILinkProviderService, IMouseCoordsService, IRenderService } from './services/Services';
import { Emitter } from 'common/Event';
import { addDisposableListener } from 'browser/Dom';
export class Linkifier extends Disposable implements ILinkifier2 {
public get currentLink(): ILinkWithState | undefined { return this._currentLink; }
protected _currentLink: ILinkWithState | undefined;
private _mouseDownLink: ILinkWithState | undefined;
private _lastMouseDownPos: IBufferCellPosition | undefined;
private _lastMouseEvent: MouseEvent | undefined;
private _linkCacheDisposables: IDisposable[] = [];
private _lastBufferCell: IBufferCellPosition | undefined;
private _isMouseOut: boolean = true;
private _wasResized: boolean = false;
private _activeProviderReplies: Map<Number, ILinkWithState[] | undefined> | undefined;
private _activeLine: number = -1;
private readonly _onShowLinkUnderline = this._register(new Emitter<ILinkifierEvent>());
public readonly onShowLinkUnderline = this._onShowLinkUnderline.event;
private readonly _onHideLinkUnderline = this._register(new Emitter<ILinkifierEvent>());
public readonly onHideLinkUnderline = this._onHideLinkUnderline.event;
constructor(
private readonly _element: HTMLElement,
@IMouseCoordsService private readonly _mouseCoordsService: IMouseCoordsService,
@IRenderService private readonly _renderService: IRenderService,
@IBufferService private readonly _bufferService: IBufferService,
@ILinkProviderService private readonly _linkProviderService: ILinkProviderService
) {
super();
this._register(toDisposable(() => {
dispose(this._linkCacheDisposables);
this._linkCacheDisposables.length = 0;
this._lastMouseEvent = undefined;
// Clear out link providers as they could easily cause an embedder memory leak
this._activeProviderReplies?.clear();
}));
// Listen to resize to catch the case where it's resized and the cursor is out of the viewport.
this._register(this._bufferService.onResize(() => {
this._clearCurrentLink();
this._wasResized = true;
}));
this._register(addDisposableListener(this._element, 'mouseleave', () => {
this._isMouseOut = true;
this._clearCurrentLink();
}));
this._register(addDisposableListener(this._element, 'mousemove', this._handleMouseMove.bind(this)));
this._register(addDisposableListener(this._element, 'mousedown', this._handleMouseDown.bind(this)));
this._register(addDisposableListener(this._element, 'mouseup', this._handleMouseUp.bind(this)));
}
private _handleMouseMove(event: MouseEvent): void {
this._lastMouseEvent = event;
const position = this._positionFromMouseEvent(event, this._element);
if (!position) {
return;
}
this._isMouseOut = false;
// Ignore the event if it's an embedder created hover widget
const composedPath = event.composedPath() as HTMLElement[];
for (let i = 0; i < composedPath.length; i++) {
const target = composedPath[i];
// Hit Terminal.element, break and continue
if (target.classList.contains('xterm')) {
break;
}
// It's a hover, don't respect hover event
if (target.classList.contains('xterm-hover')) {
return;
}
}
if (!this._lastBufferCell || (position.x !== this._lastBufferCell.x || position.y !== this._lastBufferCell.y)) {
this._handleHover(position);
this._lastBufferCell = position;
}
}
private _handleHover(position: IBufferCellPosition): void {
// TODO: This currently does not cache link provider results across wrapped lines, activeLine
// should be something like `activeRange: {startY, endY}`
// Check if we need to clear the link
if (this._activeLine !== position.y || this._wasResized) {
this._clearCurrentLink();
this._askForLink(position, false);
this._wasResized = false;
return;
}
// Check the if the link is in the mouse position
const isCurrentLinkInPosition = this._currentLink && this._linkAtPosition(this._currentLink.link, position);
if (!isCurrentLinkInPosition) {
this._clearCurrentLink();
this._askForLink(position, true);
}
}
private _askForLink(position: IBufferCellPosition, useLineCache: boolean): void {
if (!this._activeProviderReplies || !useLineCache) {
this._activeProviderReplies?.forEach(reply => {
reply?.forEach(linkWithState => {
if (linkWithState.link.dispose) {
linkWithState.link.dispose();
}
});
});
this._activeProviderReplies = new Map();
this._activeLine = position.y;
}
let linkProvided = false;
// There is no link cached, so ask for one
for (const [i, linkProvider] of this._linkProviderService.linkProviders.entries()) {
if (useLineCache) {
const existingReply = this._activeProviderReplies?.get(i);
// If there isn't a reply, the provider hasn't responded yet.
// TODO: If there isn't a reply yet it means that the provider is still resolving. Ensuring
// provideLinks isn't triggered again saves ILink.hover firing twice though. This probably
// needs promises to get fixed
if (existingReply) {
linkProvided = this._checkLinkProviderResult(i, position, linkProvided);
}
} else {
linkProvider.provideLinks(position.y, (links: ILink[] | undefined) => {
if (this._isMouseOut) {
return;
}
const linksWithState: ILinkWithState[] | undefined = links?.map(link => ({ link }));
this._activeProviderReplies?.set(i, linksWithState);
linkProvided = this._checkLinkProviderResult(i, position, linkProvided);
// If all providers have responded, remove lower priority links that intersect ranges of
// higher priority links
if (this._activeProviderReplies?.size === this._linkProviderService.linkProviders.length) {
this._removeIntersectingLinks(position.y, this._activeProviderReplies);
}
});
}
}
}
private _removeIntersectingLinks(y: number, replies: Map<Number, ILinkWithState[] | undefined>): void {
const occupiedCells = new Set<number>();
for (let i = 0; i < replies.size; i++) {
const providerReply = replies.get(i);
if (!providerReply) {
continue;
}
for (let i = 0; i < providerReply.length; i++) {
const linkWithState = providerReply[i];
const startX = linkWithState.link.range.start.y < y ? 0 : linkWithState.link.range.start.x;
const endX = linkWithState.link.range.end.y > y ? this._bufferService.cols : linkWithState.link.range.end.x;
for (let x = startX; x <= endX; x++) {
if (occupiedCells.has(x)) {
providerReply.splice(i--, 1);
break;
}
occupiedCells.add(x);
}
}
}
}
private _checkLinkProviderResult(index: number, position: IBufferCellPosition, linkProvided: boolean): boolean {
if (!this._activeProviderReplies) {
return linkProvided;
}
const links = this._activeProviderReplies.get(index);
// Check if every provider before this one has come back undefined
let hasLinkBefore = false;
for (let j = 0; j < index; j++) {
if (!this._activeProviderReplies.has(j) || this._activeProviderReplies.get(j)) {
hasLinkBefore = true;
}
}
// If all providers with higher priority came back undefined, then this provider's link for
// the position should be used
if (!hasLinkBefore && links) {
const linkAtPosition = links.find(link => this._linkAtPosition(link.link, position));
if (linkAtPosition) {
linkProvided = true;
this._handleNewLink(linkAtPosition);
}
}
// Check if all the providers have responded
if (this._activeProviderReplies.size === this._linkProviderService.linkProviders.length && !linkProvided) {
// Respect the order of the link providers
for (let j = 0; j < this._activeProviderReplies.size; j++) {
const currentLink = this._activeProviderReplies.get(j)?.find(link => this._linkAtPosition(link.link, position));
if (currentLink) {
linkProvided = true;
this._handleNewLink(currentLink);
break;
}
}
}
return linkProvided;
}
private _handleMouseDown(event: MouseEvent): void {
if (!this._element) {
return;
}
const position = this._positionFromMouseEvent(event, this._element);
this._mouseDownLink = this._currentLink;
this._lastMouseDownPos = position;
}
private _handleMouseUp(event: MouseEvent): void {
const mouseDownLink = this._mouseDownLink;
this._mouseDownLink = undefined;
if (!this._currentLink) {
return;
}
const position = this._positionFromMouseEvent(event, this._element);
if (!position) {
return;
}
// compare last mouse down position: if we strayed too much, don't open the link
// that's because very likely user intended to select the text instead of opening the link
let selectionDetected = true;
if (this._lastMouseDownPos) {
const deltaMov = Math.abs(this._lastMouseDownPos.x - position.x) + Math.abs(this._lastMouseDownPos.y - position.y);
selectionDetected = deltaMov >= 2;
}
if (!selectionDetected && mouseDownLink && linkEquals(mouseDownLink.link, this._currentLink.link) && this._linkAtPosition(this._currentLink.link, position)) {
this._currentLink.link.activate(event, this._currentLink.link.text);
}
}
private _clearCurrentLink(startRow?: number, endRow?: number): void {
if (!this._currentLink || !this._lastMouseEvent) {
return;
}
// If we have a start and end row, check that the link is within it
if (!startRow || !endRow || (this._currentLink.link.range.start.y >= startRow && this._currentLink.link.range.end.y <= endRow)) {
this._linkLeave(this._element, this._currentLink.link, this._lastMouseEvent);
this._currentLink = undefined;
dispose(this._linkCacheDisposables);
this._linkCacheDisposables.length = 0;
}
}
private _handleNewLink(linkWithState: ILinkWithState): void {
if (!this._lastMouseEvent) {
return;
}
const position = this._positionFromMouseEvent(this._lastMouseEvent, this._element);
if (!position) {
return;
}
// Trigger hover if the we have a link at the position
if (this._linkAtPosition(linkWithState.link, position)) {
this._currentLink = linkWithState;
this._currentLink.state = {
decorations: {
underline: linkWithState.link.decorations === undefined ? true : linkWithState.link.decorations.underline,
pointerCursor: linkWithState.link.decorations === undefined ? true : linkWithState.link.decorations.pointerCursor
},
isHovered: true
};
this._linkHover(this._element, linkWithState.link, this._lastMouseEvent);
// Add listener for tracking decorations changes
linkWithState.link.decorations = {} as ILinkDecorations;
Object.defineProperties(linkWithState.link.decorations, {
pointerCursor: {
get: () => this._currentLink?.state?.decorations.pointerCursor,
set: v => {
if (this._currentLink?.state && this._currentLink.state.decorations.pointerCursor !== v) {
this._currentLink.state.decorations.pointerCursor = v;
if (this._currentLink.state.isHovered) {
this._element.classList.toggle('xterm-cursor-pointer', v);
}
}
}
},
underline: {
get: () => this._currentLink?.state?.decorations.underline,
set: v => {
if (this._currentLink?.state && this._currentLink?.state?.decorations.underline !== v) {
this._currentLink.state.decorations.underline = v;
if (this._currentLink.state.isHovered) {
this._fireUnderlineEvent(linkWithState.link, v);
}
}
}
}
});
// Listen to viewport changes to re-render the link under the cursor (only when the line the
// link is on changes)
this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(e => {
// Sanity check, this shouldn't happen in practice as this listener would be disposed
if (!this._currentLink) {
return;
}
// When start is 0 a scroll most likely occurred, make sure links above the fold also get
// cleared.
const start = e.start === 0 ? 0 : e.start + 1 + this._bufferService.buffer.ydisp;
const end = this._bufferService.buffer.ydisp + 1 + e.end;
// Only clear the link if the viewport change happened on this line
if (this._currentLink.link.range.start.y >= start && this._currentLink.link.range.end.y <= end) {
this._clearCurrentLink(start, end);
if (this._lastMouseEvent) {
// re-eval previously active link after changes
const position = this._positionFromMouseEvent(this._lastMouseEvent, this._element);
if (position) {
this._askForLink(position, false);
}
}
}
}));
}
}
protected _linkHover(element: HTMLElement, link: ILink, event: MouseEvent): void {
if (this._currentLink?.state) {
this._currentLink.state.isHovered = true;
if (this._currentLink.state.decorations.underline) {
this._fireUnderlineEvent(link, true);
}
if (this._currentLink.state.decorations.pointerCursor) {
element.classList.add('xterm-cursor-pointer');
}
}
if (link.hover) {
link.hover(event, link.text);
}
}
private _fireUnderlineEvent(link: ILink, showEvent: boolean): void {
const range = link.range;
const scrollOffset = this._bufferService.buffer.ydisp;
const event = this._createLinkUnderlineEvent(range.start.x - 1, range.start.y - scrollOffset - 1, range.end.x, range.end.y - scrollOffset - 1, undefined);
const emitter = showEvent ? this._onShowLinkUnderline : this._onHideLinkUnderline;
emitter.fire(event);
}
protected _linkLeave(element: HTMLElement, link: ILink, event: MouseEvent): void {
if (this._currentLink?.state) {
this._currentLink.state.isHovered = false;
if (this._currentLink.state.decorations.underline) {
this._fireUnderlineEvent(link, false);
}
if (this._currentLink.state.decorations.pointerCursor) {
element.classList.remove('xterm-cursor-pointer');
}
}
if (link.leave) {
link.leave(event, link.text);
}
}
/**
* Check if the buffer position is within the link
* @param link
* @param position
*/
private _linkAtPosition(link: ILink, position: IBufferCellPosition): boolean {
const lower = link.range.start.y * this._bufferService.cols + link.range.start.x;
const upper = link.range.end.y * this._bufferService.cols + link.range.end.x;
const current = position.y * this._bufferService.cols + position.x;
return (lower <= current && current <= upper);
}
/**
* Get the buffer position from a mouse event
* @param event
*/
private _positionFromMouseEvent(event: MouseEvent, element: HTMLElement): IBufferCellPosition | undefined {
const coords = this._mouseCoordsService.getCoords(event, element, this._bufferService.cols, this._bufferService.rows);
if (!coords) {
return;
}
return { x: coords[0], y: coords[1] + this._bufferService.buffer.ydisp };
}
private _createLinkUnderlineEvent(x1: number, y1: number, x2: number, y2: number, fg: number | undefined): ILinkifierEvent {
return { x1, y1, x2, y2, cols: this._bufferService.cols, fg };
}
}
function linkEquals(a: ILink, b: ILink): boolean {
return (
a.text === b.text &&
a.range.start.x === b.range.start.x &&
a.range.start.y === b.range.start.y &&
a.range.end.x === b.range.end.x &&
a.range.end.y === b.range.end.y
);
}