timelinePane.ts 38.8 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
import { IAction, ActionRunner } from 'vs/base/common/actions';
10
import { CancellationTokenSource } from 'vs/base/common/cancellation';
11 12 13
import { fromNow } from 'vs/base/common/date';
import { debounce } from 'vs/base/common/decorators';
import { Emitter, Event } from 'vs/base/common/event';
14
import { FuzzyScore, createMatches } from 'vs/base/common/filters';
15
import { Iterable } from 'vs/base/common/iterator';
16
import { DisposableStore, IDisposable, Disposable } from 'vs/base/common/lifecycle';
17 18 19
import { Schemas } from 'vs/base/common/network';
import { basename } from 'vs/base/common/path';
import { escapeRegExpCharacters } from 'vs/base/common/strings';
20 21 22
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';
23
import { ITreeNode, ITreeRenderer, ITreeContextMenuEvent, ITreeElement } from 'vs/base/browser/ui/tree/tree';
24
import { ViewPane, IViewPaneOptions } from 'vs/workbench/browser/parts/views/viewPaneContainer';
J
João Moreno 已提交
25
import { TreeResourceNavigator, WorkbenchObjectTree } from 'vs/platform/list/browser/listService';
26 27
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
28
import { ContextKeyExpr, IContextKeyService, RawContextKey, IContextKey } from 'vs/platform/contextkey/common/contextkey';
29
import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration';
30
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
31
import { ITimelineService, TimelineChangeEvent, TimelineItem, TimelineOptions, TimelineProvidersChangeEvent, TimelineRequest, Timeline } from 'vs/workbench/contrib/timeline/common/timeline';
32 33
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { SideBySideEditor, toResource } from 'vs/workbench/common/editor';
34
import { ICommandService, CommandsRegistry } from 'vs/platform/commands/common/commands';
35
import { IThemeService, LIGHT, ThemeIcon } from 'vs/platform/theme/common/themeService';
36
import { IViewDescriptorService } from 'vs/workbench/common/views';
E
Eric Amodio 已提交
37
import { IProgressService } from 'vs/platform/progress/common/progress';
38
import { IOpenerService } from 'vs/platform/opener/common/opener';
39
import { IActionViewItemProvider, ActionBar, ActionViewItem } from 'vs/base/browser/ui/actionbar/actionbar';
40
import { ContextAwareMenuEntryActionViewItem, createAndFillInContextMenuActions } from 'vs/platform/actions/browser/menuEntryActionViewItem';
41
import { MenuItemAction, IMenuService, MenuId, registerAction2, Action2, MenuRegistry } from 'vs/platform/actions/common/actions';
42
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
43 44

const ItemHeight = 22;
45

46
type TreeElement = TimelineItem | LoadMoreCommand;
47

48 49
function isLoadMoreCommand(item: TreeElement | undefined): item is LoadMoreCommand {
	return item instanceof LoadMoreCommand;
50 51 52 53 54 55
}

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

56 57 58 59 60 61 62 63 64 65 66 67
function updateRelativeTime(item: TimelineItem, lastRelativeTime: string | undefined): string | undefined {
	item.relativeTime = isTimelineItem(item) ? fromNow(item.timestamp) : undefined;
	if (lastRelativeTime === undefined || item.relativeTime !== lastRelativeTime) {
		lastRelativeTime = item.relativeTime;
		item.hideRelativeTime = false;
	} else {
		item.hideRelativeTime = true;
	}

	return lastRelativeTime;
}

68 69 70 71
interface TimelineActionContext {
	uri: URI | undefined;
	item: TreeElement;
}
E
Eric Amodio 已提交
72

73 74
class TimelineAggregate {
	readonly items: TimelineItem[];
75
	readonly source: string;
76 77 78 79

	lastRenderedIndex: number;

	constructor(timeline: Timeline) {
80
		this.source = timeline.source;
81 82 83 84 85 86 87 88 89 90 91
		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 已提交
92
		return this._cursor !== undefined;
93 94 95 96 97 98 99 100 101 102
	}

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

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

103
	add(timeline: Timeline, options: TimelineOptions) {
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
		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);
		}

142 143 144 145
		// If we are not requesting more recent items than we have, then update the cursor
		if (options.cursor !== undefined || typeof options.limit !== 'object') {
			this._cursor = timeline.paging?.cursor;
		}
