-
Notifications
You must be signed in to change notification settings - Fork 268
/
Commit.tsx
820 lines (762 loc) · 28 KB
/
Commit.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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type {DagCommitInfo} from './dag/dag';
import type {CommitInfo, SuccessorInfo} from './types';
import type {ContextMenuItem} from 'shared/ContextMenu';
import {Avatar} from './Avatar';
import {BranchIndicator} from './BranchIndicator';
import {commitMode, hasUnsavedEditedCommitMessage} from './CommitInfoView/CommitInfoState';
import {currentComparisonMode} from './ComparisonView/atoms';
import {FlexRow} from './ComponentUtils';
import {EducationInfoTip} from './Education';
import {HighlightCommitsWhileHovering, isHighlightedCommit} from './HighlightedCommits';
import {InlineBadge} from './InlineBadge';
import {Subtle} from './Subtle';
import {latestSuccessorUnlessExplicitlyObsolete} from './SuccessionTracker';
import {getSuggestedRebaseOperation, suggestedRebaseDestinations} from './SuggestedRebase';
import {Tooltip} from './Tooltip';
import {UncommitButton} from './UncommitButton';
import {UncommittedChanges} from './UncommittedChanges';
import {tracker} from './analytics';
import {codeReviewProvider, latestCommitMessageTitle} from './codeReview/CodeReviewInfo';
import {DiffInfo} from './codeReview/DiffBadge';
import {SyncStatus, syncStatusAtom} from './codeReview/syncStatus';
import {islDrawerState} from './drawerState';
import {FoldButton, useRunFoldPreview} from './fold';
import {t, T} from './i18n';
import {IconStack} from './icons/IconStack';
import {readAtom, writeAtom} from './jotaiUtils';
import {getAmendToOperation, isAmendToAllowedForCommit} from './operationUtils';
import {GotoOperation} from './operations/GotoOperation';
import {HideOperation} from './operations/HideOperation';
import {RebaseOperation} from './operations/RebaseOperation';
import {CommitPreview, uncommittedChangesWithPreviews} from './previews';
import {RelativeDate} from './relativeDate';
import {isNarrowCommitTree} from './responsive';
import {selectedCommits, useCommitSelection} from './selection';
import {
inlineProgressByHash,
isFetchingUncommittedChanges,
latestDag,
latestUncommittedChanges,
operationBeingPreviewed,
useRunOperation,
useRunPreviewedOperation,
} from './serverAPIState';
import {useConfirmUnsavedEditsBeforeSplit} from './stackEdit/ui/ConfirmUnsavedEditsBeforeSplit';
import {SplitButton} from './stackEdit/ui/SplitButton';
import {editingStackIntentionHashes} from './stackEdit/ui/stackEditState';
import {useShowToast} from './toast';
import {succeedableRevset} from './types';
import {short} from './utils';
import {VSCodeButton, VSCodeTag} from '@vscode/webview-ui-toolkit/react';
import {useAtomValue, useSetAtom} from 'jotai';
import {useAtomCallback} from 'jotai/utils';
import React, {memo, useCallback, useEffect, useState} from 'react';
import {ComparisonType} from 'shared/Comparison';
import {useContextMenu} from 'shared/ContextMenu';
import {Icon} from 'shared/Icon';
import {useAutofocusRef} from 'shared/hooks';
import {notEmpty} from 'shared/utils';
function isDraggablePreview(previewType?: CommitPreview): boolean {
switch (previewType) {
// dragging preview descendants would be confusing (it would reset part of your drag),
// you probably meant to drag the root.
case CommitPreview.REBASE_DESCENDANT:
// old commits are already being dragged
case CommitPreview.REBASE_OLD:
case CommitPreview.HIDDEN_ROOT:
case CommitPreview.HIDDEN_DESCENDANT:
return false;
// you CAN let go of the preview and drag it again
case CommitPreview.REBASE_ROOT:
// optimistic rebase commits act like normal, they can be dragged just fine
case CommitPreview.REBASE_OPTIMISTIC_DESCENDANT:
case CommitPreview.REBASE_OPTIMISTIC_ROOT:
case undefined:
// other unrelated previews are draggable
default:
return true;
}
}
/**
* Some preview types should not allow actions on top of them
* For example, you can't click goto on the preview of dragging a rebase,
* but you can goto on the optimistic form of a running rebase.
*/
function previewPreventsActions(preview?: CommitPreview): boolean {
switch (preview) {
case CommitPreview.REBASE_OLD:
case CommitPreview.REBASE_DESCENDANT:
case CommitPreview.REBASE_ROOT:
case CommitPreview.HIDDEN_ROOT:
case CommitPreview.HIDDEN_DESCENDANT:
case CommitPreview.FOLD:
case CommitPreview.FOLD_PREVIEW:
case CommitPreview.NON_ACTIONABLE_COMMIT:
return true;
}
return false;
}
export const Commit = memo(
({
commit,
previewType,
hasChildren,
bodyOnly = false,
}: {
commit: DagCommitInfo | CommitInfo;
previewType?: CommitPreview;
hasChildren: boolean;
bodyOnly?: boolean;
}) => {
const isPublic = commit.phase === 'public';
const isObsoleted = commit.successorInfo != null;
const handlePreviewedOperation = useRunPreviewedOperation();
const runOperation = useRunOperation();
const setEditStackIntentionHashes = useSetAtom(editingStackIntentionHashes);
const isHighlighted = useAtomValue(isHighlightedCommit(bodyOnly ? '' : commit.hash));
const inlineProgress = useAtomValue(inlineProgressByHash(commit.hash));
const {isSelected, onClickToSelect, overrideSelection} = useCommitSelection(commit.hash);
const actionsPrevented = previewPreventsActions(previewType);
const isNarrow = useAtomValue(isNarrowCommitTree);
const title = useAtomValue(latestCommitMessageTitle(commit.hash));
const toast = useShowToast();
const clipboardCopy = (text: string) => toast.copyAndShowToast(text);
const isNonActionable = previewType === CommitPreview.NON_ACTIONABLE_COMMIT;
const onDoubleClickToShowDrawer = useCallback(() => {
// Select the commit if it was deselected.
if (!isSelected) {
overrideSelection([commit.hash]);
}
// Show the drawer.
writeAtom(islDrawerState, state => ({
...state,
right: {
...state.right,
collapsed: false,
},
}));
if (commit.isHead) {
// if we happened to be in commit mode, swap to amend mode so you see the details instead
writeAtom(commitMode, 'amend');
}
}, [overrideSelection, isSelected, commit.hash, commit.isHead]);
const viewChangesCallback = useAtomCallback((_get, set) => {
set(currentComparisonMode, {
comparison: {type: ComparisonType.Committed, hash: commit.hash},
visible: true,
});
});
const confirmUnsavedEditsBeforeSplit = useConfirmUnsavedEditsBeforeSplit();
async function handleSplit() {
if (!(await confirmUnsavedEditsBeforeSplit([commit], 'split'))) {
return;
}
setEditStackIntentionHashes(['split', new Set([commit.hash])]);
tracker.track('SplitOpenFromCommitContextMenu');
}
const makeContextMenuOptions = () => {
const hasUncommittedChanges = (readAtom(uncommittedChangesWithPreviews).length ?? 0) > 0;
const syncStatus = readAtom(syncStatusAtom)?.get(commit.hash);
const items: Array<ContextMenuItem> = [
{
label: <T replace={{$hash: short(commit?.hash)}}>Copy Commit Hash "$hash"</T>,
onClick: () => clipboardCopy(commit.hash),
},
];
if (!isPublic && commit.diffId != null) {
items.push({
label: <T replace={{$number: commit.diffId}}>Copy Diff Number "$number"</T>,
onClick: () => clipboardCopy(commit.diffId ?? ''),
});
}
if (!isPublic) {
items.push({
label: <T>View Changes in Commit</T>,
onClick: viewChangesCallback,
});
}
if (
!isPublic &&
(syncStatus === SyncStatus.LocalIsNewer || syncStatus === SyncStatus.RemoteIsNewer)
) {
const provider = readAtom(codeReviewProvider);
if (provider?.supportsComparingSinceLastSubmit) {
items.push({
label: <T replace={{$provider: provider?.label ?? 'remote'}}>Compare with $provider</T>,
onClick: () => {
writeAtom(currentComparisonMode, {
comparison: {type: ComparisonType.SinceLastCodeReviewSubmit, hash: commit.hash},
visible: true,
});
},
});
}
}
if (!isPublic && !actionsPrevented) {
bodyOnly || items.push({type: 'divider'});
const suggestedRebases = readAtom(suggestedRebaseDestinations);
items.push({
label: 'Rebase onto',
type: 'submenu',
children:
suggestedRebases?.map(([dest, name]) => ({
label: <T>{name}</T>,
onClick: () => {
const operation = getSuggestedRebaseOperation(
dest,
latestSuccessorUnlessExplicitlyObsolete(commit),
);
runOperation(operation);
},
})) ?? [],
});
if (isAmendToAllowedForCommit(commit)) {
items.push({
label: <T>Amend changes to here</T>,
onClick: () => runOperation(getAmendToOperation(commit)),
});
}
if (!isObsoleted) {
items.push({
label: hasUncommittedChanges ? (
<span className="context-menu-disabled-option">
<T>Split... </T>
<Subtle>
<T>(disabled due to uncommitted changes)</T>
</Subtle>
</span>
) : (
<T>Split...</T>
),
onClick: hasUncommittedChanges ? () => null : handleSplit,
});
}
items.push({
label: hasChildren ? <T>Hide Commit and Descendants</T> : <T>Hide Commit</T>,
onClick: () =>
writeAtom(
operationBeingPreviewed,
new HideOperation(latestSuccessorUnlessExplicitlyObsolete(commit)),
),
});
}
return items;
};
const contextMenu = useContextMenu(makeContextMenuOptions);
const commitActions = [];
if (previewType === CommitPreview.REBASE_ROOT) {
commitActions.push(
<React.Fragment key="rebase">
<VSCodeButton
appearance="secondary"
onClick={() => handlePreviewedOperation(/* cancel */ true)}>
<T>Cancel</T>
</VSCodeButton>
<VSCodeButton
appearance="primary"
onClick={() => handlePreviewedOperation(/* cancel */ false)}>
<T>Run Rebase</T>
</VSCodeButton>
</React.Fragment>,
);
} else if (previewType === CommitPreview.HIDDEN_ROOT) {
commitActions.push(
<React.Fragment key="hide">
<VSCodeButton
appearance="secondary"
onClick={() => handlePreviewedOperation(/* cancel */ true)}>
<T>Cancel</T>
</VSCodeButton>
<ConfirmHideButton onClick={() => handlePreviewedOperation(/* cancel */ false)} />
</React.Fragment>,
);
} else if (previewType === CommitPreview.FOLD_PREVIEW) {
commitActions.push(<ConfirmCombineButtons key="fold" />);
}
if (!isPublic && !actionsPrevented && isSelected) {
commitActions.push(<FoldButton key="fold-button" commit={commit} />);
}
if (!actionsPrevented && !commit.isHead) {
commitActions.push(
<span className="goto-button" key="goto-button">
<Tooltip
title={t(
'Update files in the working copy to match this commit. Mark this commit as the "current commit".',
)}
delayMs={250}>
<VSCodeButton
appearance="secondary"
aria-label={t('Go to commit "$title"', {replace: {$title: commit.title}})}
onClick={event => {
runOperation(
new GotoOperation(
// If the commit has a remote bookmark, use that instead of the hash. This is easier to read in the command history
// and works better with optimistic state
commit.remoteBookmarks.length > 0
? succeedableRevset(commit.remoteBookmarks[0])
: latestSuccessorUnlessExplicitlyObsolete(commit),
),
);
event.stopPropagation(); // don't toggle selection by letting click propagate onto selection target.
// Instead, ensure we remove the selection, so we view the new head commit by default
// (since the head commit is the default thing shown in the sidebar)
writeAtom(selectedCommits, new Set());
}}>
<T>Goto</T> <Icon icon="newline" />
</VSCodeButton>
</Tooltip>
</span>,
);
}
if (!isPublic && !actionsPrevented && commit.isHead) {
commitActions.push(<UncommitButton key="uncommit" />);
}
if (!isPublic && !actionsPrevented && commit.isHead && !isObsoleted) {
commitActions.push(<SplitButton key="split" commit={commit} />);
}
if (!isPublic && !actionsPrevented) {
commitActions.push(
<OpenCommitInfoButton
key="open-sidebar"
revealCommit={onDoubleClickToShowDrawer}
commit={commit}
/>,
);
}
if (bodyOnly && (commit as DagCommitInfo).isYouAreHere) {
return (
<div className="head-commit-info">
<UncommittedChanges place="main" />
</div>
);
}
return (
<div
className={
'commit' +
(commit.isHead ? ' head-commit' : '') +
(commit.successorInfo != null ? ' obsolete' : '') +
(isHighlighted ? ' highlighted' : '') +
(isPublic || hasChildren || bodyOnly ? '' : ' topmost')
}
onContextMenu={contextMenu}
data-testid={`commit-${commit.hash}`}>
{!isNonActionable &&
!bodyOnly &&
(commit.isHead || previewType === CommitPreview.GOTO_PREVIOUS_LOCATION) ? (
<HeadCommitInfo commit={commit} previewType={previewType} hasChildren={hasChildren} />
) : null}
<div className={'commit-rows' + (isSelected ? ' selected-commit' : '')}>
{isSelected ? (
<div className="selected-commit-background" data-testid="selected-commit" />
) : null}
<DraggableCommit
className={
'commit-details' + (previewType != null ? ` commit-preview-${previewType}` : '')
}
commit={commit}
draggable={!isPublic && isDraggablePreview(previewType)}
onClick={onClickToSelect}
onDoubleClick={onDoubleClickToShowDrawer}>
{bodyOnly || <Avatar username={commit.author} />}
{isPublic ? null : (
<span className="commit-title">
<span>{title}</span>
<CommitDate date={commit.date} />
</span>
)}
<UnsavedEditedMessageIndicator commit={commit} />
{commit.bookmarks.map(bookmark => (
<VSCodeTag key={bookmark}>{bookmark}</VSCodeTag>
))}
{commit.remoteBookmarks.map(remoteBookmarks => (
<VSCodeTag key={remoteBookmarks}>{remoteBookmarks}</VSCodeTag>
))}
{commit?.stableCommitMetadata != null ? (
<>
{commit.stableCommitMetadata.map(stable => (
<Tooltip title={stable.description} key={stable.value}>
<div className="stable-commit-metadata">
<VSCodeTag>{stable.value}</VSCodeTag>
</div>
</Tooltip>
))}
</>
) : null}
{isPublic ? <CommitDate date={commit.date} /> : null}
{isNarrow ? commitActions : null}
</DraggableCommit>
<DivIfChildren className="commit-second-row">
{commit.diffId && !isPublic ? (
<DiffInfo commit={commit} hideActions={actionsPrevented || inlineProgress != null} />
) : null}
{commit.successorInfo != null ? (
<SuccessorInfoToDisplay successorInfo={commit.successorInfo} />
) : null}
{inlineProgress && (
<span className="commit-inline-operation-progress">
<Icon icon="loading" /> <T>{inlineProgress}</T>
</span>
)}
</DivIfChildren>
{!isNarrow ? commitActions : null}
</div>
</div>
);
},
(prevProps, nextProps) => {
const prevCommit = prevProps.commit;
const nextCommit = nextProps.commit;
const commitEqual =
'equals' in nextCommit ? nextCommit.equals(prevCommit) : nextCommit === prevCommit;
return (
commitEqual &&
nextProps.previewType === prevProps.previewType &&
nextProps.bodyOnly === prevProps.bodyOnly &&
nextProps.hasChildren === prevProps.hasChildren
);
},
);
function OpenCommitInfoButton({
commit,
revealCommit,
}: {
commit: CommitInfo;
revealCommit: () => unknown;
}) {
return (
<Tooltip title={t("Open commit's details in sidebar")} delayMs={250}>
<VSCodeButton
appearance="icon"
onClick={e => {
revealCommit();
e.stopPropagation();
e.preventDefault();
}}
className="open-commit-info-button"
aria-label={t('Open commit "$title"', {replace: {$title: commit.title}})}
data-testid="open-commit-info-button">
<Icon icon="chevron-right" />
</VSCodeButton>
</Tooltip>
);
}
function ConfirmHideButton({onClick}: {onClick: () => unknown}) {
const ref = useAutofocusRef() as React.MutableRefObject<null>;
return (
<VSCodeButton ref={ref} appearance="primary" onClick={onClick}>
<T>Hide</T>
</VSCodeButton>
);
}
function ConfirmCombineButtons() {
const ref = useAutofocusRef() as React.MutableRefObject<null>;
const [cancel, run] = useRunFoldPreview();
return (
<>
<VSCodeButton appearance="secondary" onClick={cancel}>
<T>Cancel</T>
</VSCodeButton>
<VSCodeButton ref={ref} appearance="primary" onClick={run}>
<T>Run Combine</T>
</VSCodeButton>
</>
);
}
function CommitDate({date}: {date: Date}) {
return (
<span className="commit-date" title={date.toLocaleString()}>
<RelativeDate date={date} useShortVariant />
</span>
);
}
function DivIfChildren({
children,
...props
}: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>) {
if (!children || (Array.isArray(children) && children.filter(notEmpty).length === 0)) {
return null;
}
return <div {...props}>{children}</div>;
}
function UnsavedEditedMessageIndicator({commit}: {commit: CommitInfo}) {
const isEdted = useAtomValue(hasUnsavedEditedCommitMessage(commit.hash));
if (!isEdted) {
return null;
}
return (
<div className="unsaved-message-indicator" data-testid="unsaved-message-indicator">
<Tooltip title={t('This commit has unsaved changes to its message')}>
<IconStack>
<Icon icon="output" />
<Icon icon="circle-large-filled" />
</IconStack>
</Tooltip>
</div>
);
}
function HeadCommitInfo({
commit,
previewType,
hasChildren,
}: {
commit: CommitInfo;
previewType?: CommitPreview;
hasChildren: boolean;
}) {
const uncommittedChanges = useAtomValue(latestUncommittedChanges);
// render head info indented when:
// - we have uncommitted changes, so we're showing files
// and EITHER
// - we're on a public commit (you'll create a new "branch" by committing)
// - the commit we're rendering has children (we'll render the current child as new branch after committing)
const indent = uncommittedChanges.length > 0 && (commit.phase === 'public' || hasChildren);
return (
<div className={`head-commit-info-container${indent ? ' head-commit-info-indented' : ''}`}>
<YouAreHere previewType={previewType} />
{
commit.isHead ? (
<div className="head-commit-info">
<UncommittedChanges place="main" />
</div>
) : null // don't show uncommitted changes twice while checking out
}
{indent ? <BranchIndicator /> : null}
</div>
);
}
export function YouAreHere({
previewType,
hideSpinner,
}: {
previewType?: CommitPreview;
hideSpinner?: boolean;
}) {
const isFetching = useAtomValue(isFetchingUncommittedChanges) && !hideSpinner;
let text;
let spinner = false;
switch (previewType) {
case CommitPreview.GOTO_DESTINATION:
text = <T>You're moving here...</T>;
spinner = true;
break;
case CommitPreview.GOTO_PREVIOUS_LOCATION:
text = <T>You were here...</T>;
break;
default:
text = <T>You are here</T>;
break;
}
return (
<div className="you-are-here-container">
<InlineBadge kind="primary">
{spinner ? <Icon icon="loading" /> : null}
{text}
</InlineBadge>
{isFetching &&
// don't show fetch spinner on previous location
previewType !== CommitPreview.GOTO_PREVIOUS_LOCATION ? (
<Icon icon="loading" />
) : null}
</div>
);
}
let commitBeingDragged: CommitInfo | undefined = undefined;
// This is a global state outside React because commit DnD is a global
// concept: there won't be 2 DnD happening at once in the same window.
let lastDndId = 0;
function preventDefault(e: Event) {
e.preventDefault();
}
function handleDragEnd(event: Event) {
event.preventDefault();
commitBeingDragged = undefined;
const draggedDOMNode = event.target;
draggedDOMNode?.removeEventListener('dragend', handleDragEnd);
document.removeEventListener('drop', preventDefault);
document.removeEventListener('dragover', preventDefault);
}
function DraggableCommit({
commit,
children,
className,
draggable,
onClick,
onDoubleClick,
onContextMenu,
}: {
commit: CommitInfo;
children: React.ReactNode;
className: string;
draggable: boolean;
onClick?: (e: React.MouseEvent<HTMLDivElement> | React.KeyboardEvent<HTMLDivElement>) => unknown;
onDoubleClick?: (e: React.MouseEvent<HTMLDivElement>) => unknown;
onContextMenu?: React.MouseEventHandler<HTMLDivElement>;
}) {
const [dragDisabledMessage, setDragDisabledMessage] = useState<string | null>(null);
const handleDragEnter = useCallback(() => {
// Capture the environment.
const currentBeingDragged = commitBeingDragged;
const currentDndId = ++lastDndId;
const handleDnd = () => {
// Skip handling if there was a new "DragEnter" event that invalidates this one.
if (lastDndId != currentDndId) {
return;
}
const dag = readAtom(latestDag);
if (currentBeingDragged != null && commit.hash !== currentBeingDragged.hash) {
const beingDragged = currentBeingDragged;
if (dag.has(beingDragged.hash)) {
if (
// can't rebase a commit onto its descendants
!dag.isAncestor(beingDragged.hash, commit.hash) &&
// can't rebase a commit onto its parent... it's already there!
!(beingDragged.parents as Array<string>).includes(commit.hash)
) {
// if the dest commit has a remote bookmark, use that instead of the hash.
// this is easier to understand in the command history and works better with optimistic state
const destination =
commit.remoteBookmarks.length > 0
? succeedableRevset(commit.remoteBookmarks[0])
: latestSuccessorUnlessExplicitlyObsolete(commit);
writeAtom(operationBeingPreviewed, op => {
const newRebase = new RebaseOperation(
latestSuccessorUnlessExplicitlyObsolete(beingDragged),
destination,
);
const isEqual = newRebase.equals(op);
return isEqual ? op : newRebase;
});
}
}
}
};
// This allows us to recieve a list of "queued" DragEnter events
// before actually handling them. This way we can skip "invalidated"
// events and only handle the last (valid) one.
window.setTimeout(() => {
handleDnd();
}, 1);
}, [commit]);
const handleDragStart = useCallback(
(event: React.DragEvent<HTMLDivElement>) => {
// can't rebase with uncommitted changes
if (hasUncommittedChanges()) {
setDragDisabledMessage(t('Cannot drag to rebase with uncommitted changes.'));
event.preventDefault();
}
if (commit.successorInfo != null) {
setDragDisabledMessage(t('Cannot rebase obsoleted commits.'));
event.preventDefault();
}
commitBeingDragged = commit;
event.dataTransfer.dropEffect = 'none';
const draggedDOMNode = event.target;
// prevent animation of commit returning to drag start location on drop
draggedDOMNode.addEventListener('dragend', handleDragEnd);
document.addEventListener('drop', preventDefault);
document.addEventListener('dragover', preventDefault);
},
[commit],
);
useEffect(() => {
if (dragDisabledMessage) {
const timeout = setTimeout(() => setDragDisabledMessage(null), 1500);
return () => clearTimeout(timeout);
}
}, [dragDisabledMessage]);
return (
<div
className={className}
onDragStart={handleDragStart}
onDragEnter={handleDragEnter}
draggable={draggable}
onClick={onClick}
onDoubleClick={onDoubleClick}
onKeyPress={event => {
if (event.key === 'Enter') {
onClick?.(event);
}
}}
onContextMenu={onContextMenu}
data-testid={'draggable-commit'}>
<div className="commit-wide-drag-target" onDragEnter={handleDragEnter} />
{dragDisabledMessage != null ? (
<Tooltip trigger="manual" shouldShow title={dragDisabledMessage}>
{children}
</Tooltip>
) : (
children
)}
</div>
);
}
function hasUncommittedChanges(): boolean {
const changes = readAtom(uncommittedChangesWithPreviews);
return (
changes.filter(
commit => commit.status !== '?', // untracked files are ok
).length > 0
);
}
export function SuccessorInfoToDisplay({successorInfo}: {successorInfo: SuccessorInfo}) {
const successorType = successorInfo.type;
const inner: JSX.Element = {
pushrebase: <T>Landed as a newer commit</T>,
land: <T>Landed as a newer commit</T>,
amend: <T>Amended as a newer commit</T>,
rebase: <T>Rebased as a newer commit</T>,
split: <T>Split as a newer commit</T>,
fold: <T>Folded as a newer commit</T>,
histedit: <T>Histedited as a newer commit</T>,
}[successorType] ?? <T>Rewritten as a newer commit</T>;
const isSuccessorPublic = successorType === 'land' || successorType === 'pushrebase';
return (
<FlexRow style={{gap: 'var(--halfpad)'}}>
<HighlightCommitsWhileHovering toHighlight={[successorInfo.hash]}>
{inner}
</HighlightCommitsWhileHovering>
<EducationInfoTip>
<ObsoleteTip isSuccessorPublic={isSuccessorPublic} />
</EducationInfoTip>
</FlexRow>
);
}
function ObsoleteTipInner(props: {isSuccessorPublic?: boolean}) {
const tips: string[] = props.isSuccessorPublic
? [
t('Avoid editing (e.g., amend, rebase) this obsoleted commit. It cannot be landed again.'),
t(
'The new commit was landed in a public branch and became immutable. It cannot be edited or hidden.',
),
t('If you want to make changes, create a new commit.'),
]
: [
t(
'Avoid editing (e.g., amend, rebase) this obsoleted commit. You should use the new commit instead.',
),
t(
'If you do edit, there will be multiple new versions. They look like duplications and there is no easy way to de-duplicate (e.g. merge all edits back into one commit).',
),
t(
'To revert to this obsoleted commit, simply hide the new one. It will remove the "obsoleted" status.',
),
];
return (
<div style={{maxWidth: '60vw'}}>
<T>This commit is "obsoleted" because a newer version exists.</T>
<ul>
{tips.map((tip, i) => (
<li key={i}>{tip}</li>
))}
</ul>
</div>
);
}
const ObsoleteTip = React.memo(ObsoleteTipInner);