timelinePane.ts 35.1 KB
Newer Older
1 2 3 4 5 6
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import 'vs/css!./media/timelinePane';
E
Eric Amodio 已提交
7
import { localize } from 'vs/nls';
8
import * as DOM from 'vs/base/browser/dom';
9 10
import { CancellationTokenSource } from 'vs/base/common/cancellation';
import { FuzzyScore, createMatches } from 'vs/base/common/filters';
11
import { DisposableStore, IDisposable, Disposable } from 'vs/base/common/lifecycle';
12 13 14
import { URI } from 'vs/base/common/uri';
import { IconLabel } from 'vs/base/browser/ui/iconLabel/iconLabel';
import { IListVirtualDelegate, IIdentityProvider, IKeyboardNavigationLabelProvider } from 'vs/base/browser/ui/list/list';
15
import { ITreeNode, ITreeRenderer, ITreeContextMenuEvent, ITreeElement } from 'vs/base/browser/ui/tree/tree';
16
import { ViewPane, IViewPaneOptions } from 'vs/workbench/browser/parts/views/viewPaneContainer';
17
import { ResourceNavigator, WorkbenchObjectTree } from 'vs/platform/list/browser/listService';
18 19
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
20
import { ContextKeyExpr, IContextKeyService, RawContextKey, IContextKey } from 'vs/platform/contextkey/common/contextkey';
21
import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration';
22
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
23
import { ITimelineService, TimelineChangeEvent, TimelineItem, TimelineOptions, TimelineProvidersChangeEvent, TimelineRequest, Timeline } from 'vs/workbench/contrib/timeline/common/timeline';
24 25
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { SideBySideEditor, toResource } from 'vs/workbench/common/editor';
26
import { ICommandService, CommandsRegistry } from 'vs/platform/commands/common/commands';
27
import { IThemeService, LIGHT, ThemeIcon } from 'vs/platform/theme/common/themeService';
28
import { IViewDescriptorService } from 'vs/workbench/common/views';
E
Eric Amodio 已提交
29 30
import { basename } from 'vs/base/common/path';
import { IProgressService } from 'vs/platform/progress/common/progress';
31
import { debounce } from 'vs/base/common/decorators';
32
import { IOpenerService } from 'vs/platform/opener/common/opener';
33 34
import { IActionViewItemProvider, ActionBar, ActionViewItem } from 'vs/base/browser/ui/actionbar/actionbar';
import { IAction, ActionRunner } from 'vs/base/common/actions';
35
import { ContextAwareMenuEntryActionViewItem, createAndFillInContextMenuActions } from 'vs/platform/actions/browser/menuEntryActionViewItem';
36
import { MenuItemAction, IMenuService, MenuId, registerAction2, Action2, MenuRegistry } from 'vs/platform/actions/common/actions';
37
import { fromNow } from 'vs/base/common/date';
38
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
39
import { escapeRegExpCharacters } from 'vs/base/common/strings';
40
import { Iterable } from 'vs/base/common/iterator';
41
import { Schemas } from 'vs/base/common/network';
42

43
const PageSize = 20;
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

interface CommandItem {
	handle: 'vscode-command:loadMore';
	timestamp: number;
	label: string;
	themeIcon?: { id: string };
	description?: string;
	detail?: string;
	contextValue?: string;

	// Make things easier for duck typing
	id: undefined;
	icon: undefined;
	iconDark: undefined;
	source: undefined;
}

type TreeElement = TimelineItem | CommandItem;

// function isCommandItem(item: TreeElement | undefined): item is CommandItem {
// 	return item?.handle.startsWith('vscode-command:') ?? false;
// }

function isLoadMoreCommandItem(item: TreeElement | undefined): item is CommandItem & {
	handle: 'vscode-command:loadMore';
} {
	return item?.handle === 'vscode-command:loadMore';
}

function isTimelineItem(item: TreeElement | undefined): item is TimelineItem {
	return !item?.handle.startsWith('vscode-command:') ?? false;
}

77 78 79 80
interface TimelineActionContext {
	uri: URI | undefined;
	item: TreeElement;
}
E
Eric Amodio 已提交
81

82 83
class TimelineAggregate {
	readonly items: TimelineItem[];
84
	readonly source: string;
85 86 87 88

	lastRenderedIndex: number;

	constructor(timeline: Timeline) {
89
		this.source = timeline.source;
90 91 92 93 94 95 96 97 98 99 100
		this.items = timeline.items;
		this._cursor = timeline.paging?.cursor;
		this.lastRenderedIndex = -1;
	}

	private _cursor?: string;
	get cursor(): string | undefined {
		return this._cursor;
	}

	get more(): boolean {
E
Eric Amodio 已提交
101
		return this._cursor !== undefined;
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
	}

	get newest(): TimelineItem | undefined {
		return this.items[0];
	}

	get oldest(): TimelineItem | undefined {
		return this.items[this.items.length - 1];
	}