146 147 148 149 150 151 152 153 154 155 156 157 158

		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;
	}
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173

	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;
	}
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
class LoadMoreCommand {
	readonly handle = 'vscode-command:loadMore';
	readonly timestamp = 0;
	readonly description = undefined;
	readonly detail = undefined;
	readonly contextValue = undefined;
	// Make things easier for duck typing
	readonly id = undefined;
	readonly icon = undefined;
	readonly iconDark = undefined;
	readonly source = undefined;
	readonly relativeTime = undefined;
	readonly hideRelativeTime = undefined;

	constructor(loading: boolean) {
		this._loading = loading;
	}
	private _loading: boolean = false;
	get loading(): boolean {
		return this._loading;
	}
	set loading(value: boolean) {
		this._loading = value;
	}

	get ariaLabel() {
		return this.label;
	}

	get label() {
		return this.loading ? localize('timeline.loadingMore', "Loading...") : localize('timeline.loadMore', "Load more");
	}

	get themeIcon(): { id: string; } | undefined {
		return undefined; //this.loading ? { id: 'sync~spin' } : undefined;
	}
}

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

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

219 220 221 222 223 224
	private $container!: HTMLElement;
	private $message!: HTMLDivElement;
	private $titleDescription!: HTMLSpanElement;
	private $tree!: HTMLDivElement;
	private tree!: WorkbenchObjectTree<TreeElement, FuzzyScore>;
	private treeRenderer: TimelineTreeRenderer | undefined;
225
	private commands: TimelinePaneCommands;
226 227 228
	private visibilityDisposables: DisposableStore | undefined;

	private followActiveEditorContext: IContextKey<boolean>;
229

230 231 232
	private excludedSources: Set<string>;
	private pendingRequests = new Map<string, TimelineRequest>();
	private timelinesBySource = new Map<string, TimelineAggregate>();
233

234
	private uri: URI | undefined;
235

236 237 238 239 240 241 242 243 244
	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,
245
		@ICommandService protected commandService: ICommandService,
E
Eric Amodio 已提交
246
		@IProgressService private readonly progressService: IProgressService,
247 248 249
		@ITimelineService protected timelineService: ITimelineService,
		@IOpenerService openerService: IOpenerService,
		@IThemeService themeService: IThemeService,
250
		@ITelemetryService telemetryService: ITelemetryService,
251
	) {
252
		super({ ...options, titleMenuId: MenuId.TimelineTitle }, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService);
253

254
		this.commands = this._register(this.instantiationService.createInstance(TimelinePaneCommands, this));
255

256
		this.followActiveEditorContext = TimelineFollowActiveEditorContext.bindTo(this.contextKeyService);
257

258
		this.excludedSources = new Set(configurationService.getValue('timeline.excludeSources'));
259
		configurationService.onDidChangeConfiguration(this.onConfigurationChanged, this);
260

261 262
		this._register(timelineService.onDidChangeProviders(this.onProvidersChanged, this));
		this._register(timelineService.onDidChangeTimeline(this.onTimelineChanged, this));
263 264 265 266 267 268 269 270 271 272 273 274 275
		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;
276
		this.followActiveEditorContext.set(value);
277

278 279
		this.titleDescription = this.titleDescription;

280 281 282 283 284
		if (value) {
			this.onActiveEditorChanged();
		}
	}

285 286 287 288 289 290 291 292 293
	private _pageOnScroll: boolean | undefined;
	get pageOnScroll() {
		if (this._pageOnScroll === undefined) {
			this._pageOnScroll = this.configurationService.getValue<boolean | null | undefined>('timeline.pageOnScroll') ?? false;
		}

		return this._pageOnScroll;
	}

294
	get pageSize() {
295 296 297 298 299 300
		let pageSize = this.configurationService.getValue<number | null | undefined>('timeline.pageSize');
		// eslint-disable-next-line eqeqeq
		if (pageSize == null) {
			// If we are paging when scrolling, then add an extra item to the end to make sure the "Load more" item is out of view
			pageSize = Math.max(20, Math.floor((this.tree.renderHeight / ItemHeight) + (this.pageOnScroll ? 1 : -1)));
		}
301 302 303
		return pageSize;
	}

304 305 306 307 308 309 310 311 312 313 314 315 316
	reset() {
		this.loadTimeline(true);
	}

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

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

317
		this.uri = uri;
