From 62e150c29ad6ebf0f39927c9bbded38f6a45aea4 Mon Sep 17 00:00:00 2001 From: Brandon Oxendine Date: Thu, 6 Aug 2026 17:54:14 +0200 Subject: [PATCH] Rebuild the patch page, review UI, and activity timeline --- .../radicle-tauri/src/commands/cob/patch.rs | 33 +- .../radicle-types/bindings/cob/patch/Patch.ts | 3 + .../bindings/cob/patch/Reviewer.ts | 24 + .../src/domain/patch/models/patch.rs | 73 +- .../radicle-types/src/domain/patch/traits.rs | 6 +- crates/radicle-types/src/error.rs | 5 + crates/radicle-types/src/traits/patch.rs | 60 +- crates/test-http-api/src/api.rs | 45 +- public/index.css | 15 + src/components/AssigneeInput.svelte | 4 +- src/components/Button.svelte | 12 +- src/components/Changes.svelte | 775 +++++-- src/components/Changeset.svelte | 300 ++- src/components/CheckoutPatchButton.svelte | 2 +- src/components/CobCommitTeaser.svelte | 160 +- src/components/Comment.svelte | 58 +- src/components/CommentToggleInput.svelte | 31 +- src/components/CommitActivityItem.svelte | 100 + src/components/CommitsContainer.svelte | 56 +- src/components/Diff.svelte | 615 ++++++ src/components/DiffFileHeader.svelte | 6 +- src/components/DiffRow.svelte | 524 ----- src/components/Discussion.svelte | 296 ++- src/components/DraftReviewBar.svelte | 839 ++++++++ src/components/ExtendedTextarea.svelte | 266 ++- src/components/FileBlock.svelte | 139 +- src/components/FileDiff.svelte | 266 +++ src/components/Icon.svelte | 4 + src/components/Id.svelte | 42 +- src/components/IssueActivityItem.svelte | 199 ++ src/components/IssueStateButton.svelte | 2 +- src/components/IssueTeaser.svelte | 4 +- src/components/IssueTimeline.svelte | 244 --- src/components/Label.svelte | 2 +- src/components/LabelInput.svelte | 16 +- src/components/NodeId.svelte | 14 +- src/components/NotificationTeaser.svelte | 2 +- src/components/PatchActivityItem.svelte | 725 +++++++ src/components/PatchMetadata.svelte | 426 +++- src/components/PatchStateButton.svelte | 187 +- src/components/PatchTeaser.svelte | 53 +- src/components/PatchTimeline.svelte | 326 --- src/components/Path.svelte | 3 + src/components/ReactionSelector.svelte | 4 +- src/components/Review.svelte | 471 ----- src/components/ReviewCodeThread.svelte | 303 +++ src/components/ReviewItem.svelte | 118 ++ src/components/ReviewPage.svelte | 792 +++++++ src/components/ReviewProgressChip.svelte | 71 + src/components/ReviewSummary.svelte | 119 ++ src/components/Revision.svelte | 1875 +++++++++++++++-- src/components/RevisionBadges.svelte | 30 - src/components/RevisionReviews.svelte | 121 -- src/components/Revisions.svelte | 104 - src/components/ShareButton.svelte | 14 +- src/components/Thread.svelte | 70 +- src/components/VerdictBadge.svelte | 61 - src/components/VerdictButton.svelte | 98 - src/components/VirtualList.svelte | 9 + src/lib/codeCommentActions.ts | 150 ++ src/lib/commentSources.ts | 51 + src/lib/diffComments.ts | 248 --- src/lib/diffRows.ts | 108 - src/lib/draftReviewStorage.ts | 91 +- src/lib/ignoredFiles.ts | 26 + src/lib/patchActivityContext.ts | 2 +- src/lib/patchContributions.ts | 30 + src/lib/reviewSummary.ts | 140 ++ src/lib/revisionList.ts | 48 + src/lib/revisionListSettings.ts | 37 + src/lib/router/definitions.ts | 4 +- src/lib/utils.ts | 96 +- src/views/repo/Issue.svelte | 105 +- src/views/repo/Patch.svelte | 1609 ++++++++++---- src/views/repo/RepoCommit.svelte | 20 +- src/views/repo/RepoHome.svelte | 7 +- src/views/repo/router.ts | 111 +- tests/unit/reviewSummary.test.ts | 114 + 78 files changed, 10468 insertions(+), 3751 deletions(-) create mode 100644 crates/radicle-types/bindings/cob/patch/Reviewer.ts create mode 100644 src/components/CommitActivityItem.svelte create mode 100644 src/components/Diff.svelte delete mode 100644 src/components/DiffRow.svelte create mode 100644 src/components/DraftReviewBar.svelte create mode 100644 src/components/FileDiff.svelte create mode 100644 src/components/IssueActivityItem.svelte delete mode 100644 src/components/IssueTimeline.svelte create mode 100644 src/components/PatchActivityItem.svelte delete mode 100644 src/components/PatchTimeline.svelte delete mode 100644 src/components/Review.svelte create mode 100644 src/components/ReviewCodeThread.svelte create mode 100644 src/components/ReviewItem.svelte create mode 100644 src/components/ReviewPage.svelte create mode 100644 src/components/ReviewProgressChip.svelte create mode 100644 src/components/ReviewSummary.svelte delete mode 100644 src/components/RevisionBadges.svelte delete mode 100644 src/components/RevisionReviews.svelte delete mode 100644 src/components/Revisions.svelte delete mode 100644 src/components/VerdictBadge.svelte delete mode 100644 src/components/VerdictButton.svelte create mode 100644 src/lib/codeCommentActions.ts create mode 100644 src/lib/commentSources.ts delete mode 100644 src/lib/diffComments.ts delete mode 100644 src/lib/diffRows.ts create mode 100644 src/lib/ignoredFiles.ts create mode 100644 src/lib/patchContributions.ts create mode 100644 src/lib/reviewSummary.ts create mode 100644 src/lib/revisionList.ts create mode 100644 src/lib/revisionListSettings.ts create mode 100644 tests/unit/reviewSummary.test.ts diff --git a/crates/radicle-tauri/src/commands/cob/patch.rs b/crates/radicle-tauri/src/commands/cob/patch.rs index 43f366903..399930325 100644 --- a/crates/radicle-tauri/src/commands/cob/patch.rs +++ b/crates/radicle-tauri/src/commands/cob/patch.rs @@ -1,8 +1,7 @@ use std::ops::ControlFlow; -use radicle::patch::cache::Patches as _; use radicle::patch::{ReviewId, TYPENAME}; -use radicle::storage::ReadStorage; +use radicle::storage::{ReadRepository as _, ReadStorage}; use radicle::{cob, git, identity}; use radicle_types as types; @@ -31,8 +30,9 @@ pub async fn list_patches( ) -> Result>, Error> { let profile = ctx.profile(); let aliases = profile.aliases(); + let delegates = Vec::from(profile.storage.repository(rid)?.delegates()?); - Ok(sqlite_service.list_paginated(rid, status, skip, take, &aliases)?) + Ok(sqlite_service.list_paginated(rid, status, skip, take, &delegates, &aliases)?) } #[tauri::command] @@ -90,32 +90,7 @@ pub fn create_patch_review( ctx: tauri::State, args: models::patch::CreateReviewArgs, ) -> Result { - let repo = ctx.profile.storage.repository(args.rid)?; - let signer = ctx.profile.signer()?; - let mut patches = ctx.profile.patches_mut(&repo, &signer)?; - let patch_id = match patches.find_by_revision(&args.revision)? { - Some(found) => found.id, - None => return Err(cob::patch::Error::RevisionNotFound(args.revision).into()), - }; - let mut patch = patches.get_mut(&patch_id)?; - let review_id = patch.review( - args.revision, - args.verdict.map(Into::into), - args.summary, - args.labels, - )?; - - for comment in args.comments { - patch.review_comment( - review_id, - comment.body, - comment.location.map(Into::into), - None, - vec![], - )?; - } - - Ok(review_id) + ctx.create_patch_review(args) } #[tauri::command] diff --git a/crates/radicle-types/bindings/cob/patch/Patch.ts b/crates/radicle-types/bindings/cob/patch/Patch.ts index 0b98fc826..42e7fc818 100644 --- a/crates/radicle-types/bindings/cob/patch/Patch.ts +++ b/crates/radicle-types/bindings/cob/patch/Patch.ts @@ -1,5 +1,6 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { Author } from "../Author"; +import type { Reviewer } from "./Reviewer"; import type { State } from "./State"; export type Patch = { @@ -13,4 +14,6 @@ export type Patch = { labels: Array; timestamp: number; revisionIds: Array; + commentCount: number; + reviewers: Array; }; diff --git a/crates/radicle-types/bindings/cob/patch/Reviewer.ts b/crates/radicle-types/bindings/cob/patch/Reviewer.ts new file mode 100644 index 000000000..ed3be7699 --- /dev/null +++ b/crates/radicle-types/bindings/cob/patch/Reviewer.ts @@ -0,0 +1,24 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { Author } from "../Author"; +import type { Verdict } from "./Verdict"; + +/** + * One published review, flattened so the patch list can summarise a patch + * without loading its revisions. + * + * There is an entry per review, not per reviewer: the protocol allows one + * review per author per revision, so the same person appears once for each + * revision they reviewed. `revision_number` is the reviewed revision's 1-based + * position in the patch timeline, which together with `revision_ids.len()` + * tells the UI whether a review still covers the current head. + */ +export type Reviewer = { + author: Author; + verdict?: Verdict; + revisionNumber: number; + /** + * Whether the reviewer is a delegate, so their verdict can be told apart + * from a non-delegate's at a glance. + */ + delegate: boolean; +}; diff --git a/crates/radicle-types/src/domain/patch/models/patch.rs b/crates/radicle-types/src/domain/patch/models/patch.rs index 3ad1fab85..df169de64 100644 --- a/crates/radicle-types/src/domain/patch/models/patch.rs +++ b/crates/radicle-types/src/domain/patch/models/patch.rs @@ -17,6 +17,30 @@ use crate::cobs; use crate::cobs::Author; use crate::cobs::FromRadicleAction; +/// One published review, flattened so the patch list can summarise a patch +/// without loading its revisions. +/// +/// There is an entry per review, not per reviewer: the protocol allows one +/// review per author per revision, so the same person appears once for each +/// revision they reviewed. `revision_number` is the reviewed revision's 1-based +/// position in the patch timeline, which together with `revision_ids.len()` +/// tells the UI whether a review still covers the current head. +#[derive(Debug, TS, Serialize)] +#[ts(export)] +#[ts(export_to = "cob/patch/")] +#[serde(rename_all = "camelCase")] +pub struct Reviewer { + author: cobs::Author, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + verdict: Option, + #[ts(type = "number")] + revision_number: usize, + /// Whether the reviewer is a delegate, so their verdict can be told apart + /// from a non-delegate's at a glance. + delegate: bool, +} + #[derive(Debug, TS, Serialize)] #[ts(export)] #[ts(export_to = "cob/patch/")] @@ -37,6 +61,9 @@ pub struct Patch { timestamp: cob::Timestamp, #[ts(as = "Vec")] revision_ids: Vec, + #[ts(type = "number")] + comment_count: usize, + reviewers: Vec, } #[derive(Debug, thiserror::Error)] @@ -50,7 +77,34 @@ pub enum ListPatchesError { } impl Patch { - pub fn new(id: patch::PatchId, patch: &patch::Patch, aliases: &impl AliasStore) -> Self { + pub fn new( + id: patch::PatchId, + patch: &patch::Patch, + delegates: &[radicle::identity::Did], + aliases: &impl AliasStore, + ) -> Self { + // Every review on every revision, so the patch list can render the same + // summary the patch page does. `revision_number` is what lets the UI + // tell a review of the current head from one left behind by a later + // push — see the outdated handling in `reviewSummary`. It follows + // `patch.revisions()`, the timeline order `revision_ids` also uses. + let reviewers = patch + .revisions() + .enumerate() + .flat_map(|(index, (_, revision))| { + revision.reviews().map(move |(key, review)| { + let did = radicle::identity::Did::from(*key); + + Reviewer { + author: cobs::Author::new(&did, aliases), + verdict: review.verdict().map(Into::into), + revision_number: index + 1, + delegate: delegates.contains(&did), + } + }) + }) + .collect::>(); + Self { id: id.to_string(), author: cobs::Author::new(patch.author().id(), aliases), @@ -65,6 +119,23 @@ impl Patch { labels: patch.labels().cloned().collect::>(), timestamp: patch.timestamp(), revision_ids: patch.revisions().map(|(id, _)| id).collect(), + // Unlike an issue, a revision's description is a field of its own + // rather than the root of its discussion thread, so every comment + // in the thread counts. Review summaries are likewise separate from + // `Review::comments`, which holds only code comments. + comment_count: patch + .revisions() + .map(|(_, revision)| { + let discussion_comments = revision.discussion().comments().count(); + let review_comments = revision + .reviews() + .map(|(_, review)| review.comments().count()) + .sum::(); + + discussion_comments + review_comments + }) + .sum(), + reviewers, } } diff --git a/crates/radicle-types/src/domain/patch/traits.rs b/crates/radicle-types/src/domain/patch/traits.rs index 5a1f03677..803577d80 100644 --- a/crates/radicle-types/src/domain/patch/traits.rs +++ b/crates/radicle-types/src/domain/patch/traits.rs @@ -52,6 +52,7 @@ pub trait PatchService { status: Option, skip: Option, take: Option, + delegates: &[identity::Did], aliases: &impl AliasStore, ) -> Result>, models::patch::ListPatchesError> { @@ -59,8 +60,9 @@ pub trait PatchService { None => Box::new(self.list(rid)?), Some(status) => Box::new(self.list_by_status(rid, status.into())?), }; - let summary = - |(id, patch): (PatchId, Patch)| models::patch::Patch::new(id, &patch, aliases); + let summary = |(id, patch): (PatchId, Patch)| { + models::patch::Patch::new(id, &patch, delegates, aliases) + }; match take { None => Ok(cobs::PaginatedQuery { diff --git a/crates/radicle-types/src/error.rs b/crates/radicle-types/src/error.rs index 6d035a59d..df882787d 100644 --- a/crates/radicle-types/src/error.rs +++ b/crates/radicle-types/src/error.rs @@ -35,6 +35,10 @@ pub enum Error { #[error("not able to save embed")] SaveEmbedError, + /// A second review of the same revision by the same author. + #[error("you have already reviewed this revision")] + ReviewExists, + /// Init Error error. #[error(transparent)] InitError(#[from] radicle::rad::InitError), @@ -205,6 +209,7 @@ impl Error { "AliasError.InvalidAlias" } Error::FileTooLarge(_) => "PayloadError.TooLarge", + Error::ReviewExists => "PatchError.ReviewExists", _ => "UnknownError", } } diff --git a/crates/radicle-types/src/traits/patch.rs b/crates/radicle-types/src/traits/patch.rs index 34a7930a7..dfc61dced 100644 --- a/crates/radicle-types/src/traits/patch.rs +++ b/crates/radicle-types/src/traits/patch.rs @@ -3,7 +3,7 @@ use std::collections::BTreeSet; use radicle::cob::Title; use radicle::node::Handle; use radicle::patch::cache::Patches as _; -use radicle::storage::ReadStorage; +use radicle::storage::{ReadRepository as _, ReadStorage}; use radicle::{Node, cob, git, identity}; use crate::cobs; @@ -22,7 +22,9 @@ pub trait Patches: Profile { let patches = profile.patches(&repo)?; let patch = patches.get(&id.into())?; let aliases = &profile.aliases(); - let patches = patch.map(|patch| models::patch::Patch::new(id.into(), &patch, aliases)); + let delegates = Vec::from(repo.delegates()?); + let patches = + patch.map(|patch| models::patch::Patch::new(id.into(), &patch, &delegates, aliases)); Ok::<_, Error>(patches) } @@ -91,6 +93,51 @@ pub trait Patches: Profile { } pub trait PatchesMut: Profile { + /// Publish a review of a revision, together with its code comments. + fn create_patch_review( + &self, + args: models::patch::CreateReviewArgs, + ) -> Result { + let profile = self.profile(); + let repo = profile.storage.repository(args.rid)?; + let signer = profile.signer()?; + let mut patches = profile.patches_mut(&repo, &signer)?; + let patch_id = match patches.find_by_revision(&args.revision)? { + Some(found) => found.id, + None => return Err(cob::patch::Error::RevisionNotFound(args.revision).into()), + }; + let mut patch = patches.get_mut(&patch_id)?; + // The protocol keeps one review per author per revision: a second + // `Review` action is written to the object and then dropped on apply, + // leaving a review id that resolves to nothing. Publishing through it + // would either fail on the first comment or, for a review with none, + // report success while storing nothing at all. + if patch + .revision(&args.revision) + .is_some_and(|rev| rev.review_by(&profile.public_key).is_some()) + { + return Err(Error::ReviewExists); + } + let review_id = patch.review( + args.revision, + args.verdict.map(Into::into), + args.summary, + args.labels, + )?; + + for comment in args.comments { + patch.review_comment( + review_id, + comment.body, + comment.location.map(Into::into), + None, + vec![], + )?; + } + + Ok(review_id) + } + fn edit_patch( &self, rid: identity::RepoId, @@ -276,6 +323,13 @@ pub trait PatchesMut: Profile { log::error!("Not able to announce changes: {}", e) } - Ok::<_, Error>(models::patch::Patch::new(*patch.id(), &patch, &aliases)) + let delegates = Vec::from(repo.delegates()?); + + Ok::<_, Error>(models::patch::Patch::new( + *patch.id(), + &patch, + &delegates, + &aliases, + )) } } diff --git a/crates/test-http-api/src/api.rs b/crates/test-http-api/src/api.rs index c2b827c07..5e8bfd31f 100644 --- a/crates/test-http-api/src/api.rs +++ b/crates/test-http-api/src/api.rs @@ -12,6 +12,7 @@ use serde::{Deserialize, Serialize}; use tower_http::cors::{self, CorsLayer}; use radicle::node::NodeId; +use radicle::storage::{ReadRepository as _, ReadStorage as _}; use radicle::{git, identity}; use radicle_types as types; use radicle_types::cobs::CobOptions; @@ -111,6 +112,8 @@ pub fn router(ctx: Context) -> Router { .route("/list_patches", post(patches_handler)) .route("/patch_by_id", post(patch_handler)) .route("/revisions_by_patch", post(revision_handler)) + .route("/edit_patch", post(edit_patch_handler)) + .route("/create_patch_review", post(create_patch_review_handler)) .route("/get_embed", post(get_embeds_handler)) .route("/save_embed_by_path", post(save_embed_handler)) .route("/save_embed_by_clipboard", post(save_embed_handler)) @@ -641,9 +644,10 @@ async fn patches_handler( }): Json, ) -> impl IntoResponse { let aliases = ctx.profile.aliases(); + let delegates = Vec::from(ctx.profile.storage.repository(rid)?.delegates()?); let page = ctx .patches - .list_paginated(rid, status, skip, take, &aliases)?; + .list_paginated(rid, status, skip, take, &delegates, &aliases)?; Ok::<_, Error>(Json(page)) } @@ -672,6 +676,45 @@ async fn revision_handler( Ok::<_, Error>(Json(revisions)) } +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct EditPatchBody { + pub rid: identity::RepoId, + pub cob_id: git::Oid, + pub action: models::patch::Action, + pub opts: CobOptions, +} + +async fn edit_patch_handler( + State(ctx): State, + Json(EditPatchBody { + rid, + cob_id, + action, + opts, + }): Json, +) -> impl IntoResponse { + let patch = ctx.edit_patch(rid, cob_id, action, opts)?; + + Ok::<_, Error>(Json(patch)) +} + +// Deserialize only: `CreateReviewArgs` is an inbound type and isn't Serialize. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct CreatePatchReviewBody { + pub args: models::patch::CreateReviewArgs, +} + +async fn create_patch_review_handler( + State(ctx): State, + Json(CreatePatchReviewBody { args }): Json, +) -> impl IntoResponse { + let review_id = ctx.create_patch_review(args)?; + + Ok::<_, Error>(Json(review_id)) +} + #[derive(Serialize, Deserialize)] struct JobsBody { pub rid: identity::RepoId, diff --git a/public/index.css b/public/index.css index 4de5159d1..029cf649f 100644 --- a/public/index.css +++ b/public/index.css @@ -62,6 +62,21 @@ a { gap: 0.5rem; } +.global-icon-button { + display: inline-flex; + align-items: center; + justify-content: center; + padding: 0.25rem; + border-radius: var(--border-radius-sm); + color: var(--color-text-secondary); + cursor: pointer; +} +.global-icon-button:hover, +.global-icon-button:focus-visible { + background-color: var(--color-surface-subtle); + color: var(--color-text-primary); +} + .global-tab { padding-left: 0.5rem; border-left: 1px solid var(--color-border-mid); diff --git a/src/components/AssigneeInput.svelte b/src/components/AssigneeInput.svelte index ca00763e7..bb2573c30 100644 --- a/src/components/AssigneeInput.svelte +++ b/src/components/AssigneeInput.svelte @@ -171,9 +171,7 @@ -
Changes
- - {#if !hideChanges} -
- -
- {/if} - - -
- {#await cachedListCommits(rid, revision.base, revision.head) then commits} -
- - {#snippet leftHeader()} -
Commits
- {/snippet} -
- - -
{ - if (commits.length === 1) return; - selectRevision({ - headId: revision.head, - baseId: revision.base, - }); - }}> - - {commits.length} - {pluralize("commit", commits.length)} on base - -
Base
+
+ {#if showRevisionDescription || canEditDescription} + {#if editingDescription} +
+ { + await onSaveDescription?.(comment, Array.from(embeds.values())); + editingDescription = false; + }} + close={() => (editingDescription = false)} /> +
+ {:else} +
+
+ {#if showRevisionDescription} + + {:else} + No description + {/if} +
+ {#if descriptionOverflows} +
+
+ {/if} + {#if canEditDescription} +
+ +
+ {/if} +
+ {/if} + {/if} +
+
+ {#if commitList.length > 0} + + {#snippet leftHeader()} +
+ {commitList.length} + {pluralize("commit", commitList.length)} on base + +
Base
+
+ {/snippet}
- {#each [...commits].reverse() as commit, idx} -
-
-
-
+ {#each commitList as commit} + {@const active = isActiveCommit(commit.id)} + {@const toggle = () => { + if (active) { + // Keep the sole commit selected; there's nothing else to show. + if (commitList.length === 1) return; + selectRevision({ + headId: revision.head, + baseId: revision.base, + }); + } else { + selectRevision({ + headId: commit.id, + baseId: commit.parents[0], + commitId: commit.id, + commit, + }); + } + void scrollToDiff(); + }} + + +
1} + stacked + hoverable disabled={isTeaserDisabled(commit.id)} - onclick={() => { - if (commits.length === 1) return; - selectRevision({ - headId: commit.id, - baseId: commit.parents[0], - commitId: commit.id, - }); - }} {commit}> - {#if idx === commits.length - 1} + {#if commit.parents.length > 0} + {#await cachedDiffStats(rid, commit.parents[0], commit.id) then stats} + + + {stats.filesChanged} + +{stats.insertions} + -{stats.deletions} + + {/await} + {/if} + {#if commit.id === revision.head} {/if} + {#if active && commitList.length > 1} + + + + {/if}
{/each}
+ + {/if} +
+
+ {#await cachedDiffStats(rid, base, head) then stats} +
+
+ {stats.filesChanged} + {pluralize("file", stats.filesChanged)} modified with + + {stats.insertions} + {pluralize("insertion", stats.insertions)} + + and + + {stats.deletions} + {pluralize("deletion", stats.deletions)} + +
+ {#if stats.filesChanged > 0} + + {/if}
- + {/await} +
+ {#if selectedCommitData} +
+
+ {selectedCommitData.summary} +
+ {#if selectedCommitData.message.trim() !== selectedCommitData.summary.trim()} +
{selectedCommitData.message
+                  .replace(selectedCommitData.summary, "")
+                  .trim()}
+ {/if} +
+ {/if} + {#await cachedGetDiff(rid, { base, head, unified: 3, highlight: true })} + Loading… + {:then diff} + + {/await} +
- {/await} - - {#await cachedGetDiff(rid, { base, head, unified: 3, highlight: true })} - Loading… - {:then diff} - -
- -
- {/await} +
diff --git a/src/components/Changeset.svelte b/src/components/Changeset.svelte index 8ccf976b9..8ec7050ed 100644 --- a/src/components/Changeset.svelte +++ b/src/components/Changeset.svelte @@ -1,157 +1,132 @@ @@ -216,39 +166,49 @@ left: 0; right: 0; } + .diff { + padding-bottom: 1rem; + }
- {#if stickyFileIndex !== undefined} + {#if stickyFile} {/if}
- - {#snippet row(r)} - {#if r.type === "header"} - {@render header?.()} - {:else} - - {/if} + + fileDiffPath(file)} + {estimatedItemSize} + autoStartMargin + {onScrollState}> + {#snippet row(file)} +
+ setExpanded(file, next)} + {codeComments} + {file} + {head} + {rid} + {draftReviewId} /> +
{/snippet}
diff --git a/src/components/CheckoutPatchButton.svelte b/src/components/CheckoutPatchButton.svelte index 927704198..dc34b2665 100644 --- a/src/components/CheckoutPatchButton.svelte +++ b/src/components/CheckoutPatchButton.svelte @@ -33,7 +33,7 @@ {onclick} active={popoverExpanded}> - Checkout patch + Checkout {/snippet} {#snippet popover()} diff --git a/src/components/CobCommitTeaser.svelte b/src/components/CobCommitTeaser.svelte index 880b36cce..db084527d 100644 --- a/src/components/CobCommitTeaser.svelte +++ b/src/components/CobCommitTeaser.svelte @@ -2,7 +2,12 @@ import type { Commit } from "@bindings/repo/Commit"; import type { Snippet } from "svelte"; - import { twemoji } from "@app/lib/utils"; + import { + absoluteTimestamp, + formatTimestamp, + gravatarURL, + twemoji, + } from "@app/lib/utils"; import Button from "@app/components/Button.svelte"; import CompactCommitAuthorship from "@app/components/CompactCommitAuthorship.svelte"; @@ -17,6 +22,8 @@ hoverable?: boolean; onclick?: () => void; flush?: boolean; + // Stack the summary above the author/hash/date row, for narrow columns. + stacked?: boolean; } const { @@ -26,6 +33,7 @@ flush = false, hoverable = false, onclick = undefined, + stacked = false, }: Props = $props(); let commitMessageVisible = $state(false); @@ -38,6 +46,10 @@ align-items: start; padding: 0.125rem 0; } + .disabled, + .disabled :global(*) { + color: var(--color-text-disabled) !important; + } .message { align-items: center; display: flex; @@ -71,51 +83,137 @@ display: flex; align-items: center; } - .disabled { - color: var(--color-text-disabled) !important; - } pre { white-space: pre-wrap; word-wrap: break-word; } + + /* Stacked layout for the narrow commits column. */ + .teaser.stacked { + flex-direction: column; + align-items: stretch; + gap: 0.375rem; + padding: 0; + } + .stacked-header { + display: flex; + align-items: center; + gap: 0.5rem; + min-width: 0; + } + .commit-avatar { + width: 1rem; + height: 1rem; + border-radius: var(--border-radius-sm); + flex-shrink: 0; + object-fit: cover; + } + .stacked-header .summary-title { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + .stacked-meta { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 0.375rem 0.5rem; + min-width: 0; + font: var(--txt-body-s-regular); + color: var(--color-text-secondary); + } + .stacked-meta .meta-hash { + margin-left: auto; + } + .stacked-meta .meta-hash :global(.txt-id) { + color: var(--color-text-quaternary); + /* Keep the monospace family, but match the meta-row font size. */ + font: var(--txt-code-regular); + font-size: 0.75rem; + line-height: 1rem; + } + .stacked-meta .meta-time { + white-space: nowrap; + } -
-
-
-
+
+ {#if stacked} +
+ +
{#if !commit.summary} No commit message {:else} {/if}
- {#if commit.message.trim() !== commit.summary.trim()} -
- +
+
+ {@render children?.()} + + + + + {formatTimestamp(commit.committer.time * 1000)} + +
+ {:else} +
+
+
+ {#if !commit.summary} + No commit message + {:else} + + {/if} +
+ {#if commit.message.trim() !== commit.summary.trim()} +
+ +
+ {/if} +
+ {#if commitMessageVisible} +
+
{commit.message.replace(commit.summary, "").trim()}
{/if}
- {#if commitMessageVisible} -
-
{commit.message.replace(commit.summary, "").trim()}
-
- {/if} -
-
- {@render children?.()} - - - -
+
+ {@render children?.()} + + + +
+ {/if}
diff --git a/src/components/Comment.svelte b/src/components/Comment.svelte index b65fc752d..e3f1152a2 100644 --- a/src/components/Comment.svelte +++ b/src/components/Comment.svelte @@ -1,3 +1,14 @@ + + + + + +
+
+ +
+
+ {#if !hideAuthor} + {commit.author.name} + {/if} +
+ {#if !hideAuthor} + committed + {/if} + {commit.summary} +
+
+
+ +
+
+ {formatTimestamp(authoredAt)} +
+
+
+
diff --git a/src/components/CommitsContainer.svelte b/src/components/CommitsContainer.svelte index caf7d41eb..3345e794b 100644 --- a/src/components/CommitsContainer.svelte +++ b/src/components/CommitsContainer.svelte @@ -1,7 +1,6 @@ -
-
-
- - {@render leftHeader()} -
+
+
+ + {@render leftHeader()}
- - {#if expanded} -
- {@render children()} -
- {/if} + {@render children()}
diff --git a/src/components/Diff.svelte b/src/components/Diff.svelte new file mode 100644 index 000000000..c9f1ea9a1 --- /dev/null +++ b/src/components/Diff.svelte @@ -0,0 +1,615 @@ + + + + + + +{#snippet lineDiff(line: Modification, lineIdx: number, hunkIdx: number)} + {@const threads = findLineThreads(line)} + {@const commentSide = line.type === "deletion" ? "left" : "right"} + {@const canComment = Boolean(codeComments?.createComment)} +
+ {#if canComment} + + + {/if} +
+ {lineNumber(line, "left")} +
+ +
+ {lineNumber(line, "right")} +
+ +
+ {#if line.type === "addition"} + + + {:else if line.type === "deletion"} + - + {/if} +
+ + {#if line.highlight && line.highlight.items.length > 0} +
+ {@html line.highlight.items + .map( + paint => + `${escape(paint.item)}`, + ) + .join("")} +
+ {:else if line.line !== ""} +
{line.line}
+ {:else} +

+ {/if} +
+ + {#each threads as thread (thread.root.id)} + {#if codeComments} + {@const isDraftThread = + codeComments.draftThreadIds?.includes(thread.root.id) ?? false} + +
+ {#if !codeComments.hideThreadFileHeader} +
+ {@render commentHeader( + thread.root.location?.path, + rangeAnchorsFromCodeLocation(thread.root.location), + )} +
+ {/if} + { + await codeComments.createComment(body, embeds, thread.root.id); + } + : undefined} + editComment={codeComments.editComment} + canModifyComment={partial( + roles.isDelegateOrAuthor, + codeComments.config.publicKey, + codeComments.repoDelegates.map(delegate => delegate.did), + )} + deleteComment={codeComments.deleteComment} + changeCommentStatus={isDraftThread + ? undefined + : codeComments.changeCommentStatus} + canResolve={!isDraftThread && + Boolean(codeComments.changeCommentStatus) && + (codeComments.canResolveComment?.(thread.root.id) ?? false)} /> +
+ {/if} + {/each} + + {#if codeComments && selection?.hunkIdx === hunkIdx && selection?.lineIdx === lineIdx} + +
{ + e.stopPropagation(); + }}> + { + selection = undefined; + }} + focus + placeholder="Leave a comment" + submitCaption={codeComments.newCommentCaption} + submitDescription={codeComments.newCommentDescription} + disableAttachments={codeComments.disableAttachments} + submit={async (body, embeds) => { + if (selection?.codeLocation) { + try { + await codeComments.createComment( + body, + embeds, + undefined, + selection.codeLocation, + ); + } catch (e) { + console.error("Comment creation failed", e); + } finally { + selection = undefined; + } + } + }} + secondarySubmit={codeComments.addCodeCommentDirect + ? { + caption: + codeComments.addCodeCommentDirectCaption ?? "Just comment", + description: codeComments.addCodeCommentDirectDescription, + submit: async (body, embeds) => { + if ( + selection?.codeLocation && + codeComments.addCodeCommentDirect + ) { + try { + await codeComments.addCodeCommentDirect( + body, + embeds, + selection.codeLocation, + ); + } catch (e) { + console.error("Comment creation failed", e); + } finally { + selection = undefined; + } + } + }, + } + : undefined} /> +
+ {/if} +{/snippet} + +{#snippet commentHeader(filePath?: string, selectionRange?: SelectionRange)} + {#if filePath && selectionRange} +
+ {filePath.split("/").length > 1 ? "…/" : ""}{filePath + .split("/") + .slice(-1)}:{selectionRange.start.side === "left" + ? "L" + : "R"}{selectionRange.start.lineNumber} + {#if selectionRange.end} + -> + {selectionRange.end.side === "left" ? "L" : "R"}{selectionRange.end + .lineNumber} + {/if} +
+ {/if} +{/snippet} + +
+ {#if file.diff.type === "plain"} + {#each file.diff.hunks as hunk, hunkIdx} +
+
+
+
+
{hunk.header}
+
+ +
+ {#each hunk.lines as modification, lineIdx} + {@render lineDiff(modification, lineIdx, hunkIdx)} + {/each} +
+ {/each} + {/if} +
diff --git a/src/components/DiffFileHeader.svelte b/src/components/DiffFileHeader.svelte index d202f2137..2eea4fd2b 100644 --- a/src/components/DiffFileHeader.svelte +++ b/src/components/DiffFileHeader.svelte @@ -51,7 +51,11 @@ gap: 0.5rem; width: 100%; min-width: 0; - min-height: 2.5rem; + /* Pinned (not min-height): the diff virtualizer reserves a flat 2.5rem per + file header (`diffHeaderHeight` in PierreDiff), so the real header must be + exactly that height or a gap/overlap appears under it. Content is a single + truncated line, so it always fits. */ + height: 2.5rem; padding: 0 0.5rem; font: var(--txt-body-m-regular); } diff --git a/src/components/DiffRow.svelte b/src/components/DiffRow.svelte deleted file mode 100644 index fb8f8986c..000000000 --- a/src/components/DiffRow.svelte +++ /dev/null @@ -1,524 +0,0 @@ - - - - -{#snippet code(line: Modification)} - {#if line.highlight && line.highlight.items.length > 0} -
- {@html line.highlight.items - .map( - paint => - `${escape(paint.item)}`, - ) - .join("")} -
- {:else if line.line !== ""} -
{line.line}
- {:else} -

- {/if} -{/snippet} - -{#snippet commentHeader(filePath?: string, selectionRange?: SelectionRange)} - {#if filePath && selectionRange} -
- {filePath.split("/").length > 1 ? "…/" : ""}{filePath - .split("/") - .slice(-1)}:{selectionRange.start.side === "left" - ? "L" - : "R"}{selectionRange.start.lineNumber} - {#if selectionRange.end} - -> - {selectionRange.end.side === "left" ? "L" : "R"}{selectionRange.end - .lineNumber} - {/if} -
- {/if} -{/snippet} - -{#snippet readonlyLine(r: LineRow)} - {@const line = r.modification} -
-
{lineNumber(line, "left") ?? ""}
-
{lineNumber(line, "right") ?? ""}
-
- {#if line.type === "addition"}+{:else if line.type === "deletion"}-{/if} -
- {@render code(line)} -
-{/snippet} - -{#snippet interactiveLine(r: LineRow, ctx: CommentContext)} - {@const line = r.modification} - {@const cc = ctx.codeComments} - {@const thread = findLineThread(ctx.threadByLine, r.file, line)} - {@const showThread = - thread !== undefined && !ctx.expandedStates[thread.root.id]} - {@const sel = ctx.selection} - {@const inFile = sel !== undefined && sel.fileIdx === r.fileIndex} - {@const isSel = - inFile && sel.hunkIdx === r.hunkIndex && sel.lineIdx === r.lineIndex} - {@const closeOnLine = r.last && !showThread && !isSel} - {@const closeOnThread = r.last && showThread && !isSel} - {@const closeOnForm = r.last && isSel} - {@const selectable = cc.createComment !== undefined && thread === undefined} -
- -
{ - if (selectable) { - e.preventDefault(); - e.stopPropagation(); - ctx.onSelectLine( - r.fileIndex, - "left", - line, - r.hunkIndex, - r.lineIndex, - r.file, - ); - } - }}> - {lineNumber(line, "left") ?? ""} -
- -
{ - if (selectable) { - e.preventDefault(); - e.stopPropagation(); - ctx.onSelectLine( - r.fileIndex, - "right", - line, - r.hunkIndex, - r.lineIndex, - r.file, - ); - } - }}> - {lineNumber(line, "right") ?? ""} -
-
- {#if line.type === "addition"}+{:else if line.type === "deletion"}-{/if} -
- {@render code(line)} - {#if thread} -
- ctx.onToggleThread(thread.root.id)} /> -
- {/if} -
- - {#if showThread && thread} -
-
- {@render commentHeader( - thread.root.location?.path, - rangeAnchorsFromCodeLocation(thread.root.location), - )} - {#if cc.changeCommentStatus && roles.isDelegateOrAuthor( cc.config.publicKey, cc.repoDelegates.map(delegate => delegate.did), thread.root.author.did )} -
- {#if thread.root.resolved} -
- -
- {:else} -
- -
- {/if} -
- {/if} -
- { - await cc.createComment(body, embeds, thread.root.id); - } - : undefined} - editComment={cc.editComment} - canEditComment={partial( - roles.isDelegateOrAuthor, - cc.config.publicKey, - cc.repoDelegates.map(delegate => delegate.did), - )} - deleteComment={cc.deleteComment} /> -
- {/if} - - {#if isSel && sel} - -
{ - e.stopPropagation(); - }}> -
- {@render commentHeader(sel.file, { start: sel.start })} -
- ctx.onClearSelection()} - focus - placeholder="Leave a comment" - disableAttachments={cc.disableAttachments} - submit={async (body, embeds) => { - try { - await cc.createComment(body, embeds, undefined, sel.codeLocation); - } catch (e) { - console.error("Comment creation failed", e); - } finally { - ctx.onClearSelection(); - } - }} /> -
- {/if} -{/snippet} - -{#if row.type === "file-gap"} -
-{:else if row.type === "file-header"} -
- - {#if row.file.status === "moved" || row.file.status === "copied"} - - → - - {:else} - - {/if} - {#if row.file.status === "added"} - Added - {:else if row.file.status === "deleted"} - Deleted - {:else if row.file.status === "moved"} - Moved - {:else if row.file.status === "copied"} - Copied - {/if} - - - {#if row.file.diff.type === "plain" && row.file.diff.hunks.length > 0} - +{row.file.diff.stats.additions} - -{row.file.diff.stats.deletions} - {/if} - - {#if comments && (row.file.status === "added" || row.file.status === "deleted" || row.file.status === "modified")} - {@const counts = comments.threadCountsByFile.get(row.file.path)} - {#if counts !== undefined && counts.unresolved > 0} -
- - {counts.unresolved} -
- {/if} - {#if counts !== undefined && counts.resolved > 0} -
- - {counts.resolved} -
- {/if} - {/if} - - getDiffText( - diffContext.rid, - diffContext.base, - diffContext.head, - diffContext.unified, - fileDiffPath(row.file), - )} - fileName={fileDiffName(row.file)} - title="File diff actions" /> -
-{:else if row.type === "hunk-header"} -
-
-
-
-
{row.header}
-
-{:else if row.type === "file-note"} -
- {#if row.note === "binary"} - - Binary file - {:else} - Empty file - {/if} -
-{:else if comments} - {@render interactiveLine(row, comments)} -{:else} - {@render readonlyLine(row)} -{/if} diff --git a/src/components/Discussion.svelte b/src/components/Discussion.svelte index 1bb2a5c66..10407a665 100644 --- a/src/components/Discussion.svelte +++ b/src/components/Discussion.svelte @@ -1,23 +1,32 @@ - + + -
-
-
- -
- Discussion - {sum( - commentThreads.map(t => { - return t.replies.length + 1; - }), - )} - -
-
-
-
- {#each commentThreads as thread} - delegate.did), - )} - {editComment} - createReply={createComment} - {reactOnComment} /> -
- {/each} +
+
+
+ {#each runs as run, runIndex (runIndex)} + {#if run.kind === "thread"} + delegate.did), + )} + {editComment} + createReply={createComment} + {reactOnComment} /> +
+ {:else if run.kind === "single" && renderActivity} + {@render renderActivity(run.entry.data, { + hideAuthor: run.repeatsAuthor, + })} +
+ {:else if run.kind === "group" && renderActivity} + {#if !run.repeatsAuthor} +
+ +
+ {/if} +
+ {#each run.entries as entry (entry.key)} + {@render renderActivity(entry.data, { hideAuthor: true })} +
+ {/each} +
+ {/if} + {/each} -
+ {@render afterActivity?.()} +
+ +
{#key commentFormKey} + import type { Review } from "@bindings/cob/patch/Review"; + import type { CodeLocation } from "@bindings/cob/thread/CodeLocation"; + + import { untrack } from "svelte"; + import { backOut, cubicIn } from "svelte/easing"; + import { fly } from "svelte/transition"; + + import type { DraftReview } from "@app/lib/draftReviewStorage"; + import { draftReviewStorage } from "@app/lib/draftReviewStorage"; + + import Button from "@app/components/Button.svelte"; + import Icon from "@app/components/Icon.svelte"; + import Popover from "@app/components/Popover.svelte"; + import { closeFocused } from "@app/components/Popover.svelte"; + + interface Props { + draftReview: DraftReview; + filesChecked?: number; + filesTotal?: number; + // The protocol keeps one review per author per revision and silently + // ignores a second one, which would discard this draft without a trace. + alreadyReviewed?: boolean; + onChange: () => Promise; + onPublish: (revisionId: string) => Promise; + onCancel: () => void; + // Scroll the diff to a pending comment. Absent where there is no diff to + // scroll, in which case the location reads as plain text. + onSelectComment?: (comment: DraftReview["comments"][number]) => void; + } + + const { + draftReview, + filesChecked, + filesTotal, + alreadyReviewed = false, + onChange, + onPublish, + onCancel, + onSelectComment, + }: Props = $props(); + + // svelte-ignore state_referenced_locally + let summary = $state(draftReview.summary ?? ""); + // No fallback: `create` records the starting verdict, so an absent one means + // the reviewer chose "Comment". Defaulting here would undo that and write + // "accept" back the next time the summary is saved. + // svelte-ignore state_referenced_locally + let verdict: Review["verdict"] = $state(draftReview.verdict); + let publishing = $state(false); + let dropdownExpanded = $state(false); + let discardMenuExpanded = $state(false); + let summaryEl: HTMLTextAreaElement | undefined = $state(); + + // Switching between two revisions that both have a draft swaps the prop + // without remounting, so the fields have to follow it. Keyed on the id, not + // the object: saving reloads the patch and hands over a fresh object for the + // same draft, which must not clobber what is being typed. + let syncedDraftId: string | undefined; + $effect(() => { + const id = draftReview.id; + if (id === syncedDraftId) return; + syncedDraftId = id; + untrack(() => { + summary = draftReview.summary ?? ""; + verdict = draftReview.verdict; + // Transient UI belongs to the draft that opened it. + dropdownExpanded = false; + discardMenuExpanded = false; + confirmDeleteId = undefined; + }); + }); + + const expanded = $derived(summary.includes("\n") || summary.length > 80); + + function autoResizeSummary() { + if (!summaryEl) return; + summaryEl.style.height = "auto"; + summaryEl.style.height = `${summaryEl.scrollHeight}px`; + } + + $effect(() => { + void summary; + void expanded; + autoResizeSummary(); + }); + + type VerdictOption = { + value: Review["verdict"]; + label: string; + description: string; + }; + + // Wording follows the protocol: a verdict is advisory. Nothing in + // `Patch::authorization` consults verdicts when a merge is attempted, so + // neither option may claim to gate one. + const verdictOptions: VerdictOption[] = [ + { + value: "accept", + label: "Accept revision", + description: "Record your approval of this revision.", + }, + { + value: "reject", + label: "Reject revision", + description: "Record your objection to this revision.", + }, + { + value: undefined, + label: "Comment", + description: "Leave feedback without accepting or rejecting.", + }, + ]; + + const pendingComments = $derived( + draftReview.comments.filter(c => !c.replyTo), + ); + const pendingCommentCount = $derived(pendingComments.length); + + let showCommentsTooltip = $state(false); + let hideTooltipTimer: ReturnType | undefined; + let editingCommentId: string | undefined = $state(); + let editBody = $state(""); + + function openTooltip() { + if (hideTooltipTimer) { + clearTimeout(hideTooltipTimer); + hideTooltipTimer = undefined; + } + showCommentsTooltip = true; + } + function scheduleHideTooltip() { + if (editingCommentId) return; + if (hideTooltipTimer) clearTimeout(hideTooltipTimer); + hideTooltipTimer = setTimeout(() => { + showCommentsTooltip = false; + }, 150); + } + + function startEdit(commentId: string, currentBody: string) { + editingCommentId = commentId; + editBody = currentBody; + } + function cancelEdit() { + editingCommentId = undefined; + editBody = ""; + } + async function saveEdit(commentId: string) { + draftReviewStorage.updateComment(draftReview.id, commentId, { + body: editBody, + }); + editingCommentId = undefined; + editBody = ""; + await onChange(); + } + async function deleteComment(commentId: string) { + draftReviewStorage.deleteComment(draftReview.id, commentId); + if (editingCommentId === commentId) cancelEdit(); + await onChange(); + } + + let confirmDeleteId: string | undefined = $state(); + let confirmDeleteTimer: ReturnType | undefined; + function requestDeleteComment(commentId: string) { + if (confirmDeleteId === commentId) { + if (confirmDeleteTimer) clearTimeout(confirmDeleteTimer); + confirmDeleteId = undefined; + void deleteComment(commentId); + } else { + confirmDeleteId = commentId; + if (confirmDeleteTimer) clearTimeout(confirmDeleteTimer); + confirmDeleteTimer = setTimeout( + () => (confirmDeleteId = undefined), + 3000, + ); + } + } + + function formatLocation(location: CodeLocation | undefined): string { + if (!location) return ""; + const range = location.new ?? location.old; + if (!range) return location.path; + if (range.type === "lines") { + const start = range.range.start + 1; + const end = range.range.end; + return start === end + ? `${location.path}:${start}` + : `${location.path}:${start}-${end}`; + } + return `${location.path}:${range.line + 1}`; + } + + const verdictLabel = $derived( + verdict === "accept" + ? "Accept revision" + : verdict === "reject" + ? "Reject revision" + : "Comment", + ); + + const verdictColorClass = $derived( + verdict === "accept" + ? "accept" + : verdict === "reject" + ? "reject" + : "comment", + ); + + async function persistSummary() { + draftReviewStorage.update(draftReview.id, { + summary, + verdict, + labels: draftReview.labels, + }); + await onChange(); + } + + let publishError: string | undefined = $state(); + + async function publish() { + publishing = true; + publishError = undefined; + try { + draftReviewStorage.update(draftReview.id, { + summary, + verdict, + labels: draftReview.labels, + }); + const revisionId = draftReview.revisionId; + await draftReviewStorage.publish(draftReview.id); + await onPublish(revisionId); + } catch (error) { + // The draft is only discarded once the review is on the network, so + // everything typed is still here to retry with. + console.error("Publishing review failed", error); + publishError = + error instanceof Error + ? error.message + : "Publishing the review failed."; + } finally { + publishing = false; + } + } + + // The protocol rejects a verdict-less review with no summary (EmptyReview), + // so a comment-only review requires summary text; accept/reject don't. + const publishDisabled = $derived( + publishing || + alreadyReviewed || + (verdict === undefined && summary.trim() === ""), + ); + const summaryRequired = $derived(verdict === undefined); + + + + +
+ + +
+
+ {#if publishError} + + + Not published — your draft is safe. Try again. + + {:else} + Draft saved + {/if} + {#if filesTotal !== undefined && filesChecked !== undefined} + + + {filesChecked}/{filesTotal} + + {/if} + + + {pendingCommentCount} + {#if showCommentsTooltip && pendingCommentCount > 0} + + {/if} + +
+ +
+ + {#snippet toggle(onclick)} + + {/snippet} + {#snippet popover()} +
+
+
+ Discard this draft review? Your comments and verdict will be + lost. +
+
+ + +
+
+
+ {/snippet} +
+ +
+ + + + + + {#snippet toggle(onclick)} + + {/snippet} + {#snippet popover()} +
+ {#each verdictOptions as option (option.label)} + +
{ + verdict = option.value; + draftReviewStorage.update(draftReview.id, { + summary, + verdict: option.value, + labels: draftReview.labels, + }); + closeFocused(); + void onChange(); + }}> +
+ {#if verdict === option.value} + + {/if} +
+
+ {option.label} + + {option.description} + +
+
+ {/each} +
+ {/snippet} +
+
+
+
+
diff --git a/src/components/ExtendedTextarea.svelte b/src/components/ExtendedTextarea.svelte index 9bf59700d..275c172be 100644 --- a/src/components/ExtendedTextarea.svelte +++ b/src/components/ExtendedTextarea.svelte @@ -9,14 +9,14 @@ import { onDestroy, onMount } from "svelte"; import { SvelteMap } from "svelte/reactivity"; + import { hints } from "@app/lib/hints"; import { invoke } from "@app/lib/invoke"; import * as utils from "@app/lib/utils"; import Button from "@app/components/Button.svelte"; - import { hints } from "@app/lib/hints"; - import Icon from "@app/components/Icon.svelte"; import Markdown from "@app/components/Markdown.svelte"; + import Popover, { closeFocused } from "@app/components/Popover.svelte"; import Textarea from "@app/components/Textarea.svelte"; interface Props { @@ -43,6 +43,15 @@ comment: string; embeds: Map; }) => Promise; + submitDescription?: string; + secondarySubmit?: { + caption: string; + description?: string; + submit: (opts: { + comment: string; + embeds: Map; + }) => Promise; + }; close: () => void; // If true, adding attachments through drag-and-drop is disabled and there // is no "Attach" button. If a string is provided, the "Attach" button is @@ -75,6 +84,8 @@ stylePadding, borderVariant = "float", submit, + submitDescription, + secondarySubmit, close, disableAttachments: attachDisabled = false, hideDiscard = false, @@ -253,8 +264,21 @@ }); } + let activeSubmitIndex = $state<0 | 1>(0); + let dropdownExpanded = $state(false); + + const activeSubmit = $derived( + activeSubmitIndex === 1 && secondarySubmit + ? { + caption: secondarySubmit.caption, + submit: secondarySubmit.submit, + } + : { caption: submitCaption, submit }, + ); + function submitFn() { - void submit({ comment: body, embeds }) + void activeSubmit + .submit({ comment: body, embeds }) .then(() => (preview = false)) .catch(e => { console.error(e); @@ -291,7 +315,70 @@ opacity: 0.6; margin-left: 0.25rem; } + .split-submit { + display: flex; + align-items: stretch; + gap: 0.25rem; + } + .submit-menu { + border: 1px solid var(--color-border-subtle); + border-radius: var(--border-radius-sm); + background-color: var(--color-surface-canvas); + width: 22rem; + overflow: hidden; + } + .submit-option { + display: grid; + grid-template-columns: 1.5rem 1fr; + column-gap: 0.5rem; + align-items: start; + padding: 0.625rem 0.75rem; + cursor: pointer; + border-bottom: 1px solid var(--color-border-subtle); + } + .submit-option:last-child { + border-bottom: none; + } + .submit-option:hover { + background-color: var(--color-surface-subtle); + } + .submit-check { + display: flex; + align-items: center; + justify-content: center; + height: 1.25rem; + color: var(--color-text-primary); + } + .submit-text { + display: flex; + flex-direction: column; + gap: 0.125rem; + } + .submit-label { + font: var(--txt-body-m-medium); + color: var(--color-text-primary); + } + .submit-description { + font: var(--txt-body-s-regular); + color: var(--color-text-tertiary); + white-space: normal; + } + .preview { + width: 100%; + font: var(--txt-body-m-regular); + min-height: 109px; + flex: 1; + border: 1px solid var(--color-border-subtle); + border-radius: var(--border-radius-sm); + background-color: var(--color-surface-canvas); + padding: 0.75rem; + } + .inline .preview { + border: 0; + padding: 0; + background-color: transparent; + } .textarea-wrap { position: relative; display: flex; @@ -324,24 +411,21 @@ background-color: var(--color-surface-subtle); color: var(--color-text-secondary); } - .preview { - width: 100%; - font: var(--txt-body-m-regular); - min-height: 109px; - flex: 1; - border: 1px solid var(--color-border-subtle); - border-radius: var(--border-radius-sm); - background-color: var(--color-surface-canvas); - padding: 0.75rem; - } - .inline .preview { - border: 0; - padding: 0; - background-color: transparent; - } -
+ +
{ + if (!preview) return; + const auxiliarKey = utils.isMac() ? event.metaKey : event.ctrlKey; + if (auxiliarKey && event.key === "Enter") { + event.preventDefault(); + void submit({ comment: body, embeds }); + } + }}>
{#if preview}
@@ -399,25 +483,15 @@ Discard {/if} - {#if !preview} -
- {#if embedUploadError} - - - {embedUploadError} - - {/if} - - Markdown is supported. + {#if !preview && embedUploadError} +
+ + + {embedUploadError} +
{/if}
@@ -435,21 +509,107 @@ {preview ? "Edit" : "Preview"} - + {#if secondarySubmit} +
+ + + {#snippet toggle(onclick)} + + {/snippet} + {#snippet popover()} +
+ +
{ + activeSubmitIndex = 0; + closeFocused(); + }}> +
+ {#if activeSubmitIndex === 0} + + {/if} +
+
+ {submitCaption} + {#if submitDescription} + + {submitDescription} + + {/if} +
+
+ +
{ + activeSubmitIndex = 1; + closeFocused(); + }}> +
+ {#if activeSubmitIndex === 1} + + {/if} +
+
+ + {secondarySubmit.caption} + + {#if secondarySubmit.description} + + {secondarySubmit.description} + + {/if} +
+
+
+ {/snippet} +
+
+ {:else} + + {/if}
{/if} diff --git a/src/components/FileBlock.svelte b/src/components/FileBlock.svelte index f0430fe20..a3c588fff 100644 --- a/src/components/FileBlock.svelte +++ b/src/components/FileBlock.svelte @@ -3,7 +3,6 @@ import { tick } from "svelte"; - import Button from "@app/components/Button.svelte"; import Icon from "@app/components/Icon.svelte"; interface Props { @@ -15,29 +14,52 @@ sticky?: boolean; border?: boolean; headerBackground?: string; + // Render just the header, for the pinned bar a virtualized list draws + // above its rows. + headerOnly?: boolean; + // Lets an owner outside this component persist the collapse state, which + // local state can't do when the block is unmounted while scrolled away. + onToggle?: (expanded: boolean) => void; } /* eslint-disable prefer-const */ let { children, - expanded = true, + expanded = $bindable(true), leftHeader, rightHeader, sticky = true, expandable = true, border = true, headerBackground = "var(--color-surface-canvas)", + headerOnly = false, + onToggle, }: Props = $props(); /* eslint-enable prefer-const */ let header: HTMLElement | undefined = $state(); + let hasEverExpanded = $state(expanded); + + $effect(() => { + if (expanded) hasEverExpanded = true; + }); + + async function toggleExpanded() { + if (!expandable) return; + expanded = !expanded; + onToggle?.(expanded); + if (!expanded && header) { + await tick(); + header.scrollIntoView({ behavior: "smooth", block: "nearest" }); + } + } +
+ : "1px solid var(--color-border-subtle)"} + onclick={toggleExpanded} + onkeydown={async event => { + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + await toggleExpanded(); + } + }}>
- {#if expandable} - - {/if} +
+ {#if expandable} + + + + + + + {:else} + + {/if} +
{@render leftHeader?.()}
{#if rightHeader} @@ -106,17 +191,23 @@ class="global-flex" style:gap="1rem" style:margin-left="auto" - style:margin-right="1rem"> + style:margin-right="0.5rem"> {@render rightHeader()}
{/if}
-{#if expanded} -
- {@render children()} +{#if hasEverExpanded && !headerOnly} +
+
+
+ {@render children()} +
+
{/if} diff --git a/src/components/FileDiff.svelte b/src/components/FileDiff.svelte new file mode 100644 index 000000000..8af5a6f15 --- /dev/null +++ b/src/components/FileDiff.svelte @@ -0,0 +1,266 @@ + + + + +{#snippet emptyPlaceholder()} +
+ Empty file +
+{/snippet} + + + {#snippet leftHeader()} + {#if file.status === "moved" || file.status === "copied"} + + + → + + + {:else} + + {/if} + + {#if file.status === "added"} + Added + {:else if file.status === "deleted"} + Deleted + {:else if file.status === "moved"} + Moved + {:else if file.status === "copied"} + Copied + {/if} + {/snippet} + + {#snippet rightHeader()} + {#if file.diff.type === "plain" && file.diff.hunks.length > 0} +
+ + +{file.diff.stats.additions} + + + -{file.diff.stats.deletions} + +
+ {/if} + {#if commentsOfThisFile && commentsOfThisFile.threads.length > 0} + {#if unresolvedThreads > 0} +
+ + {unresolvedThreads} +
+ {/if} + {#if resolvedThreads > 0} +
+ + {resolvedThreads} +
+ {/if} + {/if} + {#if draftReviewId} + + {/if} + {/snippet} + + {#if file.diff.type === "plain"} + {#if file.diff.hunks.length > 0} + + {:else} + {@render emptyPlaceholder()} + {/if} + {:else if file.diff.type === "binary"} + {#await loadBinaryEmbed(file)} +
+ Loading binary… +
+ {:then embed} + {#if embed.mimeType?.startsWith("image/")} +
+ {fileDiffPath(file)} +
+ {:else} +
+ Binary file +
+ {/if} + {:catch} +
+ Binary file +
+ {/await} + {:else} + {@render emptyPlaceholder()} + {/if} +
diff --git a/src/components/Icon.svelte b/src/components/Icon.svelte index 4372b9622..40f83f992 100644 --- a/src/components/Icon.svelte +++ b/src/components/Icon.svelte @@ -64,6 +64,7 @@ | "fullscreen" | "git" | "guide" + | "hash" | "help" | "home" | "hourglass" @@ -459,6 +460,9 @@ + {:else if name === "hash"} + {:else if name === "help"} diff --git a/src/components/Id.svelte b/src/components/Id.svelte index 68511d373..abf98aa18 100644 --- a/src/components/Id.svelte +++ b/src/components/Id.svelte @@ -1,5 +1,4 @@ + + + + + +{#if op.type === "lifecycle"} +
+
+ {#if op.state.status === "open"} + + {:else} + + {/if} +
+
+ {#if !hideAuthor}{/if} +
+ {#if op.state.status === "closed"} + closed issue as {op.state.reason} + {:else if op.state.status === "open"} + reopened issue + {/if} +
+
+ {formatTimestamp(op.timestamp)} +
+
+
+{:else if op.type === "label"} +
+
+ +
+
+ {#if !hideAuthor}{/if} +
+ {#if op.previous && op.previous.type === op.type} + {@const changed = itemDiff(op.previous?.labels ?? [], op.labels)} + {#if changed.added.length || changed.removed.length} + {#if changed.added.length} + added {pluralize("label", changed.removed.length)} + {#each changed.added as label} + {label} + {/each} + {/if} + {#if changed.removed.length} + removed {pluralize("label", changed.removed.length)} + {#each changed.removed as label} + {label} + {/each} + {/if} + {/if} + {:else} + added {pluralize("label", op.labels.length)} + {#each op.labels as label} + {label} + {/each} + {/if} +
+
+ {formatTimestamp(op.timestamp)} +
+
+
+{:else if op.type === "assign"} +
+
+ +
+
+ {#if !hideAuthor}{/if} +
+ {#if op.previous && op.previous.type === op.type} + {@const changed = itemDiff( + op.previous?.assignees ?? [], + op.assignees, + )} + {#if changed.added.length || changed.removed.length} + {#if changed.added.length} + assigned + {#each changed.added as assignee} + + {/each} + {/if} + {#if changed.removed.length} + unassigned + {#each changed.removed as assignee} + + {/each} + {/if} + {/if} + {:else} + assigned + {#each op.assignees as assignee} + + {/each} + {/if} +
+
+ {formatTimestamp(op.timestamp)} +
+
+
+{:else if op.type === "edit"} + {#if op.previous && op.previous.type === op.type} +
+
+ +
+
+ {#if !hideAuthor}{/if} +
+ + changed title {op.previous.title} + → {op.title} + +
+
+ {formatTimestamp(op.timestamp)} +
+
+
+ {/if} +{/if} diff --git a/src/components/IssueStateButton.svelte b/src/components/IssueStateButton.svelte index 36ecda2bd..16fd9e9a1 100644 --- a/src/components/IssueStateButton.svelte +++ b/src/components/IssueStateButton.svelte @@ -35,7 +35,7 @@ {onclick} active={popoverExpanded} title={disabled - ? "You must be a delegate to change the issue state" + ? "Only delegates can change the issue state" : undefined}> opened - + {formatTimestamp(issue.timestamp)} diff --git a/src/components/IssueTimeline.svelte b/src/components/IssueTimeline.svelte deleted file mode 100644 index c068b574f..000000000 --- a/src/components/IssueTimeline.svelte +++ /dev/null @@ -1,244 +0,0 @@ - - - - -
- {#each timeline as op} - {#if op.type === "lifecycle"} -
-
- {#if op.state.status === "open"} - - {:else} - - {/if} -
-
- - {#if op.state.status === "closed"} - closed issue as {op.state.reason} - {:else if op.state.status === "open"} - reopened issue - {/if} -
- {formatTimestamp(op.timestamp)} -
-
-
- {:else if op.type === "label"} -
-
- -
-
- - {#if op.previous && op.previous.type === op.type} - {@const changed = itemDiff(op.previous?.labels ?? [], op.labels)} - {#if changed.added.length || changed.removed.length} - {#if changed.added.length} - added {pluralize("label", changed.removed.length)} - {#each changed.added as label} - {label} - {/each} - {/if} - {#if changed.removed.length} - removed {pluralize("label", changed.removed.length)} - {#each changed.removed as label} - {label} - {/each} - {/if} - {/if} - {:else} - added {pluralize("label", op.labels.length)} - {#each op.labels as label} - {label} - {/each} - {/if} -
- {formatTimestamp(op.timestamp)} -
-
-
- {:else if op.type === "assign"} -
-
- -
-
- - {#if op.previous && op.previous.type === op.type} - {@const changed = itemDiff( - op.previous?.assignees ?? [], - op.assignees, - )} - {#if changed.added.length || changed.removed.length} - {#if changed.added.length} - assigned - {#each changed.added as assignee} - - {/each} - {/if} - {#if changed.removed.length} - unassigned - {#each changed.removed as assignee} - - {/each} - {/if} - {/if} - {:else} - assigned - {#each op.assignees as assignee} - - {/each} - {/if} -
- {formatTimestamp(op.timestamp)} -
-
-
- {:else if op.type === "edit"} - {#if op.previous && op.previous.type === op.type} -
-
- -
-
- - changed title - {op.previous.title} - -> {op.title} -
- {formatTimestamp(op.timestamp)} -
-
-
- {/if} - {:else if op.type === "comment"} - {#if op.id === activity[0].id} -
-
- -
-
- -
- opened issue -
-
- {formatTimestamp(op.timestamp)} -
-
-
- {:else} - - {/if} - {/if} - {/each} -
diff --git a/src/components/Label.svelte b/src/components/Label.svelte index 621b78fff..9bbba30e9 100644 --- a/src/components/Label.svelte +++ b/src/components/Label.svelte @@ -13,7 +13,7 @@ justify-content: center; border: 1px solid var(--color-border-subtle); border-radius: var(--border-radius-sm); - height: 1.5rem; + height: 2rem; padding: 0 0.5rem; color: var(--color-text-tertiary); max-width: 10rem; diff --git a/src/components/LabelInput.svelte b/src/components/LabelInput.svelte index 3a0b5c491..8da8d0a7e 100644 --- a/src/components/LabelInput.svelte +++ b/src/components/LabelInput.svelte @@ -121,11 +121,7 @@
{#each updatedLabels as label}
- -
- {/if} +
+ + + + {#if ownDraftReview && patchView !== "activity"} + { + await loadPatch(); + const updatedRev = revisions.find(r => r.id === revisionId); + const newReview = updatedRev?.reviews?.find( + r => r.author.did === ownDid, + ); + if (newReview) { + void router.push({ + resource: "repo.patch", + rid: repo.rid, + patch: patch.id, + status: undefined, + reviewId: newReview.id, + view: patchView === "changes" ? "changes" : undefined, + }); + } + }} + onCancel={() => { + draftReviewStorage.delete(ownDraftReview.id); + void loadPatch(); + }} + onSelectComment={currentReview + ? // A published review page renders its own diff and none of this + // draft's comments, so there is nothing to scroll to; the location + // falls back to plain text. + undefined + : comment => { + const path = comment.location?.path; + if (path) { + void revisionComponent?.revealComment(comment.id, path); + } + }} /> + {/if} +
diff --git a/src/views/repo/RepoCommit.svelte b/src/views/repo/RepoCommit.svelte index 32351b6b9..caaa9a640 100644 --- a/src/views/repo/RepoCommit.svelte +++ b/src/views/repo/RepoCommit.svelte @@ -4,13 +4,13 @@ FileStatus, } from "@app/components/diffFileHeaderState.svelte"; import type { Diff } from "@bindings/diff/Diff"; - import type { FileDiff } from "@bindings/diff/FileDiff"; import type { Commit } from "@bindings/repo/Commit"; import type { RepoInfo } from "@bindings/repo/RepoInfo"; import type { Blob } from "@bindings/source/Blob"; import type { GitStatusEntry } from "@pierre/trees"; import { diffOptions } from "@app/lib/diffOptions.svelte"; + import { fileDiffPath } from "@app/lib/diffText"; import { getDiffText, invoke } from "@app/lib/invoke"; import * as router from "@app/lib/router"; import type { SidebarData } from "@app/lib/router/definitions"; @@ -54,17 +54,9 @@ }>(); let allCollapsed = $state(false); - // The new-side path Pierre keys each file by — renames and copies use the new - // path, everything else its only path. - function newSidePath(file: FileDiff): string { - return file.status === "moved" || file.status === "copied" - ? file.newPath - : file.path; - } - const changedFiles = $derived( diff.files.map((file): GitStatusEntry => { - const path = newSidePath(file); + const path = fileDiffPath(file); switch (file.status) { case "added": return { path, status: "added" }; @@ -90,7 +82,7 @@ const statuses = new Map(); /* eslint-enable svelte/prefer-svelte-reactivity */ for (const file of diff.files) { - const path = newSidePath(file); + const path = fileDiffPath(file); statuses.set(path, file.status); if (file.diff.type === "binary") { notes.set(path, "binary"); @@ -115,7 +107,7 @@ path: string, ): Promise<{ oldContents: string; newContents: string }> { const parent = commit.parents[0]; - const file = diff.files.find(entry => newSidePath(entry) === path); + const file = diff.files.find(entry => fileDiffPath(entry) === path); let oldContents = ""; let newContents = ""; if (!file) { @@ -300,7 +292,7 @@ {commit.author.name} committed - + @@ -372,7 +364,7 @@ All commits - +
diff --git a/src/views/repo/RepoHome.svelte b/src/views/repo/RepoHome.svelte index e50c72a1d..cc4470874 100644 --- a/src/views/repo/RepoHome.svelte +++ b/src/views/repo/RepoHome.svelte @@ -213,8 +213,11 @@ - + label="commit hash" /> + {blob.commit.message}
diff --git a/src/views/repo/router.ts b/src/views/repo/router.ts index 46bb0d6cd..8ea65f333 100644 --- a/src/views/repo/router.ts +++ b/src/views/repo/router.ts @@ -14,16 +14,14 @@ import type { Readme } from "@bindings/repo/Readme"; import type { RepoInfo } from "@bindings/repo/RepoInfo"; import type { Tree } from "@bindings/source/Tree"; -import type { DraftReview } from "@app/lib/draftReviewStorage"; -import { draftReviewStorage } from "@app/lib/draftReviewStorage"; import { cachedGetCommitDiff, cachedGetDiffText, invoke, } from "@app/lib/invoke"; -import type { SidebarData } from "@app/lib/router/definitions"; +import type { LoadedRoute, SidebarData } from "@app/lib/router/definitions"; import { loadSidebarData } from "@app/lib/router/definitions"; -import { didFromPublicKey, unreachable } from "@app/lib/utils"; +import { unreachable } from "@app/lib/utils"; export type IssueStatus = "all" | Issue["state"]["status"]; @@ -127,12 +125,15 @@ export interface LoadedRepoIssuesRoute { export type PatchStatus = Patch["state"]["status"]; +export type PatchView = "activity" | "changes"; + export interface RepoPatchRoute { resource: "repo.patch"; rid: string; patch: string; status: PatchStatus | undefined; reviewId: string | undefined; + view?: PatchView; } export interface LoadedRepoPatchRoute { @@ -141,8 +142,10 @@ export interface LoadedRepoPatchRoute { repo: RepoInfo; config: Config; patch: Patch; + patches: PaginatedQuery; status: PatchStatus | undefined; - review: Review | DraftReview | undefined; + view?: PatchView; + review: Review | undefined; revisions: Revision[]; activity: Operation[]; sidebarData: SidebarData; @@ -184,40 +187,67 @@ export type LoadedRepoRoute = export async function loadPatch( route: RepoPatchRoute, -): Promise { - const [sidebarData, repo, patch, revisions, activity] = await Promise.all([ - loadSidebarData(), - invoke("repo_by_id", { + previousLoaded?: LoadedRoute, +): Promise { + // Switching tab (view) or review on the same patch shouldn't refetch the + // repo-wide data, so the sidebar and patch list are reused when we stay on + // the same patch. The patch itself, its revisions and its activity are + // always refetched: they change on every comment, review and edit, and a + // reused copy resurrects pre-mutation state when the tab changes. + const reuse = + previousLoaded?.resource === "repo.patch" && + previousLoaded.params.repo.rid === route.rid && + previousLoaded.params.patch.id === route.patch && + previousLoaded.params.status === route.status + ? previousLoaded.params + : undefined; + + const [[sidebarData, repo, patches], [patch, revisions, activity]] = + await Promise.all([ + reuse + ? ([reuse.sidebarData, reuse.repo, reuse.patches] as const) + : Promise.all([ + loadSidebarData(), + invoke("repo_by_id", { + rid: route.rid, + }), + invoke>("list_patches", { + rid: route.rid, + status: route.status, + take: DEFAULT_TAKE, + }), + ] as const), + Promise.all([ + invoke("patch_by_id", { + rid: route.rid, + id: route.patch, + }), + invoke("revisions_by_patch", { + rid: route.rid, + id: route.patch, + }), + invoke[]>("activity_by_patch", { + rid: route.rid, + id: route.patch, + }), + ] as const), + ]); + + // The patch may have been deleted (removed here, on another device, or a + // stale link); fall back to the patch list instead of crashing. + if (!patch) { + return loadPatches({ + resource: "repo.patches", rid: route.rid, - }), - invoke("patch_by_id", { - rid: route.rid, - id: route.patch, - }), - invoke("revisions_by_patch", { - rid: route.rid, - id: route.patch, - }), - invoke[]>("activity_by_patch", { - rid: route.rid, - id: route.patch, - }), - ]); + status: route.status, + }); + } const config = sidebarData.config; - const draftReview = - route.reviewId !== undefined && - draftReviewStorage.get(route.reviewId, { - did: didFromPublicKey(config.publicKey), - alias: config.alias, - }); - - const review = - draftReview || - revisions - .flatMap(r => r.reviews || []) - .find(review => review.id === route.reviewId); + const review = revisions + .flatMap(r => r.reviews || []) + .find(review => review.id === route.reviewId); return { resource: "repo.patch", @@ -225,8 +255,10 @@ export async function loadPatch( repo, config, patch, + patches, revisions, status: route.status, + view: route.view, review, activity, sidebarData, @@ -473,6 +505,9 @@ export function repoRouteToPath(route: RepoRoute): string { if (route.reviewId) { searchParams.set("review", route.reviewId); } + if (route.view) { + searchParams.set("view", route.view); + } if (searchParams.size > 0) { url += `?${searchParams}`; } @@ -553,6 +588,11 @@ export function repoUrlToRoute( const status = (searchParams.get("status") ?? undefined) as PatchStatus | undefined; const reviewId = searchParams.get("review") ?? undefined; + const viewParam = searchParams.get("view"); + const view: PatchView | undefined = + viewParam === "activity" || viewParam === "changes" + ? viewParam + : undefined; if (id) { return { resource: "repo.patch", @@ -560,6 +600,7 @@ export function repoUrlToRoute( patch: id, status, reviewId, + view, }; } else { return { resource: "repo.patches", rid, status }; diff --git a/tests/unit/reviewSummary.test.ts b/tests/unit/reviewSummary.test.ts new file mode 100644 index 000000000..950f76306 --- /dev/null +++ b/tests/unit/reviewSummary.test.ts @@ -0,0 +1,114 @@ +import { describe, expect, test } from "vitest"; + +import type { ReviewEntry } from "@app/lib/reviewSummary"; +import { reviewSummary } from "@app/lib/reviewSummary"; + +function review( + alias: string, + revisionNumber: number, + verdict?: ReviewEntry["verdict"], + delegate = false, +): ReviewEntry { + return { + author: { did: `did:key:${alias}`, alias }, + verdict, + revisionNumber, + delegate, + }; +} + +describe("reviewSummary", () => { + test("a verdict on the current revision keeps its colour", () => { + const state = reviewSummary([review("alice", 2, "accept")], 2); + expect(state.outdated).toBe(false); + expect(state.allAccept).toBe(true); + }); + + test("an accept left behind by a newer revision is outdated, not approved", () => { + const state = reviewSummary([review("alice", 1, "accept")], 3); + expect(state.outdated).toBe(true); + // The whole point: a stale accept must not read as a current approval. + expect(state.allAccept).toBe(false); + }); + + test("a rejection is likewise suppressed once superseded", () => { + const state = reviewSummary([review("alice", 1, "reject")], 2); + expect(state.outdated).toBe(true); + expect(state.hasReject).toBe(false); + }); + + test("one review covering the head keeps the summary current", () => { + const state = reviewSummary( + [review("alice", 1, "accept"), review("bob", 3, "accept")], + 3, + ); + expect(state.outdated).toBe(false); + expect(state.allAccept).toBe(true); + }); + + test("a single non-accept verdict blocks the accepted state", () => { + const state = reviewSummary( + [review("alice", 2, "accept"), review("bob", 2)], + 2, + ); + expect(state.allAccept).toBe(false); + expect(state.hasReject).toBe(false); + }); + + test("counts reviews but lists people once", () => { + const state = reviewSummary( + [ + review("alice", 1, "accept"), + review("alice", 2, "accept"), + review("bob", 2, "accept"), + ], + 2, + ); + expect(state.reviews).toHaveLength(3); + expect(state.authors).toHaveLength(2); + }); + + test("delegates come first so they survive a truncated avatar stack", () => { + const state = reviewSummary( + [review("alice", 1), review("bob", 1, undefined, true)], + 1, + ); + expect(state.authors.map(a => a.alias)).toEqual(["bob", "alice"]); + expect(state.delegateCount).toBe(1); + }); + + test("groups an author's reviews together, newest revision first", () => { + const state = reviewSummary( + [review("alice", 1), review("bob", 2), review("alice", 3)], + 3, + ); + expect( + state.reviews.map(r => `${r.author.alias}${r.revisionNumber}`), + ).toEqual(["alice3", "alice1", "bob2"]); + }); + + test("names the newest reviewed revision for the outdated hint", () => { + const state = reviewSummary( + [review("alice", 1, "accept"), review("bob", 2, "accept")], + 5, + ); + expect(state.outdated).toBe(true); + // The pill renders this as "· r2" — the latest anyone looked at, not the + // oldest and not the patch's current revision. + expect(state.latestReviewedRevision).toBe(2); + }); + + test("no reviews is not outdated", () => { + const state = reviewSummary([], 3); + expect(state.outdated).toBe(false); + expect(state.reviews).toHaveLength(0); + }); + + test("an unknown revision count leaves the summary alone", () => { + // The revision picker renders one revision's own reviews and passes no + // count, since "outdated" has no meaning there. + const state = reviewSummary([review("alice", 1, "accept")], 0); + expect(state.outdated).toBe(false); + expect(state.allAccept).toBe(true); + }); +});