/
GraphWrapper.tsx
567 lines (532 loc) · 18.4 KB
/
GraphWrapper.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
import type { OnFormatCommitDateTime } from '@gitkraken/gitkraken-components';
import GraphContainer, {
type CssVariables,
type GraphColumnSetting as GKGraphColumnSetting,
type GraphColumnsSettings as GKGraphColumnsSettings,
type GraphPlatform,
type GraphRow,
type GraphZoneType,
} from '@gitkraken/gitkraken-components';
import type { ReactElement } from 'react';
import React, { createElement, useEffect, useRef, useState } from 'react';
import { getPlatform } from '@env/platform';
import { DateStyle } from '../../../../config';
import type { GraphColumnConfig } from '../../../../config';
import { RepositoryVisibility } from '../../../../git/gitProvider';
import type { GitGraphRowType } from '../../../../git/models/graph';
import type {
DismissBannerParams,
GraphComponentConfig,
GraphRepository,
State,
UpdateStateCallback,
} from '../../../../plus/webviews/graph/protocol';
import type { Subscription } from '../../../../subscription';
import { getSubscriptionTimeRemaining, SubscriptionState } from '../../../../subscription';
import { pluralize } from '../../../../system/string';
import type { DateTimeFormat } from '../../shared/date';
import { formatDate, fromNow } from '../../shared/date';
export interface GraphWrapperProps extends State {
nonce?: string;
subscriber: (callback: UpdateStateCallback) => () => void;
onSelectRepository?: (repository: GraphRepository) => void;
onColumnChange?: (name: string, settings: GraphColumnConfig) => void;
onMissingAvatars?: (emails: { [email: string]: string }) => void;
onMoreCommits?: () => void;
onDismissBanner?: (key: DismissBannerParams['key']) => void;
onSelectionChange?: (selection: { id: string; type: GitGraphRowType }[]) => void;
}
const getStyleProps = (
mixedColumnColors: CssVariables | undefined,
): { cssVariables: CssVariables; themeOpacityFactor: number } => {
const body = document.body;
const computedStyle = window.getComputedStyle(body);
return {
cssVariables: {
'--app__bg0': computedStyle.getPropertyValue('--color-background'),
'--panel__bg0': computedStyle.getPropertyValue('--graph-panel-bg'),
'--text-selected': computedStyle.getPropertyValue('--color-foreground'),
'--text-normal': computedStyle.getPropertyValue('--color-foreground--85'),
'--text-secondary': computedStyle.getPropertyValue('--color-foreground--65'),
'--text-disabled': computedStyle.getPropertyValue('--color-foreground--50'),
'--text-accent': computedStyle.getPropertyValue('--color-link-foreground'),
'--text-inverse': computedStyle.getPropertyValue('--vscode-input-background'),
'--text-bright': computedStyle.getPropertyValue('--vscode-input-background'),
...mixedColumnColors,
},
themeOpacityFactor: parseInt(computedStyle.getPropertyValue('--graph-theme-opacity-factor')) || 1,
};
};
const defaultGraphColumnsSettings: GKGraphColumnsSettings = {
commitAuthorZone: { width: 110 },
commitDateTimeZone: { width: 130 },
commitMessageZone: { width: 130 },
commitZone: { width: 170 },
refZone: { width: 150 },
};
const getGraphColSettingsModel = (config?: GraphComponentConfig): GKGraphColumnsSettings => {
const columnsSettings: GKGraphColumnsSettings = { ...defaultGraphColumnsSettings };
if (config?.columns !== undefined) {
for (const column of Object.keys(config.columns)) {
columnsSettings[column] = {
width: config.columns[column].width,
};
}
}
return columnsSettings;
};
const getGraphDateFormatter = (config?: GraphComponentConfig): OnFormatCommitDateTime => {
return (commitDateTime: number) => formatCommitDateTime(commitDateTime, config?.dateStyle, config?.dateFormat);
};
type DebouncableFn = (...args: any) => void;
type DebouncedFn = (...args: any) => void;
const debounceFrame = (func: DebouncableFn): DebouncedFn => {
let timer: number;
return function (...args: any) {
if (timer) cancelAnimationFrame(timer);
timer = requestAnimationFrame(() => {
func(...args);
});
};
};
const createIconElements = (): { [key: string]: ReactElement<any> } => {
const iconList = [
'head',
'remote',
'tag',
'stash',
'check',
'loading',
'warning',
'added',
'modified',
'deleted',
'renamed',
'resolved',
];
const elementLibrary: { [key: string]: ReactElement<any> } = {};
iconList.forEach(iconKey => {
elementLibrary[iconKey] = createElement('span', { className: `graph-icon icon--${iconKey}` });
});
return elementLibrary;
};
const iconElementLibrary = createIconElements();
const getIconElementLibrary = (iconKey: string) => {
return iconElementLibrary[iconKey];
};
const getClientPlatform = (): GraphPlatform => {
switch (getPlatform()) {
case 'web-macOS':
return 'darwin';
case 'web-windows':
return 'win32';
case 'web-linux':
default:
return 'linux';
}
};
const clientPlatform = getClientPlatform();
// eslint-disable-next-line @typescript-eslint/naming-convention
export function GraphWrapper({
subscriber,
repositories = [],
rows = [],
selectedRepository,
selectedRows,
subscription,
selectedRepositoryVisibility,
allowed,
avatars,
config,
loading,
paging,
onSelectRepository,
onColumnChange,
onMissingAvatars,
onMoreCommits,
onSelectionChange,
nonce,
mixedColumnColors,
previewBanner = true,
trialBanner = true,
onDismissBanner,
}: GraphWrapperProps) {
const [graphRows, setGraphRows] = useState(rows);
const [graphAvatars, setAvatars] = useState(avatars);
const [reposList, setReposList] = useState(repositories);
const [currentRepository, setCurrentRepository] = useState<GraphRepository | undefined>(
reposList.find(item => item.path === selectedRepository),
);
const [graphSelectedRows, setSelectedRows] = useState(selectedRows);
const [graphConfig, setGraphConfig] = useState(config);
// const [graphDateFormatter, setGraphDateFormatter] = useState(getGraphDateFormatter(config));
const [graphColSettings, setGraphColSettings] = useState(getGraphColSettingsModel(config));
const [pagingState, setPagingState] = useState(paging);
const [isLoading, setIsLoading] = useState(loading);
const [styleProps, setStyleProps] = useState(getStyleProps(mixedColumnColors));
// TODO: application shouldn't know about the graph component's header
const graphHeaderOffset = 24;
const [mainWidth, setMainWidth] = useState<number>();
const [mainHeight, setMainHeight] = useState<number>();
const mainRef = useRef<HTMLElement>(null);
// banner
const [showPreview, setShowPreview] = useState(previewBanner);
// account
const [showAccount, setShowAccount] = useState(trialBanner);
const [isAllowed, setIsAllowed] = useState(allowed ?? false);
const [isPrivateRepo, setIsPrivateRepo] = useState(selectedRepositoryVisibility === RepositoryVisibility.Private);
const [subscriptionSnapshot, setSubscriptionSnapshot] = useState<Subscription | undefined>(subscription);
// repo selection UI
const [repoExpanded, setRepoExpanded] = useState(false);
useEffect(() => {
if (mainRef.current === null) return;
const setDimensionsDebounced = debounceFrame((width, height) => {
setMainWidth(Math.floor(width));
setMainHeight(Math.floor(height) - graphHeaderOffset);
});
const resizeObserver = new ResizeObserver(entries =>
entries.forEach(e => setDimensionsDebounced(e.contentRect.width, e.contentRect.height)),
);
resizeObserver.observe(mainRef.current);
return () => resizeObserver.disconnect();
}, [mainRef]);
function transformData(state: State) {
setGraphRows(state.rows ?? []);
setAvatars(state.avatars ?? {});
setReposList(state.repositories ?? []);
setCurrentRepository(reposList.find(item => item.path === state.selectedRepository));
setSelectedRows(state.selectedRows);
setGraphConfig(state.config);
// setGraphDateFormatter(getGraphDateFormatter(config));
setGraphColSettings(getGraphColSettingsModel(state.config));
setPagingState(state.paging);
setStyleProps(getStyleProps(state.mixedColumnColors));
setIsAllowed(state.allowed ?? false);
setShowAccount(state.trialBanner ?? true);
setSubscriptionSnapshot(state.subscription);
setIsPrivateRepo(state.selectedRepositoryVisibility === RepositoryVisibility.Private);
setIsLoading(state.loading);
}
useEffect(() => subscriber?.(transformData), []);
const handleSelectRepository = (item: GraphRepository) => {
if (item != null && item !== currentRepository) {
setIsLoading(true);
onSelectRepository?.(item);
}
setRepoExpanded(false);
};
const handleToggleRepos = () => {
if (currentRepository != null && reposList.length <= 1) return;
setRepoExpanded(!repoExpanded);
};
const handleMissingAvatars = (emails: { [email: string]: string }) => {
onMissingAvatars?.(emails);
};
const handleMoreCommits = () => {
setIsLoading(true);
onMoreCommits?.();
};
const handleOnColumnResized = (graphZoneType: GraphZoneType, columnSettings: GKGraphColumnSetting) => {
onColumnChange?.(graphZoneType, { width: columnSettings.width });
};
const handleSelectGraphRows = (graphRows: GraphRow[]) => {
onSelectionChange?.(graphRows.map(r => ({ id: r.sha, type: r.type as GitGraphRowType })));
};
const handleDismissPreview = () => {
setShowPreview(false);
onDismissBanner?.('preview');
};
const handleDismissAccount = () => {
setShowAccount(false);
onDismissBanner?.('trial');
};
const renderTrialDays = () => {
if (
!subscriptionSnapshot ||
![SubscriptionState.FreeInPreviewTrial, SubscriptionState.FreePlusInTrial].includes(
subscriptionSnapshot.state,
)
) {
return;
}
const days = getSubscriptionTimeRemaining(subscriptionSnapshot, 'days') ?? 0;
return (
<span className="mr-loose">
<span className="badge">GitLens+ Trial</span> ({days < 1 ? '< 1 day' : pluralize('day', days)} left)
</span>
);
};
const renderAlertContent = () => {
if (subscriptionSnapshot == null || !isPrivateRepo || (isAllowed && !showAccount)) return;
let icon = 'account';
let modifier = '';
let content;
let actions;
let days = 0;
if (
[SubscriptionState.FreeInPreviewTrial, SubscriptionState.FreePlusInTrial].includes(
subscriptionSnapshot.state,
)
) {
days = getSubscriptionTimeRemaining(subscriptionSnapshot, 'days') ?? 0;
}
switch (subscriptionSnapshot.state) {
case SubscriptionState.Free:
case SubscriptionState.Paid:
return;
case SubscriptionState.FreeInPreviewTrial:
case SubscriptionState.FreePlusInTrial:
icon = 'calendar';
modifier = 'neutral';
content = (
<>
<p className="alert__title">GitLens+ Trial</p>
<p className="alert__message">
You have {days < 1 ? 'less than one day' : pluralize('day', days)} left in your{' '}
<a title="Learn more about GitLens+ features" href="command:gitlens.plus.learn">
GitLens+ trial
</a>
. Once your trial ends, you'll need a paid plan to continue to use GitLens+ features,
including the Commit Graph, on this and other private repos.
</p>
</>
);
break;
case SubscriptionState.FreePreviewTrialExpired:
icon = 'warning';
modifier = 'warning';
content = (
<>
<p className="alert__title">Extend Your GitLens+ Trial</p>
<p className="alert__message">
Your free trial has ended, please sign in to extend your trial of GitLens+ features on
private repos by an additional 7-days.
</p>
</>
);
actions = (
<a className="alert-action" href="command:gitlens.plus.loginOrSignUp">
Extend Trial
</a>
);
break;
case SubscriptionState.FreePlusTrialExpired:
icon = 'warning';
modifier = 'warning';
content = (
<>
<p className="alert__title">GitLens+ Trial Expired</p>
<p className="alert__message">
Your free trial has ended, please upgrade your account to continue to use GitLens+ features,
including the Commit Graph, on this and other private repos.
</p>
</>
);
actions = (
<a className="alert-action" href="command:gitlens.plus.purchase">
Upgrade Your Account
</a>
);
break;
case SubscriptionState.VerificationRequired:
icon = 'unverified';
modifier = 'warning';
content = (
<>
<p className="alert__title">Please verify your email</p>
<p className="alert__message">Please verify the email for the account you created.</p>
</>
);
actions = (
<>
<a className="alert-action" href="command:gitlens.plus.resendVerification">
Resend Verification Email
</a>
<a className="alert-action" href="command:gitlens.plus.validate">
Refresh Verification Status
</a>
</>
);
break;
}
return (
<div className={`alert${modifier !== '' ? ` alert--${modifier}` : ''}`}>
<span className={`alert__icon codicon codicon-${icon}`}></span>
<div className="alert__content">
{content}
{actions && <div className="alert__actions">{actions}</div>}
</div>
{isAllowed && (
<button className="alert__dismiss" type="button" onClick={() => handleDismissAccount()}>
<span className="codicon codicon-chrome-close"></span>
</button>
)}
</div>
);
};
return (
<>
<section className="graph-app__banners">
{showPreview && (
<div className="alert">
<span className="alert__icon codicon codicon-eye"></span>
<div className="alert__content">
<p className="alert__title">GitLens+ Feature Preview</p>
<p className="alert__message">
The Commit Graph is currently in preview. It will always be freely available for local
and public repos, while private repos require a paid plan.
</p>
<p className="alert__accent">
<span className="codicon codicon-feedback alert__accent-icon" /> Join the{' '}
<a href="https://github.com/gitkraken/vscode-gitlens/discussions/2158">
discussion on GitHub
</a>
! We'd love to hear from you.
</p>
<p className="alert__accent">
<span className="glicon glicon-clock alert__accent-icon" /> GitLens+{' '}
<a href="command:gitlens.plus.purchase">introductory pricing</a> will end with the next
release (late Sept, early Oct).
</p>
</div>
<button className="alert__dismiss" type="button" onClick={() => handleDismissPreview()}>
<span className="codicon codicon-chrome-close"></span>
</button>
</div>
)}
{renderAlertContent()}
</section>
<main
ref={mainRef}
id="main"
className={`graph-app__main${!isAllowed ? ' is-gated' : ''}`}
aria-hidden={!isAllowed}
>
{!isAllowed && <div className="graph-app__cover"></div>}
{currentRepository !== undefined ? (
<>
{mainWidth !== undefined && mainHeight !== undefined && (
<GraphContainer
avatarUrlByEmail={graphAvatars}
columnsSettings={graphColSettings}
cssVariables={styleProps.cssVariables}
enableMultiSelection={graphConfig?.enableMultiSelection}
formatCommitDateTime={getGraphDateFormatter(graphConfig)}
getExternalIcon={getIconElementLibrary}
graphRows={graphRows}
hasMoreCommits={pagingState?.more}
height={mainHeight}
// highlightRowssOnRefHover={graphConfig?.highlightRowsOnRefHover}
isLoadingRows={isLoading}
isSelectedBySha={graphSelectedRows}
nonce={nonce}
onColumnResized={handleOnColumnResized}
onSelectGraphRows={handleSelectGraphRows}
onEmailsMissingAvatarUrls={handleMissingAvatars}
onShowMoreCommits={handleMoreCommits}
platform={clientPlatform}
shaLength={graphConfig?.shaLength}
themeOpacityFactor={styleProps.themeOpacityFactor}
useAuthorInitialsForAvatars={!graphConfig?.avatars}
width={mainWidth}
/>
)}
</>
) : (
<p>No repository is selected</p>
)}
</main>
<footer className={`actionbar graph-app__footer${!isAllowed ? ' is-gated' : ''}`} aria-hidden={!isAllowed}>
<div className="actionbar__group">
<div className="actioncombo">
<button
type="button"
aria-controls="repo-actioncombo-list"
aria-expanded={repoExpanded}
aria-haspopup="listbox"
id="repo-actioncombo-label"
className="actioncombo__label"
role="combobox"
aria-activedescendant={
repoExpanded
? `repo-actioncombo-item-${reposList.findIndex(
item => item.path === currentRepository?.path,
)}`
: undefined
}
onClick={() => handleToggleRepos()}
>
<span className="codicon codicon-repo actioncombo__icon" aria-label="Repository "></span>
{currentRepository?.formattedName ?? 'none selected'}
</button>
<div
className="actioncombo__list"
id="repo-actioncombo-list"
role="listbox"
tabIndex={-1}
aria-labelledby="repo-actioncombo-label"
>
{reposList.length > 0 ? (
reposList.map((item, index) => (
<button
type="button"
className="actioncombo__item"
role="option"
data-value={item.path}
id={`repo-actioncombo-item-${index}`}
key={`repo-actioncombo-item-${index}`}
aria-selected={item.path === currentRepository?.path}
onClick={() => handleSelectRepository(item)}
disabled={item.path === currentRepository?.path}
>
{item.formattedName}
</button>
))
) : (
<span
className="actioncombo__item"
role="option"
id="repo-actioncombo-item-0"
aria-selected="true"
>
None available
</span>
)}
</div>
</div>
{isAllowed && graphRows.length > 0 && (
<span className="actionbar__details">
showing {graphRows.length} item{graphRows.length ? 's' : ''}
</span>
)}
{isLoading && (
<span className="actionbar__loading">
<span className="icon--loading icon-modifier--spin" />
</span>
)}
</div>
<div className="actionbar__group">
{renderTrialDays()}
<span className="badge">Preview</span>
<a
href="https://github.com/gitkraken/vscode-gitlens/discussions/2158"
title="Commit Graph Feedback"
aria-label="Commit Graph Feedback"
>
<span className="codicon codicon-feedback"></span>
</a>
</div>
<div className={`progress-container infinite${isLoading ? ' active' : ''}`} role="progressbar">
<div className="progress-bar"></div>
</div>
</footer>
</>
);
}
function formatCommitDateTime(
commitDateTime: number,
style: DateStyle = DateStyle.Absolute,
format: DateTimeFormat | string = 'short+short',
): string {
return style === DateStyle.Relative ? fromNow(commitDateTime) : formatDate(commitDateTime, format);
}