318
		this.titleDescription = uri ? basename(uri.fsPath) : '';
319
		this.treeRenderer?.setUri(uri);
320
		this.loadTimeline(true);
321 322 323
	}

	private onConfigurationChanged(e: IConfigurationChangeEvent) {
324 325
		if (e.affectsConfiguration('timeline.pageOnScroll')) {
			this._pageOnScroll = undefined;
326 327
		}

328 329
		if (e.affectsConfiguration('timeline.excludeSources')) {
			this.excludedSources = new Set(this.configurationService.getValue('timeline.excludeSources'));
330

331 332 333 334 335 336 337
			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();
			}
338
		}
339 340
	}

341
	private onActiveEditorChanged() {
342 343 344 345
		if (!this.followActiveEditor) {
			return;
		}

346 347 348 349 350 351 352
		let uri;

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

353
		if ((uri?.toString(true) === this.uri?.toString(true) && uri !== undefined) ||
354
			// Fallback to match on fsPath if we are dealing with files or git schemes
355
			(uri?.fsPath === this.uri?.fsPath && (uri?.scheme === 'file' || uri?.scheme === 'git') && (this.uri?.scheme === 'file' || this.uri?.scheme === 'git'))) {
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374

			// 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);
				}
			}

375 376 377
			return;
		}

378
		this.setUriCore(uri, false);
379 380
	}

381 382 383
	private onProvidersChanged(e: TimelineProvidersChangeEvent) {
		if (e.removed) {
			for (const source of e.removed) {
384
				this.timelinesBySource.delete(source);
385
			}
386 387

			this.refresh();
388 389 390
		}

		if (e.added) {
391
			this.loadTimeline(true, e.added);
392
		}
393 394
	}

395
	private onTimelineChanged(e: TimelineChangeEvent) {
396 397 398 399 400 401
		if (e?.uri === undefined || e.uri.toString(true) !== this.uri?.toString(true)) {
			const timeline = this.timelinesBySource.get(e.id);
			if (timeline === undefined) {
				return;
			}

402
			if (this.isBodyVisible()) {
E
Eric Amodio 已提交
403
				this.updateTimeline(timeline, e.reset);
404
			} else {
E
Eric Amodio 已提交
405
				timeline.invalidate(e.reset);
406
			}
407 408 409
		}
	}

410 411 412 413 414 415 416
	private _titleDescription: string | undefined;
	get titleDescription(): string | undefined {
		return this._titleDescription;
	}

	set titleDescription(description: string | undefined) {
		this._titleDescription = description;
417 418 419 420 421
		if (this.followActiveEditor || !description) {
			this.$titleDescription.textContent = description ?? '';
		} else {
			this.$titleDescription.textContent = `${description} (pinned)`;
		}
422 423
	}

E
Eric Amodio 已提交
424 425 426 427 428 429 430 431 432 433 434
	private _message: string | undefined;
	get message(): string | undefined {
		return this._message;
	}

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

	private updateMessage(): void {
435
		if (this._message !== undefined) {
E
Eric Amodio 已提交
436 437 438 439 440 441 442
			this.showMessage(this._message);
		} else {
			this.hideMessage();
		}
	}

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

446
		this.$message.textContent = message;
E
Eric Amodio 已提交
447 448 449 450
	}

	private hideMessage(): void {
		this.resetMessageElement();
451
		DOM.addClass(this.$message, 'hide');
E
Eric Amodio 已提交
452 453 454
	}

	private resetMessageElement(): void {
455
		DOM.clearNode(this.$message);
E
Eric Amodio 已提交
456 457
	}

458 459 460 461 462 463 464
	private _isEmpty = true;
	private _maxItemCount = 0;

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

466 467
	private clear(cancelPending: boolean) {
		this._visibleItemCount = 0;
468
		this._maxItemCount = this.pageSize;
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
		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;
			}
		}
	}

485
	private async loadTimeline(reset: boolean, sources?: string[]) {
486 487
		// If we have no source, we are reseting all sources, so cancel everything in flight and reset caches
		if (sources === undefined) {
488
			if (reset) {
489
				this.clear(true);
490
			}
E
Eric Amodio 已提交
491

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

496
				this.clear(false);
497
				this.refresh();
498 499 500

				return;
			}
501

502
			if (this._isEmpty && this.uri !== undefined) {
503
				this.setLoadingUriMessage();
E
Eric Amodio 已提交
504
			}
505 506
		}

