/
timelineWebview.ts
405 lines (338 loc) · 12.3 KB
/
timelineWebview.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
'use strict';
import type { Disposable, TextEditor } from 'vscode';
import { Uri, ViewColumn, window } from 'vscode';
import type { ShowQuickCommitFileCommandArgs } from '../../../commands';
import { configuration } from '../../../configuration';
import { Commands, ContextKeys } from '../../../constants';
import type { Container } from '../../../container';
import { setContext } from '../../../context';
import { PlusFeatures } from '../../../features';
import { GitUri } from '../../../git/gitUri';
import type { RepositoryChangeEvent } from '../../../git/models/repository';
import { RepositoryChange, RepositoryChangeComparisonMode } from '../../../git/models/repository';
import { executeCommand, registerCommand } from '../../../system/command';
import { createFromDateDelta } from '../../../system/date';
import { debug } from '../../../system/decorators/log';
import type { Deferrable } from '../../../system/function';
import { debounce } from '../../../system/function';
import { filter } from '../../../system/iterable';
import { getBestPath } from '../../../system/path';
import { hasVisibleTextEditor, isTextEditor } from '../../../system/utils';
import type { IpcMessage } from '../../../webviews/protocol';
import { onIpc } from '../../../webviews/protocol';
import { WebviewBase } from '../../../webviews/webviewBase';
import type { SubscriptionChangeEvent } from '../../subscription/subscriptionService';
import { ensurePlusFeaturesEnabled } from '../../subscription/utils';
import type { Commit, Period, State } from './protocol';
import { DidChangeNotificationType, OpenDataPointCommandType, UpdatePeriodCommandType } from './protocol';
import { generateRandomTimelineDataset } from './timelineWebviewView';
interface Context {
uri: Uri | undefined;
period: Period | undefined;
etagRepository: number | undefined;
etagSubscription: number | undefined;
}
const defaultPeriod: Period = '3|M';
export class TimelineWebview extends WebviewBase<State> {
private _bootstraping = true;
/** The context the webview has */
private _context: Context;
/** The context the webview should have */
private _pendingContext: Partial<Context> | undefined;
private _originalTitle: string;
constructor(container: Container) {
super(
container,
'gitlens.timeline',
'timeline.html',
'images/gitlens-icon.png',
'Visual File History',
Commands.ShowTimelinePage,
);
this._originalTitle = this.title;
this._context = {
uri: undefined,
period: defaultPeriod,
etagRepository: 0,
etagSubscription: 0,
};
}
override async show(column: ViewColumn = ViewColumn.Beside, ...args: any[]): Promise<void> {
if (!(await ensurePlusFeaturesEnabled())) return;
void this.container.usage.track('timelineWebview:shown');
return super.show(column, ...args);
}
protected override onInitializing(): Disposable[] | undefined {
this._context = {
uri: undefined,
period: defaultPeriod,
etagRepository: 0,
etagSubscription: this.container.subscription.etag,
};
this.updatePendingEditor(window.activeTextEditor);
this._context = { ...this._context, ...this._pendingContext };
this._pendingContext = undefined;
return [
this.container.subscription.onDidChange(this.onSubscriptionChanged, this),
this.container.git.onDidChangeRepository(this.onRepositoryChanged, this),
];
}
protected override onShowCommand(uri?: Uri): void {
if (uri != null) {
this.updatePendingUri(uri);
} else {
this.updatePendingEditor(window.activeTextEditor);
}
this._context = { ...this._context, ...this._pendingContext };
this._pendingContext = undefined;
super.onShowCommand();
}
protected override async includeBootstrap(): Promise<State> {
this._bootstraping = true;
this._context = { ...this._context, ...this._pendingContext };
this._pendingContext = undefined;
return this.getState(this._context);
}
protected override registerCommands(): Disposable[] {
return [registerCommand(Commands.RefreshTimelinePage, () => this.refresh())];
}
protected override onFocusChanged(focused: boolean): void {
if (focused) {
// If we are becoming focused, delay it a bit to give the UI time to update
setTimeout(() => void setContext(ContextKeys.TimelinePageFocused, focused), 0);
return;
}
void setContext(ContextKeys.TimelinePageFocused, focused);
}
protected override onVisibilityChanged(visible: boolean) {
if (!visible) return;
// Since this gets called even the first time the webview is shown, avoid sending an update, because the bootstrap has the data
if (this._bootstraping) {
this._bootstraping = false;
// If the uri changed since bootstrap still send the update
if (this._pendingContext == null || !('uri' in this._pendingContext)) {
return;
}
}
// Should be immediate, but it causes the bubbles to go missing on the chart, since the update happens while it still rendering
this.updateState();
}
protected override onMessageReceived(e: IpcMessage) {
switch (e.method) {
case OpenDataPointCommandType.method:
onIpc(OpenDataPointCommandType, e, params => {
if (params.data == null || !params.data.selected || this._context.uri == null) return;
const repository = this.container.git.getRepository(this._context.uri);
if (repository == null) return;
void executeCommand<ShowQuickCommitFileCommandArgs>(Commands.ShowQuickCommitFile, {
revisionUri: this.container.git
.getRevisionUri(params.data.id, getBestPath(this._context.uri), repository.uri)
.toString(true),
});
// const commandArgs: DiffWithPreviousCommandArgs = {
// line: 0,
// showOptions: {
// preserveFocus: true,
// preview: true,
// viewColumn: ViewColumn.Beside,
// },
// };
// void commands.executeCommand(
// Commands.DiffWithPrevious,
// new GitUri(gitUri, { repoPath: gitUri.repoPath!, sha: params.data.id }),
// commandArgs,
// );
});
break;
case UpdatePeriodCommandType.method:
onIpc(UpdatePeriodCommandType, e, params => {
if (this.updatePendingContext({ period: params.period })) {
this.updateState(true);
}
});
break;
}
}
@debug({ args: false })
private onRepositoryChanged(e: RepositoryChangeEvent) {
if (!e.changed(RepositoryChange.Heads, RepositoryChange.Index, RepositoryChangeComparisonMode.Any)) {
return;
}
if (this.updatePendingContext({ etagRepository: e.repository.etag })) {
this.updateState();
}
}
@debug({ args: false })
private onSubscriptionChanged(e: SubscriptionChangeEvent) {
if (this.updatePendingContext({ etagSubscription: e.etag })) {
this.updateState();
}
}
@debug({ args: false })
private async getState(current: Context): Promise<State> {
const access = await this.container.git.access(PlusFeatures.Timeline);
const dateFormat = configuration.get('defaultDateFormat') ?? 'MMMM Do, YYYY h:mma';
const shortDateFormat = configuration.get('defaultDateShortFormat') ?? 'short';
const period = current.period ?? defaultPeriod;
if (!access.allowed) {
const dataset = generateRandomTimelineDataset();
return {
dataset: dataset.sort((a, b) => b.sort - a.sort),
period: period,
title: 'src/app/index.ts',
uri: Uri.file('src/app/index.ts').toString(),
dateFormat: dateFormat,
shortDateFormat: shortDateFormat,
access: access,
};
}
if (current.uri == null) {
return {
period: period,
title: 'There are no editors open that can provide file history information',
dateFormat: dateFormat,
shortDateFormat: shortDateFormat,
access: access,
};
}
const gitUri = await GitUri.fromUri(current.uri);
const repoPath = gitUri.repoPath!;
const title = gitUri.relativePath;
this.title = `${this._originalTitle}: ${gitUri.fileName}`;
const [currentUser, log] = await Promise.all([
this.container.git.getCurrentUser(repoPath),
this.container.git.getLogForFile(repoPath, gitUri.fsPath, {
limit: 0,
ref: gitUri.sha,
since: this.getPeriodDate(period).toISOString(),
}),
]);
if (log == null) {
return {
dataset: [],
period: period,
title: 'No commits found for the specified time period',
uri: current.uri.toString(),
dateFormat: dateFormat,
shortDateFormat: shortDateFormat,
access: access,
};
}
let queryRequiredCommits = [
...filter(log.commits.values(), c => c.file?.stats == null && c.stats?.changedFiles !== 1),
];
if (queryRequiredCommits.length !== 0) {
const limit = configuration.get('visualHistory.queryLimit') ?? 20;
const repository = this.container.git.getRepository(current.uri);
const name = repository?.provider.name;
if (queryRequiredCommits.length > limit) {
void window.showWarningMessage(
`Unable able to show more than the first ${limit} commits for the specified time period because of ${
name ? `${name} ` : ''
}rate limits.`,
);
queryRequiredCommits = queryRequiredCommits.slice(0, 20);
}
void (await Promise.allSettled(queryRequiredCommits.map(c => c.ensureFullDetails())));
}
const name = currentUser?.name ? `${currentUser.name} (you)` : 'You';
const dataset: Commit[] = [];
for (const commit of log.commits.values()) {
const stats = commit.file?.stats ?? (commit.stats?.changedFiles === 1 ? commit.stats : undefined);
dataset.push({
author: commit.author.name === 'You' ? name : commit.author.name,
additions: stats?.additions,
deletions: stats?.deletions,
commit: commit.sha,
date: commit.date.toISOString(),
message: commit.message ?? commit.summary,
sort: commit.date.getTime(),
});
}
dataset.sort((a, b) => b.sort - a.sort);
return {
dataset: dataset,
period: period,
title: title,
uri: current.uri.toString(),
dateFormat: dateFormat,
shortDateFormat: shortDateFormat,
access: access,
};
}
private getPeriodDate(period: Period): Date {
const [number, unit] = period.split('|');
switch (unit) {
case 'D':
return createFromDateDelta(new Date(), { days: -parseInt(number, 10) });
case 'M':
return createFromDateDelta(new Date(), { months: -parseInt(number, 10) });
case 'Y':
return createFromDateDelta(new Date(), { years: -parseInt(number, 10) });
default:
return createFromDateDelta(new Date(), { months: -3 });
}
}
private updatePendingContext(context: Partial<Context>): boolean {
let changed = false;
for (const [key, value] of Object.entries(context)) {
const current = (this._context as unknown as Record<string, unknown>)[key];
if (
current === value ||
((current instanceof Uri || value instanceof Uri) && (current as any)?.toString() === value?.toString())
) {
continue;
}
if (this._pendingContext == null) {
this._pendingContext = {};
}
(this._pendingContext as Record<string, unknown>)[key] = value;
changed = true;
}
return changed;
}
private updatePendingEditor(editor: TextEditor | undefined): boolean {
if (editor == null && hasVisibleTextEditor()) return false;
if (editor != null && !isTextEditor(editor)) return false;
return this.updatePendingUri(editor?.document.uri);
}
private updatePendingUri(uri: Uri | undefined): boolean {
let etag;
if (uri != null) {
const repository = this.container.git.getRepository(uri);
etag = repository?.etag ?? 0;
} else {
etag = 0;
}
return this.updatePendingContext({ uri: uri, etagRepository: etag });
}
private _notifyDidChangeStateDebounced: Deferrable<() => void> | undefined = undefined;
@debug()
private updateState(immediate: boolean = false) {
if (!this.isReady || !this.visible) return;
if (immediate) {
void this.notifyDidChangeState();
return;
}
if (this._notifyDidChangeStateDebounced == null) {
this._notifyDidChangeStateDebounced = debounce(this.notifyDidChangeState.bind(this), 500);
}
this._notifyDidChangeStateDebounced();
}
@debug()
private async notifyDidChangeState() {
if (!this.isReady || !this.visible) return false;
this._notifyDidChangeStateDebounced?.cancel();
if (this._pendingContext == null) return false;
const context = { ...this._context, ...this._pendingContext };
return window.withProgress({ location: { viewId: this.id } }, async () => {
const success = await this.notify(DidChangeNotificationType, {
state: await this.getState(context),
});
if (success) {
this._context = context;
this._pendingContext = undefined;
}
});
}
}