	add(timeline: Timeline) {
		let updated = false;

		if (timeline.items.length !== 0 && this.items.length !== 0) {
			updated = true;

			const ids = new Set();
			const timestamps = new Set();

			for (const item of timeline.items) {
				if (item.id === undefined) {
					timestamps.add(item.timestamp);
				}
				else {
					ids.add(item.id);
				}
			}

			// Remove any duplicate items
			let i = this.items.length;
			let item;
			while (i--) {
				item = this.items[i];
				if ((item.id !== undefined && ids.has(item.id)) || timestamps.has(item.timestamp)) {
					this.items.splice(i, 1);
				}
			}

			if ((timeline.items[timeline.items.length - 1]?.timestamp ?? 0) >= (this.newest?.timestamp ?? 0)) {
				this.items.splice(0, 0, ...timeline.items);
			} else {
				this.items.push(...timeline.items);
			}
		} else if (timeline.items.length !== 0) {
			updated = true;

			this.items.push(...timeline.items);
		}

		this._cursor = timeline.paging?.cursor;

		if (updated) {
			this.items.sort(
				(a, b) =>
					(b.timestamp - a.timestamp) ||
					(a.source === undefined
						? b.source === undefined ? 0 : 1
						: b.source === undefined ? -1 : b.source.localeCompare(a.source, undefined, { numeric: true, sensitivity: 'base' }))
			);
		}

		return updated;
	}
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179

	private _stale = false;
	get stale() {
		return this._stale;
	}

	private _requiresReset = false;
	get requiresReset(): boolean {
		return this._requiresReset;
	}

	invalidate(requiresReset: boolean) {
		this._stale = true;
		this._requiresReset = requiresReset;
	}
180 181
}

182 183
export const TimelineFollowActiveEditorContext = new RawContextKey<boolean>('timelineFollowActiveEditor', true);

184
export class TimelinePane extends ViewPane {
185
	static readonly TITLE = localize('timeline', "Timeline");
E
Eric Amodio 已提交
186

187 188 189 190 191 192
	private $container!: HTMLElement;
	private $message!: HTMLDivElement;
	private $titleDescription!: HTMLSpanElement;
	private $tree!: HTMLDivElement;
	private tree!: WorkbenchObjectTree<TreeElement, FuzzyScore>;
	private treeRenderer: TimelineTreeRenderer | undefined;
193
	private commands: TimelinePaneCommands;
194 195 196
	private visibilityDisposables: DisposableStore | undefined;

	private followActiveEditorContext: IContextKey<boolean>;
197

198 199 200
	private excludedSources: Set<string>;
	private pendingRequests = new Map<string, TimelineRequest>();
	private timelinesBySource = new Map<string, TimelineAggregate>();
201

202
	private uri: URI | undefined;
203

204 205 206 207 208 209 210 211 212
	constructor(
		options: IViewPaneOptions,
		@IKeybindingService protected keybindingService: IKeybindingService,
		@IContextMenuService protected contextMenuService: IContextMenuService,
		@IContextKeyService protected contextKeyService: IContextKeyService,
		@IConfigurationService protected configurationService: IConfigurationService,
		@IViewDescriptorService viewDescriptorService: IViewDescriptorService,
		@IInstantiationService protected readonly instantiationService: IInstantiationService,
		@IEditorService protected editorService: IEditorService,
213
		@ICommandService protected commandService: ICommandService,
E
Eric Amodio 已提交
214
		@IProgressService private readonly progressService: IProgressService,
215 216 217
		@ITimelineService protected timelineService: ITimelineService,
		@IOpenerService openerService: IOpenerService,
		@IThemeService themeService: IThemeService,
218
		@ITelemetryService telemetryService: ITelemetryService,
219
	) {
220
		super({ ...options, titleMenuId: MenuId.TimelineTitle }, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService);
221

222
		this.commands = this._register(this.instantiationService.createInstance(TimelinePaneCommands, this));
223

224
		this.followActiveEditorContext = TimelineFollowActiveEditorContext.bindTo(this.contextKeyService);
225

226
		this.excludedSources = new Set(configurationService.getValue('timeline.excludeSources'));
227
		configurationService.onDidChangeConfiguration(this.onConfigurationChanged, this);
228

229 230
		this._register(timelineService.onDidChangeProviders(this.onProvidersChanged, this));
		this._register(timelineService.onDidChangeTimeline(this.onTimelineChanged, this));
231 232 233 234 235 236 237 238 239 240 241 242 243
		this._register(timelineService.onDidChangeUri(uri => this.setUri(uri), this));
	}

	private _followActiveEditor: boolean = true;
	get followActiveEditor(): boolean {
		return this._followActiveEditor;
	}
	set followActiveEditor(value: boolean) {
		if (this._followActiveEditor === value) {
			return;
		}

		this._followActiveEditor = value;
244
		this.followActiveEditorContext.set(value);
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263

		if (value) {
			this.onActiveEditorChanged();
		}
	}

	reset() {
		this.loadTimeline(true);
	}

	setUri(uri: URI) {
		this.setUriCore(uri, true);
	}

	private setUriCore(uri: URI | undefined, disableFollowing: boolean) {
		if (disableFollowing) {
			this.followActiveEditor = false;
		}

264
		this.uri = uri;
265
		this.titleDescription = uri ? basename(uri.fsPath) : '';
266
		this.treeRenderer?.setUri(uri);
267
		this.loadTimeline(true);
268 269 270 271 272 273 274
	}