507
		if (this.uri === undefined) {
508
			this.clear(false);
509 510
			this.refresh();

511 512 513
			return;
		}

514 515 516 517
		if (!this.isBodyVisible()) {
			return;
		}

518
		let hasPendingRequests = false;
519

520 521 522 523 524
		for (const source of sources ?? this.timelineService.getSources().map(s => s.id)) {
			const requested = this.loadTimelineForSource(source, this.uri, reset);
			if (requested) {
				hasPendingRequests = true;
			}
525 526
		}

527 528 529 530
		if (!hasPendingRequests) {
			this.refresh();
		} else if (this._isEmpty) {
			this.setLoadingUriMessage();
531
		}
532
	}
533

534 535 536 537
	private loadTimelineForSource(source: string, uri: URI, reset: boolean, options?: TimelineOptions) {
		if (this.excludedSources.has(source)) {
			return false;
		}
538

539
		const timeline = this.timelinesBySource.get(source);
540

541 542 543 544
		// 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 &&
545
			options?.cursor !== undefined &&
546
			timeline !== undefined &&
547
			(!timeline?.more || timeline.items.length > timeline.lastRenderedIndex + this.pageSize)
548 549 550
		) {
			return false;
		}
551

552
		if (options === undefined) {
553
			options = { cursor: reset ? undefined : timeline?.cursor, limit: this.pageSize };
554
		}
555

556 557 558
		let request = this.pendingRequests.get(source);
		if (request !== undefined) {
			options.cursor = request.options.cursor;
E
Eric Amodio 已提交
559

560 561 562 563 564 565
			// 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 已提交
566
				}
567
			}
568
		}
569
		request?.tokenSource.dispose(true);
570

571 572 573 574 575 576
		request = this.timelineService.getTimeline(
			source, uri, options, new CancellationTokenSource(), { cacheResults: true, resetCache: reset }
		);

		if (request === undefined) {
			return false;
577
		}
578 579 580 581 582 583 584

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

		this.handleRequest(request);

		return true;
585 586
	}

587 588 589 590 591 592 593 594 595
	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;
596
			this.loadTimelineForSource(timeline.source, this.uri!, false, newest !== undefined ? { limit: { timestamp: newest.timestamp, id: newest.id } } : { limit: this.pageSize });
597 598 599
		}
	}

600 601
	private _pendingRefresh = false;

602
	private async handleRequest(request: TimelineRequest) {
603
		let response: Timeline | undefined;
604
		try {
605
			response = await this.progressService.withProgress({ location: this.id }, () => request.result);
606 607
		}
		finally {
608
			this.pendingRequests.delete(request.source);
609
		}
610

611
		if (
612
			response === undefined ||
613
			request.tokenSource.token.isCancellationRequested ||
614
			request.uri !== this.uri
615
		) {
616
			if (this.pendingRequests.size === 0 && this._pendingRefresh) {
617 618 619 620 621 622
				this.refresh();
			}

			return;
		}

623 624
		const source = request.source;

625 626 627 628 629
		let updated = false;
		const timeline = this.timelinesBySource.get(source);
		if (timeline === undefined) {
			this.timelinesBySource.set(source, new TimelineAggregate(response));
			updated = true;
630
		}
631
		else {
632
			updated = timeline.add(response, request.options);
633
		}
634

635 636 637 638 639 640 641
		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 {
642 643
				this.refresh();
			}
644 645 646 647 648 649
		} else if (this.pendingRequests.size === 0) {
			if (this._pendingRefresh) {
				this.refresh();
			} else {
				this.tree.rerender();
			}
650 651 652 653 654 655 656 657
		}
	}

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

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

E
Eric Amodio 已提交
659 660 661
			return;
		}

662 663
		const maxCount = this._maxItemCount;
		let count = 0;
664

665
		if (this.timelinesBySource.size === 1) {
M
Matt Bierner 已提交
666
			const [source, timeline] = Iterable.first(this.timelinesBySource)!;
667 668 669 670 671 672 673 674 675 676 677 678

			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;
679
			}
680 681 682

			more = timeline.more;

683
			let lastRelativeTime: string | undefined;
