From 7bafeff946ed318325afbc4c659d82d195c6237a Mon Sep 17 00:00:00 2001 From: Jake Leventhal Date: Thu, 12 Nov 2026 09:21:59 -0500 Subject: [PATCH 01/24] feat(review): add missing Git and pull request review actions Consolidate the reviewed branch and follow-up fixes from #29412 before rebasing onto current main. Co-authored-by: maria-rcks --- .../t3reviewdiff/ReviewDiffCanvasDrawing.kt | 289 ++- .../t3reviewdiff/ReviewDiffCommentDrawing.kt | 97 + .../t3reviewdiff/ReviewDiffHeaderDrawing.kt | 115 ++ .../t3reviewdiff/ReviewDiffHunkDrawing.kt | 140 ++ .../t3reviewdiff/ReviewDiffLineRange.kt | 99 + .../t3reviewdiff/T3ReviewDiffModule.kt | 114 +- .../modules/t3reviewdiff/T3ReviewDiffView.kt | 453 +++-- .../t3reviewdiff/ReviewDiffCodeLayoutTest.kt | 39 + .../t3reviewdiff/ReviewDiffLineRangeTest.kt | 106 + .../ios/T3ReviewDiffModule.swift | 15 + .../t3-review-diff/ios/T3ReviewDiffView.swift | 370 +++- apps/mobile/src/Stack.tsx | 19 +- .../src/components/DiffDisclosureIcons.tsx | 50 + .../src/components/ui/AppSymbol.android.tsx | 17 +- apps/mobile/src/components/ui/AppSymbol.tsx | 3 + .../components/ui/SegmentedControl.types.ts | 6 +- apps/mobile/src/components/ui/Tabs.tsx | 102 + .../components/ui/segmentedControlColors.ts | 5 +- .../features/diffs/nativeReviewDiffSurface.ts | 30 +- .../src/features/files/FileTreeBrowser.tsx | 27 +- .../features/files/ThreadFilesRouteScreen.tsx | 73 +- .../files/thread-file-navigator-pane.tsx | 13 +- .../layout/AdaptiveWorkspaceLayout.tsx | 20 +- .../workspace/ThreadWorkspaceScreen.tsx | 244 +++ .../threadWorkspaceNavigationMemory.test.ts | 169 ++ .../threadWorkspaceNavigationMemory.ts | 108 + .../workspace/workspacePaneMemory.test.ts | 26 + .../layout/workspace/workspacePaneMemory.ts | 85 + .../PullRequestActivityFilters.tsx | 2 +- .../pull-requests/PullRequestAttachments.tsx | 164 ++ .../pull-requests/PullRequestCommentCard.tsx | 513 +++++ .../PullRequestCommentComposer.tsx | 110 + .../PullRequestCommentControls.tsx | 336 +++ .../pull-requests/PullRequestCommentForm.tsx | 71 + .../PullRequestCommentsSheet.tsx | 191 ++ .../pull-requests/PullRequestCommitPicker.tsx | 177 ++ .../PullRequestComposerNotice.tsx | 38 + .../pull-requests/PullRequestControls.tsx | 259 ++- .../pull-requests/PullRequestFilesSheet.tsx | 73 + .../PullRequestInlineCommentScreen.tsx | 297 ++- .../pull-requests/PullRequestMarkdown.tsx | 7 +- .../PullRequestMergeControls.tsx | 192 +- .../PullRequestPendingComment.tsx | 101 + .../pull-requests/PullRequestReactions.tsx | 2 +- .../pull-requests/PullRequestReviewSheet.tsx | 261 ++- .../pull-requests/PullRequestRouteScreen.tsx | 1798 ++++++++++++----- .../pull-requests/PullRequestSheetContent.tsx | 101 +- .../pull-requests/PullRequestTimeline.tsx | 370 ++-- .../pull-requests/composer-insert-notice.ts | 39 + .../guide/GuideChapterNavigation.tsx | 95 + .../pull-requests/guide/GuideFiles.tsx | 159 ++ .../guide/GuideGeneratingFiles.tsx | 64 + .../guide/GuideGeneratingHeading.tsx | 101 + .../pull-requests/guide/GuideNotice.tsx | 53 +- .../pull-requests/guide/GuideOutline.tsx | 208 +- .../pull-requests/guide/GuideViewOptions.tsx | 55 + .../guide/PullRequestGuideChapterScreen.tsx | 166 ++ .../guide/PullRequestGuideScreen.tsx | 338 +--- .../guide/ReviewGuideExcerpt.tsx | 141 -- .../guide/reviewGuideState.test.ts | 68 + .../pull-requests/guide/reviewGuideState.ts | 22 + .../pull-requests/pullRequestActions.test.ts | 15 +- .../pull-requests/pullRequestActions.ts | 10 + .../pullRequestAgentTasks.test.ts | 17 +- .../pull-requests/pullRequestAgentTasks.ts | 5 +- .../pullRequestDiffComments.test.ts | 11 + .../pull-requests/pullRequestDiffComments.ts | 35 +- .../pull-requests/pullRequestDiffPages.ts | 18 +- .../pullRequestFileChapters.test.ts | 59 + .../pull-requests/pullRequestFileChapters.ts | 20 + .../pullRequestFileFilters.test.ts | 38 +- .../pull-requests/pullRequestFileFilters.ts | 7 +- .../pullRequestMarkdownBadges.test.ts | 41 + .../pullRequestMarkdownBadges.ts | 37 + .../pullRequestReviewDrafts.test.ts | 34 +- .../pull-requests/pullRequestReviewDrafts.ts | 10 +- .../pull-requests/pullRequestViewMemory.ts | 15 + .../usePendingReviewCommentActions.ts | 104 + .../usePullRequestDescription.ts | 2 +- .../pull-requests/usePullRequestDiff.ts | 40 +- .../usePullRequestFilesViewed.ts | 113 +- .../usePullRequestMaintainerEdits.ts | 2 +- .../usePullRequestPermissions.ts | 3 +- .../usePullRequestReviewDraft.ts | 135 +- .../pull-requests/usePullRequestThreads.ts | 181 +- .../usePullRequestViewingPreferences.ts | 26 + .../useReviewAttachmentInsertion.ts | 34 + .../review/ReviewChapterNavigation.tsx | 100 + .../review/ReviewComparisonPicker.tsx | 68 + .../features/review/ReviewDisplayOptions.tsx | 78 + .../src/features/review/ReviewFileTree.tsx | 274 +++ .../src/features/review/ReviewRenamePath.tsx | 41 + .../src/features/review/ReviewSheet.tsx | 358 ++-- .../review/WorkingChangesLineActions.tsx | 95 + .../features/review/WorkingChangesReview.tsx | 1082 ++++++++++ .../features/review/WorkingChangesTree.tsx | 217 ++ .../review/nativeReviewDiffAdapter.test.ts | 23 + .../review/nativeReviewDiffAdapter.ts | 4 + .../src/features/review/reviewModel.test.ts | 24 + .../mobile/src/features/review/reviewModel.ts | 26 +- .../review/reviewPaneSelection.test.ts | 52 + .../features/review/reviewPaneSelection.ts | 25 + .../review/useDiffWhitespacePreference.ts | 15 + .../useReviewCommentSelectionController.ts | 112 +- .../src/features/review/useReviewDiffData.ts | 20 +- .../useReviewHeaderPresentation.android.ts | 14 +- .../useReviewHeaderPresentation.shared.tsx | 60 + .../review/useReviewHeaderPresentation.tsx | 60 +- .../features/review/useReviewSections.test.ts | 168 ++ .../src/features/review/useReviewSections.ts | 17 +- .../review/useWorkingChangesQuery.test.tsx | 98 + .../features/review/useWorkingChangesQuery.ts | 29 + .../review/workingChangesProjection.test.ts | 151 ++ .../review/workingChangesProjection.ts | 86 + .../review/workingChangesReviewMemory.ts | 52 + .../features/threads/ThreadGitControls.tsx | 298 +-- .../features/threads/git/GitOverviewSheet.tsx | 2 + .../src/features/threads/threadGitActions.tsx | 417 ++++ apps/mobile/src/lib/composerContext.ts | 26 + apps/mobile/src/lib/markdownDocument.ts | 5 + .../native/workspace-stack-projection.test.ts | 33 + .../src/persistence/mobile-preferences.ts | 15 +- apps/mobile/vite.config.ts | 1 + apps/server/src/auth/RpcAuthorization.test.ts | 71 +- apps/server/src/auth/RpcAuthorization.ts | 5 + apps/server/src/git/GitManager.test.ts | 42 +- apps/server/src/git/GitManager.ts | 92 +- apps/server/src/git/GitWorkflowService.ts | 4 + .../src/observability/RpcInstrumentation.ts | 7 + .../PullRequestReviewGuideService.test.ts | 125 +- .../PullRequestReviewGuideService.ts | 9 +- .../pullRequest/PullRequestService.test.ts | 214 +- .../src/pullRequest/PullRequestService.ts | 233 ++- .../pullRequestReviewGuideNormalize.test.ts | 159 +- .../pullRequestReviewGuideNormalize.ts | 136 +- apps/server/src/review/ReviewService.test.ts | 258 ++- apps/server/src/review/ReviewService.ts | 176 ++ apps/server/src/server.ts | 3 + apps/server/src/vcs/GitVcsDriver.ts | 3 +- apps/server/src/vcs/GitVcsDriverCore.test.ts | 177 +- apps/server/src/vcs/GitVcsDriverCore.ts | 74 +- apps/server/src/ws.ts | 22 +- apps/web/src/components/AnimatedWidth.tsx | 40 - .../src/components/DiffPanel.browser.test.tsx | 9 +- apps/web/src/components/DiffPanel.tsx | 68 +- apps/web/src/components/ReviewIcon.tsx | 2 + .../chat/ThreadDetailsPrRow.browser.test.tsx | 62 +- .../components/chat/ThreadDetailsPrRow.tsx | 47 +- .../components/diffs/AnnotatableCodeView.tsx | 171 +- .../diffs/DiffCommentAnnotation.tsx | 40 +- .../components/diffs/DiffDisplayControls.tsx | 108 + .../src/components/diffs/DiffFileRename.tsx | 62 + .../web/src/components/diffs/DiffFileTree.tsx | 121 +- apps/web/src/components/diffs/ReviewPath.tsx | 22 + .../components/diffs/StyledDiffCodeView.tsx | 45 +- .../components/diffs/WorkingChangesReview.tsx | 1060 ++++++++++ .../components/diffs/WorkingChangesTree.tsx | 339 ++++ .../components/diffs/diffFileTree.logic.ts | 20 + .../components/diffs/useReviewFilePatches.ts | 57 +- .../diffs/workingChangesState.test.ts | 440 ++++ .../components/diffs/workingChangesState.ts | 5 + .../src/components/files/FileBrowserPanel.tsx | 58 +- .../files/WorkspaceSourcePreview.tsx | 53 + .../preview/RightPanelResizeHandle.tsx | 14 +- .../PullRequestActionsMenu.browser.test.tsx | 6 - .../pullRequest/PullRequestActionsMenu.tsx | 58 +- .../PullRequestAdminMergeOption.tsx | 20 + .../pullRequest/PullRequestAttachments.tsx | 198 ++ .../PullRequestCodeTab.browser.test.tsx | 88 +- .../pullRequest/PullRequestCodeTab.tsx | 1367 ++++++++----- .../pullRequest/PullRequestCommentActions.tsx | 118 ++ .../pullRequest/PullRequestCommentForm.tsx | 16 +- .../PullRequestCommentsPopover.tsx | 243 +++ .../pullRequest/PullRequestComposer.tsx | 22 +- .../pullRequest/PullRequestDetailActions.tsx | 129 +- .../pullRequest/PullRequestDetailLayout.tsx | 3 +- .../pullRequest/PullRequestDetailPanel.tsx | 334 +-- .../PullRequestDiffUnavailableState.tsx | 62 - .../pullRequest/PullRequestGhosts.tsx | 21 +- .../PullRequestGuideTab.browser.test.tsx | 14 + .../pullRequest/PullRequestGuideTab.tsx | 128 +- .../pullRequest/PullRequestMergeControl.tsx | 126 ++ .../pullRequest/PullRequestReactions.tsx | 2 +- .../PullRequestResolveThreadButton.tsx | 2 +- .../PullRequestReviewAnnotation.tsx | 352 +++- .../PullRequestReviewForm.browser.test.tsx | 1 + .../pullRequest/PullRequestReviewForm.tsx | 56 +- .../pullRequest/PullRequestSpeedActions.tsx | 203 +- .../pullRequest/PullRequestSummaryTab.tsx | 2 +- .../PullRequestTimelineTab.browser.test.tsx | 16 +- .../pullRequest/PullRequestTimelineTab.tsx | 123 +- .../pullRequest/PullRequestTitleEditor.tsx | 2 +- .../pullRequest/ReviewChapterHeader.tsx | 127 ++ .../pullRequest/ReviewChapterRail.tsx | 173 ++ .../pullRequest/filesViewedStore.ts | 2 +- .../pullRequest/guide/GuideChapterPanel.tsx | 26 + .../pullRequest/guide/GuideExcerpt.tsx | 163 +- .../pullRequest/guide/GuideFileDiff.tsx | 16 +- .../pullRequest/guide/GuideNotes.tsx | 2 +- .../pullRequest/guide/GuideRail.tsx | 211 +- .../pullRequest/guide/GuideStop.tsx | 466 ++--- .../pullRequest/guide/GuideTour.tsx | 105 +- .../pullRequest/guide/guideDiffStyles.ts | 10 + .../pullRequestDetail.logic.test.ts | 158 +- .../pullRequest/pullRequestDetail.logic.ts | 98 +- .../pullRequestFileOrder.logic.test.ts | 199 +- .../pullRequest/pullRequestFileOrder.logic.ts | 196 +- .../pullRequestReviewStore.test.ts | 130 +- .../pullRequest/pullRequestReviewStore.ts | 131 +- .../useInlineActionConfirm.browser.test.tsx | 22 +- .../usePendingReviewCommentActions.ts | 86 + .../pullRequest/usePullRequestActions.ts | 12 +- ...usePullRequestFilesViewed.browser.test.tsx | 138 ++ .../pullRequest/usePullRequestFilesViewed.ts | 74 +- .../pullRequest/useReviewThreadActions.ts | 102 + apps/web/src/components/ui/input-group.tsx | 9 +- apps/web/src/components/ui/popover.tsx | 5 +- apps/web/src/diffPanelStore.test.ts | 48 +- apps/web/src/diffPanelStore.ts | 23 +- apps/web/src/index.css | 29 +- apps/web/src/lib/attachmentUploadQueue.ts | 39 +- apps/web/src/lib/diffFileContents.ts | 2 + apps/web/src/lib/diffRendering.test.ts | 52 + apps/web/src/lib/diffRendering.ts | 60 +- apps/web/src/lib/reviewLineStaging.test.ts | 234 +++ apps/web/src/pierre-tree-theme.ts | 16 +- docs/user/review.md | 23 + packages/client-runtime/package.json | 71 +- .../src/pullRequestMarkdown.test.ts | 13 + .../client-runtime/src/pullRequestMarkdown.ts | 2 +- .../client-runtime/src/reviewActivity.test.ts | 2 +- .../client-runtime/src/reviewActivity.ts | 5 +- .../src/reviewAttachments.test.ts | 139 ++ .../client-runtime/src/reviewAttachments.ts | 109 + .../src/reviewDiffContext.test.ts | 67 + .../client-runtime/src/reviewDiffContext.ts | 165 ++ .../client-runtime/src/reviewDiffMetadata.ts | 23 + .../src/reviewDiffWhitespace.ts | 56 + ...tEditing.test.ts => reviewEditing.test.ts} | 74 +- ...pullRequestEditing.ts => reviewEditing.ts} | 94 + .../src/reviewFileTreeSelection.test.ts | 110 + .../src/reviewFileTreeSelection.ts | 74 + .../src/reviewFileViewed.test.ts | 2 +- .../client-runtime/src/reviewFileViewed.ts | 8 + .../src/reviewGuideTour.test.ts | 44 + .../client-runtime/src/reviewGuideTour.ts | 11 + .../client-runtime/src/reviewLineStaging.ts | 152 ++ .../src/reviewMutationQueue.test.ts | 59 + .../client-runtime/src/reviewMutationQueue.ts | 60 + ...ctions.test.ts => reviewReactions.test.ts} | 5 +- ...RequestReactions.ts => reviewReactions.ts} | 0 .../src/reviewSelection.test.ts | 39 + .../client-runtime/src/reviewSelection.ts | 69 + packages/client-runtime/src/reviewThreads.ts | 100 + .../src/reviewWorkingChangesState.ts | 283 +++ .../src/reviewWorkspace.test.ts | 336 +++ .../client-runtime/src/reviewWorkspace.ts | 364 ++++ .../src/state/commandPermissions.test.ts | 80 + .../src/state/gitActions.test.ts | 9 + .../client-runtime/src/state/gitActions.ts | 11 + .../src/state/pullRequestResolution.test.ts | 276 +++ .../src/state/pullRequestResolution.ts | 137 ++ .../client-runtime/src/state/pullRequests.ts | 174 +- packages/client-runtime/src/state/review.ts | 26 + .../src/useReviewFileProgress.ts | 230 +++ .../contracts/src/clientRpcPermissions.ts | 17 + packages/contracts/src/pullRequest.ts | 83 +- .../contracts/src/pullRequestReviewGuide.ts | 4 + packages/contracts/src/review.ts | 38 +- packages/contracts/src/rpc.ts | 73 + packages/contracts/src/settings.ts | 15 + .../src/server/textGenerationPrompts.ts | 3 +- packages/shared/package.json | 6 +- packages/shared/src/changedFileKind.test.ts | 15 + .../src/reviewFileClassification.test.ts | 114 ++ .../shared/src/reviewFileClassification.ts | 58 + .../src/server/PullRequestProvider.ts | 31 + .../schema/github.graphql.ts | 145 ++ .../src/server/GitHubPullRequestApi.test.ts | 1151 ++++++++++- .../src/server/GitHubPullRequestApi.ts | 652 +++++- .../server/GitHubPullRequestProvider.test.ts | 45 +- .../src/server/GitHubPullRequestProvider.ts | 54 +- .../src/server/GitHubRest.test.ts | 82 +- .../src/server/GitHubRest.ts | 52 +- .../src/server/gitHubPullRequestJson.test.ts | 58 +- .../src/server/gitHubPullRequestJson.ts | 58 +- .../src/server/pullRequestBatches.graphql | 2 + .../src/server/pullRequestBatches.graphql.ts | 8 +- .../src/server/pullRequestMutations.graphql | 6 +- .../server/pullRequestMutations.graphql.ts | 8 +- .../src/server/pullRequestReads.graphql | 3 + .../src/server/pullRequestReads.graphql.ts | 11 +- .../src/server/pullRequestReviews.graphql | 93 +- .../src/server/pullRequestReviews.graphql.ts | 385 +++- pnpm-lock.yaml | 9 + scripts/review-native-startup.test.ts | 66 + 296 files changed, 27567 insertions(+), 5373 deletions(-) create mode 100644 apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCommentDrawing.kt create mode 100644 apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffHeaderDrawing.kt create mode 100644 apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffHunkDrawing.kt create mode 100644 apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffLineRange.kt create mode 100644 apps/mobile/modules/t3-review-diff/android/src/test/java/expo/modules/t3reviewdiff/ReviewDiffLineRangeTest.kt create mode 100644 apps/mobile/src/components/DiffDisclosureIcons.tsx create mode 100644 apps/mobile/src/components/ui/Tabs.tsx create mode 100644 apps/mobile/src/features/layout/workspace/ThreadWorkspaceScreen.tsx create mode 100644 apps/mobile/src/features/layout/workspace/threadWorkspaceNavigationMemory.test.ts create mode 100644 apps/mobile/src/features/layout/workspace/threadWorkspaceNavigationMemory.ts create mode 100644 apps/mobile/src/features/layout/workspace/workspacePaneMemory.test.ts create mode 100644 apps/mobile/src/features/layout/workspace/workspacePaneMemory.ts create mode 100644 apps/mobile/src/features/pull-requests/PullRequestAttachments.tsx create mode 100644 apps/mobile/src/features/pull-requests/PullRequestCommentCard.tsx create mode 100644 apps/mobile/src/features/pull-requests/PullRequestCommentComposer.tsx create mode 100644 apps/mobile/src/features/pull-requests/PullRequestCommentControls.tsx create mode 100644 apps/mobile/src/features/pull-requests/PullRequestCommentForm.tsx create mode 100644 apps/mobile/src/features/pull-requests/PullRequestCommentsSheet.tsx create mode 100644 apps/mobile/src/features/pull-requests/PullRequestCommitPicker.tsx create mode 100644 apps/mobile/src/features/pull-requests/PullRequestComposerNotice.tsx create mode 100644 apps/mobile/src/features/pull-requests/PullRequestFilesSheet.tsx create mode 100644 apps/mobile/src/features/pull-requests/PullRequestPendingComment.tsx create mode 100644 apps/mobile/src/features/pull-requests/composer-insert-notice.ts create mode 100644 apps/mobile/src/features/pull-requests/guide/GuideChapterNavigation.tsx create mode 100644 apps/mobile/src/features/pull-requests/guide/GuideFiles.tsx create mode 100644 apps/mobile/src/features/pull-requests/guide/GuideGeneratingFiles.tsx create mode 100644 apps/mobile/src/features/pull-requests/guide/GuideGeneratingHeading.tsx create mode 100644 apps/mobile/src/features/pull-requests/guide/GuideViewOptions.tsx create mode 100644 apps/mobile/src/features/pull-requests/guide/PullRequestGuideChapterScreen.tsx delete mode 100644 apps/mobile/src/features/pull-requests/guide/ReviewGuideExcerpt.tsx create mode 100644 apps/mobile/src/features/pull-requests/guide/reviewGuideState.test.ts create mode 100644 apps/mobile/src/features/pull-requests/pullRequestFileChapters.test.ts create mode 100644 apps/mobile/src/features/pull-requests/pullRequestFileChapters.ts create mode 100644 apps/mobile/src/features/pull-requests/pullRequestMarkdownBadges.test.ts create mode 100644 apps/mobile/src/features/pull-requests/pullRequestMarkdownBadges.ts create mode 100644 apps/mobile/src/features/pull-requests/pullRequestViewMemory.ts create mode 100644 apps/mobile/src/features/pull-requests/usePendingReviewCommentActions.ts create mode 100644 apps/mobile/src/features/pull-requests/usePullRequestViewingPreferences.ts create mode 100644 apps/mobile/src/features/pull-requests/useReviewAttachmentInsertion.ts create mode 100644 apps/mobile/src/features/review/ReviewChapterNavigation.tsx create mode 100644 apps/mobile/src/features/review/ReviewComparisonPicker.tsx create mode 100644 apps/mobile/src/features/review/ReviewDisplayOptions.tsx create mode 100644 apps/mobile/src/features/review/ReviewFileTree.tsx create mode 100644 apps/mobile/src/features/review/ReviewRenamePath.tsx create mode 100644 apps/mobile/src/features/review/WorkingChangesLineActions.tsx create mode 100644 apps/mobile/src/features/review/WorkingChangesReview.tsx create mode 100644 apps/mobile/src/features/review/WorkingChangesTree.tsx create mode 100644 apps/mobile/src/features/review/reviewPaneSelection.test.ts create mode 100644 apps/mobile/src/features/review/useDiffWhitespacePreference.ts create mode 100644 apps/mobile/src/features/review/useReviewHeaderPresentation.shared.tsx create mode 100644 apps/mobile/src/features/review/useReviewSections.test.ts create mode 100644 apps/mobile/src/features/review/useWorkingChangesQuery.test.tsx create mode 100644 apps/mobile/src/features/review/useWorkingChangesQuery.ts create mode 100644 apps/mobile/src/features/review/workingChangesProjection.test.ts create mode 100644 apps/mobile/src/features/review/workingChangesProjection.ts create mode 100644 apps/mobile/src/features/review/workingChangesReviewMemory.ts create mode 100644 apps/mobile/src/features/threads/threadGitActions.tsx delete mode 100644 apps/web/src/components/AnimatedWidth.tsx create mode 100644 apps/web/src/components/ReviewIcon.tsx create mode 100644 apps/web/src/components/diffs/DiffDisplayControls.tsx create mode 100644 apps/web/src/components/diffs/DiffFileRename.tsx create mode 100644 apps/web/src/components/diffs/ReviewPath.tsx create mode 100644 apps/web/src/components/diffs/WorkingChangesReview.tsx create mode 100644 apps/web/src/components/diffs/WorkingChangesTree.tsx create mode 100644 apps/web/src/components/diffs/workingChangesState.test.ts create mode 100644 apps/web/src/components/diffs/workingChangesState.ts create mode 100644 apps/web/src/components/files/WorkspaceSourcePreview.tsx create mode 100644 apps/web/src/components/pullRequest/PullRequestAdminMergeOption.tsx create mode 100644 apps/web/src/components/pullRequest/PullRequestAttachments.tsx create mode 100644 apps/web/src/components/pullRequest/PullRequestCommentActions.tsx create mode 100644 apps/web/src/components/pullRequest/PullRequestCommentsPopover.tsx delete mode 100644 apps/web/src/components/pullRequest/PullRequestDiffUnavailableState.tsx create mode 100644 apps/web/src/components/pullRequest/PullRequestMergeControl.tsx create mode 100644 apps/web/src/components/pullRequest/ReviewChapterHeader.tsx create mode 100644 apps/web/src/components/pullRequest/ReviewChapterRail.tsx create mode 100644 apps/web/src/components/pullRequest/guide/GuideChapterPanel.tsx create mode 100644 apps/web/src/components/pullRequest/guide/guideDiffStyles.ts create mode 100644 apps/web/src/components/pullRequest/usePendingReviewCommentActions.ts create mode 100644 apps/web/src/components/pullRequest/usePullRequestFilesViewed.browser.test.tsx create mode 100644 apps/web/src/components/pullRequest/useReviewThreadActions.ts create mode 100644 apps/web/src/lib/reviewLineStaging.test.ts create mode 100644 docs/user/review.md rename apps/mobile/src/features/pull-requests/pullRequestActivityFilter.test.ts => packages/client-runtime/src/reviewActivity.test.ts (98%) rename apps/mobile/src/features/pull-requests/pullRequestActivityFilter.ts => packages/client-runtime/src/reviewActivity.ts (95%) create mode 100644 packages/client-runtime/src/reviewAttachments.test.ts create mode 100644 packages/client-runtime/src/reviewAttachments.ts create mode 100644 packages/client-runtime/src/reviewDiffContext.test.ts create mode 100644 packages/client-runtime/src/reviewDiffContext.ts create mode 100644 packages/client-runtime/src/reviewDiffMetadata.ts create mode 100644 packages/client-runtime/src/reviewDiffWhitespace.ts rename packages/client-runtime/src/{pullRequestEditing.test.ts => reviewEditing.test.ts} (78%) rename packages/client-runtime/src/{pullRequestEditing.ts => reviewEditing.ts} (56%) create mode 100644 packages/client-runtime/src/reviewFileTreeSelection.test.ts create mode 100644 packages/client-runtime/src/reviewFileTreeSelection.ts rename apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.test.ts => packages/client-runtime/src/reviewFileViewed.test.ts (98%) rename apps/web/src/components/pullRequest/pullRequestFilesViewed.logic.ts => packages/client-runtime/src/reviewFileViewed.ts (91%) create mode 100644 packages/client-runtime/src/reviewLineStaging.ts create mode 100644 packages/client-runtime/src/reviewMutationQueue.test.ts create mode 100644 packages/client-runtime/src/reviewMutationQueue.ts rename packages/client-runtime/src/{pullRequestReactions.test.ts => reviewReactions.test.ts} (96%) rename packages/client-runtime/src/{pullRequestReactions.ts => reviewReactions.ts} (100%) create mode 100644 packages/client-runtime/src/reviewSelection.test.ts create mode 100644 packages/client-runtime/src/reviewSelection.ts create mode 100644 packages/client-runtime/src/reviewThreads.ts create mode 100644 packages/client-runtime/src/reviewWorkingChangesState.ts create mode 100644 packages/client-runtime/src/reviewWorkspace.test.ts create mode 100644 packages/client-runtime/src/reviewWorkspace.ts create mode 100644 packages/client-runtime/src/state/pullRequestResolution.test.ts create mode 100644 packages/client-runtime/src/state/pullRequestResolution.ts create mode 100644 packages/client-runtime/src/useReviewFileProgress.ts create mode 100644 packages/shared/src/reviewFileClassification.test.ts create mode 100644 packages/shared/src/reviewFileClassification.ts create mode 100644 scripts/review-native-startup.test.ts diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt index 2f1e4d9fd4a43..51c5c9e8bac85 100644 --- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt @@ -15,7 +15,7 @@ import kotlin.math.max import kotlin.math.min internal class ReviewDiffCanvasDrawing(context: Context) { - private val density = context.resources.displayMetrics.density + val density = context.resources.displayMetrics.density var theme: DiffTheme = DiffTheme.fallback("light") val backgroundPaint = Paint() @@ -70,90 +70,186 @@ internal class ReviewDiffCanvasDrawing(context: Context) { ) } - fun drawDisclosureChevron( + fun drawFileHeader( canvas: Canvas, + row: DiffRow, rect: RectF, - color: Int, - collapsed: Boolean + style: DiffStyle, + state: FileHeaderDrawingState + ) { + val top = rect.top.toInt() + val bottom = rect.bottom.toInt() + val width = rect.width().toInt() + backgroundPaint.color = theme.headerBackground + canvas.drawRect(rect, backgroundPaint) + + val chevronRect = fileHeaderChevronRect(top, bottom, style) + val iconRect = fileHeaderIconRect(top, bottom, style) + val checkboxRect = fileHeaderCheckboxRect(top, bottom, width, style) + drawDisclosureChevron( + canvas, + chevronRect, + theme.mutedText, + collapsed = state.collapsed, + ) + drawFileIcon(canvas, iconRect, row.changeType) + if (state.showViewedCheckbox) { + val saved = canvas.saveLayerAlpha(checkboxRect, if (state.viewedCheckboxEnabled) 255 else 102) + drawViewedCheckbox( + canvas, + checkboxRect, + state.viewed, + ) + canvas.restoreToCount(saved) + } + + configureUiPaint( + paint = uiPaint, + color = theme.deleteText, + size = style.fileHeaderMetaFontSizePx, + weight = style.fileHeaderMetaFontWeight, + ) + val deleteText = "-${row.deletions}" + val deleteWidth = uiPaint.measureText(deleteText) + val addText = "+${row.additions}" + val addWidth = uiPaint.measureText(addText) + val countGap = 4f * density + val countsRight = if (row.fileAction != null) { + width - 110f * density + } else if (state.showViewedCheckbox) { + checkboxRect.left - 10f * density + } else { + width - 16f * density + } + val countsX = countsRight - deleteWidth - countGap - addWidth + val baseline = centeredBaseline(top, bottom, uiPaint) + canvas.drawText(deleteText, countsX, baseline, uiPaint) + uiPaint.color = theme.addText + canvas.drawText(addText, countsX + deleteWidth + countGap, baseline, uiPaint) + + val pathLayout = fileHeaderPathLayout(row, iconRect, countsX, style) + val maxPathOffset = maxHeaderPathOffset(pathLayout) + val pathOffset = state.pathOffset + .coerceIn(0, maxPathOffset) + drawFileHeaderPath(canvas, row, pathLayout, pathOffset, maxPathOffset) + drawFileHeaderAction(canvas, row, rect) + borderPaint.color = theme.border + borderPaint.strokeWidth = density + canvas.drawLine(0f, bottom - density / 2f, width.toFloat(), bottom - density / 2f, borderPaint) + } + + private fun drawFileHeaderPath( + canvas: Canvas, + row: DiffRow, + pathLayout: FileHeaderPathLayout, + pathOffset: Int, + maxPathOffset: Int ) { - borderPaint.style = Paint.Style.STROKE - borderPaint.color = color - borderPaint.strokeWidth = 2f * density - borderPaint.strokeCap = Paint.Cap.ROUND - borderPaint.strokeJoin = Paint.Join.ROUND - val path = Path() - if (collapsed) { - path.moveTo(rect.left + rect.width() * 0.4f, rect.top + rect.height() * 0.28f) - path.lineTo(rect.left + rect.width() * 0.6f, rect.centerY()) - path.lineTo(rect.left + rect.width() * 0.4f, rect.bottom - rect.height() * 0.28f) + canvas.save() + canvas.clipRect(pathLayout.rect) + val metrics = uiPaint.fontMetrics + val baseline = pathLayout.rect.centerY() - (metrics.ascent + metrics.descent) / 2f + if (row.renameSegments.isNotEmpty()) { + drawRenamePath(canvas, row, pathLayout, pathOffset, baseline) } else { - path.moveTo(rect.left + rect.width() * 0.28f, rect.top + rect.height() * 0.42f) - path.lineTo(rect.centerX(), rect.top + rect.height() * 0.62f) - path.lineTo(rect.right - rect.width() * 0.28f, rect.top + rect.height() * 0.42f) + canvas.drawText(pathLayout.displayPath, pathLayout.rect.left - pathOffset, baseline, uiPaint) } - canvas.drawPath(path, borderPaint) - borderPaint.style = Paint.Style.FILL + canvas.restore() + drawFileHeaderPathScrollFades(canvas, pathLayout.rect, pathOffset, maxPathOffset) } - fun drawFileIcon(canvas: Canvas, rect: RectF, changeType: String) { - val color = when (changeType) { - "new" -> theme.addText - "deleted" -> theme.deleteText - else -> theme.hunkText + private fun drawRenamePath( + canvas: Canvas, + row: DiffRow, + pathLayout: FileHeaderPathLayout, + pathOffset: Int, + baseline: Float + ) { + var x = pathLayout.rect.left - pathOffset + for (segment in row.renameSegments) { + val segmentWidth = uiPaint.measureText(segment.text) + if (segment.kind == "removed" || segment.kind == "added") { + backgroundPaint.color = + if (segment.kind == "removed") theme.deleteBackground else theme.addBackground + canvas.drawRect( + x, + pathLayout.rect.top, + x + segmentWidth, + pathLayout.rect.bottom, + backgroundPaint + ) + } + uiPaint.color = if (segment.kind == "context") theme.mutedText else theme.text + canvas.drawText(segment.text, x, baseline, uiPaint) + x += segmentWidth } - borderPaint.style = Paint.Style.STROKE - borderPaint.color = color - borderPaint.strokeWidth = 2f * density - canvas.drawRoundRect(rect, 6f * density, 6f * density, borderPaint) + } - if (changeType == "rename-pure" || changeType == "rename-changed" || changeType == "renamed") { - drawRenameChevronIcon(canvas, rect, color) - } else { - backgroundPaint.color = color - canvas.drawCircle(rect.centerX(), rect.centerY(), 3f * density, backgroundPaint) + private fun drawFileHeaderAction(canvas: Canvas, row: DiffRow, rect: RectF) { + val top = rect.top.toInt() + val bottom = rect.bottom.toInt() + val width = rect.width().toInt() + row.fileAction?.let { label -> + val rect = RectF( + width - 96 * density, + top + 7 * density, + width - 10 * density, + bottom - 7 * density + ) + backgroundPaint.color = theme.border + backgroundPaint.style = Paint.Style.STROKE + backgroundPaint.strokeWidth = density + canvas.drawRoundRect(rect, 6 * density, 6 * density, backgroundPaint) + backgroundPaint.style = Paint.Style.FILL + configureUiPaint( + uiPaint, + if (row.fileActionDisabled) theme.mutedText else theme.hunkText, + 12 * density, + "semibold" + ) + canvas.drawText( + label, + rect.centerX() - uiPaint.measureText(label) / 2, + centeredBaseline(top, bottom, uiPaint), + uiPaint + ) } - borderPaint.style = Paint.Style.FILL } - fun drawViewedCheckbox(canvas: Canvas, rect: RectF, checked: Boolean) { - if (checked) { - backgroundPaint.color = theme.hunkText - canvas.drawRoundRect(rect, 6f * density, 6f * density, backgroundPaint) - } - borderPaint.style = Paint.Style.STROKE - borderPaint.color = if (checked) theme.hunkText else theme.mutedText - borderPaint.strokeWidth = 1.8f * density - canvas.drawRoundRect(rect, 6f * density, 6f * density, borderPaint) - if (checked) { - borderPaint.color = theme.background - borderPaint.strokeWidth = 2f * density - borderPaint.strokeCap = Paint.Cap.ROUND - borderPaint.strokeJoin = Paint.Join.ROUND - val path = Path().apply { - moveTo(rect.left + rect.width() * 0.28f, rect.centerY()) - lineTo(rect.left + rect.width() * 0.44f, rect.bottom - rect.height() * 0.3f) - lineTo(rect.right - rect.width() * 0.25f, rect.top + rect.height() * 0.3f) - } - canvas.drawPath(path, borderPaint) + fun fileHeaderPathLayout( + row: DiffRow, + iconRect: RectF, + countsX: Float, + style: DiffStyle + ): FileHeaderPathLayout { + configureUiPaint( + paint = uiPaint, + color = theme.text, + size = style.fileHeaderFontSizePx, + weight = style.fileHeaderFontWeight, + ) + val pathX = iconRect.right + 10f * density + val pathWidth = max(24f * density, countsX - pathX - 12f * density) + val centerY = iconRect.centerY() + val displayPath = if (row.renameSegments.isNotEmpty()) { + row.renameSegments.joinToString("") { it.text } + } else { + row.filePath } - borderPaint.style = Paint.Style.FILL - } - - fun drawNoticeIcon(canvas: Canvas, rect: RectF, color: Int) { - borderPaint.style = Paint.Style.STROKE - borderPaint.color = color - borderPaint.strokeWidth = 1.7f * density - borderPaint.strokeCap = Paint.Cap.ROUND - canvas.drawOval(rect, borderPaint) - canvas.drawLine( - rect.centerX(), - rect.top + rect.height() * 0.3f, - rect.centerX(), - rect.top + rect.height() * 0.58f, - borderPaint, + return FileHeaderPathLayout( + displayPath = displayPath, + rect = RectF(pathX, centerY - 10f * density, pathX + pathWidth, centerY + 10f * density), ) - borderPaint.style = Paint.Style.FILL - canvas.drawCircle(rect.centerX(), rect.bottom - rect.height() * 0.24f, density, borderPaint) + } + + private fun maxHeaderPathOffset(layout: FileHeaderPathLayout): Int = max( + 0, + ceil(uiPaint.measureText(layout.displayPath) - layout.rect.width()).toInt(), + ) + + private fun centeredBaseline(top: Int, bottom: Int, paint: Paint): Float { + val metrics = paint.fontMetrics + return (top + bottom) / 2f - (metrics.ascent + metrics.descent) / 2f } fun configureUiPaint(paint: Paint, color: Int, size: Float, weight: String) { @@ -488,25 +584,6 @@ internal class ReviewDiffCanvasDrawing(context: Context) { } } - private fun drawRenameChevronIcon(canvas: Canvas, rect: RectF, color: Int) { - borderPaint.style = Paint.Style.STROKE - borderPaint.color = color - borderPaint.strokeWidth = 1.8f * density - borderPaint.strokeCap = Paint.Cap.ROUND - borderPaint.strokeJoin = Paint.Join.ROUND - val chevronWidth = 3.6f * density - val chevronHeight = 8f * density - val gap = 2.4f * density - val startX = rect.centerX() - (chevronWidth * 2f + gap) / 2f - val path = Path() - for (x in listOf(startX, startX + chevronWidth + gap)) { - path.moveTo(x, rect.centerY() - chevronHeight / 2f) - path.lineTo(x + chevronWidth, rect.centerY()) - path.lineTo(x, rect.centerY() + chevronHeight / 2f) - } - canvas.drawPath(path, borderPaint) - } - private fun configureTextPaint(paint: Paint, color: Int, size: Float) { paint.textSize = size paint.color = color @@ -554,23 +631,15 @@ private object ReviewDiffTypefaces { } } -/** Splits color runs where a cut line's note starts; the flag marks the note's runs. */ -private fun splitAtNote(runs: List, noteStart: Int?): List> { - if (noteStart == null) return runs.map { it to false } - return buildList { - var offset = 0 - for (run in runs) { - val end = offset + run.content.length - when { - end <= noteStart -> add(run to false) - offset >= noteStart -> add(run to true) - else -> { - val cut = noteStart - offset - add(run.copy(content = run.content.substring(0, cut)) to false) - add(run.copy(content = run.content.substring(cut)) to true) - } - } - offset = end - } - } -} +internal data class FileHeaderDrawingState( + val collapsed: Boolean, + val viewed: Boolean, + val showViewedCheckbox: Boolean, + val viewedCheckboxEnabled: Boolean, + val pathOffset: Int +) + +internal data class FileHeaderPathLayout( + val displayPath: String, + val rect: RectF +) diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCommentDrawing.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCommentDrawing.kt new file mode 100644 index 0000000000000..169c796ea766b --- /dev/null +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCommentDrawing.kt @@ -0,0 +1,97 @@ +package expo.modules.t3reviewdiff + +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.graphics.RectF + +internal fun ReviewDiffCanvasDrawing.drawCommentRow( + canvas: Canvas, + row: DiffRow, + rect: RectF, + style: DiffStyle, + collapsed: Boolean +) { + val top = rect.top.toInt() + val bottom = rect.bottom.toInt() + val width = rect.width().toInt() + backgroundPaint.color = theme.background + canvas.drawRect(rect, backgroundPaint) + val cardRect = RectF( + 8f * density, + top + 5f * density, + width - 8f * density, + bottom - 5f * density, + ) + backgroundPaint.color = theme.headerBackground + canvas.drawRoundRect(cardRect, 10f * density, 10f * density, backgroundPaint) + borderPaint.style = Paint.Style.STROKE + borderPaint.color = commentColorAlpha(theme.border, 217) + borderPaint.strokeWidth = density + canvas.drawRoundRect(cardRect, 10f * density, 10f * density, borderPaint) + borderPaint.style = Paint.Style.FILL + + val chevronRect = RectF( + cardRect.left + 10f * density, + cardRect.top + 11f * density, + cardRect.left + 26f * density, + cardRect.top + 27f * density, + ) + drawDisclosureChevron(canvas, chevronRect, theme.mutedText, collapsed) + configureUiPaint( + paint = textPaint, + color = theme.mutedText, + size = style.fileHeaderSubtextFontSizePx, + weight = style.fileHeaderSubtextFontWeight, + ) + val title = + row.commentResolvedSummary ?: "Comment on ${row.commentRangeLabel.ifEmpty { "line" }}" + val titleRight = cardRect.right - (if (row.commentPending) 98f else 20f) * density + canvas.drawText( + ellipsizeDiffText(title, textPaint, titleRight - chevronRect.right), + chevronRect.right + 10f * density, + cardRect.top + 22f * density, + textPaint, + ) + if (row.commentPending) drawCommentPendingBadge(canvas, cardRect) + if (!collapsed) { + textPaint.color = theme.text + val bodyX = cardRect.left + 18f * density + canvas.drawText( + ellipsizeDiffText( + row.commentText.ifEmpty { "Comment" }, + textPaint, + cardRect.right - bodyX - 18f * density + ), + bodyX, + cardRect.top + 58f * density, + textPaint, + ) + } +} + +private fun ReviewDiffCanvasDrawing.drawCommentPendingBadge(canvas: Canvas, cardRect: RectF) { + val badge = RectF( + cardRect.right - 88f * density, + cardRect.top + 7f * density, + cardRect.right - 10f * density, + cardRect.top + 31f * density + ) + val amber = Color.rgb(217, 119, 6) + backgroundPaint.color = commentColorAlpha(amber, 35) + canvas.drawRoundRect(badge, 5f * density, 5f * density, backgroundPaint) + borderPaint.color = amber + borderPaint.style = Paint.Style.STROKE + borderPaint.strokeWidth = density + val cx = badge.left + 12f * density + val cy = badge.top + 12f * density + canvas.drawCircle(cx, cy, 6f * density, borderPaint) + canvas.drawLine(cx, cy - 3f * density, cx, cy, borderPaint) + canvas.drawLine(cx, cy, cx + 3f * density, cy + density, borderPaint) + borderPaint.style = Paint.Style.FILL + textPaint.color = amber + canvas.drawText("Pending", badge.left + 23f * density, badge.top + 17f * density, textPaint) +} + +private fun commentColorAlpha(color: Int, alpha: Int): Int = + Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color)) diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffHeaderDrawing.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffHeaderDrawing.kt new file mode 100644 index 0000000000000..5778ddce2aabb --- /dev/null +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffHeaderDrawing.kt @@ -0,0 +1,115 @@ +package expo.modules.t3reviewdiff + +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.Path +import android.graphics.RectF + +internal fun ReviewDiffCanvasDrawing.drawDisclosureChevron( + canvas: Canvas, + rect: RectF, + color: Int, + collapsed: Boolean +) { + borderPaint.style = Paint.Style.STROKE + borderPaint.color = color + borderPaint.strokeWidth = 2f * density + borderPaint.strokeCap = Paint.Cap.ROUND + borderPaint.strokeJoin = Paint.Join.ROUND + val path = Path() + if (collapsed) { + path.moveTo(rect.left + rect.width() * 0.4f, rect.top + rect.height() * 0.28f) + path.lineTo(rect.left + rect.width() * 0.6f, rect.centerY()) + path.lineTo(rect.left + rect.width() * 0.4f, rect.bottom - rect.height() * 0.28f) + } else { + path.moveTo(rect.left + rect.width() * 0.28f, rect.top + rect.height() * 0.42f) + path.lineTo(rect.centerX(), rect.top + rect.height() * 0.62f) + path.lineTo(rect.right - rect.width() * 0.28f, rect.top + rect.height() * 0.42f) + } + canvas.drawPath(path, borderPaint) + borderPaint.style = Paint.Style.FILL +} + +internal fun ReviewDiffCanvasDrawing.drawFileIcon(canvas: Canvas, rect: RectF, changeType: String) { + val color = when (changeType) { + "new" -> theme.addText + "deleted" -> theme.deleteText + else -> theme.hunkText + } + borderPaint.style = Paint.Style.STROKE + borderPaint.color = color + borderPaint.strokeWidth = 2f * density + canvas.drawRoundRect(rect, 6f * density, 6f * density, borderPaint) + + if (changeType == "rename-pure" || changeType == "rename-changed" || changeType == "renamed") { + drawRenameChevronIcon(canvas, rect, color) + } else { + backgroundPaint.color = color + canvas.drawCircle(rect.centerX(), rect.centerY(), 3f * density, backgroundPaint) + } + borderPaint.style = Paint.Style.FILL +} + +internal fun ReviewDiffCanvasDrawing.drawViewedCheckbox( + canvas: Canvas, + rect: RectF, + checked: Boolean +) { + if (checked) { + backgroundPaint.color = theme.hunkText + canvas.drawRoundRect(rect, 6f * density, 6f * density, backgroundPaint) + } + borderPaint.style = Paint.Style.STROKE + borderPaint.color = if (checked) theme.hunkText else theme.mutedText + borderPaint.strokeWidth = 1.8f * density + canvas.drawRoundRect(rect, 6f * density, 6f * density, borderPaint) + if (checked) { + borderPaint.color = theme.background + borderPaint.strokeWidth = 2f * density + borderPaint.strokeCap = Paint.Cap.ROUND + borderPaint.strokeJoin = Paint.Join.ROUND + val path = Path().apply { + moveTo(rect.left + rect.width() * 0.28f, rect.centerY()) + lineTo(rect.left + rect.width() * 0.44f, rect.bottom - rect.height() * 0.3f) + lineTo(rect.right - rect.width() * 0.25f, rect.top + rect.height() * 0.3f) + } + canvas.drawPath(path, borderPaint) + } + borderPaint.style = Paint.Style.FILL +} + +internal fun ReviewDiffCanvasDrawing.drawNoticeIcon(canvas: Canvas, rect: RectF, color: Int) { + borderPaint.style = Paint.Style.STROKE + borderPaint.color = color + borderPaint.strokeWidth = 1.7f * density + borderPaint.strokeCap = Paint.Cap.ROUND + canvas.drawOval(rect, borderPaint) + canvas.drawLine( + rect.centerX(), + rect.top + rect.height() * 0.3f, + rect.centerX(), + rect.top + rect.height() * 0.58f, + borderPaint, + ) + borderPaint.style = Paint.Style.FILL + canvas.drawCircle(rect.centerX(), rect.bottom - rect.height() * 0.24f, density, borderPaint) +} + +private fun ReviewDiffCanvasDrawing.drawRenameChevronIcon(canvas: Canvas, rect: RectF, color: Int) { + borderPaint.style = Paint.Style.STROKE + borderPaint.color = color + borderPaint.strokeWidth = 1.8f * density + borderPaint.strokeCap = Paint.Cap.ROUND + borderPaint.strokeJoin = Paint.Join.ROUND + val chevronWidth = 3.6f * density + val chevronHeight = 8f * density + val gap = 2.4f * density + val startX = rect.centerX() - (chevronWidth * 2f + gap) / 2f + val path = Path() + for (x in listOf(startX, startX + chevronWidth + gap)) { + path.moveTo(x, rect.centerY() - chevronHeight / 2f) + path.lineTo(x + chevronWidth, rect.centerY()) + path.lineTo(x, rect.centerY() + chevronHeight / 2f) + } + canvas.drawPath(path, borderPaint) +} diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffHunkDrawing.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffHunkDrawing.kt new file mode 100644 index 0000000000000..bf5e7a133536c --- /dev/null +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffHunkDrawing.kt @@ -0,0 +1,140 @@ +package expo.modules.t3reviewdiff + +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.RectF +import kotlin.math.max + +internal fun ReviewDiffCanvasDrawing.drawHunkRow( + canvas: Canvas, + row: DiffRow, + rect: RectF, + style: DiffStyle, + horizontalOffset: Int +) { + val top = rect.top.toInt() + val bottom = rect.bottom.toInt() + val width = rect.width().toInt() + backgroundPaint.color = theme.hunkBackground + canvas.drawRect(rect, backgroundPaint) + configureMonospacePaint( + color = theme.hunkText, + size = style.hunkFontSizePx, + weight = style.hunkFontWeight, + ) + canvas.save() + if (row.hunkAction != null) { + canvas.clipRect( + 0f, + top.toFloat(), + width - (if (row.hunkRevertAction) 224 else 112) * density, + bottom.toFloat() + ) + } + val gutterEnd = style.changeBarWidthPx + style.gutterWidthPx + val codeX = gutterEnd + style.codePaddingPx - horizontalOffset + canvas.save() + canvas.clipRect(gutterEnd, top.toFloat(), width.toFloat(), bottom.toFloat()) + canvas.drawText( + row.text.ifEmpty { row.content }, + codeX, + centeredBaseline(top, bottom, textPaint), + textPaint, + ) + canvas.restore() + canvas.restore() + row.hunkAction?.let { label -> + drawHunkActionButton( + canvas, + label, + RectF(width - 106 * density, top + 6 * density, width - 6 * density, bottom - 6 * density), + if (row.hunkActionDisabled) theme.mutedText else theme.hunkText, + ) + } + if (row.hunkRevertAction) { + drawHunkActionButton( + canvas, + "Revert hunk", + RectF( + width - 218 * density, + top + 6 * density, + width - 118 * density, + bottom - 6 * density + ), + if (row.hunkRevertActionDisabled) theme.mutedText else theme.deleteText, + ) + } +} + +internal fun ReviewDiffCanvasDrawing.drawNoticeRow( + canvas: Canvas, + row: DiffRow, + rect: RectF, + style: DiffStyle +) { + val top = rect.top.toInt() + val bottom = rect.bottom.toInt() + val width = rect.width().toInt() + backgroundPaint.color = theme.background + canvas.drawRect(rect, backgroundPaint) + val iconSize = 16f * density + val iconRect = RectF( + style.fileHeaderHorizontalPaddingPx + 2f * density, + (top + bottom - iconSize) / 2f, + style.fileHeaderHorizontalPaddingPx + 2f * density + iconSize, + (top + bottom + iconSize) / 2f, + ) + drawNoticeIcon(canvas, iconRect, theme.mutedText) + configureUiPaint( + paint = textPaint, + color = theme.mutedText, + size = style.fileHeaderSubtextFontSizePx, + weight = style.fileHeaderSubtextFontWeight, + ) + val textX = iconRect.right + 10f * density + canvas.drawText( + ellipsizeDiffText(row.text, textPaint, width - textX - style.fileHeaderHorizontalPaddingPx), + textX, + centeredBaseline(top, bottom, textPaint), + textPaint, + ) + borderPaint.color = theme.border + borderPaint.strokeWidth = density + canvas.drawLine(0f, bottom - density / 2f, width.toFloat(), bottom - density / 2f, borderPaint) +} + +private fun ReviewDiffCanvasDrawing.drawHunkActionButton( + canvas: Canvas, + label: String, + rect: RectF, + color: Int +) { + backgroundPaint.color = theme.headerBackground + canvas.drawRoundRect(rect, 6 * density, 6 * density, backgroundPaint) + configureUiPaint(uiPaint, color, 13 * density, "semibold") + val metrics = uiPaint.fontMetrics + canvas.drawText( + label, + rect.centerX() - uiPaint.measureText(label) / 2, + rect.centerY() - (metrics.ascent + metrics.descent) / 2f, + uiPaint + ) +} + +private fun centeredBaseline(top: Int, bottom: Int, paint: Paint): Float { + val metrics = paint.fontMetrics + return (top + bottom) / 2f - (metrics.ascent + metrics.descent) / 2f +} + +internal fun ellipsizeDiffText(value: String, paint: Paint, width: Float): String { + if (paint.measureText(value) <= width) return value + val suffix = "..." + val available = max(0f, width - paint.measureText(suffix)) + var end = paint.breakText(value, true, available, null) + if ( + end > 0 && end < value.length && Character.isSurrogatePair(value[end - 1], value[end]) + ) { + end -= 1 + } + return value.substring(0, end) + suffix +} diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffLineRange.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffLineRange.kt new file mode 100644 index 0000000000000..46333705780ff --- /dev/null +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffLineRange.kt @@ -0,0 +1,99 @@ +package expo.modules.t3reviewdiff + +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.min + +/** A native selection stays within its file while its handles cross or skip hunk headers. */ +internal class ReviewDiffLineRange { + var startIndex: Int? = null + private set + var endIndex: Int? = null + private set + var isDragging = false + var selectedRowIds: Set = emptySet() + private set + private var lineIndices = emptyList() + + fun begin(index: Int, rows: List): Boolean { + if (index !in rows.indices) return false + val fileId = rows[index].resolvedFileId + lineIndices = rows.indices.filter { + rows[it].kind == "line" && rows[it].resolvedFileId == fileId + } + isDragging = true + return true + } + + fun dragHandle(movingStart: Boolean): Boolean { + val start = startIndex + val end = endIndex + if (start == null || end == null) return false + startIndex = if (movingStart) max(start, end) else min(start, end) + endIndex = if (movingStart) min(start, end) else max(start, end) + isDragging = true + return true + } + + fun update(start: Int, end: Int, rows: List): Pair? { + if (start !in rows.indices || end !in rows.indices) return null + val validEnd = rows[end].kind == "line" && + rows[start].resolvedFileId == rows[end].resolvedFileId + return if (!validEnd || (startIndex == start && endIndex == end)) { + null + } else { + startIndex = start + endIndex = end + val first = min(start, end) + val last = max(start, end) + selectedRowIds = lineIndices.asSequence() + .filter { it in first..last }.map { rows[it].id }.toSet() + rows[first].id to rows[last].id + } + } + + fun nearestLine(index: Int): Int { + if (lineIndices.isEmpty()) return index + val target = index.coerceIn(lineIndices.first(), lineIndices.last()) + val at = lineIndices.binarySearch(target) + return lineIndices[if (at >= 0) at else (-at - 1).coerceAtMost(lineIndices.lastIndex)] + } + + fun clear() { + isDragging = false + startIndex = null + endIndex = null + lineIndices = emptyList() + selectedRowIds = emptySet() + } + + fun centers( + rows: List, + rowOffsets: IntArray, + verticalOffset: Int, + x: Float + ): Pair, Pair>? = startIndex?.let { start -> + endIndex?.let { end -> + if (start in rows.indices && end in rows.indices) { + val bottomIndex = (max(start, end) + 1).coerceAtMost(rowOffsets.lastIndex) + Pair(x, (rowOffsets[min(start, end)] - verticalOffset).toFloat()) to + Pair(x, (rowOffsets[bottomIndex] - verticalOffset).toFloat()) + } else { + null + } + } + } + + fun handleAt( + x: Float, + y: Float, + radius: Float, + centers: Pair, Pair>? + ): Boolean? = centers?.let { (start, end) -> + when { + abs(x - start.first) <= radius && abs(y - start.second) <= radius -> true + abs(x - end.first) <= radius && abs(y - end.second) <= radius -> false + else -> null + } + } +} diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.kt index 03609e3658e84..ed04157cf7907 100644 --- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.kt +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.kt @@ -3,6 +3,7 @@ package expo.modules.t3reviewdiff import expo.modules.kotlin.Promise import expo.modules.kotlin.modules.Module import expo.modules.kotlin.modules.ModuleDefinition +import expo.modules.kotlin.views.ViewDefinitionBuilder private val REVIEW_DIFF_EVENTS = arrayOf( "onDebug", @@ -19,52 +20,19 @@ class T3ReviewDiffModule : Module() { Name("T3ReviewDiffSurface") View(T3ReviewDiffView::class) { - Prop("tokensResetKey") { view: T3ReviewDiffView, tokensResetKey: String -> - view.setTokensResetKey(tokensResetKey) - } - Prop("contentResetKey") { view: T3ReviewDiffView, contentResetKey: String -> - view.setContentResetKey(contentResetKey) - } - Prop("collapsedFileIdsJson") { view: T3ReviewDiffView, collapsedFileIdsJson: String -> - view.setCollapsedFileIdsJson(collapsedFileIdsJson) - } - Prop("viewedFileIdsJson") { view: T3ReviewDiffView, viewedFileIdsJson: String -> - view.setViewedFileIdsJson(viewedFileIdsJson) - } - Prop("selectedRowIdsJson") { view: T3ReviewDiffView, selectedRowIdsJson: String -> - view.setSelectedRowIdsJson(selectedRowIdsJson) - } - Prop("collapsedCommentIdsJson") { view: T3ReviewDiffView, collapsedCommentIdsJson: String -> - view.setCollapsedCommentIdsJson(collapsedCommentIdsJson) - } - Prop("appearanceScheme") { view: T3ReviewDiffView, appearanceScheme: String -> - view.setAppearanceScheme(appearanceScheme) - } - Prop("themeJson") { view: T3ReviewDiffView, themeJson: String -> - view.setThemeJson(themeJson) - } - Prop("styleJson") { view: T3ReviewDiffView, styleJson: String -> - view.setStyleJson(styleJson) - } - Prop("rowHeight") { view: T3ReviewDiffView, rowHeight: Double -> - view.setRowHeight(rowHeight.toFloat()) - } - // Accept the shared prop while deriving Android's scroll range from the drawn text. - Prop("contentWidth") { _: T3ReviewDiffView, _: Double -> } - Prop("contentInsetBottom") { view: T3ReviewDiffView, value: Double -> - view.setContentInsetBottom(value.toFloat()) - } - Prop("scrollEnabled") { view: T3ReviewDiffView, enabled: Boolean -> - view.setScrollEnabled(enabled) - } - Prop("initialRowIndex") { view: T3ReviewDiffView, initialRowIndex: Double -> - view.setInitialRowIndex(initialRowIndex) - } - Prop("initialFileId") { view: T3ReviewDiffView, fileId: String -> - view.setInitialFileId(fileId) - } + reviewProps() - Events(REVIEW_DIFF_EVENTS) + Events( + "onDebug", + "onVisibleFileChange", + "onToggleFile", + "onToggleViewedFile", + "onPressLine", + "onSelectLineRange", + "onPressHunk", + "onPressFileAction", + "onToggleComment", + ) AsyncFunction("scrollToFile") { view: T3ReviewDiffView, fileId: String, animated: Boolean -> view.scrollToFile(fileId, animated) @@ -92,4 +60,60 @@ class T3ReviewDiffModule : Module() { } } } + + private fun ViewDefinitionBuilder.reviewProps() { + Prop("tokensResetKey") { view: T3ReviewDiffView, tokensResetKey: String -> + view.setTokensResetKey(tokensResetKey) + } + Prop("contentResetKey") { view: T3ReviewDiffView, contentResetKey: String -> + view.setContentResetKey(contentResetKey) + } + Prop("collapsedFileIdsJson") { view: T3ReviewDiffView, collapsedFileIdsJson: String -> + view.setCollapsedFileIdsJson(collapsedFileIdsJson) + } + Prop("viewedFileIdsJson") { view: T3ReviewDiffView, viewedFileIdsJson: String -> + view.setViewedFileIdsJson(viewedFileIdsJson) + } + Prop("selectedRowIdsJson") { view: T3ReviewDiffView, selectedRowIdsJson: String -> + view.setSelectedRowIdsJson(selectedRowIdsJson) + } + Prop("enableLineRangeSelection") { view: T3ReviewDiffView, enabled: Boolean -> + view.setEnableLineRangeSelection(enabled) + } + Prop("showViewedCheckbox") { view: T3ReviewDiffView, shown: Boolean -> + view.setShowViewedCheckbox(shown) + } + Prop("viewedCheckboxEnabled") { view: T3ReviewDiffView, enabled: Boolean -> + view.setViewedCheckboxEnabled(enabled) + } + Prop("collapsedCommentIdsJson") { view: T3ReviewDiffView, collapsedCommentIdsJson: String -> + view.setCollapsedCommentIdsJson(collapsedCommentIdsJson) + } + Prop("appearanceScheme") { view: T3ReviewDiffView, appearanceScheme: String -> + view.setAppearanceScheme(appearanceScheme) + } + Prop("themeJson") { view: T3ReviewDiffView, themeJson: String -> + view.setThemeJson(themeJson) + } + Prop("styleJson") { view: T3ReviewDiffView, styleJson: String -> + view.setStyleJson(styleJson) + } + Prop("rowHeight") { view: T3ReviewDiffView, rowHeight: Double -> + view.setRowHeight(rowHeight.toFloat()) + } + // Accept the shared prop while deriving Android's scroll range from the drawn text. + Prop("contentWidth") { _: T3ReviewDiffView, _: Double -> } + Prop("contentInsetBottom") { view: T3ReviewDiffView, value: Double -> + view.setContentInsetBottom(value.toFloat()) + } + Prop("scrollEnabled") { view: T3ReviewDiffView, enabled: Boolean -> + view.setScrollEnabled(enabled) + } + Prop("initialRowIndex") { view: T3ReviewDiffView, initialRowIndex: Double -> + view.setInitialRowIndex(initialRowIndex) + } + Prop("initialFileId") { view: T3ReviewDiffView, fileId: String -> + view.setInitialFileId(fileId) + } + } } diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt index 91bb6719ed8fa..21bedb756a51b 100644 --- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt @@ -29,7 +29,10 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont private val onVisibleFileChange by EventDispatcher() private val onToggleFile by EventDispatcher() private val onToggleViewedFile by EventDispatcher() + private val onPressHunk by EventDispatcher() + private val onPressFileAction by EventDispatcher() private val onPressLine by EventDispatcher() + private val onSelectLineRange by EventDispatcher() private val onToggleComment by EventDispatcher() private val onPressNotice by EventDispatcher() private var rows: List = emptyList() @@ -74,6 +77,9 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont canvasView.onVerticalAnchorRestored = { verticalScroller.forceFinished(true) } canvasView.onRowTap = { row, gesture, target -> handleRowTap(row, gesture, target) } canvasView.onViewportSizeChanged = { applyPendingInitialScroll() } + canvasView.onSelectLineRange = { start, end -> + onSelectLineRange(mapOf("startRowId" to start, "endRowId" to end)) + } canvasView.onVisibleRowsChanged = { first, last -> onDebug( mapOf( @@ -135,6 +141,18 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont canvasView.selectedRowIds = selectedRowIds } + fun setEnableLineRangeSelection(enabled: Boolean) { + canvasView.enableLineRangeSelection = enabled + } + + fun setShowViewedCheckbox(shown: Boolean) { + canvasView.showViewedCheckbox = shown + } + + fun setViewedCheckboxEnabled(enabled: Boolean) { + canvasView.viewedCheckboxEnabled = enabled + } + fun setCollapsedCommentIdsJson(value: String) { collapsedCommentIds = parseStringSet(value) canvasView.collapsedCommentIds = collapsedCommentIds @@ -269,6 +287,7 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont @Suppress("NestedBlockDepth", "ReturnCount") override fun onInterceptTouchEvent(event: MotionEvent): Boolean { + if (canvasView.isRangeDragging) return false when (event.actionMasked) { MotionEvent.ACTION_DOWN -> { verticalScroller.forceFinished(true) @@ -424,9 +443,19 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont private fun handleRowTap(row: DiffRow, gesture: String, target: RowTapTarget) { when (row.kind) { + "hunk" -> if (gesture == "tap") handleHunkTap(row, target) "file" -> { if (gesture != "tap") return - if (target == RowTapTarget.VIEWED_CHECKBOX) { + if (target == RowTapTarget.FILE_ACTION) { + if (!row.fileActionDisabled) { + onPressFileAction( + mapOf( + "fileId" to row.resolvedFileId, + "rowId" to row.id + ) + ) + } + } else if (target == RowTapTarget.VIEWED_CHECKBOX) { onToggleViewedFile(mapOf("fileId" to row.resolvedFileId)) } else { onToggleFile(mapOf("fileId" to row.resolvedFileId)) @@ -450,6 +479,14 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont } } + private fun handleHunkTap(row: DiffRow, target: RowTapTarget) { + if (target == RowTapTarget.HUNK_REVERT && !row.hunkRevertActionDisabled) { + onPressHunk(mapOf("rowId" to row.id, "action" to "revert")) + } else if (target == RowTapTarget.HUNK_ACTION && !row.hunkActionDisabled) { + onPressHunk(mapOf("rowId" to row.id, "action" to "stage")) + } + } + @Suppress("ReturnCount") private fun emitVisibleFile(firstVisibleIndex: Int) { if (visibleRows.isEmpty()) return @@ -508,7 +545,10 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont private enum class RowTapTarget { ROW, - VIEWED_CHECKBOX + VIEWED_CHECKBOX, + HUNK_ACTION, + HUNK_REVERT, + FILE_ACTION } private enum class HorizontalPanKind { @@ -539,17 +579,22 @@ internal data class DiffRow( val commentText: String, val commentRangeLabel: String, val commentSectionTitle: String, - /** A notice drawn in the warning colors. */ - val tone: String = "", - /** A notice that reports taps through `onPressNotice`. */ - val actionable: Boolean = false, - /** Where a cut line's note starts in `content`. */ - val noteStart: Int? = null + val commentPending: Boolean = false, + val commentResolvedSummary: String? = null, + val renameSegments: List = emptyList(), + val hunkAction: String? = null, + val hunkActionDisabled: Boolean = false, + val hunkRevertAction: Boolean = false, + val hunkRevertActionDisabled: Boolean = false, + val fileAction: String? = null, + val fileActionDisabled: Boolean = false ) { val resolvedFileId: String get() = fileId.ifEmpty { id } val isPlainAscii: Boolean = content.all { it in ' '..'~' } } +internal data class DiffRenameSegment(val text: String, val kind: String) + internal data class DiffWordDiffRange( val start: Int, val end: Int @@ -764,15 +809,39 @@ private class DiffCanvasView(context: Context) : View(context) { override fun onSingleTapUp(event: MotionEvent): Boolean { rowHitAt(event.y)?.let { hit -> - val target = if ( - hit.row.kind == "file" && + if (enableLineRangeSelection && hit.row.kind == "line" && lineRange.startIndex != null) { + val index = rows.indexOf(hit.row) + if (rows[lineRange.startIndex!!].resolvedFileId == hit.row.resolvedFileId) { + updateNativeRange(lineRange.startIndex!!, index) + return@let + } + } + if (hit.row.kind == "line") clearNativeRange() + val target = if (hit.row.kind == "hunk" && hit.row.hunkAction != null && + event.x >= width - 112 * density + ) { + RowTapTarget.HUNK_ACTION + } else if (hit.row.kind == "hunk" && hit.row.hunkRevertAction && + event.x >= width - 224 * density + ) { + RowTapTarget.HUNK_REVERT + } else if (hit.row.kind == "file" && hit.row.fileAction != null && + event.x >= width - 100 * density + ) { + RowTapTarget.FILE_ACTION + } else if ( + showViewedCheckbox && hit.row.kind == "file" && drawing.fileHeaderCheckboxRect( hit.top, hit.bottom, width, style - ).contains(event.x, event.y) + ).apply { + inset(-12f * density, -12f * density) + intersect(0f, hit.top.toFloat(), width.toFloat(), hit.bottom.toFloat()) + }.contains(event.x, event.y) ) { + if (!viewedCheckboxEnabled) return@let RowTapTarget.VIEWED_CHECKBOX } else { RowTapTarget.ROW @@ -783,9 +852,13 @@ private class DiffCanvasView(context: Context) : View(context) { } override fun onLongPress(event: MotionEvent) { - rowHitAt(event.y)?.row - ?.takeIf { it.kind == "line" } - ?.let { onRowTap?.invoke(it, "longPress", RowTapTarget.ROW) } + val row = rowHitAt(event.y)?.row?.takeIf { it.kind == "line" } ?: return + if (enableLineRangeSelection) { + beginNativeRange(rows.indexOf(row)) + parent?.requestDisallowInterceptTouchEvent(true) + } else { + onRowTap?.invoke(row, "longPress", RowTapTarget.ROW) + } } }, ) @@ -802,6 +875,7 @@ private class DiffCanvasView(context: Context) : View(context) { private var viewportEventsPaused = true var rows: List = emptyList() set(value) { + clearNativeRange() field = value fileHeaderIndices = indexFileHeaders(value) headerPathOffsetsByFileId.keys.retainAll( @@ -840,10 +914,33 @@ private class DiffCanvasView(context: Context) : View(context) { rebuildOffsets() } var selectedRowIds: Set = emptySet() + set(value) { + field = value + if (value.isEmpty() && !isRangeDragging) clearNativeRange() + invalidate() + } + var enableLineRangeSelection = false + set(value) { + field = value + if (!value) clearNativeRange() + } + var showViewedCheckbox = true + set(value) { + field = value + clampHeaderPathOffsets() + invalidate() + } + var viewedCheckboxEnabled = true set(value) { field = value invalidate() } + private val lineRange = ReviewDiffLineRange() + var isRangeDragging: Boolean + get() = lineRange.isDragging + private set(value) { + lineRange.isDragging = value + } var theme: DiffTheme = DiffTheme.fallback("light") set(value) { field = value @@ -857,6 +954,7 @@ private class DiffCanvasView(context: Context) : View(context) { rebuildOffsets() } var onRowTap: ((DiffRow, String, RowTapTarget) -> Unit)? = null + var onSelectLineRange: ((String, String) -> Unit)? = null var onVisibleRowsChanged: ((Int, Int) -> Unit)? = null var onContentHeightChanged: ((Int) -> Unit)? = null var onVerticalAnchorRestored: (() -> Unit)? = null @@ -901,11 +999,70 @@ private class DiffCanvasView(context: Context) : View(context) { ) } drawStickyFileHeader(canvas, first) + rangeHandleCenters()?.let { (start, end) -> + backgroundPaint.color = Color.rgb(48, 118, 237) + canvas.drawCircle(start.first, start.second, 5f * density, backgroundPaint) + canvas.drawCircle(end.first, end.second, 5f * density, backgroundPaint) + } drawHorizontalScrollIndicator(canvas) emitVisibleRange() } - override fun onTouchEvent(event: MotionEvent): Boolean = gestureDetector.onTouchEvent(event) + override fun onTouchEvent(event: MotionEvent): Boolean { + val startedDrag = if (enableLineRangeSelection && + event.actionMasked == MotionEvent.ACTION_DOWN + ) { + rangeHandleAt(event.x, event.y)?.let { lineRange.dragHandle(it) } == true + } else { + false + } + return if (startedDrag) { + parent?.requestDisallowInterceptTouchEvent(true) + true + } else if (isRangeDragging) { + when (event.actionMasked) { + MotionEvent.ACTION_MOVE -> { + val start = lineRange.startIndex + val index = rowIndexAt(verticalOffset + event.y.toInt()) + if (start != null) updateNativeRange(start, nearestRangeLine(index)) + } + MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { + isRangeDragging = false + parent?.requestDisallowInterceptTouchEvent(false) + val cancel = MotionEvent.obtain(event) + cancel.action = MotionEvent.ACTION_CANCEL + gestureDetector.onTouchEvent(cancel) + cancel.recycle() + } + } + true + } else { + gestureDetector.onTouchEvent(event) + } + } + + private fun beginNativeRange(index: Int) { + if (lineRange.begin(index, rows)) updateNativeRange(index, index) + } + + private fun updateNativeRange(start: Int, end: Int) { + lineRange.update(start, end, rows)?.let { (first, last) -> + onSelectLineRange?.invoke(first, last) + invalidate() + } + } + + private fun nearestRangeLine(index: Int): Int = lineRange.nearestLine(index) + + private fun clearNativeRange() = lineRange.clear() + + private fun rangeHandleCenters(): Pair, Pair>? { + val x = max(12f * density, style.changeBarWidthPx + style.gutterWidthPx - 6f * density) + return lineRange.centers(rows, rowOffsets, verticalOffset, x) + } + + private fun rangeHandleAt(x: Float, y: Float): Boolean? = + lineRange.handleAt(x, y, 22f * density, rangeHandleCenters()) fun rowTop(index: Int): Int = rowOffsets[index.coerceIn(0, max(0, rowOffsets.size - 2))] @@ -1002,12 +1159,19 @@ private class DiffCanvasView(context: Context) : View(context) { private fun rowHeight(row: DiffRow): Int = when (row.kind) { "file" -> style.fileHeaderHeightPx.toInt() "notice" -> max((style.rowHeightPx * 2f).toInt(), (44 * density).toInt()) - "comment" -> if (collapsedCommentIds.contains(row.id)) { + "comment" -> if (collapsedCommentIds.contains(row.id) || row.commentResolvedSummary != null) { (44 * density).toInt() } else { (124 * density).toInt() } "line" -> codeWrap.rowHeight(row, style.rowHeightPx.toInt()) + "hunk" -> if (row.hunkAction != + null + ) { + max(style.rowHeightPx.toInt(), (44 * density).toInt()) + } else { + style.rowHeightPx.toInt() + } else -> style.rowHeightPx.toInt() }.coerceAtLeast(1) @@ -1060,91 +1224,26 @@ private class DiffCanvasView(context: Context) : View(context) { } private fun drawFileRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) { - fill(canvas, theme.headerBackground, 0f, top.toFloat(), width.toFloat(), bottom.toFloat()) - - val chevronRect = drawing.fileHeaderChevronRect(top, bottom, style) - val iconRect = drawing.fileHeaderIconRect(top, bottom, style) - val checkboxRect = drawing.fileHeaderCheckboxRect(top, bottom, width, style) - drawing.drawDisclosureChevron( - canvas, - chevronRect, - theme.mutedText, - collapsed = collapsedFileIds.contains(row.resolvedFileId), - ) - drawing.drawFileIcon(canvas, iconRect, row.changeType) - drawing.drawViewedCheckbox( - canvas, - checkboxRect, - viewedFileIds.contains(row.resolvedFileId), - ) - - drawing.configureUiPaint( - paint = boldTextPaint, - color = theme.deleteText, - size = style.fileHeaderMetaFontSizePx, - weight = style.fileHeaderMetaFontWeight, - ) - val deleteText = "-${row.deletions}" - val deleteWidth = boldTextPaint.measureText(deleteText) - val addText = "+${row.additions}" - val addWidth = boldTextPaint.measureText(addText) - val countGap = 4f * density - val countsX = checkboxRect.left - 10f * density - deleteWidth - countGap - addWidth - val baseline = centeredBaseline(top, bottom, boldTextPaint) - canvas.drawText(deleteText, countsX, baseline, boldTextPaint) - boldTextPaint.color = theme.addText - canvas.drawText(addText, countsX + deleteWidth + countGap, baseline, boldTextPaint) - - val pathLayout = fileHeaderPathLayout(row, top, bottom, iconRect, countsX) - val maxPathOffset = maxHeaderPathOffset(pathLayout) - val pathOffset = (headerPathOffsetsByFileId[row.resolvedFileId] ?: 0) - .coerceIn(0, maxPathOffset) - canvas.save() - canvas.clipRect(pathLayout.rect) - canvas.drawText( - pathLayout.displayPath, - pathLayout.rect.left - pathOffset, - centeredBaseline(top, bottom, boldTextPaint), - boldTextPaint, - ) - canvas.restore() - drawing.drawFileHeaderPathScrollFades( + drawing.drawFileHeader( canvas, - pathLayout.rect, - pathOffset, - maxPathOffset, + row, + RectF(0f, top.toFloat(), width.toFloat(), bottom.toFloat()), + style, + FileHeaderDrawingState( + collapsed = collapsedFileIds.contains(row.resolvedFileId), + viewed = viewedFileIds.contains(row.resolvedFileId), + showViewedCheckbox = showViewedCheckbox, + viewedCheckboxEnabled = viewedCheckboxEnabled, + pathOffset = headerPathOffsetsByFileId[row.resolvedFileId] ?: 0, + ), ) - drawBottomBorder(canvas, bottom) } private fun fileHeaderPathLayout( row: DiffRow, - top: Int, - bottom: Int, iconRect: RectF, countsX: Float - ): FileHeaderPathLayout { - drawing.configureUiPaint( - paint = boldTextPaint, - color = theme.text, - size = style.fileHeaderFontSizePx, - weight = style.fileHeaderFontWeight, - ) - val pathX = iconRect.right + 10f * density - val pathWidth = max(24f * density, countsX - pathX - 12f * density) - val centerY = (top + bottom) / 2f - val displayPath = if ( - !row.previousPath.isNullOrEmpty() && row.previousPath != row.filePath - ) { - "${row.previousPath} -> ${row.filePath}" - } else { - row.filePath - } - return FileHeaderPathLayout( - displayPath = displayPath, - rect = RectF(pathX, centerY - 10f * density, pathX + pathWidth, centerY + 10f * density), - ) - } + ): FileHeaderPathLayout = drawing.fileHeaderPathLayout(row, iconRect, countsX, style) private fun maxHeaderPathOffset(fileId: String): Int { val rowIndex = fileHeaderIndices.firstOrNull { rows[it].resolvedFileId == fileId } ?: return 0 @@ -1159,10 +1258,17 @@ private class DiffCanvasView(context: Context) : View(context) { size = style.fileHeaderMetaFontSizePx, weight = style.fileHeaderMetaFontWeight, ) - val countsX = checkboxRect.left - 10f * density - + val countsRight = if (row.fileAction != null) { + width - 110f * density + } else if (showViewedCheckbox) { + checkboxRect.left - 10f * density + } else { + width - 16f * density + } + val countsX = countsRight - boldTextPaint.measureText("-${row.deletions}") - 4f * density - boldTextPaint.measureText("+${row.additions}") - return maxHeaderPathOffset(fileHeaderPathLayout(row, top, bottom, iconRect, countsX)) + return maxHeaderPathOffset(fileHeaderPathLayout(row, iconRect, countsX)) } private fun maxHeaderPathOffset(layout: FileHeaderPathLayout): Int = max( @@ -1190,99 +1296,32 @@ private class DiffCanvasView(context: Context) : View(context) { } private fun drawHunkRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) { - fill(canvas, theme.hunkBackground, 0f, top.toFloat(), width.toFloat(), bottom.toFloat()) - drawing.configureMonospacePaint( - color = theme.hunkText, - size = style.hunkFontSizePx, - weight = style.hunkFontWeight, + drawing.drawHunkRow( + canvas, + row, + RectF(0f, top.toFloat(), width.toFloat(), bottom.toFloat()), + style, + horizontalOffset, ) - drawScrollableCode(canvas, top, bottom) { codeX -> - canvas.drawText( - row.text.ifEmpty { row.content }, - codeX, - centeredBaseline(top, bottom, textPaint), - textPaint, - ) - } } private fun drawNoticeRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) { - fill(canvas, drawing.noticeFill(row), 0f, top.toFloat(), width.toFloat(), bottom.toFloat()) - val iconSize = 16f * density - val iconRect = RectF( - style.fileHeaderHorizontalPaddingPx + 2f * density, - (top + bottom - iconSize) / 2f, - style.fileHeaderHorizontalPaddingPx + 2f * density + iconSize, - (top + bottom + iconSize) / 2f, - ) - drawing.drawNoticeIcon(canvas, iconRect, drawing.noticeColor(row)) - drawing.configureUiPaint( - paint = textPaint, - color = drawing.noticeColor(row), - size = style.fileHeaderSubtextFontSizePx, - weight = style.fileHeaderSubtextFontWeight, - ) - val textX = iconRect.right + 10f * density - canvas.drawText( - ellipsize(row.text, textPaint, width - textX - style.fileHeaderHorizontalPaddingPx), - textX, - centeredBaseline(top, bottom, textPaint), - textPaint, + drawing.drawNoticeRow( + canvas, + row, + RectF(0f, top.toFloat(), width.toFloat(), bottom.toFloat()), + style, ) - drawBottomBorder(canvas, bottom) } private fun drawCommentRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) { - fill(canvas, theme.background, 0f, top.toFloat(), width.toFloat(), bottom.toFloat()) - val cardRect = RectF( - 8f * density, - top + 5f * density, - width - 8f * density, - bottom - 5f * density, - ) - backgroundPaint.color = theme.headerBackground - canvas.drawRoundRect(cardRect, 10f * density, 10f * density, backgroundPaint) - borderPaint.style = Paint.Style.STROKE - borderPaint.color = withAlpha(theme.border, 217) - borderPaint.strokeWidth = density - canvas.drawRoundRect(cardRect, 10f * density, 10f * density, borderPaint) - borderPaint.style = Paint.Style.FILL - - val collapsed = collapsedCommentIds.contains(row.id) - val chevronRect = RectF( - cardRect.left + 10f * density, - cardRect.top + 11f * density, - cardRect.left + 26f * density, - cardRect.top + 27f * density, - ) - drawing.drawDisclosureChevron(canvas, chevronRect, theme.mutedText, collapsed) - drawing.configureUiPaint( - paint = textPaint, - color = theme.mutedText, - size = style.fileHeaderSubtextFontSizePx, - weight = style.fileHeaderSubtextFontWeight, - ) - val title = "Comment on ${row.commentRangeLabel.ifEmpty { "line" }}" - canvas.drawText( - ellipsize(title, textPaint, cardRect.right - chevronRect.right - 20f * density), - chevronRect.right + 10f * density, - cardRect.top + 22f * density, - textPaint, + drawing.drawCommentRow( + canvas, + row, + RectF(0f, top.toFloat(), width.toFloat(), bottom.toFloat()), + style, + collapsedCommentIds.contains(row.id) || row.commentResolvedSummary != null, ) - if (!collapsed) { - textPaint.color = theme.text - val bodyX = cardRect.left + 18f * density - canvas.drawText( - ellipsize( - row.commentText.ifEmpty { "Comment" }, - textPaint, - cardRect.right - bodyX - 18f * density - ), - bodyX, - cardRect.top + 58f * density, - textPaint, - ) - } } @Suppress("CyclomaticComplexMethod") @@ -1312,8 +1351,16 @@ private class DiffCanvasView(context: Context) : View(context) { ) } } - val selected = selectedRowIds.contains(row.id) + val selected = selectedRowIds.contains(row.id) || lineRange.selectedRowIds.contains(row.id) if (selected) { + fill( + canvas, + withAlpha(Color.rgb(48, 118, 237), 25), + 0f, + top.toFloat(), + width.toFloat(), + bottom.toFloat() + ) fill( canvas, withAlpha(theme.hunkText, 242), @@ -1420,10 +1467,9 @@ private class DiffCanvasView(context: Context) : View(context) { canvas.drawRect(left, top, right, bottom, backgroundPaint) } - private fun drawBottomBorder(canvas: Canvas, bottom: Int) { - borderPaint.color = theme.border - borderPaint.strokeWidth = density - canvas.drawLine(0f, bottom - density / 2f, width.toFloat(), bottom - density / 2f, borderPaint) + private fun centeredBaseline(top: Int, bottom: Int, paint: Paint): Float { + val metrics = paint.fontMetrics + return (top + bottom) / 2f - (metrics.ascent + metrics.descent) / 2f } private data class StickyFileHeader( @@ -1437,11 +1483,6 @@ private class DiffCanvasView(context: Context) : View(context) { val top: Int, val bottom: Int ) - - private data class FileHeaderPathLayout( - val displayPath: String, - val rect: RectF - ) } private fun centeredBaseline(top: Int, bottom: Int, paint: Paint): Float { @@ -1449,26 +1490,6 @@ private fun centeredBaseline(top: Int, bottom: Int, paint: Paint): Float { return (top + bottom) / 2f - (metrics.ascent + metrics.descent) / 2f } -// A single-line preview never shows this many characters, so longer text is cut before measuring. -private const val ELLIPSIZE_MAX_CHARS = 500 - -private fun ellipsize(value: String, paint: Paint, width: Float): String { - val truncated = value.length > ELLIPSIZE_MAX_CHARS - val capEnd = surrogateSafeEnd(value, ELLIPSIZE_MAX_CHARS) - val text = if (truncated) value.substring(0, capEnd) else value - if (!truncated && paint.measureText(text) <= width) return value - val suffix = "..." - val available = max(0f, width - paint.measureText(suffix)) - val end = surrogateSafeEnd(text, paint.breakText(text, true, available, null)) - return text.substring(0, end) + suffix -} - -private fun surrogateSafeEnd(value: String, end: Int): Int { - val splitsPair = end in 1 until value.length && - Character.isSurrogatePair(value[end - 1], value[end]) - return if (splitsPair) end - 1 else end -} - private fun indexFileHeaders(rows: List): IntArray { val headers = ArrayList() rows.forEachIndexed { index, row -> @@ -1494,10 +1515,22 @@ private fun parseRows(value: String, isCancelled: () -> Boolean): List fileId = row.optString("fileId"), filePath = row.optString("filePath"), previousPath = row.optNullableString("previousPath"), + renameSegments = row.optJSONArray("renameSegments")?.let { parts -> + List(parts.length()) { index -> + val part = parts.getJSONObject(index) + DiffRenameSegment(part.getString("text"), part.getString("kind")) + } + }.orEmpty(), changeType = row.optString("changeType"), additions = row.optInt("additions"), deletions = row.optInt("deletions"), text = row.optString("text"), + hunkAction = row.optNullableString("hunkAction"), + hunkActionDisabled = row.optBoolean("hunkActionDisabled", false), + hunkRevertAction = row.optBoolean("hunkRevertAction", false), + hunkRevertActionDisabled = row.optBoolean("hunkRevertActionDisabled", false), + fileAction = row.optNullableString("fileAction"), + fileActionDisabled = row.optBoolean("fileActionDisabled", false), content = row.optString("content"), change = row.optString("change", "context"), oldLineNumber = row.optNullableInt("oldLineNumber"), @@ -1505,6 +1538,8 @@ private fun parseRows(value: String, isCancelled: () -> Boolean): List wordDiffRanges = row.optJSONArray("wordDiffRanges")?.let(::parseWordDiffRanges).orEmpty(), commentText = row.optString("commentText"), commentRangeLabel = row.optString("commentRangeLabel"), + commentPending = row.optBoolean("commentPending", false), + commentResolvedSummary = row.optNullableString("commentResolvedSummary"), commentSectionTitle = row.optString("commentSectionTitle"), tone = row.optString("tone"), actionable = row.optBoolean("actionable"), diff --git a/apps/mobile/modules/t3-review-diff/android/src/test/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayoutTest.kt b/apps/mobile/modules/t3-review-diff/android/src/test/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayoutTest.kt index 0446997423141..e7f710f3685b7 100644 --- a/apps/mobile/modules/t3-review-diff/android/src/test/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayoutTest.kt +++ b/apps/mobile/modules/t3-review-diff/android/src/test/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayoutTest.kt @@ -3,6 +3,7 @@ package expo.modules.t3reviewdiff import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color +import android.graphics.Paint import android.graphics.Typeface import android.text.Spanned import android.text.TextPaint @@ -41,6 +42,44 @@ class ReviewDiffCodeLayoutTest { } } + @Test + fun expandedCommentEllipsisBoundsMeasurementAndKeepsSurrogatePairs() { + val comment = "\uD83D\uDE00" + "a".repeat(65534) + val measuringPaint = CountingPaint() + val result = ellipsizeDiffText(comment, measuringPaint, 4f) + assertTrue( + "one comment must not measure progressively shorter prefixes", + measuringPaint.measuredCharacters <= comment.length * 2L + 3, + ) + assertEquals("...", result) + assertEquals("short", ellipsizeDiffText("short", measuringPaint, 5f)) + assertEquals("ab...", ellipsizeDiffText("abcdef", measuringPaint, 5f)) + } + + private class CountingPaint : Paint() { + var measuredCharacters = 0L + + override fun measureText(text: String): Float { + measuredCharacters += text.length + return text.length.toFloat() + } + + override fun measureText(text: String, start: Int, end: Int): Float { + measuredCharacters += end - start + return (end - start).toFloat() + } + + override fun breakText( + text: String, + measureForwards: Boolean, + maxWidth: Float, + measuredWidth: FloatArray? + ): Int { + measuredCharacters += text.length + return maxWidth.toInt().coerceIn(0, text.length) + } + } + private fun assertLinesFit(layout: android.text.StaticLayout, fixture: String, width: Int) { val text = layout.text for (line in 0 until layout.lineCount) { diff --git a/apps/mobile/modules/t3-review-diff/android/src/test/java/expo/modules/t3reviewdiff/ReviewDiffLineRangeTest.kt b/apps/mobile/modules/t3-review-diff/android/src/test/java/expo/modules/t3reviewdiff/ReviewDiffLineRangeTest.kt new file mode 100644 index 0000000000000..14e3d301b4d3f --- /dev/null +++ b/apps/mobile/modules/t3-review-diff/android/src/test/java/expo/modules/t3reviewdiff/ReviewDiffLineRangeTest.kt @@ -0,0 +1,106 @@ +package expo.modules.t3reviewdiff + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class ReviewDiffLineRangeTest { + private val rows = listOf( + row("first", "a"), + row("hunk", "a", kind = "hunk"), + row("last", "a"), + row("other", "b"), + ) + + @Test + fun selectsLinesAcrossHunksInEitherDirection() { + val range = ReviewDiffLineRange() + assertTrue(range.begin(0, rows)) + assertEquals("first" to "last", range.update(0, 2, rows)) + assertEquals(setOf("first", "last"), range.selectedRowIds) + assertNull(range.update(0, 2, rows)) + assertEquals("first" to "last", range.update(2, 0, rows)) + assertEquals(setOf("first", "last"), range.selectedRowIds) + } + + @Test + fun refusesOtherFilesAndNonLineEndpointsWithoutLosingTheSelection() { + val range = ReviewDiffLineRange() + range.begin(0, rows) + range.update(0, 2, rows) + assertNull(range.update(0, 3, rows)) + assertNull(range.update(0, 1, rows)) + assertNull(range.update(-1, 2, rows)) + assertEquals(0, range.startIndex) + assertEquals(2, range.endIndex) + assertEquals(setOf("first", "last"), range.selectedRowIds) + } + + @Test + fun draggingTheStartHandleAnchorsTheOtherEndAndSkipsHeaders() { + val range = ReviewDiffLineRange() + range.begin(0, rows) + range.update(0, 2, rows) + range.isDragging = false + assertTrue(range.dragHandle(movingStart = true)) + assertEquals(2, range.startIndex) + assertEquals(0, range.endIndex) + assertEquals(2, range.nearestLine(1)) + assertEquals(2, range.nearestLine(99)) + assertEquals(0, range.nearestLine(-1)) + assertTrue(range.dragHandle(movingStart = false)) + assertEquals(0, range.startIndex) + assertEquals(2, range.endIndex) + } + + @Test + fun handleHitAreasFollowScrolledGeometryAndPreferTheStartWhenTheyOverlap() { + val range = ReviewDiffLineRange() + range.begin(0, rows) + range.update(0, 2, rows) + val centers = range.centers(rows, intArrayOf(0, 20, 40, 60, 80), 10, 12f) + assertEquals(Pair(12f, -10f) to Pair(12f, 50f), centers) + assertEquals(true, range.handleAt(12f, -10f, 22f, centers)) + assertEquals(false, range.handleAt(12f, 50f, 22f, centers)) + assertNull(range.handleAt(100f, 100f, 22f, centers)) + range.update(0, 0, rows) + val overlapping = range.centers(rows, intArrayOf(0, 20, 40, 60, 80), 0, 12f) + assertEquals(true, range.handleAt(12f, 10f, 22f, overlapping)) + } + + @Test + fun clearingRowsRetiresTheRangeAndItsDragHandles() { + val range = ReviewDiffLineRange() + range.begin(0, rows) + range.update(0, 2, rows) + range.clear() + assertNull(range.startIndex) + assertNull(range.endIndex) + assertTrue(range.selectedRowIds.isEmpty()) + assertFalse(range.isDragging) + assertFalse(range.dragHandle(movingStart = true)) + assertNull(range.centers(rows, intArrayOf(0, 20, 40, 60, 80), 0, 12f)) + } + + private fun row(id: String, fileId: String, kind: String = "line") = DiffRow( + kind = kind, + id = id, + fileId = fileId, + filePath = "$fileId.ts", + previousPath = null, + changeType = "modified", + additions = 0, + deletions = 0, + text = "", + content = "", + change = "context", + oldLineNumber = null, + newLineNumber = null, + wordDiffRanges = emptyList(), + commentText = "", + commentRangeLabel = "", + commentSectionTitle = "", + ) +} diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift index d1be707b0d9d6..aa8f47acb7d4a 100644 --- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift +++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift @@ -33,6 +33,18 @@ public class T3ReviewDiffModule: Module { view.setSelectedRowIdsJson(selectedRowIdsJson) } + Prop("enableLineRangeSelection") { (view: T3ReviewDiffView, enabled: Bool) in + view.setEnableLineRangeSelection(enabled) + } + + Prop("showViewedCheckbox") { (view: T3ReviewDiffView, shown: Bool) in + view.setShowViewedCheckbox(shown) + } + + Prop("viewedCheckboxEnabled") { (view: T3ReviewDiffView, enabled: Bool) in + view.setViewedCheckboxEnabled(enabled) + } + Prop("collapsedCommentIdsJson") { (view: T3ReviewDiffView, collapsedCommentIdsJson: String) in view.setCollapsedCommentIdsJson(collapsedCommentIdsJson) } @@ -87,6 +99,9 @@ public class T3ReviewDiffModule: Module { "onToggleFile", "onToggleViewedFile", "onPressLine", + "onSelectLineRange", + "onPressHunk", + "onPressFileAction", "onToggleComment", "onPressNotice", "onPullToRefresh" diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift index 7fe4a068f9bbb..bd267cdb641b5 100644 --- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift +++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift @@ -7,6 +7,7 @@ private struct ReviewDiffNativeRow: Decodable, Sendable { let fileId: String? let filePath: String? let previousPath: String? + let renameSegments: [ReviewDiffRenameSegment]? let changeType: String? let additions: Int? let deletions: Int? @@ -18,13 +19,20 @@ private struct ReviewDiffNativeRow: Decodable, Sendable { let wordDiffRanges: [ReviewDiffNativeWordDiffRange]? let commentText: String? let commentRangeLabel: String? + let commentPending: Bool? + let commentResolvedSummary: String? let commentSectionTitle: String? - /** A notice drawn in the warning colors. */ - let tone: String? - /** A notice that reports taps through `onPressNotice`. */ - let actionable: Bool? - /** Where a cut line's note starts in `content`, in UTF-16 units. */ - let noteStart: Int? + let hunkAction: String? + let hunkActionDisabled: Bool? + let hunkRevertAction: Bool? + let hunkRevertActionDisabled: Bool? + let fileAction: String? + let fileActionDisabled: Bool? +} + +private struct ReviewDiffRenameSegment: Decodable, Sendable { + let text: String + let kind: String } private struct ReviewDiffNativeWordDiffRange: Decodable, Sendable { @@ -366,6 +374,9 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { let onToggleFile = EventDispatcher() let onToggleViewedFile = EventDispatcher() let onPressLine = EventDispatcher() + let onSelectLineRange = EventDispatcher() + let onPressHunk = EventDispatcher() + let onPressFileAction = EventDispatcher() let onToggleComment = EventDispatcher() let onPressNotice = EventDispatcher() let onPullToRefresh = EventDispatcher() @@ -398,6 +409,15 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { contentView.onPressLine = { [weak self] payload in self?.onPressLine(payload) } + contentView.onSelectLineRange = { [weak self] payload in + self?.onSelectLineRange(payload) + } + contentView.onPressHunk = { [weak self] rowId, action in + self?.onPressHunk(["rowId": rowId, "action": action]) + } + contentView.onPressFileAction = { [weak self] fileId, rowId in + self?.onPressFileAction(["fileId": fileId, "rowId": rowId]) + } contentView.onToggleComment = { [weak self] commentId in self?.onToggleComment(["commentId": commentId]) } @@ -408,6 +428,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { self?.emitDebug("draw-metrics", metrics) } scrollView.addSubview(contentView) + contentView.attachScrollView(scrollView) } deinit { @@ -692,6 +713,18 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { contentView.selectedRowIds = decodeFileIdSet(selectedRowIdsJson) } + func setEnableLineRangeSelection(_ enabled: Bool) { + contentView.enableLineRangeSelection = enabled + } + + func setShowViewedCheckbox(_ shown: Bool) { + contentView.showViewedCheckbox = shown + } + + func setViewedCheckboxEnabled(_ enabled: Bool) { + contentView.viewedCheckboxEnabled = enabled + } + func setCollapsedCommentIdsJson(_ collapsedCommentIdsJson: String) { contentView.collapsedCommentIds = decodeFileIdSet(collapsedCommentIdsJson) updateContentMetrics() @@ -1079,7 +1112,8 @@ private struct ReviewDiffGeometryConfiguration: Equatable { if row.kind == "file" { return style.fileHeaderHeight } if collapsedFileIds.contains(row.resolvedFileId) { return 0 } if row.kind == "notice" { return max(style.rowHeight * 2, 44) } - if row.kind == "comment" { return collapsedCommentIds.contains(row.id) ? 44 : 124 } + if row.kind == "comment" { return collapsedCommentIds.contains(row.id) || row.commentResolvedSummary != nil ? 44 : 124 } + if row.kind == "hunk", row.hunkAction != nil { return max(style.rowHeight, 44) } return style.rowHeight } } @@ -1116,6 +1150,7 @@ private extension ReviewDiffNativeRow { private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { var rows: [ReviewDiffNativeRow] = [] { didSet { + clearNativeRange() stopHorizontalDeceleration() horizontalOffsetsByFileId.removeAll() headerPathOffsetsByFileId.removeAll() @@ -1123,6 +1158,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { activePanKind = nil codeDecorationVersion += 1 tokenAttributedStringsByRowId.removeAll() + renameAttributedStringsByRowId.removeAll() if let geometry = preparedRowGeometry { preparedRowGeometry = nil applyRowGeometry(geometry) @@ -1137,6 +1173,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { didSet { codeDecorationVersion += 1 tokenAttributedStringsByRowId.removeAll() + renameAttributedStringsByRowId.removeAll() clampHorizontalOffsets() setNeedsDisplayForVisibleBounds() } @@ -1161,9 +1198,22 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { } var selectedRowIds: Set = [] { didSet { + if selectedRowIds.isEmpty && !isRangeDragging { clearNativeRange() } setNeedsDisplayForVisibleBounds() } } + var enableLineRangeSelection = false { + didSet { if !enableLineRangeSelection { clearNativeRange() } } + } + var showViewedCheckbox = true { + didSet { + clampHorizontalOffsets() + setNeedsDisplayForVisibleBounds() + } + } + var viewedCheckboxEnabled = true { + didSet { setNeedsDisplayForVisibleBounds() } + } var collapsedCommentIds: Set = [] { didSet { rebuildRowLayout() @@ -1174,6 +1224,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { didSet { codeDecorationVersion += 1 tokenAttributedStringsByRowId.removeAll() + renameAttributedStringsByRowId.removeAll() rebuildRowLayout() clampHorizontalOffsets() setNeedsDisplayForVisibleBounds() @@ -1195,6 +1246,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { tokenColorsByHex.removeAll() codeDecorationVersion += 1 tokenAttributedStringsByRowId.removeAll() + renameAttributedStringsByRowId.removeAll() setNeedsDisplayForVisibleBounds() } } @@ -1204,6 +1256,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { private var fileHeaderRowIndices: [Int] = [] private var contentWidthsByFileId: [String: CGFloat] = [:] private var tokenColorsByHex: [String: UIColor] = [:] + private var renameAttributedStringsByRowId: [String: NSAttributedString] = [:] private var tokenAttributedStringsByRowId: [String: NSAttributedString] = [:] private var codeCharacterWidth: CGFloat = 8 private var codeWrapColumns: Int? @@ -1230,10 +1283,19 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { private var horizontalVelocity: CGFloat = 0 private var lastDecelerationTimestamp: CFTimeInterval = 0 private var lastDrawMetricsTimestamp: CFTimeInterval = 0 + private weak var parentScrollView: UIScrollView? + private var rangeStartIndex: Int? + private var rangeEndIndex: Int? + private var rangeLineIndices: [Int] = [] + private var nativeSelectedRowIds: Set = [] + private var isRangeDragging = false var isVerticalScrollActive = false var onToggleFile: ((String) -> Void)? var onToggleViewedFile: ((String) -> Void)? var onPressLine: (([String: Any]) -> Void)? + var onSelectLineRange: (([String: Any]) -> Void)? + var onPressHunk: ((String, String) -> Void)? + var onPressFileAction: ((String, String) -> Void)? var onToggleComment: ((String) -> Void)? var onPressNotice: (([String: Any]) -> Void)? var onDrawMetrics: (([String: Any]) -> Void)? @@ -1505,6 +1567,17 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { return gesture }() + private lazy var rangeHandlePanGesture: UIPanGestureRecognizer = { + let gesture = UIPanGestureRecognizer(target: self, action: #selector(handleRangeHandlePan(_:))) + gesture.delegate = self + return gesture + }() + + func attachScrollView(_ scrollView: UIScrollView) { + parentScrollView = scrollView + scrollView.panGestureRecognizer.require(toFail: rangeHandlePanGesture) + } + override init(frame: CGRect) { super.init(frame: frame) isOpaque = true @@ -1512,6 +1585,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { addGestureRecognizer(horizontalPanGesture) addGestureRecognizer(tapGesture) addGestureRecognizer(longPressGesture) + addGestureRecognizer(rangeHandlePanGesture) tapGesture.require(toFail: longPressGesture) } @@ -1530,10 +1604,15 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { addGestureRecognizer(horizontalPanGesture) addGestureRecognizer(tapGesture) addGestureRecognizer(longPressGesture) + addGestureRecognizer(rangeHandlePanGesture) tapGesture.require(toFail: longPressGesture) } override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { + if gestureRecognizer === rangeHandlePanGesture { + return enableLineRangeSelection && rangeHandle(at: gestureRecognizer.location(in: self)) != nil + } + if isRangeDragging { return false } guard gestureRecognizer === horizontalPanGesture else { return true } @@ -1572,6 +1651,11 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { } let row = rows[rowIndex] + if row.kind == "hunk", row.hunkAction != nil { + let rect = CGRect(x: 0, y: rowOffsets[rowIndex] - verticalOffset, width: viewportWidth, height: height(for: row)) + handleHunkTap(row: row, rect: rect, point: point) + return + } if row.kind == "comment" { onToggleComment?(row.id) return @@ -1583,6 +1667,12 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { } if row.kind == "line" { + if enableLineRangeSelection, let start = rangeStartIndex, + resolvedFileId(for: rows[start]) == resolvedFileId(for: row) { + updateNativeRange(start: start, end: rowIndex) + return + } + clearNativeRange() onPressLine?(linePressPayload(for: row, gesture: "tap")) return } @@ -1596,8 +1686,17 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { handleFileHeaderTap(row: row, rect: rect, point: point) } + private func handleHunkTap(row: ReviewDiffNativeRow, rect: CGRect, point: CGPoint) { + if row.hunkRevertAction == true, hunkRevertRect(in: rect).contains(point) { + if row.hunkRevertActionDisabled != true { onPressHunk?(row.id, "revert") } + } else if hunkActionRect(in: rect).contains(point), row.hunkActionDisabled != true { + onPressHunk?(row.id, "stage") + } + } + @objc private func handleLongPress(_ gesture: UILongPressGestureRecognizer) { - guard gesture.state == .began else { + if gesture.state == .ended || gesture.state == .cancelled || gesture.state == .failed { + finishRangeDrag() return } @@ -1612,11 +1711,100 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { } let row = rows[rowIndex] - guard row.kind == "line" else { - return + if gesture.state == .began { + guard row.kind == "line" else { return } + if !enableLineRangeSelection { + onPressLine?(linePressPayload(for: row, gesture: "longPress")) + return + } + beginNativeRange(at: rowIndex) + } else if gesture.state == .changed, isRangeDragging, let start = rangeStartIndex { + updateNativeRange(start: start, end: nearestRangeLine(to: rowIndex)) } + } - onPressLine?(linePressPayload(for: row, gesture: "longPress")) + private func beginNativeRange(at index: Int) { + let fileId = resolvedFileId(for: rows[index]) + rangeLineIndices = rows.indices.filter { + rows[$0].kind == "line" && resolvedFileId(for: rows[$0]) == fileId && height(at: $0) > 0 + } + isRangeDragging = true + parentScrollView?.panGestureRecognizer.isEnabled = false + updateNativeRange(start: index, end: index) + } + + private func updateNativeRange(start: Int, end: Int) { + guard rows.indices.contains(start), rows.indices.contains(end), rows[end].kind == "line", + resolvedFileId(for: rows[start]) == resolvedFileId(for: rows[end]) else { return } + if rangeStartIndex == start && rangeEndIndex == end { return } + rangeStartIndex = start + rangeEndIndex = end + let first = min(start, end), last = max(start, end) + nativeSelectedRowIds = Set(rangeLineIndices.filter { $0 >= first && $0 <= last }.map { rows[$0].id }) + onSelectLineRange?(["startRowId": rows[first].id, "endRowId": rows[last].id]) + setNeedsDisplayForVisibleBounds() + } + + private func nearestRangeLine(to index: Int) -> Int { + guard let first = rangeLineIndices.first, let last = rangeLineIndices.last else { return index } + let target = min(max(index, first), last) + var low = 0, high = rangeLineIndices.count + while low < high { + let middle = (low + high) / 2 + if rangeLineIndices[middle] < target { low = middle + 1 } else { high = middle } + } + return rangeLineIndices[min(low, rangeLineIndices.count - 1)] + } + + private func finishRangeDrag() { + isRangeDragging = false + parentScrollView?.panGestureRecognizer.isEnabled = true + } + + private func clearNativeRange() { + finishRangeDrag() + rangeStartIndex = nil + rangeEndIndex = nil + rangeLineIndices = [] + nativeSelectedRowIds = [] + } + + private func rangeHandleCenters() -> (CGPoint, CGPoint)? { + guard let start = rangeStartIndex, let end = rangeEndIndex, + rows.indices.contains(start), rows.indices.contains(end) else { return nil } + let first = min(start, end), last = max(start, end) + guard height(at: first) > 0, height(at: last) > 0 else { return nil } + let x = max(12, stickyWidth - 6) + return ( + CGPoint(x: x, y: rowOffsets[first] - verticalOffset), + CGPoint(x: x, y: rowOffsets[last] + height(at: last) - verticalOffset) + ) + } + + private func rangeHandle(at point: CGPoint) -> Bool? { + guard let (start, end) = rangeHandleCenters() else { return nil } + if hypot(point.x - start.x, point.y - start.y) <= 22 { return true } + if hypot(point.x - end.x, point.y - end.y) <= 22 { return false } + return nil + } + + @objc private func handleRangeHandlePan(_ gesture: UIPanGestureRecognizer) { + if gesture.state == .ended || gesture.state == .cancelled || gesture.state == .failed { + finishRangeDrag() + return + } + let point = gesture.location(in: self) + if gesture.state == .began, let movingStart = rangeHandle(at: point), + let start = rangeStartIndex, let end = rangeEndIndex { + rangeStartIndex = movingStart ? max(start, end) : min(start, end) + rangeEndIndex = movingStart ? min(start, end) : max(start, end) + isRangeDragging = true + parentScrollView?.panGestureRecognizer.isEnabled = false + } + if isRangeDragging, let start = rangeStartIndex, + let index = rowIndex(at: verticalOffset + point.y) { + updateNativeRange(start: start, end: nearestRangeLine(to: index)) + } } private func linePressPayload(for row: ReviewDiffNativeRow, gesture: String) -> [String: Any] { @@ -1643,8 +1831,15 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { let interactiveRects = fileHeaderInteractiveRects(for: row, cardRect: rect) let fileId = resolvedFileId(for: row) - if interactiveRects.checkbox.contains(point) { - onToggleViewedFile?(fileId) + if row.fileAction != nil, fileActionRect(in: rect).contains(point) { + if row.fileActionDisabled != true { onPressFileAction?(fileId, row.id) } + return + } + + // Keep the drawn mark small while giving it a full touch target in the file header. + let checkboxTouchRect = interactiveRects.checkbox.insetBy(dx: -12, dy: -12).intersection(rect) + if showViewedCheckbox && checkboxTouchRect.contains(point) { + if viewedCheckboxEnabled { onToggleViewedFile?(fileId) } return } @@ -2093,6 +2288,12 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { drawnRowCount += 1 } drawStickyFileHeader(context: context) + if let (start, end) = rangeHandleCenters() { + UIColor.systemBlue.setFill() + for point in [start, end] { + UIBezierPath(ovalIn: CGRect(x: point.x - 5, y: point.y - 5, width: 10, height: 10)).fill() + } + } maybeEmitDrawMetrics( drawnRowCount: drawnRowCount, @@ -2186,7 +2387,12 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { drawFileIcon(rect: interactiveRects.icon, changeType: row.changeType) - drawViewedCheckbox(rect: interactiveRects.checkbox, checked: viewedFileIds.contains(fileId)) + if showViewedCheckbox { + context.saveGState() + if !viewedCheckboxEnabled { context.setAlpha(0.4) } + drawViewedCheckbox(rect: interactiveRects.checkbox, checked: viewedFileIds.contains(fileId)) + context.restoreGState() + } let deletions = row.deletions ?? 0 let additions = row.additions ?? 0 @@ -2196,7 +2402,8 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { let addWidth = textWidth(addText, font: fileHeaderMetaFont) let countsGap = min(style.fileHeaderCountGap, 4) let countsWidth = deleteWidth + countsGap + addWidth - let countsX = interactiveRects.checkbox.minX - 10 - countsWidth + let countsRight = row.fileAction == nil ? interactiveRects.checkbox.minX : fileActionRect(in: cardRect).minX + let countsX = countsRight - 10 - countsWidth drawSingleLineText( deleteText, rect: CGRect(x: countsX, y: centerY - 9, width: deleteWidth, height: 18), @@ -2212,14 +2419,34 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { let pathLayout = fileHeaderPathLayout(for: row, cardRect: cardRect) let pathOffset = horizontalOffset(for: resolvedFileId(for: row), kind: .fileHeaderPath) - drawSingleLineText( - pathLayout.displayPath, - rect: pathLayout.rect, - color: theme.text, - font: fileHeaderFont, - horizontalOffset: pathOffset - ) + if let segments = row.renameSegments, !segments.isEmpty { + drawRenamePath(segments, rowId: row.id, rect: pathLayout.rect, horizontalOffset: pathOffset, context: context) + } else { + drawSingleLineText( + pathLayout.displayPath, + rect: pathLayout.rect, + color: theme.text, + font: fileHeaderFont, + horizontalOffset: pathOffset + ) + } drawFileHeaderPathScrollFade(row, pathRect: pathLayout.rect, horizontalOffset: pathOffset, context: context) + if let action = row.fileAction { + let button = fileActionRect(in: cardRect).insetBy(dx: 4, dy: 7) + context.setStrokeColor(theme.border.cgColor) + context.setLineWidth(1 / traitCollection.displayScale) + UIBezierPath(roundedRect: button, cornerRadius: 6).stroke() + drawCenteredText( + action, + rect: button, + color: row.fileActionDisabled == true ? theme.mutedText : theme.hunkText, + font: .systemFont(ofSize: 12, weight: .semibold) + ) + } + } + + private func fileActionRect(in rect: CGRect) -> CGRect { + CGRect(x: rect.maxX - 100, y: rect.minY, width: 94, height: rect.height) } private func drawNoticeRow(_ row: ReviewDiffNativeRow, rect: CGRect, context: CGContext) { @@ -2266,7 +2493,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { theme.background.setFill() context.fill(rect) - let isCollapsed = collapsedCommentIds.contains(row.id) + let isCollapsed = collapsedCommentIds.contains(row.id) || row.commentResolvedSummary != nil let cardInset = CGFloat(8) let cardRect = rect.insetBy(dx: cardInset, dy: 5) let cardPath = UIBezierPath(roundedRect: cardRect, cornerRadius: 10) @@ -2279,13 +2506,28 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { let chevronRect = CGRect(x: cardRect.minX + 10, y: cardRect.minY + 11, width: 16, height: 16) drawDisclosureChevron(rect: chevronRect, color: theme.mutedText, collapsed: isCollapsed) - let title = "Comment on \(row.commentRangeLabel ?? "line")" + let pending = row.commentPending == true + if pending { + let badge = CGRect(x: cardRect.maxX - 88, y: cardRect.minY + 7, width: 78, height: 24) + UIColor.systemOrange.withAlphaComponent(0.14).setFill() + UIBezierPath(roundedRect: badge, cornerRadius: 5).fill() + UIColor.systemOrange.setStroke() + let clock = CGRect(x: badge.minX + 6, y: badge.minY + 6, width: 12, height: 12) + let path = UIBezierPath(ovalIn: clock) + path.move(to: CGPoint(x: clock.midX, y: clock.minY + 3)) + path.addLine(to: CGPoint(x: clock.midX, y: clock.midY)) + path.addLine(to: CGPoint(x: clock.midX + 3, y: clock.midY + 1)) + path.lineWidth = 1 + path.stroke() + drawSingleLineText("Pending", rect: CGRect(x: badge.minX + 23, y: badge.minY + 3, width: 52, height: 18), color: UIColor.systemOrange, font: fileHeaderSubtextFont) + } + let title = row.commentResolvedSummary ?? "Comment on \(row.commentRangeLabel ?? "line")" drawSingleLineText( title, rect: CGRect( x: chevronRect.maxX + 10, y: cardRect.minY + 8, - width: max(24, cardRect.width - chevronRect.maxX - 28), + width: max(24, cardRect.maxX - chevronRect.maxX - (pending ? 98 : 28)), height: fileHeaderSubtextFont.lineHeight + 4 ), color: theme.mutedText, @@ -2324,12 +2566,13 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { let addWidth = textWidth("+\(additions)", font: fileHeaderMetaFont) let countsGap = min(style.fileHeaderCountGap, 4) let countsWidth = deleteWidth + countsGap + addWidth - let countsX = interactiveRects.checkbox.minX - 10 - countsWidth + let countsRight = row.fileAction == nil ? interactiveRects.checkbox.minX : fileActionRect(in: cardRect).minX + let countsX = countsRight - 10 - countsWidth let pathX = interactiveRects.icon.maxX + 10 let pathWidth = max(CGFloat(24), countsX - pathX - 12) let displayPath: String - if let previousPath = row.previousPath, previousPath != row.filePath, let filePath = row.filePath { - displayPath = "\(previousPath) -> \(filePath)" + if let segments = row.renameSegments, !segments.isEmpty { + displayPath = segments.map(\.text).joined() } else { displayPath = row.filePath ?? "" } @@ -2348,7 +2591,9 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { let horizontalPadding = style.fileHeaderHorizontalPadding let chevronRect = CGRect(x: cardRect.minX + horizontalPadding, y: centerY - 10, width: 20, height: 20) let iconRect = CGRect(x: chevronRect.maxX + 8, y: centerY - 10, width: 20, height: 20) - let checkboxRect = CGRect(x: cardRect.maxX - horizontalPadding - 20, y: centerY - 10, width: 20, height: 20) + let checkboxRect = showViewedCheckbox + ? CGRect(x: cardRect.maxX - horizontalPadding - 20, y: centerY - 10, width: 20, height: 20) + : CGRect(x: cardRect.maxX - horizontalPadding + 10, y: centerY, width: 0, height: 0) return ReviewDiffFileHeaderInteractiveRects( chevron: chevronRect, icon: iconRect, @@ -2496,7 +2741,13 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { .foregroundColor: color, .paragraphStyle: paragraphStyle, ] - (text as NSString).draw(in: rect, withAttributes: attributes) + (text as NSString).draw( + in: CGRect( + x: rect.minX, y: centeredTextY(in: rect, font: font), + width: rect.width, height: font.lineHeight + ), + withAttributes: attributes + ) } private func drawHunkRow(_ row: ReviewDiffNativeRow, rect: CGRect, context: CGContext) { @@ -2507,7 +2758,8 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { context.fill(rect) context.saveGState() - context.clip(to: CGRect(x: stickyWidth, y: rect.minY, width: max(0, viewportWidth - stickyWidth), height: style.rowHeight)) + let actionWidth: CGFloat = row.hunkAction == nil ? 0 : (row.hunkRevertAction == true ? 224 : 112) + context.clip(to: CGRect(x: stickyWidth, y: rect.minY, width: max(0, viewportWidth - stickyWidth - actionWidth), height: rect.height)) drawText( row.text ?? "", rect: CGRect( @@ -2520,6 +2772,31 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { font: hunkFont ) context.restoreGState() + if let action = row.hunkAction { + let button = hunkActionRect(in: rect).insetBy(dx: 6, dy: 6) + theme.headerBackground.setFill() + UIBezierPath(roundedRect: button, cornerRadius: 6).fill() + drawCenteredText(action, rect: button, color: row.hunkActionDisabled == true ? theme.mutedText : theme.hunkText, font: .systemFont(ofSize: 13, weight: .semibold)) + } + if row.hunkRevertAction == true { + let button = hunkRevertRect(in: rect).insetBy(dx: 6, dy: 6) + theme.headerBackground.setFill() + UIBezierPath(roundedRect: button, cornerRadius: 6).fill() + drawCenteredText( + "Revert hunk", + rect: button, + color: row.hunkRevertActionDisabled == true ? theme.mutedText : theme.deleteText, + font: .systemFont(ofSize: 13, weight: .semibold) + ) + } + } + + private func hunkActionRect(in rect: CGRect) -> CGRect { + CGRect(x: viewportWidth - 112, y: rect.minY, width: 112, height: rect.height) + } + + private func hunkRevertRect(in rect: CGRect) -> CGRect { + CGRect(x: viewportWidth - 224, y: rect.minY, width: 112, height: rect.height) } private func drawCodeRow(_ row: ReviewDiffNativeRow, rect: CGRect, context: CGContext) { @@ -2657,10 +2934,12 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { rect: CGRect, context: CGContext ) { - guard selectedRowIds.contains(row.id) else { + guard selectedRowIds.contains(row.id) || nativeSelectedRowIds.contains(row.id) else { return } + UIColor.systemBlue.withAlphaComponent(0.1).setFill() + context.fill(rect) theme.hunkText.withAlphaComponent(0.95).setFill() context.fill(CGRect(x: 0, y: rect.minY, width: style.changeBarWidth, height: rect.height)) } @@ -2780,6 +3059,33 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { rect.midY - font.lineHeight / 2 } + private func drawRenamePath( + _ segments: [ReviewDiffRenameSegment], rowId: String, rect: CGRect, + horizontalOffset: CGFloat, context: CGContext + ) { + let text: NSAttributedString + if let cached = renameAttributedStringsByRowId[rowId] { + text = cached + } else { + let result = NSMutableAttributedString(string: "") + for segment in segments { + var attributes: [NSAttributedString.Key: Any] = [ + .font: fileHeaderFont, .ligature: 0, + .foregroundColor: segment.kind == "context" ? theme.mutedText : theme.text + ] + if segment.kind == "removed" { attributes[.backgroundColor] = theme.deleteBackground } + if segment.kind == "added" { attributes[.backgroundColor] = theme.addBackground } + result.append(NSAttributedString(string: segment.text, attributes: attributes)) + } + renameAttributedStringsByRowId[rowId] = result + text = result + } + context.saveGState() + context.clip(to: rect) + text.draw(at: CGPoint(x: rect.minX - horizontalOffset, y: rect.midY - fileHeaderFont.lineHeight / 2)) + context.restoreGState() + } + private func drawSingleLineText( _ text: String, rect: CGRect, diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index 7b81d0880a401..5506453e21b87 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -1,6 +1,6 @@ import { isDraftThreadRoute } from "./features/threads/thread-route-state"; import { ComponentCatalogScreen } from "./features/development/ComponentCatalogScreen"; -import { PullRequestGuideStopScreen } from "./features/pull-requests/guide/PullRequestGuideScreen"; +import { PullRequestGuideStopScreen } from "./features/pull-requests/guide/PullRequestGuideChapterScreen"; import { PullRequestInlineCommentScreen } from "./features/pull-requests/PullRequestInlineCommentScreen"; import { PullRequestDiscussionScreen } from "./features/pull-requests/PullRequestDiscussionScreen"; import { createWorkspaceStackNavigator } from "./features/layout/createWorkspaceStackNavigator"; @@ -51,13 +51,17 @@ import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRo import { ConnectOnboardingRouteScreen } from "./features/cloud/ConnectOnboardingRouteScreen"; import { AttachmentFileScreen } from "./features/files/AttachmentFileScreen"; import { ThreadFilesTreeScreen, ThreadFileScreen } from "./features/files/ThreadFilesRouteScreen"; +import { + ThreadFilesWorkspaceScreen, + ThreadGitWorkspaceScreen, + ThreadFileWorkspaceScreen, +} from "./features/layout/workspace/ThreadWorkspaceScreen"; import { AdaptiveWorkspaceLayout } from "./features/layout/AdaptiveWorkspaceLayout"; import { HardwareKeyboardCommandOverlay, HardwareKeyboardCommandProvider, } from "./features/keyboard/HardwareKeyboardCommandProvider"; import { ReviewCommentComposerSheet } from "./features/review/ReviewCommentComposerSheet"; -import { ReviewSheet } from "./features/review/ReviewSheet"; import { ThreadTerminalRouteScreen } from "./features/terminal/ThreadTerminalRouteScreen"; import { DevicePreviewRouteScreen } from "./features/devices/DevicePreviewRouteScreen"; import { BrowserPreviewRouteScreen } from "./features/browser/BrowserPreviewRouteScreen"; @@ -676,22 +680,27 @@ const RootStackConfig = createWorkspaceStackNavigator({ options: { ...modalRoute({ header: "solid" }), gestureEnabled: false }, }), ThreadReview: createNativeStackScreen({ - screen: ReviewSheet, + screen: ThreadGitWorkspaceScreen, linking: `${THREAD_LINKING_PREFIX}/review`, options: pageRoute(), }), + ThreadReviewFile: createNativeStackScreen({ + screen: ThreadGitWorkspaceScreen, + linking: `${THREAD_LINKING_PREFIX}/review/file`, + options: pageRoute(), + }), ThreadReviewComment: createNativeStackScreen({ screen: ReviewCommentComposerSheet, linking: `${THREAD_LINKING_PREFIX}/review-comment`, options: sheetRoute({ detent: 0.55, android: "fullScreen" }), }), ThreadFiles: createNativeStackScreen({ - screen: ThreadFilesTreeScreen, + screen: ThreadFilesWorkspaceScreen, linking: `${THREAD_LINKING_PREFIX}/files`, options: pageRoute({ title: "Files" }), }), ThreadFile: createNativeStackScreen({ - screen: ThreadFileScreen, + screen: ThreadFileWorkspaceScreen, linking: `${THREAD_LINKING_PREFIX}/files/:path*`, options: pageRoute(), }), diff --git a/apps/mobile/src/components/DiffDisclosureIcons.tsx b/apps/mobile/src/components/DiffDisclosureIcons.tsx new file mode 100644 index 0000000000000..918d0ba1ca378 --- /dev/null +++ b/apps/mobile/src/components/DiffDisclosureIcons.tsx @@ -0,0 +1,50 @@ +import type { IconProps } from "@tabler/icons-react-native/types"; +import { forwardRef } from "react"; +import Svg, { Path } from "react-native-svg"; + +// Match the paired chevrons used by the desktop diff controls. +export const DiffCollapseIcon = forwardRef(function DiffCollapseIcon( + { size = 24, color = "currentColor", strokeWidth = 2, ...props }, + ref, +) { + return ( + + + + + ); +}); + +export const DiffExpandIcon = forwardRef(function DiffExpandIcon( + { size = 24, color = "currentColor", strokeWidth = 2, ...props }, + ref, +) { + return ( + + + + + ); +}); diff --git a/apps/mobile/src/components/ui/AppSymbol.android.tsx b/apps/mobile/src/components/ui/AppSymbol.android.tsx index 5333af3ea577a..0d10fba4db731 100644 --- a/apps/mobile/src/components/ui/AppSymbol.android.tsx +++ b/apps/mobile/src/components/ui/AppSymbol.android.tsx @@ -1,3 +1,8 @@ +import IconPaperclip from "@tabler/icons-react-native/IconPaperclip"; +import IconSquare from "@tabler/icons-react-native/IconSquare"; +import IconSquareCheckFilled from "@tabler/icons-react-native/IconSquareCheckFilled"; +import IconSparkles from "@tabler/icons-react-native/IconSparkles"; +import { DiffCollapseIcon, DiffExpandIcon } from "../DiffDisclosureIcons"; import type { Icon } from "@tabler/icons-react-native/types"; /* Package-root imports eagerly register the entire Tabler icon set in Metro. */ import IconAdjustmentsHorizontal from "@tabler/icons-react-native/IconAdjustmentsHorizontal"; @@ -209,6 +214,12 @@ const ANDROID_ICON_BY_SF_SYMBOL = { "doc.on.doc": IconCopy, "doc.text": IconFileText, "file.diff": IconFileDiff, + "diff.collapse": DiffCollapseIcon, + "diff.expand": DiffExpandIcon, + paperclip: IconPaperclip, + square: IconSquare, + "checkmark.square.fill": IconSquareCheckFilled, + sparkles: IconSparkles, ellipsis: IconDots, moon: IconMoon, "ellipsis.circle": IconDotsCircleHorizontal, @@ -305,7 +316,8 @@ const ANDROID_ICON_BY_SF_SYMBOL = { | "git.pull-request.closed" | "git.pull-request.draft" | "git.commit" - | "git.issue" + | "diff.collapse" + | "diff.expand" | "file.diff" | "robot", Icon @@ -317,7 +329,8 @@ const SF_ICON_LOOKUP: Partial< | "git.pull-request.closed" | "git.pull-request.draft" | "git.commit" - | "git.issue" + | "diff.collapse" + | "diff.expand" | "file.diff" | "robot", Icon diff --git a/apps/mobile/src/components/ui/AppSymbol.tsx b/apps/mobile/src/components/ui/AppSymbol.tsx index 896765db5d233..6172ba75a5466 100644 --- a/apps/mobile/src/components/ui/AppSymbol.tsx +++ b/apps/mobile/src/components/ui/AppSymbol.tsx @@ -1,3 +1,4 @@ +import { DiffCollapseIcon, DiffExpandIcon } from "../DiffDisclosureIcons"; import IconGitBranch from "@tabler/icons-react-native/IconGitBranch"; import IconGitMerge from "@tabler/icons-react-native/IconGitMerge"; import IconGitCommit from "@tabler/icons-react-native/IconGitCommit"; @@ -26,6 +27,8 @@ const CUSTOM_ICONS = { "git.commit": IconGitCommit, "git.issue": IconCircleDot, robot: IconRobot, + "diff.collapse": DiffCollapseIcon, + "diff.expand": DiffExpandIcon, }; function AppSymbolView(props: AppSymbolViewProps) { diff --git a/apps/mobile/src/components/ui/SegmentedControl.types.ts b/apps/mobile/src/components/ui/SegmentedControl.types.ts index 472ed46b0e2f2..538643568b65b 100644 --- a/apps/mobile/src/components/ui/SegmentedControl.types.ts +++ b/apps/mobile/src/components/ui/SegmentedControl.types.ts @@ -1,12 +1,16 @@ +import type { AppSymbolName } from "./AppSymbol"; + export interface SegmentedControlProps { readonly options: readonly { readonly value: Value; readonly label: string; + readonly badge?: number; readonly accessibilityLabel?: string; + readonly icon?: AppSymbolName; }[]; readonly selected: Value; readonly onSelect: (value: Value) => void; - /** Compact uses a 32-point capsule; default uses 36 points on iOS and 40 on Android. */ + /** Sizing applies to the non-Material control. */ readonly size?: "default" | "compact"; readonly variant?: "standalone" | "card"; readonly role?: "tab" | "button"; diff --git a/apps/mobile/src/components/ui/Tabs.tsx b/apps/mobile/src/components/ui/Tabs.tsx new file mode 100644 index 0000000000000..931769180c909 --- /dev/null +++ b/apps/mobile/src/components/ui/Tabs.tsx @@ -0,0 +1,102 @@ +import { GlassView } from "expo-glass-effect"; +import { useEffect, useRef, useState, type ComponentRef, type ReactNode } from "react"; +import { Pressable, ScrollView, View } from "react-native"; +import Animated, { useAnimatedStyle, useReducedMotion, withTiming } from "react-native-reanimated"; +import { withUniwind } from "uniwind"; + +import { cn } from "../../lib/cn"; +import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass"; +import { useAppearancePreferences } from "../../features/settings/appearance/AppearancePreferencesProvider"; +import { AppText } from "./AppText"; + +const TabGlass = withUniwind(GlassView, { style: { fromClassName: "className" } }); + +export interface TabsProps { + readonly options: readonly { + readonly value: Value; + readonly label: string; + /** Rendered after the label, such as diff stats or a count. */ + readonly trailing?: ReactNode; + }[]; + readonly selected: Value; + readonly onSelect: (value: Value) => void; + readonly className?: string; +} + +/** Section navigation. Value pickers use SegmentedControl. */ +export function Tabs(props: TabsProps) { + const { themeAppearance } = useAppearancePreferences(); + const reduceMotion = useReducedMotion(); + const scrollView = useRef>(null); + const [frames, setFrames] = useState>>({}); + const frame = frames[props.selected]; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the selected tab visible in the native scroll viewport + useEffect(() => { + if (frame) scrollView.current?.scrollTo({ x: frame.x, animated: false }); + }, [frame]); + const duration = reduceMotion ? 0 : 220; + const indicatorStyle = useAnimatedStyle(() => ({ + width: withTiming(frame?.width ?? 0, { duration }), + transform: [{ translateX: withTiming(frame?.x ?? 0, { duration }) }], + })); + + return ( + + + {frame ? ( + + {NATIVE_LIQUID_GLASS_SUPPORTED ? ( + + ) : ( + + )} + + ) : null} + {props.options.map((option) => { + const selected = option.value === props.selected; + return ( + props.onSelect(option.value)} + onLayout={({ nativeEvent: { layout } }) => + setFrames((current) => + current[option.value]?.x === layout.x && + current[option.value]?.width === layout.width + ? current + : { ...current, [option.value]: { x: layout.x, width: layout.width } }, + ) + } + className="min-h-11 shrink-0 flex-row items-center gap-1.5 rounded-full px-3.5 active:opacity-70" + > + + {option.label} + + {option.trailing} + + ); + })} + + + ); +} diff --git a/apps/mobile/src/components/ui/segmentedControlColors.ts b/apps/mobile/src/components/ui/segmentedControlColors.ts index 6b58675726e4f..b612e9b1f006d 100644 --- a/apps/mobile/src/components/ui/segmentedControlColors.ts +++ b/apps/mobile/src/components/ui/segmentedControlColors.ts @@ -28,10 +28,11 @@ export function segmentedControlColors( colors["--color-grouped-card"], ) : flattenThemeColor(themeColorWithAlpha(accent, dark ? 0.1 : 0.07), colors["--color-screen"]); - let selectedColor = colors["--color-secondary"]; + // The thumb must lift off the track: --color-secondary nearly matches it in light themes. + let selectedColor = dark && card ? colors["--color-secondary"] : colors["--color-card"]; if (card && !dark) selectedColor = colors["--color-screen"]; if (dark && (!card || themeId === "t3-code")) { - selectedColor = flattenThemeColor(themeColorWithAlpha(accent, 0.32), colors["--color-screen"]); + selectedColor = flattenThemeColor(themeColorWithAlpha(accent, 0.2), colors["--color-screen"]); } let selectedTextColor = colors[!card && dark ? "--color-foreground" : "--color-secondary-foreground"]; diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts index 2699bb995406c..e628bc077797c 100644 --- a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts +++ b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts @@ -29,6 +29,10 @@ export interface NativeReviewDiffRow { readonly fileId?: string; readonly filePath?: string; readonly previousPath?: string | null; + readonly renameSegments?: ReadonlyArray<{ + readonly text: string; + readonly kind: "unchanged" | "removed" | "added" | "context"; + }>; readonly changeType?: | "modified" | "new" @@ -46,13 +50,15 @@ export interface NativeReviewDiffRow { readonly wordDiffRanges?: ReadonlyArray; readonly commentText?: string; readonly commentRangeLabel?: string; + readonly commentPending?: boolean; + readonly commentResolvedSummary?: string; readonly commentSectionTitle?: string; - /** A notice drawn in the warning colors. */ - readonly tone?: "warning"; - /** A notice that reports taps through `onPressNotice`. */ - readonly actionable?: boolean; - /** Where a cut line's note starts in `content`. */ - readonly noteStart?: number; + readonly hunkAction?: "Stage hunk" | "Unstage hunk"; + readonly hunkActionDisabled?: boolean; + readonly hunkRevertAction?: boolean; + readonly hunkRevertActionDisabled?: boolean; + readonly fileAction?: "Stage file" | "Unstage file"; + readonly fileActionDisabled?: boolean; } export interface NativeReviewDiffWordDiffRange { @@ -128,6 +134,9 @@ export interface NativeReviewDiffViewProps extends ViewProps { readonly collapsedFileIdsJson?: string; readonly viewedFileIdsJson?: string; readonly selectedRowIdsJson?: string; + readonly enableLineRangeSelection?: boolean; + readonly showViewedCheckbox?: boolean; + readonly viewedCheckboxEnabled?: boolean; readonly collapsedCommentIdsJson?: string; readonly appearanceScheme: "light" | "dark"; readonly themeJson: string; @@ -148,6 +157,12 @@ export interface NativeReviewDiffViewProps extends ViewProps { ) => void; readonly onToggleFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void; readonly onToggleViewedFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void; + readonly onPressHunk?: ( + event: NativeSyntheticEvent<{ readonly rowId?: string; readonly action?: "stage" | "revert" }>, + ) => void; + readonly onPressFileAction?: ( + event: NativeSyntheticEvent<{ readonly fileId?: string; readonly rowId?: string }>, + ) => void; readonly onPressLine?: ( event: NativeSyntheticEvent<{ readonly rowId?: string; @@ -158,6 +173,9 @@ export interface NativeReviewDiffViewProps extends ViewProps { readonly change?: "context" | "add" | "delete"; }>, ) => void; + readonly onSelectLineRange?: ( + event: NativeSyntheticEvent<{ readonly startRowId: string; readonly endRowId: string }>, + ) => void; readonly onToggleComment?: (event: NativeSyntheticEvent<{ readonly commentId?: string }>) => void; readonly onPressNotice?: ( event: NativeSyntheticEvent<{ readonly rowId?: string; readonly fileId?: string }>, diff --git a/apps/mobile/src/features/files/FileTreeBrowser.tsx b/apps/mobile/src/features/files/FileTreeBrowser.tsx index 24d82a93daa79..3e2fa95558a37 100644 --- a/apps/mobile/src/features/files/FileTreeBrowser.tsx +++ b/apps/mobile/src/features/files/FileTreeBrowser.tsx @@ -4,9 +4,9 @@ import { LegendList } from "@legendapp/list/react-native"; import type { ProjectEntry } from "@t3tools/contracts"; import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; import { SymbolView } from "../../components/ui/AppSymbol"; -import { useEffect, useRef, useState } from "react"; -import { Pressable, View } from "react-native"; -import { RefreshControl } from "../../components/ui/RefreshControl"; +import { useEffect, useRef, useState, type ReactNode } from "react"; +import { Platform, Pressable, RefreshControl, View } from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; import { AppText as Text } from "../../components/ui/AppText"; import { PierreEntryIcon } from "../../components/PierreEntryIcon"; @@ -116,6 +116,8 @@ export function FileTreeBrowser(props: { readonly onPreviewFile?: (path: string) => void; readonly onRefresh: () => void; readonly onSelectFile: (path: string) => void; + readonly toolbar?: ReactNode; + readonly pinnedToolbar?: boolean; }) { const { expandedPaths, setExpandedPaths } = props; const [pendingSelection, setPendingSelection] = useState<{ @@ -213,11 +215,11 @@ export function FileTreeBrowser(props: { const extraData = { expandedPaths, loadingDirectories, selectedPath }; // Keep the list as direct screen content so UIKit can apply header insets. - return ( + const list = ( } renderItem={renderItem} ListHeaderComponent={ <> + {props.pinnedToolbar ? null : props.toolbar} {props.error && props.entries.length > 0 ? ( {props.error} @@ -285,4 +292,12 @@ export function FileTreeBrowser(props: { } /> ); + return props.pinnedToolbar ? ( + + {props.toolbar} + {list} + + ) : ( + list + ); } diff --git a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx index 6de31137fb7d4..284a490885d13 100644 --- a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx +++ b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx @@ -20,6 +20,7 @@ import { } from "@t3tools/shared/filePreview"; import { mediaFileReference } from "@t3tools/client-runtime/media-reference"; +import { AppTextInput } from "../../components/ui/AppText"; import { ScreenContent } from "../../components/ui/ScreenContent"; import { filePreviewDelimiter, parseDelimitedPreview } from "@t3tools/shared/delimitedPreview"; import { DelimitedFilePreview } from "./DelimitedFilePreview"; @@ -250,7 +251,7 @@ function FileContent(props: { readonly threadId: ThreadId | null; readonly initialLine: number | null; readonly truncated: boolean; - readonly selectable: boolean; + readonly headerReserved?: boolean; readonly onRefresh?: () => Promise | void; }) { // Reopening a mutable host file must not reuse a poster from an earlier visit. @@ -351,8 +352,7 @@ function FileContent(props: { contents={props.fileContents} path={props.relativePath} initialLine={props.initialLine} - headerInsetTop={props.truncated ? 0 : undefined} - selectable={props.selectable} + headerInsetTop={props.truncated || props.headerReserved ? 0 : undefined} onRefresh={props.onRefresh} /> )} @@ -458,7 +458,12 @@ function FilesToolbarBottomFade() { ); } -export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) { +export function ThreadFilesTreeScreen( + props: ThreadFilesRouteScreenProps & { + readonly workspaceTabs?: ReactNode; + readonly workspaceHeader?: ReactNode; + }, +) { const navigation = useNavigation(); const { fileInspector } = useWorkspacePaneState(); const [searchQuery, setSearchQuery] = useState(""); @@ -525,6 +530,7 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) { projectName={projectName} selectedPath={null} onSelectFile={handleSelectFile} + toolbar={props.workspaceTabs} /> ) : null; const handlePreviewFile = (relativePath: string) => { @@ -576,15 +582,17 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) { ); } - return ( - - + const content = ( + <> + {props.workspaceHeader ?? ( + + )} + {props.workspaceTabs} + + + + + ) : ( + props.workspaceTabs + ) + } /> - + ); + return {content}; } -export function ThreadFileScreen(props: ThreadFileRouteScreenProps) { +export function ThreadFileScreen( + props: ThreadFileRouteScreenProps & { readonly workspaceTabs?: ReactNode }, +) { const navigation = useNavigation(); const { fileInspector } = useWorkspacePaneState(); const { appearance, setCodeWordBreak } = useAppearancePreferences(); @@ -1045,6 +1077,15 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) { actions={fileMenuActions} /> + {props.workspaceTabs ? ( + + {props.workspaceTabs} + + ) : null} fileQuery.refresh()} /> diff --git a/apps/mobile/src/features/files/thread-file-navigator-pane.tsx b/apps/mobile/src/features/files/thread-file-navigator-pane.tsx index cc0c86e6d3e4b..a2ee6d05adfff 100644 --- a/apps/mobile/src/features/files/thread-file-navigator-pane.tsx +++ b/apps/mobile/src/features/files/thread-file-navigator-pane.tsx @@ -3,8 +3,15 @@ import { environmentSession } from "../../state/session"; import type { EnvironmentId } from "@t3tools/contracts"; import { AppBar } from "../../components/ui/AppBar"; import { ScreenContent } from "../../components/ui/ScreenContent"; -import { useState } from "react"; -import { SheetPane } from "../../components/ui/SheetPane"; +import { useState, type ComponentProps, type ReactNode } from "react"; +import { Platform, Pressable, View, type NativeSyntheticEvent } from "react-native"; +import { + Screen, + ScreenStack, + ScreenStackHeaderConfig, + ScreenStackHeaderSearchBarView, + SearchBar, +} from "react-native-screens"; import { useEnvironmentQuery } from "../../state/query"; import { useEnvironmentPresentation } from "../../state/presentation"; @@ -19,6 +26,7 @@ export function ThreadFileNavigatorPane(props: { readonly projectName: string; readonly selectedPath: string | null; readonly onSelectFile: (path: string) => void; + readonly toolbar?: ReactNode; }) { const workspaceKey = JSON.stringify([props.environmentId, props.cwd]); // The pane stays mounted across thread switches; a query only filters the workspace it was typed in. @@ -78,6 +86,7 @@ export function ThreadFileNavigatorPane(props: { entriesQuery.selectPath(path); props.onSelectFile(path); }} + toolbar={props.toolbar} /> ); diff --git a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx index a90ba87eedda2..17e5672a2b69e 100644 --- a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx +++ b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx @@ -84,6 +84,10 @@ import { } from "./workspace/workspace-detail-selection"; import { startOpeningDetail } from "./workspace/useSelectWorkspaceDetail"; import { useWorkspaceTabs } from "./workspace/WorkspaceTabsContext"; +import { + rememberedThreadWorkspaceNavigationState, + useRememberThreadWorkspaceLocation, +} from "./workspace/threadWorkspaceNavigationMemory"; import { HomeListOptionsProvider } from "../home/home-list-options"; import { buildHomeProjectScopes, resolveHomeProjectFilterScope } from "../home/homeThreadList"; import { newTaskDestination, newTaskFilteredProject } from "../threads/new-task-project-selection"; @@ -272,6 +276,7 @@ function AdaptiveWorkspaceLayoutContent( const workspacePage = Platform.OS === "android" && (androidSettingsOpen || workspace?.state.selectedTab === "usage"); const navigation = useNavigation(); + useRememberThreadWorkspaceLocation(); const [primarySidebarPreferredVisible, setPrimarySidebarPreferredVisible] = useState(true); const [fileInspectorPreferredVisible, setFileInspectorPreferredVisible] = useState(true); const [nativeInspectorWidthFraction, setNativeInspectorWidthFraction] = useState(0.4); @@ -575,7 +580,20 @@ function AdaptiveWorkspaceLayoutContent( if (layout.variant === "medium") setPrimarySidebarVisible(false); workspace?.dispatch({ type: "select", tab: workspaceTabOf(detail.name) }); startOpeningDetail(detail); - navigation.dispatch(selectWorkspaceDetail(detail, sheet)); + const state = rootStackState(navigation); + const remembered = + detail.name === "Thread" && !sheet && detail.params?.environmentId && detail.params.threadId + ? rememberedThreadWorkspaceNavigationState( + state, + { + environmentId: detail.params.environmentId, + threadId: detail.params.threadId, + }, + true, + ) + : null; + if (state && remembered) dispatchRootStackReset(navigation, state, remembered); + else navigation.dispatch(selectWorkspaceDetail(detail, sheet)); }); } const handleSelectThreadRoute = (params: ReactNavigation.RootParamList["Thread"]) => diff --git a/apps/mobile/src/features/layout/workspace/ThreadWorkspaceScreen.tsx b/apps/mobile/src/features/layout/workspace/ThreadWorkspaceScreen.tsx new file mode 100644 index 0000000000000..7a40d3b7b9c52 --- /dev/null +++ b/apps/mobile/src/features/layout/workspace/ThreadWorkspaceScreen.tsx @@ -0,0 +1,244 @@ +import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem"; +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { useNavigation, type StaticScreenProps } from "@react-navigation/native"; +import { useState } from "react"; +import { View } from "react-native"; +import { AppActivityIndicator } from "../../../components/ui/AppActivityIndicator"; +import { + readWorkspacePane, + rememberWorkspacePane, + resolveWorkspacePane, + rememberThreadWorkspaceLocation, + readThreadReviewSelection, + workspaceThreadMemoryKey, + type WorkspacePane, +} from "./workspacePaneMemory"; +import { Tabs } from "../../../components/ui/Tabs"; +import { useEnvironmentQuery } from "../../../state/query"; +import { useEnvironmentPresentation } from "../../../state/presentation"; +import { vcsEnvironment } from "../../../state/vcs"; +import { environmentSession } from "../../../state/session"; +import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions"; +import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state"; +import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-worktree"; +import { useThreadSelection } from "../../../state/use-thread-selection"; +import { ThreadFilesTreeScreen, ThreadFileScreen } from "../../files/ThreadFilesRouteScreen"; +import { PullRequestDiffStats } from "../../pull-requests/PullRequestPresentation"; +import { ThreadGitSplitButton } from "../../threads/threadGitActions"; +import { ReviewHeader, ReviewSheet } from "../../review/ReviewSheet"; + +type Props = StaticScreenProps<{ + readonly environmentId: string; + readonly threadId: string; + readonly path?: string[]; + readonly line?: string; + readonly cwd?: string; + readonly projectName?: string; + readonly reviewSectionId?: string; + readonly reviewFilePath?: string; + readonly reviewWorkingTreeScope?: "staged" | "unstaged"; +}>; + +function ThreadWorkspaceScreen(props: Props & { readonly defaultPane?: WorkspacePane }) { + const navigation = useNavigation(); + const paneKey = workspaceThreadMemoryKey( + props.route.params.environmentId, + props.route.params.threadId, + ); + const [tab, setTab] = useState(() => + props.route.params.path + ? "files" + : props.route.params.reviewSectionId + ? "git" + : (props.defaultPane ?? readWorkspacePane(paneKey)), + ); + const environmentId = EnvironmentId.make(props.route.params.environmentId); + const threadId = ThreadId.make(props.route.params.threadId); + const { selectedThreadCwd: cwd } = useSelectedThreadWorktree(); + const session = useEnvironmentQuery(environmentSession.sessionStateAtom(environmentId)); + const environment = useEnvironmentPresentation(environmentId); + const access = resolveFilesystemReadAccess({ + isCatalogReady: environment.isReady, + connection: environment.presentation?.connection ?? null, + session: session.data, + sessionError: session.error, + }); + const status = useEnvironmentQuery( + access.canReadFiles && cwd !== null + ? vcsEnvironment.status({ environmentId, input: { cwd } }) + : null, + ); + // Status counts each changed path once, including edits that cancel between + // the index and working tree, and updates through the existing Git subscription. + const count = status.data?.workingTree?.files.length; + const statusUnavailable = + !access.isPending && (!access.canReadFiles || cwd === null || status.error !== null); + const selectedTab = resolveWorkspacePane(tab, count ?? (statusUnavailable ? 0 : undefined)); + if (selectedTab !== null && selectedTab !== tab) { + setTab(selectedTab); + rememberWorkspacePane(paneKey, selectedTab); + } + const selectTab = (pane: WorkspacePane) => { + setTab(pane); + rememberWorkspacePane(paneKey, pane); + const params = props.route.params; + if (pane === "files") { + rememberThreadWorkspaceLocation({ + name: params.path ? "ThreadFile" : "ThreadFiles", + params: { + environmentId: params.environmentId, + threadId: params.threadId, + ...(params.path ? { path: params.path } : {}), + ...(params.line ? { line: params.line } : {}), + ...(params.cwd ? { cwd: params.cwd } : {}), + ...(params.projectName ? { projectName: params.projectName } : {}), + }, + }); + } else { + const sectionId = params.reviewSectionId ?? readThreadReviewSelection(paneKey)?.sectionId; + rememberThreadWorkspaceLocation({ + name: + params.reviewFilePath || params.reviewWorkingTreeScope + ? "ThreadReviewFile" + : "ThreadReview", + params: { + environmentId: params.environmentId, + threadId: params.threadId, + ...(sectionId ? { reviewSectionId: sectionId } : {}), + ...(params.reviewFilePath ? { reviewFilePath: params.reviewFilePath } : {}), + ...(params.reviewWorkingTreeScope + ? { reviewWorkingTreeScope: params.reviewWorkingTreeScope } + : {}), + }, + }); + } + }; + const workingTree = status.data?.workingTree; + const { selectedThread } = useThreadSelection(); + const gitState = useSelectedThreadGitState(); + const gitActions = useSelectedThreadGitActions(); + // The selection-based git hooks only apply when this workspace belongs to the selected thread. + const gitActionsAvailable = + selectedThread !== null && String(selectedThread.id) === String(threadId); + const tabs = ( + + 0 || workingTree.deletions > 0) ? ( + + ) : undefined, + }, + { value: "files" as const, label: "Files" }, + ]} + selected={selectedTab ?? "files"} + onSelect={selectTab} + /> + + {gitActionsAvailable ? ( + + ) : null} + + ); + const workspaceHeader = ( + status.refresh()} + onReturnToThread={() => navigation.goBack()} + /> + ); + if (selectedTab === null) + return ( + + {workspaceHeader} + {tabs} + + + + + ); + return selectedTab === "files" ? ( + props.route.params.path ? ( + + ) : ( + + ) + ) : ( + + ); +} + +export function ThreadFilesWorkspaceScreen(props: Props) { + return ( + + ); +} + +export function ThreadGitWorkspaceScreen(props: Props) { + return ( + + ); +} + +export function ThreadFileWorkspaceScreen(props: Parameters[0]) { + const { threadId } = props.route.params; + if (!threadId) return ; + return ( + + ); +} diff --git a/apps/mobile/src/features/layout/workspace/threadWorkspaceNavigationMemory.test.ts b/apps/mobile/src/features/layout/workspace/threadWorkspaceNavigationMemory.test.ts new file mode 100644 index 0000000000000..4f88072f4ca92 --- /dev/null +++ b/apps/mobile/src/features/layout/workspace/threadWorkspaceNavigationMemory.test.ts @@ -0,0 +1,169 @@ +import * as NodeModule from "node:module"; +import { describe, expect, it, vi } from "vite-plus/test"; +import type { + StackNavigationState, + StackRouter as StackRouterType, +} from "@react-navigation/native"; + +vi.mock("@react-navigation/native", () => ({ useNavigation: vi.fn() })); + +import { + isFocusedThreadWorkspace, + rememberFocusedThreadWorkspace, + rememberedThreadWorkspaceNavigationState, +} from "./threadWorkspaceNavigationMemory"; +import { readThreadWorkspaceLocation } from "./workspacePaneMemory"; + +function loadRouters() { + const require = NodeModule.createRequire(import.meta.url); + const nativePackage = require.resolve("@react-navigation/native/package.json"); + const requireFromNative = NodeModule.createRequire(nativePackage); + const corePackage = requireFromNative.resolve("@react-navigation/core/package.json"); + const requireFromCore = NodeModule.createRequire(corePackage); + return requireFromCore("@react-navigation/routers") as { + readonly CommonActions: typeof import("@react-navigation/native").CommonActions; + readonly StackActions: typeof import("@react-navigation/native").StackActions; + readonly StackRouter: typeof StackRouterType; + }; +} + +const { CommonActions, StackActions, StackRouter } = loadRouters(); +const router = StackRouter({}); +const routeNames = [ + "Home", + "Thread", + "ThreadReview", + "ThreadReviewFile", + "ThreadFiles", + "ThreadFile", + "ThreadReviewComment", +]; +const options = { + routeNames, + routeParamList: Object.fromEntries(routeNames.map((name) => [name, undefined])), + routeGetIdList: {}, +}; +type State = StackNavigationState>; +const initial = () => router.getInitialState(options); +function apply(state: State, action: Parameters[1]) { + const next = router.getStateForAction(state, action, options); + if (!next) throw new Error("Router rejected the navigation action"); + return next as State; +} +const identity = (environmentId: string, threadId: string) => ({ environmentId, threadId }); + +function openReviewFile( + state: State, + params: { environmentId: string; threadId: string }, + scope: "staged" | "unstaged" = "unstaged", +) { + let next = apply(state, StackActions.push("Thread", params)); + next = apply(next, StackActions.push("ThreadReview", params)); + return apply( + next, + StackActions.push("ThreadReviewFile", { + ...params, + reviewSectionId: "git:working-tree", + reviewFilePath: "src/rates.ts", + reviewWorkingTreeScope: scope, + }), + ); +} + +describe("native per-thread workspace restoration", () => { + it("restores a diff above its own chat/tree and remembers explicit Back to tree then chat", () => { + const first = identity("restore-env", "thread-a"); + const second = identity("restore-env", "thread-b"); + const opened = openReviewFile(initial(), first, "staged"); + rememberFocusedThreadWorkspace(opened); + let switched = apply(initial(), StackActions.push("Thread", second)); + rememberFocusedThreadWorkspace(switched); + const restored = rememberedThreadWorkspaceNavigationState(switched, first); + expect(restored).not.toBeNull(); + switched = apply(switched, CommonActions.reset(restored!)); + expect(switched.routes.map((route) => route.name)).toEqual([ + "Home", + "Thread", + "ThreadReview", + "ThreadReviewFile", + ]); + expect(switched.routes[1]?.params).toEqual(first); + expect(switched.routes.at(-1)?.params).toMatchObject({ + ...first, + reviewSectionId: "git:working-tree", + reviewFilePath: "src/rates.ts", + reviewWorkingTreeScope: "staged", + }); + + const backToTree = apply(switched, StackActions.pop()); + rememberFocusedThreadWorkspace(backToTree); + const treeRestored = apply( + backToTree, + CommonActions.reset(rememberedThreadWorkspaceNavigationState(backToTree, first)!), + ); + expect(treeRestored.routes.at(-1)?.name).toBe("ThreadReview"); + expect(treeRestored.routes.at(-1)?.params).not.toHaveProperty("reviewFilePath"); + + const backToChat = apply(backToTree, StackActions.pop()); + rememberFocusedThreadWorkspace(backToChat); + expect(backToChat.routes.at(-1)?.name).toBe("Thread"); + expect(rememberedThreadWorkspaceNavigationState(backToChat, first)).toBeNull(); + }); + + it("keeps environments isolated and does not let the comment sheet overwrite its underlying diff", () => { + const first = identity("isolated-env-one", "same-thread-id"); + const second = identity("isolated-env-two", "same-thread-id"); + const opened = openReviewFile(initial(), first); + rememberFocusedThreadWorkspace(opened); + const comment = apply(opened, StackActions.push("ThreadReviewComment", first)); + rememberFocusedThreadWorkspace(comment); + expect(readThreadWorkspaceLocation(first.environmentId, first.threadId)?.name).toBe( + "ThreadReviewFile", + ); + const secondChat = apply(initial(), StackActions.push("Thread", second)); + rememberFocusedThreadWorkspace(secondChat); + expect(rememberedThreadWorkspaceNavigationState(secondChat, second)).toBeNull(); + expect(rememberedThreadWorkspaceNavigationState(secondChat, first)?.routes.at(-1)?.name).toBe( + "ThreadReviewFile", + ); + }); + + it("recognizes the current thread while its viewer is open and reconstructs an Android peer above Home", () => { + const current = identity("android-restore-env", "active-thread"); + const opened = openReviewFile(initial(), current); + rememberFocusedThreadWorkspace(opened); + expect(isFocusedThreadWorkspace(opened, current)).toBe(true); + expect(isFocusedThreadWorkspace(opened, identity("android-restore-env", "other-thread"))).toBe( + false, + ); + const peer = rememberedThreadWorkspaceNavigationState(opened, current, true); + expect(peer?.routes.map((route) => route.name)).toEqual([ + "Home", + "Thread", + "ThreadReview", + "ThreadReviewFile", + ]); + }); + + it("restores all-files scope without turning it into a single-file view", () => { + const params = identity("scope-restore-env", "all-files-thread"); + const opened = apply( + initial(), + StackActions.push("ThreadReviewFile", { + ...params, + reviewSectionId: "git:working-tree", + reviewWorkingTreeScope: "unstaged", + }), + ); + rememberFocusedThreadWorkspace(opened); + const restored = apply( + initial(), + CommonActions.reset(rememberedThreadWorkspaceNavigationState(initial(), params)!), + ); + expect(restored.routes.at(-1)?.params).toMatchObject({ + ...params, + reviewWorkingTreeScope: "unstaged", + }); + expect(restored.routes.at(-1)?.params).not.toHaveProperty("reviewFilePath"); + }); +}); diff --git a/apps/mobile/src/features/layout/workspace/threadWorkspaceNavigationMemory.ts b/apps/mobile/src/features/layout/workspace/threadWorkspaceNavigationMemory.ts new file mode 100644 index 0000000000000..3d713630d328b --- /dev/null +++ b/apps/mobile/src/features/layout/workspace/threadWorkspaceNavigationMemory.ts @@ -0,0 +1,108 @@ +import { useEffect } from "react"; +import { useNavigation, type NavigationState } from "@react-navigation/native"; +import { + readThreadWorkspaceLocation, + rememberThreadWorkspaceLocation, + type ThreadWorkspaceLocation, +} from "./workspacePaneMemory"; + +const locationNames = new Set([ + "Thread", + "ThreadReview", + "ThreadReviewFile", + "ThreadFiles", + "ThreadFile", +]); + +/** Only the focused destination writes memory; a hidden chat cannot overwrite its diff. */ +export function rememberFocusedThreadWorkspace( + state: Pick | undefined, +) { + if (!state) return; + const route = state.routes[state.index]; + if (!route || !locationNames.has(route.name)) return; + const params = route.params as Readonly> | undefined; + if (typeof params?.environmentId !== "string" || typeof params.threadId !== "string") return; + const stringParam = (key: string) => (typeof params[key] === "string" ? params[key] : undefined); + const scope = params.reviewWorkingTreeScope; + const path = params.path; + rememberThreadWorkspaceLocation({ + name: route.name as ThreadWorkspaceLocation["name"], + params: { + environmentId: params.environmentId, + threadId: params.threadId, + ...(typeof params.reviewSectionId === "string" + ? { reviewSectionId: params.reviewSectionId } + : {}), + ...(typeof params.reviewFilePath === "string" + ? { reviewFilePath: params.reviewFilePath } + : {}), + ...(scope === "staged" || scope === "unstaged" ? { reviewWorkingTreeScope: scope } : {}), + ...(Array.isArray(path) && path.every((part) => typeof part === "string") ? { path } : {}), + ...(stringParam("line") ? { line: String(params.line) } : {}), + ...(stringParam("cwd") ? { cwd: String(params.cwd) } : {}), + ...(stringParam("projectName") ? { projectName: String(params.projectName) } : {}), + }, + }); +} + +export function useRememberThreadWorkspaceLocation() { + const navigation = useNavigation(); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Subscribe to native navigation changes. + useEffect(() => { + // Route state also observes explicit Back: returning to chat remembers chat. + const remember = () => rememberFocusedThreadWorkspace(navigation.getState()); + remember(); + return navigation.addListener("state", remember); + }, [navigation]); +} + +/** Restore an inspector above its own chat/tree, keeping ordinary Back navigation intact. */ +export function rememberedThreadWorkspaceNavigationState( + state: NavigationState | undefined, + params: { readonly environmentId: string; readonly threadId: string }, + peer = false, +) { + if (!state) return null; + const location = readThreadWorkspaceLocation(params.environmentId, params.threadId); + if (!location || location.name === "Thread") return null; + const firstThread = state.routes.findIndex((route) => locationNames.has(route.name)); + const home = state.routes.find((route) => route.name === "Home"); + const prefix = peer + ? home + ? [home] + : [{ name: "Home" }] + : firstThread >= 0 + ? state.routes.slice(0, firstThread) + : state.routes.slice(0, state.index + 1); + const rememberedParams = { ...location.params, ...params }; + const tree = + location.name === "ThreadReviewFile" + ? [{ name: "ThreadReview", params }] + : location.name === "ThreadFile" + ? [{ name: "ThreadFiles", params }] + : []; + const routes = [ + ...prefix, + { name: "Thread", params }, + ...tree, + { name: location.name, params: rememberedParams }, + ]; + return { ...state, index: routes.length - 1, routes }; +} + +/** Selecting the current sidebar thread should leave its nested viewer alone. */ +export function isFocusedThreadWorkspace( + state: Pick | undefined, + params: { readonly environmentId: string; readonly threadId: string }, +) { + if (!state) return false; + const route = state.routes[state.index]; + const current = route?.params as Readonly> | undefined; + return Boolean( + route && + locationNames.has(route.name) && + current?.environmentId === params.environmentId && + current.threadId === params.threadId, + ); +} diff --git a/apps/mobile/src/features/layout/workspace/workspacePaneMemory.test.ts b/apps/mobile/src/features/layout/workspace/workspacePaneMemory.test.ts new file mode 100644 index 0000000000000..d2c0b0142295b --- /dev/null +++ b/apps/mobile/src/features/layout/workspace/workspacePaneMemory.test.ts @@ -0,0 +1,26 @@ +import { expect, it } from "vite-plus/test"; +import { + readWorkspacePane, + rememberWorkspacePane, + resolveWorkspacePane, +} from "./workspacePaneMemory"; + +it("waits for the initial status and chooses Git for changed files or Files for a clean tree", () => { + expect(resolveWorkspacePane(null, undefined)).toBeNull(); + expect(resolveWorkspacePane(null, 4)).toBe("git"); + expect(resolveWorkspacePane(null, 0)).toBe("files"); +}); + +it("keeps the selected pane across staging updates and thread changes", () => { + const first = "mobile-pane-thread-one"; + const second = "mobile-pane-thread-two"; + expect(readWorkspacePane(first)).toBeNull(); + const initial = resolveWorkspacePane(null, 3)!; + rememberWorkspacePane(first, initial); + expect(resolveWorkspacePane(readWorkspacePane(first), 0)).toBe("git"); + rememberWorkspacePane(first, "files"); + rememberWorkspacePane(second, "git"); + expect(resolveWorkspacePane(readWorkspacePane(first), 7)).toBe("files"); + expect(readWorkspacePane(second)).toBe("git"); + expect(readWorkspacePane(first)).toBe("files"); +}); diff --git a/apps/mobile/src/features/layout/workspace/workspacePaneMemory.ts b/apps/mobile/src/features/layout/workspace/workspacePaneMemory.ts new file mode 100644 index 0000000000000..176ed127b1962 --- /dev/null +++ b/apps/mobile/src/features/layout/workspace/workspacePaneMemory.ts @@ -0,0 +1,85 @@ +import { Atom } from "effect/reactivity"; +import { appAtomRegistry } from "../../../state/atom-registry"; + +export type WorkspacePane = "git" | "files"; +const rememberedPane = Atom.family((key: string) => + Atom.make(null).pipe( + Atom.keepAlive, + Atom.withLabel(`mobile:workspace:pane:${key}`), + ), +); + +export function readWorkspacePane(key: string) { + return appAtomRegistry.get(rememberedPane(key)); +} +export function rememberWorkspacePane(key: string, pane: WorkspacePane) { + appAtomRegistry.set(rememberedPane(key), pane); +} + +/** The first ready status chooses a pane once; later Git updates preserve that choice. */ +export function resolveWorkspacePane( + current: WorkspacePane | null, + changedFiles: number | undefined, +): WorkspacePane | null { + if (current !== null) return current; + return changedFiles === undefined ? null : changedFiles > 0 ? "git" : "files"; +} + +export interface ThreadReviewSelection { + readonly sectionId: string; + readonly path?: string; + readonly scope?: "staged" | "unstaged"; +} + +export interface ThreadWorkspaceLocation { + readonly name: "Thread" | "ThreadReview" | "ThreadReviewFile" | "ThreadFiles" | "ThreadFile"; + readonly params: { + readonly environmentId: string; + readonly threadId: string; + readonly reviewSectionId?: string; + readonly reviewFilePath?: string; + readonly reviewWorkingTreeScope?: "staged" | "unstaged"; + readonly path?: string[]; + readonly line?: string; + readonly cwd?: string; + readonly projectName?: string; + }; +} + +const rememberedLocation = Atom.family((key: string) => + Atom.make(null).pipe( + Atom.keepAlive, + Atom.withLabel(`mobile:workspace:location:${key}`), + ), +); +const rememberedReviewSelection = Atom.family((key: string) => + Atom.make(null).pipe( + Atom.keepAlive, + Atom.withLabel(`mobile:workspace:review-selection:${key}`), + ), +); + +export function workspaceThreadMemoryKey(environmentId: string, threadId: string) { + return JSON.stringify([environmentId, threadId]); +} + +export function readThreadWorkspaceLocation(environmentId: string, threadId: string) { + return appAtomRegistry.get(rememberedLocation(workspaceThreadMemoryKey(environmentId, threadId))); +} + +export function rememberThreadWorkspaceLocation(location: ThreadWorkspaceLocation) { + const key = workspaceThreadMemoryKey(location.params.environmentId, location.params.threadId); + const atom = rememberedLocation(key); + if (JSON.stringify(appAtomRegistry.get(atom)) !== JSON.stringify(location)) + appAtomRegistry.set(atom, location); +} + +export function readThreadReviewSelection(key: string) { + return appAtomRegistry.get(rememberedReviewSelection(key)); +} + +export function rememberThreadReviewSelection(key: string, selection: ThreadReviewSelection) { + const atom = rememberedReviewSelection(key); + if (JSON.stringify(appAtomRegistry.get(atom)) !== JSON.stringify(selection)) + appAtomRegistry.set(atom, selection); +} diff --git a/apps/mobile/src/features/pull-requests/PullRequestActivityFilters.tsx b/apps/mobile/src/features/pull-requests/PullRequestActivityFilters.tsx index e1e9383f44e8e..7a734299b50c3 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestActivityFilters.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestActivityFilters.tsx @@ -2,7 +2,7 @@ import { Pressable, View } from "react-native"; import { AppText as Text } from "../../components/ui/AppText"; import { SymbolView } from "../../components/ui/AppSymbol"; import { Menu } from "../../components/ui/Menu"; -import type { ActivityFilter } from "./pullRequestActivityFilter"; +import type { ActivityFilter } from "@t3tools/client-runtime/review-activity"; export function PullRequestActivityFilters({ value, diff --git a/apps/mobile/src/features/pull-requests/PullRequestAttachments.tsx b/apps/mobile/src/features/pull-requests/PullRequestAttachments.tsx new file mode 100644 index 0000000000000..c66be837e5c6f --- /dev/null +++ b/apps/mobile/src/features/pull-requests/PullRequestAttachments.tsx @@ -0,0 +1,164 @@ +import { useAtomValue } from "@effect/atom-react"; +import { publishReviewAttachment } from "@t3tools/client-runtime/review-attachments"; +import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets"; +import * as Option from "effect/Option"; +import * as DocumentPicker from "expo-document-picker"; +import { File, UploadType } from "expo-file-system"; +import { useEffect, useRef, useState } from "react"; +import { ActivityIndicator, Alert, Pressable } from "react-native"; +import { SymbolView } from "../../components/ui/AppSymbol"; +import { appAtomRegistry } from "../../state/atom-registry"; +import { attachmentEnvironment } from "../../state/attachments"; +import { composerPullRequests } from "../../state/pull-requests"; +import { environmentSession } from "../../state/session"; +import { useEnvironmentQuery } from "../../state/query"; +import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff"; + +export function PullRequestAttachments({ + params, + disabled, + onAppend, + onBusyChange, +}: { + params: PullRequestParams; + disabled?: boolean; + onAppend: (markdown: string) => void; + onBusyChange?: (busy: boolean) => void; +}) { + const target = pullRequestTarget(params); + const detail = useEnvironmentQuery(composerPullRequests.detail(target)); + const allowed = useAtomValue( + composerPullRequests.uploadAttachment.permissionAtom(target.environmentId), + ); + const [busy, setBusy] = useState(false); + const lock = useRef(false); + const scopeKey = JSON.stringify([ + params.environmentId, + params.projectId, + params.host, + params.repository, + params.number, + ]); + const transfer = useRef<{ + scopeKey: string; + cancelled: boolean; + abort?: (() => void) | undefined; + } | null>(null); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Abort in-flight uploads when their destination changes or unmounts. + useEffect( + () => () => { + if (transfer.current?.scopeKey === scopeKey) { + transfer.current.cancelled = true; + transfer.current.abort?.(); + } + }, + [scopeKey], + ); + const upload = async () => { + if (lock.current || disabled) return; + lock.current = true; + const session = { scopeKey, cancelled: false, abort: undefined as (() => void) | undefined }; + transfer.current = session; + setBusy(true); + onBusyChange?.(true); + return await (async () => { + const selection = await DocumentPicker.getDocumentAsync({ + type: [ + "image/png", + "image/jpeg", + "image/gif", + "image/webp", + "video/mp4", + "video/quicktime", + "video/webm", + ], + multiple: true, + copyToCacheDirectory: true, + }); + if (selection.canceled) return; + for (const asset of selection.assets) { + const file = new File(asset.uri); + await (async () => { + if (session.cancelled) return; + const mimeType = asset.mimeType || file.type || "application/octet-stream"; + const markdown = await publishReviewAttachment({ + registry: appAtomRegistry, + createUploadUrl: attachmentEnvironment.createUploadUrl, + remove: attachmentEnvironment.remove, + publish: composerPullRequests.uploadAttachment, + environmentId: target.environmentId, + reference: target.input, + isCancelled: () => session.cancelled, + onMinted: () => (session.cancelled ? "cancel" : "continue"), + onTransferStart: (abort) => { + session.abort = abort; + if (session.cancelled) abort(); + }, + upload: { type: "file", name: asset.name, mimeType, sizeBytes: file.size }, + resolveUploadUrl: (relativeUrl) => { + const connection = appAtomRegistry.get( + environmentSession.preparedConnectionValueAtom(target.environmentId), + ); + return Option.isSome(connection) + ? resolveAssetUrl(connection.value.httpBaseUrl, relativeUrl) + : null; + }, + transport: (url) => { + const abort = new AbortController(); + return { + abort: () => abort.abort(), + done: file + .upload(url, { + httpMethod: "POST", + uploadType: UploadType.BINARY_CONTENT, + headers: { "Content-Type": mimeType }, + signal: abort.signal, + }) + .then((result) => { + if (result.status < 200 || result.status >= 300) + throw new Error(`Upload failed (${result.status}).`); + }), + }; + }, + }); + if (!session.cancelled) onAppend(markdown); + })().finally(async () => { + if (file.exists) file.delete(); + }); + } + })() + .catch(async (error: unknown) => { + if (!session.cancelled) + Alert.alert( + "Could not attach the file", + error instanceof Error ? error.message : "Try uploading again.", + ); + }) + .finally(async () => { + lock.current = false; + setBusy(false); + onBusyChange?.(false); + }); + }; + if ( + !allowed || + !detail.data?.capabilities.attachments || + detail.data.viewerPermissions.attachments !== true + ) + return null; + return ( + void upload()} + > + {busy ? ( + + ) : ( + + )} + + ); +} diff --git a/apps/mobile/src/features/pull-requests/PullRequestCommentCard.tsx b/apps/mobile/src/features/pull-requests/PullRequestCommentCard.tsx new file mode 100644 index 0000000000000..af93d4b61cfd2 --- /dev/null +++ b/apps/mobile/src/features/pull-requests/PullRequestCommentCard.tsx @@ -0,0 +1,513 @@ +import { usePendingReviewCommentActions } from "./usePendingReviewCommentActions"; +import { useRetiredReviewDraftCommentIds } from "./usePullRequestReviewDraft"; +import { + reviewThreadReplyTarget, + pendingReviewCommentsFromThreads, +} from "@t3tools/client-runtime/review-editing"; +import { useAtomRefresh } from "@effect/atom-react"; +import { useNavigation } from "@react-navigation/native"; +import { reviewLineRangeLabel } from "@t3tools/client-runtime/review-selection"; +import { + mergeReviewThreadComments, + reviewThreadSummary, +} from "@t3tools/client-runtime/review-threads"; +import type { + PullRequestActor, + PullRequestReaction, + PullRequestReviewThread, + PullRequestThreadComment, +} from "@t3tools/contracts"; +import { useMemo, useRef, useState, type ReactNode } from "react"; +import { Alert, Pressable, StyleSheet, View } from "react-native"; +import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg"; +import { SymbolView } from "../../components/ui/AppSymbol"; +import { AppText as Text } from "../../components/ui/AppText"; +import { relativeTime } from "../../lib/time"; +import { composerPullRequests } from "../../state/pull-requests"; +import { useEnvironmentQuery } from "../../state/query"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; +import { PullRequestCommentComposer } from "./PullRequestCommentComposer"; +import { PullRequestCommentControls } from "./PullRequestCommentControls"; +import { PullRequestMarkdown } from "./PullRequestMarkdown"; +import { PullRequestPendingBadge } from "./PullRequestPendingComment"; +import { PullRequestAvatar } from "./PullRequestPresentation"; +import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff"; +import { usePullRequestPermissions } from "./usePullRequestPermissions"; + +const LONG_BODY_CHARACTERS = 450; +const LONG_BODY_LINES = 8; + +/** A comment body that folds very long remarks behind "Show more" so lists stay scannable. */ +export function PullRequestCommentBody({ body }: { body: string }) { + const [expanded, setExpanded] = useState(false); + const { themeVariables: colors } = useAppearancePreferences(); + const long = body.length > LONG_BODY_CHARACTERS || body.split("\n").length > LONG_BODY_LINES; + const folded = long && !expanded; + const fill = colors["--color-grouped-card"]; + return ( + + + + + {folded ? ( + + + + + + + + + + + + + ) : null} + {long ? ( + setExpanded(!expanded)} + hitSlop={8} + className="flex-row items-center justify-center gap-1 pt-1 active:opacity-70" + > + + {expanded ? "Show less" : "Show more"} + + + + ) : null} + + ); +} + +/** + * One dense comment: author, time and actions on a single row, the body directly beneath. The + * action slot keeps 44pt targets but pulls them into the row so they add no vertical gap. + */ +export function PullRequestCommentItem({ + params, + comment, + title, + badges, + meta, + leadingAction, + onDiscard, + disabled, + onResolve, + onUnresolve, +}: { + params: PullRequestParams; + comment: { + id: string; + body: string; + url: string | null; + createdAt: string; + author: PullRequestActor | null; + reactions?: ReadonlyArray | undefined; + kind?: string; + canEdit?: boolean; + }; + /** Muted verb after the author, such as "commented" or "approved". */ + title?: string | undefined; + badges?: ReactNode; + /** A second muted line, such as the file a remark was left on. */ + meta?: ReactNode; + /** A direct action shown before the reaction and overflow controls. */ + leadingAction?: ReactNode; + onDiscard?: (() => void) | undefined; + disabled?: boolean; + onResolve?: (() => void) | undefined; + onUnresolve?: (() => void) | undefined; +}) { + return ( + ( + + + + + + {comment.author?.name ?? comment.author?.login ?? "Unknown author"} + + {title ? {title} : null} + + + {relativeTime(comment.createdAt)} + + {badges} + + {leadingAction} + {actions} + + + {meta} + {comment.body.trim() ? : null} + {reactions} + + )} + /> + ); +} + +/** Icon-only action that matches the reaction and overflow controls beside it. */ +function InlineIconAction({ + icon, + label, + onPress, + disabled, +}: { + icon: "checkmark" | "arrow.uturn.backward"; + label: string; + onPress: () => void; + disabled?: boolean; +}) { + return ( + + + + ); +} + +/** + * Host operations for one review conversation. Resolution goes through the shared optimistic + * command, so every card, count, and tab reflects it before the host answers and rolls back on + * failure; only the error needs reporting here. + */ +export function usePullRequestThreadActions( + params: PullRequestParams, + thread: PullRequestReviewThread, +) { + const target = pullRequestTarget(params); + const detail = useEnvironmentQuery(composerPullRequests.detail(target)); + const permissions = usePullRequestPermissions(params, detail.data); + const refresh = useAtomRefresh(composerPullRequests.activity(target)); + const replyCommand = useAtomCommand(composerPullRequests.replyToThread, { + reportFailure: false, + }); + const resolveCommand = useAtomCommand(composerPullRequests.setThreadResolution, { + reportFailure: false, + }); + const loadCommand = useAtomCommand(composerPullRequests.threadComments, { + reportFailure: false, + }); + const hasPending = thread.comments.some((comment) => comment.pendingReviewId); + return { + canReply: permissions.canReply, + canResolve: permissions.canResolve && thread.canResolve !== false && !hasPending, + toggleResolved: () => { + const resolved = !thread.isResolved; + void resolveCommand({ + ...target, + input: { ...target.input, threadId: thread.id, resolved }, + }).then((result) => { + if (result._tag === "Failure") + Alert.alert( + resolved ? "Could not resolve the conversation" : "Could not reopen the conversation", + "Its previous state has been restored. Try again.", + ); + }); + }, + /** Resolves to whether the host took it, so a failed reply keeps its words. */ + reply: async (body: string) => { + const result = await replyCommand({ + ...target, + input: { ...target.input, ...reviewThreadReplyTarget(thread), body }, + }); + if (result._tag === "Failure") { + Alert.alert("Reply could not be posted", "Your reply has been kept. Try again."); + return false; + } + refresh(); + return true; + }, + loadMore: async (cursor: string) => { + const result = await loadCommand({ + ...target, + input: { ...target.input, threadId: thread.id, cursor }, + }); + if (result._tag === "Failure") { + Alert.alert("More comments could not be loaded"); + return null; + } + return result.value; + }, + }; +} + +/** + * A review conversation as one card, shared by the Comments sheet, the Overview timeline, and the + * discussion screen. It follows desktop's floating panel: a summary header that folds the thread, + * dense comments, a direct Resolve on the first comment, and the reply field inside the card. + * Resolved conversations open folded and fold again whenever they become resolved. + */ +export function PullRequestThreadCard({ + params, + thread, + showPath = true, + defaultExpanded, + autoFocusReply = false, + onBeforeNavigate, +}: { + params: PullRequestParams; + thread: PullRequestReviewThread; + showPath?: boolean; + defaultExpanded?: boolean; + autoFocusReply?: boolean; + /** Lets a modal host dismiss itself before the file diff is pushed beneath it. */ + onBeforeNavigate?: () => void; +}) { + const navigation = useNavigation(); + const actions = usePullRequestThreadActions(params, thread); + const [expanded, setExpanded] = useState(defaultExpanded ?? !thread.isResolved); + const [lastResolved, setLastResolved] = useState(thread.isResolved); + if (lastResolved !== thread.isResolved) { + setLastResolved(thread.isResolved); + setExpanded(!thread.isResolved); + } + const [loadedPage, setLoadedPage] = useState<{ + readonly threadId: string; + readonly comments: ReadonlyArray; + readonly nextCursor: string | null; + } | null>(null); + const [loadingMore, setLoadingMore] = useState(false); + const [reply, setReply] = useState(""); + const [sending, setSending] = useState(false); + const [uploading, setUploading] = useState(false); + const sendingRef = useRef(false); + const page = loadedPage?.threadId === thread.id ? loadedPage : null; + const pendingActions = usePendingReviewCommentActions(params); + const retiredIds = useRetiredReviewDraftCommentIds(params); + const comments = useMemo(() => { + const retired = new Set(retiredIds); + return mergeReviewThreadComments(thread.comments, page?.comments ?? []).filter( + (comment) => !comment.pendingReviewId || !retired.has(comment.id), + ); + }, [thread.comments, page?.comments, retiredIds]); + const nextCursor = page === null ? (thread.nextCommentsCursor ?? null) : page.nextCursor; + const summary = reviewThreadSummary(thread); + const pendingById = new Map( + pendingReviewCommentsFromThreads([{ ...thread, comments }]).map((comment) => [ + comment.id, + { ...comment, headSha: "", code: "" }, + ]), + ); + + const send = async () => { + const body = reply.trim(); + if (!body || sendingRef.current || uploading) return; + sendingRef.current = true; + setSending(true); + return await (async () => { + if (await actions.reply(body)) { + // The mutation returns no comment; reopen the cursor so the reply stays reachable. + setLoadedPage((previous) => + previous?.threadId === thread.id + ? { ...previous, nextCursor: previous.nextCursor ?? thread.nextCommentsCursor ?? null } + : previous, + ); + setReply((current) => (current.trim() === body ? "" : current)); + } + })().finally(async () => { + sendingRef.current = false; + setSending(false); + }); + }; + const loadMore = async () => { + if (nextCursor === null || loadingMore) return; + setLoadingMore(true); + return await (async () => { + const result = await actions.loadMore(nextCursor); + if (result === null) return; + setLoadedPage((previous) => ({ + threadId: thread.id, + comments: mergeReviewThreadComments( + previous?.threadId === thread.id ? previous.comments : [], + result.comments, + ), + nextCursor: result.nextCursor, + })); + })().finally(async () => { + setLoadingMore(false); + }); + }; + + return ( + + {showPath ? ( + { + onBeforeNavigate?.(); + navigation.navigate("PullRequestFile", { ...params, path: thread.path }); + }} + className="flex-row items-center gap-1.5 border-b border-border-subtle px-3 py-1.5 active:opacity-70" + > + + + {thread.path} + {thread.line === null ? "" : `:${thread.line}`} + + {thread.isOutdated ? ( + Outdated + ) : null} + + ) : null} + + setExpanded(!expanded)} + className="min-h-10 min-w-0 flex-1 flex-row items-center gap-2 pl-3 active:opacity-70" + > + + + {thread.isResolved && expanded ? "Collapse" : summary} + + {thread.line !== null ? ( + + {reviewLineRangeLabel(thread)} + + ) : null} + + + + {thread.isResolved && actions.canResolve ? ( + + Unresolve + + ) : ( + + )} + + {expanded ? ( + <> + {comments.map((comment, index) => ( + + : null} + disabled={pendingActions.busy} + onDiscard={ + comment.pendingReviewId && + pendingById.has(comment.id) && + pendingActions.canDiscard + ? () => + Alert.alert( + "Discard this comment?", + "Your other review comments will be kept.", + [ + { text: "Cancel", style: "cancel" }, + { + text: "Discard", + style: "destructive", + onPress: () => + void pendingActions.discard(pendingById.get(comment.id)!), + }, + ], + ) + : undefined + } + leadingAction={ + index === 0 && actions.canResolve && !thread.isResolved ? ( + + ) : null + } + onResolve={ + actions.canResolve && !thread.isResolved ? actions.toggleResolved : undefined + } + onUnresolve={ + actions.canResolve && thread.isResolved ? actions.toggleResolved : undefined + } + /> + + ))} + {nextCursor !== null ? ( + void loadMore()} + className="min-h-10 justify-center border-t border-border-subtle px-3 active:opacity-70" + > + + {loadingMore ? "Loading…" : "Load more comments"} + + + ) : null} + {actions.canReply ? ( + void send()} + onBusyChange={setUploading} + autoFocus={autoFocusReply} + minimumHeight={44} + /> + ) : null} + + ) : null} + + ); +} diff --git a/apps/mobile/src/features/pull-requests/PullRequestCommentComposer.tsx b/apps/mobile/src/features/pull-requests/PullRequestCommentComposer.tsx new file mode 100644 index 0000000000000..85e349489ac1f --- /dev/null +++ b/apps/mobile/src/features/pull-requests/PullRequestCommentComposer.tsx @@ -0,0 +1,110 @@ +import { useState } from "react"; +import { View } from "react-native"; +import { AppTextInput as TextInput } from "../../components/ui/AppText"; +import { ControlPill } from "../../components/ui/ControlPill"; +import { PullRequestAttachments } from "./PullRequestAttachments"; +import type { PullRequestParams } from "./usePullRequestDiff"; +import { useReviewAttachmentInsertion } from "./useReviewAttachmentInsertion"; + +/** + * One compact field and attached upload/send toolbar for every native review composer. `inline` + * drops the outer card so a reply can sit inside a comment card, as on desktop. + */ +export function PullRequestCommentComposer({ + params, + value, + onChangeText, + label, + placeholder, + editable = true, + busy = false, + canSubmit, + submitLabel, + showSubmitLabel = false, + onSubmit, + onBusyChange, + autoFocus = false, + minimumHeight = 80, + variant = "card", +}: { + params: PullRequestParams; + value: string; + onChangeText: (value: string) => void; + label: string; + placeholder: string; + editable?: boolean; + busy?: boolean; + canSubmit: boolean; + submitLabel: string; + showSubmitLabel?: boolean; + onSubmit: () => void; + onBusyChange?: (busy: boolean) => void; + autoFocus?: boolean; + minimumHeight?: number; + variant?: "card" | "inline"; +}) { + const insertion = useReviewAttachmentInsertion(value, onChangeText); + const [uploading, setUploading] = useState(false); + const [height, setHeight] = useState(minimumHeight); + return ( + + { + const next = Math.min( + 200, + Math.max(minimumHeight, Math.ceil(event.nativeEvent.contentSize.height)), + ); + setHeight((current) => (current === next ? current : next)); + }} + className={ + variant === "inline" + ? "min-h-0 flex-1 rounded-none border-0 bg-transparent px-3 py-2.5 text-sm text-foreground" + : "min-h-0 rounded-none border-0 bg-transparent px-3 py-3 text-base text-foreground" + } + style={{ height, textAlignVertical: "top" }} + /> + + { + setUploading(busy); + onBusyChange?.(busy); + }} + onAppend={insertion.insert} + /> + {variant === "inline" ? null : } + + + + ); +} diff --git a/apps/mobile/src/features/pull-requests/PullRequestCommentControls.tsx b/apps/mobile/src/features/pull-requests/PullRequestCommentControls.tsx new file mode 100644 index 0000000000000..15e8da683aade --- /dev/null +++ b/apps/mobile/src/features/pull-requests/PullRequestCommentControls.tsx @@ -0,0 +1,336 @@ +import { usePullRequestThreads } from "./usePullRequestThreads"; +import { canEditPullRequestComment } from "@t3tools/client-runtime/review-editing"; +import { PullRequestCommentComposer } from "./PullRequestCommentComposer"; +import { SafeAreaView } from "react-native-safe-area-context"; +import { useAtomValue } from "@effect/atom-react"; +import { + PULL_REQUEST_REACTION_ORDER, + applyPendingPullRequestReactions, + pullRequestReactionEmoji, + pullRequestReactionName, +} from "@t3tools/client-runtime/review-reactions"; +import type { + PullRequestActor, + PullRequestReaction, + PullRequestReactionContent, +} from "@t3tools/contracts"; +import { useState, type ReactNode } from "react"; +import { Alert, Linking, Modal, Pressable, View } from "react-native"; +import * as Clipboard from "expo-clipboard"; +import { Menu } from "../../components/ui/Menu"; +import { SymbolView } from "../../components/ui/AppSymbol"; +import { AppText as Text } from "../../components/ui/AppText"; +import { composerPullRequests } from "../../state/pull-requests"; +import { useEnvironmentQuery } from "../../state/query"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff"; +import { ControlPill } from "../../components/ui/ControlPill"; +import { KeyboardAvoidingView } from "react-native-keyboard-controller"; + +/** Native controls share reaction vocabulary and optimistic counts with desktop. */ +export function PullRequestCommentControls({ + params, + comment, + onEdit, + onUnresolve, + onResolve, + onDiscard, + disabled, + render, +}: { + params: PullRequestParams; + comment: { + id: string; + body: string; + url: string | null; + reactions?: ReadonlyArray | undefined; + kind?: string; + author?: PullRequestActor | null; + canEdit?: boolean; + }; + onEdit?: (() => void) | undefined; + onUnresolve?: (() => void) | undefined; + onResolve?: (() => void) | undefined; + disabled?: boolean; + onDiscard?: (() => void) | undefined; + render?: (slots: { actions: ReactNode; reactions: ReactNode }) => ReactNode; +}) { + const target = pullRequestTarget(params); + const detail = useEnvironmentQuery(composerPullRequests.detail(target)); + const activity = useEnvironmentQuery(composerPullRequests.activity(target)); + const agent = usePullRequestThreads(params, detail.data); + const markdown = `${comment.author?.login ? `**${comment.author.login}**\n\n` : ""}${comment.body}${comment.url ? `\n\n[View comment](${comment.url})` : ""}`; + const allowed = useAtomValue( + composerPullRequests.setReaction.permissionAtom(target.environmentId), + ); + const write = useAtomCommand(composerPullRequests.setReaction, { reportFailure: false }); + const update = useAtomCommand(composerPullRequests.updateComment, { reportFailure: false }); + const canWriteComment = useAtomValue( + composerPullRequests.updateComment.permissionAtom(target.environmentId), + ); + const [editing, setEditing] = useState(false); + const [draft, setDraft] = useState(comment.body); + const [saving, setSaving] = useState(false); + const [uploading, setUploading] = useState(false); + const kind = + comment.kind === undefined + ? "review-comment" + : comment.kind === "issue-comment" + ? "issue-comment" + : comment.kind === "review-comment" + ? "review-comment" + : "review"; + const canEdit = + canWriteComment && + detail.data !== null && + canEditPullRequestComment(detail.data, { + kind, + author: comment.author ?? null, + ...(comment.canEdit === undefined ? {} : { canEdit: comment.canEdit }), + }); + const edit = () => { + if (onEdit) onEdit(); + else { + setDraft(comment.body); + setEditing(true); + } + }; + const save = async () => { + if (!canEdit || saving || uploading || !draft.trim() || kind === "review") return; + setSaving(true); + const result = await update({ + ...target, + input: { ...target.input, commentId: comment.id, kind, body: draft }, + }); + setSaving(false); + if (result._tag === "Failure") { + Alert.alert("Could not edit the comment", "Your draft has been kept. Try again."); + return; + } + setEditing(false); + activity.refresh(); + }; + const reactions = comment.reactions ?? []; + const signature = JSON.stringify(reactions); + const [state, setState] = useState({ + signature, + overlay: new Map(), + }); + const [busy, setBusy] = useState(false); + if (signature !== state.signature) setState({ signature, overlay: new Map() }); + const shown = applyPendingPullRequestReactions( + reactions, + state.signature === signature ? state.overlay : new Map(), + ); + const canReact = allowed && detail.data?.capabilities.reactions === true; + const react = async (content: PullRequestReactionContent) => { + if (!canReact || busy) return; + const reacted = !shown.find((reaction) => reaction.content === content)?.viewerHasReacted; + setState((current) => ({ signature, overlay: new Map(current.overlay).set(content, reacted) })); + setBusy(true); + const result = await write({ + ...target, + input: { ...target.input, subjectId: comment.id, content, reacted }, + }); + setBusy(false); + if (result._tag === "Failure") { + setState({ signature, overlay: new Map() }); + Alert.alert("Could not save the reaction"); + } else activity.refresh(); + }; + const reactionChips = shown.map((reaction) => ( + void react(reaction.content)} + > + + {pullRequestReactionEmoji(reaction.content)} {reaction.count} + + + )); + const reactionPicker = canReact ? ( + ({ + id: content, + title: `${pullRequestReactionEmoji(content)} ${pullRequestReactionName(content)}`, + state: shown.some((reaction) => reaction.content === content && reaction.viewerHasReacted) + ? ("on" as const) + : ("off" as const), + attributes: { disabled: busy || Boolean(disabled) }, + }))} + onPressAction={({ nativeEvent }) => { + const content = PULL_REQUEST_REACTION_ORDER.find( + (content) => content === nativeEvent.event, + ); + if (content) void react(content); + }} + > + + + + + ) : null; + const commentMenu = ( + { + if (nativeEvent.event === "resolve") onResolve?.(); + else if (nativeEvent.event === "composer") { + if (agent.canAddToComposer) void agent.addToComposer({ markdown }); + else + void agent.ask( + agent.threads.length === 1 ? agent.threads[0] : undefined, + "ask", + markdown, + ); + } else if (nativeEvent.event === "unresolve") onUnresolve?.(); + else if (nativeEvent.event === "discard") onDiscard?.(); + else if (nativeEvent.event === "edit") edit(); + else if (nativeEvent.event === "copy") void Clipboard.setStringAsync(markdown); + else if (nativeEvent.event === "copy-link" && comment.url) + void Clipboard.setStringAsync(comment.url); + else if (nativeEvent.event === "open" && comment.url) void Linking.openURL(comment.url); + }} + > + + + + + ); + const actions = ( + + {reactionPicker} + {commentMenu} + + ); + return ( + <> + {render ? ( + render({ + actions, + reactions: shown.length ? ( + {reactionChips} + ) : null, + }) + ) : ( + + {reactionChips} + {actions} + + )} + { + if (!saving && !uploading) setEditing(false); + }} + > + + { + if (!saving && !uploading) setEditing(false); + }} + /> + + + Edit comment + setEditing(false)} + /> + + void save()} + onBusyChange={setUploading} + autoFocus + /> + + + + + ); +} diff --git a/apps/mobile/src/features/pull-requests/PullRequestCommentForm.tsx b/apps/mobile/src/features/pull-requests/PullRequestCommentForm.tsx new file mode 100644 index 0000000000000..9668017dd26d9 --- /dev/null +++ b/apps/mobile/src/features/pull-requests/PullRequestCommentForm.tsx @@ -0,0 +1,71 @@ +import { useState } from "react"; +import { View } from "react-native"; +import { AppTextInput as TextInput } from "../../components/ui/AppText"; +import { PullRequestAttachments } from "./PullRequestAttachments"; +import type { PullRequestParams } from "./usePullRequestDiff"; +import { useReviewAttachmentInsertion } from "./useReviewAttachmentInsertion"; + +/** Desktop's comment form: a plain field with the attachment control beneath; buttons live in the sheet footer. */ +export function PullRequestCommentForm({ + params, + value, + onChangeText, + label, + placeholder, + editable = true, + busy = false, + onBusyChange, + autoFocus = false, + minimumHeight = 88, +}: { + params: PullRequestParams; + value: string; + onChangeText: (value: string) => void; + label: string; + placeholder: string; + editable?: boolean; + busy?: boolean; + onBusyChange?: (busy: boolean) => void; + autoFocus?: boolean; + minimumHeight?: number; +}) { + const insertion = useReviewAttachmentInsertion(value, onChangeText); + const [uploading, setUploading] = useState(false); + const [height, setHeight] = useState(minimumHeight); + return ( + + { + const next = Math.min( + 220, + Math.max(minimumHeight, Math.ceil(event.nativeEvent.contentSize.height)), + ); + setHeight((current) => (current === next ? current : next)); + }} + className="rounded-xl border border-border-subtle bg-grouped-card px-3 py-3 text-base text-foreground" + style={{ height, textAlignVertical: "top" }} + /> + + { + setUploading(busy); + onBusyChange?.(busy); + }} + onAppend={insertion.insert} + /> + + + ); +} diff --git a/apps/mobile/src/features/pull-requests/PullRequestCommentsSheet.tsx b/apps/mobile/src/features/pull-requests/PullRequestCommentsSheet.tsx new file mode 100644 index 0000000000000..58bb9e85b3c5e --- /dev/null +++ b/apps/mobile/src/features/pull-requests/PullRequestCommentsSheet.tsx @@ -0,0 +1,191 @@ +import { useNavigation } from "@react-navigation/native"; +import { countReviewThreads } from "@t3tools/client-runtime/review-threads"; +import { useState } from "react"; +import { Modal, Pressable, ScrollView, View } from "react-native"; +import { KeyboardAvoidingView } from "react-native-keyboard-controller"; +import { SafeAreaView } from "react-native-safe-area-context"; +import { SymbolView } from "../../components/ui/AppSymbol"; +import { AppText as Text } from "../../components/ui/AppText"; +import { SegmentedControl } from "../../components/ui/SegmentedControl"; +import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; +import { PullRequestThreadCard } from "./PullRequestCommentCard"; +import { PullRequestMarkdown } from "./PullRequestMarkdown"; +import { + PullRequestPendingBadge, + PullRequestPendingCommentActions, +} from "./PullRequestPendingComment"; +import { usePullRequestReviewDraft } from "./usePullRequestReviewDraft"; +import type { PullRequestParams } from "./usePullRequestDiff"; + +/** One PR-wide checklist remains accessible while switching review tabs. */ +export function PullRequestCommentsSheet({ + params, + visible, + onClose, +}: { + params: PullRequestParams; + visible: boolean; + onClose: () => void; +}) { + const navigation = useNavigation(); + const { themeVariables: colors } = useAppearancePreferences(); + const draft = usePullRequestReviewDraft(params); + const [status, setStatus] = useState<"resolved" | "unresolved" | "pending">("unresolved"); + // Threads come from the optimistic activity projection, so a resolve moves its card between + // tabs and updates every count before the host answers. + const published = draft.threads.filter((thread) => + thread.comments.some((comment) => !comment.pendingReviewId), + ); + const pendingThreads = draft.threads.filter((thread) => + thread.comments.some((comment) => comment.pendingReviewId), + ); + const resolved = published.filter((thread) => thread.isResolved); + const unresolved = published.filter((thread) => !thread.isResolved); + const counts = countReviewThreads(published); + // Removing the last draft also removes its tab; stay on an available status. + const selectedStatus = + status === "pending" && draft.comments.length === 0 ? "unresolved" : status; + if (selectedStatus !== status) setStatus(selectedStatus); + const threads = + selectedStatus === "resolved" + ? resolved + : selectedStatus === "unresolved" + ? unresolved + : pendingThreads; + const pending = selectedStatus === "pending" ? draft.ungroupedComments : []; + const options = [ + { + value: "unresolved" as const, + label: "Unresolved", + ...(draft.activityLoaded ? { badge: unresolved.length } : {}), + }, + { + value: "resolved" as const, + label: "Resolved", + ...(draft.activityLoaded ? { badge: resolved.length } : {}), + }, + ...(draft.comments.length + ? [{ value: "pending" as const, label: "Pending", badge: draft.comments.length }] + : []), + ]; + return ( + + {/* SafeAreaView forwards className to a native view without Uniwind styling. */} + + + + Comments + + {draft.activityLoaded + ? `${counts.open} open · ${counts.resolved} resolved` + : draft.activityError + ? "Could not load comments" + : "Loading comments…"} + {draft.comments.length ? ` · ${draft.comments.length} pending` : ""} + + + + + + + + + + {/* Replies are written inside the cards, so the list must clear the keyboard. */} + + + {pending.map((comment) => ( + + + + + + + + {comment.path} + + + { + onClose(); + navigation.navigate("PullRequestInlineComment", { + ...params, + draftId: comment.id, + path: comment.path, + position: comment.position, + ...(comment.startPosition ? { startPosition: comment.startPosition } : {}), + headSha: comment.headSha, + code: comment.code, + ...(comment.oldPath ? { oldPath: comment.oldPath } : {}), + }); + }} + > + Open pending comment + + + ))} + {threads.map((thread) => ( + + ))} + {draft.activityError ? ( + + + {draft.activityError} + + + Try again + + + ) : !draft.activityLoaded && selectedStatus !== "pending" ? ( + + Loading comments… + + ) : null} + {draft.activityLoaded && !draft.activityError && !threads.length && !pending.length ? ( + + {selectedStatus === "resolved" + ? "No resolved comments." + : "No unresolved comments."} + + ) : null} + + + + + ); +} diff --git a/apps/mobile/src/features/pull-requests/PullRequestCommitPicker.tsx b/apps/mobile/src/features/pull-requests/PullRequestCommitPicker.tsx new file mode 100644 index 0000000000000..cbcd2df01a755 --- /dev/null +++ b/apps/mobile/src/features/pull-requests/PullRequestCommitPicker.tsx @@ -0,0 +1,177 @@ +import type { PullRequestCommit } from "@t3tools/contracts"; +import { + reviewCommitScope, + reviewCommitSelection, + toggleReviewCommit, +} from "@t3tools/client-runtime/review-workspace"; +import { useState } from "react"; +import { Modal, Pressable, ScrollView, View, useWindowDimensions } from "react-native"; +import { AppText as Text } from "../../components/ui/AppText"; +import { ControlPill } from "../../components/ui/ControlPill"; +import { SymbolView } from "../../components/ui/AppSymbol"; +import { relativeTime } from "../../lib/time"; +import { REVIEW_MONO_FONT_FAMILY } from "../review/reviewDiffRendering"; + +/** A compact range picker keeps native menus from wrapping every commit into a tall card. */ +export function PullRequestCommitPicker({ + open, + onClose, + commits, + scope, + lastReviewed, + canSelectRange, + onChange, +}: { + readonly open: boolean; + readonly onClose: () => void; + /** Oldest first, matching the shared contiguous-range selection helpers. */ + readonly commits: ReadonlyArray; + readonly scope: string | null; + readonly lastReviewed: string | null; + readonly canSelectRange: boolean; + readonly onChange: (scope: string | null) => void; +}) { + const { height } = useWindowDimensions(); + const [shown, setShown] = useState(10); + const oids = commits.map((commit) => commit.oid); + const selected = reviewCommitSelection(oids, scope); + const first = selected[0]; + const last = selected.at(-1); + const reviewedIndex = lastReviewed === null ? -1 : oids.indexOf(lastReviewed); + const sinceDisabled = reviewedIndex < 0 || reviewedIndex === commits.length - 1; + const recentCommits = [...commits].reverse().slice(0, shown); + const chooseQuick = (next: string | null) => { + onChange(next); + onClose(); + }; + return ( + + + + + + Commit range + + + + + {scope === null + ? "All" + : `${selected.length} ${selected.length === 1 ? "commit" : "commits"} selected`} + + {scope !== null && first ? ( + + {first.slice(0, 7)} + {last && first !== last ? ` → ${last.slice(0, 7)}` : ""} + + ) : null} + + chooseQuick(null)} + > + + {scope === null ? ( + + ) : null} + + All + + chooseQuick(reviewCommitScope(oids.slice(reviewedIndex + 1)))} + > + + Since last reviewed + + + {recentCommits.map((entry) => { + const checked = selected.includes(entry.oid); + const authors = entry.authors + ?.map((author) => author.name ?? author.login) + .join(", "); + return ( + { + onChange( + canSelectRange + ? reviewCommitScope( + toggleReviewCommit(oids, scope === null ? [] : selected, entry.oid), + ) + : entry.oid, + ); + if (!canSelectRange) onClose(); + }} + > + + {checked ? ( + + ) : null} + + + + {entry.messageHeadline || "Untitled commit"} + + + {authors ? `${authors} · ` : ""} + {relativeTime(entry.committedDate)} + + + + {entry.oid.slice(0, 7)} + + + ); + })} + {commits.length > shown ? ( + setShown((current) => current + 10)} + > + + Show more ({commits.length - shown} left) + + + ) : null} + + + + + ); +} diff --git a/apps/mobile/src/features/pull-requests/PullRequestComposerNotice.tsx b/apps/mobile/src/features/pull-requests/PullRequestComposerNotice.tsx new file mode 100644 index 0000000000000..e16865ee8368a --- /dev/null +++ b/apps/mobile/src/features/pull-requests/PullRequestComposerNotice.tsx @@ -0,0 +1,38 @@ +import { View } from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; +import { Toast } from "../../components/ui/Toast"; +import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail"; +import { dismissComposerInsertNotice, useComposerInsertNotice } from "./composer-insert-notice"; + +/** Confirms a comment reached the thread's composer without leaving the pull request. */ +export function PullRequestComposerNotice(props: { readonly bottomInset?: number }) { + const notice = useComposerInsertNotice(); + const selectDetail = useSelectWorkspaceDetail(); + const insets = useSafeAreaInsets(); + if (notice === null) return null; + return ( + + { + dismissComposerInsertNotice(); + selectDetail({ + name: "Thread", + params: { environmentId: notice.environmentId, threadId: notice.threadId }, + }); + }, + }} + dismissMode="swipe" + onDismiss={dismissComposerInsertNotice} + /> + + ); +} diff --git a/apps/mobile/src/features/pull-requests/PullRequestControls.tsx b/apps/mobile/src/features/pull-requests/PullRequestControls.tsx index ef8f59c74b079..00cc5988e1ce5 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestControls.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestControls.tsx @@ -20,6 +20,7 @@ import { usePullRequestPermissions } from "./usePullRequestPermissions"; import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; import { usePullRequestReviewDraft } from "./usePullRequestReviewDraft"; import { usePullRequestAgentActions } from "./usePullRequestAgentActions"; +import type { PullRequestAgentTask } from "./pullRequestAgentTasks"; export function PullRequestCardGroup(props: { readonly children: ReactNode }) { return ( @@ -105,30 +106,208 @@ export function PullRequestCardRow(props: { ); } -export function PullRequestActionToolbar(props: { +type PullRequestActionToolbarProps = { readonly pr: PullRequestDetail | null; readonly params: PullRequestParams; readonly filePath?: string; readonly onOpenFiles?: () => void; + readonly showFiles?: boolean; readonly onHeightChange?: (height: number) => void; -}) { +}; + +function useVerticalPullRequestRail() { + const metrics = useNativeLayoutMetrics(); + return Platform.OS === "ios" && metrics !== null && metrics.verticalBarEdge !== "none"; +} + +function pullRequestThreadMenuItems( + agent: ReturnType, + task: PullRequestAgentTask, +) { + return agent + .threadActions(task) + .filter((item) => item.id !== undefined) + .map((item) => ( + item.id !== undefined && agent.select(item.id)} + > + {item.title} + + )); +} + +function pullRequestAgentMenuItems(agent: ReturnType) { + return agent.actions + .filter((action) => action.task !== "ask") + .map((action) => + agent.threads.length > 1 && !action.disabled ? ( + + {pullRequestThreadMenuItems(agent, action.task)} + + ) : ( + agent.start(action.task)} + > + {action.title} + + ), + ); +} + +type PullRequestHeaderToolbarProps = { + readonly pr: PullRequestDetail | null; + readonly params: PullRequestParams; + readonly filePath?: string; + readonly title: string; + readonly accessibilityLabel?: string; + readonly onOpenComments: () => void; + readonly commentsInHorizontalBar?: boolean; + readonly controls?: ReadonlyArray; + readonly railMenuItems?: ReactNode; + readonly children?: ReactNode; +}; + +function pullRequestHeaderMenu(props: PullRequestHeaderToolbarProps, actions?: ReactNode) { + return ( + + {actions} + {props.children} + + ); +} + +export function PullRequestHeaderToolbar(props: PullRequestHeaderToolbarProps) { + const vertical = useVerticalPullRequestRail(); + return vertical ? ( + + ) : ( + + {props.controls} + {props.commentsInHorizontalBar !== false ? ( + + ) : null} + {pullRequestHeaderMenu(props)} + + ); +} + +function PullRequestVerticalHeaderToolbar(props: PullRequestHeaderToolbarProps) { + const navigation = useNavigation(); + const draft = usePullRequestReviewDraft(props.params); + const permissions = usePullRequestPermissions(props.params, props.pr); + const agent = usePullRequestAgentActions(props.params, props.pr, props.filePath); + const { themeVariables: colors } = useAppearancePreferences(); + const pendingReview = + props.pr !== null && + permissions.verdicts.length > 0 && + (draft.comments.length > 0 || Boolean(draft.pendingReviewId)); + const showAgentControls = props.pr !== null && (agent.canAsk || !permissions.connected); + const canOpenThread = props.pr !== null && (agent.threads.length > 0 || showAgentControls); + const { shortLabel } = sourceControlClients.get( + (props.pr ?? props.params.initialSummary)?.provider, + ).changeRequest; + const threadLabel = agent.threads.length ? "Continue thread" : `Work on ${shortLabel}`; + const submitLabel = `Submit review${draft.comments.length ? ` · ${draft.comments.length}` : ""}`; + const actions = ( + <> + {canOpenThread ? ( + agent.threads.length > 1 ? ( + + {pullRequestThreadMenuItems(agent, "ask")} + + ) : ( + agent.start("ask")} + > + {threadLabel} + + ) + ) : null} + {showAgentControls ? ( + + {pullRequestAgentMenuItems(agent)} + + ) : null} + {props.railMenuItems} + + ); + return ( + + {/* UIKit places trailing items from the edge inward, reversing the vertical order. */} + {pendingReview ? ( + + navigation.navigate("PullRequestReview", { ...props.params, mode: "review" }) + } + separateBackground + visibilityPriority="high" + /> + ) : null} + {pullRequestHeaderMenu(props, actions)} + + + ); +} + +export function PullRequestActionToolbar(props: PullRequestActionToolbarProps) { + const vertical = useVerticalPullRequestRail(); + return vertical ? null : ; +} + +function PullRequestHorizontalActionToolbar(props: PullRequestActionToolbarProps) { const navigation = useNavigation(); - const { draft } = usePullRequestReviewDraft(props.params); + const { comments, pendingReviewId, busy: draftBusy } = usePullRequestReviewDraft(props.params); const { themeVariables: colors } = useAppearancePreferences(); const insets = useSafeAreaInsets(); - const nativeMetrics = useNativeLayoutMetrics(); - const verticalControls = nativeMetrics !== null && nativeMetrics.verticalBarEdge !== "none"; const permissions = usePullRequestPermissions(props.params, props.pr); const agent = usePullRequestAgentActions(props.params, props.pr, props.filePath); const canReview = permissions.verdicts.length > 0; - const pendingReview = canReview && draft.comments.length > 0; + const pendingReview = canReview && (comments.length > 0 || Boolean(pendingReviewId)); const showAgentControls = agent.canAsk || !permissions.connected; const canOpenThread = agent.threads.length > 0 || showAgentControls; const { shortLabel } = sourceControlClients.get( (props.pr ?? props.params.initialSummary)?.provider, ).changeRequest; const threadLabel = agent.threads.length ? "Continue thread" : `Work on ${shortLabel}`; - const primaryLabel = pendingReview ? `Submit review · ${draft.comments.length}` : threadLabel; + const primaryLabel = pendingReview + ? `Submit review${comments.length ? ` · ${comments.length}` : ""}` + : threadLabel; const chooseThread = agent.chooseThread; const agentActions = agent.actions.filter((action) => action.task !== "ask"); const open = (mode: "review" | "comment") => @@ -138,7 +317,7 @@ export function PullRequestActionToolbar(props: { const openFiles = props.onOpenFiles ?? (() => navigation.navigate("PullRequestFiles", props.params)); if (!props.pr) return null; - const primaryDisabled = pendingReview ? false : agent.disabled; + const primaryDisabled = pendingReview ? draftBusy : agent.disabled; const showPrimary = pendingReview || canOpenThread; if (Platform.OS === "android") { const primary = ( @@ -188,12 +367,15 @@ export function PullRequestActionToolbar(props: { )} ) : null} - + {props.showFiles !== false ? ( + + ) : null} ); } + const nativeThreadItems = pullRequestThreadMenuItems(agent, "ask"); const primaryControl = showPrimary ? ( !pendingReview && chooseThread ? ( - {agentActions.map((action) => - chooseThread && !action.disabled ? ( - - {renderThreadMenuItems(agent.threadActions(action.task), agent.select)} - - ) : ( - agent.start(action.task)} - > - {action.title} - - ), - )} + {pullRequestAgentMenuItems(agent)} ) : null; - const filesControl = ( - - ); - if (verticalControls) - return ( - - {filesControl} - {agentControl} - {primaryControl} - - ); + // Tabler file-diff geometry, rasterized at 1x/2x/3x for UIKit template images. + const filesControl = + props.showFiles !== false ? ( + + ) : null; return ( {agentControl} diff --git a/apps/mobile/src/features/pull-requests/PullRequestFilesSheet.tsx b/apps/mobile/src/features/pull-requests/PullRequestFilesSheet.tsx new file mode 100644 index 0000000000000..565d71f5e17d6 --- /dev/null +++ b/apps/mobile/src/features/pull-requests/PullRequestFilesSheet.tsx @@ -0,0 +1,73 @@ +import { Modal, Pressable, View } from "react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; +import { AppText as Text } from "../../components/ui/AppText"; +import { SymbolView } from "../../components/ui/AppSymbol"; +import { ReviewFileTree, type ReviewFileTreeItem } from "../review/ReviewFileTree"; +import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; + +/** Shows exactly the file set in the reader, including its chapter and filters. */ +export function PullRequestFilesSheet({ + open, + onClose, + files, + title, + onSelectFile, + onSetViewed, + onLoadMore, +}: { + readonly open: boolean; + readonly onClose: () => void; + readonly files: ReadonlyArray; + readonly title: string; + readonly onSelectFile: (path: string) => void; + readonly onSetViewed?: (paths: ReadonlyArray, viewed: boolean) => void; + readonly onLoadMore?: () => void; +}) { + const { themeVariables: colors } = useAppearancePreferences(); + return ( + + + + + {title} + {files.length} + + + + + {files.length ? ( + { + onSelectFile(path); + onClose(); + }} + onSetViewed={onSetViewed} + /> + ) : ( + No files match this view. + )} + {onLoadMore ? ( + + Load more files + + ) : null} + + + ); +} diff --git a/apps/mobile/src/features/pull-requests/PullRequestInlineCommentScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestInlineCommentScreen.tsx index d199fe3990ca4..3f9e4861a3134 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestInlineCommentScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestInlineCommentScreen.tsx @@ -1,38 +1,64 @@ -import { settlePromise } from "@t3tools/client-runtime/state/runtime"; -import { AsyncResult } from "effect/reactivity"; -import * as Dialog from "../../components/ui/Dialog"; +import { PullRequestThreadCard } from "./PullRequestCommentCard"; +import { Alert } from "react-native"; +import { PullRequestCommentForm } from "./PullRequestCommentForm"; import { useFocusEffect, useNavigation, type StaticScreenProps } from "@react-navigation/native"; import { useRef, useState } from "react"; -import { View } from "react-native"; +import { ScrollView, View } from "react-native"; import type { PullRequestReviewPosition } from "@t3tools/contracts"; -import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText"; +import { AppText as Text } from "../../components/ui/AppText"; import { Button } from "../../components/ui/Button"; +import { SymbolView } from "../../components/ui/AppSymbol"; import { uuidv4 } from "../../lib/uuid"; import { composerPullRequests } from "../../state/pull-requests"; import { useEnvironmentQuery } from "../../state/query"; import { PullRequestSheetContent } from "./PullRequestSheetContent"; -import { usePullRequestReviewDraft } from "./usePullRequestReviewDraft"; +import { setReviewDraftBusy, usePullRequestReviewDraft } from "./usePullRequestReviewDraft"; import { reviewPositionLabel } from "./pullRequestDiffComments"; import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff"; import { usePullRequestPermissions } from "./usePullRequestPermissions"; import { PullRequestCompletionSuggestions } from "./PullRequestCompletionSuggestions"; import { usePullRequestCompletions } from "./usePullRequestCompletions"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import { usePendingReviewCommentActions } from "./usePendingReviewCommentActions"; +import { pendingCommentComposerContext, usePullRequestThreads } from "./usePullRequestThreads"; +import { + PullRequestPendingBadge, + PullRequestPendingCommentActions, +} from "./PullRequestPendingComment"; export type InlineCommentParams = PullRequestParams & { readonly draftId?: string; readonly path: string; readonly oldPath?: string; readonly position: PullRequestReviewPosition; + /** The first line of a range comment, which ends at `position`. */ + readonly startPosition?: PullRequestReviewPosition; readonly headSha: string; readonly code: string; + readonly body?: string; }; export function PullRequestInlineCommentScreen({ route }: StaticScreenProps) { const params = route.params; const navigation = useNavigation(); const store = usePullRequestReviewDraft(params); - const saved = store.draft.comments.find((draft) => draft.id === params.draftId); + const [commentId] = useState(() => params.draftId ?? uuidv4()); + const saved = store.comments.find((draft) => draft.id === commentId); const [editedBody, setBody] = useState(null); - const body = editedBody ?? saved?.body ?? ""; + const body = editedBody ?? saved?.body ?? params.body ?? ""; + const pendingActions = usePendingReviewCommentActions(params); + const updateComment = useAtomCommand(composerPullRequests.updateComment, { + reportFailure: false, + }); + const saveDraftComment = useAtomCommand(composerPullRequests.saveDraftComment, { + reportFailure: false, + }); + const activity = useEnvironmentQuery(composerPullRequests.activity(pullRequestTarget(params))); + const pendingThread = saved?.hostedComment + ? activity.data?.reviewThreads.find((thread) => + thread.comments.some((comment) => comment.id === saved.hostedComment?.commentId), + ) + : undefined; const detail = useEnvironmentQuery(composerPullRequests.detail(pullRequestTarget(params))); const { refresh: refreshDetail } = detail; const completions = usePullRequestCompletions({ @@ -46,10 +72,13 @@ export function PullRequestInlineCommentScreen({ route }: StaticScreenProps { if ( pending.current || + uploading || + store.busy || !store.ready || !body.trim() || detail.isPending || @@ -60,76 +89,182 @@ export function PullRequestInlineCommentScreen({ route }: StaticScreenProps ({ - ...draft, - comments: [ - ...draft.comments.filter((comment) => comment.id !== params.draftId), - { - id: params.draftId ?? uuidv4(), - path: params.path, - ...(params.oldPath ? { oldPath: params.oldPath } : {}), - position: params.position, - headSha: params.headSha, - code: params.code, - body, - }, - ], - })); - // flush reports write failures through the draft store's error field. - const result = await settlePromise(() => store.flush()); - pending.current = false; - setBusy(false); - if (AsyncResult.isSuccess(result)) navigation.goBack(); + let locked = false; + return await (async () => { + let hostedComment = saved?.hostedComment; + if (hostedComment && saved) { + const moved = + saved.headSha !== params.headSha || + saved.path !== params.path || + JSON.stringify(saved.position) !== JSON.stringify(params.position) || + JSON.stringify(saved.startPosition) !== JSON.stringify(params.startPosition); + if (moved) { + if (!(await pendingActions.discard(saved))) return; + hostedComment = undefined; + } + } + if (!setReviewDraftBusy(params, true)) + throw new Error("Wait for the pending comment to finish saving."); + locked = true; + if (hostedComment && saved && body !== saved.body) { + const target = pullRequestTarget(params); + const result = await updateComment({ + ...target, + input: { + ...target.input, + kind: "review-comment", + commentId: hostedComment.commentId, + body, + }, + }); + if (result._tag === "Failure") throw squashAtomCommandFailure(result); + } + const comment = { + id: commentId, + path: params.path, + ...(params.oldPath ? { oldPath: params.oldPath } : {}), + position: params.position, + ...(params.startPosition ? { startPosition: params.startPosition } : {}), + headSha: params.headSha, + code: params.code, + body, + ...(hostedComment ? { hostedComment } : {}), + }; + store.update((draft) => ({ + ...draft, + comments: [...draft.comments.filter((comment) => comment.id !== commentId), comment], + })); + await store.flush(); + if (!hostedComment && detail.data?.capabilities.review.draftComment === true) { + const target = pullRequestTarget(params); + const result = await saveDraftComment({ + ...target, + input: { ...target.input, comment }, + }); + if (result._tag === "Failure") throw squashAtomCommandFailure(result); + store.update((draft) => ({ + ...draft, + comments: draft.comments.map((entry) => + entry.id === comment.id ? { ...entry, hostedComment: result.value } : entry, + ), + })); + await store.flush(); + } + detail.refresh(); + navigation.goBack(); + })() + .catch(async (cause: unknown) => { + Alert.alert( + "Could not save the review comment", + `${cause instanceof Error ? cause.message : "Saving failed."}\nYour draft is kept in T3. Try saving again.`, + ); + }) + .finally(async () => { + if (locked) setReviewDraftBusy(params, false); + pending.current = false; + setBusy(false); + }); + }; + const agent = usePullRequestThreads(params, detail.data, params.path); + const addToComposer = async () => { + if (!detail.data || !body.trim()) return; + const added = await agent.addToComposer({ + context: pendingCommentComposerContext(detail.data, { + path: params.path, + body, + code: params.code, + position: params.position, + ...(params.startPosition ? { startPosition: params.startPosition } : {}), + }), + filePath: params.path, + }); + if (added) navigation.goBack(); }; + const canSave = + !uploading && + !store.busy && + store.ready && + Boolean(body.trim()) && + !detail.isPending && + detail.error === null && + !stale && + permissions.canInlineComment; return ( void save()} - /> + + + + ); + }; + const viewTabs = ( + { + const next = values[0]; + if (next === "files" || next === "git") { + if (next === "files" && selection.path) setWorkspacePath(selection.path); + setView(next); + } + }} + aria-label="Workspace navigation" + > + + + Git + + {changedCount} + + + + + Files + + + ); + return ( +
+
+
+ + {view === "git" + ? scope === "staged" + ? "Staged" + : "Unstaged" + : (workspacePath ?? "Workspace files")} + + {!fileTreeOpen ? viewTabs : null} +
+ {fileTreeOpen ? ( +
+ {viewTabs} +
+ ) : null} +
+
+
+ {view === "files" ? ( + + ) : ( + <> + {data.query.error ? ( +
+

{data.query.error}

+ +
+ ) : null} + {files.length === 0 ? ( +

+ {!optimistic && data.query.isPending ? "Loading changes…" : "No changes."} +

+ ) : ( + + canStage && + !pending && + Boolean( + reviewSelectedLinesPatch( + data.hunksByPath.get(resolveFileDiffPath(file)) ?? [], + range, + scope === "staged", + props.split ? "split" : "unified", + ), + ) + } + onStageLines={ + view === "git" + ? (file, range) => { + const path = resolveFileDiffPath(file); + const patch = reviewSelectedLinesPatch( + data.hunksByPath.get(path) ?? [], + range, + scope === "staged", + props.split ? "split" : "unified", + ); + if (patch) void updateStaging(scope, stagingPaths(scope, path), patch); + } + : undefined + } + canRevertLines={(file, range) => + canRevert && + !pending && + Boolean( + reviewSelectedLinesPatch( + data.hunksByPath.get(resolveFileDiffPath(file)) ?? [], + range, + true, + props.split ? "split" : "unified", + ), + ) + } + onRevertLines={ + view === "git" && scope === "unstaged" + ? (file, range) => { + const path = resolveFileDiffPath(file); + const patch = reviewSelectedLinesPatch( + data.hunksByPath.get(path) ?? [], + range, + true, + props.split ? "split" : "unified", + ); + if (patch) + setReverting({ + paths: stagingPaths(scope, path), + patch, + label: `the selected ${range.start === range.end ? "line" : "lines"} in ${path}`, + }); + } + : undefined + } + renderHunkAction={ + view === "git" + ? (file, index) => { + const path = resolveFileDiffPath(file); + const patch = reviewHunkPatch( + data.hunksByPath.get(path) ?? [], + file.hunks[index]?.hunkSpecs ?? "", + ); + return patch ? ( +
+ {scope === "unstaged" ? ( + + ) : null} + +
+ ) : null; + } + : undefined + } + renderHeaderFilenameSuffix={renderActions} + renderHeaderMetadata={(file) => { + const stat = file.cacheKey?.endsWith(":pending") + ? data.source?.files?.find((stat) => stat.path === resolveFileDiffPath(file)) + : null; + return ; + }} + renderHeaderPrefix={(file) => ( + + )} + onRevealSearchMatch={(key) => { + const file = files.find((file) => buildFileDiffIdentityKey(file) === key); + if (file) + setFolded( + (current) => + new Set( + [...current].filter((path) => path !== resolveFileDiffPath(file)), + ), + ); + }} + options={{ + diffStyle: props.split ? "split" : "unified", + overflow: props.wordWrap ? "wrap" : "scroll", + theme: resolveDiffThemeName(resolvedTheme), + themeType: resolvedTheme, + ...(optimistic ? {} : { loadDiffFiles: data.loadDiffFiles }), + }} + /> + )} + {data.patches.settledFileCount < data.files.length && !selectedPath ? ( + + ) : null} + + )} +
+ {fileTreeOpen ? ( + + ) : null} +
+ { + if (!open && !pending) setReverting(null); + }} + > + + + Revert unstaged changes? + + This reverts {reverting?.patch ? "only " : "unstaged edits in "} + {reverting?.label}. Staged changes are kept. + {!reverting?.patch ? " Selected new, untracked files will be deleted." : null} + + + + + + + + +
+ ); +} diff --git a/apps/web/src/components/diffs/WorkingChangesTree.tsx b/apps/web/src/components/diffs/WorkingChangesTree.tsx new file mode 100644 index 0000000000000..55fd13b277462 --- /dev/null +++ b/apps/web/src/components/diffs/WorkingChangesTree.tsx @@ -0,0 +1,339 @@ +import { LegendList, type LegendListRef } from "@legendapp/list/react"; +import { reviewFileTreeRows, reviewFolderContains } from "@t3tools/client-runtime/review-workspace"; +import { + reviewTreeRowKey, + selectReviewTreeRows, + reviewTreeActionFiles, + type ReviewTreeRow, + type ReviewTreeSelection, +} from "@t3tools/client-runtime/review-tree-selection"; +import { ChevronDown, ChevronRight, Minus, Plus, Undo2, PanelsTopLeft } from "lucide-react"; +import { useEffect, useRef, useState } from "react"; +import { useTheme } from "~/hooks/useTheme"; +import { PierreEntryIcon } from "../chat/PierreEntryIcon"; +import { ReviewIcon as MorphIcon } from "~/components/ReviewIcon"; +import { Button } from "../ui/button"; +import { Badge } from "../ui/badge"; +import { Menu, MenuItem, MenuPopup } from "../ui/menu"; +import { ReviewPath } from "./ReviewPath"; +import type { DiffFileTreeEntry } from "./diffFileTree.logic"; + +type Scope = "staged" | "unstaged"; +type Row = + | { kind: "section"; scope: Scope; path: string } + | (ReturnType>[number] & { scope: Scope }); + +/** One virtualized list keeps Git sections adjacent and exposes actions beside every row. */ +export function WorkingChangesTree({ + staged, + unstaged, + selected, + disabled, + revertDisabled, + onSelect, + onStage, + onRevert, + onViewAll, +}: { + staged: ReadonlyArray; + unstaged: ReadonlyArray; + selected: { scope: Scope; path: string } | null; + disabled: boolean; + revertDisabled: boolean; + onSelect: (scope: Scope, path: string) => void; + onStage: (scope: Scope, paths: ReadonlyArray | null) => void; + onRevert: (paths: ReadonlyArray | null) => void; + onViewAll: (scope: Scope) => void; +}) { + const { resolvedTheme } = useTheme(); + const list = useRef(null); + const [open, setOpen] = useState({ staged: true, unstaged: true }); + const [collapsed, setCollapsed] = useState>(() => new Set()); + const [selection, setSelection] = useState(() => ({ + rows: selected ? [{ ...selected, kind: "file" }] : [], + anchor: selected ? { ...selected, kind: "file" } : null, + })); + const [contextMenu, setContextMenu] = useState<{ + row: ReviewTreeRow; + x: number; + y: number; + } | null>(null); + const menuAnchor = contextMenu + ? { getBoundingClientRect: () => new DOMRect(contextMenu.x, contextMenu.y, 0, 0) } + : undefined; + const lastRevealed = useRef(null); + const sections = { staged, unstaged }; + const sectionPaths = { + staged: staged.map((file) => file.path), + unstaged: unstaged.map((file) => file.path), + }; + const rows = (["staged", "unstaged"] as const).flatMap((scope) => [ + { kind: "section" as const, scope, path: scope }, + ...(open[scope] + ? reviewFileTreeRows( + scope === "staged" ? staged : unstaged, + (entry) => entry.path, + new Set( + [...collapsed] + .filter((key) => key.startsWith(`${scope}:`)) + .map((key) => key.slice(scope.length + 1)), + ), + ).map((row) => ({ ...row, scope })) + : []), + ]) satisfies Row[]; + const selectableRows = rows.filter((row) => row.kind !== "section"); + const selectedKeys = new Set(selection.rows.map(reviewTreeRowKey)); + const selectedFolders = selection.rows.filter((row) => row.kind === "folder"); + const isInSelection = (row: ReviewTreeRow) => + selectedKeys.has(reviewTreeRowKey(row)) || + selectedFolders.some( + (folder) => folder.scope === row.scope && reviewFolderContains(folder.path, row.path), + ); + const contextPaths = contextMenu + ? reviewTreeActionFiles(sectionPaths[contextMenu.row.scope], selection.rows, contextMenu.row) + : []; + const revealScope = selected?.scope; + const revealPath = selected?.path; + const revealKey = selected ? reviewTreeRowKey(selected) : null; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Scroll the virtualized tree to an externally selected file. + useEffect(() => { + if (revealKey === lastRevealed.current) return; + const index = rows.findIndex( + (row) => row.kind === "file" && row.scope === revealScope && row.path === revealPath, + ); + if (index >= 0) { + lastRevealed.current = revealKey; + list.current?.scrollToIndex({ index, animated: false, viewPosition: 0.5 }); + } + if (revealKey === null) lastRevealed.current = null; + }, [rows, revealScope, revealPath, revealKey]); + const toggleFolder = (row: ReviewTreeRow) => + setCollapsed((current) => { + const next = new Set(current); + const key = `${row.scope}:${row.path}`; + if (next.has(key)) next.delete(key); + else next.add(key); + return next; + }); + const actions = (scope: Scope, row: ReviewTreeRow | null) => { + const path = row?.path ?? null; + const groupTarget = row && isInSelection(row); + const label = + groupTarget && (selection.rows.length > 1 || row.kind === "folder") + ? "selected files" + : (path ?? "all files"); + const targets = () => reviewTreeActionFiles(sectionPaths[scope], selection.rows, row); + return ( +
+ {scope === "unstaged" ? ( + + ) : null} + +
+ ); + }; + return ( +
+ `${row.scope}:${row.kind}:${row.path}`} + estimatedItemSize={24} + drawDistance={240} + className="min-h-0 flex-1 overflow-x-hidden px-4" + extraData={{ selected, selectedKeys, disabled, revertDisabled, resolvedTheme }} + renderItem={({ item: row }) => { + if (row.kind === "section") + return ( +
+ + + {sections[row.scope].length} + + + {actions(row.scope, null)} +
+ ); + const folder = row.kind === "folder"; + const batchSelected = selectedKeys.has(reviewTreeRowKey(row)); + const current = selected?.scope === row.scope && selected.path === row.path; + const status = folder ? "modified" : row.file.status; + const statusColor = + status === "added" || status === "untracked" + ? "light-dark(#16a994, #00cab1)" + : status === "deleted" + ? "light-dark(#ff2e3f, #ff6762)" + : status === "renamed" + ? "light-dark(#d5a910, #ffd452)" + : "light-dark(#1ca1c7, #08c0ef)"; + return ( +
{ + event.preventDefault(); + event.stopPropagation(); + if (!isInSelection(row)) setSelection({ rows: [row], anchor: row }); + setContextMenu({ row, x: event.clientX, y: event.clientY }); + }} + > + {folder ? ( + + ) : null} + +
+ {actions(row.scope, row)} +
+ + {folder + ? "•" + : row.file.status === "added" + ? "A" + : row.file.status === "deleted" + ? "D" + : row.file.status === "renamed" + ? "R" + : "M"} + +
+ ); + }} + /> + { + if (!open) setContextMenu(null); + }} + > + + {contextMenu ? ( + <> + { + onStage(contextMenu.row.scope, contextPaths); + setContextMenu(null); + }} + > + + {contextMenu.row.scope === "staged" ? "Unstage changes" : "Stage changes"} + + {contextMenu.row.scope === "unstaged" ? ( + { + onRevert(contextPaths); + setContextMenu(null); + }} + > + + Revert changes + + ) : null} + + ) : null} + + +
+ ); +} diff --git a/apps/web/src/components/diffs/diffFileTree.logic.ts b/apps/web/src/components/diffs/diffFileTree.logic.ts index 41d2a5e676e70..612b38c88f2a0 100644 --- a/apps/web/src/components/diffs/diffFileTree.logic.ts +++ b/apps/web/src/components/diffs/diffFileTree.logic.ts @@ -12,6 +12,26 @@ import { basenameOfPath, resolvePierreIconForEntry, T3_PIERRE_ICONS } from "~/pi export interface DiffFileTreeEntry { readonly path: string; readonly status: GitStatus; + readonly reviewed?: boolean; + readonly unresolvedComments?: number; +} + +/** Pierre folder ids end with a slash; a selected folder includes its hidden descendants. */ +export function diffFileTreeReviewEntries( + entries: ReadonlyArray, + selectedPaths: ReadonlyArray, + clickedPath: string, +): ReadonlyArray { + const contains = (target: string, path: string) => + target.endsWith("/") ? path.startsWith(target) : path === target; + const targets = selectedPaths.some((path) => contains(path, clickedPath)) + ? selectedPaths + : [clickedPath]; + const exact = new Set(targets); + const folders = targets.filter((path) => path.endsWith("/")); + return entries.filter( + (entry) => exact.has(entry.path) || folders.some((path) => entry.path.startsWith(path)), + ); } function toGitStatus(file: FileDiffMetadata): GitStatus { diff --git a/apps/web/src/components/diffs/useReviewFilePatches.ts b/apps/web/src/components/diffs/useReviewFilePatches.ts index 4f68b51fb5edd..2e53ef59e5642 100644 --- a/apps/web/src/components/diffs/useReviewFilePatches.ts +++ b/apps/web/src/components/diffs/useReviewFilePatches.ts @@ -1,3 +1,4 @@ +import { orderReviewFiles } from "@t3tools/client-runtime/review-workspace"; import { RegistryContext, useAtomValue } from "@effect/atom-react"; import type { FileDiffMetadata } from "@pierre/diffs"; import type { @@ -28,6 +29,7 @@ export function useReviewFilePatches({ theme, previewInput, preview, + workingTreeScope, }: { environmentId: EnvironmentId | undefined; cwd: string | undefined; @@ -38,6 +40,7 @@ export function useReviewFilePatches({ /** The preview the file list came from; a newer revision of it refreshes loaded patches. */ previewInput: ReviewDiffPreviewInput | undefined; preview: RenderablePatch | null; + workingTreeScope?: "staged" | "unstaged" | undefined; }) { const registry = useContext(RegistryContext); const scope = JSON.stringify([ @@ -47,7 +50,7 @@ export function useReviewFilePatches({ source?.baseRef, source?.headRef, baseRef, - ignoreWhitespace, + workingTreeScope, ]); const files = sortedReviewFiles(source); const automaticPaths = files.slice(0, INITIAL_FILE_COUNT).map((file) => file.path); @@ -66,9 +69,10 @@ export function useReviewFilePatches({ previewInput, scope, requested, + workingTreeScope, }); const queriedPatchesAtom = reviewPatchesAtom( - JSON.stringify([theme, queries.map(({ index, target }) => [index, target])]), + JSON.stringify([theme, ignoreWhitespace, queries.map(({ index, target }) => [index, target])]), ); const patches = useAtomValue(queriedPatchesAtom); const retry = useStableCallback((path: string) => { @@ -117,7 +121,14 @@ export function useReviewFilePatches({ { name: file.path, ...(file.previousPath ? { prevName: file.previousPath } : {}), - type: file.changeType ?? (file.previousPath ? "rename-changed" : "change"), + type: + file.status === "added" + ? "new" + : file.status === "deleted" + ? "deleted" + : file.previousPath || file.status === "renamed" + ? "rename-changed" + : "change", hunks: [], additionLines: [], deletionLines: [], @@ -130,9 +141,7 @@ export function useReviewFilePatches({ }, ]; }) - : (preview?.kind === "files" ? preview.files : []).toSorted((a, b) => - filePathCollator.compare(resolveFileDiffPath(a), resolveFileDiffPath(b)), - ); + : orderReviewFiles(preview?.kind === "files" ? preview.files : [], resolveFileDiffPath); const fileStates = new Map( files.map((file, index) => { const patch = patches.get(index); @@ -151,7 +160,22 @@ export function useReviewFilePatches({ ] as const; }), ); + const readyFilePaths = new Set( + files + .filter((_, index) => { + const patch = patches.get(index); + return patch && patch._tag !== "Initial"; + }) + .map((file) => file.path), + ); + const rawPatches = [...patches.values()].flatMap((result) => + result._tag === "Success" ? [result.value.source.diff] : [], + ); return { + rawPatches, + scope, + settledFileCount, + readyFilePaths, fileStates, isPending: [...patches.values()].some((patch) => patch._tag === "Initial" || patch.waiting), retry, @@ -167,10 +191,10 @@ function reviewFileQueries({ cwd, source, baseRef, - ignoreWhitespace, previewInput, scope, requested, + workingTreeScope, }: { environmentId: EnvironmentId | undefined; cwd: string | undefined; @@ -178,6 +202,7 @@ function reviewFileQueries({ baseRef: string | null; ignoreWhitespace: boolean; previewInput: ReviewDiffPreviewInput | undefined; + workingTreeScope?: "staged" | "unstaged" | undefined; scope: string; requested: { scope: string; paths: string[] }; }) { @@ -201,7 +226,8 @@ function reviewFileQueries({ cwd, ...(baseRef ? { baseRef } : {}), ...(source.kind === "commit" ? { commitSha: source.id } : {}), - ignoreWhitespace, + ignoreWhitespace: false, + ...(workingTreeScope ? { workingTreeScope } : {}), file: { path: file.path, previousPath: file.previousPath, @@ -216,17 +242,22 @@ function reviewFileQueries({ } function sortedReviewFiles(source: ReviewDiffPreviewSource | null) { - return source?.files?.toSorted((a, b) => filePathCollator.compare(a.path, b.path)) ?? []; + return orderReviewFiles(source?.files ?? [], (file) => file.path); } type ReviewPatchTarget = Parameters[0]; const parsedPatchAtom = Atom.family((key: string) => { - const [theme, target] = JSON.parse(key) as ["light" | "dark", ReviewPatchTarget]; + const [theme, ignoreWhitespace, target] = JSON.parse(key) as [ + "light" | "dark", + boolean, + ReviewPatchTarget, + ]; return Atom.map(reviewEnvironment.diffFilePatch(target), (result) => AsyncResult.map(result, (source) => { let patch = getRenderablePatch(source.diff, `diff-panel:${theme}`, { compactPartialHunkOffsets: true, + ignoreWhitespace, }); if (patch?.kind === "files" && patch.files.length === 1 && source.files?.length === 1) { const stat = source.files[0]!; @@ -241,12 +272,14 @@ const parsedPatchAtom = Atom.family((key: string) => { }); const reviewPatchesAtom = Atom.family((key: string) => { - const [theme, entries] = JSON.parse(key) as [ + const [theme, ignoreWhitespace, entries] = JSON.parse(key) as [ "light" | "dark", + boolean, ReadonlyArray, ]; const parsed = entries.map( - ([index, target]) => [index, parsedPatchAtom(JSON.stringify([theme, target]))] as const, + ([index, target]) => + [index, parsedPatchAtom(JSON.stringify([theme, ignoreWhitespace, target]))] as const, ); return Atom.make((get) => new Map(parsed.map(([index, atom]) => [index, get(atom)]))); }); diff --git a/apps/web/src/components/diffs/workingChangesState.test.ts b/apps/web/src/components/diffs/workingChangesState.test.ts new file mode 100644 index 0000000000000..d1666732d3fe9 --- /dev/null +++ b/apps/web/src/components/diffs/workingChangesState.test.ts @@ -0,0 +1,440 @@ +import { describe, expect, it } from "vite-plus/test"; +import { hydratePartialDiff } from "@pierre/diffs"; +import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles"; +import { + reviewPatchHunks, + reviewSelectedLinesPatch, +} from "@t3tools/client-runtime/review-workspace"; +import { reviewDiffEdits } from "@t3tools/client-runtime/review-diff-context"; +import { getRenderablePatch } from "~/lib/diffRendering"; +import { + applyWorkingChangesMutation, + type WorkingChangesSnapshot, + type WorkingChangesState, +} from "./workingChangesState"; + +const header = "diff --git a/file.txt b/file.txt\n--- a/file.txt\n+++ b/file.txt\n"; +function snapshot(body: string): WorkingChangesSnapshot { + if (!body) return { files: [], hunksByPath: new Map() }; + const patch = header + body; + const parsed = getRenderablePatch(patch, patch); + if (parsed?.kind !== "files") throw new Error("Invalid fixture"); + return { + files: parsed.files, + hunksByPath: new Map([["file.txt", reviewPatchHunks(patch)[0]!.hunks]]), + }; +} +function edits(snapshot: WorkingChangesSnapshot) { + return snapshot.files.flatMap((file) => + file.hunks.flatMap((hunk) => + hunk.hunkContent.flatMap((content) => + content.type === "change" + ? [ + ...file.deletionLines + .slice(content.deletionLineIndex, content.deletionLineIndex + content.deletions) + .map((line) => `-${line.trimEnd()}`), + ...file.additionLines + .slice(content.additionLineIndex, content.additionLineIndex + content.additions) + .map((line) => `+${line.trimEnd()}`), + ] + : [], + ), + ), + ); +} +const stagedAlpha = snapshot("@@ -1,3 +1,3 @@\n-alpha\n+ALPHA\n beta\n gamma\n"); +const unstagedGamma = snapshot("@@ -1,3 +1,3 @@\n ALPHA\n beta\n-gamma\n+GAMMA\n"); +const combined = snapshot("@@ -1,3 +1,3 @@\n-alpha\n+ALPHA\n beta\n-gamma\n+GAMMA\n"); + +describe("optimistic working changes", () => { + it("reverts one selected added line while preserving staged and neighboring unstaged changes", () => { + const unstaged = snapshot("@@ -1,3 +1,4 @@\n ALPHA\n-beta\n+BETA\n+extra\n gamma\n"); + const patch = reviewSelectedLinesPatch( + unstaged.hunksByPath.get("file.txt")!, + { start: 3, end: 3, side: "additions" }, + true, + )!; + const next = applyWorkingChangesMutation({ staged: stagedAlpha, unstaged }, unstaged, { + scope: "unstaged", + paths: ["file.txt"], + patch, + revert: true, + }); + expect(edits(next.unstaged)).toEqual(["-beta", "+BETA"]); + expect(edits(next.staged)).toEqual(["-alpha", "+ALPHA"]); + expect(next.staged.hunksByPath.get("file.txt")).toEqual( + stagedAlpha.hunksByPath.get("file.txt"), + ); + }); + + it("removes a completed hunk from the all-files render but retains it as context in a selected file", () => { + const unstaged = snapshot( + "@@ -1,3 +1,3 @@\n-old\n+new\n context\n end\n@@ -20,1 +20,1 @@\n-other old\n+other new\n", + ); + const patch = unstaged.hunksByPath.get("file.txt")![0]!; + const mutation = { scope: "unstaged" as const, paths: ["file.txt"], patch, revert: true }; + const allFiles = applyWorkingChangesMutation({ staged: snapshot(""), unstaged }, unstaged, { + ...mutation, + retainContext: false, + }); + const singleFile = applyWorkingChangesMutation({ staged: snapshot(""), unstaged }, unstaged, { + ...mutation, + retainContext: true, + }); + expect(edits(allFiles.unstaged)).toEqual(["-other old", "+other new"]); + expect(allFiles.unstaged.files[0]!.hunks).toHaveLength(1); + expect(allFiles.unstaged.files[0]!.hunks[0]!.additionStart).toBe(20); + expect(singleFile.unstaged.files[0]!.hunks).toHaveLength(2); + const final = applyWorkingChangesMutation(singleFile, unstaged, { + ...mutation, + patch: singleFile.unstaged.hunksByPath.get("file.txt")![0]!, + retainContext: true, + }); + expect(final.unstaged.files).toEqual([]); + expect(final.unstaged.retainedFiles).toHaveLength(1); + expect(reviewDiffEdits(final.unstaged.retainedFiles![0]!)).toBe("[]"); + expect(final.staged.files).toEqual([]); + }); + + it("retains a fully reverted file as context for the single-file reader", () => { + const next = applyWorkingChangesMutation( + { staged: stagedAlpha, unstaged: unstagedGamma }, + combined, + { scope: "unstaged", paths: ["file.txt"], revert: true }, + ); + expect(next.unstaged.files).toEqual([]); + expect(next.unstaged.retainedFiles).toHaveLength(1); + expect(reviewDiffEdits(next.unstaged.retainedFiles![0]!)).toBe("[]"); + expect(edits(next.staged)).toEqual(["-alpha", "+ALPHA"]); + }); + + it("keeps a restored line visible after reverting an addition and then its remaining deletion", () => { + const unstaged = snapshot("@@ -1,3 +1,3 @@\n ALPHA\n-beta\n+BETA\n gamma\n"); + const patch = reviewSelectedLinesPatch( + unstaged.hunksByPath.get("file.txt")!, + { start: 2, end: 2, side: "additions" }, + true, + )!; + const partial = applyWorkingChangesMutation({ staged: stagedAlpha, unstaged }, unstaged, { + scope: "unstaged", + paths: ["file.txt"], + patch, + revert: true, + }); + const cleared = applyWorkingChangesMutation(partial, unstaged, { + scope: "unstaged", + paths: ["file.txt"], + patch: partial.unstaged.hunksByPath.get("file.txt")![0]!, + revert: true, + }); + expect(cleared.unstaged.files).toEqual([]); + expect(cleared.unstaged.retainedFiles![0]!.additionLines).toContain("beta\n"); + }); + + it.each(["staged", "unstaged"] as const)( + "drops cleared hunks from the %s all-files view", + (scope) => { + const changes = snapshot( + "@@ -1,1 +1,1 @@\n-old\n+new\n@@ -20,1 +20,1 @@\n-other old\n+other new\n", + ); + const empty = snapshot(""); + const current = { + staged: scope === "staged" ? changes : empty, + unstaged: scope === "unstaged" ? changes : empty, + }; + const next = applyWorkingChangesMutation(current, changes, { + scope, + paths: ["file.txt"], + patch: changes.hunksByPath.get("file.txt")![0]!, + retainContext: false, + }); + expect(next[scope].files[0]!.hunks).toHaveLength(1); + expect(edits(next[scope])).toEqual(["-other old", "+other new"]); + }, + ); + + it("composes overlapping context when a hunk moves into an already-staged file", () => { + const current = { staged: stagedAlpha, unstaged: unstagedGamma }; + const next = applyWorkingChangesMutation(current, combined, { + scope: "unstaged", + paths: ["file.txt"], + patch: unstagedGamma.hunksByPath.get("file.txt")![0]!, + }); + expect(next.unstaged.files).toEqual([]); + expect(edits(next.staged)).toEqual(["-alpha", "+ALPHA", "-gamma", "+GAMMA"]); + expect( + next.staged.files[0]?.hunks.map((hunk) => [hunk.deletionStart, hunk.additionStart]), + ).toEqual([[1, 1]]); + // The retained authoritative snapshot is a complete rollback, not a mutated cache. + expect(current.staged).toBe(stagedAlpha); + expect(current.unstaged).toBe(unstagedGamma); + expect(edits(current.unstaged)).toEqual(["-gamma", "+GAMMA"]); + }); + + it("unstages a hunk without losing another staged edit in the same file", () => { + const next = applyWorkingChangesMutation( + { staged: combined, unstaged: snapshot("") }, + combined, + { + scope: "staged", + paths: ["file.txt"], + patch: unstagedGamma.hunksByPath.get("file.txt")![0]!, + }, + ); + expect(edits(next.staged)).toEqual(["-alpha", "+ALPHA"]); + expect(edits(next.unstaged)).toEqual(["-gamma", "+GAMMA"]); + }); + + it("keeps correct destination coordinates when unstaging an insertion before unstaged edits", () => { + const staged = snapshot("@@ -1,3 +1,4 @@\n alpha\n+inserted\n beta\n gamma\n"); + const unstaged = snapshot("@@ -1,4 +1,4 @@\n alpha\n inserted\n beta\n-gamma\n+GAMMA\n"); + const next = applyWorkingChangesMutation({ staged, unstaged }, snapshot(""), { + scope: "staged", + paths: ["file.txt"], + patch: staged.hunksByPath.get("file.txt")![0]!, + }); + expect(next.staged.files).toEqual([]); + expect(edits(next.unstaged)).toEqual(["+inserted", "-gamma", "+GAMMA"]); + expect(JSON.parse(reviewDiffEdits(next.unstaged.files[0]!))).toContainEqual([ + "+", + 4, + "GAMMA\n", + ]); + expect(JSON.parse(reviewDiffEdits(next.unstaged.files[0]!))).toContainEqual([ + "-", + 3, + "gamma\n", + ]); + }); + + it("stages selected added lines while keeping the remaining replacement unstaged", () => { + const current: WorkingChangesState = { + staged: snapshot(""), + unstaged: snapshot("@@ -1,3 +1,4 @@\n alpha\n-beta\n+BETA\n+extra\n gamma\n"), + }; + const selected = header + "@@ -1,3 +1,4 @@\n alpha\n beta\n+extra\n gamma\n"; + const next = applyWorkingChangesMutation(current, snapshot(""), { + scope: "unstaged", + paths: ["file.txt"], + patch: selected, + }); + expect(edits(next.staged)).toEqual(["+extra"]); + expect(edits(next.unstaged)).toEqual(["-beta", "+BETA"]); + for (const scope of [next.staged, next.unstaged]) { + for (const patch of scope.hunksByPath.get("file.txt")!) { + expect(parsePatchFiles(patch, { throwOnError: true })[0]?.files).toHaveLength(1); + } + } + expect(next.unstaged.files[0]?.additionLines).toEqual([ + "alpha\n", + "BETA\n", + "extra\n", + "gamma\n", + ]); + }); + + it("whole-file stage and unstage merge both scopes without dropping existing edits", () => { + const staged = applyWorkingChangesMutation( + { staged: stagedAlpha, unstaged: unstagedGamma }, + combined, + { scope: "unstaged", paths: ["file.txt"] }, + ); + expect(staged.unstaged.files).toEqual([]); + expect(edits(staged.staged)).toEqual(["-alpha", "+ALPHA", "-gamma", "+GAMMA"]); + const unstaged = applyWorkingChangesMutation( + { staged: stagedAlpha, unstaged: unstagedGamma }, + combined, + { scope: "staged", paths: ["file.txt"] }, + ); + expect(unstaged.staged.files).toEqual([]); + expect(edits(unstaged.unstaged)).toEqual(["-alpha", "+ALPHA", "-gamma", "+GAMMA"]); + }); + + it("revert removes only the unstaged entry and retains the staged snapshot", () => { + const next = applyWorkingChangesMutation( + { staged: stagedAlpha, unstaged: unstagedGamma }, + combined, + { scope: "unstaged", paths: ["file.txt"], revert: true }, + ); + expect(next.unstaged.files).toEqual([]); + expect(edits(next.staged)).toEqual(["-alpha", "+ALPHA"]); + }); + + it("keeps a staged hunk's open code region as context, alongside remaining edits", () => { + const unstaged = snapshot( + "@@ -10,3 +10,3 @@\n before\n-old\n+new\n after\n@@ -30,3 +30,3 @@\n other before\n-other old\n+other new\n other after\n", + ); + const next = applyWorkingChangesMutation({ staged: snapshot(""), unstaged }, unstaged, { + scope: "unstaged", + paths: ["file.txt"], + patch: unstaged.hunksByPath.get("file.txt")![0]!, + }); + const file = next.unstaged.files[0]!; + expect(file.hunks.map((hunk) => [hunk.additionStart, hunk.additionCount])).toEqual([ + [10, 3], + [30, 3], + ]); + expect(file.hunks[0]!.hunkContent).toEqual([ + { type: "context", lines: 3, additionLineIndex: 0, deletionLineIndex: 0 }, + ]); + expect(file.additionLines.slice(0, 3)).toEqual(["before\n", "new\n", "after\n"]); + expect(edits(next.unstaged)).toEqual(["-other old", "+other new"]); + expect(file.additionLines.some((line) => line.includes("\u0000unknown:"))).toBe(false); + }); + + it("keeps the open file after staging its final edit without leaving it in the unstaged tree", () => { + const next = applyWorkingChangesMutation( + { staged: snapshot(""), unstaged: unstagedGamma }, + combined, + { + scope: "unstaged", + paths: ["file.txt"], + }, + ); + expect(next.unstaged.files).toEqual([]); + expect(next.unstaged.retainedFiles).toHaveLength(1); + const file = next.unstaged.retainedFiles![0]!; + expect(reviewDiffEdits(file)).toBe("[]"); + expect(file.additionLines).toEqual(["ALPHA\n", "beta\n", "GAMMA\n"]); + expect(file.hunks[0]!.additionStart).toBe(1); + }); + + it("retains the same context and line mapping when staging selected lines inside a hunk", () => { + const unstaged = snapshot("@@ -10,4 +10,5 @@\n before\n-old\n+new\n+extra\n after\n end\n"); + const next = applyWorkingChangesMutation({ staged: snapshot(""), unstaged }, unstaged, { + scope: "unstaged", + paths: ["file.txt"], + patch: header + "@@ -10,4 +10,5 @@\n before\n old\n+extra\n after\n end\n", + }); + expect(edits(next.unstaged)).toEqual(["-old", "+new"]); + expect(next.unstaged.files[0]!.hunks[0]!.additionStart).toBe(10); + expect(next.unstaged.files[0]!.additionLines).toEqual([ + "before\n", + "new\n", + "extra\n", + "after\n", + "end\n", + ]); + const authoritative = snapshot( + "@@ -10,5 +10,5 @@\n before\n-old\n+new\n extra\n after\n end\n", + ); + expect(reviewDiffEdits(next.unstaged.files[0]!)).toBe(reviewDiffEdits(authoritative.files[0]!)); + }); + + it("preserves both open regions across consecutive writes after Git regroups the remaining patch", () => { + const unstaged = snapshot( + "@@ -10,3 +10,3 @@\n before\n-old\n+new\n after\n@@ -30,3 +30,3 @@\n other before\n-other old\n+other new\n other after\n", + ); + const first = applyWorkingChangesMutation({ staged: snapshot(""), unstaged }, unstaged, { + scope: "unstaged", + paths: ["file.txt"], + patch: unstaged.hunksByPath.get("file.txt")![0]!, + }); + const refreshed = snapshot( + "@@ -30,3 +30,3 @@\n other before\n-other old\n+other new\n other after\n", + ); + const second = applyWorkingChangesMutation( + { + staged: first.staged, + unstaged: { ...refreshed, files: first.unstaged.files }, + }, + unstaged, + { + scope: "unstaged", + paths: ["file.txt"], + patch: refreshed.hunksByPath.get("file.txt")![0]!, + }, + ); + expect(second.unstaged.files).toEqual([]); + const file = second.unstaged.retainedFiles![0]!; + expect(reviewDiffEdits(file)).toBe("[]"); + expect(file.hunks.map((hunk) => [hunk.additionStart, hunk.additionCount])).toEqual([ + [10, 3], + [30, 3], + ]); + expect(file.additionLines).toEqual([ + "before\n", + "new\n", + "after\n", + "other before\n", + "other new\n", + "other after\n", + ]); + }); + + it("retains hydrated full contents and region indices so expanded context stays available", () => { + const oldLines = Array.from({ length: 40 }, (_, index) => `line ${index + 1}\n`); + const newLines = [...oldLines]; + newLines[10] = "new first\n"; + newLines[30] = "new second\n"; + const unstaged = snapshot( + "@@ -10,3 +10,3 @@\n line 10\n-line 11\n+new first\n line 12\n@@ -30,3 +30,3 @@\n line 30\n-line 31\n+new second\n line 32\n", + ); + hydratePartialDiff("merge", unstaged.files[0]!, { + oldFile: { name: "file.txt", contents: oldLines.join("") }, + newFile: { name: "file.txt", contents: newLines.join("") }, + }); + const next = applyWorkingChangesMutation({ staged: snapshot(""), unstaged }, unstaged, { + scope: "unstaged", + paths: ["file.txt"], + patch: unstaged.hunksByPath.get("file.txt")![0]!, + }); + const file = next.unstaged.files[0]!; + expect(file.isPartial).toBe(false); + expect(file.additionLines).toEqual(newLines); + expect(file.deletionLines[10]).toBe("new first\n"); + expect(file.deletionLines[30]).toBe("line 31\n"); + expect(file.hunks.map((hunk) => [hunk.additionStart, hunk.additionLineIndex])).toEqual([ + [10, 9], + [30, 29], + ]); + expect(file.hunks.map((hunk) => hunk.splitLineStart)).toEqual([9, 29]); + expect(file.splitLineCount).toBe(40); + expect(file.unifiedLineCount).toBe(41); + expect(edits(next.unstaged)).toEqual(["-line 31", "+new second"]); + }); + + it("keeps nearby and far hydrated windows while selected insertion lines become context", () => { + const original = Array.from({ length: 150 }, (_, index) => `line ${index + 1}\n`); + const working = [...original]; + working[82] = "changed near\n"; + working[123] = "changed far\n"; + working.splice(83, 0, "extra\n"); + const unstaged = snapshot( + "@@ -80,7 +80,8 @@\n line 80\n line 81\n line 82\n-line 83\n+changed near\n+extra\n line 84\n line 85\n line 86\n@@ -121,7 +122,7 @@\n line 121\n line 122\n line 123\n-line 124\n+changed far\n line 125\n line 126\n line 127\n", + ); + hydratePartialDiff("merge", unstaged.files[0]!, { + oldFile: { name: "file.txt", contents: original.join("") }, + newFile: { name: "file.txt", contents: working.join("") }, + }); + const selected = + header + + "@@ -80,7 +80,8 @@\n line 80\n line 81\n line 82\n line 83\n+extra\n line 84\n line 85\n line 86\n"; + const next = applyWorkingChangesMutation({ staged: snapshot(""), unstaged }, unstaged, { + scope: "unstaged", + paths: ["file.txt"], + patch: selected, + }); + const file = next.unstaged.files[0]!; + expect(file.isPartial).toBe(false); + expect(file.additionLines).toEqual(working); + expect(file.deletionLines[83]).toBe("extra\n"); + expect(file.hunks.map((hunk) => [hunk.additionStart, hunk.additionCount])).toEqual([ + [80, 8], + [122, 7], + ]); + expect(file.hunks.map((hunk) => hunk.splitLineStart)).toEqual([79, 121]); + expect(file.splitLineCount).toBe(151); + expect(edits(next.unstaged)).toEqual([ + "-line 83", + "+changed near", + "-line 124", + "+changed far", + ]); + expect(edits(next.staged)).toEqual(["+extra"]); + const refreshed = snapshot( + "@@ -83 +83 @@\n-line 83\n+changed near\n@@ -125 +125 @@\n-line 124\n+changed far\n", + ); + expect(reviewDiffEdits(file)).toBe(reviewDiffEdits(refreshed.files[0]!)); + }); +}); diff --git a/apps/web/src/components/diffs/workingChangesState.ts b/apps/web/src/components/diffs/workingChangesState.ts new file mode 100644 index 0000000000000..a5c4442b4f885 --- /dev/null +++ b/apps/web/src/components/diffs/workingChangesState.ts @@ -0,0 +1,5 @@ +export { + applyWorkingChangesMutation, + type WorkingChangesSnapshot, + type WorkingChangesState, +} from "@t3tools/client-runtime/review-working-changes-state"; diff --git a/apps/web/src/components/files/FileBrowserPanel.tsx b/apps/web/src/components/files/FileBrowserPanel.tsx index 24912502fc355..76cf318cf63bd 100644 --- a/apps/web/src/components/files/FileBrowserPanel.tsx +++ b/apps/web/src/components/files/FileBrowserPanel.tsx @@ -1,7 +1,9 @@ +import { ReviewIcon as MorphIcon } from "~/components/ReviewIcon"; import { RefreshIcon } from "~/components/ui/refresh-icon"; import type { ContextMenuItem as TreeContextMenuItem, ContextMenuOpenContext as TreeContextMenuOpenContext, + GitStatusEntry, } from "@pierre/trees"; import type { EnvironmentId, ProjectEntry } from "@t3tools/contracts"; import { FileTree, useFileTree, useFileTreeSearch, useFileTreeSelector } from "@pierre/trees/react"; @@ -55,8 +57,12 @@ interface FileBrowserPanelProps { onRefreshSelectedFile?: () => void; workspaceMutationId: string | null; answersPanelFind?: boolean; + /** Existing Git status data decorates loaded rows without loading more directories. */ + gitChanges?: ReadonlyArray; } +const NO_GIT_CHANGES: ReadonlyArray = []; + function treePath(entry: ProjectEntry): string { return entry.kind === "directory" ? `${entry.path}/` : entry.path; } @@ -157,10 +163,27 @@ export default function FileBrowserPanel({ workspaceMutationId, hostFolder = false, answersPanelFind = false, + gitChanges = NO_GIT_CHANGES, }: FileBrowserPanelProps) { const panelPath = (relativePath: string) => hostFolder ? joinHostPath(cwd, relativePath) : relativePath; const { resolvedTheme } = useTheme(); + const selectionCSS = (() => { + if (!selectedPath) return PIERRE_TREE_UNSAFE_CSS; + const path = selectedPath.replace(/\/$/, ""); + return `${PIERRE_TREE_UNSAFE_CSS} + button[data-type='item']:is([data-item-path=${CSS.escape(path)}], [data-item-path=${CSS.escape(`${path}/`)}])::before { + content: ''; + position: absolute; + inset: 0; + display: block; + pointer-events: none; + outline: 1px solid var(--ring); + outline-offset: -1px; + border-radius: var(--radius-md); + } + `; + })(); const composerRef = useComposerHandleContext(); const fileContextMenu = useFileContextMenu(environmentId); const { @@ -311,6 +334,16 @@ export default function FileBrowserPanel({ loadingDirectoriesRef.current = loadingDirectories; model.setComposition(model.getComposition()); }, [loadingDirectories, model]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- installs selection styling into the imperative tree shadow DOM + useEffect(() => { + const shadow = model.getFileTreeContainer()?.shadowRoot; + if (!shadow) return; + const style = document.createElement("style"); + style.dataset.reviewSelection = "true"; + style.textContent = selectionCSS; + shadow.append(style); + return () => style.remove(); + }, [model, selectionCSS]); const search = useFileTreeSearch(model); // Pierre restores the unfiltered tree when a search has no matches. const hasNoSearchMatches = search.value.trim().length > 0 && search.matchingPaths.length === 0; @@ -386,16 +419,19 @@ export default function FileBrowserPanel({ }, [directoryPaths, expansionRoot, load, model, pendingExpandedPaths]); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pushes ignored-file status into the imperative Pierre tree model useEffect(() => { - model.setGitStatus( - entries - .filter((entry) => entry.ignored) - .map((entry) => ({ - path: treePath(entry), - status: "ignored", - })), - ); - }, [entries, model]); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- loads the selected file's ancestor directories and aborts on cleanup + const statuses = new Map(); + for (const entry of entries) { + if (entry.ignored) { + const path = treePath(entry); + statuses.set(path, { path, status: "ignored" }); + } + } + // Pierre colors filenames, adds the status letter, and marks ancestor folders. + // Supplying unloaded paths also marks their visible ancestors without scanning them. + for (const change of gitChanges) statuses.set(change.path, change); + model.setGitStatus([...statuses.values()]); + }, [entries, gitChanges, model]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- loads the selected file ancestors into the imperative tree useEffect(() => { if (!selectedPath) return; const controller = new AbortController(); @@ -520,7 +556,7 @@ export default function FileBrowserPanel({ return (
{ diff --git a/apps/web/src/components/files/WorkspaceSourcePreview.tsx b/apps/web/src/components/files/WorkspaceSourcePreview.tsx new file mode 100644 index 0000000000000..040ae377c2ce9 --- /dev/null +++ b/apps/web/src/components/files/WorkspaceSourcePreview.tsx @@ -0,0 +1,53 @@ +import type { EnvironmentId } from "@t3tools/contracts"; +import * as Hash from "effect/Hash"; +import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh"; +import { Button } from "../ui/button"; +import { useProjectFileQuery } from "./projectFilesQueryState"; +import ReadOnlySourcePreview from "./ReadOnlySourcePreview"; + +/** The explorer opens ordinary source without changing the active Git comparison. */ +export function WorkspaceSourcePreview(props: { + environmentId: EnvironmentId; + cwd: string; + path: string | null; + revision: string | null; + onOpenFile: (path: string) => void; +}) { + const file = useProjectFileQuery(props.environmentId, props.cwd, props.path); + useWorkspaceMutationRefresh({ + mutationId: props.revision, + resourceKey: `${props.environmentId}:${props.cwd}:${props.path}`, + refresh: file.refresh, + }); + if (!props.path) + return ( +

Select a file to view its contents.

+ ); + if (file.error) + return ( +
+

{file.error}

+ + +
+ ); + if (!file.data) return

Loading file…

; + return ( + <> + {file.data.truncated ? ( +

+ Showing the first 1 MB of this file. +

+ ) : null} + + + ); +} diff --git a/apps/web/src/components/preview/RightPanelResizeHandle.tsx b/apps/web/src/components/preview/RightPanelResizeHandle.tsx index affd8ee729388..2c46277adb07d 100644 --- a/apps/web/src/components/preview/RightPanelResizeHandle.tsx +++ b/apps/web/src/components/preview/RightPanelResizeHandle.tsx @@ -8,10 +8,17 @@ interface Props extends Pick< > { handlers: ResizableWidthHandlers; className?: string; + edge?: "left" | "right"; label?: string; } -export function RightPanelResizeHandle({ handlers, className, label, ...separatorProps }: Props) { +export function RightPanelResizeHandle({ + handlers, + className, + edge = "left", + label, + ...separatorProps +}: Props) { return (
{}} - explainPullRequest={() => {}} canFixFindings={false} startFixFindings={() => {}} handoffLabels={{ fixFindings: "Fix review findings" }} - canWriteGuide={false} - guideRunning={false} - guideWritten={false} - writeGuide={() => {}} pickableEnvironments={[]} actingEnvironmentId={environmentId} onActingEnvironmentChange={() => {}} can={() => false} autoMergeArmed={false} showsDraftToggle={false} - showsMergeNow={false} showsAutoMerge={false} showsMergeMethods={false} allowedMergeMethods={[]} diff --git a/apps/web/src/components/pullRequest/PullRequestActionsMenu.tsx b/apps/web/src/components/pullRequest/PullRequestActionsMenu.tsx index 3c075a937d181..091cd4d0d364c 100644 --- a/apps/web/src/components/pullRequest/PullRequestActionsMenu.tsx +++ b/apps/web/src/components/pullRequest/PullRequestActionsMenu.tsx @@ -3,7 +3,7 @@ import { canEditPullRequestMaintainerEdits, maintainerEditsChoiceInForce, type MaintainerEditsChoice, -} from "@t3tools/client-runtime/pull-request-editing"; +} from "@t3tools/client-runtime/review-editing"; import type { ChangeRequestTerminology } from "@t3tools/client-runtime/source-control-clients"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import type { @@ -16,14 +16,12 @@ import type { } from "@t3tools/contracts"; import { ArrowUpRightIcon, - BookOpenIcon, CopyIcon, HammerIcon, LinkIcon, MessageCircleQuestionIcon, MoreHorizontalIcon, RotateCcwIcon, - ScrollTextIcon, Trash2Icon, } from "lucide-react"; import { useId, useState } from "react"; @@ -73,21 +71,15 @@ export function PullRequestActionsMenu({ handoff, attachesToComposer, askAboutPullRequest, - explainPullRequest, canFixFindings, startFixFindings, handoffLabels, - canWriteGuide, - guideRunning, - guideWritten, - writeGuide, pickableEnvironments, actingEnvironmentId, onActingEnvironmentChange, can, autoMergeArmed, showsDraftToggle, - showsMergeNow, showsAutoMerge, showsMergeMethods, allowedMergeMethods, @@ -125,21 +117,15 @@ export function PullRequestActionsMenu({ handoff: string | null; attachesToComposer: boolean; askAboutPullRequest: () => void; - explainPullRequest: () => void; canFixFindings: boolean; startFixFindings: () => void; handoffLabels: { readonly fixFindings: string }; - canWriteGuide: boolean; - guideRunning: boolean; - guideWritten: boolean; - writeGuide: () => void; pickableEnvironments: ReadonlyArray; actingEnvironmentId: EnvironmentId; onActingEnvironmentChange: (environmentId: EnvironmentId) => void; can: (action: PullRequestAction) => boolean; autoMergeArmed: boolean; showsDraftToggle: boolean; - showsMergeNow: boolean; showsAutoMerge: boolean; showsMergeMethods: boolean; allowedMergeMethods: ReadonlyArray; @@ -255,27 +241,10 @@ export function PullRequestActionsMenu({ - - - - - {handoff === "explain" ? "Opening..." : `Explain this ${terminology.shortLabel}`} - - - A walk through the diff and what to read closely. - - - {handoff === "findings" ? "Preparing..." : handoffLabels.fixFindings} - {canWriteGuide ? ( - - - {guideRunning ? "Writing guide..." : !guideWritten ? "Write guide" : "Rewrite guide"} - - ) : null} {pickableEnvironments.length > 0 ? ( ) : null} - {showsMergeNow ? ( - void perform("merge", selectedMergeMethod))} - > - - {inlineConfirm.isArmed("merge") ? "Confirm merge?" : "Merge now"} - - ) : null} + {/* The same merge, left with the host to carry out once its requirements + pass. A conflicting branch cannot be armed because nothing the host + waits for will clear the conflict. */} {autoMergeArmed && can("disable-auto-merge") ? ( void perform("disable-auto-merge")}> @@ -365,7 +326,10 @@ export function PullRequestActionsMenu({ ) : null} {showsMergeMethods ? ( <> - {showsDraftToggle || showsMergeNow || showsAutoMerge ? : null} + {/* Only below the draft control. A host with no draft of its own, or + a draft whose control is already the header button, would leave + this against the separator that opened the group. */} + {showsDraftToggle || showsAutoMerge ? : null} onSelectMergeMethod(method as PullRequestMergeMethod)} @@ -386,11 +350,7 @@ export function PullRequestActionsMenu({ ) : null} - {pullRequestActionMenuHasGroup( - showsDraftToggle, - showsAutoMerge || showsMergeNow, - showsMergeMethods, - ) ? ( + {pullRequestActionMenuHasGroup(showsDraftToggle, showsAutoMerge, showsMergeMethods) ? ( ) : null} diff --git a/apps/web/src/components/pullRequest/PullRequestAdminMergeOption.tsx b/apps/web/src/components/pullRequest/PullRequestAdminMergeOption.tsx new file mode 100644 index 0000000000000..c31bfd247e425 --- /dev/null +++ b/apps/web/src/components/pullRequest/PullRequestAdminMergeOption.tsx @@ -0,0 +1,20 @@ +import { useId } from "react"; +import { Checkbox } from "../ui/checkbox"; + +export function PullRequestAdminMergeOption({ + checked, + disabled, + onCheckedChange, +}: { + checked: boolean; + disabled: boolean; + onCheckedChange: (checked: boolean) => void; +}) { + const id = useId(); + return ( + + ); +} diff --git a/apps/web/src/components/pullRequest/PullRequestAttachments.tsx b/apps/web/src/components/pullRequest/PullRequestAttachments.tsx new file mode 100644 index 0000000000000..307d924636a10 --- /dev/null +++ b/apps/web/src/components/pullRequest/PullRequestAttachments.tsx @@ -0,0 +1,198 @@ +import { useAtomValue } from "@effect/atom-react"; +import { publishReviewAttachment } from "@t3tools/client-runtime/review-attachments"; +import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets"; +import type { EnvironmentId, PullRequestRef } from "@t3tools/contracts"; +import { PaperclipIcon } from "lucide-react"; +import { useEffect, useRef, useState, type RefObject } from "react"; +import { uploadAttachmentBytes } from "~/lib/attachmentUploadQueue"; +import { appAtomRegistry } from "~/rpc/atomRegistry"; +import { attachmentEnvironment } from "~/state/attachments"; +import { pullRequestEnvironment } from "~/state/pullRequests"; +import { readPreparedConnection } from "~/state/session"; +import { useEnvironmentQuery } from "~/state/query"; +import { Button } from "../ui/button"; +import { toastManager } from "../ui/toast"; + +/** Publishes media before inserting its link, so every kind of comment can share it. */ +export function PullRequestAttachments({ + environmentId, + reference, + disabled, + textareaRef, + onTextChange, + onBusyChange, +}: { + environmentId: EnvironmentId; + reference: PullRequestRef; + disabled?: boolean; + textareaRef: RefObject; + onTextChange: (text: string) => void; + onBusyChange?: (busy: boolean) => void; +}) { + const fileInput = useRef(null); + const target = { environmentId, input: reference }; + const detail = useEnvironmentQuery(pullRequestEnvironment.detail(target)); + const allowed = useAtomValue( + pullRequestEnvironment.uploadAttachment.permissionAtom(environmentId), + ); + const canTransfer = useAtomValue( + attachmentEnvironment.createUploadUrl.permissionAtom(environmentId), + ); + const [busy, setBusy] = useState(false); + const lock = useRef(false); + const transfer = useRef<{ cancelled: boolean; abort?: (() => void) | undefined } | null>(null); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Abort in-flight uploads when their destination changes or unmounts. + useEffect( + () => () => { + if (transfer.current) { + transfer.current.cancelled = true; + transfer.current.abort?.(); + } + }, + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A new PR or environment must cancel the previous upload. + [environmentId, reference.projectId, reference.repository, reference.host, reference.number], + ); + const canAttach = + detail.data?.capabilities.attachments === true && + detail.data.viewerPermissions.attachments === true && + allowed && + canTransfer; + const upload = async (files: File[]) => { + if (lock.current || disabled || !canAttach || files.length === 0) return; + const textarea = textareaRef.current; + if (!textarea) return; + let start = textarea.selectionStart; + const end = textarea.selectionEnd; + const before = textarea.value.slice(0, start); + const after = textarea.value.slice(end); + let inserted = ""; + lock.current = true; + const session = { cancelled: false, abort: undefined as (() => void) | undefined }; + transfer.current = session; + setBusy(true); + onBusyChange?.(true); + return await (async () => { + for (const file of files) { + if (session.cancelled) break; + const markdown = await publishReviewAttachment({ + registry: appAtomRegistry, + createUploadUrl: attachmentEnvironment.createUploadUrl, + remove: attachmentEnvironment.remove, + publish: pullRequestEnvironment.uploadAttachment, + environmentId, + reference, + isCancelled: () => session.cancelled, + onMinted: () => (session.cancelled ? "cancel" : "continue"), + onTransferStart: (abort) => { + session.abort = abort; + if (session.cancelled) abort(); + }, + upload: { + type: "file", + name: file.name, + mimeType: file.type || "application/octet-stream", + sizeBytes: file.size, + }, + resolveUploadUrl: (relativeUrl) => { + const connection = readPreparedConnection(environmentId); + return connection ? resolveAssetUrl(connection.httpBaseUrl, relativeUrl) : null; + }, + transport: (url) => + uploadAttachmentBytes({ + url, + file, + mimeType: file.type || "application/octet-stream", + onProgress: () => {}, + }), + }); + if (!session.cancelled) { + const prefix = inserted.length > 0 || (before && !before.endsWith("\n")) ? "\n\n" : ""; + inserted += `${prefix}${markdown}`; + const suffix = after && !after.startsWith("\n") ? "\n\n" : ""; + onTextChange(`${before}${inserted}${suffix}${after}`); + start = before.length + inserted.length; + } + } + })() + .catch(async (error: unknown) => { + if (!session.cancelled) + toastManager.add({ + type: "error", + title: "Could not attach the file", + description: error instanceof Error ? error.message : "Try uploading again.", + }); + }) + .finally(async () => { + lock.current = false; + setBusy(false); + onBusyChange?.(false); + if (!session.cancelled) { + requestAnimationFrame(() => { + textarea.focus({ preventScroll: true }); + textarea.setSelectionRange(start, start); + }); + } + }); + }; + // File drops are handled by the same publisher as the picker, including permission and + // cancellation checks. Ordinary pasted links remain ordinary composer text. + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Attach native drag listeners to the mounted editor. + useEffect(() => { + const textarea = textareaRef.current; + const composer = + textarea?.closest("[data-review-attachment-composer]") ?? textarea; + if (!composer) return; + const isFile = (event: DragEvent) => event.dataTransfer?.types.includes("Files"); + const over = (event: DragEvent) => { + if (!isFile(event)) return; + event.preventDefault(); + if (event.dataTransfer) { + event.dataTransfer.dropEffect = canAttach && !disabled && !busy ? "copy" : "none"; + } + }; + const drop = (event: DragEvent) => { + if (!isFile(event)) return; + event.preventDefault(); + event.stopPropagation(); + void upload(Array.from(event.dataTransfer?.files ?? [])); + }; + composer.addEventListener("dragover", over); + composer.addEventListener("drop", drop); + return () => { + composer.removeEventListener("dragover", over); + composer.removeEventListener("drop", drop); + }; + }); + if (!canAttach) return null; + return ( + <> + { + const files = Array.from(event.target.files ?? []); + event.target.value = ""; + void upload(files); + }} + /> + {busy ? ( + + Uploading… + + ) : null} + + + ); +} diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx index 4d305c4da66ed..1bf1afa4c0d33 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx @@ -70,10 +70,7 @@ function deliverViewedPaths(paths: ReadonlySet | null) { for (const listener of mocks.viewedListeners) listener(); } -vi.mock(import("~/state/use-atom-command"), async (original) => ({ - ...(await original()), - useAtomCommand: (() => vi.fn()) as never, -})); +vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() })); vi.mock(import("./usePullRequestFilesViewed"), async () => { const { useSyncExternalStore } = await import("react"); const subscribe = (listener: () => void) => { @@ -84,6 +81,9 @@ vi.mock(import("./usePullRequestFilesViewed"), async () => { usePullRequestFilesViewed: () => { const viewedPaths = useSyncExternalStore(subscribe, () => mocks.viewedPaths); return { + ready: true, + filePaths: viewedPaths === null ? null : [...viewedPaths], + viewedCount: viewedPaths?.size ?? 0, enabled: viewedPaths !== null, isViewed: (path: string) => viewedPaths?.has(path) === true, isStale: () => false, @@ -341,40 +341,52 @@ it("pages forward to a file asked for that is not loaded yet, then scrolls to it await expectFileHeaderShown(screen, container, "late.test.ts"); }); -it("never requests the diff of a selected commit the pull request no longer has", async () => { - setup({ paged: false }); - const container = document.createElement("div"); - container.className = "flex h-[700px] w-[900px]"; - // The timeline can open a commit that a force-push removed from the pull request. - await using screen = await render( - {}} - environmentId={EnvironmentId.make("environment")} - reference={detail} - detail={{ - ...detail, - commits: [ - { - oid: "kept", - messageHeadline: "Kept commit", - committedDate: "2026-09-01T00:00:00Z", - }, - ], - }} - selectedCommitOid="gone" - onSelectedCommitChange={() => {}} - onRefresh={() => {}} - />, - { container }, - ); - - await expect.element(screen.getByText("1 file", { exact: true })).toBeVisible(); - await expect - .element(screen.getByRole("button", { name: "Diff scope: All commits" })) - .toBeVisible(); - expect(mocks.diffCommits).not.toContain("gone"); -}); - +it.each(["gone", "kept..newer"])( + "validates the selected commit scope %s against the pull request", + async (selection) => { + setup({ paged: false }); + const container = document.createElement("div"); + container.className = "flex h-[700px] w-[900px]"; + // The timeline can open a commit that a force-push removed from the pull request. + await using screen = await render( + {}} + environmentId={EnvironmentId.make("environment")} + reference={detail} + detail={{ + ...detail, + commits: [ + { + oid: "newer", + messageHeadline: "Newer commit", + committedDate: "2026-09-02T00:00:00Z", + }, + { + oid: "kept", + messageHeadline: "Kept commit", + committedDate: "2026-09-01T00:00:00Z", + }, + ], + }} + selectedCommitOid={selection} + onSelectedCommitChange={() => {}} + onRefresh={() => {}} + />, + { container }, + ); + + await expect.element(screen.getByText("1 file", { exact: true })).toBeVisible(); + await expect + .element( + screen.getByRole("button", { + name: selection === "gone" ? "Diff scope: All commits" : "Diff scope: 2 commits", + }), + ) + .toBeVisible(); + expect(mocks.diffCommits).not.toContain("gone"); + if (selection !== "gone") expect(mocks.diffCommits).toContain(selection); + }, +); it("answers a commit's diff link only once that commit's diff is shown", async () => { setup({ paged: false }); const container = document.createElement("div"); diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index 573a7bfb27988..fd4a2475d62c1 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -1,3 +1,5 @@ +import { ReviewIcon as MorphIcon } from "~/components/ReviewIcon"; +import { FlaskConicalOffIcon } from "lucide-react"; import { isFileDiffCollapsed, withFileDiffFold, @@ -14,12 +16,19 @@ import { capitalizeTerm, sourceControlClients, } from "@t3tools/client-runtime/source-control-clients"; -import type { - CodeViewItem, - DiffLineAnnotation, - FileDiffMetadata, - SelectedLineRange, -} from "@pierre/diffs"; +import { + reviewFileChapterIndex, + reviewFileGroup, + type ReviewFileGroup, +} from "@t3tools/shared/reviewFileClassification"; +import { createPortal } from "react-dom"; +import { ReviewPath } from "../diffs/ReviewPath"; +import { + reviewPositionLabel, + reviewLineRangeLabel, +} from "@t3tools/client-runtime/review-selection"; +import { PullRequestAttachments } from "./PullRequestAttachments"; +import type { CodeViewItem, DiffLineAnnotation, SelectedLineRange } from "@pierre/diffs"; import type { CodeViewAnnotationArgs, CodeViewDiffItem } from "@pierre/diffs/react"; import type { EnvironmentId, @@ -31,26 +40,21 @@ import type { PullRequestReviewPosition, PullRequestReviewThread, PullRequestThreadCommentsResult, + PullRequestThreadComment, } from "@t3tools/contracts"; import { SOURCE_CONTROL_MEDIA_ASSET } from "@t3tools/contracts"; import { ChevronDownIcon, ChevronRightIcon, - Columns2Icon, - FlaskConicalOffIcon, FolderTreeIcon, InfoIcon, MessageSquareOffIcon, - PilcrowIcon, - Rows3Icon, - Settings2Icon, - TextWrapIcon, TriangleAlertIcon, ChevronsDownUpIcon, ChevronsUpDownIcon, } from "lucide-react"; -import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-react"; -import { AsyncResult, Atom } from "effect/reactivity"; +import { ChevronDown, ChevronRight, ChevronsDownUp, ChevronsUpDown } from "lucide-react"; +import { useAtomRefresh, useAtomValue } from "@effect/atom-react"; import * as Schema from "effect/Schema"; import { createContext, @@ -58,12 +62,21 @@ import { useContext, useEffect, useEffectEvent, + useLayoutEffect, useRef, useState, type ReactNode, } from "react"; import { observeIntersection } from "~/lib/observeIntersection"; +import { + isReviewFileVisible, + reviewCommentCounts, + toggleReviewCommit, + reviewCommitSelection, + reviewCommitScope, + latestReviewedCommit, +} from "@t3tools/client-runtime/review-workspace"; import { useLocalStorage } from "~/hooks/useLocalStorage"; import { useClientSettings, updateClientSettings } from "~/hooks/useSettings"; import { useRenderedAppearance } from "~/hooks/useTheme"; @@ -75,8 +88,10 @@ import { } from "./pullRequestDetail.logic"; import { canEditPullRequestComment, + groupPendingReviewComments, + reviewThreadReplyTarget, canResolvePullRequestThread, -} from "@t3tools/client-runtime/pull-request-editing"; +} from "@t3tools/client-runtime/review-editing"; import { fileDiffRows } from "@t3tools/client-runtime/review-guide-tour"; import { isTestChangedFile } from "@t3tools/shared/changedFileKind"; import { isWorkspaceImagePreviewPath } from "@t3tools/shared/mediaPreview"; @@ -111,9 +126,12 @@ import { useDiffWorkerPool } from "../DiffWorkerPoolProvider"; import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation"; import { DiffFileTree } from "../diffs/DiffFileTree"; import { FileExplorerPane } from "../files/FileExplorerPane"; +import { ReviewChapterRail, ReviewChapterFileLink } from "./ReviewChapterRail"; +import { GuideChapterPanel } from "./guide/GuideChapterPanel"; +import { ReviewChapterHeader, ReviewChapterProgress } from "./ReviewChapterHeader"; import { useCodeViewFileReveal } from "../diffs/useCodeViewFileReveal"; import { useHideTestFiles } from "../diffs/useHideTestFiles"; -import { diffFileTreeEntries, orderDiffFilesLikeTree } from "../diffs/diffFileTree.logic"; +import { diffFileTreeEntries } from "../diffs/diffFileTree.logic"; import { StyledDiffCodeView } from "../diffs/StyledDiffCodeView"; import { Button } from "../ui/button"; import { Checkbox } from "../ui/checkbox"; @@ -123,13 +141,11 @@ import { DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuItem, - DropdownMenuRadioGroup, - DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuTrigger, } from "../ui/menu"; import { toastManager } from "../ui/toast"; -import { Toggle, ToggleGroup } from "../ui/toggle-group"; +import { Toggle } from "../ui/toggle-group"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { getReviewPositionAnchor, @@ -141,18 +157,17 @@ import { import { pullRequestCompletionScope } from "./PullRequestMarkdownTextarea"; import { getFileViewedRange, isLineInFileDiff } from "./pullRequestDiff.logic"; import { PullRequestDiffStat, PullRequestMetaLine } from "./pullRequestPresentation"; -import { PullRequestDiffUnavailableState } from "./PullRequestDiffUnavailableState"; import { usePullRequestFilesViewed } from "./usePullRequestFilesViewed"; -import { hasCutLines } from "@t3tools/shared/diffCutLines"; -import { CUT_LINES_CSS, markCutLineNotes } from "./cutLineNotes"; +import { DiffDisplayControls } from "../diffs/DiffDisplayControls"; import { nextPendingReviewCommentId, pullRequestReviewKey, usePendingReviewComments, - usePullRequestReviewStore, type PendingReviewComment, } from "./pullRequestReviewStore"; +import { usePendingReviewCommentActions } from "./usePendingReviewCommentActions"; +/** Everything pinned to one line of one file: what is already there, and what is being added. */ interface ReviewAnnotationGroup { readonly threads: ReadonlyArray; readonly pending: ReadonlyArray; @@ -183,10 +198,12 @@ const NO_PATHS: ReadonlyArray = []; type ReviewAnnotation = DiffLineAnnotation; +/** Commits per press of "Show more" in the scope menu. */ const COMMIT_PAGE_SIZE = 10; const PULL_REQUEST_FILE_TREE_STORAGE_KEY = "t3code.pullRequestFileTreeOpen"; +/** One answer from the host: a whole number of files, and where the next one carries on. */ interface DiffSlice { readonly source: PullRequestDiffResult; readonly cursor: string | null; @@ -203,6 +220,7 @@ const REPLACE_FILE_COUNTS_CSS = ` display: none !important; }`; +/** Nothing loaded yet, as one identity, so the memos below do not see a new array every render. */ const NO_SLICES: ReadonlyArray = []; // Query results outlive the panel's slices, so their parses survive closing and reopening @@ -238,6 +256,7 @@ function diffModel( slices: ReadonlyArray, keyPrefix: string, ignoreWhitespace: boolean, + groupByType: boolean, ): DiffModel { let models = diffModels.get(slices); if (models === undefined) diffModels.set(slices, (models = new Map())); @@ -252,10 +271,9 @@ function diffModel( }); const model: DiffModel = { parsedSlices, - loadedFiles: orderDiffFilesLikeTree( - parsedSlices.flatMap((parsed) => - parsed?.kind === "files" ? orderDiffFiles(parsed.files) : [], - ), + loadedFiles: orderDiffFiles( + parsedSlices.flatMap((parsed) => (parsed?.kind === "files" ? parsed.files : [])), + groupByType, ), sourceFileStats: new Map( parsedSlices.flatMap((parsed) => @@ -353,6 +371,7 @@ function FileViewedToggle({ ); } +/** A group while it is still gathering what belongs on its line. */ interface MutableAnnotationGroup { readonly side: PullRequestDiffSide; readonly line: number; @@ -364,29 +383,32 @@ interface MutableAnnotationGroup { interface DraftAnchor { readonly fileKey: string; readonly path: string; + /** What the file was called before the change, for the hosts that resolve a position by both. */ readonly oldPath: string | null; readonly position: PullRequestReviewPosition; readonly startPosition?: PullRequestReviewPosition; + /** The selected lines used for the comment and composer context. */ readonly range: SelectedLineRange; } +/** A range of the diff and the reader's request for the agent. */ export interface PullRequestAgentSelectionInput { + /** The marked lines, already in the shape the composer draws and the agent reads. */ readonly comment: ReviewCommentContext; readonly request: string; } -function isRemovedLine(fileDiff: FileDiffMetadata, oldLine: number): boolean { - return fileDiff.hunks.some((hunk) => { - let next = hunk.deletionStart; - return hunk.hunkContent.some((content) => { - const count = content.type === "context" ? content.lines : content.deletions; - const removed = content.type === "change" && oldLine >= next && oldLine < next + count; - next += count; - return removed; - }); - }); -} - +/** + * Whether the viewer draws this line at all. A line counts the new file on the right and the old + * one on the left, and each hunk covers one run of each; a line outside every run — a + * conversation the host could not mark outdated, or one under a hunk it withheld — has no row to + * be pinned to, however much its file looks like a match. + */ +/** + * The pull request's patch, with the review written against it. Conversations already on the + * host sit under the line they were written on, and a new comment joins the review being + * drafted rather than being posted as it is typed. + */ function PullRequestCodeTab({ scrollerRef, environmentId, @@ -399,37 +421,61 @@ function PullRequestCodeTab({ onFixFinding, onAddToChat, onAddToAgentSelection, + onAddThreadCommentToComposer, + onAddPendingToComposer, onRefresh, refreshToken = 0, backgroundRefreshToken = 0, revealRequest = null, revealUrl, onRevealSettled, + guideFallback = false, + guideStatus, + viewControlsTarget, }: { + guideStatus?: ReactNode; + viewControlsTarget?: HTMLElement | null; + /** Before a Guide is ready, keep its chapter layout with files grouped by type. */ + guideFallback?: boolean; scrollerRef: (node: HTMLDivElement | null) => void; environmentId: EnvironmentId; reference: PullRequestRef; detail: PullRequestDetailView; + /** Commit whose diff is open. Null keeps the whole pull-request diff selected. */ selectedCommitOid: string | null; onSelectedCommitChange: (oid: string | null) => void; + /** The hand-off currently preparing, if any, so only the finding it belongs to says so. */ pendingFinding?: string | null; fixFindingLabel?: string; onFixFinding?: (finding: PullRequestFinding) => void; /** Absent where there is no composer beside the panel to add a conversation to. */ onAddToChat?: (subject: PullRequestChatSubject) => void; onAddToAgentSelection?: (input: PullRequestAgentSelectionInput) => void; + onAddThreadCommentToComposer?: + | ((thread: PullRequestReviewThread, comment: PullRequestThreadComment) => void) + | undefined; + onAddPendingToComposer?: ((comment: PendingReviewComment) => void) | undefined; onRefresh: () => void; + /** Bumped by the panel's refresh button: drop the accumulated pages and re-read the diff. */ refreshToken?: number; backgroundRefreshToken?: number; /** A clicked link to a file or line range, until onRevealSettled reports it shown. */ revealUrl?: string | undefined; onRevealSettled?: ((revealUrl: string) => void) | undefined; - revealRequest?: { readonly path: string; readonly nonce: number } | null; + /** A file another tab asked to show. A new nonce asks again for the same path. */ + revealRequest?: { + readonly path: string; + readonly nonce: number; + readonly line?: number | null; + readonly side?: PullRequestDiffSide; + readonly threadId?: string; + } | null; }) { const resolvedTheme = useRenderedAppearance(); // Initialize the shared tokenizer and workers while the diff request is still pending. useDiffWorkerPool(); const settings = useClientSettings((settings) => ({ + pullRequestViewing: settings.pullRequestViewing, diffFilesCollapsed: settings.diffFilesCollapsed, diffIgnoreWhitespace: settings.diffIgnoreWhitespace, diffLayout: settings.diffLayout, @@ -437,19 +483,35 @@ function PullRequestCodeTab({ })); const [foldChoices, setFoldChoices] = useState(() => new Map()); const [lastViewedFileKey, setLastViewedFileKey] = useState(null); + // A change of any size can carry hundreds of commits, and a menu that long is a scroll rather + // than a choice. The rest arrive ten at a time, on request. const [visibleCommitCount, setVisibleCommitCount] = useState(COMMIT_PAGE_SIZE); + /** Set once the reader has asked for every file at once, until they pick a file apart again. */ const [foldOverride, setFoldOverride] = useState(null); const effectiveFoldOverride = foldOverride ?? (settings.diffFilesCollapsed ? "folded" : null); const diffLayout = settings.diffLayout; - const [wordWrapOverride, setWordWrapOverride] = useState(null); - const wordWrap = wordWrapOverride ?? settings.wordWrap; - const [ignoreWhitespace, setIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace); + const wordWrap = settings.wordWrap; + const ignoreWhitespace = settings.diffIgnoreWhitespace; const [fileTreeOpen, setFileTreeOpen] = useLocalStorage( PULL_REQUEST_FILE_TREE_STORAGE_KEY, false, Schema.Boolean, ); const [hideTestFiles, setHideTestFiles] = useHideTestFiles(); + const commentsOnly = !guideFallback && settings.pullRequestViewing.commentsOnly; + const hideReviewed = !guideFallback && settings.pullRequestViewing.hideReviewed; + const groupByType = guideFallback || settings.pullRequestViewing.groupByType; + const [selectedChapter, setSelectedChapter] = useState("code"); + const [chapterRailOpen, setChapterRailOpen] = useState(false); + const canSetChapterViewed = useAtomValue( + pullRequestEnvironment.setFilesViewed.permissionAtom(environmentId), + ); + const scrollElement = useRef(null); + const savedScroll = useRef(null); + const setScroller = (node: HTMLDivElement | null) => { + scrollElement.current = node; + scrollerRef(node); + }; const [selectedLines, setSelectedLines] = useState<{ id: string; range: SelectedLineRange; @@ -465,10 +527,15 @@ function PullRequestCodeTab({ }>({ key: "", cursor: null, slices: NO_SLICES }); const referenceKey = pullRequestReviewKey(reference); + const orderedCommits = // GitLab preserves UTC offsets, so compare instants. + detail.commits.toSorted( + (left, right) => Date.parse(right.committedDate) - Date.parse(left.committedDate), + ); + const commitOids = orderedCommits.toReversed().map((entry) => entry.oid); // A commit opened from the timeline or left selected across a force-push may no longer be // part of the pull request; read it as "All commits" instead of requesting its diff. const commit = - selectedCommitOid !== null && detail.commits.some((entry) => entry.oid === selectedCommitOid) + selectedCommitOid !== null && reviewCommitSelection(commitOids, selectedCommitOid).length > 0 ? selectedCommitOid : null; const scopeKey = JSON.stringify([environmentId, referenceKey, commit]); @@ -484,6 +551,8 @@ function PullRequestCodeTab({ setFoldOverride(null); setVisibleCommitCount(COMMIT_PAGE_SIZE); setOrphansOpen(false); + setSelectedChapter("code"); + setChapterRailOpen(false); setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES }); } @@ -550,16 +619,16 @@ function PullRequestCodeTab({ return { key: scopeKey, cursor, slices: [...slices.slice(0, index), next] }; }); } + // The refresh button rereads from the first page rather than the page the reader is on: + // pages are positions in one snapshot of the diff, and a fresh snapshot starts over. const refreshFirstDiffPage = useAtomRefresh( pullRequestEnvironment.diff({ environmentId, input: { ...reference, ...(commit === null ? {} : { commit }) }, }), ); - const reviewKey = referenceKey; - const pendingComments = usePendingReviewComments(reference); - const addComment = usePullRequestReviewStore((store) => store.addComment); - const removeComment = usePullRequestReviewStore((store) => store.removeComment); + const pendingComments = usePendingReviewComments(reference, detail.reviewThreads); + const { add: addComment } = usePendingReviewCommentActions(environmentId, reference); const replyToThread = useAtomCommand(pullRequestEnvironment.replyToThread, { reportFailure: false, }); @@ -573,12 +642,56 @@ function PullRequestCodeTab({ reportFailure: false, }); const getDiffFileContents = useAtomCommand(pullRequestEnvironment.diffFileContents); + const loadDiffFiles = createPullRequestDiffFileContentsLoader(getDiffFileContents, { + environmentId, + reference, + commit, + cacheKey: `pull-request:${referenceKey}:${detail.updatedAt}:${commit ?? "all"}`, + }); + // What is offered is the intersection of two different questions: what this host can do at + // all, and what this account may do on this repository. Either one saying no means a control + // that would only ever end in a refusal. + const review = (() => { + const hostReview = detail.capabilities.review; + const viewer = detail.viewerPermissions; + return { + inlineComment: hostReview.inlineComment && viewer.comment, + reply: hostReview.reply && viewer.comment, + resolve: hostReview.resolve && viewer.resolve, + }; + })(); + // A comment is posted against the pull request's head diff, so a line number taken from one + // commit's own diff would land somewhere else entirely. Commenting waits for the whole change. + const canCommentOnLines = review.inlineComment && commit === null; + const rangeComments = detail.capabilities.review.rangeComment === true; + const canSelectLines = + commit === null && (review.inlineComment || onAddToAgentSelection !== undefined); + const { parsedSlices, loadedFiles, sourceFileStats } = diffModel( + loadedSlices, + `pull-request:${scopeKey}:${resolvedTheme}:${ignoreWhitespace}:${groupByType}`, + ignoreWhitespace, + groupByType, + ); + const testFileCount = loadedFiles.filter((file) => + isTestChangedFile(resolveFileDiffPath(file)), + ).length; + const files = hideTestFiles + ? loadedFiles.filter((file) => { + const path = resolveFileDiffPath(file); + return path === revealRequest?.path || path === linkPath || !isTestChangedFile(path); + }) + : loadedFiles; + const filePaths = files.map((file) => resolveFileDiffPath(file)); + // Offered under a commit scope as well as from the whole change, because reading a change one + // commit at a time is what the scope is for. The tick is kept against the change request rather + // than the scope it was made in, so clearing a file here clears it everywhere. const viewedFilesStore = detail.capabilities.viewedFiles; const filesViewed = usePullRequestFilesViewed({ environmentId, reference, enabled: viewedFilesStore !== undefined, + paths: filePaths, }); const { setViewed, @@ -587,20 +700,9 @@ function PullRequestCodeTab({ isViewed: isFileViewed, isStale: isFileViewedStale, } = filesViewed; - const [withheldLoads, setWithheldLoads] = useState<{ - readonly scope: string; - readonly paths: ReadonlyArray; - /** The render key each loaded file was last shown under; a changed patch gets a new one. */ - readonly shownKeys: ReadonlyMap; - }>({ scope: "", paths: NO_PATHS, shownKeys: new Map() }); - const withheldPaths = withheldLoads.scope === scopeKey ? withheldLoads.paths : NO_PATHS; - const withheldInput = { ...reference, ...(commit === null ? {} : { commit }) }; - const atomRegistry = useContext(RegistryContext); - const withheldFileDiff = (path: string) => - pullRequestEnvironment.diff({ environmentId, input: { ...withheldInput, path } }); - const refreshWithheldFiles = useEffectEvent(() => { - for (const path of withheldPaths) atomRegistry.refresh(withheldFileDiff(path)); - }); + // The button goes around the host's cache, so everything the tab reads from it starts over: + // the diff from its first page, and with it the ticks, which a push since the last read can + // have marked as standing against an older version of the file. const appliedRefreshToken = useRef(refreshToken); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a new refresh token clears loaded slices and refetches the first diff page and viewed files useEffect(() => { @@ -625,107 +727,21 @@ function PullRequestCodeTab({ refreshWithheldFiles(); refreshFilesViewed(); }, [backgroundRefreshToken, refreshFirstDiffPage, refreshFilesViewed]); + const nextCursor = loadedSlices.at(-1)?.nextCursor ?? null; + // What a slice withheld: the host declining to inline part of it, or a patch the viewer could + // not structure and so dropped. Neither says anything about there being more to fetch. + const withheldContent = + loadedSlices.some((slice) => slice.truncated) || + parsedSlices.some((parsed) => parsed?.kind === "raw"); const codeViewReveal = useCodeViewFileReveal(); - const answeredRevealNonce = useRef(null); + // Placing a conversation takes more than its file being in the diff: its line has to fall + // inside a hunk that was rendered. One that does not is drawn nowhere, so it belongs in the + // off-diff list rather than disappearing between the two. + const { threads: visibleHostThreads, pendingComments: unthreadedPendingComments } = + groupPendingReviewComments(detail.reviewThreads, pendingComments); - const loadDiffFiles = createPullRequestDiffFileContentsLoader(getDiffFileContents, { - environmentId, - reference, - commit, - cacheKey: `pull-request:${referenceKey}:${detail.updatedAt}:${commit ?? "all"}`, - }); const completionScope = pullRequestCompletionScope(detail, environmentId, reference); - const hostReview = detail.capabilities.review; - const review = { - inlineComment: hostReview.inlineComment && detail.viewerPermissions.comment, - reply: hostReview.reply && detail.viewerPermissions.comment, - resolve: hostReview.resolve && detail.viewerPermissions.resolve, - }; - const canCommentOnLines = review.inlineComment && commit === null; - const rangeComments = hostReview.rangeComment === true; - // Agent context is local, so it does not require host comment permission. - const canSelectLines = - commit === null && (review.inlineComment || onAddToAgentSelection !== undefined); - const { - parsedSlices, - loadedFiles: pagedFiles, - sourceFileStats, - } = diffModel(loadedSlices, `pull-request:${scopeKey}:${ignoreWhitespace}`, ignoreWhitespace); - const withheldResults = useAtomValue( - withheldFileDiffsAtom( - JSON.stringify({ environmentId, input: withheldInput, paths: withheldPaths }), - ), - ); - // A refetch keeps showing the last patch, whose lines may not exist at the new head. - const withheldRefetching = withheldResults.some((result) => result.waiting); - const withheldStatuses = new Map(); - const withheldFiles = new Map(); - const cutFiles = new Set(); - withheldPaths.forEach((path, index) => { - const result = withheldResults[index]; - if (result === undefined) return; - // A failed refresh still carries the earlier patch; show the failure instead of stale code. - const data = result._tag === "Failure" ? null : AsyncResult.getOrElse(result, () => null); - if (data === null) { - withheldStatuses.set(path, result._tag === "Failure" ? "error" : "loading"); - return; - } - const parsed = parseSlice( - { - source: data, - cursor: null, - patch: data.patch, - truncated: false, - nextCursor: null, - omittedFileStats: [], - }, - `pull-request:${scopeKey}:withheld:${path}`, - // Cut lines can match up to the cut and differ after it; hiding them would drop changes. - false, - ); - const file = parsed?.kind === "files" ? parsed.files[0] : undefined; - if (file !== undefined && file.hunks.length > 0) { - withheldFiles.set(path, file); - if (hasCutLines(data.patch)) cutFiles.add(file); - } else withheldStatuses.set(path, "empty"); - }); - // Fold choices follow render keys, so a loaded or refetched patch would otherwise fold again - // when marked Viewed: it opens on first load and keeps its earlier key's choice after. - const rekeyed = [...withheldFiles].flatMap(([path, file]) => { - const key = buildFileDiffRenderKey(file); - return withheldLoads.shownKeys.get(path) === key ? [] : [[path, key] as const]; - }); - if (withheldLoads.scope === scopeKey && rekeyed.length > 0) { - setWithheldLoads({ - ...withheldLoads, - shownKeys: new Map([...withheldLoads.shownKeys, ...rekeyed]), - }); - setFoldChoices((current) => - rekeyed.reduce((next, [path, key]) => { - const shown = withheldLoads.shownKeys.get(path); - const collapsed = shown === undefined ? false : current.get(shown); - return collapsed === undefined ? next : withFileDiffFold(next, key, collapsed); - }, current), - ); - } - const loadedFiles = - withheldFiles.size === 0 - ? pagedFiles - : // A refreshed page may carry the file's patch itself now. - pagedFiles.map((file) => - file.hunks.length === 0 ? (withheldFiles.get(resolveFileDiffPath(file)) ?? file) : file, - ); - const loadWithheldFile = (path: string) => { - // The read is keyed without the head, so even a first load must not reuse an older one. - atomRegistry.refresh(withheldFileDiff(path)); - if (withheldPaths.includes(path)) return; - setWithheldLoads({ - scope: scopeKey, - paths: [...withheldPaths, path], - shownKeys: withheldLoads.scope === scopeKey ? withheldLoads.shownKeys : new Map(), - }); - }; const linkAnchor = parsePullRequestAnchor(revealUrl); const linkFile = linkAnchor?.kind === "diff" @@ -740,26 +756,7 @@ function PullRequestCodeTab({ readonly path: string; } | null>(null); const linkPath = pendingLinkPath ?? (revealedLink?.scope === scopeKey ? revealedLink.path : null); - const testFileCount = loadedFiles.filter((file) => - isTestChangedFile(resolveFileDiffPath(file)), - ).length; - // A requested file stays visible so a jump to a hidden test still lands. - const files = hideTestFiles - ? loadedFiles.filter((file) => { - const path = resolveFileDiffPath(file); - return path === revealRequest?.path || path === linkPath || !isTestChangedFile(path); - }) - : loadedFiles; - const hiddenTestFileCount = loadedFiles.length - files.length; - const filePaths = files.map((file) => resolveFileDiffPath(file)); - const omittedFileStats = new Map( - loadedSlices.flatMap((slice) => - slice.omittedFileStats.map((file) => [file.path, file] as const), - ), - ); - const fileTreeEntries = diffFileTreeEntries(files); - const threadsByPath = reviewThreadsByPath(detail.reviewThreads); - // File membership does not guarantee a rendered hunk for the thread. + const threadsByPath = reviewThreadsByPath(visibleHostThreads); const placedThreadIds = (() => { const placed = new Set(); // Commit diffs use different line coordinates; list conversations separately. @@ -774,23 +771,13 @@ function PullRequestCodeTab({ return placed; })(); - const imageRevision = commit ?? detail.headSha; - const rawFileUrl = sourceControlClients.find(detail.provider)?.rawFileUrl; - const repositoryUrl = sourceControlClients.parseChangeRequestUrl(detail.url)?.link.repositoryUrl; - // Hosts send no patch for an image, so its expanded row shows the file at this revision. - const imagePreviewUrl = (fileDiff: FileDiffMetadata, path: string) => - fileDiff.hunks.length === 0 && - fileDiff.type !== "deleted" && - isWorkspaceImagePreviewPath(path) && - imageRevision !== undefined && - rawFileUrl !== undefined && - repositoryUrl !== undefined - ? rawFileUrl({ repositoryUrl, sha: imageRevision, path }) - : null; - + // Hashing what the annotations show is the costly part of an item's version, and none of it + // moves when a file is ticked or folded, so it is kept apart from the two that do. const annotatedFiles = files.map((fileDiff) => { const fileKey = buildFileDiffRenderKey(fileDiff); const path = resolveFileDiffPath(fileDiff); + // One annotation per line, so a line that already carries a conversation shows a new + // comment underneath it rather than in place of it. const groups = new Map(); // Stacked view draws a context row once, so its old side shares the new side's annotation. const contextNewLines = new Map(); @@ -823,8 +810,10 @@ function PullRequestCodeTab({ if (thread.line === null || !placedThreadIds.has(thread.id)) continue; groupAt(thread.side, thread.line).threads.push(thread); } + // Pending comments anchor to the head diff exactly like host threads do, so a + // commit's diff must not place them either — the same line means other code there. if (commit === null) { - for (const comment of pendingComments) { + for (const comment of unthreadedPendingComments) { if (comment.path !== path) continue; const anchor = getReviewPositionAnchor(comment.position); groupAt(anchor.side, anchor.line).pending.push(comment); @@ -869,8 +858,11 @@ function PullRequestCodeTab({ annotations .map( ({ side, lineNumber, metadata }) => - `${side}:${lineNumber}:${metadata.image?.url ?? ""}:${metadata.withheld?.status ?? ""}:${metadata.draft ? "d" : ""}:${metadata.pending - .map((comment) => `${comment.id}:${comment.body}`) + `${side}:${lineNumber}:${metadata.draft ? "d" : ""}:${metadata.pending + .map( + (comment) => + `${comment.id}:${comment.body}:${comment.hostedComment?.commentId ?? ""}`, + ) .join(",")}:${metadata.threads .map( (thread) => @@ -894,67 +886,120 @@ function PullRequestCodeTab({ }; }); - const nextCursor = loadedSlices.at(-1)?.nextCursor ?? null; - const withheldFilesReadable = loadedSlices[0]?.source.withheldFilesReadable === true; - const withheldContent = - loadedSlices.some((slice) => slice.truncated) || - parsedSlices.some((parsed) => parsed?.kind === "raw"); - // Keep the sentinel until all pages load; returning raw slices early would stop pagination. - const rawSlices = - nextCursor === null - ? parsedSlices.flatMap((parsed) => (parsed?.kind === "raw" ? [parsed] : [])) - : []; - const rawSlicesView = - files.length === 0 && rawSlices.length > 0 ? ( -
- {rawSlices.map((slice) => ( -
-

{slice.reason}

-
{slice.text}
-
- ))} -
- ) : null; - const unstructured = - rawSlices.length === 0 ? null : ( -
- {rawSlices.map((slice) => ( -
-

{slice.reason}

-
{slice.text}
-
- ))} -
- ); - + // A stale mark means the file changed since it was viewed; Fold all and Expand all outrank marks. const foldsAsViewed = (path: string) => - filesViewedEnabled && isFileViewed(path) && !isFileViewedStale(path); - const items: CodeViewDiffItem[] = annotatedFiles.map( - ({ fileKey, path, fileDiff, annotations, annotationsVersion }) => { - const collapsed = isFileDiffCollapsed( - fileKey, - effectiveFoldOverride, - foldChoices, - foldsAsViewed(path), - ); - const viewedMark = filesViewedEnabled - ? `e${isFileViewed(path) ? "v" : ""}${isFileViewedStale(path) ? "s" : ""}` - : ""; - return { - id: fileKey, - type: "diff" as const, - fileDiff, - annotations, - collapsed, - version: fnv1a32(`${collapsed ? "1" : "0"}:${viewedMark}:${annotationsVersion}`), - }; - }, + foldOverride === null && filesViewedEnabled && isFileViewed(path) && !isFileViewedStale(path); + const commentCounts = reviewCommentCounts( + files.map((file) => ({ + path: resolveFileDiffPath(file), + previousPath: resolveFileDiffPreviousPath(file), + })), + detail.reviewThreads, + pendingComments, + ); + const filteredFiles = annotatedFiles.filter( + ({ path }) => + path === revealRequest?.path || + path === linkPath || + isReviewFileVisible( + { hideReviewed, commentsOnly }, + isFileViewed(path), + (commentCounts.get(path)?.unresolved ?? 0) > 0, + ), + ); + const diffComplete = + loadedSlices.length > 0 && + nextCursor === null && + !diffQuery.isPending && + diffQuery.error === null; + const chapterIndex = reviewFileChapterIndex({ + completePaths: + commit === null && viewedFilesStore === "host" && filesViewed.filePaths !== null + ? filesViewed.filePaths + : diffComplete && !withheldContent + ? filePaths + : null, + loadedFiles: annotatedFiles, + visibleFiles: filteredFiles, + getPath: (file) => file.path, + }); + const chapters = groupByType ? chapterIndex.chapters : []; + const chapterPosition = Math.max( + 0, + chapters.findIndex((chapter) => chapter.id === selectedChapter), + ); + const chapter = chapters[chapterPosition] ?? null; + const chapterReviewComplete = + chapterIndex.complete && (!filesViewedEnabled || (filesViewed.ready && !filesViewed.truncated)); + const chapterCountsPending = + filesViewed.error || filesViewed.truncated || diffQuery.error + ? "File counts unavailable" + : "Loading file counts…"; + const items = ((): CodeViewDiffItem[] => + (chapter?.visibleFiles ?? filteredFiles).map( + ({ fileKey, path, fileDiff, annotations, annotationsVersion }) => { + const collapsed = isFileDiffCollapsed( + fileKey, + effectiveFoldOverride, + foldChoices, + foldsAsViewed(path), + ); + // Ticking a file that is already folded changes no fold, so without this the box on + // screen would keep saying the opposite of what the count says. + const viewedMark = filesViewedEnabled + ? `e${isFileViewed(path) ? "v" : ""}${isFileViewedStale(path) ? "s" : ""}` + : ""; + return { + id: fileKey, + type: "diff" as const, + fileDiff, + annotations, + collapsed, + version: fnv1a32(`${collapsed ? "1" : "0"}:${viewedMark}:${annotationsVersion}`), + }; + }, + ))(); + const omittedFileStats = new Map( + loadedSlices.flatMap((slice) => + slice.omittedFileStats.map((file) => [file.path, file] as const), + ), ); const fileKeys = items.map((item) => item.id); const collapsedFileKeys = new Set( items.filter((item) => item.collapsed === true).map((item) => item.id), ); const allFilesCollapsed = areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys); + const fileTreeEntries = diffFileTreeEntries(items.map((item) => item.fileDiff)).map((entry) => ({ + ...entry, + reviewed: isFileViewed(entry.path), + unresolvedComments: commentCounts.get(entry.path)?.unresolved ?? 0, + })); + const folderReviewEntries = diffFileTreeEntries(annotatedFiles.map((file) => file.fileDiff)).map( + (entry) => ({ + ...entry, + reviewed: isFileViewed(entry.path), + }), + ); + const displayedChapter = useRef(null); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- restores the code viewer DOM scroll position after chapter and reviewed-file changes + useLayoutEffect(() => { + const chapterId = chapter?.id ?? null; + if (displayedChapter.current !== chapterId) { + displayedChapter.current = chapterId; + savedScroll.current = null; + scrollElement.current?.scrollTo({ top: 0 }); + } + if (savedScroll.current !== null && scrollElement.current) { + scrollElement.current.scrollTop = savedScroll.current; + savedScroll.current = null; + } + }); + const chapterId = chapter?.id ?? null; + const [selectionChapter, setSelectionChapter] = useState(chapterId); + if (selectionChapter !== chapterId) { + setSelectionChapter(chapterId); + setSelectedLines(null); + } // Do not re-arm the visible sentinel after failure; it would retry indefinitely. const canLoadNextSlice = @@ -990,6 +1035,7 @@ function PullRequestCodeTab({ }; const setFileViewed = (fileKey: string, viewed: boolean, extendRange: boolean) => { + savedScroll.current = scrollElement.current?.scrollTop ?? null; const range = getFileViewedRange( annotatedFiles, fileKey, @@ -1008,15 +1054,11 @@ function PullRequestCodeTab({ ), ); }; - const fileViewedToggle = { - enabled: filesViewedEnabled, - isViewed: isFileViewed, - isStale: isFileViewedStale, - setFileViewed, - }; const revealFile = (path: string, range?: SelectedLineRange) => { - const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path); + const file = filteredFiles.find((candidate) => candidate.path === path); + if (file && groupByType) setSelectedChapter(reviewFileGroup(path)); + const item = file ? { id: file.fileKey } : undefined; if (item === undefined) return; // Record the unfold even when already open, so a Viewed mark that loads later cannot fold it. setFoldChoices((current) => withFileDiffFold(current, item.id, false)); @@ -1024,16 +1066,106 @@ function PullRequestCodeTab({ codeViewReveal.request(item.id, range); }; + const setChapterViewed = (paths: ReadonlyArray, reviewed: boolean) => { + const selected = new Set(paths); + const remaining = new Set(paths); + for (const file of annotatedFiles) { + if (!selected.has(file.path)) continue; + setFileViewed(file.fileKey, reviewed, false); + remaining.delete(file.path); + } + for (const path of remaining) setViewed(path, reviewed); + }; + const chapterSummaries = chapters.map((candidate, index) => { + const members = candidate.files; + const reviewedCount = members.filter(isFileViewed).length; + const stat = annotatedFiles + .filter((file) => reviewFileGroup(file.path) === candidate.id) + .reduce( + (total, file) => { + const next = sourceFileStats.get(file.fileKey) ?? getDiffLineStat([file.fileDiff]); + return { + additions: total.additions + next.additions, + deletions: total.deletions + next.deletions, + }; + }, + { additions: 0, deletions: 0 }, + ); + return { + title: candidate.title, + reviewed: chapterReviewComplete && reviewedCount === members.length, + stat: diffComplete ? stat : null, + detail: + index !== chapterPosition ? ( + + {chapterReviewComplete + ? `${reviewedCount} of ${members.length} files reviewed` + : chapterCountsPending} + + ) : null, + ...(filesViewed.enabled && canSetChapterViewed + ? { + review: { + reviewedCount, + fileCount: members.length, + disabled: !chapterReviewComplete, + onSetReviewed: (reviewed: boolean) => { + setChapterViewed(members, reviewed); + }, + }, + } + : {}), + }; + }); + + // Answered once the requested file has arrived: a large diff may still be paging when the + // request comes in, so it waits for the slice that carries the path rather than dropping it. + const answeredReveal = useRef(null); + const answerReveal = useEffectEvent(() => { + if (revealRequest === null || answeredReveal.current === revealRequest.nonce) return; + if (diffQuery.isPending && files.length === 0) return; + if ( + revealRequest.threadId && + !placedThreadIds.has(revealRequest.threadId) && + !canLoadNextSlice + ) { + setOrphansOpen(true); + scrollElement.current?.scrollTo({ top: 0 }); + answeredReveal.current = revealRequest.nonce; + return; + } + if (!filteredFiles.some((file) => file.path === revealRequest.path)) { + // The reader is not scrolling toward it, so the sentinel would never ask for its slice. + if (canLoadNextSlice) loadNextSlice(); + return; + } + answeredReveal.current = revealRequest.nonce; + revealFile( + revealRequest.path, + revealRequest.line == null + ? undefined + : { + start: revealRequest.line, + end: revealRequest.line, + side: toViewerSide(revealRequest.side ?? "right"), + }, + ); + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- scrolls the mounted code viewer once a requested file and its conversation load + useEffect(() => { + // oxlint-disable-next-line react/set-state-in-effect -- A reveal may open its conversation or advance the diff cursor. + answerReveal(); + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Re-check the external reveal as its files and conversations load. + }, [canLoadNextSlice, diffQuery.isPending, files, filteredFiles, placedThreadIds, revealRequest]); + const toggleAllFiles = () => { + // Held as an override of the default rather than as the file keys on screen: a diff that is + // still paging would otherwise bring its next slice in folded, moments after the reader + // asked for everything to be open. setFoldOverride(areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys) ? "expanded" : "folded"); setFoldChoices(new Map()); }; - const orderedCommits = // GitLab preserves UTC offsets, so compare instants. - detail.commits.toSorted( - (left, right) => Date.parse(right.committedDate) - Date.parse(left.committedDate), - ); - const beginComment = ( range: SelectedLineRange | null, context: { item: CodeViewItem }, @@ -1063,6 +1195,9 @@ function PullRequestCodeTab({ }); }; + // Built here because the parsed diff only lives here, and built by the same function the + // thread panel's own line selection uses — the gesture is the same one, so a second reading of + // the hunks would only be a second place for it to drift. const finishSelection = ( anchor: DraftAnchor, text: string, @@ -1087,8 +1222,18 @@ function PullRequestCodeTab({ }; // Stable props preserve viewer portals during selection, typing, and review updates. + const refreshDiffQuery = diffQuery.refresh; + const hasVisibleItems = items.length > 0; const renderCodeViewFooter = () => - nextCursor === null ? null : ( + // An empty filtered chapter keeps its navigation and totals. Loading failures belong + // only to an outstanding cursor, rather than a failed refresh of a finished diff. + nextCursor === null ? ( + !hasVisibleItems ? ( +

+ No files match the viewing options. +

+ ) : null + ) : (
The rest of this diff could not be loaded. - @@ -1107,6 +1252,8 @@ function PullRequestCodeTab({ ); const renderHeaderPrefix = (item: CodeViewItem) => { + // The item the viewer is drawing already carries the state the memo settled on, so the + // chevron follows it rather than recomputing the default here. const collapsed = item.collapsed === true; return (
); + // Clear obsolete commit scopes even when an empty list hides the dropdown. + const selectedOids = reviewCommitSelection(commitOids, commit); const selectedCommit = orderedCommits.find((entry) => entry.oid === commit); - const scopeLabel = selectedCommit ? selectedCommit.messageHeadline : "All commits"; + const lastReviewedSha = latestReviewedCommit(detail.comments, detail.viewer); + const lastReviewedIndex = lastReviewedSha === null ? -1 : commitOids.indexOf(lastReviewedSha); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- A refreshed host commit list can invalidate the parent selection. + useEffect(() => { + if (commit !== null && selectedOids.length === 0) onSelectedCommitChange(null); + }, [commit, onSelectedCommitChange, selectedOids.length]); + const scopeLabel = selectedCommit + ? selectedCommit.messageHeadline + : commit === null + ? "All commits" + : `${selectedOids.length} commits`; const changeIgnoreWhitespace = (next: boolean) => { - setIgnoreWhitespace(next); + updateClientSettings({ diffIgnoreWhitespace: next }); setDraft(null); setSelectedLines(null); }; - const toolbar = ( + const displayControls = ( + + updateClientSettings({ + pullRequestViewing: { + ...settings.pullRequestViewing, + hideReviewed: checked, + }, + }), + }, + { + label: "Hide without unresolved comments", + checked: commentsOnly, + onCheckedChange: (checked) => + updateClientSettings({ + pullRequestViewing: { + ...settings.pullRequestViewing, + commentsOnly: checked, + }, + }), + }, + { + label: "Group by file type", + checked: groupByType, + onCheckedChange: (checked) => + updateClientSettings({ + pullRequestViewing: { + ...settings.pullRequestViewing, + groupByType: checked, + }, + }), + }, + ] + } + /> + ); + const toolbarContent = (
- {orderedCommits.length > 0 ? ( + {/* A host that reports no commits has nothing to scope by, and a dropdown whose only + entry is the scope already showing is a control that does nothing. */} + {!guideFallback && orderedCommits.length > 0 ? ( } @@ -1374,30 +1614,57 @@ function PullRequestCodeTab({ - onSelectedCommitChange(value === "all" ? null : value)} + onSelectedCommitChange(null)}> + All commits + + + onSelectedCommitChange(reviewCommitScope(commitOids.slice(lastReviewedIndex + 1))) + } > - - All commits - - {orderedCommits.slice(0, visibleCommitCount).map((entry) => ( - - - - {entry.messageHeadline}} - /> - {entry.messageHeadline} - - + Since last reviewed + + + {orderedCommits.slice(0, visibleCommitCount).map((entry) => + detail.provider === "github" ? ( + + onSelectedCommitChange( + reviewCommitScope( + toggleReviewCommit( + commitOids, + commit === null ? [] : selectedOids, + entry.oid, + ), + ), + ) + } + > + + + {entry.oid.slice(0, 7)} - - ))} - + + ) : ( + onSelectedCommitChange(entry.oid)} + > + {entry.messageHeadline} + + ), + )} {orderedCommits.length > visibleCommitCount ? ( + // Kept out of the radio group: it changes how much of the list is on screen + // rather than what the diff is scoped to. setVisibleCommitCount((count) => count + COMMIT_PAGE_SIZE)} @@ -1410,20 +1677,22 @@ function PullRequestCodeTab({ ) : null} + {/* One count, and the caveats as icons that carry their own words. Spelled out they + competed for a strip this narrow and every one of them truncated to nothing. */} - - {files.length} {files.length === 1 ? "file" : "files"} - {nextCursor === null ? "" : "+"} - - {hiddenTestFileCount > 0 ? ( - + {!filesViewed.enabled ? ( + + {files.length} {files.length === 1 ? "file" : "files"} + {nextCursor === null ? "" : "+"} + ) : null} {filesViewed.enabled && files.length > 0 ? ( + {/* Named on a host that keeps no record of its own, so the reader is told whose + ticks these are without having to find the icon beside them. The count holds its + width and the wording gives way, so the narrow right panel keeps its controls. */} - {filePaths.filter(isFileViewed).length} / {files.length} + {filesViewed.viewedCount} / {files.length} {viewedFilesStore === "environment" ? `viewed in ${APP_BASE_NAME}` : "viewed"} @@ -1502,131 +1771,25 @@ function PullRequestCodeTab({
- - - } - className="@lg:hidden" - aria-label="Diff options" - /> - } - > - - - Diff options - - - changeIgnoreWhitespace(checked)} - > - Hide whitespace changes - - setWordWrapOverride(checked)} - > - Wrap lines - - - { - if (value === "stacked" || value === "split") { - updateClientSettings({ diffLayout: value }); - } - }} - > - - Stacked - - - Split - - - - -
- - changeIgnoreWhitespace(Boolean(pressed))} - /> - } - > - - - - {ignoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"} - - - { - const next = value[0]; - if (next === "stacked" || next === "split") { - updateClientSettings({ diffLayout: next }); - } - }} - > - - - - - - - - - { - setWordWrapOverride(Boolean(pressed)); - }} - /> - } - > - - - - {wordWrap ? "Disable line wrapping" : "Enable line wrapping"} - - -
+ {viewControlsTarget === undefined ? displayControls : null} {fileKeys.length > 0 ? ( } > - {allFilesCollapsed ? ( - - ) : ( - - )} + + {allFilesCollapsed ? "Expand all" : "Collapse all"} {allFilesCollapsed ? "Expand all files" : "Collapse all files"} @@ -1676,23 +1839,6 @@ function PullRequestCodeTab({
); - // A file not loaded yet pages forward each time a slice arrives; once loaded, the viewer - // positions it when it renders it. - const answerReveal = useEffectEvent(() => { - if (revealRequest === null || answeredRevealNonce.current === revealRequest.nonce) return; - if (!items.some((item) => resolveFileDiffPath(item.fileDiff) === revealRequest.path)) { - if (canLoadNextSlice) loadNextSlice(); - return; - } - answeredRevealNonce.current = revealRequest.nonce; - revealFile(revealRequest.path); - }); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- scrolls the code view to a requested file once loaded, or pages forward until it arrives - useEffect(() => { - // oxlint-disable-next-line react/set-state-in-effect -- A reveal for a file not loaded yet pages forward, which sets the slice cursor. - answerReveal(); - // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Re-checked as pages load until the requested file arrives. - }, [canLoadNextSlice, items, revealRequest]); // The store clears a settled link after this render, so one link must not reveal twice. const answeredLink = useRef(null); const revealLink = useEffectEvent(() => { @@ -1745,44 +1891,80 @@ function PullRequestCodeTab({ revealLink(); // oxlint-disable-next-line react/exhaustive-effect-dependencies -- retries the reveal as diff pages and viewer items arrive }, [revealUrl, pendingLinkPath, canLoadNextSlice, items]); + const toolbar = ( + <> + {viewControlsTarget ? createPortal(displayControls, viewControlsTarget) : null} + {guideFallback ? null : toolbarContent} + + ); + // The toolbar rides above every branch below, not just the one with a patch in it: a commit + // whose diff is empty or unreadable still needs the scope dropdown that got the reader there. const withToolbar = (body: ReactNode) => (
{toolbar} -
- {body} +
+ {guideFallback && guideStatus ? {guideStatus} : null} +
+ {guideFallback && guideStatus ? ( +
{guideStatus}
+ ) : null} + {body} +
); const term = sourceControlClients.get(detail.provider).changeRequest.singular; + // Under the toolbar rather than in place of it, so choosing a commit does not take the + // dropdown that was just used off the screen while its diff loads. if (diffQuery.isPending && loadedSlices.length === 0) { return withToolbar(); } + // A slice that fails once there are files on screen is reported at the end of them instead: + // the diff already read is worth more than the error that stopped it growing. if (diffQuery.error && loadedSlices.length === 0) { return withToolbar( - diffQuery.refresh()} - />, +

{diffQuery.error}

, ); } - if (rawSlicesView !== null) { - return withToolbar(rawSlicesView); + // A patch the viewer cannot structure (binary, or a format it does not parse) still has to + // be readable, so it falls back to the raw text rather than an empty tab. Only once the diff + // is whole: returning here while a cursor is outstanding would take the sentinel off screen + // and end the walk, leaving the rest of the change unasked for. + const rawSlices = + nextCursor === null + ? parsedSlices.flatMap((parsed) => (parsed?.kind === "raw" ? [parsed] : [])) + : []; + if (files.length === 0 && rawSlices.length > 0) { + return withToolbar( +
+ {rawSlices.map((slice) => ( +
+

{slice.reason}

+
{slice.text}
+
+ ))} +
, + ); } - if (items.length === 0 && nextCursor === null) { + if (items.length === 0 && nextCursor === null && chapter === null) { return withToolbar(

- {commit === null ? `This ${term} has no file changes.` : "This commit has no file changes."} + {files.length > 0 + ? "No files match the viewing options." + : commit === null + ? `This ${term} has no file changes.` + : "This commit has no file changes."}

, ); } - const orphanThreads = detail.reviewThreads.filter((thread) => !placedThreadIds.has(thread.id)); + const orphanThreads = visibleHostThreads.filter((thread) => !placedThreadIds.has(thread.id)); + // A file carrying five stranded conversations should read as that file once rather than as + // five copies of its path. const orphanFiles = new Map(); for (const thread of orphanThreads) { const existing = orphanFiles.get(thread.path); @@ -1790,14 +1972,112 @@ function PullRequestCodeTab({ else orphanFiles.set(thread.path, [thread]); } + const unstructured = + rawSlices.length === 0 ? null : ( + // A slice the viewer cannot structure is still part of the change. Shown under the files + // that did parse rather than dropped, because the alternative is a diff that silently + // omits whatever the viewer could not read. +
+ {rawSlices.map((slice) => ( +
+

{slice.reason}

+
{slice.text}
+
+ ))} +
+ ); + + const selectChapter = (position: number) => { + const next = chapters[position]; + if (!next) return; + savedScroll.current = null; + scrollElement.current?.scrollTo({ top: 0 }); + setSelectedLines(null); + setSelectedChapter(next.id); + setChapterRailOpen(false); + }; + const chapterRail = chapter ? ( + { + const members = chapters[index]?.files ?? []; + const reviewedCount = members.filter(isFileViewed).length; + return { + ...summary, + selectedContent: + index === chapterPosition ? ( +
+ {chapterReviewComplete ? ( + { + setChapterViewed(members, reviewed); + } + : null + } + /> + ) : null} + {!chapterReviewComplete ? ( +

{chapterCountsPending}

+ ) : null} + {guideFallback ? ( +
    + {chapters[index]?.visibleFiles.map((file) => ( +
  • + revealFile(file.path)} + /> +
  • + ))} +
+ ) : null} +
+ ) : null, + }; + })} + position={chapterPosition} + onSelect={selectChapter} + /> + ) : null; + + const chapterHeader = chapter ? ( +
+ {guideFallback && guideStatus ? ( +
{guideStatus}
+ ) : null} + selectChapter(chapterPosition + delta)} + /> +

{chapter.title}

+
+ ) : null; return ( -
+
{toolbar} + {/* Above the code, closed, and counted: these belong to the change rather than to any + line of it, and in the stream they read as cards dropped into the patch. */} {orphanFiles.size > 0 ? (
+ {/* Still a heading, so the section keeps its place in a screen reader's outline; + the count is spelled out there rather than left as a bare number. */}

+ {/* While slices are still arriving a conversation may simply belong to a file + that has not landed yet, which is not the same as being off the diff. */} {nextCursor === null ? "Conversations not on the current diff" @@ -1818,7 +2098,11 @@ function PullRequestCodeTab({

-
+ {/* Keep room for the diff, but let an active reply form fit at its full height. */} +
{[...orphanFiles].map(([path, threads]) => (
@@ -1833,7 +2117,9 @@ function PullRequestCodeTab({ {threads.map((thread) => (
{thread.line === null ? null : ( -

Line {thread.line}

+

+ {reviewLineRangeLabel(thread)} +

)} {renderThreadCard(thread)}
@@ -1847,52 +2133,85 @@ function PullRequestCodeTab({
) : null}
-
{ - const composedPath = event.nativeEvent.composedPath?.() ?? []; - for (const node of composedPath) { - if (!(node instanceof HTMLElement)) continue; - if (node instanceof HTMLButtonElement || node instanceof HTMLAnchorElement) { - return; - } - if (node.hasAttribute("data-viewed-toggle")) return; - if (node.hasAttribute("data-diffs-header")) { - const filePath = node.querySelector("[data-title]")?.textContent?.trim(); - if (filePath === undefined || filePath === "") return; - const item = items.find( - (candidate) => resolveFileDiffPath(candidate.fileDiff) === filePath, - ); - if (item !== undefined) toggleFile(item.id); - return; + {chapter && guideFallback ? ( + + {guideStatus} + {chapterRail} + + ) : chapter ? ( + + ) : null} +
+ {/* Relative wrapper so the review overlay floats over the diff rather than pushing it + up; the viewer inside still owns its own scrolling. */} +
{ + const composedPath = event.nativeEvent.composedPath?.() ?? []; + for (const node of composedPath) { + if (!(node instanceof HTMLElement)) continue; + // A control inside the header — the collapse chevron — handles itself, and + // this capture listener fires before its own click does. Leave it alone or + // the two toggles cancel out. + if (node instanceof HTMLButtonElement || node instanceof HTMLAnchorElement) { + return; + } + // A label answers for the control it names and this listener runs before it hears + // anything, so stopping the press keeps the header from folding what the tick folds. + if (node.hasAttribute("data-viewed-toggle")) return; + if (node.hasAttribute("data-diffs-header")) { + const filePath = node.querySelector("[data-title]")?.textContent?.trim(); + if (filePath === undefined || filePath === "") return; + const item = items.find( + (candidate) => resolveFileDiffPath(candidate.fileDiff) === filePath, + ); + if (item !== undefined) toggleFile(item.id); + return; + } } - } - }} - > - {/* The viewer must own its scroll element to position virtual rows within it. */} - - - className="@container h-full overflow-auto [scrollbar-gutter:stable]" - containerRef={scrollerRef} - viewerRef={codeViewReveal.attach} - items={items} - selectedLines={selectedLines} - onSelectedLinesChange={setSelectedLines} - options={diffViewOptions} - renderCodeViewFooter={renderCodeViewFooter} - renderHeaderPrefix={renderHeaderPrefix} - renderHeaderMetadata={renderHeaderMetadata} - renderAnnotation={renderAnnotation} - unsafeCSSExtra={`${REPLACE_FILE_COUNTS_CSS}\n${CUT_LINES_CSS}`} - /> - + }} + > + {/* The viewer virtualizes against the element it is told is scrolling and places its + rows absolutely, so it has to own that element — the thread diff panel hands it the + same one. Scrolling from a parent instead leaves it painting over its neighbours. */} + + + // Keep scrollbar space stable so file metadata and line numbers do not shift as a + // diff crosses the overflow boundary. The viewer is itself focusable for keyboard + // interaction, but its native host outline clips and competes with the focus + // indicators on its actual controls. + className="@container h-full overflow-auto [scrollbar-gutter:stable]" + containerRef={setScroller} + viewerRef={codeViewReveal.attach} + items={items} + selectedLines={selectedLines} + onSelectedLinesChange={setSelectedLines} + options={diffViewOptions} + // The viewer owns the scroll container, so the sentinel that asks for the next slice + // has to live inside it — at the end of the files, where reaching it means the reader + // is running out of diff. + renderCodeViewHeader={() => chapterHeader} + renderCodeViewFooter={renderCodeViewFooter} + renderHeaderPrefix={renderHeaderPrefix} + renderHeaderMetadata={renderHeaderMetadata} + renderAnnotation={renderAnnotation} + // Find can ask again before the unfolded file arrives, so this unfolds and never folds. + unsafeCSSExtra={REPLACE_FILE_COUNTS_CSS} + /> + +
- {fileTreeOpen ? ( + {!guideFallback && fileTreeOpen ? ( reviewFileGroup(entry.path) === chapter.id, + ) + : folderReviewEntries + } onSelectFile={revealFile} + onReviewFiles={ + filesViewed.enabled && canSetChapterViewed && nextCursor === null + ? (paths, reviewed) => { + const selectedPaths = new Set(paths); + for (const item of annotatedFiles) { + if (selectedPaths.has(item.path)) + setFileViewed(item.fileKey, reviewed, false); + } + } + : undefined + } + // The tree lists only what has arrived; a footer says so while the diff is still + // paging, and lets the reader pull the rest in without scrolling for it. footer={ nextCursor === null ? null : (
diff --git a/apps/web/src/components/pullRequest/PullRequestCommentActions.tsx b/apps/web/src/components/pullRequest/PullRequestCommentActions.tsx new file mode 100644 index 0000000000000..faa95174fd6b9 --- /dev/null +++ b/apps/web/src/components/pullRequest/PullRequestCommentActions.tsx @@ -0,0 +1,118 @@ +import { + CheckIcon, + ClipboardIcon, + LinkIcon, + MessageSquarePlusIcon, + MoreHorizontalIcon, + TextIcon, + ExternalLinkIcon, +} from "lucide-react"; +import { readLocalApi } from "~/localApi"; +import { useCopyToClipboard } from "~/hooks/useCopyToClipboard"; +import { Button } from "../ui/button"; +import { + Menu, + MenuItem, + MenuPopup, + MenuSeparator, + MenuSub, + MenuSubPopup, + MenuSubTrigger, + MenuTrigger, +} from "../ui/menu"; +import { toastManager } from "../ui/toast"; + +export function PullRequestCommentActions({ + body, + url, + onEdit, + onOpen, + resolution, + onCopyLink, + disabled, + onAddToComposer, +}: { + body: string; + onOpen?: ((url: string) => void) | undefined; + url: string | null; + onCopyLink?: (() => Promise) | undefined; + disabled?: boolean | undefined; + onAddToComposer?: (() => void) | undefined; + onEdit?: (() => void) | undefined; + resolution?: + | { + resolved: boolean; + pending: boolean; + onToggle: () => void; + } + | undefined; +}) { + const { copyToClipboard } = useCopyToClipboard({ + target: "comment", + onError: () => toastManager.add({ type: "error", title: "Could not copy the comment" }), + }); + return ( + + } + aria-label="Comment actions" + disabled={disabled} + > + + + + {resolution ? ( + <> + + + {resolution.resolved ? "Unresolve thread" : "Resolve thread"} + + + + ) : null} + {url ? ( + (onOpen ? onOpen(url) : void readLocalApi()?.shell.openExternal(url))} + > + + Open on host + + ) : null} + {onEdit ? Edit comment : null} + + + + Copy + + + + void (async () => { + const link = onCopyLink ? await onCopyLink() : url; + if (link) await copyToClipboard(link, undefined); + })() + } + > + + Link to comment + + copyToClipboard(body, undefined)}> + + Copy as Markdown + + + + {onAddToComposer ? ( + <> + + + + Add to composer + + + ) : null} + + + ); +} diff --git a/apps/web/src/components/pullRequest/PullRequestCommentForm.tsx b/apps/web/src/components/pullRequest/PullRequestCommentForm.tsx index cf0ff1ab468c2..bf9ee9464b33e 100644 --- a/apps/web/src/components/pullRequest/PullRequestCommentForm.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCommentForm.tsx @@ -1,4 +1,5 @@ import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; +import { PullRequestAttachments } from "./PullRequestAttachments"; import { useAtomCommand } from "~/state/use-atom-command"; import type { EnvironmentId, PullRequestDetailView, PullRequestRef } from "@t3tools/contracts"; import { SendIcon } from "lucide-react"; @@ -42,9 +43,10 @@ export function PullRequestCommentForm({ onCommented: () => void; onClose: () => void; }) { + const [uploading, setUploading] = useState(false); const [body, setBody] = useState(""); const [submitting, setSubmitting] = useState<"comment" | "close" | "reopen" | null>(null); - const locked = submitting !== null || actionPending; + const locked = submitting !== null || actionPending || uploading; const speech = useTextFieldSpeech({ environmentId, projectId: reference.projectId, @@ -76,7 +78,7 @@ export function PullRequestCommentForm({ const submit = async (action: "comment" | "close" | "reopen", text: string) => { const trimmed = text.trim(); - if (trimmed.length === 0 || submitting !== null || actionPending) return; + if (trimmed.length === 0 || submitting !== null || actionPending || uploading) return; setSubmitting(action); if (action !== "comment") { const result = await onCommentAction(trimmed, action); @@ -110,7 +112,7 @@ export function PullRequestCommentForm({ speech.preparing || (body.trim().length === 0 && !speech.blocksSubmission) || locked; return ( -
+
+
{followUpAction === null ? null : ( diff --git a/apps/web/src/components/pullRequest/PullRequestCommentsPopover.tsx b/apps/web/src/components/pullRequest/PullRequestCommentsPopover.tsx new file mode 100644 index 0000000000000..d8a526812c159 --- /dev/null +++ b/apps/web/src/components/pullRequest/PullRequestCommentsPopover.tsx @@ -0,0 +1,243 @@ +import type { + EnvironmentId, + PullRequestDetailView, + PullRequestRef, + PullRequestReviewThread, + PullRequestThreadComment, +} from "@t3tools/contracts"; +import { FileCode2Icon, MessageSquareIcon, XIcon } from "lucide-react"; +import { useState } from "react"; +import { reviewLineRangeLabel } from "@t3tools/client-runtime/review-selection"; +import { Button } from "../ui/button"; +import { Badge } from "../ui/badge"; +import { Toggle, ToggleGroup } from "../ui/toggle-group"; +import { Popover, PopoverPopup, PopoverTrigger, PopoverTitle } from "../ui/popover"; +import { + getReviewPositionAnchor, + PendingReviewCommentCard, + ReviewThreadCard, +} from "./PullRequestReviewAnnotation"; +import { usePendingReviewComments, type PendingReviewComment } from "./pullRequestReviewStore"; +import { useReviewThreadActions } from "./useReviewThreadActions"; + +type CommentLocation = { + readonly path: string; + readonly line: number | null; + readonly side: "left" | "right"; + readonly threadId?: string; +}; + +/** A PR-wide conversation checklist that stays reachable across all three review tabs. */ +export function PullRequestCommentsPopover({ + environmentId, + reference, + detail, + onRefresh, + onOpenComment, + onAddThreadCommentToComposer, + onAddPendingToComposer, +}: { + environmentId: EnvironmentId; + reference: PullRequestRef; + detail: PullRequestDetailView; + onRefresh: () => void; + onOpenComment: (location: CommentLocation) => void; + onAddThreadCommentToComposer?: + | ((thread: PullRequestReviewThread, comment: PullRequestThreadComment) => void) + | undefined; + onAddPendingToComposer?: ((comment: PendingReviewComment) => void) | undefined; +}) { + const [open, setOpen] = useState(false); + const [trigger, setTrigger] = useState(null); + const anchor = trigger + ? { + contextElement: trigger, + getBoundingClientRect: () => { + const button = trigger.getBoundingClientRect(); + const panel = trigger.closest("[data-pull-request-panel]")?.getBoundingClientRect(); + return new DOMRect( + panel?.left ?? button.left, + button.top, + panel?.width ?? button.width, + button.height, + ); + }, + } + : undefined; + const [selectedStatus, setSelectedStatus] = useState<"resolved" | "unresolved" | "pending">( + "unresolved", + ); + const pending = usePendingReviewComments(reference, detail.reviewThreads); + const actions = useReviewThreadActions(environmentId, reference, detail, onRefresh); + // Hosted drafts are represented by the merged pending list, so they get one checklist entry. + const threads = detail.reviewThreads.flatMap((thread) => { + const comments = thread.comments.filter((comment) => !comment.pendingReviewId); + return comments.length ? [{ ...thread, comments }] : []; + }); + const unresolved = threads.filter((thread) => !thread.isResolved); + const resolved = threads.filter((thread) => thread.isResolved); + const openCount = unresolved.length + pending.length; + const status = + selectedStatus === "pending" && pending.length === 0 ? "unresolved" : selectedStatus; + if (status !== selectedStatus) setSelectedStatus(status); + const visibleThreads = + status === "resolved" ? resolved : status === "unresolved" ? unresolved : []; + const jump = (location: CommentLocation) => { + setOpen(false); + onOpenComment(location); + }; + return ( + + } + aria-label={`Comments, ${openCount} open`} + > + + Comments + + {openCount} + + + +
+
+ Comments + +
+
+ { + const next = values[0]; + if (next === "resolved" || next === "unresolved" || next === "pending") + setSelectedStatus(next); + }} + > + + Unresolved{" "} + + {unresolved.length} + + + + Resolved{" "} + + {resolved.length} + + + {pending.length > 0 ? ( + + Pending{" "} + + {pending.length} + + + ) : null} + +
+
+ {open ? ( + <> + {visibleThreads.map((thread) => ( +
+
+ +
+ onAddThreadCommentToComposer(thread, comment) + : undefined + } + /> +
+ ))} + {(status === "pending" ? pending : []).map((comment) => ( +
+
+ +
+ onAddPendingToComposer(comment) : undefined + } + /> +
+ ))} + {visibleThreads.length === 0 && (status !== "pending" || pending.length === 0) ? ( +

No {status} comments.

+ ) : null} + + ) : null} +
+
+
+
+ ); +} diff --git a/apps/web/src/components/pullRequest/PullRequestComposer.tsx b/apps/web/src/components/pullRequest/PullRequestComposer.tsx index f954c2b262dee..f395e69eb64fe 100644 --- a/apps/web/src/components/pullRequest/PullRequestComposer.tsx +++ b/apps/web/src/components/pullRequest/PullRequestComposer.tsx @@ -9,6 +9,7 @@ import { useRef, useState } from "react"; import { Button } from "../ui/button"; import { Popover, PopoverClose, PopoverPopup, PopoverTitle, PopoverTrigger } from "../ui/popover"; import { Toggle, ToggleGroup } from "../ui/toggle-group"; +import { usePendingReviewCommentActions } from "./usePendingReviewCommentActions"; import { PullRequestCommentForm } from "./PullRequestCommentForm"; import { PullRequestReviewForm } from "./PullRequestReviewForm"; import { @@ -46,9 +47,14 @@ export function PullRequestComposer({ const [requestedMode, setRequestedMode] = useState<"comment" | "review">("comment"); const commentRef = useRef(null); const reviewRef = useRef(null); - const pendingComments = usePendingReviewComments(reference); - const clearComments = usePullRequestReviewStore((store) => store.clear); - // Unsent summaries outlive the popover; select a boolean to avoid per-keystroke renders. + const pendingComments = usePendingReviewComments(reference, detail.reviewThreads); + const { + busy: draftBusy, + canDiscard, + discardAll, + } = usePendingReviewCommentActions(environmentId, reference); + // A summary typed but not sent is review work too, and it outlives the popover. Selected as a + // boolean rather than the text, so typing one does not re-render the composer per keystroke. const reviewKey = pullRequestReviewKey(reference); const summaryStarted = usePullRequestReviewStore( (store) => (store.summaries[reviewKey] ?? "").trim().length > 0, @@ -134,8 +140,13 @@ export function PullRequestComposer({ variant="ghost" aria-label="Discard pending line comments" title="Discard pending line comments" - disabled={reviewPending} - onClick={() => clearComments(reviewKey)} + disabled={ + reviewPending || + draftBusy || + (!canDiscard && + pendingComments.some((comment) => comment.hostedComment !== undefined)) + } + onClick={() => void discardAll(pendingComments)} > @@ -157,6 +168,7 @@ export function PullRequestComposer({ reference={reference} completionScope={pullRequestCompletionScope(detail, environmentId, reference)} term={term} + reviewThreads={detail.reviewThreads} verdicts={verdicts} requestChangesSummaryRequired={sourceControlClients .get(detail.provider) diff --git a/apps/web/src/components/pullRequest/PullRequestDetailActions.tsx b/apps/web/src/components/pullRequest/PullRequestDetailActions.tsx index f5a5b4ee77bd9..c67a46dd2ef0b 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailActions.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailActions.tsx @@ -4,10 +4,9 @@ import type { PullRequestMergeMethod, PullRequestUpdateMethod, } from "@t3tools/contracts"; -import { CheckIcon, ChevronDownIcon, FolderGit2Icon, GitBranchIcon, PlayIcon } from "lucide-react"; +import { ChevronDownIcon, FolderGit2Icon, GitBranchIcon, PlayIcon } from "lucide-react"; import type { ReactNode } from "react"; -import { AnimatedWidth } from "~/components/AnimatedWidth"; import { cn } from "~/lib/utils"; import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon"; import { Badge } from "../ui/badge"; @@ -32,6 +31,7 @@ export type PerformPullRequestAction = ( action: PullRequestAction, method?: PullRequestMergeMethod, updateMethod?: PullRequestUpdateMethod, + adminOverride?: boolean, ) => Promise; export function ActOnEnvironmentPicker({ @@ -189,33 +189,25 @@ export function PullRequestResolveConflictsButton({ /** The header's one prominent control, which depends on where the pull request stands. */ export function PullRequestPrimaryAction({ - pullRequestKey, primaryAction, - mergeBlockedReason, autoMergeArmed, armedAutoMergeLabel, - pendingAutoMergeLabel, - selectedMergeMethod, - selectedMergeMethodLabel, statePresentation, pendingAction, perform, resolveConflicts, + mergeControl, }: { - pullRequestKey: string; primaryAction: ReturnType | null; - mergeBlockedReason: string | null; autoMergeArmed: boolean; armedAutoMergeLabel: string; - pendingAutoMergeLabel: string; - selectedMergeMethod: PullRequestMergeMethod; - selectedMergeMethodLabel: string; statePresentation: ReturnType | null; pendingAction: PullRequestAction | null; perform: PerformPullRequestAction; resolveConflicts: ReactNode; + /** The merge button, with its confirmation and any admin override; armed for auto-merge or not. */ + mergeControl: (autoMerge: boolean) => ReactNode; }) { - const inlineConfirm = useInlineActionConfirm(pullRequestKey); const actionPending = pendingAction !== null; return ( <> @@ -257,62 +249,7 @@ export function PullRequestPrimaryAction({ Ready for review ) : primaryAction === "enable-auto-merge" ? ( - - - - - } - /> - - {mergeBlockedReason ?? - (pendingAction === "enable-auto-merge" - ? "Enabling..." - : inlineConfirm.isArmed("enable-auto-merge") - ? "Confirm auto-merge?" - : pendingAutoMergeLabel)} - - + mergeControl(true) ) : primaryAction === "auto-merge-armed" ? ( ) : primaryAction === "merge" ? ( - - - - - } - /> - - {mergeBlockedReason ?? - (pendingAction === "merge" - ? "Merging..." - : inlineConfirm.isArmed("merge") - ? "Confirm merge?" - : selectedMergeMethodLabel)} - - + mergeControl(false) ) : (primaryAction === "merged" || primaryAction === "closed") && statePresentation !== null ? ( diff --git a/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx b/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx index 95bef6edeec91..4842d4b2780e1 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx @@ -70,7 +70,7 @@ export function PullRequestDetailTabBar({ inert, children, }: { - tabs: ReadonlyArray<{ readonly value: Tab; readonly label: string }>; + tabs: ReadonlyArray<{ readonly value: Tab; readonly label: string; readonly icon?: ReactNode }>; value: Tab; onValueChange?: (tab: Tab) => void; onTabIntent?: (tab: Tab) => void; @@ -112,6 +112,7 @@ export function PullRequestDetailTabBar({ onPointerLeave={onTabIntent ? () => clearTimeout(pointerIntent.current) : undefined} onFocus={onTabIntent ? () => onTabIntent(tab.value) : undefined} > + {tab.icon} {tab.label} ))} diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index 611185ec9f308..32be34c84578e 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -1,3 +1,4 @@ +import { PullRequestActivityUnavailableState } from "./PullRequestActivityUnavailableState"; import { parsePullRequestAnchor, pullRequestLinkCommit, @@ -25,16 +26,19 @@ import { type PullRequestRef, type PullRequestReviewGuideStop, type PullRequestSummary, + type PullRequestReviewThread, + type PullRequestThreadComment, + type PullRequestComment, resolveEnvironmentMachineKind, type ScopedThreadRef, } from "@t3tools/contracts"; import { - ArrowDownUpIcon, ArrowLeftIcon, CircleDotIcon, FileDiffIcon, - GitCommitHorizontalIcon, - MessageSquareIcon, + FileTextIcon, + ListOrderedIcon, + DiffIcon, PanelRightIcon, } from "lucide-react"; import { @@ -45,6 +49,7 @@ import { useLayoutEffect, useRef, useState, + type ReactNode, } from "react"; import { type DraftId, useComposerDraftStore } from "~/composerDraftStore"; @@ -78,6 +83,7 @@ import { capitalizeTerm, sourceControlClients, } from "@t3tools/client-runtime/source-control-clients"; +import { PullRequestMergeControl } from "./PullRequestMergeControl"; import { PullRequestThreadLinks } from "./PullRequestThreadLinks"; import { vcsEnvironment } from "~/state/vcs"; import { RelativeTime } from "~/components/RelativeTime"; @@ -92,7 +98,7 @@ import { PullRequestDetailHeaderBody, PullRequestDetailTabBar, } from "./PullRequestDetailLayout"; -import { PullRequestDetailGhost, PullRequestTimelineGhost } from "./PullRequestGhosts"; +import { PullRequestDetailGhost, PullRequestConversationGhost } from "./PullRequestGhosts"; import { PullRequestCopyableCode } from "./PullRequestCopyableCode"; import { pullRequestRefKey, usePullRequestDetail } from "./usePullRequestDetail"; import { PullRequestActionsMenu } from "./PullRequestActionsMenu"; @@ -105,7 +111,6 @@ import { import { PullRequestBaseBranch } from "./PullRequestBaseBranch"; import { PullRequestDetailCrumbs } from "./PullRequestDetailCrumbs"; import { PullRequestTitleEditor } from "./PullRequestTitleEditor"; -import { PullRequestActivityUnavailableState } from "./PullRequestActivityUnavailableState"; import { SourceControlAppAccessNotice } from "../SourceControlAppAccessNotice"; import { DiffPanelLoadingState } from "../DiffPanelShell"; import { PullRequestsUnavailableState } from "./PullRequestsUnavailableState"; @@ -115,12 +120,14 @@ import { PullRequestMarkdownContext } from "./PullRequestMarkdown"; import { pullRequestMarkdownPlugins } from "./pullRequestMarkdown.logic"; import { PullRequestComposer } from "./PullRequestComposer"; import { PullRequestSummaryTab } from "./PullRequestSummaryTab"; +import { PullRequestCommentsPopover } from "./PullRequestCommentsPopover"; +import { getReviewPositionAnchor } from "./PullRequestReviewAnnotation"; +import type { PendingReviewComment } from "./pullRequestReviewStore"; import { PullRequestTimelineTab } from "./PullRequestTimelineTab"; import { buildAddSelectionToAgentHandoff, buildAskAboutGuideStopHandoff, buildAskAboutPullRequestHandoff, - buildExplainPullRequestHandoff, buildFixFindingHandoff, buildFixFindingsHandoff, buildPullRequestCommentContext, @@ -155,17 +162,13 @@ import { resolvePickableEnvironments } from "./pullRequestProjectAssignment.logi import { PullRequestChecksPopover } from "./PullRequestChecksPopover"; import { PullRequestActorLabel, - PullRequestMetaLine, - PullRequestReviewOutcomeIcon, pullRequestChecksState, pullRequestChecksStatePresentation, - pullRequestReviewOutcomeToneClassName, resolvePullRequestState, summarizePullRequestChecks, } from "./pullRequestPresentation"; import { PullRequestGuideTab } from "./PullRequestGuideTab"; import { guideRunKey, useGuideRunStore } from "./guide/guideRunStore"; -import { useReviewGuideWriter } from "./guide/useReviewGuideWriter"; const actionFailureLabels = (term: string): Record => ({ merge: `Could not merge this ${term}`, @@ -205,11 +208,10 @@ const actionFailureHints = (term: string): Record => const UPDATE_BRANCH_REBASE_FAILURE_HINT = "The host refused it. A rebase stops at the first commit that does not apply cleanly; updating with a merge commit may still work."; -const TABS: ReadonlyArray<{ value: PullRequestDetailTab; label: string }> = [ - { value: "summary", label: "Summary" }, - { value: "guide", label: "Guide" }, - { value: "timeline", label: "Timeline" }, - { value: "code", label: "Code" }, +const TABS: ReadonlyArray<{ value: PullRequestDetailTab; label: string; icon: ReactNode }> = [ + { value: "summary", label: "Overview", icon: }, + { value: "guide", label: "Guide", icon: }, + { value: "code", label: "Code", icon: }, ]; // Defer the diff viewer's worker pool until Code is approached. @@ -403,12 +405,12 @@ export function PullRequestDetailPanel({ (value !== "guide" || reviewGuidesEnabled); // An unavailable tab falls back without overwriting the saved selection. const tab = isTabAvailable(requestedTab) ? requestedTab : "summary"; + const [viewControlsTarget, setViewControlsTarget] = useState(null); const selectTab = (next: PullRequestDetailTab) => { if (tabOnPage) useGuideRunStore.getState().showPageDetailTab(guideKey, next); else setTab(next); onTabChange?.(next); }; - const [timelineOrder, setTimelineOrder] = useState<"newest" | "oldest">("newest"); const [codeCommitScope, setCodeCommitScope] = useState<{ readonly pullRequestKey: string; readonly oid: string | null; @@ -425,6 +427,9 @@ export function PullRequestDetailPanel({ const [codeRevealRequest, setCodeRevealRequest] = useState<{ readonly path: string; readonly nonce: number; + readonly line?: number | null; + readonly side?: "left" | "right"; + readonly threadId?: string; } | null>(null); const openFileInCode = (path: string) => { selectCodeCommit(null); @@ -459,6 +464,17 @@ export function PullRequestDetailPanel({ followLink(); // oxlint-disable-next-line react/exhaustive-effect-dependencies -- each clicked link is a navigation request }, [revealUrl]); + const openCommentInCode = (location: { + path: string; + line: number | null; + side: "left" | "right"; + threadId?: string; + }) => { + selectCodeCommit(null); + setCodeRevealRequest((previous) => ({ ...location, nonce: (previous?.nonce ?? 0) + 1 })); + void loadCodeTab(); + selectTab("code"); + }; const tabScopeKey = `${environmentId}:${pullRequestKey}`; const [tabMountState, setTabMountState] = useState(() => ({ key: tabScopeKey, @@ -493,6 +509,9 @@ export function PullRequestDetailPanel({ timeline: (node: HTMLElement | null) => { scrollerByTab.current.timeline = node; }, + guide: (node: HTMLDivElement | null) => { + scrollerByTab.current.guide = node; + }, code: (node: HTMLElement | null) => { scrollerByTab.current.code = node; }, @@ -627,10 +646,13 @@ export function PullRequestDetailPanel({ : "Checking stack membership…"; const activityPending = activityQuery.isPending && activity === null; const activityError = activity === null ? activityQuery.error : null; + const refreshDetailQuery = detailQuery.refresh; + const refreshActivityQuery = activityQuery.refresh; + const refreshNativeStackQuery = nativeStackQuery.refresh; const refreshDetail = () => { - detailQuery.refresh(); - activityQuery.refresh(); - nativeStackQuery.refresh(); + refreshDetailQuery(); + refreshActivityQuery(); + refreshNativeStackQuery(); }; const [refreshToken, setRefreshToken] = useState(0); const [activityRevision, setActivityRevision] = useState<{ @@ -784,6 +806,7 @@ export function PullRequestDetailPanel({ action: PullRequestAction, method?: PullRequestMergeMethod, updateMethod?: PullRequestUpdateMethod, + adminOverride = false, ) => { onActed?.(action, "sent"); const result = await runAction({ @@ -793,6 +816,7 @@ export function PullRequestDetailPanel({ action, ...(method ? { mergeMethod: method } : {}), ...(updateMethod ? { updateMethod } : {}), + ...(adminOverride ? { adminOverride: true } : {}), }, }); setPendingAction(null); @@ -832,10 +856,11 @@ export function PullRequestDetailPanel({ action: PullRequestAction, method?: PullRequestMergeMethod, updateMethod?: PullRequestUpdateMethod, + adminOverride = false, ) => { if (!canWriteSourceControl || pendingAction !== null) return false; setPendingAction(action); - return finishAction(action, method, updateMethod); + return finishAction(action, method, updateMethod, adminOverride); }; const performCommentAction = async (body: string, action: "close" | "reopen") => { @@ -865,15 +890,6 @@ export function PullRequestDetailPanel({ const canPrepareWorktree = prepareThread.isAllowed && canOperateThread; const canFixFindings = attachTarget !== null || canPrepareWorktree; const handoffLabels = pullRequestHandoffLabels(attachTarget !== null); - const guideWriter = useReviewGuideWriter({ - environmentId, - reference, - title: detail?.title ?? null, - }); - const writeGuide = () => { - void guideWriter.write(); - if (guideWriter.data?.guide == null) selectTab("guide"); - }; const openThreadWithTask = async ( projectRef: ReturnType, @@ -1087,21 +1103,6 @@ export function PullRequestDetailPanel({ }); }; - const explainPullRequest = () => { - if (!detail) return; - void startAsk("explain", { - ...buildExplainPullRequestHandoff({ - number: detail.number, - title: detail.title, - url: detail.url, - headBranch: detail.headBranch, - baseBranch: detail.baseBranch, - state: detail.state, - isDraft: detail.isDraft, - }), - }); - }; - const askAboutGuideStop = (stop: PullRequestReviewGuideStop, index: number, question: string) => { if (!detail) return; void startAsk( @@ -1209,6 +1210,76 @@ export function PullRequestDetailPanel({ ); }; + const addThreadCommentToComposer = ( + thread: PullRequestReviewThread, + comment: PullRequestThreadComment, + ) => { + if (!detail) return; + const task = buildFixFindingHandoff({ + number: detail.number, + title: detail.title, + url: detail.url, + headBranch: detail.headBranch, + baseBranch: detail.baseBranch, + state: detail.state, + isDraft: detail.isDraft, + finding: { kind: "thread", thread: { ...thread, comments: [comment] } }, + }); + void startAsk( + `comment:${comment.id}`, + { + ...task, + prompt: "", + reviewComments: task.reviewComments.map((context) => ({ + ...context, + id: `pull-request-comment:${comment.id}`, + text: comment.body, + startIndex: Math.max(0, (thread.startLine ?? thread.line ?? 1) - 1), + })), + }, + { keepGuide: true }, + ); + }; + const addCommentToComposer = (comment: PullRequestComment) => { + if (!detail) return; + const task = buildFixFindingHandoff({ + number: detail.number, + title: detail.title, + url: detail.url, + headBranch: detail.headBranch, + baseBranch: detail.baseBranch, + state: detail.state, + isDraft: detail.isDraft, + finding: { kind: "comment", comment }, + }); + // General comments have no diff anchor, so their words belong in the composer itself. + void startAsk(`comment:${comment.id}`, { ...task, prompt: comment.body }, { keepGuide: true }); + }; + const addPendingToComposer = (comment: PendingReviewComment) => { + const anchor = getReviewPositionAnchor(comment.position); + const start = comment.startPosition ? getReviewPositionAnchor(comment.startPosition) : null; + void startAsk( + `comment:${comment.id}`, + { + prompt: "", + reviewComments: [ + { + id: comment.id, + sectionId: `pull-request:${reference.number}`, + sectionTitle: `PR #${reference.number} review`, + filePath: comment.path, + startIndex: (start?.line ?? anchor.line) - 1, + endIndex: anchor.line - 1, + rangeLabel: `${start ? `L${start.line} to ` : ""}L${anchor.line}${anchor.side === "left" ? " (before)" : ""}`, + text: comment.body, + diff: "", + }, + ], + }, + { keepGuide: true }, + ); + }; + const startFixFindings = () => { if (!detail) return; void startHandoff( @@ -1318,6 +1389,34 @@ export function PullRequestDetailPanel({ !detail.isDraft && !conflicting && allowedMergeMethods.length > 0; + const canAdminOverride = + canMergeSinglePullRequest && + detail?.viewerPermissions.adminMerge === true && + can("merge") && + canWriteSourceControl && + !detail.isDraft && + !conflicting; + const renderMergeControl = (autoMerge: boolean) => + detail ? ( + + perform( + autoMerge && !adminOverride ? "enable-auto-merge" : "merge", + selectedMergeMethod, + undefined, + adminOverride, + ) + } + /> + ) : null; const showsMergeMethods = detail?.state === "open" && can("merge") && @@ -1352,13 +1451,6 @@ export function PullRequestDetailPanel({ : detail ? summarizePullRequestChecks(detail.checks) : null; - const approvalCount = - detail && !detail.commentsTruncated - ? latestPullRequestReviewOutcomes(detail.comments, detail.commits).filter( - (entry) => entry.outcome === "approved" && !entry.stale, - ).length - : 0; - const checkoutControl = context === "page" ? ( ) : undefined @@ -1409,7 +1502,10 @@ export function PullRequestDetailPanel({ } return ( -
+
{threadPickerOpen && detail ? ( ) : null} + {/* Keep checkout beside the menu so host actions arriving on its left cannot + move a different action under the reader's pointer. */} + {showsMergeNow ? renderMergeControl(false) : null} {checkoutControl} ) - ) : tab === "timeline" ? ( -
- - - - {activityError - ? "-" - : activityPending - ? "…" - : detail.commentCount.toLocaleString()} - - - - {activityError - ? "-" - : activityPending - ? "…" - : detail.commits.length.toLocaleString()} - - {approvalCount > 0 ? ( - - - {approvalCount.toLocaleString()} - - {approvalCount === 1 ? "approval" : "approvals"} - - - ) : null} - - -
) : null} +
+
+ + + +
) : null}
@@ -1912,7 +1942,9 @@ export function PullRequestDetailPanel({ environmentId={environmentId} reference={reference} active={tab === "guide"} + viewControlsTarget={tab === "guide" ? viewControlsTarget : null} title={detail.title} + detail={detail} workspaceRoot={detail.workspaceRoot} canComment={ detail.capabilities.review.inlineComment && detail.viewerPermissions.comment @@ -1932,13 +1964,36 @@ export function PullRequestDetailPanel({ } onOpenFile={openFileInCode} onTourShown={onGuideShown} + renderFallback={(status) => ( + } + > + + addSelectionToAgent(input, { keepGuide: true }) + } + environmentId={environmentId} + reference={reference} + detail={detail} + selectedCommitOid={null} + onSelectedCommitChange={selectCodeCommit} + onRefresh={refreshDetail} + refreshToken={refreshToken} + backgroundRefreshToken={turnRefresh ?? 0} + /> + + )} />
) : null} {mountedTabs.has("timeline") ? (
{activityPending ? ( - + ) : activityError ? (
diff --git a/apps/web/src/components/pullRequest/PullRequestDiffUnavailableState.tsx b/apps/web/src/components/pullRequest/PullRequestDiffUnavailableState.tsx deleted file mode 100644 index f40d0599e2c52..0000000000000 --- a/apps/web/src/components/pullRequest/PullRequestDiffUnavailableState.tsx +++ /dev/null @@ -1,62 +0,0 @@ -import type { SourceControlProviderKind } from "@t3tools/contracts"; -import { ExternalLinkIcon, TriangleAlertIcon } from "lucide-react"; - -import { getSourceControlPresentationForKind } from "~/sourceControlPresentation"; - -import { Button } from "../ui/button"; -import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "../ui/empty"; -import { RefreshIcon } from "../ui/refresh-icon"; -import { describePullRequestDiffError } from "./pullRequestDiffError"; - -export function PullRequestDiffUnavailableState({ - error, - provider, - url, - onRetry, -}: { - error: string; - provider: SourceControlProviderKind; - url: string; - onRetry: () => void; -}) { - const { providerName, terminology } = getSourceControlPresentationForKind(provider); - const { title, description } = describePullRequestDiffError( - error, - providerName, - terminology.singular, - ); - - return ( - -
- -
- - {title} - {description} - -
- - -
-
- - Technical details - -
-          {error}
-        
-
-
- ); -} diff --git a/apps/web/src/components/pullRequest/PullRequestGhosts.tsx b/apps/web/src/components/pullRequest/PullRequestGhosts.tsx index d4ef9056cf351..a4ee4118a3163 100644 --- a/apps/web/src/components/pullRequest/PullRequestGhosts.tsx +++ b/apps/web/src/components/pullRequest/PullRequestGhosts.tsx @@ -387,26 +387,7 @@ export function PullRequestPeopleGhost({ rows = 4 }: { rows?: number }) { ); } -export function PullRequestTimelineGhost({ rows = 6 }: { rows?: number }) { - return ( -
-
- {Array.from({ length: rows }, (_, index) => ( -
- - - -
- ))} -
-
- ); -} - +/** A compact placeholder for the conversation while the core detail is already readable. */ export function PullRequestConversationGhost({ rows = 3, terminology, diff --git a/apps/web/src/components/pullRequest/PullRequestGuideTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestGuideTab.browser.test.tsx index 21fa5afe5e910..8351baa3416ef 100644 --- a/apps/web/src/components/pullRequest/PullRequestGuideTab.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestGuideTab.browser.test.tsx @@ -62,6 +62,20 @@ it("keeps Try again inside a short panel when a failed guide has long diagnostic reference={reference} title="Test pull request" workspaceRoot="/workspace" + renderFallback={(status) =>
{status}
} + viewControlsTarget={null} + detail={{ + reviewThreads: [], + capabilities: { + diff: true, + comment: false, + actions: [], + mergeMethods: [], + search: true, + review: { inlineComment: false, reply: false, resolve: false, verdicts: [] }, + reviewers: { request: false, listCandidates: false }, + }, + }} active canComment={false} rangeComments={false} diff --git a/apps/web/src/components/pullRequest/PullRequestGuideTab.tsx b/apps/web/src/components/pullRequest/PullRequestGuideTab.tsx index e97ef597acb57..07d579fb1fd7d 100644 --- a/apps/web/src/components/pullRequest/PullRequestGuideTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestGuideTab.tsx @@ -1,16 +1,25 @@ -import type { EnvironmentId, PullRequestRef, PullRequestReviewGuideStop } from "@t3tools/contracts"; -import { ScrollTextIcon, TriangleAlertIcon } from "lucide-react"; -import { useEffect, useEffectEvent } from "react"; +import type { + EnvironmentId, + PullRequestDetailView, + PullRequestRef, + PullRequestReviewGuideStop, +} from "@t3tools/contracts"; +import { ScrollTextIcon, SparklesIcon, TriangleAlertIcon } from "lucide-react"; +import { useEffect, useEffectEvent, useRef, type ReactNode } from "react"; import type { ReviewCommentContext } from "~/reviewCommentContext"; +import { observeVisibleAnimation } from "~/lib/visibleAnimation"; import { Alert, AlertAction, AlertDescription } from "../ui/alert"; import { Button } from "../ui/button"; import { Spinner } from "../ui/spinner"; import type { ExcerptCommenting } from "./guide/GuideExcerpt"; +import { PullRequestAttachments } from "./PullRequestAttachments"; +import { guideRunKey } from "./guide/guideRunStore"; import { GuideProseContext } from "./guide/GuideProse"; import { GuideTour } from "./guide/GuideTour"; import { useReviewGuideWriter } from "./guide/useReviewGuideWriter"; +import { usePendingReviewCommentActions } from "./usePendingReviewCommentActions"; import { nextPendingReviewCommentId, pullRequestReviewKey, @@ -23,6 +32,7 @@ export function PullRequestGuideTab({ environmentId, reference, title, + detail, workspaceRoot, active, canComment, @@ -33,10 +43,17 @@ export function PullRequestGuideTab({ onFinishReview, onOpenFile, onTourShown, + renderFallback, + viewControlsTarget, }: { + /** The ordinary diff reader keeps the whole change available until the guide arrives. */ + renderFallback: (status: ReactNode) => ReactNode; + viewControlsTarget: HTMLElement | null; environmentId: EnvironmentId; reference: PullRequestRef; title: string | null; + detail: Pick; + /** The checkout the guide's prose renders against, as the description does. */ workspaceRoot: string; active: boolean; canComment: boolean; @@ -55,30 +72,52 @@ export function PullRequestGuideTab({ reference, title, }); + const runKey = guideRunKey(environmentId, reference); const reviewKey = pullRequestReviewKey(reference); - const pending = usePendingReviewComments(reference); - const addComment = usePullRequestReviewStore((store) => store.addComment); + const pending = usePendingReviewComments(reference, detail.reviewThreads); + const { add: addComment } = usePendingReviewCommentActions(environmentId, reference); const removeComment = usePullRequestReviewStore((store) => store.removeComment); const commenting: ExcerptCommenting | null = - !canComment && onAskAboutLines === null + !canComment && onAskAboutLines === null && !detail.capabilities.review.reply ? null : { canComment, rangeComments, completionScope, + renderAttachments: (onTextChange, onBusyChange, textarea) => ( + + ), pending, + threads: detail.reviewThreads.filter((thread) => + thread.comments.some((comment) => !comment.pendingReviewId), + ), + pendingCommentTarget: { + environmentId, + reference, + canCopyLink: detail.capabilities.review.draftComment === true, + }, onComment: ({ path, oldPath, position, startPosition, body }) => - addComment(reviewKey, { - id: nextPendingReviewCommentId(), - path, - ...(oldPath === null ? {} : { oldPath }), - ...(startPosition === undefined ? {} : { startPosition }), - position, - body, - }), + addComment( + { + id: nextPendingReviewCommentId(), + path, + ...(oldPath === null ? {} : { oldPath }), + ...(startPosition === undefined ? {} : { startPosition }), + position, + body, + }, + detail.capabilities.review.draftComment === true, + ), onRemove: (commentId) => removeComment(reviewKey, commentId), onAskAgent: onAskAboutLines, }; + const guide = data?.guide ?? null; const tourShown = active && guide !== null; const reportTourShown = useEffectEvent(() => onTourShown?.()); @@ -91,6 +130,23 @@ export function PullRequestGuideTab({ const stale = guide !== null && currentHeadSha !== null && currentHeadSha !== guide.headSha; const failure = runState?._tag === "Failed" && runState.headSha === currentHeadSha ? runState.detail : null; + const attemptedGuide = useRef(null); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- starts remote guide generation once the active host query permits it + useEffect(() => { + if ( + !active || + data === null || + data === undefined || + guide !== null || + running || + !canWrite || + failure !== null || + attemptedGuide.current === runKey + ) + return; + attemptedGuide.current = runKey; + void write(); + }, [active, data, guide, running, canWrite, failure, runKey, write]); const writeButton = (label: string, size: "sm" | "xs") => canWrite ? ( + ); + } + return ( + + + } + > + + {pending ? "Working..." : label} + + +
+
+

{methodLabel}

+

+ {autoMerge && !adminOverride ? ( + "Merge automatically once the requirements are met." + ) : ( + <> + Merge this pull request into {baseBranch}. + + )} +

+
+ {canAdminOverride ? ( + + ) : null} +
+ + +
+
+
+
+ ); +} diff --git a/apps/web/src/components/pullRequest/PullRequestReactions.tsx b/apps/web/src/components/pullRequest/PullRequestReactions.tsx index 4e700da696c2f..80545ba89b20b 100644 --- a/apps/web/src/components/pullRequest/PullRequestReactions.tsx +++ b/apps/web/src/components/pullRequest/PullRequestReactions.tsx @@ -22,7 +22,7 @@ import { pullRequestReactionName, pullRequestReactionTooltip, pullRequestReactionsSignature, -} from "@t3tools/client-runtime/pull-request-reactions"; +} from "@t3tools/client-runtime/review-reactions"; const PILL_CLASS = "inline-flex h-6 shrink-0 items-center gap-1 rounded-full border px-2 text-xs outline-none transition-colors focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"; diff --git a/apps/web/src/components/pullRequest/PullRequestResolveThreadButton.tsx b/apps/web/src/components/pullRequest/PullRequestResolveThreadButton.tsx index e7ec576a1cc48..222258b19496f 100644 --- a/apps/web/src/components/pullRequest/PullRequestResolveThreadButton.tsx +++ b/apps/web/src/components/pullRequest/PullRequestResolveThreadButton.tsx @@ -4,7 +4,7 @@ import type { PullRequestRef, PullRequestConversationThread, } from "@t3tools/contracts"; -import { canResolvePullRequestThread } from "@t3tools/client-runtime/pull-request-editing"; +import { canResolvePullRequestThread } from "@t3tools/client-runtime/review-editing"; import { useState } from "react"; import { pullRequestEnvironment } from "~/state/pullRequests"; diff --git a/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx b/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx index 1b95a1a563aab..06571c57fd04f 100644 --- a/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx +++ b/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx @@ -1,3 +1,17 @@ +import { pullRequestEnvironment } from "~/state/pullRequests"; +import { useEnvironmentQuery } from "~/state/query"; +import { useReviewThreadActions } from "./useReviewThreadActions"; +import type { PullRequestDetail } from "@t3tools/contracts"; +import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import { formatRelativeTimeLabel } from "~/timestampFormat"; +import { reviewLineRangeLabel } from "@t3tools/client-runtime/review-selection"; +import { PullRequestAttachments } from "./PullRequestAttachments"; +import { usePendingReviewCommentActions } from "./usePendingReviewCommentActions"; +import { PullRequestCommentActions } from "./PullRequestCommentActions"; +/** + * Pull-request-specific annotations: conversations already on the host and comments queued for + * the review being written. New comment composition uses the shared diff annotation. + */ import type { EnvironmentId, PullRequestActor, @@ -9,6 +23,11 @@ import type { PullRequestThreadComment, } from "@t3tools/contracts"; import { + ArrowUpIcon, + CheckIcon, + ChevronDownIcon, + ChevronUpIcon, + ClockIcon, HammerIcon, MessageSquareIcon, MessageSquarePlusIcon, @@ -16,16 +35,17 @@ import { CircleCheckIcon, CircleIcon, } from "lucide-react"; -import { type ReactNode, useRef, useState } from "react"; -import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import { type ReactNode, useEffect, useRef, useState } from "react"; +import { Circle, CircleCheck } from "lucide-react"; -import { RelativeTime } from "~/components/RelativeTime"; import { cn } from "~/lib/utils"; import { SpeechTextField, TextFieldSpeechControls } from "~/speech/useTextFieldSpeech"; import { Button } from "../ui/button"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { PullRequestEditButton } from "./PullRequestEditButton"; +import { Badge } from "../ui/badge"; +import { ReviewIcon as MorphIcon } from "~/components/ReviewIcon"; import { isCommentSubmitShortcut } from "../diffs/commentSubmitShortcut"; import { editPullRequestThreadComment, @@ -36,7 +56,7 @@ import { PullRequestActorAvatar, PullRequestActorLabel } from "./pullRequestPres import { PullRequestMarkdown } from "./PullRequestMarkdown"; import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor"; import { PullRequestReactionBar } from "./PullRequestReactions"; -import type { PendingReviewComment } from "./pullRequestReviewStore"; +import { usePendingReviewComments, type PendingReviewComment } from "./pullRequestReviewStore"; import { PullRequestMarkdownTextarea, type PullRequestCompletionScope, @@ -87,11 +107,28 @@ export function getReviewPositionAnchor(position: PullRequestReviewPosition): { export function PendingReviewCommentCard({ comment, - onRemove, + environmentId, + reference, + canCopyLink, + onAddToComposer, }: { comment: PendingReviewComment; - onRemove: () => void; + environmentId: EnvironmentId; + reference: PullRequestRef; + canCopyLink: boolean; + onAddToComposer?: (() => void) | undefined; }) { + const [replyCommentId, setReplyCommentId] = useState(null); + const { busy, canSave, canDiscard, saveDraft, copyLink, discard } = + usePendingReviewCommentActions(environmentId, reference); + if (replyCommentId) + return ( + + ); return (
event.stopPropagation()} >
- - Pending. Sent when you submit the review + + + Pending + + + {comment.hostedComment + ? "Saved on GitHub · private until submitted" + : canCopyLink + ? busy + ? "Saving to GitHub…" + : "Only saved in T3" + : "Sent when you submit the review"} + + {canCopyLink && canSave && !comment.hostedComment && !busy ? ( + + ) : null} +
+ copyLink(comment) : undefined} + disabled={busy} + onAddToComposer={onAddToComposer} + /> + +
+
+

{comment.body}

+ {canCopyLink && canSave ? ( -
-

{comment.body}

+ ) : null}
); } @@ -184,7 +261,7 @@ export function ReviewThreadCard({ canReact, environmentId, reference, - completionScope, + completionScope = null, pending, fixPending, fixLabel = "Fix in a thread", @@ -197,6 +274,8 @@ export function ReviewThreadCard({ onToggleResolved, onReacted, hidden, + onAddToComposer, + revealRequest, }: { thread: PullRequestReviewThread; workspaceRoot: string; @@ -205,7 +284,7 @@ export function ReviewThreadCard({ canReact: boolean; environmentId: EnvironmentId; reference: PullRequestRef; - completionScope: PullRequestCompletionScope | null; + completionScope?: PullRequestCompletionScope | null; pending: boolean; fixPending?: boolean; fixLabel?: string; @@ -221,12 +300,25 @@ export function ReviewThreadCard({ onEditComment: (commentId: string, body: string) => Promise; onToggleResolved: () => void; onReacted: () => void; - /** Set on a diff line. Hidden draws nothing but stays mounted, so an unsent reply survives. */ hidden?: boolean; + revealRequest?: number | undefined; + onAddToComposer?: ((comment: PullRequestThreadComment) => void) | undefined; }) { - const [expanded, setExpanded] = useState(hidden !== undefined || !thread.isResolved); + // A resolved thread is finished work, so it opens collapsed and stays one line until asked for. + const pendingActions = usePendingReviewCommentActions(environmentId, reference); + const [expanded, setExpanded] = useState( + hidden !== undefined || revealRequest !== undefined || !thread.isResolved, + ); + const [lastRevealRequest, setLastRevealRequest] = useState(revealRequest); + if (lastRevealRequest !== revealRequest) { + setLastRevealRequest(revealRequest); + if (revealRequest !== undefined) setExpanded(true); + } + const [uploading, setUploading] = useState(false); + const replyInputRef = useRef(null); const [replying, setReplying] = useState(false); const [reply, setReply] = useState(""); + const [lastResolved, setLastResolved] = useState(thread.isResolved); const [editingId, setEditingId] = useState(null); const [savingEdit, setSavingEdit] = useState(false); const sendingRef = useRef(false); @@ -236,10 +328,39 @@ export function ReviewThreadCard({ >(null); const [loadingMore, setLoadingMore] = useState(false); const currentPage = loadedPage?.threadId === thread.id ? loadedPage : null; - const comments = mergePullRequestThreadComments(thread.comments, currentPage?.comments ?? []); + const receivedComments = mergePullRequestThreadComments( + thread.comments, + currentPage?.comments ?? [], + ); + const pendingComments = usePendingReviewComments(reference, [ + { ...thread, comments: receivedComments }, + ]); + const pendingById = new Map( + pendingComments.flatMap((comment) => + comment.hostedComment ? [[comment.hostedComment.commentId, comment] as const] : [], + ), + ); + const comments = receivedComments.filter( + (comment) => !comment.pendingReviewId || pendingById.has(comment.id), + ); const nextCommentsCursor = currentPage === null ? (thread.nextCommentsCursor ?? null) : currentPage.nextCursor; const commentCount = thread.commentCount ?? comments.length; + const authors = [ + ...new Set(comments.map((comment) => comment.author?.name ?? comment.author?.login ?? "ghost")), + ]; + const authorLabel = + authors.length > 2 + ? `${authors.slice(0, 2).join(", ")} and ${authors.length - 2} more` + : authors.join(" and "); + const collapsedLabel = `${commentCount} resolved ${commentCount === 1 ? "comment" : "comments"}${authorLabel ? ` from ${authorLabel}` : ""}`; + + // Follow resolution changes from this client or GitHub while allowing a finished thread to + // be opened manually. Failed resolve requests leave the current view and draft intact. + if (lastResolved !== thread.isResolved) { + setLastResolved(thread.isResolved); + setExpanded(!thread.isResolved); + } const saveEdit = async (commentId: string, body: string) => { if (savingEdit) return; @@ -261,7 +382,7 @@ export function ReviewThreadCard({ const send = async (text: string) => { const trimmed = text.trim(); - if (trimmed.length === 0 || pending || sendingRef.current) return; + if (trimmed.length === 0 || pending || uploading || sendingRef.current) return; sendingRef.current = true; const result = await settlePromise(() => onReply(trimmed)); sendingRef.current = false; @@ -277,7 +398,6 @@ export function ReviewThreadCard({ : previous, ); setReply(""); - setReplying(false); }; const loadMore = async () => { if (nextCommentsCursor === null || loadingMore) return; @@ -359,23 +479,69 @@ export function ReviewThreadCard({ {expanded ? ( <> -
- {comments.map((comment) => ( -
+
+ {comments.map((comment, index) => ( +
- - - - + {formatRelativeTimeLabel(comment.createdAt)} + {comment.pendingReviewId ? ( + + + Pending + + ) : null} + {index === 0 && thread.isOutdated ? ( + + Outdated + + ) : null} +
+ + {index === 0 && canResolve && !thread.isResolved && !comment.pendingReviewId ? ( + + ) : null} + {comment.pendingReviewId && + pendingById.has(comment.id) && + pendingActions.canDiscard ? ( + + ) : null} + setEditingId(comment.id) : undefined} + onAddToComposer={onAddToComposer ? () => onAddToComposer(comment) : undefined} + resolution={ + canResolve && !thread.comments.some((entry) => entry.pendingReviewId) + ? { resolved: thread.isResolved, pending, onToggle: onToggleResolved } + : undefined + } + /> +
{editingId === comment.id ? ( setEditingId(null)} /> ) : ( -
+
- {canEditComment(comment) ? ( - setEditingId(comment.id)} - /> - ) : null}
)}
@@ -430,10 +590,10 @@ export function ReviewThreadCard({ text={reply} textareaRef={replyRef} onTextChange={setReply} - disabled={pending} + disabled={pending || uploading} > {(speech) => ( -
+
+
- + @@ -474,7 +642,14 @@ export function ReviewThreadCard({ )} ) : ( - ) @@ -484,3 +659,84 @@ export function ReviewThreadCard({
); } + +/** Shared cached queries keep a Guide or pending-comment conversation live after a reply. */ +export function HostedReviewThreadCard({ + environmentId, + reference, + threadId, + commentId, +}: { + environmentId: EnvironmentId; + reference: PullRequestRef; + threadId?: string | undefined; + commentId?: string | undefined; +}) { + const target = { environmentId, input: reference }; + const detail = useEnvironmentQuery(pullRequestEnvironment.detail(target)); + const activity = useEnvironmentQuery(pullRequestEnvironment.activity(target)); + const thread = activity.data?.reviewThreads.find((entry) => + threadId ? entry.id === threadId : entry.comments.some((comment) => comment.id === commentId), + ); + const refreshActivity = activity.refresh; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Re-read hosted activity when opening a newly saved comment's conversation. + useEffect(() => { + if (commentId) refreshActivity(); + }, [commentId, refreshActivity]); + if (!thread || !detail.data) + return ( +
+ {activity.error ?? + detail.error ?? + (activity.isPending || detail.isPending + ? "Loading conversation…" + : "This conversation is not available yet. Refresh to check again.")} + +
+ ); + return ( + + ); +} + +function HostedReviewThreadContent({ + environmentId, + reference, + detail, + thread, + onRefresh, +}: { + environmentId: EnvironmentId; + reference: PullRequestRef; + detail: PullRequestDetail; + thread: PullRequestReviewThread; + onRefresh: () => void; +}) { + const actions = useReviewThreadActions(environmentId, reference, detail, onRefresh); + return ( + + ); +} diff --git a/apps/web/src/components/pullRequest/PullRequestReviewForm.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestReviewForm.browser.test.tsx index eae69143d31ea..353090970f8f8 100644 --- a/apps/web/src/components/pullRequest/PullRequestReviewForm.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestReviewForm.browser.test.tsx @@ -35,6 +35,7 @@ it("submits only the line comments still in the draft when dictation finishes", await using screen = await render( ; verdicts: ReadonlyArray; requestChangesSummaryRequired: boolean; textareaRef: RefObject; @@ -76,9 +91,16 @@ export function PullRequestReviewForm({ onPendingChange: (pending: boolean) => void; onSubmitted: () => void; }) { + const { busy: draftBusy } = usePendingReviewCommentActions(environmentId, reference); + const [uploading, setUploading] = useState(false); const [requestedVerdict, setRequestedVerdict] = useState("comment"); - const comments = usePendingReviewComments(reference); + const comments = usePendingReviewComments(reference, reviewThreads); const reviewKey = pullRequestReviewKey(reference); + const pendingReviewId = comments.find((comment) => comment.hostedComment)?.hostedComment + ?.reviewId; + // The panel stays mounted while the selected pull request changes. Keeping summaries beside + // the keyed line-comment drafts makes the selected pull request's body correct on the first + // render, before an effect could reset state left behind by the previous one. const body = usePullRequestReviewStore((store) => store.summaries[reviewKey] ?? ""); const removeComments = usePullRequestReviewStore((store) => store.removeComments); const setSummary = usePullRequestReviewStore((store) => store.setSummary); @@ -107,7 +129,13 @@ export function PullRequestReviewForm({ const submit = async (verdict: (typeof VERDICTS)[number], text: string) => { const submittedComments = usePullRequestReviewStore.getState().drafts[reviewKey] ?? []; - if (pending || !canSubmit(verdict.value, text, submittedComments.length)) return; + if ( + pending || + uploading || + draftBusy || + !canSubmit(verdict.value, text, submittedComments.length) + ) + return; const submittedBody = text; onPendingChange(true); const result = await submitReview({ @@ -115,6 +143,7 @@ export function PullRequestReviewForm({ input: { ...reference, verdict: verdict.value, + ...(pendingReviewId ? { pendingReviewId } : {}), body: submittedBody, comments: submittedComments, }, @@ -135,6 +164,9 @@ export function PullRequestReviewForm({ removeComments( reviewKey, submittedComments.map((comment) => comment.id), + submittedComments.flatMap((comment) => + comment.hostedComment ? [comment.hostedComment.commentId] : [], + ), ); clearSummary(reviewKey, submittedBody); toastManager.add({ type: "success", title: verdict.sent(term) }); @@ -145,7 +177,10 @@ export function PullRequestReviewForm({ const canSubmit = (verdict: PullRequestReviewVerdict, summary: string, commentCount: number) => verdict === "request-changes" && requestChangesSummaryRequired ? summary.trim().length > 0 - : verdict === "approve" || summary.trim().length > 0 || commentCount > 0; + : verdict === "approve" || + summary.trim().length > 0 || + commentCount > 0 || + pendingReviewId !== undefined; const placeholder = selectedVerdict === undefined || canSubmit(selectedVerdict.value, "", comments.length) ? "Summarize your review (optional)" @@ -158,6 +193,7 @@ export function PullRequestReviewForm({ + setSummary(reviewKey, text)} + />
{offered.length > 1 ? ( ; } -export { InputGroup, InputGroupAddon, InputGroupInput }; +function InputGroupTextarea(props: TextareaProps) { + return