	private onConfigurationChanged(e: IConfigurationChangeEvent) {
		if (!e.affectsConfiguration('timeline.excludeSources')) {
			return;
		}

275 276 277 278 279 280 281 282 283
		this.excludedSources = new Set(this.configurationService.getValue('timeline.excludeSources'));

		const missing = this.timelineService.getSources()
			.filter(({ id }) => !this.excludedSources.has(id) && !this.timelinesBySource.has(id));
		if (missing.length !== 0) {
			this.loadTimeline(true, missing.map(({ id }) => id));
		} else {
			this.refresh();
		}
284 285
	}

286
	private onActiveEditorChanged() {
287 288 289 290
		if (!this.followActiveEditor) {
			return;
		}

291 292 293 294 295 296 297
		let uri;

		const editor = this.editorService.activeEditor;
		if (editor) {
			uri = toResource(editor, { supportSideBySide: SideBySideEditor.MASTER });
		}

298
		if ((uri?.toString(true) === this.uri?.toString(true) && uri !== undefined) ||
299
			// Fallback to match on fsPath if we are dealing with files or git schemes
300
			(uri?.fsPath === this.uri?.fsPath && (uri?.scheme === 'file' || uri?.scheme === 'git') && (this.uri?.scheme === 'file' || this.uri?.scheme === 'git'))) {
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319

			// If the uri hasn't changed, make sure we have valid caches
			for (const source of this.timelineService.getSources()) {
				if (this.excludedSources.has(source.id)) {
					continue;
				}

				const timeline = this.timelinesBySource.get(source.id);
				if (timeline !== undefined && !timeline.stale) {
					continue;
				}

				if (timeline !== undefined) {
					this.updateTimeline(timeline, timeline.requiresReset);
				} else {
					this.loadTimelineForSource(source.id, uri, true);
				}
			}

320 321 322
			return;
		}

323
		this.setUriCore(uri, false);
324 325
	}

326 327 328
	private onProvidersChanged(e: TimelineProvidersChangeEvent) {
		if (e.removed) {
			for (const source of e.removed) {
329
				this.timelinesBySource.delete(source);
330
			}
331 332

			this.refresh();
333 334 335
		}

		if (e.added) {
336
			this.loadTimeline(true, e.added);
337
		}
338 339
	}

340
	private onTimelineChanged(e: TimelineChangeEvent) {
341 342 343 344 345 346
		if (e?.uri === undefined || e.uri.toString(true) !== this.uri?.toString(true)) {
			const timeline = this.timelinesBySource.get(e.id);
			if (timeline === undefined) {
				return;
			}

347 348
			if (this.isBodyVisible()) {
				this.updateTimeline(timeline, e.reset ?? false);
349
			} else {
350
				timeline.invalidate(e.reset ?? false);
351
			}
352 353 354
		}
	}

355 356 357 358 359 360 361
	private _titleDescription: string | undefined;
	get titleDescription(): string | undefined {
		return this._titleDescription;
	}

	set titleDescription(description: string | undefined) {
		this._titleDescription = description;
362
		this.$titleDescription.textContent = description ?? '';
363 364
	}

E
Eric Amodio 已提交
365 366 367 368 369 370 371 372 373 374 375
	private _message: string | undefined;
	get message(): string | undefined {
		return this._message;
	}

	set message(message: string | undefined) {
		this._message = message;
		this.updateMessage();
	}

	private updateMessage(): void {
376
		if (this._message !== undefined) {
E
Eric Amodio 已提交
377 378 379 380 381 382 383
			this.showMessage(this._message);
		} else {
			this.hideMessage();
		}
	}

	private showMessage(message: string): void {
384
		DOM.removeClass(this.$message, 'hide');
E
Eric Amodio 已提交
385 386
		this.resetMessageElement();

387
		this.$message.textContent = message;
E
Eric Amodio 已提交
388 389 390 391
	}

	private hideMessage(): void {
		this.resetMessageElement();
392
		DOM.addClass(this.$message, 'hide');
E
Eric Amodio 已提交
393 394 395
	}

	private resetMessageElement(): void {
396
		DOM.clearNode(this.$message);
E
Eric Amodio 已提交
397 398
	}

399 400 401 402 403 404 405
	private _isEmpty = true;
	private _maxItemCount = 0;