684
			for (const item of timeline.items) {
685 686 687
				item.relativeTime = undefined;
				item.hideRelativeTime = undefined;

688 689 690 691
				count++;
				if (count > maxCount) {
					more = true;
					break;
692
				}
693

694
				lastRelativeTime = updateRelativeTime(item, lastRelativeTime);
695
				yield { element: item };
696 697
			}

698
			timeline.lastRenderedIndex = count - 1;
699
		}
700 701
		else {
			const sources: { timeline: TimelineAggregate; iterator: IterableIterator<TimelineItem>; nextItem: IteratorResult<TimelineItem, TimelineItem> }[] = [];
702

703 704
			let hasAnyItems = false;
			let mostRecentEnd = 0;
705

706 707
			for (const [source, timeline] of this.timelinesBySource) {
				timeline.lastRenderedIndex = -1;
708

709
				if (this.excludedSources.has(source) || timeline.stale) {
710
					continue;
711
				}
712 713 714

				if (timeline.items.length !== 0) {
					hasAnyItems = true;
715 716
				}

717 718 719 720 721 722 723
				if (timeline.more) {
					more = true;

					const last = timeline.items[Math.min(maxCount, timeline.items.length - 1)];
					if (last.timestamp > mostRecentEnd) {
						mostRecentEnd = last.timestamp;
					}
724
				}
725 726 727

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

730
			this._visibleItemCount = hasAnyItems ? 1 : 0;
731

732 733 734 735 736
			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!);
			}
737

738
			let lastRelativeTime: string | undefined;
739 740 741
			let nextSource;
			while (nextSource = getNextMostRecentSource()) {
				nextSource.timeline.lastRenderedIndex++;
742

743 744 745 746 747
				const item = nextSource.nextItem.value;
				item.relativeTime = undefined;
				item.hideRelativeTime = undefined;

				if (item.timestamp >= mostRecentEnd) {
748 749 750 751 752
					count++;
					if (count > maxCount) {
						more = true;
						break;
					}
753

754 755
					lastRelativeTime = updateRelativeTime(item, lastRelativeTime);
					yield { element: item };
756
				}
757

758 759
				nextSource.nextItem = nextSource.iterator.next();
			}
760 761
		}

762
		this._visibleItemCount = count;
763

764 765
		if (more) {
			yield {
766 767 768 769 770
				element: new LoadMoreCommand(this.pendingRequests.size !== 0)
			};
		} else if (this.pendingRequests.size !== 0) {
			yield {
				element: new LoadMoreCommand(true)
771 772
			};
		}
773 774
	}

775
	private refresh() {
776 777 778 779
		if (!this.isBodyVisible()) {
			return;
		}

780 781 782 783
		this.tree.setChildren(null, this.getItems() as any);
		this._isEmpty = !this.hasVisibleItems;

		if (this.uri === undefined) {
784
			this.titleDescription = undefined;
785
			this.message = localize('timeline.editorCannotProvideTimeline', "The active editor cannot provide timeline information.");
786 787
		} else if (this._isEmpty) {
			if (this.pendingRequests.size !== 0) {
788
				this.setLoadingUriMessage();
789
			} else {
790
				this.titleDescription = basename(this.uri.fsPath);
791
				this.message = localize('timeline.noTimelineInfo', "No timeline information was provided.");
792
			}
793
		} else {
794
			this.titleDescription = basename(this.uri.fsPath);
795
			this.message = undefined;
796 797
		}

798
		this._pendingRefresh = false;
799 800 801 802
	}

	@debounce(500)
	private refreshDebounced() {
803 804 805 806 807
		this.refresh();
	}

	focus(): void {
		super.focus();
808
		this.tree.domFocus();
809 810
	}

811 812 813 814
	setExpanded(expanded: boolean): boolean {
		const changed = super.setExpanded(expanded);

		if (changed && this.isBodyVisible()) {
E
Eric Amodio 已提交
815 816 817 818 819
			if (!this.followActiveEditor) {
				this.setUriCore(this.uri, true);
			} else {
				this.onActiveEditorChanged();
			}
820 821 822 823 824
		}

		return changed;
	}

825 826
	setVisible(visible: boolean): void {
		if (visible) {
827
			this.visibilityDisposables = new DisposableStore();
828

829
			this.editorService.onDidActiveEditorChange(this.onActiveEditorChanged, this, this.visibilityDisposables);
830 831
			// Refresh the view on focus to update the relative timestamps
			this.onDidFocus(() => this.refreshDebounced(), this, this.visibilityDisposables);
832

833 834
			super.setVisible(visible);

835 836
			this.onActiveEditorChanged();
		} else {
837
			this.visibilityDisposables?.dispose();
838

839 840
			super.setVisible(visible);
		}
841 842 843
	}

	protected layoutBody(height: number, width: number): void {
J
João Moreno 已提交
844
		super.layoutBody(height, width);
845
		this.tree.layout(height, width);
846 847
	}

848 849 850 851
	protected renderHeaderTitle(container: HTMLElement): void {
		super.renderHeaderTitle(container, this.title);

		DOM.addClass(container, 'timeline-view');
852
		this.$titleDescription = DOM.append(container, DOM.$('span.description', undefined, this.titleDescription ?? ''));
853 854
	}

855
	protected renderBody(container: HTMLElement): void {
856 857
		super.renderBody(container);

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

861 862
		this.$message = DOM.append(this.$container, DOM.$('.message'));
		DOM.addClass(this.$message, 'timeline-subtle');
E
Eric Amodio 已提交
863

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

866 867 868 869
		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);
870

871
		this.treeRenderer = this.instantiationService.createInstance(TimelineTreeRenderer, this.commands);
872 873 874 875 876 877
		this.treeRenderer.onDidScrollToEnd(item => {
			if (this.pageOnScroll) {
				this.loadMore(item);
			}
		});

878 879
		this.tree = <WorkbenchObjectTree<TreeElement, FuzzyScore>>this.instantiationService.createInstance(WorkbenchObjectTree, 'TimelinePane',
			this.$tree, new TimelineListVirtualDelegate(), [this.treeRenderer], {
880
			identityProvider: new TimelineIdentityProvider(),
881 882
			accessibilityProvider: {
				getAriaLabel(element: TreeElement): string {
883 884
					if (isLoadMoreCommand(element)) {
						return element.ariaLabel;
885
					}
886
					return element.accessibilityInformation ? element.accessibilityInformation.label : localize('timeline.aria.item', "{0}: {1}", element.relativeTime ?? '', element.label);
887 888 889
				},
				getWidgetAriaLabel(): string {
					return localize('timeline', "Timeline");
890 891
				}
			},
S
SteVen Batten 已提交
892 893
			keyboardNavigationLabelProvider: new TimelineKeyboardNavigationLabelProvider(),
			overrideStyles: {
894 895
				listBackground: this.getBackgroundColor(),

S
SteVen Batten 已提交
896
			}
897 898
		});

J
João Moreno 已提交
899
		const customTreeNavigator = new TreeResourceNavigator(this.tree, { openOnFocus: false, openOnSelection: false });
900
		this._register(customTreeNavigator);
901 902
		this._register(this.tree.onContextMenu(e => this.onContextMenu(this.commands, e)));
		this._register(this.tree.onDidChangeSelection(e => this.ensureValidItems()));
903 904
		this._register(
			customTreeNavigator.onDidOpenResource(e => {
905
				if (!e.browserEvent || !this.ensureValidItems()) {
906 907 908
					return;
				}

909
				const selection = this.tree.getSelection();
910 911 912 913 914 915 916 917 918 919 920
				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 || []));
					}
				}
921
				else if (isLoadMoreCommand(item)) {
922
					this.loadMore(item);
923 924
				}
			})
925 926
		);
	}
927 928

	private loadMore(item: LoadMoreCommand) {
929 930 931 932
		if (item.loading) {
			return;
		}

933 934 935 936 937 938 939 940 941 942 943
		item.loading = true;
		this.tree.rerender(item);

		if (this.pendingRequests.size !== 0) {
			return;
		}

		this._maxItemCount = this._visibleItemCount + this.pageSize;
		this.loadTimeline(false);
	}

944
	ensureValidItems() {
945 946 947 948
		// 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;
949 950 951 952 953 954 955 956 957 958

			this.setLoadingUriMessage();

			return false;
		}

		return true;
	}

	setLoadingUriMessage() {
959
		const file = this.uri && basename(this.uri.fsPath);
960
		this.titleDescription = file ?? '';
961
		this.message = file ? localize('timeline.loading', "Loading timeline for {0}...", file) : '';
962
	}
963