	private _visibleItemCount = 0;
	private get hasVisibleItems() {
		return this._visibleItemCount > 0;
	}
406

407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
	private clear(cancelPending: boolean) {
		this._visibleItemCount = 0;
		this._maxItemCount = PageSize;
		this.timelinesBySource.clear();

		if (cancelPending) {
			for (const { tokenSource } of this.pendingRequests.values()) {
				tokenSource.dispose(true);
			}

			this.pendingRequests.clear();

			if (!this.isBodyVisible()) {
				this.tree.setChildren(null, undefined);
				this._isEmpty = true;
			}
		}
	}

426
	private async loadTimeline(reset: boolean, sources?: string[]) {
427 428
		// If we have no source, we are reseting all sources, so cancel everything in flight and reset caches
		if (sources === undefined) {
429
			if (reset) {
430
				this.clear(true);
431
			}
E
Eric Amodio 已提交
432

433
			// TODO@eamodio: Are these the right the list of schemes to exclude? Is there a better way?
434
			if (this.uri?.scheme === Schemas.vscodeSettings || this.uri?.scheme === Schemas.webviewPanel || this.uri?.scheme === Schemas.walkThrough) {
435 436
				this.uri = undefined;

437
				this.clear(false);
438
				this.refresh();
439 440 441

				return;
			}
442

443
			if (this._isEmpty && this.uri !== undefined) {
444
				this.setLoadingUriMessage();
E
Eric Amodio 已提交
445
			}
446 447
		}

448
		if (this.uri === undefined) {
449
			this.clear(false);
450 451
			this.refresh();

452 453 454
			return;
		}

455 456 457 458
		if (!this.isBodyVisible()) {
			return;
		}

459
		let hasPendingRequests = false;
460

461 462 463 464 465
		for (const source of sources ?? this.timelineService.getSources().map(s => s.id)) {
			const requested = this.loadTimelineForSource(source, this.uri, reset);
			if (requested) {
				hasPendingRequests = true;
			}
466 467
		}

468 469 470 471
		if (!hasPendingRequests) {
			this.refresh();
		} else if (this._isEmpty) {
			this.setLoadingUriMessage();
472
		}
473
	}
474

475 476 477 478
	private loadTimelineForSource(source: string, uri: URI, reset: boolean, options?: TimelineOptions) {
		if (this.excludedSources.has(source)) {
			return false;
		}
479

480
		const timeline = this.timelinesBySource.get(source);
481

482 483 484 485 486 487 488 489 490
		// If we are paging, and there are no more items or we have enough cached items to cover the next page,
		// don't bother querying for more
		if (
			!reset &&
			timeline !== undefined &&
			(!timeline?.more || timeline.items.length > timeline.lastRenderedIndex + PageSize)
		) {
			return false;
		}
491

492 493 494
		if (options === undefined) {
			options = { cursor: reset ? undefined : timeline?.cursor, limit: PageSize };
		}
495

496 497 498
		let request = this.pendingRequests.get(source);
		if (request !== undefined) {
			options.cursor = request.options.cursor;
E
Eric Amodio 已提交
499

500 501 502 503 504 505
			// TODO@eamodio deal with concurrent requests better
			if (typeof options.limit === 'number') {
				if (typeof request.options.limit === 'number') {
					options.limit += request.options.limit;
				} else {
					options.limit = request.options.limit;
E
Eric Amodio 已提交
506
				}
507
			}
508
		}
509
		request?.tokenSource.dispose(true);
510

511 512 513 514 515 516
		request = this.timelineService.getTimeline(
			source, uri, options, new CancellationTokenSource(), { cacheResults: true, resetCache: reset }
		);

		if (request === undefined) {
			return false;
517
		}
518 519 520 521 522 523 524

		this.pendingRequests.set(source, request);
		request.tokenSource.token.onCancellationRequested(() => this.pendingRequests.delete(source));

		this.handleRequest(request);

		return true;
525 526
	}

527 528 529 530 531 532 533 534 535 536 537 538 539
	private updateTimeline(timeline: TimelineAggregate, reset: boolean) {
		if (reset) {
			this.timelinesBySource.delete(timeline.source);
			// Override the limit, to re-query for all our existing cached (possibly visible) items to keep visual continuity
			const { oldest } = timeline;
			this.loadTimelineForSource(timeline.source, this.uri!, true, oldest !== undefined ? { limit: { timestamp: oldest.timestamp, id: oldest.id } } : undefined);
		} else {
			// Override the limit, to query for any newer items
			const { newest } = timeline;
			this.loadTimelineForSource(timeline.source, this.uri!, false, newest !== undefined ? { limit: { timestamp: newest.timestamp, id: newest.id } } : { limit: PageSize });
		}
	}

540 541
	private _pendingRefresh = false;

542
	private async handleRequest(request: TimelineRequest) {
543
		let response: Timeline | undefined;
544
		try {
545
			response = await this.progressService.withProgress({ location: this.id }, () => request.result);
546 547
		}
		finally {
548
			this.pendingRequests.delete(request.source);
549
		}
550

551
		if (
552
			response === undefined ||
553
			request.tokenSource.token.isCancellationRequested ||
554
			request.uri !== this.uri
555
		) {
556
			if (this.pendingRequests.size === 0 && this._pendingRefresh) {
557 558 559 560 561 562
				this.refresh();
			}

			return;
		}

563 564
		const source = request.source;

565 566 567 568 569
		let updated = false;
		const timeline = this.timelinesBySource.get(source);
		if (timeline === undefined) {
			this.timelinesBySource.set(source, new TimelineAggregate(response));
			updated = true;
570
		}
571 572
		else {
			updated = timeline.add(response);
573
		}
574

575 576 577 578 579 580 581
		if (updated) {
			this._pendingRefresh = true;

			// If we have visible items already and there are other pending requests, debounce for a bit to wait for other requests
			if (this.hasVisibleItems && this.pendingRequests.size !== 0) {
				this.refreshDebounced();
			} else {
582 583
				this.refresh();
			}
584 585 586 587 588 589 590 591 592 593
		} else if (this.pendingRequests.size === 0 && this._pendingRefresh) {
			this.refresh();
		}
	}