964
	private onContextMenu(commands: TimelinePaneCommands, treeEvent: ITreeContextMenuEvent<TreeElement | null>): void {
965 966 967 968 969 970 971 972 973
		const item = treeEvent.element;
		if (item === null) {
			return;
		}
		const event: UIEvent = treeEvent.browserEvent;

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

974 975 976 977
		if (!this.ensureValidItems()) {
			return;
		}

978
		this.tree.setFocus([item]);
979
		const actions = commands.getItemContextActions(item);
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
		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) {
996
					this.tree.domFocus();
997 998
				}
			},
999
			getActionsContext: (): TimelineActionContext => ({ uri: this.uri, item: item }),
1000 1001 1002
			actionRunner: new TimelineActionRunner()
		});
	}
1003 1004
}

1005
export class TimelineElementTemplate implements IDisposable {
1006 1007
	static readonly id = 'TimelineElementTemplate';

1008 1009 1010 1011 1012
	readonly actionBar: ActionBar;
	readonly icon: HTMLElement;
	readonly iconLabel: IconLabel;
	readonly timestamp: HTMLSpanElement;

1013 1014
	constructor(
		readonly container: HTMLElement,
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
		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() {
1035 1036
		this.icon.className = '';
		this.icon.style.backgroundImage = '';
1037 1038 1039 1040 1041 1042 1043 1044
		this.actionBar.clear();
	}
}

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

1047 1048 1049
class TimelineActionRunner extends ActionRunner {

	runAction(action: IAction, { uri, item }: TimelineActionContext): Promise<any> {
1050
		if (!isTimelineItem(item)) {
1051
			// TODO@eamodio do we need to do anything else?
1052 1053 1054
			return action.run();
		}

1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
		return action.run(...[
			{
				$mid: 11,
				handle: item.handle,
				source: item.source,
				uri: uri
			},
			uri,
			item.source,
		]);
1065 1066 1067
	}
}

1068 1069
export class TimelineKeyboardNavigationLabelProvider implements IKeyboardNavigationLabelProvider<TreeElement> {
	getKeyboardNavigationLabel(element: TreeElement): { toString(): string } {
1070 1071 1072 1073
		return element.label;
	}
}

1074 1075
export class TimelineListVirtualDelegate implements IListVirtualDelegate<TreeElement> {
	getHeight(_element: TreeElement): number {
1076
		return ItemHeight;
1077 1078
	}

1079
	getTemplateId(element: TreeElement): string {
1080 1081 1082 1083 1084
		return TimelineElementTemplate.id;
	}
}

class TimelineTreeRenderer implements ITreeRenderer<TreeElement, FuzzyScore, TimelineElementTemplate> {
1085 1086 1087
	private readonly _onDidScrollToEnd = new Emitter<LoadMoreCommand>();
	readonly onDidScrollToEnd: Event<LoadMoreCommand> = this._onDidScrollToEnd.event;

1088 1089
	readonly templateId: string = TimelineElementTemplate.id;

1090
	private actionViewItemProvider: IActionViewItemProvider;
1091

1092
	constructor(
1093
		private readonly commands: TimelinePaneCommands,
1094
		@IInstantiationService protected readonly instantiationService: IInstantiationService,
1095
		@IThemeService private themeService: IThemeService
1096
	) {
1097
		this.actionViewItemProvider = (action: IAction) => action instanceof MenuItemAction
1098 1099 1100 1101
			? this.instantiationService.createInstance(ContextAwareMenuEntryActionViewItem, action)
			: undefined;
	}

1102
	private uri: URI | undefined;
1103
	setUri(uri: URI | undefined) {
1104
		this.uri = uri;
1105
	}
1106

1107
	renderTemplate(container: HTMLElement): TimelineElementTemplate {
1108
		return new TimelineElementTemplate(container, this.actionViewItemProvider);
1109 1110
	}

1111 1112 1113 1114 1115 1116
	renderElement(
		node: ITreeNode<TreeElement, FuzzyScore>,
		index: number,
		template: TimelineElementTemplate,
		height: number | undefined
	): void {
1117
		template.reset();
1118

1119 1120
		const { element: item } = node;

1121
		const icon = this.themeService.getColorTheme().type === LIGHT ? item.icon : item.iconDark;
1122 1123 1124 1125 1126 1127 1128
		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;
1129 1130
			if (item.themeIcon /*&& !this.isFileKindThemeIcon(element.themeIcon)*/) {
				iconClass = ThemeIcon.asClassName(item.themeIcon);
1131 1132 1133 1134
			}
			template.icon.className = iconClass ? `custom-view-tree-node-item-icon ${iconClass}` : '';
		}

1135 1136
		template.iconLabel.setLabel(item.label, item.description, {
			title: item.detail,
1137 1138
			matches: createMatches(node.filterData)
		});
1139

1140 1141
		template.timestamp.textContent = item.relativeTime ?? '';
		DOM.toggleClass(template.timestamp.parentElement!, 'timeline-timestamp--duplicate', isTimelineItem(item) && item.hideRelativeTime);
1142

1143
		template.actionBar.context = { uri: this.uri, item: item } as TimelineActionContext;
1144
		template.actionBar.actionRunner = new TimelineActionRunner();
1145
		template.actionBar.push(this.commands.getItemActions(item), { icon: true, label: false });
1146 1147 1148 1149 1150

		// If we are rendering the load more item, we've scrolled to the end, so trigger an event
		if (isLoadMoreCommand(item)) {
			setTimeout(() => this._onDidScrollToEnd.fire(item), 0);
		}
1151 1152 1153 1154 1155 1156
	}

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

1158 1159
class TimelinePaneCommands extends Disposable {
	private sourceDisposables: DisposableStore;
1160 1161

	constructor(
1162 1163 1164
		private readonly pane: TimelinePane,
		@ITimelineService private readonly timelineService: ITimelineService,
		@IConfigurationService private readonly configurationService: IConfigurationService,
1165 1166 1167 1168 1169
		@IContextKeyService private readonly contextKeyService: IContextKeyService,
		@IMenuService private readonly menuService: IMenuService,
		@IContextMenuService private readonly contextMenuService: IContextMenuService
	) {
		super();
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191

		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();
			}
		}));

1192 1193 1194 1195 1196 1197 1198
		this._register(CommandsRegistry.registerCommand('timeline.toggleFollowActiveEditor',
			(accessor: ServicesAccessor, ...args: any[]) => pane.followActiveEditor = !pane.followActiveEditor
		));

		this._register(MenuRegistry.appendMenuItem(MenuId.TimelineTitle, ({
			command: {
				id: 'timeline.toggleFollowActiveEditor',
1199 1200
				title: { value: localize('timeline.toggleFollowActiveEditorCommand.follow', "Pin the Current Timeline"), original: 'Pin the Current Timeline' },
				icon: { id: 'codicon/pin' },
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
				category: { value: localize('timeline', "Timeline"), original: 'Timeline' },
			},
			group: 'navigation',
			order: 98,
			when: TimelineFollowActiveEditorContext
		})));

		this._register(MenuRegistry.appendMenuItem(MenuId.TimelineTitle, ({
			command: {
				id: 'timeline.toggleFollowActiveEditor',
1211 1212
				title: { value: localize('timeline.toggleFollowActiveEditorCommand.unfollow', "Unpin the Current Timeline"), original: 'Unpin the Current Timeline' },
				icon: { id: 'codicon/pinned' },
1213 1214 1215 1216 1217 1218
				category: { value: localize('timeline', "Timeline"), original: 'Timeline' },
			},
			group: 'navigation',
			order: 98,
			when: TimelineFollowActiveEditorContext.toNegated()
		})));
1219 1220 1221

		this._register(timelineService.onDidChangeProviders(() => this.updateTimelineSourceFilters()));
		this.updateTimelineSourceFilters();
1222 1223
	}

1224
	getItemActions(element: TreeElement): IAction[] {
1225 1226 1227
		return this.getActions(MenuId.TimelineItemContext, { key: 'timelineItem', value: element.contextValue }).primary;
	}

1228
	getItemContextActions(element: TreeElement): IAction[] {
1229 1230 1231 1232
		return this.getActions(MenuId.TimelineItemContext, { key: 'timelineItem', value: element.contextValue }).secondary;
	}

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

1237
		const menu = this.menuService.createMenu(menuId, scoped);
1238 1239 1240 1241 1242 1243
		const primary: IAction[] = [];
		const secondary: IAction[] = [];
		const result = { primary, secondary };
		createAndFillInContextMenuActions(menu, { shouldForwardArgs: true }, result, this.contextMenuService, g => /^inline/.test(g));

		menu.dispose();
1244
		scoped.dispose();
1245 1246 1247

		return result;
	}
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280

	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()]);
				}
			}));
		}
	}
1281
}