	private *getItems(): Generator<ITreeElement<TreeElement>, any, any> {
		let more = false;

		if (this.uri === undefined || this.timelinesBySource.size === 0) {
			this._visibleItemCount = 0;
594

E
Eric Amodio 已提交
595 596 597
			return;
		}

598 599
		const maxCount = this._maxItemCount;
		let count = 0;
600

601 602 603 604 605 606 607 608 609 610 611 612 613 614
		if (this.timelinesBySource.size === 1) {
			const [source, timeline] = Iterable.first(this.timelinesBySource);

			timeline.lastRenderedIndex = -1;

			if (this.excludedSources.has(source)) {
				this._visibleItemCount = 0;

				return;
			}

			if (timeline.items.length !== 0) {
				// If we have any items, just say we have one for now -- the real count will be updated below
				this._visibleItemCount = 1;
615
			}
616 617 618 619 620 621 622 623

			more = timeline.more;

			for (const item of timeline.items) {
				count++;
				if (count > maxCount) {
					more = true;
					break;
624
				}
625 626

				yield { element: item };
627 628
			}

629
			timeline.lastRenderedIndex = count - 1;
630
		}
631 632
		else {
			const sources: { timeline: TimelineAggregate; iterator: IterableIterator<TimelineItem>; nextItem: IteratorResult<TimelineItem, TimelineItem> }[] = [];
633

634 635
			let hasAnyItems = false;
			let mostRecentEnd = 0;
636

637 638
			for (const [source, timeline] of this.timelinesBySource) {
				timeline.lastRenderedIndex = -1;
639

640
				if (this.excludedSources.has(source) || timeline.stale) {
641
					continue;
642
				}
643 644 645

				if (timeline.items.length !== 0) {
					hasAnyItems = true;
646 647
				}

648 649 650 651 652 653 654
				if (timeline.more) {
					more = true;

					const last = timeline.items[Math.min(maxCount, timeline.items.length - 1)];
					if (last.timestamp > mostRecentEnd) {
						mostRecentEnd = last.timestamp;
					}
655
				}
656 657 658

				const iterator = timeline.items[Symbol.iterator]();
				sources.push({ timeline: timeline, iterator: iterator, nextItem: iterator.next() });
659 660
			}

661
			this._visibleItemCount = hasAnyItems ? 1 : 0;
662

663 664 665 666 667
			function getNextMostRecentSource() {
				return sources
					.filter(source => !source.nextItem!.done)
					.reduce((previous, current) => (previous === undefined || current.nextItem!.value.timestamp >= previous.nextItem!.value.timestamp) ? current : previous, undefined!);
			}
668

669 670 671
			let nextSource;
			while (nextSource = getNextMostRecentSource()) {
				nextSource.timeline.lastRenderedIndex++;
672

673 674 675 676 677 678
				if (nextSource.nextItem.value.timestamp >= mostRecentEnd) {
					count++;
					if (count > maxCount) {
						more = true;
						break;
					}
679

680 681
					yield { element: nextSource.nextItem.value };
				}
682

683 684
				nextSource.nextItem = nextSource.iterator.next();
			}
685 686
		}

687
		this._visibleItemCount = count;
688

689 690 691 692 693 694 695 696 697
		if (more) {
			yield {
				element: {
					handle: 'vscode-command:loadMore',
					label: localize('timeline.loadMore', 'Load more'),
					timestamp: 0
				} as CommandItem
			};
		}
698 699
	}

700
	private refresh() {
701 702 703 704
		if (!this.isBodyVisible()) {
			return;
		}

705 706 707 708
		this.tree.setChildren(null, this.getItems() as any);
		this._isEmpty = !this.hasVisibleItems;

		if (this.uri === undefined) {
709 710
			this.titleDescription = undefined;
			this.message = localize('timeline.editorCannotProvideTimeline', 'The active editor cannot provide timeline information.');
711 712
		} else if (this._isEmpty) {
			if (this.pendingRequests.size !== 0) {
713
				this.setLoadingUriMessage();
714
			} else {
715
				this.titleDescription = basename(this.uri.fsPath);
716
				this.message = localize('timeline.noTimelineInfo', 'No timeline information was provided.');
717
			}
718
		} else {
719
			this.titleDescription = basename(this.uri.fsPath);
720
			this.message = undefined;
721 722
		}

723
		this._pendingRefresh = false;
724 725 726 727
	}

	@debounce(500)
	private refreshDebounced() {
728 729 730 731 732
		this.refresh();
	}

	focus(): void {
		super.focus();
733
		this.tree.domFocus();
734 735
	}

736 737 738 739 740 741 742 743 744 745
	setExpanded(expanded: boolean): boolean {
		const changed = super.setExpanded(expanded);

		if (changed && this.isBodyVisible()) {
			this.onActiveEditorChanged();
		}

		return changed;
	}

746 747
	setVisible(visible: boolean): void {
		if (visible) {
748
			this.visibilityDisposables = new DisposableStore();
749

750
			this.editorService.onDidActiveEditorChange(this.onActiveEditorChanged, this, this.visibilityDisposables);
751

752 753
			this.onActiveEditorChanged();
		} else {
754
			this.visibilityDisposables?.dispose();
755
		}
756 757

		super.setVisible(visible);
758 759 760
	}

	protected layoutBody(height: number, width: number): void {
761
		this.tree.layout(height, width);
762 763
	}

764 765 766 767
	protected renderHeaderTitle(container: HTMLElement): void {
		super.renderHeaderTitle(container, this.title);

		DOM.addClass(container, 'timeline-view');
768
		this.$titleDescription = DOM.append(container, DOM.$('span.description', undefined, this.titleDescription ?? ''));
769 770
	}

771
	protected renderBody(container: HTMLElement): void {
772 773
		super.renderBody(container);

774
		this.$container = container;
775
		DOM.addClasses(container, 'tree-explorer-viewlet-tree-view', 'timeline-tree-view');
E
Eric Amodio 已提交
776

777 778
		this.$message = DOM.append(this.$container, DOM.$('.message'));
		DOM.addClass(this.$message, 'timeline-subtle');
E
Eric Amodio 已提交
779

E
Eric Amodio 已提交
780
		this.message = localize('timeline.editorCannotProvideTimeline', 'The active editor cannot provide timeline information.');
E
Eric Amodio 已提交
781

782 783 784 785
		this.$tree = document.createElement('div');
		DOM.addClasses(this.$tree, 'customview-tree', 'file-icon-themable-tree', 'hide-arrows');
		// DOM.addClass(this.treeElement, 'show-file-icons');
		container.appendChild(this.$tree);
786

787 788 789
		this.treeRenderer = this.instantiationService.createInstance(TimelineTreeRenderer, this.commands);
		this.tree = <WorkbenchObjectTree<TreeElement, FuzzyScore>>this.instantiationService.createInstance(WorkbenchObjectTree, 'TimelinePane',
			this.$tree, new TimelineListVirtualDelegate(), [this.treeRenderer], {
790
			identityProvider: new TimelineIdentityProvider(),
S
SteVen Batten 已提交
791 792
			keyboardNavigationLabelProvider: new TimelineKeyboardNavigationLabelProvider(),
			overrideStyles: {
793 794
				listBackground: this.getBackgroundColor(),

S
SteVen Batten 已提交
795
			}
796 797
		});

798
		const customTreeNavigator = ResourceNavigator.createTreeResourceNavigator(this.tree, { openOnFocus: false, openOnSelection: false });
799
		this._register(customTreeNavigator);
800 801
		this._register(this.tree.onContextMenu(e => this.onContextMenu(this.commands, e)));
		this._register(this.tree.onDidChangeSelection(e => this.ensureValidItems()));
802 803
		this._register(
			customTreeNavigator.onDidOpenResource(e => {
804
				if (!e.browserEvent || !this.ensureValidItems()) {
805 806 807
					return;
				}

808
				const selection = this.tree.getSelection();
809 810 811 812 813 814 815 816 817 818 819 820
				const item = selection.length === 1 ? selection[0] : undefined;
				// eslint-disable-next-line eqeqeq
				if (item == null) {
					return;
				}

				if (isTimelineItem(item)) {
					if (item.command) {
						this.commandService.executeCommand(item.command.id, ...(item.command.arguments || []));
					}
				}
				else if (isLoadMoreCommandItem(item)) {
821
					if (this.pendingRequests.size !== 0) {
822 823 824
						return;
					}

825
					this._maxItemCount = this._visibleItemCount + PageSize;
826
					this.loadTimeline(false);
827 828
				}
			})
829 830
		);
	}
831
	ensureValidItems() {
832 833 834 835
		// If we don't have any non-excluded timelines, clear the tree and show the loading message
		if (!this.hasVisibleItems || !this.timelineService.getSources().some(({ id }) => !this.excludedSources.has(id) && this.timelinesBySource.has(id))) {
			this.tree.setChildren(null, undefined);
			this._isEmpty = true;
836 837 838 839 840 841 842 843 844 845

			this.setLoadingUriMessage();

			return false;
		}

		return true;
	}

	setLoadingUriMessage() {
846
		const file = this.uri && basename(this.uri.fsPath);
847 848 849
		this.titleDescription = file ?? '';
		this.message = file ? localize('timeline.loading', 'Loading timeline for {0}...', file) : '';
	}
850

851
	private onContextMenu(commands: TimelinePaneCommands, treeEvent: ITreeContextMenuEvent<TreeElement | null>): void {
852 853 854 855 856 857 858 859 860
		const item = treeEvent.element;
		if (item === null) {
			return;
		}
		const event: UIEvent = treeEvent.browserEvent;

		event.preventDefault();
		event.stopPropagation();

861 862 863 864
		if (!this.ensureValidItems()) {
			return;
		}

865
		this.tree.setFocus([item]);
866
		const actions = commands.getItemContextActions(item);
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882
		if (!actions.length) {
			return;
		}

		this.contextMenuService.showContextMenu({
			getAnchor: () => treeEvent.anchor,
			getActions: () => actions,
			getActionViewItem: (action) => {
				const keybinding = this.keybindingService.lookupKeybinding(action.id);
				if (keybinding) {
					return new ActionViewItem(action, action, { label: true, keybinding: keybinding.getLabel() });
				}
				return undefined;
			},
			onHide: (wasCancelled?: boolean) => {
				if (wasCancelled) {
883
					this.tree.domFocus();
884 885
				}
			},
886
			getActionsContext: (): TimelineActionContext => ({ uri: this.uri, item: item }),
887 888 889
			actionRunner: new TimelineActionRunner()
		});
	}
890 891
}

892
export class TimelineElementTemplate implements IDisposable {
893 894
	static readonly id = 'TimelineElementTemplate';

895 896 897 898 899
	readonly actionBar: ActionBar;
	readonly icon: HTMLElement;
	readonly iconLabel: IconLabel;
	readonly timestamp: HTMLSpanElement;

900 901
	constructor(
		readonly container: HTMLElement,
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
		actionViewItemProvider: IActionViewItemProvider
	) {
		DOM.addClass(container, 'custom-view-tree-node-item');
		this.icon = DOM.append(container, DOM.$('.custom-view-tree-node-item-icon'));

		this.iconLabel = new IconLabel(container, { supportHighlights: true, supportCodicons: true });

		const timestampContainer = DOM.append(this.iconLabel.element, DOM.$('.timeline-timestamp-container'));
		this.timestamp = DOM.append(timestampContainer, DOM.$('span.timeline-timestamp'));

		const actionsContainer = DOM.append(this.iconLabel.element, DOM.$('.actions'));
		this.actionBar = new ActionBar(actionsContainer, { actionViewItemProvider: actionViewItemProvider });
	}

	dispose() {
		this.iconLabel.dispose();
		this.actionBar.dispose();
	}

	reset() {
		this.actionBar.clear();
	}
}

export class TimelineIdentityProvider implements IIdentityProvider<TreeElement> {
	getId(item: TreeElement): { toString(): string } {
		return item.handle;
	}
930 931
}

932 933 934
class TimelineActionRunner extends ActionRunner {

	runAction(action: IAction, { uri, item }: TimelineActionContext): Promise<any> {
935
		if (!isTimelineItem(item)) {
936
			// TODO@eamodio do we need to do anything else?
937 938 939
			return action.run();
		}

940 941 942 943 944 945 946 947 948 949
		return action.run(...[
			{
				$mid: 11,
				handle: item.handle,
				source: item.source,
				uri: uri
			},
			uri,
			item.source,
		]);
950 951 952
	}
}

953 954
export class TimelineKeyboardNavigationLabelProvider implements IKeyboardNavigationLabelProvider<TreeElement> {
	getKeyboardNavigationLabel(element: TreeElement): { toString(): string } {
955 956 957 958
		return element.label;
	}
}

959 960
export class TimelineListVirtualDelegate implements IListVirtualDelegate<TreeElement> {
	getHeight(_element: TreeElement): number {
961 962 963
		return 22;
	}

964
	getTemplateId(element: TreeElement): string {
965 966 967 968 969 970 971
		return TimelineElementTemplate.id;
	}
}

class TimelineTreeRenderer implements ITreeRenderer<TreeElement, FuzzyScore, TimelineElementTemplate> {
	readonly templateId: string = TimelineElementTemplate.id;

972
	private actionViewItemProvider: IActionViewItemProvider;
973

974
	constructor(
975
		private readonly commands: TimelinePaneCommands,
976
		@IInstantiationService protected readonly instantiationService: IInstantiationService,
977
		@IThemeService private themeService: IThemeService
978
	) {
979
		this.actionViewItemProvider = (action: IAction) => action instanceof MenuItemAction
980 981 982 983
			? this.instantiationService.createInstance(ContextAwareMenuEntryActionViewItem, action)
			: undefined;
	}

984
	private uri: URI | undefined;
985
	setUri(uri: URI | undefined) {
986
		this.uri = uri;
987
	}
988

989
	renderTemplate(container: HTMLElement): TimelineElementTemplate {
990
		return new TimelineElementTemplate(container, this.actionViewItemProvider);
991 992
	}

993 994 995 996 997 998
	renderElement(
		node: ITreeNode<TreeElement, FuzzyScore>,
		index: number,
		template: TimelineElementTemplate,
		height: number | undefined
	): void {
999
		template.reset();
1000

1001 1002
		const { element: item } = node;

1003
		const icon = this.themeService.getColorTheme().type === LIGHT ? item.icon : item.iconDark;
1004 1005 1006 1007 1008 1009 1010
		const iconUrl = icon ? URI.revive(icon) : null;

		if (iconUrl) {
			template.icon.className = 'custom-view-tree-node-item-icon';
			template.icon.style.backgroundImage = DOM.asCSSUrl(iconUrl);
		} else {
			let iconClass: string | undefined;
1011 1012
			if (item.themeIcon /*&& !this.isFileKindThemeIcon(element.themeIcon)*/) {
				iconClass = ThemeIcon.asClassName(item.themeIcon);
1013 1014 1015 1016
			}
			template.icon.className = iconClass ? `custom-view-tree-node-item-icon ${iconClass}` : '';
		}

1017 1018
		template.iconLabel.setLabel(item.label, item.description, {
			title: item.detail,
1019 1020
			matches: createMatches(node.filterData)
		});
1021

1022
		template.timestamp.textContent = isTimelineItem(item) ? fromNow(item.timestamp) : '';
1023

1024
		template.actionBar.context = { uri: this.uri, item: item } as TimelineActionContext;
1025
		template.actionBar.actionRunner = new TimelineActionRunner();
1026
		template.actionBar.push(this.commands.getItemActions(item), { icon: true, label: false });
1027 1028 1029 1030 1031 1032
	}

	disposeTemplate(template: TimelineElementTemplate): void {
		template.iconLabel.dispose();
	}
}
1033

1034 1035
class TimelinePaneCommands extends Disposable {
	private sourceDisposables: DisposableStore;
1036 1037

	constructor(
1038 1039 1040
		private readonly pane: TimelinePane,
		@ITimelineService private readonly timelineService: ITimelineService,
		@IConfigurationService private readonly configurationService: IConfigurationService,
1041 1042 1043 1044 1045
		@IContextKeyService private readonly contextKeyService: IContextKeyService,
		@IMenuService private readonly menuService: IMenuService,
		@IContextMenuService private readonly contextMenuService: IContextMenuService
	) {
		super();
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067

		this._register(this.sourceDisposables = new DisposableStore());

		this._register(registerAction2(class extends Action2 {
			constructor() {
				super({
					id: 'timeline.refresh',
					title: { value: localize('refresh', "Refresh"), original: 'Refresh' },
					icon: { id: 'codicon/refresh' },
					category: { value: localize('timeline', "Timeline"), original: 'Timeline' },
					menu: {
						id: MenuId.TimelineTitle,
						group: 'navigation',
						order: 99,
					}
				});
			}
			run(accessor: ServicesAccessor, ...args: any[]) {
				pane.reset();
			}
		}));

1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
		this._register(CommandsRegistry.registerCommand('timeline.toggleFollowActiveEditor',
			(accessor: ServicesAccessor, ...args: any[]) => pane.followActiveEditor = !pane.followActiveEditor
		));

		this._register(MenuRegistry.appendMenuItem(MenuId.TimelineTitle, ({
			command: {
				id: 'timeline.toggleFollowActiveEditor',
				title: { value: localize('timeline.toggleFollowActiveEditorCommand', "Toggle Active Editor Following"), original: 'Toggle Active Editor Following' },
				// title: localize(`timeline.toggleFollowActiveEditorCommand.stop`, "Stop following the Active Editor"),
				icon: { id: 'codicon/eye' },
				category: { value: localize('timeline', "Timeline"), original: 'Timeline' },
			},
			group: 'navigation',
			order: 98,
			when: TimelineFollowActiveEditorContext
		})));

		this._register(MenuRegistry.appendMenuItem(MenuId.TimelineTitle, ({
			command: {
				id: 'timeline.toggleFollowActiveEditor',
				title: { value: localize('timeline.toggleFollowActiveEditorCommand', "Toggle Active Editor Following"), original: 'Toggle Active Editor Following' },
				// title: localize(`timeline.toggleFollowActiveEditorCommand.stop`, "Stop following the Active Editor"),
				icon: { id: 'codicon/eye-closed' },
				category: { value: localize('timeline', "Timeline"), original: 'Timeline' },
			},
			group: 'navigation',
			order: 98,
			when: TimelineFollowActiveEditorContext.toNegated()
		})));
1097 1098 1099

		this._register(timelineService.onDidChangeProviders(() => this.updateTimelineSourceFilters()));
		this.updateTimelineSourceFilters();
1100 1101
	}

1102
	getItemActions(element: TreeElement): IAction[] {
1103 1104 1105
		return this.getActions(MenuId.TimelineItemContext, { key: 'timelineItem', value: element.contextValue }).primary;
	}

1106
	getItemContextActions(element: TreeElement): IAction[] {
1107 1108 1109 1110
		return this.getActions(MenuId.TimelineItemContext, { key: 'timelineItem', value: element.contextValue }).secondary;
	}

	private getActions(menuId: MenuId, context: { key: string, value?: string }): { primary: IAction[]; secondary: IAction[]; } {
1111 1112 1113
		const scoped = this.contextKeyService.createScoped();
		scoped.createKey('view', this.pane.id);
		scoped.createKey(context.key, context.value);
1114

1115
		const menu = this.menuService.createMenu(menuId, scoped);
1116 1117 1118 1119 1120 1121
		const primary: IAction[] = [];
		const secondary: IAction[] = [];
		const result = { primary, secondary };
		createAndFillInContextMenuActions(menu, { shouldForwardArgs: true }, result, this.contextMenuService, g => /^inline/.test(g));

		menu.dispose();
1122
		scoped.dispose();
1123 1124 1125

		return result;
	}
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158

	private updateTimelineSourceFilters() {
		this.sourceDisposables.clear();

		const excluded = new Set(this.configurationService.getValue<string[] | undefined>('timeline.excludeSources') ?? []);

		for (const source of this.timelineService.getSources()) {
			this.sourceDisposables.add(registerAction2(class extends Action2 {
				constructor() {
					super({
						id: `timeline.toggleExcludeSource:${source.id}`,
						title: { value: localize('timeline.filterSource', "Include: {0}", source.label), original: `Include: ${source.label}` },
						category: { value: localize('timeline', "Timeline"), original: 'Timeline' },
						menu: {
							id: MenuId.TimelineTitle,
							group: '2_sources',
						},
						toggled: ContextKeyExpr.regex(`config.timeline.excludeSources`, new RegExp(`\\b${escapeRegExpCharacters(source.id)}\\b`)).negate()
					});
				}
				run(accessor: ServicesAccessor, ...args: any[]) {
					if (excluded.has(source.id)) {
						excluded.delete(source.id);
					} else {
						excluded.add(source.id);
					}

					const configurationService = accessor.get(IConfigurationService);
					configurationService.updateValue('timeline.excludeSources', [...excluded.keys()]);
				}
			}));
		}
	}
1159
}