Rebuild the patch page, review UI, and activity timeline

This commit is contained in:
Brandon Oxendine
2026-08-10 12:54:39 +02:00
committed by Rūdolfs Ošiņš
parent 030b5fe1f1
commit 62e150c29a
78 changed files with 10468 additions and 3751 deletions
+4 -29
View File
@@ -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<types::cobs::PaginatedQuery<Vec<models::patch::Patch>>, 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<AppState>,
args: models::patch::CreateReviewArgs,
) -> Result<ReviewId, Error> {
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]
@@ -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<string>;
timestamp: number;
revisionIds: Array<string>;
commentCount: number;
reviewers: Array<Reviewer>;
};
@@ -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;
};
@@ -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<Verdict>,
#[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<String>")]
revision_ids: Vec<patch::RevisionId>,
#[ts(type = "number")]
comment_count: usize,
reviewers: Vec<Reviewer>,
}
#[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::<Vec<_>>();
Self {
id: id.to_string(),
author: cobs::Author::new(patch.author().id(), aliases),
@@ -65,6 +119,23 @@ impl Patch {
labels: patch.labels().cloned().collect::<Vec<_>>(),
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::<usize>();
discussion_comments + review_comments
})
.sum(),
reviewers,
}
}
@@ -52,6 +52,7 @@ pub trait PatchService {
status: Option<cobs::query::PatchStatus>,
skip: Option<usize>,
take: Option<usize>,
delegates: &[identity::Did],
aliases: &impl AliasStore,
) -> Result<cobs::PaginatedQuery<Vec<models::patch::Patch>>, 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 {
+5
View File
@@ -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",
}
}
+57 -3
View File
@@ -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<cob::patch::ReviewId, Error> {
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,
))
}
}
+44 -1
View File
@@ -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<PatchesBody>,
) -> 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<Context>,
Json(EditPatchBody {
rid,
cob_id,
action,
opts,
}): Json<EditPatchBody>,
) -> 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<Context>,
Json(CreatePatchReviewBody { args }): Json<CreatePatchReviewBody>,
) -> impl IntoResponse {
let review_id = ctx.create_patch_review(args)?;
Ok::<_, Error>(Json(review_id))
}
#[derive(Serialize, Deserialize)]
struct JobsBody {
pub rid: identity::RepoId,
+15
View File
@@ -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);
+1 -3
View File
@@ -171,9 +171,7 @@
<Button
variant="outline"
disabled={!allowedToEdit}
title={allowedToEdit
? undefined
: "Only delegates are allowed to add assignees"}
title={allowedToEdit ? undefined : "Only delegates can add assignees"}
onclick={() => {
inputValue = "";
showInput = true;
+11 -1
View File
@@ -12,8 +12,9 @@
active?: boolean;
flatLeft?: boolean;
flatRight?: boolean;
bordered?: boolean;
title?: string;
styleHeight?: "1.75rem" | "2rem" | "2.5rem";
styleHeight?: "1.5rem" | "1.75rem" | "2rem" | "2.5rem";
styleWidth?: string;
styleJustifyContent?: string;
stylePadding?: string;
@@ -29,6 +30,7 @@
active = false,
flatLeft = false,
flatRight = false,
bordered = false,
title,
styleHeight = "2rem",
styleWidth = undefined,
@@ -125,6 +127,13 @@
.button.outline:hover:not(.disabled) {
border-color: var(--color-border-mid);
}
.button.bordered {
border: 1px solid var(--color-border-subtle);
background-color: var(--color-surface-canvas);
}
.button.bordered:hover:not(.disabled) {
background-color: var(--color-surface-subtle);
}
.button.outline.active:not(.disabled),
.button.outline:active:not(.disabled) {
@@ -154,6 +163,7 @@
class:ghost={variant === "ghost"}
class:naked={variant === "naked"}
class:outline={variant === "outline"}
class:bordered
class:disabled
class:active
class:flat-left={flatLeft}
+635 -140
View File
@@ -1,30 +1,61 @@
<script lang="ts">
import type { CodeComments } from "@app/components/Diff.svelte";
import type { Revision } from "@bindings/cob/patch/Revision";
import type { Embed } from "@bindings/cob/thread/Embed";
import type { Commit } from "@bindings/repo/Commit";
import type { CodeComments } from "@app/lib/diffComments";
import { cachedGetDiff, cachedListCommits } from "@app/lib/invoke";
import { tick, untrack } from "svelte";
import {
cachedDiffStats,
cachedGetDiff,
cachedListCommits,
} from "@app/lib/invoke";
import { pluralize } from "@app/lib/utils";
import Button from "@app/components/Button.svelte";
import Changeset from "@app/components/Changeset.svelte";
import CobCommitTeaser from "@app/components/CobCommitTeaser.svelte";
import CommitsContainer from "@app/components/CommitsContainer.svelte";
import ExtendedTextarea from "@app/components/ExtendedTextarea.svelte";
import Icon from "@app/components/Icon.svelte";
import Id from "@app/components/Id.svelte";
import JobCob from "@app/components/JobCob.svelte";
import Markdown from "@app/components/Markdown.svelte";
import { getScrollViewport } from "@app/components/ScrollArea.svelte";
interface Props {
patchId: string;
revision: Revision;
rid: string;
codeComments?: CodeComments;
draftReviewId?: string;
// Reported upward so the review bar knows whether its per-file progress
// applies to what's on screen.
showingRevisionDiff?: boolean;
filesExpanded?: boolean;
canEditDescription?: boolean;
onSaveDescription?: (body: string, embeds: Embed[]) => Promise<void>;
}
const { patchId, revision, rid, codeComments }: Props = $props();
/* eslint-disable prefer-const */
let {
patchId,
revision,
rid,
codeComments,
draftReviewId,
showingRevisionDiff = $bindable(true),
filesExpanded = $bindable(true),
canEditDescription = false,
onSaveDescription,
}: Props = $props();
/* eslint-enable prefer-const */
let hideChanges = $state(false);
let filesExpanded = $state(true);
let selectedCommit = $state<string>();
let selectedCommitData = $state<Commit>();
let editingDescription = $state(false);
let diffScrollEl = $state<HTMLElement>();
// Parent reuses this component across patch revisions; a sibling $effect
// resets base and head when patchId changes.
// svelte-ignore state_referenced_locally
@@ -32,193 +63,657 @@
// svelte-ignore state_referenced_locally
let head = $state(revision.head);
// Guarded on the ids, not the `revision` prop: reloading after a comment or
// reaction hands down a fresh object with the same contents, and resetting on
// that would drop the selected commit and the reader's scroll position.
// svelte-ignore state_referenced_locally
let viewedKey = `${patchId}:${revision.id}`;
$effect(() => {
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
patchId;
hideChanges = false;
filesExpanded = true;
selectedCommit = undefined;
base = revision.base;
head = revision.head;
const key = `${patchId}:${revision.id}`;
const nextBase = revision.base;
const nextHead = revision.head;
untrack(() => {
if (key === viewedKey) return;
viewedKey = key;
filesExpanded = true;
selectedCommit = undefined;
selectedCommitData = undefined;
editingDescription = false;
base = nextBase;
head = nextHead;
});
});
function selectRevision({
headId,
baseId,
commitId = undefined,
commit = undefined,
showFiles = true,
}: {
headId: string;
baseId: string;
commitId?: string;
commit?: Commit;
showFiles?: boolean;
}) {
head = headId;
base = baseId;
selectedCommit = commitId;
selectedCommitData = commit;
filesExpanded = showFiles;
}
// Whether the diff on screen is the revision's own changeset. Selecting a
// commit normally narrows it, but a single-commit revision's commit diff is
// the revision diff, so reviewing stays available there. This, rather than
// "a commit is selected", is what the review affordances depend on.
const isRevisionDiff = $derived(
base === revision.base && head === revision.head,
);
$effect(() => {
if (showingRevisionDiff !== isRevisionDiff) {
showingRevisionDiff = isRevisionDiff;
}
});
// A `CodeLocation` records the commit a comment was written against but not
// the base it was diffed from, and placement matches on path and line alone,
// so a narrowed view carries no comment layer at all.
const diffCodeComments = $derived(isRevisionDiff ? codeComments : undefined);
const isActiveCommit = (commitId: string) => selectedCommit === commitId;
const isTeaserDisabled = (commitId: string) =>
selectedCommit ? selectedCommit !== commitId : false;
let commitList = $state<Commit[]>([]);
$effect(() => {
const ridLocal = rid;
const baseRev = revision.base;
const headRev = revision.head;
let cancelled = false;
void cachedListCommits(ridLocal, baseRev, headRev).then(c => {
if (!cancelled) commitList = c;
});
return () => {
cancelled = true;
};
});
// A single-commit revision has nothing to choose between, so select that
// commit automatically to surface its message.
$effect(() => {
if (commitList.length === 1 && !selectedCommit) {
const only = commitList[0];
selectRevision({
headId: only.id,
baseId: only.parents[0],
commitId: only.id,
commit: only,
});
}
});
function isCommitListDescription(description: string, commits: Commit[]) {
if (commits.length === 0) return false;
const chunks = description
.split("\n")
.map(l => l.trim())
.filter(l => l.length > 0);
if (chunks.length !== commits.length) return false;
const summaries = new Set(commits.map(c => c.summary.trim()));
return chunks.every(line => summaries.has(line));
}
const revisionDescription = $derived(
revision.description.slice(-1)[0]?.body?.trim() ?? "",
);
const showRevisionDescription = $derived(
revisionDescription !== "" &&
!isCommitListDescription(revisionDescription, commitList),
);
const DESCRIPTION_MAX_HEIGHT = 150;
let descriptionExpanded = $state(false);
let descriptionEl = $state<HTMLElement>();
let descriptionOverflows = $state(false);
const descriptionCollapsed = $derived(
descriptionOverflows && !descriptionExpanded,
);
$effect(() => {
const el = descriptionEl;
if (!el) return;
const measure = () => {
descriptionOverflows = el.scrollHeight > DESCRIPTION_MAX_HEIGHT;
};
measure();
const observer = new ResizeObserver(measure);
observer.observe(el);
return () => observer.disconnect();
});
// The Changes tab scrolls with the page (see the CSS): the whole patch
// scrolls so the headers move off-screen and the diff gets the full height,
// while the commit list is sticky and stays in view alongside it.
let reviewLayout = $state<HTMLElement>();
const getViewport = getScrollViewport();
// Bring the top of the diff into view after the reader changes what the diff
// column shows; otherwise the old scroll position leaves you mid-diff and the
// new commit message looks missing.
//
// Driven by the click that caused it rather than by watching `selectedCommit`.
// That selection is also set programmatically — a single-commit revision
// auto-selects its only commit — so an effect could not tell "the reader
// picked a commit" from "the revision changed underneath them", and scrolled
// on both.
let scrollRequest = 0;
async function scrollToDiff() {
const request = ++scrollRequest;
// Measure only once the column above the diff has settled. The stats row
// sits in an `{#await}` keyed on base..head, so a cold cache unmounts it and
// the diff jumps up by its height — measuring first would aim the scroll at
// a position that no longer exists by the time it lands.
await cachedDiffStats(rid, base, head).catch(() => undefined);
await tick();
// A newer click already started its own scroll; that one wins.
if (request !== scrollRequest) return;
const vp = getViewport();
const el = diffScrollEl;
if (!vp || !el) return;
const top =
el.getBoundingClientRect().top -
vp.getBoundingClientRect().top +
vp.scrollTop;
vp.scrollTo({ top: Math.max(top, 0), behavior: "smooth" });
}
let changeset = $state<ReturnType<typeof Changeset> | undefined>();
/// Scroll to one of the draft review's code comments. Called from the review
/// bar, which sits outside this component.
export async function revealComment(threadId: string, path: string) {
// Code comments are only superimposed on the revision's own diff, so a view
// narrowed to a single commit has none to scroll to. Widen back first.
if (!isRevisionDiff) {
selectRevision({ headId: revision.head, baseId: revision.base });
// The widened diff is a fresh `{#await}`, so `changeset` is remounted;
// wait for it before asking it to scroll.
await tick();
await cachedGetDiff(rid, {
base: revision.base,
head: revision.head,
unified: 3,
highlight: true,
}).catch(() => undefined);
await tick();
}
await changeset?.revealThread(threadId, path);
}
function selectCommitAt(index: number) {
if (commitList.length <= 1) return;
const clamped = Math.max(0, Math.min(index, commitList.length - 1));
const commit = commitList[clamped];
selectRevision({
headId: commit.id,
baseId: commit.parents[0],
commitId: commit.id,
commit,
});
void scrollToDiff();
void tick().then(() => {
reviewLayout
?.querySelector(".commit.active")
?.scrollIntoView({ block: "nearest" });
});
}
// Up/Down step through commits; Escape deselects. Ignored while typing.
$effect(() => {
const onKeydown = (e: KeyboardEvent) => {
const el = document.activeElement;
if (
el instanceof HTMLElement &&
(el.tagName === "INPUT" ||
el.tagName === "TEXTAREA" ||
el.isContentEditable)
) {
return;
}
if (e.key === "Escape") {
if (selectedCommit) {
e.preventDefault();
selectRevision({ headId: revision.head, baseId: revision.base });
void scrollToDiff();
}
return;
}
if (commitList.length <= 1) return;
const current = commitList.findIndex(c => c.id === selectedCommit);
if (e.key === "ArrowDown") {
e.preventDefault();
selectCommitAt(current === -1 ? 0 : current + 1);
} else if (e.key === "ArrowUp") {
e.preventDefault();
selectCommitAt(current === -1 ? commitList.length - 1 : current - 1);
}
};
window.addEventListener("keydown", onKeydown);
return () => window.removeEventListener("keydown", onKeydown);
});
</script>
<style>
.commits {
.revision-description {
position: relative;
margin-bottom: 1rem;
color: var(--color-text-primary);
}
.revision-description:has(.revision-description-actions)
.revision-description-body {
padding-right: 2.5rem;
}
.revision-description-actions {
position: absolute;
top: 0;
right: 0;
display: flex;
align-items: center;
}
.revision-description-edit {
display: inline-flex;
align-items: center;
justify-content: center;
background: none;
border: none;
padding: 0.25rem;
border-radius: var(--border-radius-sm);
cursor: pointer;
color: var(--color-text-tertiary);
opacity: 0;
transition: opacity 150ms ease;
}
.revision-description:hover .revision-description-edit,
.revision-description-edit:focus-visible {
opacity: 1;
}
.revision-description-edit:hover,
.revision-description-edit:focus-visible {
color: var(--color-text-primary);
background-color: var(--color-surface-subtle);
}
.revision-description.collapsed .revision-description-body {
max-height: 150px;
overflow: hidden;
}
.revision-description-toggle {
display: flex;
justify-content: center;
margin-top: 0.5rem;
}
.revision-description.collapsed .revision-description-toggle {
position: absolute;
left: 0;
right: 0;
bottom: 0;
align-items: flex-end;
height: 3rem;
margin: 0;
padding-bottom: 0.25rem;
background: linear-gradient(
to bottom,
transparent,
var(--color-surface-canvas)
);
pointer-events: none;
}
/* Identical to the "View all revision changes" button (.diff-tease-button). */
.revision-description-button {
pointer-events: auto;
position: relative;
z-index: 1;
display: inline-flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem 1rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-canvas);
color: var(--color-text-primary);
cursor: pointer;
box-shadow: var(--elevation-low);
}
.revision-description-button:hover,
.revision-description-button:focus-visible {
background-color: var(--color-surface-subtle);
}
.review-layout {
display: grid;
grid-template-columns: minmax(15rem, 22rem) minmax(0, 1fr);
gap: 1rem;
align-items: start;
min-height: 0;
}
/* The whole patch scrolls with the page; the commit list sticks to the top of
the viewport and scrolls internally only when it's taller than the screen,
so it stays in view while you scroll through the diff. */
.commits-column {
position: sticky;
top: 0;
align-self: start;
max-height: calc(100vh - 1rem);
min-width: 0;
overflow-y: auto;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-canvas);
}
.diff-column {
display: flex;
flex-direction: column;
min-width: 0;
min-height: 0;
}
.diff-scroll {
border-radius: var(--border-radius-md);
}
@media (max-width: 60rem) {
.review-layout {
grid-template-columns: 1fr;
}
.commits-column {
position: static;
max-height: none;
overflow-y: visible;
}
.diff-column {
display: block;
}
}
.stats-row {
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
margin-bottom: 1rem;
padding: 0.375rem 0.75rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-canvas);
}
.stats {
min-width: 0;
}
.selected-commit-message {
margin-bottom: 1rem;
padding: 0.75rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-canvas);
}
.selected-commit-body {
margin: 0.5rem 0 0;
white-space: pre-wrap;
word-wrap: break-word;
color: var(--color-text-secondary);
font: var(--txt-body-m-regular);
}
.commit-stats {
display: inline-flex;
align-items: center;
gap: 0.25rem;
white-space: nowrap;
color: var(--color-text-secondary);
font: var(--txt-body-s-regular);
}
.commit-stats .insertions {
color: var(--color-feedback-success-text);
margin-left: 0.5rem;
}
.commit-stats .deletions {
color: var(--color-feedback-error-text);
}
.commits {
display: flex;
flex-direction: column;
font: var(--txt-body-m-regular);
margin-left: 0.5rem;
gap: 0.5rem;
padding: 1rem 0.5rem 0.5rem 1rem;
border-left: 1px solid var(--color-border-subtle);
}
.commit:last-of-type::after {
content: "";
position: absolute;
left: -18.5px;
top: 14px;
bottom: -0.5rem;
border-left: 4px solid var(--color-surface-canvas);
}
.commit-dot {
width: 0.25rem;
height: 0.25rem;
position: absolute;
top: 0.625rem;
left: -18.5px;
background-color: var(--color-border-subtle);
}
.commit {
position: relative;
display: flex;
align-items: center;
gap: 0.5rem;
cursor: pointer;
padding: 0.5rem 1rem;
}
.commit + .commit {
border-top: 1px solid var(--color-border-subtle);
}
/* The last row sits flush against the container's bottom edge, so its hover
and selected fill has to follow the rounded corners itself rather than
relying on the scroll container to clip it. */
.commit:last-child {
border-bottom-left-radius: var(--border-radius-md);
border-bottom-right-radius: var(--border-radius-md);
}
.commit > :global(.teaser) {
flex: 1;
min-width: 0;
}
.commit:hover {
background-color: var(--color-surface-subtle);
}
/* Overlay the close button so showing it on selection doesn't shift the
commit content, straddling the commit list's right edge as an outline
button. */
.commit-close {
position: absolute;
top: 0;
right: 0;
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0;
border: 1px solid var(--color-border-default);
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-canvas);
color: var(--color-text-secondary);
cursor: pointer;
}
.commit-dot.active {
background-color: var(--color-border-brand);
.commit-close:hover,
.commit-close:focus-visible {
background-color: var(--color-surface-subtle);
color: var(--color-text-primary);
}
.commit:hover:not(.single-commit) .commit-dot:not(.active) {
background-color: var(--color-text-primary);
}
.commit:hover:not(.single-commit) {
background-color: var(--color-surface-canvas);
}
.disabled {
color: var(--color-text-disabled) !important;
.commit.active {
background-color: var(--color-surface-subtle);
}
.summary {
cursor: pointer;
padding: 0.25rem 0;
}
.summary:hover:not(.single-commit) {
background-color: var(--color-surface-canvas);
color: var(--color-text-primary) !important;
}
.single-commit {
cursor: default !important;
}
</style>
<div
class="txt-body-m-regular global-flex"
style:margin-bottom={hideChanges ? undefined : "1rem"}>
<div class="global-flex">
<Button variant="naked" onclick={() => (hideChanges = !hideChanges)}>
<Icon name={hideChanges ? "chevron-right" : "chevron-down"} />
</Button>
<div class="txt-body-m-regular global-flex">Changes</div>
</div>
{#if !hideChanges}
<div style:margin-left="auto">
<Button variant="naked" onclick={() => (filesExpanded = !filesExpanded)}>
{#if filesExpanded === true}
<Icon name="collapse-vertical" />
Collapse all
{:else}
<Icon name="expand-vertical" />
Expand all
{/if}
</Button>
</div>
{/if}
</div>
<div style:display={hideChanges ? "none" : "revert"}>
{#await cachedListCommits(rid, revision.base, revision.head) then commits}
<div style:margin-bottom="1rem">
<CommitsContainer>
{#snippet leftHeader()}
<div class="txt-body-m-regular">Commits</div>
{/snippet}
<div style:padding="0 1rem">
<!-- svelte-ignore a11y_no_static_element_interactions -->
<!-- svelte-ignore a11y_click_events_have_key_events -->
<div
class="global-flex txt-body-m-regular summary"
class:single-commit={commits.length === 1}
class:disabled={selectedCommit}
onclick={() => {
if (commits.length === 1) return;
selectRevision({
headId: revision.head,
baseId: revision.base,
});
}}>
<Icon name="branch" />
{commits.length}
{pluralize("commit", commits.length)} on base
<Id id={revision.base} clipboard={revision.base} />
<div class="global-chip">Base</div>
<div>
{#if showRevisionDescription || canEditDescription}
{#if editingDescription}
<div class="revision-description">
<ExtendedTextarea
{rid}
body={showRevisionDescription ? revisionDescription : ""}
focus
submitCaption="Save"
submit={async ({ comment, embeds }) => {
await onSaveDescription?.(comment, Array.from(embeds.values()));
editingDescription = false;
}}
close={() => (editingDescription = false)} />
</div>
{:else}
<div class="revision-description" class:collapsed={descriptionCollapsed}>
<div
class="revision-description-body txt-body-m-regular"
bind:this={descriptionEl}>
{#if showRevisionDescription}
<Markdown {rid} breaks content={revisionDescription} />
{:else}
<span style:color="var(--color-text-tertiary)">No description</span>
{/if}
</div>
{#if descriptionOverflows}
<div class="revision-description-toggle">
<button
type="button"
class="revision-description-button txt-body-m-medium"
onclick={() => (descriptionExpanded = !descriptionExpanded)}>
{descriptionExpanded ? "Show less" : "Show more"}
<Icon
name={descriptionExpanded
? "collapse-vertical"
: "expand-vertical"} />
</button>
</div>
{/if}
{#if canEditDescription}
<div class="revision-description-actions">
<button
type="button"
class="revision-description-edit"
title="Edit description"
onclick={() => (editingDescription = true)}>
<Icon name="edit" />
</button>
</div>
{/if}
</div>
{/if}
{/if}
<div class="review-layout" bind:this={reviewLayout}>
<div class="commits-column">
{#if commitList.length > 0}
<CommitsContainer>
{#snippet leftHeader()}
<div class="global-flex txt-body-m-regular summary">
{commitList.length}
{pluralize("commit", commitList.length)} on base
<Id
id={revision.base}
clipboard={revision.base}
label="base commit" />
<div class="global-chip">Base</div>
</div>
{/snippet}
<div class="commits">
{#each [...commits].reverse() as commit, idx}
<div
class="commit"
class:single-commit={commits.length === 1}
style:position="relative">
<div class="commit-dot"></div>
<div
class="commit-dot"
class:active={isActiveCommit(commit.id)}>
</div>
{#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();
}}
<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="commit" class:active onclick={toggle}>
<CobCommitTeaser
hoverable={commits.length > 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}
<span class="commit-stats">
<Icon name="document" />
{stats.filesChanged}
<span class="insertions">+{stats.insertions}</span>
<span class="deletions">-{stats.deletions}</span>
</span>
{/await}
{/if}
{#if commit.id === revision.head}
<JobCob {rid} commit={commit.id} />
{/if}
</CobCommitTeaser>
{#if active && commitList.length > 1}
<span class="commit-close" title="Show all changes">
<Icon name="close" />
</span>
{/if}
</div>
{/each}
</div>
</CommitsContainer>
{/if}
</div>
<div class="diff-column">
{#await cachedDiffStats(rid, base, head) then stats}
<div class="stats-row txt-body-m-regular">
<div class="stats" style:color="var(--color-text-secondary)">
{stats.filesChanged}
{pluralize("file", stats.filesChanged)} modified with
<span style:color="var(--color-feedback-success-text)">
{stats.insertions}
{pluralize("insertion", stats.insertions)}
</span>
and
<span style:color="var(--color-feedback-error-text)">
{stats.deletions}
{pluralize("deletion", stats.deletions)}
</span>
</div>
{#if stats.filesChanged > 0}
<Button
variant="naked"
onclick={() => (filesExpanded = !filesExpanded)}>
{#if filesExpanded}
<Icon name="collapse-vertical" />
Collapse all
{:else}
<Icon name="expand-vertical" />
Expand all
{/if}
</Button>
{/if}
</div>
</CommitsContainer>
{/await}
<div class="diff-scroll" bind:this={diffScrollEl}>
{#if selectedCommitData}
<div class="selected-commit-message txt-selectable">
<div class="selected-commit-summary txt-body-m-medium">
{selectedCommitData.summary}
</div>
{#if selectedCommitData.message.trim() !== selectedCommitData.summary.trim()}
<pre class="selected-commit-body">{selectedCommitData.message
.replace(selectedCommitData.summary, "")
.trim()}</pre>
{/if}
</div>
{/if}
{#await cachedGetDiff(rid, { base, head, unified: 3, highlight: true })}
<span class="txt-body-m-regular">Loading…</span>
{:then diff}
<Changeset
bind:this={changeset}
expanded={filesExpanded}
{head}
{diff}
{rid}
codeComments={diffCodeComments}
draftReviewId={isRevisionDiff ? draftReviewId : undefined} />
{/await}
</div>
</div>
{/await}
{#await cachedGetDiff(rid, { base, head, unified: 3, highlight: true })}
<span class="txt-body-m-regular">Loading…</span>
{:then diff}
<!-- The patch layout already pads its content, so the diff cards don't add
their own side inset and align with the rest of the patch. -->
<div style:--diff-inset="0">
<Changeset
expanded={filesExpanded}
{rid}
{base}
{head}
{diff}
{codeComments} />
</div>
{/await}
</div>
</div>
+130 -170
View File
@@ -1,157 +1,132 @@
<script lang="ts">
import type { CodeComments } from "@app/components/Diff.svelte";
import type { Diff } from "@bindings/diff/Diff";
import type { FileDiff } from "@bindings/diff/FileDiff";
import type { Modification } from "@bindings/diff/Modification";
import type { Snippet } from "svelte";
import { tick } from "svelte";
import { SvelteSet } from "svelte/reactivity";
import type {
CodeComments,
CommentContext,
Selection,
Side,
} from "@app/lib/diffComments";
import {
buildSelection,
buildThreadByLine,
buildThreadCountsByFile,
} from "@app/lib/diffComments";
import type { DiffRow } from "@app/lib/diffRows";
import { diffRowKey, flattenDiff } from "@app/lib/diffRows";
import { fileDiffPath } from "@app/lib/diffText";
import { isIgnoredFile } from "@app/lib/ignoredFiles";
import DiffRowView from "@app/components/DiffRow.svelte";
import FileDiffComponent from "@app/components/FileDiff.svelte";
import VirtualList from "@app/components/VirtualList.svelte";
interface Props {
codeComments?: CodeComments;
diff: Diff;
expanded?: boolean;
rid: string;
// Base of the commit range `diff` was built from; unset means `head`'s
// first parent (a single-commit diff).
base?: string;
head: string;
// Context lines `diff` was built with, so patch text fetched by diff
// actions matches the rendered diff.
unified?: number;
// Rendered as the first virtualized row (e.g. commit/patch metadata), so
// the virtualizer owns the whole scroll content and starts at offset 0.
header?: Snippet;
rid: string;
draftReviewId?: string;
}
const {
codeComments,
diff,
expanded = true,
rid,
base,
head,
unified = 3,
header,
rid,
draftReviewId,
}: Props = $props();
const diffContext = $derived({ rid, base, head, unified });
// Per-file collapse state. The `expanded` prop is the "expand all"/"collapse
// all" command: when it flips, re-seed every file; individual chevrons then
// deviate from that until the next flip.
const collapsed = new SvelteSet<number>();
// Collapse state lives here rather than in each FileDiff: a virtualized row
// unmounts once scrolled out of view, which would reset it. The `expanded`
// prop is expand-all/collapse-all, so the set is re-seeded whenever it flips.
const collapsed = new SvelteSet<string>();
$effect(() => {
if (expanded) {
collapsed.clear();
} else {
for (let i = 0; i < diff.files.length; i++) {
collapsed.add(i);
const all = expanded;
collapsed.clear();
for (const file of diff.files) {
if (!all || isIgnoredFile(file)) {
collapsed.add(fileDiffPath(file));
}
}
});
function isFileExpanded(fileIndex: number): boolean {
return !collapsed.has(fileIndex);
function isExpanded(file: FileDiff): boolean {
return !collapsed.has(fileDiffPath(file));
}
function toggleFile(fileIndex: number) {
if (collapsed.has(fileIndex)) {
collapsed.delete(fileIndex);
function setExpanded(file: FileDiff, next: boolean) {
if (next) {
collapsed.delete(fileDiffPath(file));
} else {
collapsed.add(fileIndex);
collapsed.add(fileDiffPath(file));
}
}
// Patch-review comment state (lifted from the old per-file Diff.svelte so a
// single virtualizer can own the whole changeset).
let selection = $state<Selection | undefined>(undefined);
const threadByLine = $derived(buildThreadByLine(codeComments?.threads ?? []));
const threadCountsByFile = $derived(
buildThreadCountsByFile(codeComments?.threads ?? []),
);
// eslint-disable-next-line svelte/prefer-writable-derived -- needs a $state proxy so toggleCommentExpand's property mutation triggers reactivity
let threadExpandedStates: Record<string, boolean> = $state({});
$effect(() => {
threadExpandedStates = codeComments
? Object.fromEntries(
codeComments.threads.map(t => [t.root.id, t.root.resolved]),
)
: {};
// virtua takes one estimate for every item, so aim at the right total rather
// than the right file: the scrollbar then starts near its true length and
// corrections stay local instead of accumulating into a jump. Derived from
// the initial expand state, so collapsing mid-scroll doesn't move it.
const LINE_HEIGHT = 20;
const HEADER_HEIGHT = 40;
const FILE_GAP = 16;
const estimatedItemSize = $derived.by(() => {
if (diff.files.length === 0) {
return HEADER_HEIGHT;
}
let total = 0;
for (const file of diff.files) {
total += HEADER_HEIGHT + FILE_GAP;
if (!expanded || isIgnoredFile(file) || file.diff.type !== "plain") {
continue;
}
for (const hunk of file.diff.hunks) {
total += (hunk.lines.length + 1) * LINE_HEIGHT;
}
}
return Math.round(total / diff.files.length);
});
function toggleCommentExpand(commentId: string) {
threadExpandedStates[commentId] = !threadExpandedStates[commentId];
}
function selectLine(
fileIdx: number,
side: Side,
line: Modification,
hunkIdx: number,
lineIdx: number,
file: FileDiff,
) {
selection = buildSelection(
head,
file,
fileIdx,
side,
line,
hunkIdx,
lineIdx,
);
}
const comments = $derived<CommentContext | undefined>(
codeComments
? {
codeComments,
threadByLine,
threadCountsByFile,
selection,
expandedStates: threadExpandedStates,
onSelectLine: selectLine,
onClearSelection: () => {
selection = undefined;
},
onToggleThread: toggleCommentExpand,
}
: undefined,
);
type Row = { type: "header" } | DiffRow;
const rows = $derived<Row[]>(
header
? [{ type: "header" }, ...flattenDiff(diff, isFileExpanded)]
: flattenDiff(diff, isFileExpanded),
);
function rowKey(row: Row): string {
return row.type === "header" ? "header" : diffRowKey(row);
}
// Sticky file header. A row's own `position: sticky` can't work inside the
// virtualizer's absolutely-positioned items, so the header of the topmost
// visible file is drawn separately and pinned here.
let topIndex = $state(0);
let scrollOffset = $state(0);
let itemOffset = $state<(index: number) => number>(() => 0);
let stickyBarHeight = $state(0);
let list = $state<ReturnType<typeof VirtualList> | undefined>();
/// Bring a code comment thread into view, expanding and rendering whatever is
/// needed to get there. Returns false when the file isn't in this diff.
///
/// Two stages, because the file list is virtualised: scroll the file into
/// existence, then to the thread inside it. The retry covers the gap between
/// virtua committing the scroll and the row mounting, which is more than one
/// tick when the row has never been measured.
export async function revealThread(
threadId: string,
path: string,
): Promise<boolean> {
const index = diff.files.findIndex(file => fileDiffPath(file) === path);
if (index === -1) return false;
// An ignored file (a lockfile, say) starts collapsed, and a collapsed file
// renders no threads at all.
collapsed.delete(path);
await tick();
list?.scrollToIndex(index, { align: "start" });
for (let attempt = 0; attempt < 20; attempt++) {
await tick();
// Queried from the document: thread ids are object ids (or a draft's
// UUID), unique across the page, and the rows live inside the virtualiser
// rather than in a subtree this component holds a reference to.
const el = document.querySelector(
`[data-thread-id="${CSS.escape(threadId)}"]`,
);
if (el) {
el.scrollIntoView({ block: "center", behavior: "smooth" });
return true;
}
await new Promise(resolve => requestAnimationFrame(() => resolve(null)));
}
// The file is on screen even if the thread never appeared, which is still
// closer than where the reader started.
return true;
}
function onScrollState(s: {
topIndex: number;
scrollOffset: number;
@@ -162,41 +137,16 @@
itemOffset = s.itemOffset;
}
// The file whose header is pinned: the topmost row's file, or the file above a
// gap row (so the bar persists while transitioning between files). Pinned from
// the moment any of a file's rows reaches the top, including its own header.
const stickyFileIndex = $derived.by(() => {
const r = rows[topIndex];
if (!r) return undefined;
if (
r.type === "file-header" ||
r.type === "hunk-header" ||
r.type === "file-note" ||
r.type === "line"
) {
return r.fileIndex;
}
if (r.type === "file-gap") {
return r.fileIndex - 1;
}
return undefined;
});
const stickyFile = $derived(diff.files[topIndex]);
// The next file's header row, used to push the current sticky bar up and out
// as the next header rises into it (VSCode-style sticky scroll).
const nextHeaderIndex = $derived.by(() => {
for (let i = topIndex + 1; i < rows.length; i++) {
if (rows[i].type === "file-header") {
return i;
}
}
return undefined;
});
// As the next file's header rises into the pinned bar, push the bar up and
// out rather than letting the two overlap.
const pushOffset = $derived.by(() => {
if (nextHeaderIndex === undefined || stickyBarHeight === 0) {
const next = topIndex + 1;
if (next >= diff.files.length || stickyBarHeight === 0) {
return 0;
}
const nextTop = itemOffset(nextHeaderIndex) - scrollOffset;
const nextTop = itemOffset(next) - scrollOffset;
return nextTop < stickyBarHeight ? stickyBarHeight - nextTop : 0;
});
</script>
@@ -216,39 +166,49 @@
left: 0;
right: 0;
}
.diff {
padding-bottom: 1rem;
}
</style>
<div class="sticky-anchor">
{#if stickyFileIndex !== undefined}
{#if stickyFile}
<div
class="sticky-bar"
bind:clientHeight={stickyBarHeight}
style:transform="translateY({-pushOffset}px)">
<DiffRowView
row={{
type: "file-header",
fileIndex: stickyFileIndex,
file: diff.files[stickyFileIndex],
standalone: false,
}}
expanded={isFileExpanded(stickyFileIndex)}
onToggleFile={toggleFile}
{comments}
{diffContext} />
<FileDiffComponent
headerOnly
sticky={false}
expanded={isExpanded(stickyFile)}
onToggle={next => setExpanded(stickyFile, next)}
file={stickyFile}
{head}
{rid}
{codeComments}
{draftReviewId} />
</div>
{/if}
</div>
<VirtualList items={rows} getKey={rowKey} autoStartMargin {onScrollState}>
{#snippet row(r)}
{#if r.type === "header"}
{@render header?.()}
{:else}
<DiffRowView
row={r}
expanded={isFileExpanded(r.fileIndex)}
onToggleFile={toggleFile}
{comments}
{diffContext} />
{/if}
<VirtualList
bind:this={list}
items={diff.files}
getKey={file => fileDiffPath(file)}
{estimatedItemSize}
autoStartMargin
{onScrollState}>
{#snippet row(file)}
<div class="diff">
<FileDiffComponent
sticky={false}
expanded={isExpanded(file)}
onToggle={next => setExpanded(file, next)}
{codeComments}
{file}
{head}
{rid}
{draftReviewId} />
</div>
{/snippet}
</VirtualList>
+1 -1
View File
@@ -33,7 +33,7 @@
{onclick}
active={popoverExpanded}>
<Icon name="checkout" />
<span class="global-hide-on-medium-desktop-down">Checkout patch</span>
<span class="global-hide-on-medium-desktop-down">Checkout</span>
</Button>
{/snippet}
{#snippet popover()}
+129 -31
View File
@@ -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;
}
</style>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<!-- svelte-ignore a11y_click_events_have_key_events -->
<div class="teaser" class:disabled {onclick} aria-label="commit-teaser">
<div class="left" style:padding={flush ? "0" : undefined}>
<div class="message">
<div style:cursor={hoverable ? "pointer" : "default"} use:twemoji>
<div
class="teaser"
class:disabled
class:stacked
{onclick}
aria-label="commit-teaser">
{#if stacked}
<div class="stacked-header">
<img
class="commit-avatar"
alt=""
src={gravatarURL(commit.author.email)}
title={commit.author.name} />
<div
class="summary-title"
style:cursor={hoverable ? "pointer" : "default"}
use:twemoji>
{#if !commit.summary}
<span class="txt-missing">No commit message</span>
{:else}
<InlineTitle fontSize="small" content={commit.summary} />
{/if}
</div>
{#if commit.message.trim() !== commit.summary.trim()}
<div class="commit-expand-button">
<Button
variant="naked"
stylePadding="0 0.25rem"
onclick={e => {
e.stopPropagation();
commitMessageVisible = !commitMessageVisible;
}}>
<Icon name="ellipsis" />
</Button>
</div>
<div class="stacked-meta">
{@render children?.()}
<span class="meta-hash">
<Id id={commit.id} clipboard={commit.id} label="commit hash" />
</span>
<span
class="meta-time"
title={absoluteTimestamp(commit.committer.time * 1000)}>
{formatTimestamp(commit.committer.time * 1000)}
</span>
</div>
{:else}
<div class="left" style:padding={flush ? "0" : undefined}>
<div class="message">
<div
class="summary-title"
style:cursor={hoverable ? "pointer" : "default"}
use:twemoji>
{#if !commit.summary}
<span class="txt-missing">No commit message</span>
{:else}
<InlineTitle fontSize="small" content={commit.summary} />
{/if}
</div>
{#if commit.message.trim() !== commit.summary.trim()}
<div class="commit-expand-button">
<Button
variant="naked"
stylePadding="0 0.25rem"
onclick={e => {
e.stopPropagation();
commitMessageVisible = !commitMessageVisible;
}}>
<Icon name="ellipsis" />
</Button>
</div>
{/if}
</div>
{#if commitMessageVisible}
<div class="commit-message">
<pre>{commit.message.replace(commit.summary, "").trim()}</pre>
</div>
{/if}
</div>
{#if commitMessageVisible}
<div class="commit-message">
<pre>{commit.message.replace(commit.summary, "").trim()}</pre>
</div>
{/if}
</div>
<div class="right">
{@render children?.()}
<CompactCommitAuthorship {commit}>
<Id id={commit.id} clipboard={commit.id} />
</CompactCommitAuthorship>
</div>
<div class="right">
{@render children?.()}
<CompactCommitAuthorship {commit}>
<Id id={commit.id} clipboard={commit.id} label="commit hash" />
</CompactCommitAuthorship>
</div>
{/if}
</div>
+49 -9
View File
@@ -1,3 +1,14 @@
<script lang="ts" module>
// Says where a comment lives when a view mixes comments from several places
// — a review's own comments and comments left directly on a revision look
// alike otherwise, but they differ in what can be done to them.
export interface CommentOrigin {
text: string;
title?: string;
onclick?: () => void;
}
</script>
<script lang="ts">
import type { Author } from "@bindings/cob/Author";
import type { Edit } from "@bindings/cob/patch/Edit";
@@ -29,6 +40,9 @@
reactions?: Reaction[];
embeds?: Map<string, Embed>;
caption?: string;
// Marks a comment that is part of an unpublished draft review.
draft?: boolean;
origin?: CommentOrigin;
timestamp?: number;
lastEdit?: Edit;
disallowEmptyBody?: boolean;
@@ -53,6 +67,8 @@
reactions,
embeds,
caption = "commented",
draft = false,
origin,
timestamp,
lastEdit,
disallowEmptyBody = false,
@@ -104,6 +120,7 @@
}
.header-right {
display: flex;
align-items: center;
margin-left: auto;
gap: 0.5rem;
opacity: 0;
@@ -141,14 +158,17 @@
gap: 0.5rem;
padding: 0 0.75rem 0.25rem;
}
button.caption {
background: none;
border: none;
padding: 0;
cursor: pointer;
}
.timestamp,
.caption {
font: var(--txt-body-m-regular);
color: var(--color-text-quaternary);
}
.icon-button {
cursor: pointer;
}
</style>
<div
@@ -160,6 +180,26 @@
<div class="card-header">
<NodeId {...utils.authorForNodeId(author)} />
<span class="caption">{caption}</span>
{#if draft}
<span
class="global-chip"
title="Not published yet, only visible to you">
Draft
</span>
{/if}
{#if origin}
{#if origin.onclick}
<button
class="global-link caption"
type="button"
title={origin.title}
onclick={origin.onclick}>
{origin.text}
</button>
{:else}
<span class="caption" title={origin.title}>{origin.text}</span>
{/if}
{/if}
{#if beforeTimestamp}
{@render beforeTimestamp()}
{/if}
@@ -180,17 +220,17 @@
{/if}
<div class="header-right">
{#if id}
<Id {id} clipboard={id} />
<Id {id} clipboard={id} label="comment ID" />
{/if}
{#if editComment}
<div class="icon-button">
<span class="global-icon-button" title="Edit comment">
<Icon name="edit" onclick={toggleEdit} />
</div>
</span>
{/if}
{#if deleteComment}
<div class="icon-button">
{#if deleteComment && currentUserNid && utils.publicKeyFromDid(author.did) === currentUserNid}
<span class="global-icon-button" title="Delete comment">
<Icon name="trash" onclick={deleteComment} />
</div>
</span>
{/if}
{#if reactions && reactOnComment}
<ReactionSelector
+30 -1
View File
@@ -7,7 +7,14 @@
rid: string;
placeholder?: string;
focus?: boolean;
submitCaption?: string;
submitDescription?: string;
submit: (comment: string, embeds: Embed[]) => Promise<void>;
secondarySubmit?: {
caption: string;
description?: string;
submit: (comment: string, embeds: Embed[]) => Promise<void>;
};
onclose?: () => void;
onexpand?: () => void;
disallowEmptyBody?: boolean;
@@ -20,7 +27,10 @@
rid,
placeholder,
focus = false,
submitCaption,
submitDescription,
submit,
secondarySubmit,
onclose,
onexpand,
disallowEmptyBody = false,
@@ -52,6 +62,8 @@
{disallowEmptyBody}
{rid}
{placeholder}
{submitCaption}
{submitDescription}
borderVariant="ghost"
submitActiveVariant="secondary"
submitInProgress={state === "submit"}
@@ -72,7 +84,24 @@
} finally {
state = "collapsed";
}
}} />
}}
secondarySubmit={secondarySubmit
? {
caption: secondarySubmit.caption,
description: secondarySubmit.description,
submit: async ({ comment, embeds }) => {
try {
state = "submit";
await secondarySubmit.submit(
comment,
Array.from(embeds.values()),
);
} finally {
state = "collapsed";
}
},
}
: undefined} />
{:else}
<!-- svelte-ignore a11y_click_events_have_key_events -->
<div
+100
View File
@@ -0,0 +1,100 @@
<script lang="ts">
import type { Commit } from "@bindings/repo/Commit";
import { absoluteTimestamp, formatTimestamp } from "@app/lib/utils";
import Icon from "@app/components/Icon.svelte";
import Id from "@app/components/Id.svelte";
interface Props {
commit: Commit;
hideAuthor?: boolean;
}
const { commit, hideAuthor }: Props = $props();
const authoredAt = $derived(commit.author.time * 1000);
</script>
<style>
.timeline-item {
display: grid;
grid-template-columns: 1rem minmax(0, 1fr);
column-gap: 0.5rem;
align-items: center;
min-width: 0;
padding: 0.375rem 0.5rem;
border-radius: var(--border-radius-sm);
min-height: 2.5rem;
}
.wrapper {
display: flex;
flex-wrap: wrap;
gap: 0.25rem;
min-width: 0;
flex: 1 1 0;
}
.icon {
width: 1rem;
color: var(--color-text-secondary);
}
.author {
color: var(--color-text-tertiary);
}
.summary-line {
flex: 1 1 0;
min-width: 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.action-verb {
color: var(--color-text-tertiary);
}
.summary-content {
color: var(--color-text-primary);
}
.timestamp {
color: var(--color-text-quaternary);
}
.meta {
display: flex;
align-items: center;
gap: 0.5rem;
flex-shrink: 0;
}
.meta-hash {
color: var(--color-text-quaternary);
}
.meta-hash :global(.txt-id) {
color: inherit;
}
.meta-hash :global(.txt-id:hover) {
color: inherit;
}
</style>
<div class="timeline-item txt-body-m-regular">
<div class="icon">
<Icon name="commit" />
</div>
<div class="wrapper">
{#if !hideAuthor}
<span class="author">{commit.author.name}</span>
{/if}
<div class="summary-line">
{#if !hideAuthor}
<span class="action-verb">committed</span>
{/if}
<span class="txt-body-m-medium summary-content">{commit.summary}</span>
</div>
<div class="meta">
<div class="meta-hash">
<Id id={commit.id} clipboard={commit.id} label="commit hash" />
</div>
<div class="timestamp" title={absoluteTimestamp(authoredAt)}>
{formatTimestamp(authoredAt)}
</div>
</div>
</div>
</div>
+19 -37
View File
@@ -1,7 +1,6 @@
<script lang="ts">
import type { Snippet } from "svelte";
import Button from "@app/components/Button.svelte";
import Icon from "@app/components/Icon.svelte";
interface Props {
@@ -10,51 +9,34 @@
}
const { leftHeader, children }: Props = $props();
let expanded = $state(true);
</script>
<style>
.header {
position: sticky;
top: 0;
z-index: 1;
display: flex;
align-items: center;
height: 2.5rem;
padding-left: 0.25rem;
font: var(--txt-body-m-regular);
}
.left {
display: flex;
gap: 0.5rem;
align-items: center;
height: 2.5rem;
padding: 0 0.5rem;
font: var(--txt-body-m-regular);
background-color: var(--color-surface-canvas);
border-bottom: 1px solid var(--color-border-subtle);
}
.icon {
display: grid;
width: 1rem;
height: 1rem;
place-items: center;
}
</style>
<div
style:border="1px solid var(--color-border-subtle)"
style:border-radius="var(--border-radius-md)"
style:display="flex"
style:align-items="flex-start"
style:background-color="var(--color-surface-canvas)"
style:flex-direction="column">
<div class="header" class:collapsed={!expanded}>
<div class="left">
<Button
variant="naked"
onclick={async () => {
expanded = !expanded;
}}>
<Icon name={expanded ? "chevron-down" : "chevron-right"} />
</Button>
{@render leftHeader()}
</div>
<div style:display="flex" style:flex-direction="column" style:width="100%">
<div class="header">
<span class="icon"><Icon name="commit" /></span>
{@render leftHeader()}
</div>
{#if expanded}
<div
style:width="100%"
style:border-top="1px solid var(--color-border-subtle)">
{@render children()}
</div>
{/if}
{@render children()}
</div>
+615
View File
@@ -0,0 +1,615 @@
<script lang="ts" module>
import type { CommentOrigin } from "@app/components/Comment.svelte";
export interface CodeComments {
changeCommentStatus?: (
commentId: string,
resolved: boolean,
) => Promise<void>;
// Whether this thread can be resolved and the current user may do it.
// Decided by the host: the protocol allows the comment author, the review
// author or the revision author, and only the host knows all three.
canResolveComment?: (commentId: string) => boolean;
config: Config;
createComment: (
body: string,
embeds: Embed[],
replyTo?: string,
location?: CodeLocation,
) => Promise<void>;
// Defaults to "Comment".
newCommentCaption?: string;
newCommentDescription?: string;
// When provided, the new-code-comment composer shows a second submit option
// in the split-button dropdown that posts a `revision.comment` directly
// (no review wrapping). The primary `createComment` continues to take
// whatever path the host wires (typically: stash into a draft review).
addCodeCommentDirect?: (
body: string,
embeds: Embed[],
location: CodeLocation,
) => Promise<void>;
addCodeCommentDirectCaption?: string;
addCodeCommentDirectDescription?: string;
editComment: (
commentId: string,
body: string,
embeds: Embed[],
) => Promise<void>;
reactOnComment?: (
commentId: string,
authors: Author[],
reaction: string,
) => Promise<void>;
deleteComment?: (commentId: string) => Promise<void>;
// Defaults to `true`.
canReply?: boolean;
// See `ExtendedTextarea`.
disableAttachments?: boolean | string;
// For hosts whose surrounding context already shows the file path.
hideThreadFileHeader?: boolean;
// Unpublished draft roots, which render alongside published threads and so
// have to be told apart.
draftThreadIds?: string[];
// Root comment id -> where that thread lives, so comments merged from
// several sources stay distinguishable in one diff.
threadOrigins?: Record<string, CommentOrigin>;
repoDelegates: Author[];
rid: string;
threads: Thread<CodeLocation>[];
}
</script>
<script lang="ts">
type Side = "left" | "right";
type SelectionAnchor = { side: Side; lineNumber: number };
type SelectionRange = { start: SelectionAnchor; end?: SelectionAnchor };
interface Selection {
file: string;
start: SelectionAnchor;
end: SelectionAnchor;
lineIdx: number;
hunkIdx: number;
codeLocation: CodeLocation;
}
import type { Author } from "@bindings/cob/Author";
import type { CodeLocation } from "@bindings/cob/thread/CodeLocation";
import type { Embed } from "@bindings/cob/thread/Embed";
import type { Thread } from "@bindings/cob/thread/Thread";
import type { Config } from "@bindings/config/Config";
import type { FileDiff } from "@bindings/diff/FileDiff";
import type { Modification } from "@bindings/diff/Modification";
import escape from "lodash/escape";
import partial from "lodash/partial";
import * as roles from "@app/lib/roles";
import CommentToggleInput from "@app/components/CommentToggleInput.svelte";
import ThreadComponent from "@app/components/Thread.svelte";
interface Props {
codeComments?: CodeComments;
file: FileDiff;
head: string;
}
const { file, head, codeComments }: Props = $props();
let selection: Selection | undefined = $state(undefined);
function lineNumber(line: Modification, side: Side): number | undefined {
if (side === "left") {
if (line.type === "context") {
return line.lineNoOld;
}
if (line.type === "deletion") {
return line.lineNo;
}
} else {
if (line.type === "context") {
return line.lineNoNew;
}
if (line.type === "addition") {
return line.lineNo;
}
}
}
// A line can carry more than one thread: two reviewers can comment on the
// same line, and a comment can arrive over the network onto a line we just
// commented on ourselves. Return all of them, oldest first, so none is
// shadowed by another.
function findLineThreads(line: Modification) {
return (
(codeComments?.threads ?? [])
.filter(t => {
if (line.type === "addition") {
return t.root.location?.new?.range.end === line.lineNo + 1;
} else if (line.type === "deletion") {
return t.root.location?.old?.range.end === line.lineNo + 1;
} else if (line.type === "context") {
return (
t.root.location?.new?.range.end === line.lineNoNew + 1 ||
t.root.location?.old?.range.end === line.lineNoOld + 1
);
}
})
.sort((a, b) => a.root.edits[0].timestamp - b.root.edits[0].timestamp)
// The keyed `each` below throws on a duplicate key, and the thread list
// is merged from several sources.
.filter(
(t, i, all) => all.findIndex(o => o.root.id === t.root.id) === i,
)
);
}
function determineSelectedAnchor(
side: Side,
line: Modification,
): SelectionAnchor {
if (side === "left" && line.type === "addition") {
return { side: "right", lineNumber: line.lineNo };
} else if (side === "right" && line.type === "deletion") {
return { side: "left", lineNumber: line.lineNo };
} else {
return side === "left"
? { side: "left", lineNumber: lineNumber(line, "left") as number }
: { side: "right", lineNumber: lineNumber(line, "right") as number };
}
}
function filePath(file: FileDiff, side: Side): string {
if (file.status === "moved" || file.status === "copied") {
if (side === "left") {
return file.oldPath;
} else {
return file.newPath;
}
} else {
return file.path;
}
}
function selectLine(
e: MouseEvent,
file: FileDiff,
side: Side,
line: Modification,
hunkIdx: number,
lineIdx: number,
) {
e.preventDefault();
e.stopPropagation();
const commentAnchor = determineSelectedAnchor(side, line);
selection = {
file: filePath(file, side),
start: commentAnchor,
end: commentAnchor,
hunkIdx: hunkIdx,
lineIdx: lineIdx,
codeLocation: {
commit: head,
path: filePath(file, side),
old:
commentAnchor.side === "left"
? {
type: "lines",
range: {
start: commentAnchor.lineNumber,
end: commentAnchor.lineNumber + 1,
},
}
: null,
new:
commentAnchor.side === "right"
? {
type: "lines",
range: {
start: commentAnchor.lineNumber,
end: commentAnchor.lineNumber + 1,
},
}
: null,
},
};
}
function isSelected(file: string, hunkIdx: number, lineIdx: number) {
return (
selection &&
selection.file === file &&
selection.hunkIdx === hunkIdx &&
selection.lineIdx === lineIdx
);
}
function rangeAnchorsFromCodeLocation(
location: CodeLocation | null,
): SelectionRange | undefined {
if (location?.old?.type === "lines") {
return {
start: { side: "left", lineNumber: location.old.range.start },
};
} else if (location?.new?.type === "lines") {
return {
start: { side: "right", lineNumber: location.new.range.start },
};
}
}
</script>
<style>
.container {
/* Make space for the box-shadow border, otherwise it gets cut off due to
overflow: hide on the container. */
padding: 0 0.0625rem 0.5rem;
font: var(--txt-code-regular);
}
.line {
display: flex;
position: relative;
white-space: pre-wrap;
}
/* Hover and selection tint the line directly. The previous approach declared
a `--hover-bg` custom property on every line, which inherits into each of
its cells, and painted it with a full-bleed inset box-shadow. Both are
per-line costs on a diff with thousands of lines; these rules only ever
match the one line being hovered or selected. */
.line.commentable.context:hover,
.line.selected.context {
background-color: color-mix(
in srgb,
var(--color-surface-subtle) 85%,
var(--color-surface-canvas)
);
}
.line.commentable.addition:hover,
.line.selected.addition {
background-color: color-mix(
in srgb,
var(--color-feedback-success-bg) 92%,
var(--color-feedback-success-text) 8%
);
}
.line.commentable.deletion:hover,
.line.selected.deletion {
background-color: color-mix(
in srgb,
var(--color-feedback-error-bg) 92%,
var(--color-feedback-error-text) 8%
);
}
.hunk-header {
color: var(--color-text-secondary);
}
.hunk-header > .left,
.hunk-header > .right {
cursor: default;
}
.addition {
background-color: var(--color-feedback-success-bg);
}
.deletion {
background-color: var(--color-feedback-error-bg);
}
.addition > .left,
.addition > .right,
.addition > .sign {
color: var(--color-feedback-success-text);
}
.deletion > .left,
.deletion > .right,
.deletion > .sign {
color: var(--color-feedback-error-text);
}
.context > .left,
.context > .right,
.context > .sign {
color: var(--color-text-disabled);
}
.marker {
color: var(--color-text-primary) !important;
}
.selected {
z-index: 1;
}
.left,
.right {
min-width: 3rem;
text-align: center;
position: relative;
cursor: default;
}
.comment-add {
position: absolute;
right: 0.5rem;
top: 50%;
width: 1rem;
height: 1rem;
border: 0;
border-radius: 999px;
padding: 0;
background-color: var(--color-surface-brand-secondary);
color: var(--color-text-on-brand);
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
z-index: 2;
transform: translateY(-50%) scale(0);
transform-origin: center;
transition: transform 120ms ease-out;
pointer-events: none;
}
/* The plus is drawn as two bars rather than a "+" glyph, whose optical
centre depends on the font's metrics. Matches the geometry of the `plus`
icon: 10x1px within a 16px box. */
.comment-add::before,
.comment-add::after {
content: "";
position: absolute;
top: 50%;
left: 50%;
background-color: currentColor;
}
.comment-add::before {
width: 0.625rem;
height: 0.0625rem;
transform: translate(-50%, -50%);
}
.comment-add::after {
width: 0.0625rem;
height: 0.625rem;
transform: translate(-50%, -50%);
}
.line.commentable:hover .comment-add {
transform: translateY(-50%) scale(1);
pointer-events: auto;
}
.comment-add:hover,
.comment-add:focus-visible {
background-color: var(--color-brand-hover);
color: var(--color-text-on-brand);
}
.sign {
min-width: 1.5rem;
}
.code {
-webkit-touch-callout: initial;
-webkit-user-select: text;
user-select: text;
width: 100%;
word-break: break-word;
cursor: text;
}
.thread {
background-color: var(--color-surface-base);
font: var(--txt-body-m-regular);
padding: 0.5rem;
}
.comment-form {
background-color: var(--color-surface-base);
display: flex;
flex-direction: column;
font: var(--txt-body-m-regular);
padding: 1rem;
}
.comment-header {
display: flex;
background-color: var(--color-surface-subtle);
border-radius: var(--border-radius-sm);
padding: 0 0.5rem;
width: fit-content;
}
</style>
{#snippet lineDiff(line: Modification, lineIdx: number, hunkIdx: number)}
{@const threads = findLineThreads(line)}
{@const commentSide = line.type === "deletion" ? "left" : "right"}
{@const canComment = Boolean(codeComments?.createComment)}
<div
class="line"
class:commentable={canComment}
class:addition={line.type === "addition"}
class:deletion={line.type === "deletion"}
class:context={line.type === "context"}
class:selected={isSelected(filePath(file, "left"), hunkIdx, lineIdx)}>
{#if canComment}
<!-- The glyph is drawn in CSS rather than with <Icon>: this button
exists on every line of the diff, so an inline SVG here costs two
extra nodes per line on a patch with thousands of them. -->
<button
type="button"
class="comment-add"
aria-label="Add a comment on this line"
title="Add a comment on this line"
onclick={e => selectLine(e, file, commentSide, line, hunkIdx, lineIdx)}>
</button>
{/if}
<div
class="left"
class:marker={selection?.start.side === "left" &&
selection.start.lineNumber === lineNumber(line, "left")}>
{lineNumber(line, "left")}
</div>
<div
class="right"
class:marker={selection?.start.side === "right" &&
selection.start.lineNumber === lineNumber(line, "right")}>
{lineNumber(line, "right")}
</div>
<div class="sign">
{#if line.type === "addition"}
+
{:else if line.type === "deletion"}
-
{/if}
</div>
{#if line.highlight && line.highlight.items.length > 0}
<div class="code">
{@html line.highlight.items
.map(
paint =>
`<span class="global-syntax ${paint.style}">${escape(paint.item)}</span>`,
)
.join("")}
</div>
{:else if line.line !== ""}
<div class="code">{line.line}</div>
{:else}
<div class="code"><br /></div>
{/if}
</div>
{#each threads as thread (thread.root.id)}
{#if codeComments}
{@const isDraftThread =
codeComments.draftThreadIds?.includes(thread.root.id) ?? false}
<!-- Anchors "jump to this comment" from the draft review bar. -->
<div class="thread" data-thread-id={thread.root.id}>
{#if !codeComments.hideThreadFileHeader}
<div class="global-flex" style:padding="0.5rem">
{@render commentHeader(
thread.root.location?.path,
rangeAnchorsFromCodeLocation(thread.root.location),
)}
</div>
{/if}
<ThreadComponent
rid={codeComments.rid}
currentUserNid={codeComments.config.publicKey}
{thread}
inline
draft={isDraftThread}
origin={codeComments.threadOrigins?.[thread.root.id]}
reactOnComment={isDraftThread
? undefined
: codeComments.reactOnComment}
createReply={(codeComments.canReply ?? true)
? async (body, embeds) => {
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)} />
</div>
{/if}
{/each}
{#if codeComments && selection?.hunkIdx === hunkIdx && selection?.lineIdx === lineIdx}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="comment-form"
onpointerdown={e => {
e.stopPropagation();
}}>
<CommentToggleInput
disallowEmptyBody
rid={codeComments.rid}
onclose={() => {
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} />
</div>
{/if}
{/snippet}
{#snippet commentHeader(filePath?: string, selectionRange?: SelectionRange)}
{#if filePath && selectionRange}
<div class="comment-header">
{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}
</div>
{/if}
{/snippet}
<div class="container">
{#if file.diff.type === "plain"}
{#each file.diff.hunks as hunk, hunkIdx}
<div class="line hunk-header">
<div class="left"></div>
<div class="right"></div>
<div class="sign"></div>
<div class="code">{hunk.header}</div>
</div>
<div>
{#each hunk.lines as modification, lineIdx}
{@render lineDiff(modification, lineIdx, hunkIdx)}
{/each}
</div>
{/each}
{/if}
</div>
+5 -1
View File
@@ -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);
}
-524
View File
@@ -1,524 +0,0 @@
<script lang="ts">
import type { Modification } from "@bindings/diff/Modification";
import escape from "lodash/escape";
import partial from "lodash/partial";
import type { CommentContext, SelectionRange } from "@app/lib/diffComments";
import {
findLineThread,
lineNumber,
rangeAnchorsFromCodeLocation,
} from "@app/lib/diffComments";
import type { DiffRow } from "@app/lib/diffRows";
import { fileDiffName, fileDiffPath } from "@app/lib/diffText";
import { getDiffText } from "@app/lib/invoke";
import * as roles from "@app/lib/roles";
import CommentToggleInput from "@app/components/CommentToggleInput.svelte";
import DiffActions from "@app/components/DiffActions.svelte";
import Icon from "@app/components/Icon.svelte";
import Path from "@app/components/Path.svelte";
import ThreadComponent from "@app/components/Thread.svelte";
interface Props {
row: DiffRow;
// Whether the row's file is expanded (only meaningful for file-header rows).
expanded?: boolean;
onToggleFile?: (fileIndex: number) => void;
// Present only on the patch-review path; enables inline comments/selection.
comments?: CommentContext;
// Identifies the commit range this row's diff belongs to, so file-level
// actions can ask the backend for patch text.
diffContext: { rid: string; base?: string; head: string; unified: number };
}
const {
row,
expanded = true,
onToggleFile,
comments,
diffContext,
}: Props = $props();
type LineRow = Extract<DiffRow, { type: "line" }>;
</script>
<style>
.file-gap {
height: 1rem;
}
.file-header {
display: flex;
align-items: center;
gap: 0.5rem;
height: 2.5rem;
/* Horizontal inset of the diff cards. The container sets `--diff-inset`
(e.g. 0 when it already provides its own side padding); falls back to 1rem
when the diff is the full-width scroll content (commit view). */
margin: 0 var(--diff-inset, 1rem);
padding: 0 0.5rem;
background-color: var(--color-surface-canvas);
/* Bottom border present in both states: it's the separator above the lines
when expanded, and the card bottom when standalone. Keeping it always
avoids a 1px reflow when toggling collapse. */
border: 1px solid var(--color-border-subtle);
border-top-left-radius: var(--border-radius-md);
border-top-right-radius: var(--border-radius-md);
font: var(--txt-body-m-regular);
}
.file-header.standalone {
border-bottom-left-radius: var(--border-radius-md);
border-bottom-right-radius: var(--border-radius-md);
}
.collapse {
background: none;
border: none;
padding: 0;
cursor: pointer;
color: var(--color-text-secondary);
display: flex;
align-items: center;
}
.collapse:hover {
color: var(--color-text-primary);
}
.arrow {
padding: 0 0.25rem;
color: var(--color-text-secondary);
}
.status {
padding: 0 0.375rem;
border-radius: var(--border-radius-sm);
}
.status.added {
color: var(--color-feedback-success-text);
background-color: var(--color-feedback-success-bg);
}
.status.deleted {
color: var(--color-feedback-error-text);
background-color: var(--color-feedback-error-bg);
}
.status.moved,
.status.copied {
color: var(--color-text-secondary);
background: var(--color-surface-subtle);
}
.stats {
margin-left: auto;
font: var(--txt-code-regular);
white-space: nowrap;
}
.add {
color: var(--color-feedback-success-text);
}
.del {
color: var(--color-feedback-error-text);
}
.line {
display: flex;
position: relative;
white-space: pre-wrap;
margin: 0 var(--diff-inset, 1rem);
font: var(--txt-code-regular);
border-left: 1px solid var(--color-border-subtle);
border-right: 1px solid var(--color-border-subtle);
background-color: var(--color-surface-canvas);
}
.line.last {
border-bottom: 1px solid var(--color-border-subtle);
border-bottom-left-radius: var(--border-radius-md);
border-bottom-right-radius: var(--border-radius-md);
}
.line.selected {
box-shadow: 0 0 0 1px var(--color-border-brand);
z-index: 1;
}
.hunk-header {
color: var(--color-text-secondary);
}
.file-note {
justify-content: center;
align-items: center;
gap: 0.5rem;
padding: 1rem 0;
font: var(--txt-body-m-regular);
}
.addition {
background-color: var(--color-feedback-success-bg);
}
.deletion {
background-color: var(--color-feedback-error-bg);
}
.addition > .num,
.addition > .sign {
color: var(--color-feedback-success-text);
}
.deletion > .num,
.deletion > .sign {
color: var(--color-feedback-error-text);
}
.context > .num,
.context > .sign {
color: var(--color-text-disabled);
}
.num {
min-width: 3rem;
text-align: center;
flex-shrink: 0;
}
.num.gutter:not(.selection-disabled) {
cursor: cell;
}
.num.gutter:not(.selection-disabled):hover {
color: var(--color-text-primary);
}
.marker {
color: var(--color-text-primary) !important;
}
.sign {
min-width: 1.5rem;
flex-shrink: 0;
}
.code {
-webkit-user-select: text;
user-select: text;
width: 100%;
word-break: break-word;
padding-right: 1rem;
}
.comment-icon {
margin-left: auto;
margin-right: 1rem;
margin-top: 3px;
align-self: flex-start;
}
.thread,
.comment-form {
margin: 0 var(--diff-inset, 1rem);
border-left: 1px solid var(--color-border-subtle);
border-right: 1px solid var(--color-border-subtle);
background-color: var(--color-surface-base);
font: var(--txt-body-m-regular);
}
.thread {
padding: 0.5rem;
}
.comment-form {
display: flex;
flex-direction: column;
padding: 1rem;
}
.thread.last,
.comment-form.last {
border-bottom: 1px solid var(--color-border-subtle);
border-bottom-left-radius: var(--border-radius-md);
border-bottom-right-radius: var(--border-radius-md);
}
.comment-header {
display: flex;
background-color: var(--color-surface-subtle);
border-radius: var(--border-radius-sm);
padding: 0 0.5rem;
width: fit-content;
}
</style>
{#snippet code(line: Modification)}
{#if line.highlight && line.highlight.items.length > 0}
<div class="code">
{@html line.highlight.items
.map(
paint =>
`<span class="global-syntax ${paint.style}">${escape(paint.item)}</span>`,
)
.join("")}
</div>
{:else if line.line !== ""}
<div class="code">{line.line}</div>
{:else}
<div class="code"><br /></div>
{/if}
{/snippet}
{#snippet commentHeader(filePath?: string, selectionRange?: SelectionRange)}
{#if filePath && selectionRange}
<div class="comment-header">
{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}
</div>
{/if}
{/snippet}
{#snippet readonlyLine(r: LineRow)}
{@const line = r.modification}
<div
class="line"
class:addition={line.type === "addition"}
class:deletion={line.type === "deletion"}
class:context={line.type === "context"}
class:last={r.last}>
<div class="num">{lineNumber(line, "left") ?? ""}</div>
<div class="num">{lineNumber(line, "right") ?? ""}</div>
<div class="sign">
{#if line.type === "addition"}+{:else if line.type === "deletion"}-{/if}
</div>
{@render code(line)}
</div>
{/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}
<div
class="line"
class:addition={line.type === "addition"}
class:deletion={line.type === "deletion"}
class:context={line.type === "context"}
class:selected={thread === undefined && isSel}
class:last={closeOnLine}>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="num gutter"
class:selection-disabled={!selectable}
class:marker={inFile &&
sel.start.side === "left" &&
sel.start.lineNumber === lineNumber(line, "left")}
onpointerdown={e => {
if (selectable) {
e.preventDefault();
e.stopPropagation();
ctx.onSelectLine(
r.fileIndex,
"left",
line,
r.hunkIndex,
r.lineIndex,
r.file,
);
}
}}>
{lineNumber(line, "left") ?? ""}
</div>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="num gutter"
class:selection-disabled={!selectable}
class:marker={inFile &&
sel.start.side === "right" &&
sel.start.lineNumber === lineNumber(line, "right")}
onpointerdown={e => {
if (selectable) {
e.preventDefault();
e.stopPropagation();
ctx.onSelectLine(
r.fileIndex,
"right",
line,
r.hunkIndex,
r.lineIndex,
r.file,
);
}
}}>
{lineNumber(line, "right") ?? ""}
</div>
<div class="sign">
{#if line.type === "addition"}+{:else if line.type === "deletion"}-{/if}
</div>
{@render code(line)}
{#if thread}
<div class="global-flex comment-icon">
<Icon
name={thread.root.resolved ? "comment-checkmark" : "comment-cross"}
onclick={() => ctx.onToggleThread(thread.root.id)} />
</div>
{/if}
</div>
{#if showThread && thread}
<div class="thread" class:last={closeOnThread}>
<div class="global-flex" style:padding="0.5rem">
{@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 )}
<div style:margin-left="auto">
{#if thread.root.resolved}
<div title="Unresolve comment thread">
<Icon
name="close"
onclick={partial(
cc.changeCommentStatus,
thread.root.id,
false,
)} />
</div>
{:else}
<div title="Resolve comment thread">
<Icon
name="checkmark"
onclick={partial(
cc.changeCommentStatus,
thread.root.id,
true,
)} />
</div>
{/if}
</div>
{/if}
</div>
<ThreadComponent
inline
rid={cc.rid}
currentUserNid={cc.config.publicKey}
{thread}
reactOnComment={cc.reactOnComment}
createReply={(cc.canReply ?? true)
? async (body, embeds) => {
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} />
</div>
{/if}
{#if isSel && sel}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="comment-form"
class:last={closeOnForm}
onpointerdown={e => {
e.stopPropagation();
}}>
<div style:margin-bottom="1rem">
{@render commentHeader(sel.file, { start: sel.start })}
</div>
<CommentToggleInput
disallowEmptyBody
rid={cc.rid}
onclose={() => 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();
}
}} />
</div>
{/if}
{/snippet}
{#if row.type === "file-gap"}
<div class="file-gap"></div>
{:else if row.type === "file-header"}
<div class="file-header" class:standalone={row.standalone}>
<button
class="collapse"
onclick={() => onToggleFile?.(row.fileIndex)}
title={expanded ? "Collapse file" : "Expand file"}>
<Icon name={expanded ? "chevron-down" : "chevron-right"} />
</button>
{#if row.file.status === "moved" || row.file.status === "copied"}
<Path fullPath={row.file.oldPath} />
<span class="arrow">→</span>
<Path fullPath={row.file.newPath} />
{:else}
<Path fullPath={row.file.path} />
{/if}
{#if row.file.status === "added"}
<span class="status added">Added</span>
{:else if row.file.status === "deleted"}
<span class="status deleted">Deleted</span>
{:else if row.file.status === "moved"}
<span class="status moved">Moved</span>
{:else if row.file.status === "copied"}
<span class="status copied">Copied</span>
{/if}
<span class="stats">
{#if row.file.diff.type === "plain" && row.file.diff.hunks.length > 0}
<span class="add">+{row.file.diff.stats.additions}</span>
<span class="del">-{row.file.diff.stats.deletions}</span>
{/if}
</span>
{#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}
<div class="global-flex">
<Icon name="comment-cross" />
{counts.unresolved}
</div>
{/if}
{#if counts !== undefined && counts.resolved > 0}
<div class="global-flex">
<Icon name="comment-checkmark" />
{counts.resolved}
</div>
{/if}
{/if}
<DiffActions
text={() =>
getDiffText(
diffContext.rid,
diffContext.base,
diffContext.head,
diffContext.unified,
fileDiffPath(row.file),
)}
fileName={fileDiffName(row.file)}
title="File diff actions" />
</div>
{:else if row.type === "hunk-header"}
<div class="line hunk-header">
<div class="num"></div>
<div class="num"></div>
<div class="sign"></div>
<div class="code">{row.header}</div>
</div>
{:else if row.type === "file-note"}
<div class="line last file-note">
{#if row.note === "binary"}
<Icon name="binary" />
Binary file
{:else}
Empty file
{/if}
</div>
{:else if comments}
{@render interactiveLine(row, comments)}
{:else}
{@render readonlyLine(row)}
{/if}
+239 -57
View File
@@ -1,23 +1,32 @@
<script lang="ts">
<script lang="ts" module>
export interface ActivityItem<T = unknown> {
key: string;
timestamp: number;
data: T;
}
</script>
<script lang="ts" generics="A">
import type { Author } from "@bindings/cob/Author";
import type { Embed } from "@bindings/cob/thread/Embed";
import type { Thread } from "@bindings/cob/thread/Thread";
import type { Config } from "@bindings/config/Config";
import type { Snippet } from "svelte";
import partial from "lodash/partial";
import sum from "lodash/sum";
import * as roles from "@app/lib/roles";
import { authorForNodeId } from "@app/lib/utils";
import Button from "@app/components/Button.svelte";
import ExtendedTextarea from "@app/components/ExtendedTextarea.svelte";
import Icon from "@app/components/Icon.svelte";
import NodeId from "@app/components/NodeId.svelte";
import ThreadComponent from "@app/components/Thread.svelte";
interface Props {
cobId: string;
commentThreads: Thread[];
config: Config;
repoDelegates: Author[];
createComment: (
body: string,
embeds: Embed[],
@@ -33,8 +42,11 @@
authors: Author[],
reaction: string,
) => Promise<void>;
repoDelegates: Author[];
rid: string;
activityItems?: ActivityItem<A>[];
renderActivity?: Snippet<[A, { hideAuthor: boolean }]>;
authorOf?: (data: A) => Author | undefined;
afterActivity?: Snippet;
}
/* eslint-disable prefer-const */
@@ -42,83 +54,253 @@
cobId,
commentThreads,
config,
repoDelegates,
createComment,
editComment,
reactOnComment,
repoDelegates,
rid,
activityItems,
renderActivity,
authorOf,
afterActivity,
}: Props = $props();
/* eslint-enable prefer-const */
let previousCobId: string | undefined;
// svelte-ignore state_referenced_locally
let previousCobId = cobId;
let focusReply: boolean = $state(false);
let commentFormKey = $state(0);
let hideDiscussion = $state(false);
type TimelineEntry =
| { kind: "thread"; key: string; timestamp: number; thread: Thread }
| { kind: "activity"; key: string; timestamp: number; data: A };
const timeline: TimelineEntry[] = $derived(
[
...commentThreads.map(
thread =>
({
kind: "thread",
key: thread.root.id,
timestamp: thread.root.edits[0].timestamp,
thread,
}) satisfies TimelineEntry,
),
...(activityItems ?? []).map(
item =>
({
kind: "activity",
key: item.key,
timestamp: item.timestamp,
data: item.data,
}) satisfies TimelineEntry,
),
].sort((a, b) => a.timestamp - b.timestamp),
);
function entryAuthor(entry: TimelineEntry): Author | undefined {
if (entry.kind === "thread") {
return entry.thread.root.author;
}
return authorOf?.(entry.data);
}
type Run =
| { kind: "thread"; entry: Extract<TimelineEntry, { kind: "thread" }> }
| {
kind: "single";
entry: Extract<TimelineEntry, { kind: "activity" }>;
repeatsAuthor: boolean;
}
| {
kind: "group";
author: Author;
entries: Extract<TimelineEntry, { kind: "activity" }>[];
repeatsAuthor: boolean;
};
function runAuthor(run: Run): Author | undefined {
if (run.kind === "thread") return run.entry.thread.root.author;
if (run.kind === "single") return entryAuthor(run.entry);
return run.author;
}
const runs: Run[] = $derived.by(() => {
const result: Run[] = [];
for (const entry of timeline) {
if (entry.kind === "thread") {
result.push({ kind: "thread", entry });
continue;
}
const author = entryAuthor(entry);
const last = result[result.length - 1];
if (
author &&
last &&
((last.kind === "single" &&
entryAuthor(last.entry)?.did === author.did) ||
(last.kind === "group" && last.author.did === author.did))
) {
if (last.kind === "single") {
result[result.length - 1] = {
kind: "group",
author,
entries: [last.entry, entry],
repeatsAuthor: last.repeatsAuthor,
};
} else {
last.entries.push(entry);
}
} else {
result.push({ kind: "single", entry, repeatsAuthor: false });
}
}
// A run only names its author when the run before it was someone else's.
// A comment breaks a run, so without this the same person's actions are
// re-attributed on the other side of their own comment.
for (let i = 1; i < result.length; i++) {
const run = result[i];
if (run.kind === "thread") continue;
const previous = runAuthor(result[i - 1]);
const current = runAuthor(run);
run.repeatsAuthor = Boolean(
previous && current && previous.did === current.did,
);
}
return result;
});
$effect(() => {
if (previousCobId !== undefined && cobId !== previousCobId) {
hideDiscussion = false;
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
cobId;
if (cobId !== previousCobId) {
previousCobId = cobId;
focusReply = false;
commentFormKey += 1;
}
previousCobId = cobId;
});
</script>
<style>
.connector {
.timeline-rail {
position: relative;
}
.activity-stream {
position: relative;
}
.activity-stream::before {
content: "";
position: absolute;
top: 0.5rem;
bottom: -1rem;
left: 1rem;
width: 1px;
height: 1rem;
margin-left: 1.25rem;
background-color: var(--color-border-subtle);
pointer-events: none;
z-index: -1;
}
.timeline-rail :global(.icon) {
background-color: var(--color-surface-canvas);
}
.timeline-rail :global(.timeline-item.toggleable:hover .icon),
.timeline-rail :global(.timeline-item.toggleable:focus-visible .icon),
.timeline-rail :global(.older-revisions:hover .icon),
.timeline-rail :global(.older-revisions:focus-visible .icon) {
background-color: var(--color-surface-subtle);
}
.timeline-rail :global(.verdict-accept .icon),
.timeline-rail :global(.verdict-reject .icon),
.timeline-rail :global(.verdict-comment .icon),
.timeline-rail :global(.merge-badge .icon) {
background-color: transparent;
}
.timeline-rail :global(.replies-wrapper) {
margin-left: 1.5rem;
}
.timeline-rail :global(.replies-wrapper)::before {
display: none;
}
.connector {
height: 0.5rem;
}
/* Grouped actions are bare rows whose own min-height already spaces them;
the connector on top of that leaves more air between them than between
the header and the first row. The last one is kept: it separates the
group from whatever follows. */
.run-children > .connector:not(:last-child) {
height: 0;
}
.run-header {
position: relative;
display: flex;
align-items: center;
gap: 0.375rem;
padding: 1.5rem 0.5rem 0.5rem;
color: var(--color-text-tertiary);
min-height: 2.5rem;
}
/* The first group's top padding is redundant with the space the timeline
container already leaves below the tabs, so drop it to tighten the gap
between the patch nav and the first author. */
.activity-stream > .run-header:first-child {
padding-top: 0;
}
/* A first child with its own top margin (e.g. a revision card) would push
that margin out above the group, leaving the rail to span a wider gap than
the rest of the group's spacing. */
.run-children > :global(:first-child) {
margin-top: 0;
}
.reply-wrapper {
margin-top: 1rem;
}
</style>
<div style:margin={hideDiscussion ? "1.5rem 0" : "1.5rem 0 2.5rem 0"}>
<div class="global-flex">
<div class="global-flex">
<Button
variant="naked"
disabled={commentThreads.length === 0}
onclick={() => (hideDiscussion = !hideDiscussion)}>
<Icon name={hideDiscussion ? "chevron-right" : "chevron-down"} />
</Button>
<div
class="txt-body-m-regular global-flex"
style:color={commentThreads.length === 0
? "var(--color-text-disabled)"
: undefined}>
Discussion <span>
{sum(
commentThreads.map(t => {
return t.replies.length + 1;
}),
)}
</span>
</div>
</div>
</div>
<div
style:display={hideDiscussion ? "none" : "revert"}
style:margin-top="1rem">
{#each commentThreads as thread}
<ThreadComponent
{thread}
{rid}
currentUserNid={config.publicKey}
canEditComment={partial(
roles.isDelegateOrAuthor,
config.publicKey,
repoDelegates.map(delegate => delegate.did),
)}
{editComment}
createReply={createComment}
{reactOnComment} />
<div class="connector"></div>
{/each}
<div style:margin="1.5rem 0 2.5rem 0">
<div class="timeline-rail">
<div class="activity-stream">
{#each runs as run, runIndex (runIndex)}
{#if run.kind === "thread"}
<ThreadComponent
thread={run.entry.thread}
{rid}
currentUserNid={config.publicKey}
canModifyComment={partial(
roles.isDelegateOrAuthor,
config.publicKey,
repoDelegates.map(delegate => delegate.did),
)}
{editComment}
createReply={createComment}
{reactOnComment} />
<div class="connector"></div>
{:else if run.kind === "single" && renderActivity}
{@render renderActivity(run.entry.data, {
hideAuthor: run.repeatsAuthor,
})}
<div class="connector"></div>
{:else if run.kind === "group" && renderActivity}
{#if !run.repeatsAuthor}
<div class="run-header">
<NodeId
{...authorForNodeId(run.author)}
styleFont="var(--txt-body-m-medium)" />
</div>
{/if}
<div class="run-children">
{#each run.entries as entry (entry.key)}
{@render renderActivity(entry.data, { hideAuthor: true })}
<div class="connector"></div>
{/each}
</div>
{/if}
{/each}
<div id={`reply-${cobId}`}>
{@render afterActivity?.()}
</div>
<div id={`reply-${cobId}`} class="reply-wrapper">
{#key commentFormKey}
<ExtendedTextarea
disallowEmptyBody
+839
View File
@@ -0,0 +1,839 @@
<script lang="ts">
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<void>;
onPublish: (revisionId: string) => Promise<void>;
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<typeof setTimeout> | 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<typeof setTimeout> | 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);
</script>
<style>
.bar {
flex-shrink: 0;
margin: 0 1rem 1rem;
background-color: var(--color-surface-canvas);
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
box-shadow: var(--elevation-low);
padding: 1rem;
display: flex;
flex-direction: row;
align-items: center;
gap: 1.5rem;
}
.bar.expanded {
flex-direction: column;
align-items: stretch;
gap: 0.75rem;
}
.actions {
display: flex;
align-items: center;
gap: 1.5rem;
}
.summary {
flex: 1;
min-width: 0;
box-sizing: border-box;
background: transparent;
border: 0;
outline: none;
font: var(--txt-body-m-regular);
color: var(--color-text-primary);
padding: 0.25rem 0;
resize: none;
overflow-y: auto;
line-height: 1.4;
max-height: 12rem;
}
.bar.expanded .summary {
flex: 0 1 auto;
width: 100%;
}
.summary::placeholder {
color: var(--color-text-quaternary);
}
.status {
display: flex;
align-items: center;
gap: 0.5rem;
color: var(--color-text-quaternary);
font: var(--txt-body-m-regular);
}
.chip {
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-sm);
padding: 0.125rem 0.5rem;
color: var(--color-text-primary);
}
.saved-count {
position: relative;
display: inline-flex;
align-items: center;
gap: 0.25rem;
}
.comments-tooltip {
position: absolute;
bottom: 100%;
right: 0;
left: auto;
z-index: 10;
width: min(28rem, calc(100vw - 2rem));
max-height: 24rem;
overflow-y: auto;
background-color: var(--color-surface-canvas);
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-sm);
box-shadow: var(--elevation-low);
padding: 0.5rem 0;
margin-bottom: 0.5rem;
}
.comments-tooltip::after {
content: "";
position: absolute;
top: 100%;
left: 0;
right: 0;
height: 0.5rem;
}
.comments-tooltip-header {
padding: 0.25rem 0.75rem 0.5rem;
color: var(--color-text-tertiary);
border-bottom: 1px solid var(--color-border-subtle);
}
.comments-tooltip-list {
list-style: none;
margin: 0;
padding: 0;
}
.comments-tooltip-item {
display: flex;
flex-direction: column;
gap: 0.25rem;
padding: 0.5rem 0.75rem;
border-bottom: 1px solid var(--color-border-subtle);
}
.comments-tooltip-item:last-child {
border-bottom: none;
}
.comments-tooltip-item-header {
display: flex;
align-items: center;
gap: 0.5rem;
min-height: 1.25rem;
}
.comments-tooltip-location {
color: var(--color-text-tertiary);
font-family: var(--font-family-monospace);
overflow-wrap: anywhere;
flex: 1 1 auto;
min-width: 0;
}
button.comments-tooltip-location.is-link {
background: none;
border: 0;
padding: 0;
text-align: left;
cursor: pointer;
}
button.comments-tooltip-location.is-link:hover,
button.comments-tooltip-location.is-link:focus-visible {
color: var(--color-text-primary);
text-decoration: underline;
}
.comments-tooltip-actions {
display: flex;
align-items: center;
gap: 0.25rem;
margin-left: auto;
opacity: 0;
transition: opacity 100ms ease;
}
.comments-tooltip-item:hover .comments-tooltip-actions,
.comments-tooltip-item:focus-within .comments-tooltip-actions {
opacity: 1;
}
.comments-tooltip-action {
background: none;
border: 1px solid transparent;
cursor: pointer;
color: var(--color-text-tertiary);
padding: 0.125rem;
border-radius: var(--border-radius-sm);
display: inline-flex;
align-items: center;
justify-content: center;
}
.comments-tooltip-action:hover,
.comments-tooltip-action:focus-visible {
color: var(--color-text-primary);
background-color: var(--color-surface-subtle);
}
.comments-tooltip-action.confirming {
color: var(--color-feedback-error-text);
background-color: var(--color-feedback-error-bg);
}
.comments-tooltip-body {
color: var(--color-text-primary);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.comments-tooltip-edit {
width: 100%;
box-sizing: border-box;
background-color: var(--color-surface-subtle);
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-sm);
outline: none;
color: var(--color-text-primary);
font: inherit;
padding: 0.25rem 0.5rem;
resize: vertical;
}
.comments-tooltip-edit:focus {
border-color: var(--color-border-default);
}
.comments-tooltip-edit-actions {
display: flex;
justify-content: flex-end;
gap: 0.25rem;
}
.split-button {
display: flex;
align-items: stretch;
gap: 0.25rem;
}
.publish-wrap {
display: inline-flex;
}
.verdict-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
border: none;
border-radius: var(--border-radius-sm);
height: 2rem;
padding: 0 0.5rem;
cursor: pointer;
white-space: nowrap;
-webkit-user-select: none;
user-select: none;
transition: background-color 0.1s ease;
color: var(--color-text-on-brand);
}
.verdict-btn:disabled {
cursor: default;
opacity: 0.6;
}
.publish-error {
display: inline-flex;
align-items: center;
gap: 0.25rem;
white-space: nowrap;
color: var(--color-feedback-error-text);
}
.verdict-btn.accept {
background-color: var(--color-feedback-success-fill);
}
.verdict-btn.accept:hover:not(:disabled) {
background-color: var(--color-feedback-success-fill-hover);
}
.verdict-btn.accept:active:not(:disabled),
.verdict-btn.accept.active:not(:disabled) {
background-color: var(--color-feedback-success-fill-active);
}
.verdict-btn.reject {
background-color: var(--color-feedback-error-fill);
}
.verdict-btn.reject:hover:not(:disabled) {
background-color: var(--color-feedback-error-fill-hover);
}
.verdict-btn.reject:active:not(:disabled),
.verdict-btn.reject.active:not(:disabled) {
background-color: var(--color-feedback-error-fill-active);
}
.verdict-btn.comment {
background-color: var(--color-surface-brand-secondary);
}
.verdict-btn.comment:active:not(:disabled),
.verdict-btn.comment.active:not(:disabled) {
background-color: var(--color-surface-brand-primary);
}
.verdict-btn.caret {
width: 2rem;
padding: 0;
}
.verdict-menu {
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-canvas);
width: 22rem;
overflow: hidden;
}
.verdict-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);
}
.verdict-option:last-child {
border-bottom: none;
}
.verdict-option:hover {
background-color: var(--color-surface-subtle);
}
.verdict-check {
display: flex;
align-items: center;
justify-content: center;
height: 1.25rem;
color: var(--color-text-primary);
}
.verdict-text {
display: flex;
flex-direction: column;
gap: 0.125rem;
}
.verdict-label {
font: var(--txt-body-m-medium);
color: var(--color-text-primary);
}
.verdict-description {
font: var(--txt-body-s-regular);
color: var(--color-text-tertiary);
white-space: normal;
}
.confirm-discard {
display: flex;
flex-direction: column;
gap: 0.75rem;
padding: 0.75rem;
min-width: 16rem;
}
.confirm-discard-text {
color: var(--color-text-primary);
}
.confirm-discard-actions {
display: flex;
justify-content: flex-end;
gap: 0.5rem;
}
.confirm-discard-button {
display: inline-flex;
align-items: center;
gap: 0.5rem;
height: 2rem;
padding: 0 0.75rem;
border: 0;
border-radius: var(--border-radius-sm);
background-color: var(--color-feedback-error-fill);
color: var(--color-text-on-brand);
cursor: pointer;
transition: background-color 0.1s ease;
}
.confirm-discard-button:hover:not(:disabled),
.confirm-discard-button:focus-visible:not(:disabled) {
background-color: var(--color-feedback-error-fill-hover);
}
.confirm-discard-button:active:not(:disabled) {
background-color: var(--color-feedback-error-fill-active);
}
.confirm-discard-button:disabled {
cursor: default;
opacity: 0.6;
}
</style>
<div
class="bar"
class:expanded
in:fly={{ y: 120, duration: 260, easing: backOut }}
out:fly={{ y: 120, duration: 180, easing: cubicIn }}>
<textarea
bind:this={summaryEl}
class="summary"
rows="1"
placeholder={summaryRequired
? "Add a review summary"
: "Add an optional review summary"}
bind:value={summary}
oninput={autoResizeSummary}
onblur={persistSummary}>
</textarea>
<div class="actions">
<div class="status">
{#if publishError}
<span class="publish-error" title={publishError}>
<Icon name="warning" />
Not published — your draft is safe. Try again.
</span>
{:else}
<span class="chip">Draft saved</span>
{/if}
{#if filesTotal !== undefined && filesChecked !== undefined}
<span class="saved-count" title="Files reviewed in this revision">
<Icon name="document" />
{filesChecked}/{filesTotal}
</span>
{/if}
<span
role="status"
class="saved-count"
onmouseenter={openTooltip}
onmouseleave={scheduleHideTooltip}>
<Icon name="comment" />
{pendingCommentCount}
{#if showCommentsTooltip && pendingCommentCount > 0}
<div
class="comments-tooltip"
onmouseenter={openTooltip}
onmouseleave={scheduleHideTooltip}
role="presentation">
<div class="comments-tooltip-header txt-body-s-medium">
{pendingCommentCount}
{pendingCommentCount === 1 ? "comment" : "comments"}
</div>
<ul class="comments-tooltip-list">
{#each pendingComments as comment (comment.id)}
{@const body =
comment.edits[comment.edits.length - 1]?.body ?? ""}
<li class="comments-tooltip-item">
<div class="comments-tooltip-item-header">
{#if comment.location}
{#if onSelectComment}
<button
type="button"
class="comments-tooltip-location is-link txt-body-s-regular"
title="Jump to this comment in the diff"
onclick={() => {
showCommentsTooltip = false;
onSelectComment(comment);
}}>
{formatLocation(comment.location)}
</button>
{:else}
<div
class="comments-tooltip-location txt-body-s-regular">
{formatLocation(comment.location)}
</div>
{/if}
{/if}
{#if editingCommentId !== comment.id}
<div class="comments-tooltip-actions">
<button
type="button"
class="comments-tooltip-action"
title="Edit"
onclick={() => startEdit(comment.id, body)}>
<Icon name="edit" />
</button>
<button
type="button"
class="comments-tooltip-action"
class:confirming={confirmDeleteId === comment.id}
title={confirmDeleteId === comment.id
? "Click again to confirm"
: "Delete"}
onclick={() => requestDeleteComment(comment.id)}>
<Icon
name={confirmDeleteId === comment.id
? "checkmark"
: "trash"} />
</button>
</div>
{/if}
</div>
{#if editingCommentId === comment.id}
<textarea
class="comments-tooltip-edit txt-body-m-regular"
bind:value={editBody}
rows="3">
</textarea>
<div class="comments-tooltip-edit-actions">
<Button variant="outline" onclick={cancelEdit}>
Cancel
</Button>
<Button
variant="secondary"
onclick={() => saveEdit(comment.id)}>
Save
</Button>
</div>
{:else}
<div class="comments-tooltip-body txt-body-m-regular">
{body}
</div>
{/if}
</li>
{/each}
</ul>
</div>
{/if}
</span>
</div>
<div style:margin-left="auto" style:display="flex" style:gap="0.5rem">
<Popover
popoverPadding="0"
placement="top-start"
bind:expanded={discardMenuExpanded}>
{#snippet toggle(onclick)}
<Button
variant="outline"
disabled={publishing}
active={discardMenuExpanded}
{onclick}>
Discard
</Button>
{/snippet}
{#snippet popover()}
<div
style:border="1px solid var(--color-border-subtle)"
style:border-radius="var(--border-radius-sm)"
style:background-color="var(--color-surface-canvas)">
<div class="confirm-discard">
<div class="confirm-discard-text txt-body-m-regular">
Discard this draft review? Your comments and verdict will be
lost.
</div>
<div class="confirm-discard-actions">
<Button
variant="outline"
disabled={publishing}
onclick={() => (discardMenuExpanded = false)}>
Cancel
</Button>
<button
type="button"
class="confirm-discard-button txt-body-m-medium"
disabled={publishing}
onclick={() => {
discardMenuExpanded = false;
onCancel();
}}>
<Icon name="trash" />
Discard
</button>
</div>
</div>
</div>
{/snippet}
</Popover>
<div class="split-button">
<!-- Wrapper carries the title: a disabled <button> won't show one. -->
<span
class="publish-wrap"
title={alreadyReviewed
? "You already published a review of this revision, and the protocol keeps one review per author per revision. Comment on the changes directly to add to it."
: summaryRequired && summary.trim() === ""
? "Review summary required"
: undefined}>
<button
class="verdict-btn txt-body-m-medium {verdictColorClass}"
disabled={publishDisabled}
onclick={publish}>
{verdictLabel}
</button>
</span>
<Popover
popoverPadding="0"
placement="top-end"
bind:expanded={dropdownExpanded}>
{#snippet toggle(onclick)}
<button
class="verdict-btn caret {verdictColorClass}"
class:active={dropdownExpanded}
disabled={publishing}
{onclick}>
<Icon name={dropdownExpanded ? "chevron-up" : "chevron-down"} />
</button>
{/snippet}
{#snippet popover()}
<div class="verdict-menu">
{#each verdictOptions as option (option.label)}
<!-- svelte-ignore a11y_click_events_have_key_events -->
<div
role="button"
tabindex="0"
class="verdict-option"
onclick={() => {
verdict = option.value;
draftReviewStorage.update(draftReview.id, {
summary,
verdict: option.value,
labels: draftReview.labels,
});
closeFocused();
void onChange();
}}>
<div class="verdict-check">
{#if verdict === option.value}
<Icon name="checkmark" />
{/if}
</div>
<div class="verdict-text">
<span class="verdict-label">{option.label}</span>
<span class="verdict-description">
{option.description}
</span>
</div>
</div>
{/each}
</div>
{/snippet}
</Popover>
</div>
</div>
</div>
</div>
+213 -53
View File
@@ -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<string, Embed>;
}) => Promise<void>;
submitDescription?: string;
secondarySubmit?: {
caption: string;
description?: string;
submit: (opts: {
comment: string;
embeds: Map<string, Embed>;
}) => Promise<void>;
};
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;
}
</style>
<div class="comment-section" aria-label="extended-textarea" class:inline>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="comment-section"
aria-label="extended-textarea"
class:inline
onkeydown={event => {
if (!preview) return;
const auxiliarKey = utils.isMac() ? event.metaKey : event.ctrlKey;
if (auxiliarKey && event.key === "Enter") {
event.preventDefault();
void submit({ comment: body, embeds });
}
}}>
<div class="textarea-wrap">
{#if preview}
<div class="preview" style:min-height={styleMinHeight}>
@@ -399,25 +483,15 @@
<span class="global-hide-on-small-desktop-down">Discard</span>
</Button>
{/if}
{#if !preview}
<div
style:display=""
class="txt-overflow txt-body-m-regular txt-missing"
title="Markdown is supported.">
{#if embedUploadError}
<span style:color="var(--color-feedback-error-text)">
<Icon
styleDisplay="inline"
styleVerticalAlign="text-top"
name="warning" />
{embedUploadError}
</span>
{/if}
<Icon
name="markdown"
styleDisplay="inline"
styleVerticalAlign="text-top" />
Markdown is supported.
{#if !preview && embedUploadError}
<div class="txt-overflow txt-body-m-regular">
<span style:color="var(--color-feedback-error-text)">
<Icon
styleDisplay="inline"
styleVerticalAlign="text-top"
name="warning" />
{embedUploadError}
</span>
</div>
{/if}
<div class="buttons">
@@ -435,21 +509,107 @@
<Icon name={preview ? "edit" : "eye"} />
{preview ? "Edit" : "Preview"}
</Button>
<Button
variant={effectiveSubmitVariant}
title={emptyBodyTooltip}
disabled={!isValid() ||
submitInProgress ||
disableSubmit ||
(disallowEmptyBody && body.trim() === "")}
onclick={submitFn}>
{#if submitInProgress}
Saving…
{:else}
{submitCaption}
<span class="shortcut">{utils.modifierKey()}↵</span>
{/if}
</Button>
{#if secondarySubmit}
<div class="split-submit">
<Button
variant={effectiveSubmitVariant}
title={emptyBodyTooltip}
disabled={!isValid() ||
submitInProgress ||
disableSubmit ||
(disallowEmptyBody && body.trim() === "")}
onclick={submitFn}>
{#if submitInProgress}
Saving…
{:else}
{activeSubmit.caption}
<span class="shortcut">{utils.modifierKey()}↵</span>
{/if}
</Button>
<Popover
popoverPadding="0"
placement="top-end"
bind:expanded={dropdownExpanded}>
{#snippet toggle(onclick)}
<Button
variant={effectiveSubmitVariant}
disabled={submitInProgress}
{onclick}>
<Icon
name={dropdownExpanded ? "chevron-up" : "chevron-down"} />
</Button>
{/snippet}
{#snippet popover()}
<div class="submit-menu">
<!-- svelte-ignore a11y_click_events_have_key_events -->
<div
role="button"
tabindex="0"
class="submit-option"
onclick={() => {
activeSubmitIndex = 0;
closeFocused();
}}>
<div class="submit-check">
{#if activeSubmitIndex === 0}
<Icon name="checkmark" />
{/if}
</div>
<div class="submit-text">
<span class="submit-label">{submitCaption}</span>
{#if submitDescription}
<span class="submit-description">
{submitDescription}
</span>
{/if}
</div>
</div>
<!-- svelte-ignore a11y_click_events_have_key_events -->
<div
role="button"
tabindex="0"
class="submit-option"
onclick={() => {
activeSubmitIndex = 1;
closeFocused();
}}>
<div class="submit-check">
{#if activeSubmitIndex === 1}
<Icon name="checkmark" />
{/if}
</div>
<div class="submit-text">
<span class="submit-label">
{secondarySubmit.caption}
</span>
{#if secondarySubmit.description}
<span class="submit-description">
{secondarySubmit.description}
</span>
{/if}
</div>
</div>
</div>
{/snippet}
</Popover>
</div>
{:else}
<Button
variant={effectiveSubmitVariant}
title={emptyBodyTooltip}
disabled={!isValid() ||
submitInProgress ||
disableSubmit ||
(disallowEmptyBody && body.trim() === "")}
onclick={submitFn}>
{#if submitInProgress}
Saving…
{:else}
{submitCaption}
<span class="shortcut">{utils.modifierKey()}↵</span>
{/if}
</Button>
{/if}
</div>
</div>
{/if}
+115 -24
View File
@@ -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" });
}
}
</script>
<style>
.header {
display: flex;
align-items: center;
height: 2.5rem;
min-height: 2.5rem;
padding-left: 0.25rem;
z-index: 2;
font: var(--txt-body-m-regular);
@@ -46,6 +68,17 @@
border-top-left-radius: var(--border-radius-md);
border-top-right-radius: var(--border-radius-md);
}
.header:not(:first-child) {
margin-top: 0.5rem;
}
.header.expandable {
cursor: pointer;
transition: background-color 0.1s ease-in-out;
}
.header.expandable:hover,
.header.expandable:focus-visible {
background-color: var(--color-surface-subtle);
}
.header.collapsed {
border-bottom-left-radius: var(--border-radius-md);
border-bottom-right-radius: var(--border-radius-md);
@@ -64,6 +97,36 @@
flex: 1;
min-width: 0;
}
.toggle-icon {
width: 1.5rem;
display: flex;
justify-content: center;
color: var(--color-text-secondary);
}
.icon-stack {
display: grid;
}
.icon-default,
.icon-hover {
grid-area: 1 / 1;
transition:
opacity 150ms ease,
transform 150ms ease;
}
.icon-hover {
opacity: 0;
transform: rotate(-90deg);
}
.header.expandable:hover .icon-default,
.header.expandable:focus-visible .icon-default {
opacity: 0;
transform: rotate(90deg);
}
.header.expandable:hover .icon-hover,
.header.expandable:focus-visible .icon-hover {
opacity: 1;
transform: rotate(0);
}
.container {
position: relative;
@@ -73,32 +136,54 @@
border-bottom-left-radius: var(--border-radius-md);
border-bottom-right-radius: var(--border-radius-md);
}
.collapsible {
display: grid;
grid-template-rows: 0fr;
transition: grid-template-rows 180ms ease-out;
}
.collapsible.open {
grid-template-rows: 1fr;
}
.collapsible-inner {
overflow: hidden;
min-height: 0;
}
</style>
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
<div
class="header"
class:expandable
class:sticky
class:collapsed={!expanded}
bind:this={header}
style:--header-background={headerBackground}
role={expandable ? "button" : undefined}
tabindex={expandable ? 0 : undefined}
style:border={border ? "1px solid var(--color-border-subtle)" : undefined}
style:border-bottom={border
? "undefined"
: "1px solid var(--color-border-subtle)"}>
: "1px solid var(--color-border-subtle)"}
onclick={toggleExpanded}
onkeydown={async event => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
await toggleExpanded();
}
}}>
<div class="left">
{#if expandable}
<Button
variant="naked"
onclick={async () => {
expanded = !expanded;
if (!expanded && header) {
await tick();
header.scrollIntoView({ behavior: "smooth", block: "nearest" });
}
}}>
<Icon name={expanded ? "chevron-down" : "chevron-right"} />
</Button>
{/if}
<div class="toggle-icon" style:padding="0 0.5rem">
{#if expandable}
<span class="icon-stack">
<span class="icon-default"><Icon name="document" /></span>
<span class="icon-hover">
<Icon name={expanded ? "collapse-vertical" : "expand-vertical"} />
</span>
</span>
{:else}
<Icon name="document" />
{/if}
</div>
{@render leftHeader?.()}
</div>
{#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()}
</div>
{/if}
</div>
{#if expanded}
<div
class="container"
style:border={border ? "1px solid var(--color-border-subtle)" : "undefined"}
style:border-top="none">
{@render children()}
{#if hasEverExpanded && !headerOnly}
<div class="collapsible" class:open={expanded}>
<div class="collapsible-inner">
<div
class="container"
style:border={border
? "1px solid var(--color-border-subtle)"
: "undefined"}
style:border-top="none">
{@render children()}
</div>
</div>
</div>
{/if}
+266
View File
@@ -0,0 +1,266 @@
<script lang="ts">
import type { CodeComments } from "@app/components/Diff.svelte";
import type { Embed } from "@bindings/cob/Embed";
import type { FileDiff } from "@bindings/diff/FileDiff";
import { Buffer } from "buffer";
import { fileDiffPath } from "@app/lib/diffText";
import { draftReviewStorage } from "@app/lib/draftReviewStorage";
import { invoke } from "@app/lib/invoke";
import Button from "@app/components/Button.svelte";
import Diff from "@app/components/Diff.svelte";
import FileBlock from "@app/components/FileBlock.svelte";
import Icon from "@app/components/Icon.svelte";
import Path from "@app/components/Path.svelte";
interface Props {
expanded: boolean;
expandable?: boolean;
file: FileDiff;
head: string;
rid: string;
codeComments?: CodeComments;
draftReviewId?: string;
// Set when the changeset is virtualized: the block's own sticky header
// can't work inside an absolutely-positioned row, so the list draws a
// pinned header itself and owns the collapse state.
sticky?: boolean;
headerOnly?: boolean;
onToggle?: (expanded: boolean) => void;
}
const {
expanded,
expandable = true,
file,
head,
rid,
codeComments,
draftReviewId,
sticky = true,
headerOnly = false,
onToggle,
}: Props = $props();
function binaryBlobOid(f: FileDiff): string {
return f.status === "deleted" ? f.old.oid : f.new.oid;
}
async function loadBinaryEmbed(f: FileDiff): Promise<Embed> {
return invoke<Embed>("get_embed", {
rid,
name: fileDiffPath(f),
oid: binaryBlobOid(f),
});
}
function blobUrl(content: Array<number>): string {
return URL.createObjectURL(new Blob([Buffer.from(content)]));
}
let expandedState = $derived(expanded);
const filePathKey = $derived(fileDiffPath(file));
const checked = $derived(
draftReviewId
? draftReviewStorage.isFileChecked(draftReviewId, filePathKey)
: false,
);
function filterThreadsByFilePath() {
if (codeComments) {
if (
file.status === "added" ||
file.status === "deleted" ||
file.status === "modified"
) {
return {
...codeComments,
threads:
codeComments.threads.filter(t => {
return t.root.location?.path === file.path;
}) ?? [],
};
} else {
return { ...codeComments, threads: [] };
}
} else {
return undefined;
}
}
const commentsOfThisFile = $derived(filterThreadsByFilePath());
// Only review comments can be resolved. Draft and standalone revision
// comments carry a `resolved` flag that no action can ever set, so counting
// them would leave the file permanently showing unresolved work.
const resolvableThreads = $derived(
commentsOfThisFile
? commentsOfThisFile.threads.filter(
t => commentsOfThisFile.canResolveComment?.(t.root.id) ?? true,
)
: [],
);
const resolvedThreads = $derived(
resolvableThreads.filter(t => t.root.resolved === true).length,
);
const unresolvedThreads = $derived(
resolvableThreads.filter(t => t.root.resolved === false).length,
);
</script>
<style>
.added {
color: var(--color-feedback-success-text);
background-color: var(--color-feedback-success-bg);
}
.deleted {
color: var(--color-feedback-error-text);
background-color: var(--color-feedback-error-bg);
}
.moved,
.copied {
color: var(--color-text-secondary);
background: var(--color-surface-subtle);
}
.stats {
font: var(--txt-code-regular);
}
.binary-image {
max-width: 100%;
max-height: 32rem;
object-fit: contain;
display: block;
}
</style>
{#snippet emptyPlaceholder()}
<div
class="global-flex txt-body-m-regular"
style:margin="1rem 0"
style:justify-content="center">
Empty file
</div>
{/snippet}
<FileBlock
bind:expanded={expandedState}
{expandable}
{sticky}
{headerOnly}
{onToggle}>
{#snippet leftHeader()}
{#if file.status === "moved" || file.status === "copied"}
<span style="display: flex; align-items: center; flex-wrap: wrap;">
<Path fullPath={file.oldPath} />
<span style:padding="0 0.5rem">→</span>
<Path fullPath={file.newPath} />
</span>
{:else}
<Path fullPath={file.path} />
{/if}
{#if file.status === "added"}
<span class="global-chip added">Added</span>
{:else if file.status === "deleted"}
<span class="global-chip deleted">Deleted</span>
{:else if file.status === "moved"}
<span class="global-chip moved">Moved</span>
{:else if file.status === "copied"}
<span class="global-chip copied">Copied</span>
{/if}
{/snippet}
{#snippet rightHeader()}
{#if file.diff.type === "plain" && file.diff.hunks.length > 0}
<div class="stats">
<span style:color="var(--color-feedback-success-text)">
+{file.diff.stats.additions}
</span>
<span style:color="var(--color-feedback-error-text)">
-{file.diff.stats.deletions}
</span>
</div>
{/if}
{#if commentsOfThisFile && commentsOfThisFile.threads.length > 0}
{#if unresolvedThreads > 0}
<div class="global-flex">
<Icon name="comment" />
{unresolvedThreads}
</div>
{/if}
{#if resolvedThreads > 0}
<div class="global-flex">
<Icon name="comment-checkmark" />
{resolvedThreads}
</div>
{/if}
{/if}
{#if draftReviewId}
<Button
variant="ghost"
active={checked}
bordered
styleHeight="1.5rem"
stylePadding="0 0.375rem"
onclick={e => {
e.stopPropagation();
const wasChecked = checked;
draftReviewStorage.toggleCheckedFile(draftReviewId, filePathKey);
// Collapse when marking reviewed, re-expand when un-marking. Report
// it too, so an owner tracking collapse state stays in step.
expandedState = wasChecked;
onToggle?.(wasChecked);
}}
title={checked ? "Mark file as not reviewed" : "Mark file as reviewed"}>
<Icon name={checked ? "checkmark" : "eye"} />
{checked ? "Reviewed" : "Review"}
</Button>
{/if}
{/snippet}
{#if file.diff.type === "plain"}
{#if file.diff.hunks.length > 0}
<Diff {file} {head} codeComments={commentsOfThisFile} />
{:else}
{@render emptyPlaceholder()}
{/if}
{:else if file.diff.type === "binary"}
{#await loadBinaryEmbed(file)}
<div
class="global-flex"
style:margin="1rem 0"
style:justify-content="center"
style:color="var(--color-text-tertiary)">
Loading binary…
</div>
{:then embed}
{#if embed.mimeType?.startsWith("image/")}
<div
class="global-flex"
style:margin="0.5rem"
style:justify-content="center">
<img
class="binary-image"
src={blobUrl(embed.content)}
alt={fileDiffPath(file)} />
</div>
{:else}
<div
class="global-flex"
style:margin="1rem 0"
style:justify-content="center">
<Icon name="binary" />Binary file
</div>
{/if}
{:catch}
<div
class="global-flex"
style:margin="1rem 0"
style:justify-content="center">
<Icon name="binary" />Binary file
</div>
{/await}
{:else}
{@render emptyPlaceholder()}
{/if}
</FileBlock>
+4
View File
@@ -64,6 +64,7 @@
| "fullscreen"
| "git"
| "guide"
| "hash"
| "help"
| "home"
| "hourglass"
@@ -459,6 +460,9 @@
<path d="M8.5 6.25V10.5H9.5V11.5H6.5V10.5H7.5V7.25H6.75V6.25H8.5Z" />
<path
d="M8.625 4.625C8.625 4.97018 8.34518 5.25 8 5.25C7.65482 5.25 7.375 4.97018 7.375 4.625C7.375 4.27982 7.65482 4 8 4C8.34518 4 8.625 4.27982 8.625 4.625Z" />
{:else if name === "hash"}
<path
d="M6.5 5.5H9.5V2.5H10.5V5.5H13.5V6.5H10.5V9.5H13.5V10.5H10.5V13.5H9.5V10.5H6.5V13.5H5.5V10.5H2.5V9.5H5.5V6.5H2.5V5.5H5.5V2.5H6.5V5.5ZM6.5 9.5H9.5V6.5H6.5V9.5Z" />
{:else if name === "help"}
<path
d="M13.5 8C13.5 4.96243 11.0376 2.5 8 2.5C4.96243 2.5 2.5 4.96243 2.5 8C2.5 11.0376 4.96243 13.5 8 13.5C11.0376 13.5 13.5 11.0376 13.5 8ZM14.5 8C14.5 11.5899 11.5899 14.5 8 14.5C4.41015 14.5 1.5 11.5899 1.5 8C1.5 4.41015 4.41015 1.5 8 1.5C11.5899 1.5 14.5 4.41015 14.5 8Z" />
+19 -23
View File
@@ -1,5 +1,4 @@
<script lang="ts">
import type { Placement } from "@floating-ui/dom";
import type { ComponentProps } from "svelte";
import {
@@ -17,19 +16,32 @@
import Icon from "@app/components/Icon.svelte";
interface Props {
ariaLabel?: string;
clipboard: string;
id: string;
// What the hash is (e.g. "patch ID"), named in the tooltip.
label?: string;
shorten?: boolean;
}
const { ariaLabel, clipboard, id, label, shorten = true }: Props = $props();
let icon: ComponentProps<typeof Icon>["name"] = $state("copy");
const text = "Click to copy";
let tooltip = $state(text);
let copied = $state(false);
const tooltip = $derived(
copied ? "Copied to clipboard" : label ? `Copy ${label}` : "Click to copy",
);
const restoreIcon = debounce(() => {
icon = "copy";
tooltip = text;
copied = false;
}, 1000);
async function copy() {
await writeToClipboard(clipboard);
icon = "checkmark";
tooltip = "Copied to clipboard";
copied = true;
restoreIcon();
}
@@ -37,34 +49,18 @@
let anchorEl: HTMLDivElement | undefined = $state();
let floatingEl: HTMLDivElement | undefined = $state();
interface Props {
ariaLabel?: string;
clipboard: string;
id: string;
placement?: Placement;
shorten?: boolean;
}
const {
ariaLabel,
clipboard,
id,
placement = "top-start",
shorten = true,
}: Props = $props();
const setVisible = debounce((value: boolean) => {
visible = value;
}, 50);
$effect(() => {
// Re-run when tooltip text changes so the wider "Copied to clipboard"
// Re-run when the tooltip text changes so the wider "Copied to clipboard"
// text is repositioned and doesn't overflow the viewport edge.
void tooltip;
if (floatingEl && anchorEl) {
const cleanup = autoUpdate(anchorEl, floatingEl, () => {
void computePosition(anchorEl!, floatingEl!, {
placement,
placement: "top-start",
middleware: [offset(6), flip(), shift({ padding: 8 })],
}).then(({ x, y }) => {
if (floatingEl) {
+199
View File
@@ -0,0 +1,199 @@
<script lang="ts" module>
import type { Author } from "@bindings/cob/Author";
import type { Action } from "@bindings/cob/issue/Action";
export type FlattenedIssueOperation = Action & {
id: string;
author: Author;
timestamp: number;
previous?: Action;
};
</script>
<script lang="ts">
import {
absoluteTimestamp,
authorForNodeId,
formatTimestamp,
issueStatusColor,
pluralize,
} from "@app/lib/utils";
import Icon from "@app/components/Icon.svelte";
import NodeId from "@app/components/NodeId.svelte";
interface Props {
op: FlattenedIssueOperation;
// Set when the surrounding run already names the author above the group.
hideAuthor?: boolean;
}
const { op, hideAuthor }: Props = $props();
function itemDiff<A>(previousState: A[], newState: A[]) {
const removed = previousState.filter(x => !newState.includes(x));
const added = newState.filter(x => !previousState.includes(x));
return { removed, added };
}
</script>
<style>
.timeline-item {
display: flex;
align-items: center;
gap: 0.5rem;
min-width: 0;
padding: 0.375rem 0.5rem;
min-height: 2.5rem;
}
.wrapper {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.25rem;
min-width: 0;
flex: 1 1 0;
}
.icon {
padding-top: 0;
}
.summary-line {
display: flex;
align-items: center;
flex: 1 1 0;
min-width: 0;
gap: 0.25rem;
white-space: nowrap;
overflow: hidden;
}
/* Ellipsis has to sit on a child: it does not apply to the anonymous flex
items a flex container makes of its text nodes. */
.summary-text {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
}
.timestamp {
color: var(--color-text-quaternary);
}
</style>
{#if op.type === "lifecycle"}
<div class="timeline-item txt-body-m-regular">
<div class="icon" style:color={issueStatusColor[op.state.status]}>
{#if op.state.status === "open"}
<Icon name="issue" />
{:else}
<Icon name="issue-closed" />
{/if}
</div>
<div class="wrapper">
{#if !hideAuthor}<NodeId {...authorForNodeId(op.author)} />{/if}
<div class="summary-line">
{#if op.state.status === "closed"}
closed issue as {op.state.reason}
{:else if op.state.status === "open"}
reopened issue
{/if}
</div>
<div class="timestamp" title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
{:else if op.type === "label"}
<div class="timeline-item txt-body-m-regular">
<div class="icon">
<Icon name="label" />
</div>
<div class="wrapper">
{#if !hideAuthor}<NodeId {...authorForNodeId(op.author)} />{/if}
<div class="summary-line">
{#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}
<b>{label}</b>
{/each}
{/if}
{#if changed.removed.length}
removed {pluralize("label", changed.removed.length)}
{#each changed.removed as label}
<b>{label}</b>
{/each}
{/if}
{/if}
{:else}
added {pluralize("label", op.labels.length)}
{#each op.labels as label}
<b>{label}</b>
{/each}
{/if}
</div>
<div class="timestamp" title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
{:else if op.type === "assign"}
<div class="timeline-item txt-body-m-regular">
<div class="icon">
<Icon name="avatar-incognito" />
</div>
<div class="wrapper">
{#if !hideAuthor}<NodeId {...authorForNodeId(op.author)} />{/if}
<div class="summary-line">
{#if op.previous && op.previous.type === op.type}
{@const changed = itemDiff<Author>(
op.previous?.assignees ?? [],
op.assignees,
)}
{#if changed.added.length || changed.removed.length}
{#if changed.added.length}
assigned
{#each changed.added as assignee}
<NodeId {...authorForNodeId(assignee)} />
{/each}
{/if}
{#if changed.removed.length}
unassigned
{#each changed.removed as assignee}
<NodeId {...authorForNodeId(assignee)} />
{/each}
{/if}
{/if}
{:else}
assigned
{#each op.assignees as assignee}
<NodeId {...authorForNodeId(assignee)} />
{/each}
{/if}
</div>
<div class="timestamp" title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
{:else if op.type === "edit"}
{#if op.previous && op.previous.type === op.type}
<div class="timeline-item txt-body-m-regular">
<div class="icon">
<Icon name="edit" />
</div>
<div class="wrapper">
{#if !hideAuthor}<NodeId {...authorForNodeId(op.author)} />{/if}
<div class="summary-line">
<span class="summary-text">
changed title <s>{op.previous.title}</s>
→ {op.title}
</span>
</div>
<div class="timestamp" title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
{/if}
{/if}
+1 -1
View File
@@ -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}>
<span
class="global-chip"
+2 -2
View File
@@ -4,8 +4,8 @@
import { push } from "@app/lib/router";
import {
authorForNodeId,
absoluteTimestamp,
authorForNodeId,
formatTimestamp,
issueStatusBackgroundColor,
issueStatusColor,
@@ -89,7 +89,7 @@
<div class="global-flex txt-body-m-regular" style:flex-wrap="wrap">
<NodeId {...authorForNodeId(issue.author)} />
opened
<Id id={issue.id} clipboard={issue.id} />
<Id id={issue.id} clipboard={issue.id} label="issue ID" />
<span title={absoluteTimestamp(issue.timestamp)}>
{formatTimestamp(issue.timestamp)}
</span>
-244
View File
@@ -1,244 +0,0 @@
<script lang="ts">
import type { Author } from "@bindings/cob/Author";
import type { Action } from "@bindings/cob/issue/Action";
import type { Operation } from "@bindings/cob/Operation";
type FlattenedOperation = Action & {
id: string;
author: Author;
timestamp: number;
previous?: Action;
};
type StateTracker = Record<Action["type"], Action>;
import {
absoluteTimestamp,
authorForNodeId,
formatTimestamp,
issueStatusColor,
pluralize,
} from "@app/lib/utils";
import Icon from "@app/components/Icon.svelte";
import Id from "@app/components/Id.svelte";
import NodeId from "@app/components/NodeId.svelte";
interface Props {
activity: Operation<Action>[];
}
/* eslint-disable prefer-const */
let { activity }: Props = $props();
/* eslint-enable prefer-const */
const timeline = $derived(enrichActivity(flattenActivity(activity)));
function flattenActivity(
activity: Operation<Action>[],
): FlattenedOperation[] {
return activity.flatMap(operation =>
operation.actions.map(action => ({
...action,
id: operation.id,
author: operation.author,
timestamp: operation.timestamp,
})),
);
}
function enrichActivity(
flatActivity: FlattenedOperation[],
): FlattenedOperation[] {
const result: FlattenedOperation[] = [];
const timelineStateTracker: StateTracker = {} as StateTracker;
flatActivity.forEach(entry => {
if (timelineStateTracker[entry.type]) {
result.push({ ...entry, previous: timelineStateTracker[entry.type] });
} else {
result.push(entry);
}
timelineStateTracker[entry.type] = entry;
});
return result;
}
function itemDiff<A>(previousState: A[], newState: A[]) {
const removed = previousState.filter(x => !newState.includes(x));
const added = newState.filter(x => !previousState.includes(x));
return { removed, added };
}
</script>
<style>
.timeline {
display: flex;
gap: 0.75rem;
flex-direction: column;
}
.timeline-item {
display: flex;
align-items: flex-start;
gap: 0.5rem;
word-break: break-word;
}
.wrapper {
display: flex;
flex-wrap: wrap;
gap: 0.25rem;
}
.icon {
padding-top: 3px;
}
</style>
<div class="timeline txt-body-m-regular">
{#each timeline as op}
{#if op.type === "lifecycle"}
<div class="timeline-item">
<div class="icon" style:color={issueStatusColor[op.state.status]}>
{#if op.state.status === "open"}
<Icon name="issue" />
{:else}
<Icon name="issue-closed" />
{/if}
</div>
<div class="wrapper">
<NodeId {...authorForNodeId(op.author)} />
{#if op.state.status === "closed"}
closed issue as {op.state.reason}
{:else if op.state.status === "open"}
reopened issue
{/if}
<div title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
{:else if op.type === "label"}
<div class="timeline-item">
<div class="icon">
<Icon name="label" />
</div>
<div class="wrapper">
<NodeId {...authorForNodeId(op.author)} />
{#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}
<b>{label}</b>
{/each}
{/if}
{#if changed.removed.length}
removed {pluralize("label", changed.removed.length)}
{#each changed.removed as label}
<b>{label}</b>
{/each}
{/if}
{/if}
{:else}
added {pluralize("label", op.labels.length)}
{#each op.labels as label}
<b>{label}</b>
{/each}
{/if}
<div title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
{:else if op.type === "assign"}
<div class="timeline-item">
<div class="icon">
<Icon name="avatar-incognito" />
</div>
<div class="wrapper">
<NodeId {...authorForNodeId(op.author)} />
{#if op.previous && op.previous.type === op.type}
{@const changed = itemDiff<Author>(
op.previous?.assignees ?? [],
op.assignees,
)}
{#if changed.added.length || changed.removed.length}
{#if changed.added.length}
assigned
{#each changed.added as assignee}
<NodeId {...authorForNodeId(assignee)} />
{/each}
{/if}
{#if changed.removed.length}
unassigned
{#each changed.removed as assignee}
<NodeId {...authorForNodeId(assignee)} />
{/each}
{/if}
{/if}
{:else}
assigned
{#each op.assignees as assignee}
<NodeId {...authorForNodeId(assignee)} />
{/each}
{/if}
<div title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
{:else if op.type === "edit"}
{#if op.previous && op.previous.type === op.type}
<div class="timeline-item">
<div class="icon">
<Icon name="edit" />
</div>
<div class="wrapper">
<NodeId {...authorForNodeId(op.author)} />
changed title
<s>{op.previous.title}</s>
-> {op.title}
<div title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
{/if}
{:else if op.type === "comment"}
{#if op.id === activity[0].id}
<div class="timeline-item">
<div class="icon" style:color="var(--color-feedback-success-text)">
<Icon name="issue" />
</div>
<div class="wrapper">
<NodeId {...authorForNodeId(op.author)} />
<div>
opened issue <Id id={op.id} clipboard={op.id} />
</div>
<div title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
{:else}
<div class="timeline-item">
<div class="icon">
<Icon name="comment" />
</div>
<div class="wrapper">
<NodeId {...authorForNodeId(op.author)} />
<a class="global-link" href="#{op.id}">
{op.replyTo && op.replyTo !== activity[0].id
? "replied to a comment"
: "commented"}
</a>
<div title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
{/if}
{/if}
{/each}
</div>
+1 -1
View File
@@ -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;
+3 -13
View File
@@ -121,11 +121,7 @@
<div class="row">
<Button variant="outline" disabled>
<Icon name="label" />
{#if updatedLabels.length === 0}
Add labels
{:else}
Labels
{/if}
Add labels
</Button>
{#each updatedLabels as label}
<Label {label} />
@@ -157,19 +153,13 @@
<Button
variant="outline"
disabled={!allowedToEdit}
title={allowedToEdit
? undefined
: "Only delegates are allowed to add labels"}
title={allowedToEdit ? undefined : "Only delegates can add labels"}
onclick={() => {
inputValue = "";
showInput = true;
}}>
<Icon name="label" />
{#if updatedLabels.length === 0}
Add labels
{:else}
Labels
{/if}
Add labels
</Button>
{/if}
+7 -7
View File
@@ -369,18 +369,18 @@
label: `${activity.revisionCount} ${pluralize("revision", activity.revisionCount)}`,
}
: undefined,
activity.commitCount > 0
? {
icon: "commit" as IconName,
label: `${activity.commitCount} ${pluralize("commit", activity.commitCount)}`,
}
: undefined,
activity.reviewCount > 0
? {
icon: "comment" as IconName,
icon: "comment-checkmark" as IconName,
label: `${activity.reviewCount} ${pluralize("review", activity.reviewCount)}`,
}
: undefined,
activity.commentCount > 0
? {
icon: "comment" as IconName,
label: `${activity.commentCount} ${pluralize("comment", activity.commentCount)}`,
}
: undefined,
] as ({ icon: IconName; label: string } | undefined)[]
).filter(
(x): x is { icon: IconName; label: string } => x !== undefined,
+1 -1
View File
@@ -11,8 +11,8 @@
import { compressActions } from "@app/lib/notification";
import { push } from "@app/lib/router";
import {
authorForNodeId,
absoluteTimestamp,
authorForNodeId,
formatTimestamp,
issueStatusBackgroundColor,
issueStatusColor,
+725
View File
@@ -0,0 +1,725 @@
<script lang="ts" module>
import type { Author } from "@bindings/cob/Author";
import type { Action } from "@bindings/cob/patch/Action";
export type FlattenedPatchOperation = Action & {
id: string;
author: Author;
timestamp: number;
previous?: Action;
};
export function splitDescription(text: string): {
subject?: string;
body?: string;
} {
const trimmed = text.trim();
if (!trimmed) return {};
const idx = trimmed.indexOf("\n");
if (idx === -1) return { subject: trimmed };
const subject = trimmed.slice(0, idx).trim();
const body = trimmed.slice(idx + 1).trim();
return {
subject: subject || undefined,
body: body || undefined,
};
}
</script>
<script lang="ts">
import { slide } from "svelte/transition";
import { cachedConfig, writeToClipboard } from "@app/lib/invoke";
import {
absoluteTimestamp,
authorForNodeId,
explorerUrl,
formatTimestamp,
patchStatusColor,
pluralize,
} from "@app/lib/utils";
import Icon from "@app/components/Icon.svelte";
import Id from "@app/components/Id.svelte";
import Markdown from "@app/components/Markdown.svelte";
import NodeId from "@app/components/NodeId.svelte";
import ReviewProgressChip from "@app/components/ReviewProgressChip.svelte";
interface Props {
op: FlattenedPatchOperation;
expanded?: boolean;
onToggle?: () => void;
hideAuthor?: boolean;
targetBranch?: string;
firstRevision?: boolean;
onViewFullReview?: () => void;
onOpenReview?: () => void;
onOpenChanges?: () => void;
rid?: string;
patchId?: string;
latest?: boolean;
reviewInProgress?: boolean;
bodyExternal?: boolean;
openedAsDraft?: boolean;
}
const {
op,
expanded,
onToggle,
hideAuthor,
targetBranch,
firstRevision = false,
onViewFullReview,
onOpenReview,
onOpenChanges,
rid,
patchId,
latest = false,
reviewInProgress = false,
bodyExternal = false,
openedAsDraft = false,
}: Props = $props();
function itemDiff<A>(previousState: A[], newState: A[]) {
const removed = previousState.filter(x => !newState.includes(x));
const added = newState.filter(x => !previousState.includes(x));
return { removed, added };
}
let copyLinkIcon: "link" | "checkmark" = $state("link");
async function copyRevisionLink() {
if (!rid || !patchId) return;
const config = await cachedConfig();
// Deep-link to the Changes tab with this revision pre-selected. The
// revision id goes in the path (`/patches/<patch>/<revision>`), which is
// the form the explorer resolves; `?revision=` does not navigate there.
await writeToClipboard(
explorerUrl(`${rid}/patches/${patchId}/${op.id}?tab=changes`, config),
);
copyLinkIcon = "checkmark";
setTimeout(() => (copyLinkIcon = "link"), 1000);
}
</script>
<style>
.timeline-item {
display: flex;
align-items: center;
gap: 0.5rem;
min-width: 0;
padding: 0.375rem 0.5rem;
border-radius: var(--border-radius-sm);
min-height: 2.5rem;
}
.timeline-item:has(.revision-body) {
align-items: flex-start;
}
.timeline-item.toggleable {
cursor: pointer;
}
.timeline-item.toggleable:hover,
.timeline-item.toggleable:focus-visible {
background-color: var(--color-surface-subtle);
}
.timeline-item.card-header {
border-radius: 0;
border-bottom: 1px solid var(--color-border-subtle);
}
.wrapper {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.25rem;
min-width: 0;
flex: 1 1 0;
}
.icon {
padding-top: 0;
}
.timeline-item:has(.revision-body) .icon {
padding-top: 0.1875rem;
}
.icon-stack {
display: grid;
width: 1rem;
place-items: center;
}
.icon-default,
.icon-hover {
grid-area: 1 / 1;
transition:
opacity 150ms ease,
transform 150ms ease;
}
.icon-hover {
opacity: 0;
transform: rotate(-90deg);
}
.timeline-item.toggleable:hover .icon-default,
.timeline-item.toggleable:focus-visible .icon-default,
.timeline-item.verdict-toggleable:hover .icon-default,
.timeline-item.verdict-toggleable:focus-visible .icon-default {
opacity: 0;
transform: rotate(90deg);
}
.timeline-item.toggleable:hover .icon-hover,
.timeline-item.toggleable:focus-visible .icon-hover,
.timeline-item.verdict-toggleable:hover .icon-hover,
.timeline-item.verdict-toggleable:focus-visible .icon-hover {
opacity: 1;
transform: rotate(0);
}
.verdict-toggleable {
cursor: pointer;
}
.summary-line {
display: flex;
align-items: center;
flex: 1 1 0;
min-width: 0;
gap: 0.25rem;
}
.summary-secondary {
color: var(--color-text-tertiary);
white-space: nowrap;
flex-shrink: 0;
}
.no-description {
color: var(--color-text-tertiary);
white-space: nowrap;
}
.latest-chip {
flex-shrink: 0;
padding: 0 0.375rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-brand-subtle);
color: var(--color-text-brand);
}
.summary-content {
color: var(--color-text-primary);
min-width: 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.timestamp {
color: var(--color-text-quaternary);
}
.meta {
display: flex;
align-items: center;
gap: 0.5rem;
flex-shrink: 0;
}
.meta-hash {
color: var(--color-text-quaternary);
}
.meta-hash :global(.txt-id) {
color: inherit;
}
.meta-hash :global(.txt-id:hover) {
color: inherit;
}
.verdict-accept {
background-color: var(--color-feedback-success-bg);
color: var(--color-feedback-success-text);
}
.verdict-accept,
.verdict-accept :global(*) {
color: var(--color-feedback-success-text);
}
.verdict-reject {
background-color: var(--color-feedback-error-bg);
color: var(--color-feedback-error-text);
}
.verdict-reject,
.verdict-reject :global(*) {
color: var(--color-feedback-error-text);
}
.verdict-comment {
background-color: var(--color-surface-subtle);
}
.revision-body {
flex-basis: 100%;
color: var(--color-text-primary);
overflow-wrap: anywhere;
}
.merge-badge {
background-color: var(--color-surface-brand-subtle);
color: var(--color-text-brand);
}
.merge-badge,
.merge-badge :global(*) {
color: inherit;
}
.copy-link {
display: inline-flex;
align-items: center;
justify-content: center;
width: 1.25rem;
height: 1.25rem;
padding: 0;
border: 0;
border-radius: var(--border-radius-sm);
background: none;
color: var(--color-text-quaternary);
cursor: pointer;
}
.copy-link:hover,
.copy-link:focus-visible {
background-color: var(--color-surface-subtle);
color: var(--color-text-primary);
}
.open-changes {
display: inline-flex;
align-items: center;
justify-content: center;
width: 1.25rem;
height: 1.25rem;
padding: 0;
border: 0;
border-radius: var(--border-radius-sm);
background: none;
color: var(--color-text-quaternary);
cursor: pointer;
opacity: 0;
transition: opacity 150ms ease;
}
.timeline-item:hover .open-changes,
.open-changes:focus-visible {
opacity: 1;
}
.open-changes:hover,
.open-changes:focus-visible {
background-color: var(--color-surface-subtle);
color: var(--color-text-primary);
}
.view-full-review {
display: inline-flex;
align-items: center;
gap: 0.125rem;
background: none;
border: 1px solid transparent;
cursor: pointer;
color: inherit;
padding: 0.125rem 0.375rem;
border-radius: var(--border-radius-sm);
font: inherit;
white-space: nowrap;
flex-shrink: 0;
}
.view-full-review:hover,
.view-full-review:focus-visible {
background-color: var(--color-surface-subtle);
color: var(--color-text-primary);
}
.verdict-accept .view-full-review:hover,
.verdict-accept .view-full-review:focus-visible {
background-color: var(--color-surface-canvas);
color: var(--color-feedback-success-text);
}
.verdict-reject .view-full-review:hover,
.verdict-reject .view-full-review:focus-visible {
background-color: var(--color-surface-canvas);
color: var(--color-feedback-error-text);
}
.verdict-comment .view-full-review:hover,
.verdict-comment .view-full-review:focus-visible {
background-color: var(--color-surface-canvas);
color: var(--color-text-primary);
}
</style>
{#snippet viewFullReviewButton()}
{#if onViewFullReview}
<button
type="button"
class="view-full-review"
onclick={e => {
e.stopPropagation();
onViewFullReview();
}}>
View full review
<Icon name="chevron-right" />
</button>
{/if}
{/snippet}
{#snippet copyLinkButton()}
{#if rid && patchId}
<button
type="button"
class="copy-link"
title="Copy revision link"
onclick={e => {
e.stopPropagation();
void copyRevisionLink();
}}>
<Icon name={copyLinkIcon} />
</button>
{/if}
{/snippet}
{#if op.type === "revision"}
{@const desc = splitDescription(op.description)}
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
<div
class="timeline-item txt-body-m-regular"
class:toggleable={onToggle !== undefined}
class:card-header={bodyExternal}
role={onToggle ? "button" : undefined}
tabindex={onToggle ? 0 : undefined}
onclick={onToggle}>
<div class="icon">
{#if onToggle}
<span class="icon-stack">
<span class="icon-default">
<Icon name={firstRevision ? "patch" : "revision"} />
</span>
<span class="icon-hover">
<Icon name={expanded ? "collapse-vertical" : "expand-vertical"} />
</span>
</span>
{:else}
<Icon name={firstRevision ? "patch" : "revision"} />
{/if}
</div>
<div class="wrapper">
{#if !hideAuthor}<NodeId {...authorForNodeId(op.author)} />{/if}
<div class="summary-line">
<span class="summary-secondary">
{firstRevision
? openedAsDraft
? "opened a draft patch"
: "opened patch"
: "created revision"}
</span>
{#if !firstRevision}
{#if desc.subject}
<span class="txt-body-m-medium summary-content">
{desc.subject}
</span>
{:else}
<span class="no-description">No description</span>
{/if}
{/if}
{#if latest}
<span class="latest-chip txt-body-s-medium">latest</span>
{/if}
{#if reviewInProgress}
<ReviewProgressChip onclick={() => onOpenReview?.()} />
{/if}
{#if onOpenChanges}
<button
type="button"
class="open-changes"
title="Open revision changes"
onclick={e => {
e.stopPropagation();
onOpenChanges();
}}>
<Icon name="arrow-right" />
</button>
{/if}
</div>
<div class="meta">
{#if !firstRevision}
<div class="meta-hash">
<Id id={op.id} clipboard={op.id} label="revision ID" />
</div>
{/if}
<div class="timestamp" title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
{#if expanded}
{@render copyLinkButton()}
{/if}
</div>
{#if !firstRevision && desc.body && expanded && !bodyExternal}
<div class="revision-body" transition:slide={{ duration: 180 }}>
<Markdown {rid} breaks content={desc.body} />
</div>
{/if}
</div>
</div>
{:else if op.type === "lifecycle"}
<div class="timeline-item txt-body-m-regular">
<div class="icon" style:color={patchStatusColor[op.state.status]}>
<Icon
name={op.state.status === "open"
? "patch"
: `patch-${op.state.status}`} />
</div>
<div class="wrapper">
{#if !hideAuthor}<NodeId {...authorForNodeId(op.author)} />{/if}
<div class="summary-line">
<span class="summary-secondary">
{#if op.state.status === "draft"}
converted patch to draft
{:else if op.state.status === "archived"}
archived patch
{:else if op.state.status === "open"}
{#if op.previous?.type === "lifecycle" && op.previous.state.status === "draft"}
marked patch ready to review
{:else}
reopened patch
{/if}
{/if}
</span>
</div>
<div class="meta">
<div class="timestamp" title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
</div>
{:else if op.type === "label"}
<div class="timeline-item txt-body-m-regular">
<div class="icon">
<Icon name="label" />
</div>
<div class="wrapper">
{#if !hideAuthor}<NodeId {...authorForNodeId(op.author)} />{/if}
<div class="summary-line">
{#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}
<span class="summary-secondary">
added {pluralize("label", changed.added.length)}
</span>
{#each changed.added as label}
<b class="summary-content">{label}</b>
{/each}
{/if}
{#if changed.removed.length}
<span class="summary-secondary">
removed {pluralize("label", changed.removed.length)}
</span>
{#each changed.removed as label}
<b class="summary-content">{label}</b>
{/each}
{/if}
{/if}
{:else}
<span class="summary-secondary">
added {pluralize("label", op.labels.length)}
</span>
{#each op.labels as label}
<b class="summary-content">{label}</b>
{/each}
{/if}
</div>
<div class="meta">
<div class="timestamp" title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
</div>
{:else if op.type === "assign"}
<div class="timeline-item txt-body-m-regular">
<div class="icon">
<Icon name="avatar-incognito" />
</div>
<div class="wrapper">
{#if !hideAuthor}<NodeId {...authorForNodeId(op.author)} />{/if}
<div class="summary-line">
{#if op.previous && op.previous.type === op.type}
{@const changed = itemDiff<Author>(
op.previous?.assignees ?? [],
op.assignees,
)}
{#if changed.added.length}
<span class="summary-secondary">assigned</span>
{#each changed.added as assignee}
<NodeId {...authorForNodeId(assignee)} />
{/each}
{/if}
{#if changed.removed.length}
<span class="summary-secondary">unassigned</span>
{#each changed.removed as assignee}
<NodeId {...authorForNodeId(assignee)} />
{/each}
{/if}
{:else}
<span class="txt-body-m-medium">assigned</span>
{#each op.assignees as assignee}
<NodeId {...authorForNodeId(assignee)} />
{/each}
{/if}
</div>
<div class="meta">
<div class="timestamp" title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
</div>
{:else if op.type === "merge"}
<div class="timeline-item txt-body-m-regular merge-badge">
<div class="icon" style:color="var(--color-text-brand)">
<Icon name="patch-merged" />
</div>
<div class="wrapper">
{#if !hideAuthor}<NodeId {...authorForNodeId(op.author)} />{/if}
<div class="summary-line">
<span class="txt-body-m-medium">merged patch</span>
{#if targetBranch}
into <b>{targetBranch}</b>
{/if}
</div>
<div class="meta">
<Id id={op.revision} clipboard={op.revision} label="revision ID" />
<div class="timestamp" title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
</div>
{:else if op.type === "edit"}
{#if op.previous && op.previous.type === op.type}
<div class="timeline-item txt-body-m-regular">
<div class="icon">
<Icon name="edit" />
</div>
<div class="wrapper">
{#if !hideAuthor}<NodeId {...authorForNodeId(op.author)} />{/if}
<div class="summary-line">
<span class="summary-secondary">changed title</span>
<s class="summary-secondary">{op.previous.title}</s>
<span class="summary-secondary">→</span>
<span class="txt-body-m-medium summary-content">{op.title}</span>
</div>
<div class="meta">
<div class="timestamp" title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
</div>
{/if}
{:else if op.type === "review"}
{@const reviewSummary = splitDescription(op.summary ?? "")}
{@const isToggleable = onToggle !== undefined}
{#if op.verdict === "accept"}
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
<div
class="timeline-item txt-body-m-regular verdict-accept"
class:verdict-toggleable={isToggleable}
role={isToggleable ? "button" : undefined}
tabindex={isToggleable ? 0 : undefined}
onclick={isToggleable ? onToggle : undefined}>
<div class="icon" style:color="var(--color-feedback-success-text)">
{#if isToggleable}
<span class="icon-stack">
<span class="icon-default"><Icon name="thumbs-up" /></span>
<span class="icon-hover">
<Icon name={expanded ? "collapse-vertical" : "expand-vertical"} />
</span>
</span>
{:else}
<Icon name="thumbs-up" />
{/if}
</div>
<div class="wrapper">
{#if !hideAuthor}<NodeId {...authorForNodeId(op.author)} />{/if}
<div class="summary-line">
<span class="summary-secondary">accepted revision</span>
{#if reviewSummary.subject}
<span class="txt-body-m-medium summary-content">
{reviewSummary.subject}
</span>
{/if}
{@render viewFullReviewButton()}
</div>
<div class="meta">
<Id id={op.revision} clipboard={op.revision} label="revision ID" />
<div class="timestamp" title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
</div>
{:else if op.verdict === "reject"}
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
<div
class="timeline-item txt-body-m-regular verdict-reject"
class:verdict-toggleable={isToggleable}
role={isToggleable ? "button" : undefined}
tabindex={isToggleable ? 0 : undefined}
onclick={isToggleable ? onToggle : undefined}>
<div class="icon" style:color="var(--color-feedback-error-text)">
{#if isToggleable}
<span class="icon-stack">
<span class="icon-default"><Icon name="stop" /></span>
<span class="icon-hover">
<Icon name={expanded ? "collapse-vertical" : "expand-vertical"} />
</span>
</span>
{:else}
<Icon name="stop" />
{/if}
</div>
<div class="wrapper">
{#if !hideAuthor}<NodeId {...authorForNodeId(op.author)} />{/if}
<div class="summary-line">
<span class="summary-secondary">rejected revision</span>
{#if reviewSummary.subject}
<span class="txt-body-m-medium summary-content">
{reviewSummary.subject}
</span>
{/if}
{@render viewFullReviewButton()}
</div>
<div class="meta">
<Id id={op.revision} clipboard={op.revision} label="revision ID" />
<div class="timestamp" title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
</div>
{:else if op.verdict === undefined}
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
<div
class="timeline-item txt-body-m-regular verdict-comment"
class:verdict-toggleable={isToggleable}
role={isToggleable ? "button" : undefined}
tabindex={isToggleable ? 0 : undefined}
onclick={isToggleable ? onToggle : undefined}>
<div class="icon">
{#if isToggleable}
<span class="icon-stack">
<span class="icon-default"><Icon name="comment" /></span>
<span class="icon-hover">
<Icon name={expanded ? "collapse-vertical" : "expand-vertical"} />
</span>
</span>
{:else}
<Icon name="comment" />
{/if}
</div>
<div class="wrapper">
{#if !hideAuthor}<NodeId {...authorForNodeId(op.author)} />{/if}
<div class="summary-line">
<span class="summary-secondary">reviewed revision</span>
{#if reviewSummary.subject}
<span class="txt-body-m-medium summary-content">
{reviewSummary.subject}
</span>
{/if}
{@render viewFullReviewButton()}
</div>
<div class="meta">
<Id id={op.revision} clipboard={op.revision} label="revision ID" />
<div class="timestamp" title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
</div>
{/if}
{/if}
+371 -55
View File
@@ -1,36 +1,112 @@
<script lang="ts">
import type { PatchView } from "@app/views/repo/router";
import type { Author } from "@bindings/cob/Author";
import type { Patch } from "@bindings/cob/patch/Patch";
import type { Revision } from "@bindings/cob/patch/Revision";
import type { Config } from "@bindings/config/Config";
import type { Stats } from "@bindings/diff/Stats";
import type { RepoInfo } from "@bindings/repo/RepoInfo";
import debounce from "lodash/debounce";
import { nodeRunning } from "@app/lib/events";
import { invoke } from "@app/lib/invoke";
import { invoke, writeToClipboard } from "@app/lib/invoke";
import type { ReviewEntry } from "@app/lib/reviewSummary";
import {
entriesFromRevisions,
isOutdatedReview,
reviewSummary,
summaryTitle,
} from "@app/lib/reviewSummary";
import * as roles from "@app/lib/roles";
import { push } from "@app/lib/router";
import {
authorForNodeId,
formatOid,
pluralize,
publicKeyFromDid,
verdictIcon,
} from "@app/lib/utils";
import { announce } from "@app/components/AnnounceSwitch.svelte";
import AssigneeInput from "@app/components/AssigneeInput.svelte";
import DropdownList from "@app/components/DropdownList.svelte";
import DropdownListItem from "@app/components/DropdownListItem.svelte";
import Icon from "@app/components/Icon.svelte";
import LabelInput from "@app/components/LabelInput.svelte";
import PatchStateButton from "@app/components/PatchStateButton.svelte";
import NodeId from "@app/components/NodeId.svelte";
import Popover, { closeFocused } from "@app/components/Popover.svelte";
import UserAvatar from "@app/components/UserAvatar.svelte";
interface Props {
config: Config;
horizontal?: boolean;
loadPatch: () => Promise<void>;
patch: Patch;
repo: RepoInfo;
saveState: (newState: Patch["state"]) => Promise<void>;
revisions: Revision[];
stats?: Stats;
// The tab the review is opened from, so its back button returns there.
view?: PatchView;
onShowChanges?: () => void;
}
const {
config,
horizontal = false,
loadPatch,
patch,
repo,
saveState,
revisions,
stats,
view,
onShowChanges,
}: Props = $props();
// Shared with the patch list so both summaries say the same thing — the
// counting, ordering and outdated rules all live in `reviewSummary`.
const summary = $derived(
reviewSummary(
entriesFromRevisions(
revisions,
repo.delegates.map(d => d.did),
),
revisions.length,
),
);
const reviews = $derived(summary.reviews);
const reviewAuthors = $derived(summary.authors);
// Which revision a review is of only matters when the patch has more than
// one revision; with a single revision the whole indicator is hidden.
const showRevision = $derived(revisions.length > 1);
let reviewersPopoverExpanded = $state(false);
// `ReviewEntry.reviewId` is optional because the patch list has no review to
// link to; every entry built from revisions here carries one.
function openReview(reviewId: string | undefined) {
if (!reviewId) return;
reviewersPopoverExpanded = false;
closeFocused();
void push({
resource: "repo.patch",
rid: repo.rid,
patch: patch.id,
status: undefined,
reviewId,
view,
});
}
let patchIdCopied = $state(false);
const resetPatchIdCopied = debounce(() => {
patchIdCopied = false;
}, 1000);
async function copyPatchId() {
await writeToClipboard(patch.id);
patchIdCopied = true;
resetPatchIdCopied();
}
let labelSaveInProgress: boolean = $state(false);
let assigneesSaveInProgress: boolean = $state(false);
@@ -76,58 +152,298 @@
</script>
<style>
.metadata-section {
padding: 0.5rem;
font: var(--txt-body-m-regular);
.meta-row {
display: flex;
flex-direction: column;
align-items: flex;
height: 100%;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem;
font: var(--txt-body-m-regular);
}
.stats {
display: inline-flex;
align-items: center;
gap: 0.5rem;
height: 2rem;
padding: 0 0.5rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-canvas);
color: var(--color-text-tertiary);
font: var(--txt-body-m-regular);
}
.stats.stats-button {
cursor: pointer;
}
.stats.stats-button:hover,
.stats.stats-button:focus-visible {
background-color: var(--color-surface-subtle);
color: var(--color-text-primary);
}
.stats .insertions {
color: var(--color-feedback-success-text);
}
.stats .deletions {
color: var(--color-feedback-error-text);
}
.reviews {
display: inline-flex;
align-items: center;
gap: 0.5rem;
height: 2rem;
padding: 0 0.5rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-canvas);
color: var(--color-text-tertiary);
cursor: pointer;
font: var(--txt-body-m-regular);
}
.reviews:hover,
.reviews:focus-visible {
background-color: var(--color-surface-subtle);
color: var(--color-text-primary);
}
.reviewer-stack {
display: inline-flex;
align-items: center;
}
.reviewer-stack :global(img) {
outline: 1px solid var(--color-surface-canvas);
margin-left: -0.375rem;
}
.reviewer-stack :global(img:first-child) {
margin-left: 0;
}
.reviewer-overflow {
margin-left: 0.25rem;
color: var(--color-text-tertiary);
}
.verdict-accept {
color: var(--color-feedback-success-text);
}
.verdict-reject {
color: var(--color-feedback-error-text);
}
/* Matches the patch list: the whole chip recedes instead of spelling it out,
with the tooltip carrying the detail. */
.reviews.outdated {
color: var(--color-text-quaternary);
}
.reviews .outdated {
color: var(--color-text-quaternary);
}
.delegate-badge {
display: inline-flex;
align-items: center;
color: var(--color-text-brand);
}
.patch-id-chip,
.author-chip {
display: inline-flex;
align-items: center;
height: 2rem;
padding: 0 0.5rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-canvas);
color: var(--color-text-tertiary);
font: var(--txt-body-m-regular);
}
.patch-id-chip {
gap: 0.375rem;
cursor: pointer;
}
.patch-id-chip:hover,
.patch-id-chip:focus-visible {
background-color: var(--color-surface-subtle);
color: var(--color-text-primary);
}
.patch-id-value {
font: var(--txt-code-regular);
}
/* Patch icon by default, copy icon on hover, checkmark on click. */
.pid-icon-default,
.pid-icon-hover {
display: inline-flex;
align-items: center;
}
.pid-icon-hover {
display: none;
}
.patch-id-chip:hover .pid-icon-default,
.patch-id-chip:focus-visible .pid-icon-default {
display: none;
}
.patch-id-chip:hover .pid-icon-hover,
.patch-id-chip:focus-visible .pid-icon-hover {
display: inline-flex;
}
</style>
<div
class="global-flex"
style:flex-direction={horizontal ? "row" : "column"}
style:align-items="flex-start">
<div
class="metadata-section"
style={horizontal ? "flex: 1;" : "width: 100%;"}>
<PatchStateButton
selectedState={patch.state}
onSelect={newState => {
void saveState(newState);
}}
disabled={!roles.isDelegateOrAuthor(
config.publicKey,
repo.delegates.map(d => d.did),
patch.author.did,
)} />
</div>
<div
class="metadata-section"
style={horizontal ? "flex: 1;" : "width: 100%;"}>
<LabelInput
allowedToEdit={!!roles.isDelegate(
config.publicKey,
repo.delegates.map(delegate => delegate.did),
)}
labels={patch.labels}
submitInProgress={labelSaveInProgress}
save={saveLabels} />
</div>
<div
class="metadata-section"
style={horizontal ? "flex: 1;" : "width: 100%;"}>
<AssigneeInput
allowedToEdit={!!roles.isDelegate(
config.publicKey,
repo.delegates.map(delegate => delegate.did),
)}
assignees={patch.assignees}
submitInProgress={assigneesSaveInProgress}
save={saveAssignees} />
<div class="meta-row">
<div class="author-chip" title="Patch author">
<NodeId {...authorForNodeId(patch.author)} />
</div>
<button
type="button"
class="patch-id-chip"
title={patchIdCopied ? "Copied to clipboard" : "Copy patch ID"}
onclick={copyPatchId}>
{#if patchIdCopied}
<Icon name="checkmark" />
{:else}
<span class="pid-icon-default"><Icon name="hash" /></span>
<span class="pid-icon-hover"><Icon name="copy" /></span>
{/if}
<span class="patch-id-value">{formatOid(patch.id)}</span>
</button>
{#if stats}
{#if onShowChanges}
<button
type="button"
class="stats stats-button"
onclick={onShowChanges}
title="View changed files">
<Icon name="diff" />
<span>
{stats.filesChanged}
{pluralize("file", stats.filesChanged)}
</span>
<span class="insertions">+{stats.insertions}</span>
<span class="deletions">-{stats.deletions}</span>
</button>
{:else}
<div class="stats">
<Icon name="diff" />
<span>
{stats.filesChanged}
{pluralize("file", stats.filesChanged)}
</span>
<span class="insertions">+{stats.insertions}</span>
<span class="deletions">-{stats.deletions}</span>
</div>
{/if}
{/if}
{#if reviews.length > 0}
{@const hasReject = summary.hasReject}
{@const allAccept = summary.allAccept}
{#snippet reviewsButton(
onclick: (() => void) | undefined,
single?: ReviewEntry,
)}
<button
type="button"
class="reviews"
class:outdated={summary.outdated}
{onclick}
aria-haspopup={reviews.length > 1 ? "menu" : undefined}
aria-expanded={reviews.length > 1
? reviewersPopoverExpanded
: undefined}
title={summaryTitle(summary)}>
<span class:verdict-accept={allAccept} class:verdict-reject={hasReject}>
<Icon
name={summary.outdated
? "clock"
: hasReject
? "stop"
: allAccept
? "thumbs-up"
: "comment"} />
</span>
<span>
{reviews.length}
{pluralize("review", reviews.length)}
{#if single && showRevision}
of Revision {single.revisionNumber} of {revisions.length}
{/if}
</span>
{#if summary.outdated && !(single && showRevision)}
<!-- Skipped when the single-review case above already names the
revision, which would otherwise say it twice. -->
<span class="outdated">· r{summary.latestReviewedRevision}</span>
{/if}
<span class="reviewer-stack">
{#each reviewAuthors.slice(0, 3) as author (author.did)}
<UserAvatar
nodeId={publicKeyFromDid(author.did)}
styleWidth="1.125rem" />
{/each}
{#if reviewAuthors.length > 3}
<span class="reviewer-overflow">+{reviewAuthors.length - 3}</span>
{/if}
</span>
</button>
{/snippet}
<div class="reviewers-compact">
{#if reviews.length === 1}
{@render reviewsButton(
() => openReview(reviews[0].reviewId),
reviews[0],
)}
{:else}
<Popover
popoverPadding="0"
placement="bottom-start"
bind:expanded={reviewersPopoverExpanded}>
{#snippet toggle(onclick)}
{@render reviewsButton(onclick)}
{/snippet}
{#snippet popover()}
<div
style:border="1px solid var(--color-border-subtle)"
style:border-radius="var(--border-radius-sm)"
style:background-color="var(--color-surface-canvas)">
<DropdownList items={reviews}>
{#snippet item(reviewer)}
<DropdownListItem
selected={false}
styleGap="0.5rem"
onclick={() => openReview(reviewer.reviewId)}>
<span
class:verdict-accept={reviewer.verdict === "accept"}
class:verdict-reject={reviewer.verdict === "reject"}>
<Icon name={verdictIcon(reviewer.verdict)} />
</span>
<NodeId {...authorForNodeId(reviewer.author)} />
{#if reviewer.delegate}
<span class="delegate-badge" title="Delegate">
<Icon name="badge" />
</span>
{/if}
{#if showRevision}
<span
style:margin-left="auto"
style:color="var(--color-text-quaternary)">
Revision {reviewer.revisionNumber} of {revisions.length}
{#if isOutdatedReview(reviewer, revisions.length)}
· outdated
{/if}
</span>
{/if}
</DropdownListItem>
{/snippet}
</DropdownList>
</div>
{/snippet}
</Popover>
{/if}
</div>
{/if}
<LabelInput
allowedToEdit={!!roles.isDelegate(
config.publicKey,
repo.delegates.map(delegate => delegate.did),
)}
labels={patch.labels}
submitInProgress={labelSaveInProgress}
save={saveLabels} />
<AssigneeInput
allowedToEdit={!!roles.isDelegate(
config.publicKey,
repo.delegates.map(delegate => delegate.did),
)}
assignees={patch.assignees}
submitInProgress={assigneesSaveInProgress}
save={saveAssignees} />
</div>
+108 -79
View File
@@ -5,7 +5,6 @@
import { patchStatusBackgroundColor, patchStatusColor } from "@app/lib/utils";
import Button from "@app/components/Button.svelte";
import DropdownList from "@app/components/DropdownList.svelte";
import DropdownListItem from "@app/components/DropdownListItem.svelte";
import Icon from "@app/components/Icon.svelte";
@@ -21,88 +20,118 @@
const { selectedState, onSelect, disabled = false }: Props = $props();
let popoverExpanded: boolean = $state(false);
const isStatic = $derived(selectedState.status === "merged" || disabled);
</script>
<Popover
popoverPadding="0"
placement="bottom-start"
bind:expanded={popoverExpanded}>
{#snippet toggle(onclick)}
<Button
variant="outline"
disabled={selectedState.status === "merged" || disabled}
{onclick}
active={popoverExpanded}
title={selectedState.status === "merged"
? "The state of merged patches can not be changed"
: disabled
? "You must be a delegate or the patch author to change the patch state"
: undefined}>
<span
class="global-chip"
style:padding="0"
style:margin-left="-0.25rem"
style:color={selectedState.status === "merged" || disabled
? undefined
: patchStatusColor[selectedState.status]}
style:background-color={selectedState.status === "merged" || disabled
? undefined
: patchStatusBackgroundColor[selectedState.status]}>
<style>
.status-button {
display: inline-flex;
align-items: center;
gap: 0.375rem;
height: 2rem;
padding: 0 0.5rem;
border: none;
border-radius: var(--border-radius-sm);
font: var(--txt-body-m-regular);
cursor: pointer;
}
.status-button:hover:not(:disabled),
.status-button.active {
filter: brightness(0.95);
}
.status-button:disabled {
cursor: default;
}
.status-chip {
display: inline-flex;
align-items: center;
gap: 0.375rem;
height: 2rem;
padding: 0 0.5rem;
border-radius: var(--border-radius-sm);
font: var(--txt-body-m-regular);
}
</style>
{#if isStatic}
<span
class="status-chip"
style:color={patchStatusColor[selectedState.status]}
style:background-color={patchStatusBackgroundColor[selectedState.status]}
title={selectedState.status === "merged"
? "The state of merged patches can not be changed"
: "Only delegates and the patch author can change the patch state"}>
<Icon
name={selectedState.status === "open"
? "patch"
: `patch-${selectedState.status}`} />
<span>{capitalize(selectedState.status)}</span>
</span>
{:else}
<Popover
popoverPadding="0"
placement="bottom-start"
bind:expanded={popoverExpanded}>
{#snippet toggle(onclick)}
<button
type="button"
class="status-button"
class:active={popoverExpanded}
style:color={patchStatusColor[selectedState.status]}
style:background-color={patchStatusBackgroundColor[
selectedState.status
]}
{onclick}>
<Icon
name={selectedState.status === "open"
? "patch"
: `patch-${selectedState.status}`} />
</span>
<span
style:color={selectedState.status === "merged" || disabled
? undefined
: "var(--color-text-secondary)"}>
{capitalize(selectedState.status)}
</span>
{#if selectedState.status !== "merged"}
<span>{capitalize(selectedState.status)}</span>
<Icon name={popoverExpanded ? "chevron-up" : "chevron-down"} />
{/if}
</Button>
{/snippet}
{#snippet popover()}
<div
style:border="1px solid var(--color-border-subtle)"
style:border-radius="var(--border-radius-sm)"
style:display="flex"
style:gap="0.5rem"
style:align-items="center"
style:background-color="var(--color-surface-canvas)">
<DropdownList
items={[
{ status: "open" },
{ status: "draft" },
{ status: "archived" },
] as State[]}>
{#snippet item(state)}
<DropdownListItem
selected={selectedState.status === state.status}
styleGap="0.5rem"
onclick={() => {
onSelect(state);
closeFocused();
}}>
<span
class="global-chip"
style:padding="0"
style:margin-left="-0.5rem"
style:color={patchStatusColor[state.status]}
style:background-color={patchStatusBackgroundColor[state.status]}>
<Icon
name={state.status === "open"
? "patch"
: `patch-${state.status}`} />
</span>
<span style:color="var(--color-text-secondary)">
{capitalize(state.status)}
</span>
</DropdownListItem>
{/snippet}
</DropdownList>
</div>
{/snippet}
</Popover>
</button>
{/snippet}
{#snippet popover()}
<div
style:border="1px solid var(--color-border-subtle)"
style:border-radius="var(--border-radius-sm)"
style:display="flex"
style:gap="0.5rem"
style:align-items="center"
style:background-color="var(--color-surface-canvas)">
<DropdownList
items={[
{ status: "open" },
{ status: "draft" },
{ status: "archived" },
] as State[]}>
{#snippet item(state)}
<DropdownListItem
selected={selectedState.status === state.status}
styleGap="0.5rem"
onclick={() => {
onSelect(state);
closeFocused();
}}>
<span
class="global-chip"
style:padding="0"
style:margin-left="-0.5rem"
style:color={patchStatusColor[state.status]}
style:background-color={patchStatusBackgroundColor[
state.status
]}>
<Icon
name={state.status === "open"
? "patch"
: `patch-${state.status}`} />
</span>
<span style:color="var(--color-text-secondary)">
{capitalize(state.status)}
</span>
</DropdownListItem>
{/snippet}
</DropdownList>
</div>
{/snippet}
</Popover>
{/if}
+47 -6
View File
@@ -3,9 +3,11 @@
import type { Patch } from "@bindings/cob/patch/Patch";
import { draftReviewStorage } from "@app/lib/draftReviewStorage";
import { cachedDiffStats } from "@app/lib/invoke";
import { cachedConfig, cachedDiffStats } from "@app/lib/invoke";
import { entriesFromReviewers } from "@app/lib/reviewSummary";
import { push } from "@app/lib/router";
import {
absoluteTimestamp,
authorForNodeId,
formatTimestamp,
patchStatusBackgroundColor,
@@ -18,6 +20,7 @@
import InlineTitle from "@app/components/InlineTitle.svelte";
import Label from "@app/components/Label.svelte";
import NodeId from "@app/components/NodeId.svelte";
import ReviewSummary from "@app/components/ReviewSummary.svelte";
interface Props {
focussed?: boolean;
@@ -28,9 +31,29 @@
const { focussed, patch, rid, status }: Props = $props();
const hasDraftReview = $derived(
patch.revisionIds.some(id => draftReviewStorage.hasForRevision(id)),
);
// Drafts belong to an identity, so the marker has to know who is signed in.
// Until the config arrives the marker stays off rather than showing someone
// else's draft.
let publicKey: string | undefined = $state();
$effect(() => {
let cancelled = false;
void cachedConfig()
.then(result => {
if (!cancelled) publicKey = result.publicKey;
})
.catch(() => undefined);
return () => {
cancelled = true;
};
});
const hasDraftReview = $derived.by(() => {
const nid = publicKey;
if (nid === undefined) return false;
return patch.revisionIds.some(id =>
draftReviewStorage.hasForRevision(id, nid),
);
});
</script>
<style>
@@ -101,8 +124,10 @@
<div class="global-flex txt-body-m-regular" style:flex-wrap="wrap">
<NodeId {...authorForNodeId(patch.author)} />
opened
<Id id={patch.id} clipboard={patch.id} />
{formatTimestamp(patch.timestamp)}
<Id id={patch.id} clipboard={patch.id} label="patch ID" />
<span title={absoluteTimestamp(patch.timestamp)}>
{formatTimestamp(patch.timestamp)}
</span>
</div>
</div>
</div>
@@ -127,6 +152,22 @@
{#each patch.labels as label}
<Label {label} />
{/each}
{#if patch.commentCount > 0}
<div
class="txt-body-m-regular global-flex"
style:gap="0.25rem"
style:border="1px solid var(--color-border-subtle)"
style:border-radius="var(--border-radius-sm)"
style:height="1.5rem"
style:padding="0 0.5rem"
style:color="var(--color-text-tertiary)">
<Icon name="comment" />
{patch.commentCount}
</div>
{/if}
<ReviewSummary
reviews={entriesFromReviewers(patch.reviewers)}
revisionCount={patch.revisionIds.length} />
<div
class="txt-body-m-regular global-flex"
style:gap="0.25rem"
-326
View File
@@ -1,326 +0,0 @@
<script lang="ts">
import type { Author } from "@bindings/cob/Author";
import type { Operation } from "@bindings/cob/Operation";
import type { Action } from "@bindings/cob/patch/Action";
type FlattenedOperation = Action & {
id: string;
author: Author;
timestamp: number;
previous?: Action;
};
type StateTracker = Record<Action["type"], Action>;
import {
absoluteTimestamp,
authorForNodeId,
formatTimestamp,
patchStatusColor,
pluralize,
} from "@app/lib/utils";
import Icon from "@app/components/Icon.svelte";
import Id from "@app/components/Id.svelte";
import NodeId from "@app/components/NodeId.svelte";
interface Props {
patchId: string;
activity: Operation<Action>[];
}
/* eslint-disable prefer-const */
let { activity, patchId }: Props = $props();
/* eslint-enable prefer-const */
const timeline = $derived(enrichActivity(flattenActivity(activity)));
function flattenActivity(
activity: Operation<Action>[],
): FlattenedOperation[] {
return activity.flatMap(operation =>
operation.actions.map(action => ({
...action,
id: operation.id,
author: operation.author,
timestamp: operation.timestamp,
})),
);
}
function enrichActivity(
flatActivity: FlattenedOperation[],
): FlattenedOperation[] {
const result: FlattenedOperation[] = [];
const timelineStateTracker: StateTracker = {} as StateTracker;
flatActivity.forEach(entry => {
if (timelineStateTracker[entry.type]) {
result.push({ ...entry, previous: timelineStateTracker[entry.type] });
} else {
result.push(entry);
}
timelineStateTracker[entry.type] = entry;
});
return result;
}
function itemDiff<A>(previousState: A[], newState: A[]) {
const removed = previousState.filter(x => !newState.includes(x));
const added = newState.filter(x => !previousState.includes(x));
return { removed, added };
}
</script>
<style>
.timeline {
display: flex;
gap: 0.75rem;
flex-direction: column;
}
.timeline-item {
display: flex;
align-items: flex-start;
gap: 0.5rem;
word-break: break-word;
}
.wrapper {
display: flex;
flex-wrap: wrap;
gap: 0.25rem;
}
.icon {
padding-top: 0.1875rem;
}
</style>
<div class="timeline txt-body-m-regular">
{#each timeline as op}
{#if op.type === "revision"}
{#if op.id === patchId}
<div class="timeline-item">
<div class="icon" style:color="var(--color-feedback-success-text)">
<Icon name="patch" />
</div>
<div class="wrapper">
<NodeId {...authorForNodeId(op.author)} />
<div>
opened patch <Id id={op.id} clipboard={op.id} />
</div>
<div title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
{:else}
<div class="timeline-item">
<div class="icon">
<Icon name="revision" />
</div>
<div class="wrapper">
<NodeId {...authorForNodeId(op.author)} />
<div>
created revision <Id id={op.id} clipboard={op.id} />
</div>
<div title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
{/if}
{:else if op.type === "lifecycle"}
<div class="timeline-item">
<div class="icon" style:color={patchStatusColor[op.state.status]}>
<Icon
name={op.state.status === "open"
? "patch"
: `patch-${op.state.status}`} />
</div>
<div class="wrapper">
<NodeId {...authorForNodeId(op.author)} />
{#if op.state.status === "draft"}
converted patch to draft
{:else if op.state.status === "archived"}
archived patch
{:else if op.state.status === "open"}
reopened patch
{/if}
<div title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
{:else if op.type === "label"}
<div class="timeline-item">
<div class="icon">
<Icon name="label" />
</div>
<div class="wrapper">
<NodeId {...authorForNodeId(op.author)} />
{#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.added.length)}
{#each changed.added as label}
<b>{label}</b>
{/each}
{/if}
{#if changed.removed.length}
removed {pluralize("label", changed.removed.length)}
{#each changed.removed as label}
<b>{label}</b>
{/each}
{/if}
{/if}
{:else}
added {pluralize("label", op.labels.length)}
{#each op.labels as label}
<b>{label}</b>
{/each}
{/if}
<div title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
{:else if op.type === "assign"}
<div class="timeline-item">
<div class="icon">
<Icon name="avatar-incognito" />
</div>
<div class="wrapper">
<NodeId {...authorForNodeId(op.author)} />
{#if op.previous && op.previous.type === op.type}
{@const changed = itemDiff<Author>(
op.previous?.assignees ?? [],
op.assignees,
)}
{#if changed.added.length}
assigned
{#each changed.added as assignee}
<NodeId {...authorForNodeId(assignee)} />
{/each}
{/if}
{#if changed.removed.length}
unassigned
{#each changed.removed as assignee}
<NodeId {...authorForNodeId(assignee)} />
{/each}
{/if}
{:else}
assigned
{#each op.assignees as assignee}
<NodeId {...authorForNodeId(assignee)} />
{/each}
{/if}
<div title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
{:else if op.type === "merge"}
<div class="timeline-item">
<div class="icon" style:color="var(--color-brand-bg)">
<Icon name="patch-merged" />
</div>
<div class="wrapper">
<NodeId {...authorForNodeId(op.author)} />
<div>
merged patch at revision <Id
id={op.revision}
clipboard={op.revision} />
</div>
<div title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
{:else if op.type === "edit"}
{#if op.previous && op.previous.type === op.type}
<div class="timeline-item">
<div class="icon">
<Icon name="edit" />
</div>
<div class="wrapper">
<NodeId {...authorForNodeId(op.author)} />
changed title
<s>{op.previous.title}</s>
-> {op.title}
<div title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
{/if}
{:else if op.type === "review"}
<div class="timeline-item">
{#if op.verdict === "accept"}
<div class="icon" style:color="var(--color-feedback-success-text)">
<Icon name="thumbs-up" />
</div>
<div class="wrapper">
<NodeId {...authorForNodeId(op.author)} />
accepted revision <Id id={op.revision} clipboard={op.revision} />
<div title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
{:else if op.verdict === "reject"}
<div class="icon" style:color="var(--color-feedback-error-text)">
<Icon name="stop" />
</div>
<div class="wrapper">
<NodeId {...authorForNodeId(op.author)} />
rejected revision <Id id={op.revision} clipboard={op.revision} />
<div title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
{:else if op.verdict === undefined}
<div class="icon">
<Icon name="comment" />
</div>
<div class="wrapper">
<NodeId {...authorForNodeId(op.author)} />
reviewed revision <Id id={op.revision} clipboard={op.revision} />
<div title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
{/if}
</div>
{:else if op.type === "review.comment"}
<div class="timeline-item">
<div class="icon">
<Icon name="comment" />
</div>
<div class="wrapper">
<NodeId {...authorForNodeId(op.author)} />
{op.replyTo ? "replied to a comment" : "commented"} on review <Id
id={op.review}
clipboard={op.review} />
<div title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
{:else if op.type === "revision.comment"}
<div class="timeline-item">
<div class="icon">
<Icon name="comment" />
</div>
<div class="wrapper">
<NodeId {...authorForNodeId(op.author)} />
{op.replyTo ? "replied to a comment" : "commented"} on revision <Id
id={op.revision}
clipboard={op.revision} />
<div title={absoluteTimestamp(op.timestamp)}>
{formatTimestamp(op.timestamp)}
</div>
</div>
</div>
{/if}
{/each}
</div>
+3
View File
@@ -8,7 +8,10 @@
<style>
.container {
min-width: 0;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
-webkit-touch-callout: initial;
-webkit-user-select: text;
user-select: text;
+3 -1
View File
@@ -45,7 +45,9 @@
<Popover {placement} popoverPadding="0">
{#snippet toggle(onclick)}
<Icon name="emoji" {onclick} />
<span class="global-icon-button" title="React">
<Icon name="emoji" {onclick} />
</span>
{/snippet}
{#snippet popover()}
<div
-471
View File
@@ -1,471 +0,0 @@
<script lang="ts">
import type { Author } from "@bindings/cob/Author";
import type { Review } from "@bindings/cob/patch/Review";
import type { Revision } from "@bindings/cob/patch/Revision";
import type { CodeLocation } from "@bindings/cob/thread/CodeLocation";
import type { Embed } from "@bindings/cob/thread/Embed";
import type { Thread } from "@bindings/cob/thread/Thread";
import type { Config } from "@bindings/config/Config";
import type { RepoInfo } from "@bindings/repo/RepoInfo";
import partial from "lodash/partial";
import type { DraftReview } from "@app/lib/draftReviewStorage";
import { draftReviewStorage } from "@app/lib/draftReviewStorage";
import { nodeRunning } from "@app/lib/events";
import { invoke } from "@app/lib/invoke";
import * as roles from "@app/lib/roles";
import * as router from "@app/lib/router";
import { formatOid, publicKeyFromDid, truncateId } from "@app/lib/utils";
import { announce } from "@app/components/AnnounceSwitch.svelte";
import Button from "@app/components/Button.svelte";
import Changes from "@app/components/Changes.svelte";
import CommentComponent from "@app/components/Comment.svelte";
import Discussion from "@app/components/Discussion.svelte";
import Icon from "@app/components/Icon.svelte";
import Id from "@app/components/Id.svelte";
import ScrollArea from "@app/components/ScrollArea.svelte";
import VerdictBadge from "@app/components/VerdictBadge.svelte";
import VerdictButton from "@app/components/VerdictButton.svelte";
interface Props {
config: Config;
onNavigateBack: () => void;
patchId: string;
loadReview: () => Promise<void>;
repo: RepoInfo;
review: Review | DraftReview;
revision: Revision;
}
const {
config,
onNavigateBack,
patchId,
loadReview,
repo,
review,
revision,
}: Props = $props();
let publishingInProgress = $state(false);
const canPublish = $derived(review.verdict || review.summary);
const commentThreads = $derived(
((review.comments &&
review.comments
.filter(
comment =>
(!comment.location &&
comment.id !== review.id &&
!comment.replyTo) ||
comment.replyTo === review.id,
)
.map(thread => {
return {
root: thread,
replies:
review.comments &&
review.comments
.filter(comment => comment.replyTo === thread.id)
.sort((a, b) => a.edits[0].timestamp - b.edits[0].timestamp),
};
}, [])) as Thread[]) || [],
);
const codeCommentThreads = $derived(
((review.comments &&
review.comments
.filter(
comment =>
(comment.location &&
comment.id !== review.id &&
!comment.replyTo) ||
comment.replyTo === review.id,
)
.map(thread => {
return {
root: thread,
replies:
review.comments &&
review.comments
.filter(comment => comment.replyTo === thread.id)
.sort((a, b) => a.edits[0].timestamp - b.edits[0].timestamp),
};
}, [])) as Thread<CodeLocation>[]) || [],
);
// The verdict prop seeds a local working copy that the form mutates until
// submit; later prop updates intentionally do not overwrite it.
// svelte-ignore state_referenced_locally
let verdict: Review["verdict"] = $state(review.verdict);
async function editReview(
reviewId: string,
verdict: Review["verdict"],
labels: string[],
summary?: string,
) {
if (summary?.trim() === "") {
summary = undefined;
} else {
summary = summary?.trim();
}
try {
if ("draft" in review) {
draftReviewStorage.update(review.id, {
verdict,
summary: summary ?? "",
labels,
});
} else {
await invoke("edit_patch", {
rid: repo.rid,
cobId: patchId,
action: {
type: "review.edit",
review: reviewId,
summary,
verdict,
labels,
},
opts: { announce: $nodeRunning && $announce },
});
}
} catch (error) {
console.error("Editing review failed: ", error);
} finally {
await loadReview();
}
}
async function createComment(
body: string,
embeds: Embed[],
replyTo?: string,
location?: CodeLocation,
) {
try {
if ("draft" in review) {
draftReviewStorage.addComment(review.id, {
body,
location: location!,
});
} else {
await invoke("edit_patch", {
rid: repo.rid,
cobId: patchId,
action: {
type: "review.comment",
review: review.id,
body,
embeds,
replyTo,
location,
},
opts: { announce: $nodeRunning && $announce },
});
}
} catch (error) {
console.error("Creating comment failed", error);
} finally {
await loadReview();
}
}
async function editComment(commentId: string, body: string, embeds: Embed[]) {
try {
if ("draft" in review) {
draftReviewStorage.updateComment(review.id, commentId, {
body,
});
} else {
await invoke("edit_patch", {
rid: repo.rid,
cobId: patchId,
action: {
type: "review.comment.edit",
comment: commentId,
body,
review: review.id,
embeds,
},
opts: { announce: $nodeRunning && $announce },
});
}
} catch (error) {
console.error("Editing comment failed: ", error);
} finally {
await loadReview();
}
}
async function reactOnComment(
commentId: string,
authors: Author[],
reaction: string,
) {
if ("draft" in review) {
throw new Error("Cannot react on comment for draft review");
}
try {
await invoke("edit_patch", {
rid: repo.rid,
cobId: patchId,
action: {
type: "review.comment.react",
comment: commentId,
reaction,
review: review.id,
active: !authors.find(
({ did }) => publicKeyFromDid(did) === config.publicKey,
),
},
opts: { announce: $nodeRunning && $announce },
});
} catch (error) {
console.error("Editing comment reactions failed", error);
} finally {
await loadReview();
}
}
async function changeCommentStatus(commentId: string, resolved: boolean) {
if ("draft" in review) {
throw new Error("Cannot change comment status for draft review");
}
try {
await invoke("edit_patch", {
rid: repo.rid,
cobId: patchId,
action: {
type: resolved
? "review.comment.resolve"
: "review.comment.unresolve",
comment: commentId,
review: review.id,
},
opts: { announce: $nodeRunning && $announce },
});
} catch (error) {
console.error("Updating comment status failed: ", error);
} finally {
await loadReview();
}
}
async function deleteDraftComment(commentId: string) {
if (!("draft" in review)) {
throw new Error("Cannot change comment status for draft review");
}
draftReviewStorage.deleteComment(review.id, commentId);
await loadReview();
}
</script>
<style>
.page {
display: flex;
flex-direction: column;
height: 100%;
}
.topbar {
display: flex;
align-items: center;
padding: 0 1rem;
height: 2.5rem;
flex-shrink: 0;
gap: 0.375rem;
border-bottom: 1px solid var(--color-border-subtle);
font: var(--txt-body-m-regular);
color: var(--color-text-secondary);
}
.topbar-link {
cursor: pointer;
background: none;
border: none;
padding: 0;
font: var(--txt-body-m-regular);
color: var(--color-text-secondary);
}
.topbar-link:hover {
color: var(--color-text-primary);
}
.title {
display: flex;
align-items: center;
gap: 0.75rem;
margin-bottom: 1rem;
font: var(--txt-heading-s);
}
.main {
padding: 1.5rem 2rem;
min-width: 0;
}
.review-body {
margin: 1rem 0;
background-color: var(--color-surface-canvas);
border-radius: var(--border-radius-md);
}
</style>
<div class="page">
<div class="topbar">
<Icon name="patch" />
<button
class="topbar-link"
onclick={() =>
router.push({
resource: "repo.patches",
rid: repo.rid,
status: undefined,
})}>
All Patches
</button>
<Icon name="chevron-right" />
<button class="topbar-link" onclick={onNavigateBack}>
{formatOid(patchId)}
</button>
<Icon name="chevron-right" />
<span>Review</span>
</div>
<ScrollArea style="flex: 1; min-height: 0;">
<div class="main">
<div class="title">
{#if "draft" in review}
<span
class="global-chip"
title="This review is not yet visible to your peers">
Draft
</span>
{/if}
<span>
{review.author.alias ??
truncateId(publicKeyFromDid(review.author.did))}'s verdict
</span>
{#if !!roles.isDelegateOrAuthor( config.publicKey, repo.delegates.map(delegate => delegate.did), review.author.did )}
<VerdictButton
selectedVerdict={verdict}
draft={"draft" in review}
summaryMissing={review.summary === undefined ||
review.summary.trim() === ""}
onSelect={async newVerdict => {
verdict = newVerdict;
await editReview(
review.id,
verdict,
review.labels,
review.summary,
);
}} />
{:else}
<VerdictBadge {verdict} />
{/if}
{#if "draft" in review}
<div class="global-flex" style:margin-left="auto" style:gap="0.5rem">
<Button
variant="naked"
styleHeight="2rem"
onclick={() => {
draftReviewStorage.delete(review.id);
void router.push({
resource: "repo.patch",
rid: repo.rid,
patch: patchId,
reviewId: undefined,
status: undefined,
});
}}>
<Icon name="trash" />Delete
</Button>
<Button
styleHeight="2rem"
variant="secondary"
title={canPublish
? undefined
: "Add a summary or select a verdict to publish the review"}
disabled={!canPublish || publishingInProgress}
onclick={async () => {
publishingInProgress = true;
try {
await draftReviewStorage.publish(review.id);
await router.push({
resource: "repo.patch",
rid: repo.rid,
patch: patchId,
reviewId: undefined,
status: undefined,
});
} finally {
publishingInProgress = false;
}
}}>
<Icon name="checkout" />Publish
</Button>
</div>
{/if}
</div>
<div class="review-body">
<CommentComponent
disableAttachments
rid={repo.rid}
currentUserNid={config.publicKey}
disallowEmptyBody={!("draft" in review) &&
review.verdict === undefined}
emptyBodyTooltip="Summary is mandatory when verdict is None"
styleWidth="100%"
caption={"draft" in review ? "draft review" : "published review"}
id={"draft" in review ? undefined : review.id}
author={review.author}
timestamp={"draft" in review ? undefined : review.timestamp}
editComment={(publicKeyFromDid(review.author.did) ===
config.publicKey ||
undefined) &&
partial(async (id: string, summary: string) => {
await editReview(id, verdict, review.labels, summary);
}, review.id)}
body={review.summary}>
{#snippet beforeTimestamp()}
on revision <Id id={revision.id} clipboard={revision.id} />
{/snippet}
</CommentComponent>
</div>
{#if !("draft" in review)}
<Discussion
cobId={patchId}
repoDelegates={repo.delegates}
rid={repo.rid}
{commentThreads}
{config}
{createComment}
{editComment}
{reactOnComment} />
{/if}
<Changes
codeComments={{
changeCommentStatus:
"draft" in review ? undefined : changeCommentStatus,
config,
createComment,
editComment,
reactOnComment: "draft" in review ? undefined : reactOnComment,
deleteComment: "draft" in review ? deleteDraftComment : undefined,
repoDelegates: repo.delegates,
canReply: !("draft" in review),
disableAttachments:
"draft" in review ? "Publish your review to attach files" : false,
rid: repo.rid,
threads: codeCommentThreads,
}}
rid={repo.rid}
{patchId}
{revision} />
</div>
</ScrollArea>
</div>
+303
View File
@@ -0,0 +1,303 @@
<script lang="ts">
import type { CodeComments } from "@app/components/Diff.svelte";
import type { Author } from "@bindings/cob/Author";
import type { CodeLocation } from "@bindings/cob/thread/CodeLocation";
import type { Embed } from "@bindings/cob/thread/Embed";
import type { Thread } from "@bindings/cob/thread/Thread";
import type { Config } from "@bindings/config/Config";
import type { Diff as DiffType } from "@bindings/diff/Diff";
import type { FileDiff } from "@bindings/diff/FileDiff";
import type { Hunk } from "@bindings/diff/Hunk";
import { cachedGetDiff } from "@app/lib/invoke";
import Diff from "@app/components/Diff.svelte";
import Icon from "@app/components/Icon.svelte";
interface Props {
rid: string;
base: string;
head: string;
threads: Thread<CodeLocation>[];
config: Config;
repoDelegates: Author[];
createComment?: (
body: string,
embeds: Embed[],
replyTo?: string,
location?: CodeLocation,
) => Promise<void>;
editComment?: (
commentId: string,
body: string,
embeds: Embed[],
) => Promise<void>;
deleteComment?: (commentId: string) => Promise<void>;
reactOnComment?: (
commentId: string,
authors: Author[],
reaction: string,
) => Promise<void>;
}
const {
rid,
base,
head,
threads,
config,
repoDelegates,
createComment,
editComment,
deleteComment,
reactOnComment,
}: Props = $props();
// Per-thread hunk expand state, keyed by the thread's root comment id.
let expandedThreads: Record<string, boolean> = $state({});
const noop = () => Promise.resolve();
// All threads passed to one instance belong to the same file, so the file
// header is rendered once and each thread's hunk stacks beneath it.
const path = $derived(threads[0]?.root.location?.path);
function codeCommentsFor(thread: Thread<CodeLocation>): CodeComments {
return {
config,
repoDelegates,
rid,
threads: [thread],
canReply: Boolean(createComment),
hideThreadFileHeader: true,
createComment: createComment ?? noop,
editComment: editComment ?? noop,
deleteComment,
reactOnComment,
};
}
function findFileDiff(
diff: DiffType,
location: CodeLocation,
): FileDiff | undefined {
return diff.files.find(file => {
if (file.status === "moved" || file.status === "copied") {
return file.oldPath === location.path || file.newPath === location.path;
}
return file.path === location.path;
});
}
function findHunk(file: FileDiff, location: CodeLocation): Hunk | undefined {
if (file.diff.type !== "plain") return undefined;
const range = location.new ?? location.old;
if (!range || range.type !== "lines") return undefined;
const targetSide: "old" | "new" = location.new ? "new" : "old";
return file.diff.hunks.find(hunk => {
const hunkRange = hunk[targetSide];
return (
hunkRange.start <= range.range.start && hunkRange.end >= range.range.end
);
});
}
function sliceHunkAroundRange(
hunk: Hunk,
range: { start: number; end: number },
side: "old" | "new",
context: number,
): Hunk {
const matches: number[] = [];
hunk.lines.forEach((line, idx) => {
let lineNo: number | undefined;
if (line.type === "context") {
lineNo = side === "new" ? line.lineNoNew : line.lineNoOld;
} else if (side === "new" && line.type === "addition") {
lineNo = line.lineNo;
} else if (side === "old" && line.type === "deletion") {
lineNo = line.lineNo;
}
if (lineNo !== undefined && lineNo >= range.start && lineNo < range.end) {
matches.push(idx);
}
});
if (matches.length === 0) return hunk;
const startIdx = Math.max(0, matches[0] - context);
const endIdx = Math.min(
hunk.lines.length - 1,
matches[matches.length - 1] + context,
);
if (startIdx === 0 && endIdx === hunk.lines.length - 1) return hunk;
const slicedLines = hunk.lines.slice(startIdx, endIdx + 1);
let oldStart: number | undefined;
let oldEnd: number | undefined;
let newStart: number | undefined;
let newEnd: number | undefined;
for (const line of slicedLines) {
if (line.type === "context") {
oldStart ??= line.lineNoOld;
oldEnd = line.lineNoOld;
newStart ??= line.lineNoNew;
newEnd = line.lineNoNew;
} else if (line.type === "addition") {
newStart ??= line.lineNo;
newEnd = line.lineNo;
} else if (line.type === "deletion") {
oldStart ??= line.lineNo;
oldEnd = line.lineNo;
}
}
const slicedOld =
oldStart !== undefined && oldEnd !== undefined
? { start: oldStart, end: oldEnd + 1 }
: hunk.old;
const slicedNew =
newStart !== undefined && newEnd !== undefined
? { start: newStart, end: newEnd + 1 }
: hunk.new;
const oldLen = slicedOld.end - slicedOld.start;
const newLen = slicedNew.end - slicedNew.start;
return {
header: `@@ -${slicedOld.start},${oldLen} +${slicedNew.start},${newLen} @@`,
lines: slicedLines,
old: slicedOld,
new: slicedNew,
};
}
function sliceFileDiff(file: FileDiff, hunk: Hunk): FileDiff {
if (file.diff.type !== "plain") return file;
return {
...file,
diff: { ...file.diff, hunks: [hunk] },
};
}
</script>
<style>
.wrapper {
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
overflow: hidden;
}
.wrapper :global(.container) {
padding-top: 0;
padding-bottom: 0;
}
.file-header {
display: flex;
align-items: center;
gap: 0.5rem;
font: var(--txt-body-m-regular);
color: var(--color-text-secondary);
padding: 0.5rem 0.75rem;
border-bottom: 1px solid var(--color-border-subtle);
background-color: var(--color-surface-canvas);
}
.file-path {
flex: 1 1 0;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.thread + .thread {
border-top: 1px solid var(--color-border-subtle);
}
.hunk-toolbar {
display: flex;
justify-content: flex-end;
padding: 0.25rem 0.5rem 0;
}
.toggle {
display: inline-flex;
align-items: center;
justify-content: center;
background: none;
border: none;
padding: 0.125rem;
border-radius: var(--border-radius-sm);
cursor: pointer;
color: var(--color-text-tertiary);
}
.toggle:hover,
.toggle:focus-visible {
color: var(--color-text-primary);
background-color: var(--color-surface-subtle);
}
.fallback {
font: var(--txt-body-m-regular);
color: var(--color-text-secondary);
}
</style>
{#await cachedGetDiff(rid, { base, head, unified: 3, highlight: true })}
<div class="fallback">Loading code…</div>
{:then diff}
{@const location0 = threads[0]?.root.location}
{#if path && location0}
{@const file = findFileDiff(diff, location0)}
{#if file}
<div class="wrapper">
<div class="file-header">
<span class="file-path">{path}</span>
</div>
{#each threads as thread (thread.root.id)}
{@const location = thread.root.location}
{#if location}
{@const hunk = findHunk(file, location)}
{#if hunk}
{@const codeRange = location.new ?? location.old}
{@const targetSide = location.new ? "new" : "old"}
{@const clampedHunk =
codeRange && codeRange.type === "lines"
? sliceHunkAroundRange(hunk, codeRange.range, targetSide, 3)
: hunk}
{@const isClamped = clampedHunk !== hunk}
{@const expanded = expandedThreads[thread.root.id] ?? false}
{@const displayHunk = expanded ? hunk : clampedHunk}
<div class="thread">
{#if isClamped}
<div class="hunk-toolbar">
<button
class="toggle"
type="button"
title={expanded ? "Collapse hunk" : "Expand hunk"}
onclick={() =>
(expandedThreads = {
...expandedThreads,
[thread.root.id]: !expanded,
})}>
<Icon
name={expanded
? "collapse-vertical"
: "expand-vertical"} />
</button>
</div>
{/if}
<Diff
file={sliceFileDiff(file, displayHunk)}
{head}
codeComments={codeCommentsFor(thread)} />
</div>
{:else}
<div class="fallback">Code unavailable for {location.path}</div>
{/if}
{/if}
{/each}
</div>
{:else}
<div class="fallback">Code unavailable for {path}</div>
{/if}
{/if}
{/await}
+118
View File
@@ -0,0 +1,118 @@
<script lang="ts">
import type { Author } from "@bindings/cob/Author";
import type { Verdict } from "@bindings/cob/patch/Verdict";
import {
absoluteTimestamp,
authorForNodeId,
formatTimestamp,
verdictBadge,
} from "@app/lib/utils";
import Icon from "@app/components/Icon.svelte";
import Markdown from "@app/components/Markdown.svelte";
import NodeId from "@app/components/NodeId.svelte";
interface Props {
rid: string;
author: Author;
verdict?: Verdict;
summary: string;
timestamp: number;
onViewFullReview?: () => void;
}
const { rid, author, verdict, summary, timestamp, onViewFullReview }: Props =
$props();
const badge = $derived(verdictBadge(verdict));
</script>
<style>
.review {
display: flex;
flex-direction: column;
gap: 0.5rem;
padding: 0.5rem 0;
background-color: var(--color-surface-canvas);
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-sm);
}
.header {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.5rem;
padding: 0 0.75rem;
min-height: 1.5rem;
font: var(--txt-body-m-regular);
}
.caption,
.timestamp {
color: var(--color-text-quaternary);
}
.badge {
flex-shrink: 0;
white-space: nowrap;
padding: 0.125rem 0.375rem;
border-radius: var(--border-radius-sm);
}
.badge.accept {
background-color: var(--color-feedback-success-bg);
color: var(--color-feedback-success-text);
}
.badge.reject {
background-color: var(--color-feedback-error-bg);
color: var(--color-feedback-error-text);
}
.badge.comment {
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
}
.view-full {
display: inline-flex;
align-items: center;
gap: 0.125rem;
margin-left: auto;
padding: 0.125rem 0.375rem;
border: 1px solid transparent;
border-radius: var(--border-radius-sm);
background: none;
font: inherit;
color: var(--color-text-secondary);
white-space: nowrap;
cursor: pointer;
}
.view-full:hover,
.view-full:focus-visible {
background-color: var(--color-surface-subtle);
color: var(--color-text-primary);
}
.body {
padding: 0 0.75rem;
word-wrap: break-word;
overflow-wrap: anywhere;
}
</style>
<div class="review">
<div class="header">
<NodeId {...authorForNodeId(author)} />
<span class="caption">reviewed</span>
<span class="badge {badge.variant} txt-body-s-medium">{badge.label}</span>
<span class="timestamp" title={absoluteTimestamp(timestamp)}>
{formatTimestamp(timestamp)}
</span>
{#if onViewFullReview}
<button type="button" class="view-full" onclick={onViewFullReview}>
View full review
<Icon name="chevron-right" />
</button>
{/if}
</div>
{#if summary.trim() !== ""}
<div class="body txt-body-m-regular">
<Markdown {rid} breaks content={summary} />
</div>
{/if}
</div>
+792
View File
@@ -0,0 +1,792 @@
<script lang="ts">
import type { CommentOrigin } from "@app/components/Comment.svelte";
import type { CodeComments } from "@app/components/Diff.svelte";
import type { PatchView } from "@app/views/repo/router";
import type { Author } from "@bindings/cob/Author";
import type { Patch } from "@bindings/cob/patch/Patch";
import type { Review } from "@bindings/cob/patch/Review";
import type { Revision } from "@bindings/cob/patch/Revision";
import type { Verdict } from "@bindings/cob/patch/Verdict";
import type { CodeLocation } from "@bindings/cob/thread/CodeLocation";
import type { Comment } from "@bindings/cob/thread/Comment";
import type { Embed } from "@bindings/cob/thread/Embed";
import type { Thread } from "@bindings/cob/thread/Thread";
import type { Config } from "@bindings/config/Config";
import type { CommentOwner } from "@app/lib/codeCommentActions";
import { commentActions } from "@app/lib/codeCommentActions";
import { fileDiffPath } from "@app/lib/diffText";
import { nodeRunning } from "@app/lib/events";
import { isIgnoredFile } from "@app/lib/ignoredFiles";
import { cachedGetDiff, invoke } from "@app/lib/invoke";
import * as roles from "@app/lib/roles";
import { push } from "@app/lib/router";
import {
absoluteTimestamp,
authorForNodeId,
didFromPublicKey,
formatTimestamp,
publicKeyFromDid,
revisionPosition,
verdictAction,
verdictBadge,
verdictIcon,
} from "@app/lib/utils";
import { announce } from "@app/components/AnnounceSwitch.svelte";
import Button from "@app/components/Button.svelte";
import Discussion from "@app/components/Discussion.svelte";
import DropdownList from "@app/components/DropdownList.svelte";
import DropdownListItem from "@app/components/DropdownListItem.svelte";
import ExtendedTextarea from "@app/components/ExtendedTextarea.svelte";
import FileDiff from "@app/components/FileDiff.svelte";
import Icon from "@app/components/Icon.svelte";
import Id from "@app/components/Id.svelte";
import Markdown from "@app/components/Markdown.svelte";
import NodeId from "@app/components/NodeId.svelte";
import Popover, { closeFocused } from "@app/components/Popover.svelte";
interface Props {
config: Config;
loadPatch: () => Promise<void>;
patch: Patch;
repoDelegates: Author[];
review: Review;
revisions: Revision[];
rid: string;
status: Patch["state"]["status"] | undefined;
// The tab this review was opened from, so leaving it returns there.
fromView?: PatchView;
}
const {
config,
loadPatch,
patch,
repoDelegates,
review,
revisions,
rid,
status,
fromView,
}: Props = $props();
const isOwnPublishedReview = $derived(
review.author.did === didFromPublicKey(config.publicKey),
);
let verdictPickerExpanded = $state(false);
let savingVerdict = $state(false);
let editingSummary = $state(false);
let savingSummary = $state(false);
let deleteConfirmExpanded = $state(false);
let deleting = $state(false);
const verdictOptions: { value: Verdict | undefined; label: string }[] = (
[undefined, "accept", "reject"] as const
).map(value => ({ value, label: verdictAction(value) }));
async function createCodeComment(
body: string,
embeds: Embed[],
replyTo?: string,
location?: CodeLocation,
) {
// Commenting from inside a review joins that review, whoever authored it,
// so the comment is resolvable and travels with the verdict. Attribution
// stays per-comment, and the protocol allows anyone to comment on a review.
if (!replyTo) {
if (!location) return;
try {
await invoke("edit_patch", {
rid,
cobId: patch.id,
action: {
type: "review.comment",
review: review.id,
body,
location,
embeds,
},
opts: { announce: $nodeRunning && $announce },
});
} catch (error) {
console.error("Adding comment to review failed", error);
} finally {
await loadPatch();
}
return;
}
// Replies follow their parent: into the review, or onto the revision when
// replying to a standalone comment. Without a revision there is nothing to
// attach the latter to, so don't send an action with an empty target.
const toReview = reviewCommentIds.has(replyTo);
if (!toReview && !reviewedRevision) return;
try {
await invoke("edit_patch", {
rid,
cobId: patch.id,
action: toReview
? {
type: "review.comment",
review: review.id,
body,
replyTo,
embeds,
}
: {
type: "revision.comment",
revision: reviewedRevision?.id,
body,
replyTo,
embeds,
},
opts: { announce: $nodeRunning && $announce },
});
} catch (error) {
console.error("Replying to comment failed", error);
} finally {
await loadPatch();
}
}
async function saveSummary(newSummary: string) {
try {
savingSummary = true;
await invoke("edit_patch", {
rid,
cobId: patch.id,
action: {
type: "review.edit",
review: review.id,
summary: newSummary,
verdict: review.verdict,
labels: review.labels,
},
opts: { announce: $nodeRunning && $announce },
});
} catch (error) {
console.error("Editing review summary failed", error);
} finally {
savingSummary = false;
editingSummary = false;
await loadPatch();
}
}
async function deleteReview() {
try {
deleting = true;
closeFocused();
await invoke("edit_patch", {
rid,
cobId: patch.id,
action: { type: "review.redact", review: review.id },
opts: { announce: $nodeRunning && $announce },
});
} catch (error) {
console.error("Deleting review failed", error);
deleting = false;
return;
}
deleting = false;
backToPatch();
await loadPatch();
}
async function setVerdict(verdict: Verdict | undefined) {
if (verdict === review.verdict) {
closeFocused();
return;
}
try {
savingVerdict = true;
closeFocused();
await invoke("edit_patch", {
rid,
cobId: patch.id,
action: {
type: "review.edit",
review: review.id,
summary: review.summary ?? "",
verdict,
labels: review.labels,
},
opts: { announce: $nodeRunning && $announce },
});
} catch (error) {
console.error("Editing review verdict failed", error);
} finally {
savingVerdict = false;
await loadPatch();
}
}
// Comments on the review itself rather than on a line. The summary is a
// field, not the root of this thread, so a comment replying to the review id
// starts a root thread of its own.
const commentThreads: Thread[] = $derived.by(() => {
const comments = (review.comments ?? []) as Comment<CodeLocation>[];
return comments
.filter(c => (!c.location && !c.replyTo) || c.replyTo === review.id)
.map(root => ({
root,
replies: comments
.filter(c => c.replyTo === root.id)
.sort((a, b) => a.edits[0].timestamp - b.edits[0].timestamp),
})) as unknown as Thread[];
});
async function createDiscussionComment(
body: string,
embeds: Embed[],
replyTo?: string,
) {
try {
await invoke("edit_patch", {
rid,
cobId: patch.id,
action: {
type: "review.comment",
review: review.id,
body,
replyTo,
embeds,
},
opts: { announce: $nodeRunning && $announce },
});
} catch (error) {
console.error("Commenting on review failed", error);
} finally {
await loadPatch();
}
}
type FileGroup = {
path: string;
threads: Thread<CodeLocation>[];
};
const reviewedRevision: Revision | undefined = $derived(
revisions.find(r => r.reviews?.some(rev => rev.id === review.id)),
);
// 1-based position of the reviewed revision, so the page can say which
// revision (of how many) this review is of.
const reviewedRevisionNumber = $derived(
reviewedRevision
? revisionPosition(revisions, reviewedRevision.id)
: undefined,
);
// Ids of comments that belong to the review itself (as opposed to standalone
// code comments left directly on the revision), so edits/replies target the
// right action.
const reviewCommentIds = $derived(
new Set((review.comments as Comment<CodeLocation>[]).map(c => c.id)),
);
// Threads here mix this review's own comments with standalone comments on
// the reviewed revision, so each mutation resolves its target first.
function ownerOf(commentId: string): CommentOwner | undefined {
if (reviewCommentIds.has(commentId)) {
return { kind: "review", reviewId: review.id };
}
if (reviewedRevision) {
return { kind: "revision", revisionId: reviewedRevision.id };
}
return undefined;
}
// The protocol lets the comment author, the review author or the revision
// author resolve a review comment; delegates may do anything. Standalone
// revision comments have no resolve action at all.
function canResolveComment(commentId: string): boolean {
if (ownerOf(commentId)?.kind !== "review") return false;
if (
roles.isDelegate(
config.publicKey,
repoDelegates.map(d => d.did),
)
) {
return true;
}
const comment = (review.comments ?? []).find(c => c.id === commentId);
return [
comment?.author.did,
review.author.did,
reviewedRevision?.author.did,
].some(
did => did !== undefined && publicKeyFromDid(did) === config.publicKey,
);
}
const codeActions = $derived(
commentActions({
rid,
patchId: patch.id,
publicKey: config.publicKey,
announce: $nodeRunning && $announce,
ownerOf,
reload: loadPatch,
}),
);
const fileGroups: FileGroup[] = $derived.by(() => {
// eslint-disable-next-line svelte/prefer-svelte-reactivity
const groups = new Map<string, Thread<CodeLocation>[]>();
const addThreads = (
comments: Comment<CodeLocation>[],
excludeId: string,
) => {
const roots = comments.filter(
c => c.location && !c.replyTo && c.id !== excludeId,
);
for (const root of roots) {
const replies = comments
.filter(c => c.replyTo === root.id)
.sort((a, b) => a.edits[0].timestamp - b.edits[0].timestamp);
const thread = { root, replies } as Thread<CodeLocation>;
const path = root.location!.path;
const list = groups.get(path) ?? [];
list.push(thread);
groups.set(path, list);
}
};
addThreads(review.comments as Comment<CodeLocation>[], review.id);
// Standalone code comments left directly on the reviewed revision (not part
// of the review itself) also belong on this page.
if (reviewedRevision?.discussion) {
addThreads(reviewedRevision.discussion, reviewedRevision.id);
}
return [...groups.entries()].map(([path, threads]) => ({ path, threads }));
});
// Standalone comments render next to the review's own and look identical,
// but nothing can resolve them and their edits target the revision, so they
// say where they live.
const threadOrigins: Record<string, CommentOrigin> = $derived.by(() => {
const origins: Record<string, CommentOrigin> = {};
for (const group of fileGroups) {
for (const thread of group.threads) {
if (reviewCommentIds.has(thread.root.id)) continue;
origins[thread.root.id] = {
text: "on the revision",
title: "Left directly on the revision, not part of this review",
};
}
}
return origins;
});
// File paths that carry review comments; those files start expanded, the
// rest of the changed files render collapsed.
const commentedPaths = $derived(new Set(fileGroups.map(g => g.path)));
const reviewCodeComments: CodeComments = $derived({
config,
repoDelegates,
rid,
threads: fileGroups.flatMap(g => g.threads),
threadOrigins,
canReply: true,
hideThreadFileHeader: true,
createComment: createCodeComment,
editComment: codeActions.editComment,
deleteComment: codeActions.deleteComment,
changeCommentStatus: codeActions.changeCommentStatus,
canResolveComment,
reactOnComment: codeActions.reactOnComment,
});
const verdict = $derived(review.verdict);
const timestamp = $derived(review.timestamp);
const summary = $derived(review.summary?.trim() ?? "");
const backCaption = $derived(
fromView === "changes" ? "Back to changes" : "Back to activity",
);
function backToPatch() {
void push({
resource: "repo.patch",
rid,
patch: patch.id,
status,
reviewId: undefined,
view: fromView === "changes" ? "changes" : undefined,
});
}
</script>
<style>
.header {
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
margin-bottom: 0.75rem;
}
.back {
background-color: var(--color-surface-canvas);
border: 1px solid var(--color-border-subtle);
padding: 0.375rem 0.625rem;
border-radius: var(--border-radius-sm);
cursor: pointer;
color: var(--color-text-secondary);
display: inline-flex;
align-items: center;
gap: 0.375rem;
font: var(--txt-body-m-regular);
}
.back:hover,
.back:focus-visible {
color: var(--color-text-primary);
background-color: var(--color-surface-subtle);
}
.meta {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.5rem;
margin-bottom: 1.5rem;
color: var(--color-text-secondary);
font: var(--txt-body-m-regular);
}
.meta :global(*) {
font: inherit;
}
.verdict-chip {
display: inline-flex;
align-items: center;
gap: 0.375rem;
padding: 0.125rem 0.5rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-canvas);
/* Inherit the meta text colour; without this the <button> variant falls
back to the UA `ButtonText` system colour, which is unreadable on the
dark surface. */
color: inherit;
font: inherit;
}
.verdict-chip.accept {
background-color: var(--color-feedback-success-bg);
border-color: transparent;
color: var(--color-feedback-success-text);
}
.verdict-chip.reject {
background-color: var(--color-feedback-error-bg);
border-color: transparent;
color: var(--color-feedback-error-text);
}
.summary {
position: relative;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
padding: 0.75rem 1rem;
margin-bottom: 1.5rem;
font: var(--txt-body-m-regular);
}
.summary-empty {
color: var(--color-text-tertiary);
}
.summary-edit {
position: absolute;
top: 0.375rem;
right: 0.375rem;
opacity: 0;
transition: opacity 150ms ease;
}
.summary:hover .summary-edit,
.summary:focus-within .summary-edit,
.summary-edit:focus-visible {
opacity: 1;
}
.summary-editor {
margin-bottom: 1.5rem;
}
.action-icon {
background: none;
border: 1px solid transparent;
cursor: pointer;
color: var(--color-text-tertiary);
padding: 0.25rem;
border-radius: var(--border-radius-sm);
display: inline-flex;
align-items: center;
justify-content: center;
}
.action-icon:hover:not(:disabled),
.action-icon:focus-visible {
color: var(--color-text-primary);
background-color: var(--color-surface-subtle);
}
.action-icon:disabled {
cursor: progress;
opacity: 0.6;
}
.delete-confirm {
padding: 0.75rem;
display: flex;
flex-direction: column;
gap: 0.75rem;
background-color: var(--color-surface-canvas);
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-sm);
max-width: 20rem;
}
.delete-confirm-message {
font: var(--txt-body-m-regular);
color: var(--color-text-primary);
}
.delete-confirm-actions {
display: flex;
gap: 0.5rem;
justify-content: flex-end;
}
.delete-confirm-button {
display: inline-flex;
align-items: center;
gap: 0.375rem;
background-color: var(--color-feedback-error-bg);
color: var(--color-feedback-error-text);
border: 1px solid var(--color-feedback-error-text);
border-radius: var(--border-radius-sm);
padding: 0.25rem 0.75rem;
cursor: pointer;
font: var(--txt-body-m-medium);
}
.delete-confirm-button:hover:not(:disabled),
.delete-confirm-button:focus-visible {
background-color: var(--color-feedback-error-text);
color: var(--color-surface-canvas);
}
.delete-confirm-button:disabled {
cursor: progress;
opacity: 0.6;
}
.threads {
display: flex;
flex-direction: column;
gap: 1rem;
}
.timestamp {
color: var(--color-text-quaternary);
}
.verdict-toggle {
cursor: pointer;
font: inherit;
}
.verdict-toggle:not(.accept):not(.reject):hover,
.verdict-toggle:not(.accept):not(.reject):focus-visible {
background-color: var(--color-surface-subtle);
}
.verdict-toggle.accept:hover,
.verdict-toggle.accept:focus-visible,
.verdict-toggle.reject:hover,
.verdict-toggle.reject:focus-visible {
filter: brightness(0.97);
}
.verdict-toggle:disabled {
cursor: progress;
opacity: 0.6;
}
.verdict-accept {
color: var(--color-feedback-success-text);
}
.verdict-reject {
color: var(--color-feedback-error-text);
}
</style>
<div class="header">
<button type="button" class="back" onclick={backToPatch} title={backCaption}>
<Icon name="arrow-left" />
{backCaption}
</button>
</div>
<div class="meta">
<NodeId {...authorForNodeId(review.author)} />
{#if isOwnPublishedReview}
{@const verdictLabel = verdictBadge(verdict).label}
<Popover
popoverPadding="0"
placement="bottom-start"
bind:expanded={verdictPickerExpanded}>
{#snippet toggle(onclick)}
<button
type="button"
class="verdict-chip verdict-toggle"
class:accept={verdict === "accept"}
class:reject={verdict === "reject"}
aria-haspopup="menu"
aria-expanded={verdictPickerExpanded}
disabled={savingVerdict}
{onclick}>
<Icon name={verdictIcon(verdict)} />
{verdictLabel}
<Icon name={verdictPickerExpanded ? "chevron-up" : "chevron-down"} />
</button>
{/snippet}
{#snippet popover()}
<div
style:border="1px solid var(--color-border-subtle)"
style:border-radius="var(--border-radius-sm)"
style:background-color="var(--color-surface-canvas)"
style:min-width="10rem">
<DropdownList items={verdictOptions}>
{#snippet item(option)}
{@const disabled = option.value === undefined && summary === ""}
<DropdownListItem
selected={verdict === option.value}
{disabled}
title={disabled
? "Add a summary before switching to Comment"
: undefined}
styleGap="0.5rem"
onclick={() => setVerdict(option.value)}>
<span
class:verdict-accept={option.value === "accept"}
class:verdict-reject={option.value === "reject"}>
<Icon name={verdictIcon(option.value)} />
</span>
{option.label}
</DropdownListItem>
{/snippet}
</DropdownList>
</div>
{/snippet}
</Popover>
{:else}
<span
class="verdict-chip"
class:accept={verdict === "accept"}
class:reject={verdict === "reject"}>
<Icon name={verdictIcon(verdict)} />
{verdict === "accept"
? "Accepted"
: verdict === "reject"
? "Rejected"
: "Reviewed"}
</span>
{/if}
{#if reviewedRevision}
<span>
Revision {reviewedRevisionNumber} of {revisions.length}
</span>
<Id
id={reviewedRevision.id}
clipboard={reviewedRevision.id}
label="revision ID" />
{/if}
<span class="timestamp" title={absoluteTimestamp(timestamp)}>
{formatTimestamp(timestamp)}
</span>
{#if isOwnPublishedReview}
<span style:margin-left="auto"></span>
<Popover
popoverPadding="0"
placement="bottom-end"
bind:expanded={deleteConfirmExpanded}>
{#snippet toggle(onclick)}
<button
type="button"
class="action-icon"
title="Delete review"
aria-haspopup="dialog"
aria-expanded={deleteConfirmExpanded}
disabled={deleting}
{onclick}>
<Icon name="trash" />
</button>
{/snippet}
{#snippet popover()}
<div class="delete-confirm">
<div class="delete-confirm-message">
Delete this review? This cannot be undone.
</div>
<div class="delete-confirm-actions">
<Button variant="naked" onclick={() => closeFocused()}>
Cancel
</Button>
<button
type="button"
class="delete-confirm-button"
onclick={deleteReview}
disabled={deleting}>
<Icon name="trash" />
Delete review
</button>
</div>
</div>
{/snippet}
</Popover>
{/if}
</div>
{#if editingSummary}
<div class="summary-editor">
<ExtendedTextarea
{rid}
body={review.summary ?? ""}
focus
submitCaption={savingSummary ? "Saving…" : "Save"}
disableSubmit={savingSummary}
submit={async ({ comment }) => {
await saveSummary(comment);
}}
close={() => (editingSummary = false)} />
</div>
{:else if summary !== "" || isOwnPublishedReview}
<div class="summary">
{#if summary !== ""}
<Markdown {rid} breaks content={summary} />
{:else}
<span class="summary-empty">No summary.</span>
{/if}
{#if isOwnPublishedReview}
<button
type="button"
class="action-icon summary-edit"
title="Edit summary"
onclick={() => (editingSummary = true)}>
<Icon name="edit" />
</button>
{/if}
</div>
{/if}
<Discussion
{repoDelegates}
cobId={patch.id}
{rid}
{commentThreads}
{config}
createComment={createDiscussionComment}
editComment={codeActions.editComment}
reactOnComment={codeActions.reactOnComment} />
{#if reviewedRevision}
{@const rev = reviewedRevision}
{#await cachedGetDiff( rid, { base: rev.base, head: rev.head, unified: 3, highlight: true } )}
<div class="threads-loading txt-body-m-regular">Loading changes…</div>
{:then diff}
<div class="threads">
{#each diff.files as file, i (i)}
{@const path = fileDiffPath(file)}
<!-- FileBlock renders the header and the body as siblings, so each
file needs its own wrapper; otherwise the parent's gap lands
between a file's header and its diff. -->
<div>
<FileDiff
{file}
head={rev.head}
{rid}
codeComments={reviewCodeComments}
expanded={commentedPaths.has(path) && !isIgnoredFile(file)} />
</div>
{/each}
</div>
{/await}
{/if}
+71
View File
@@ -0,0 +1,71 @@
<script lang="ts">
import Icon from "@app/components/Icon.svelte";
import UserAvatar from "@app/components/UserAvatar.svelte";
interface Props {
// Given when the chip navigates somewhere; otherwise it is a plain marker,
// as in the revision dropdown where the whole row is already clickable.
onclick?: () => void;
// Set where the column is too narrow for the wording: the chip shrinks to
// a pencil and this avatar, keeping the same colours.
nid?: string;
}
const { onclick, nid }: Props = $props();
</script>
<style>
.chip {
flex-shrink: 0;
white-space: nowrap;
padding: 0.125rem 0.375rem;
border: 0;
border-radius: var(--border-radius-sm);
background-color: var(--color-feedback-warning-bg);
color: var(--color-feedback-warning-text);
}
/* No fill and no accent at this size: the pencil and avatar read as a pair
of glyphs beside the review pairs rather than as a pill. */
.chip.compact {
display: inline-flex;
align-items: center;
gap: 0.25rem;
padding: 0;
background-color: transparent;
color: var(--color-text-tertiary);
}
button.chip {
cursor: pointer;
}
button.chip:hover,
button.chip:focus-visible {
background-color: var(--color-feedback-warning-text);
color: var(--color-feedback-warning-bg);
}
</style>
{#if nid}
<span
class="chip compact"
title="You have an unpublished review of this revision">
<Icon name="edit" />
<UserAvatar nodeId={nid} styleWidth="1rem" />
</span>
{:else if onclick}
<button
type="button"
class="chip txt-body-s-medium"
title="Go to your review in progress"
onclick={e => {
e.stopPropagation();
onclick();
}}>
Review in progress
</button>
{:else}
<span
class="chip txt-body-s-medium"
title="You have an unpublished review of this revision">
Review in progress
</span>
{/if}
+119
View File
@@ -0,0 +1,119 @@
<script lang="ts">
import type { ReviewEntry } from "@app/lib/reviewSummary";
import { reviewSummary, summaryTitle } from "@app/lib/reviewSummary";
import { publicKeyFromDid } from "@app/lib/utils";
import Icon from "@app/components/Icon.svelte";
import UserAvatar from "@app/components/UserAvatar.svelte";
interface Props {
reviews: ReviewEntry[];
// How many revisions the patch has, so the summary can tell whether any
// review still covers the current head. Omitted where the question doesn't
// arise — the revision picker already shows one revision's own reviews.
revisionCount?: number;
// Drops the frame where the summary sits among other columns rather than
// standing on its own.
borderless?: boolean;
}
const { reviews, revisionCount, borderless = false }: Props = $props();
const state = $derived(reviewSummary(reviews, revisionCount ?? 0));
</script>
<style>
.reviews {
display: inline-flex;
align-items: center;
gap: 0.375rem;
height: 1.5rem;
padding: 0 0.5rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-sm);
color: var(--color-text-tertiary);
white-space: nowrap;
}
.reviews.borderless {
border: 0;
padding: 0;
}
.reviewer-stack {
display: inline-flex;
align-items: center;
}
/* Each avatar is wrapped, so the stacking has to sit on the wrapper: with
the image nested, `img:first-child` matches every one of them and the
overlap never applies. */
.reviewer-stack .avatar {
display: inline-flex;
align-items: center;
margin-left: -0.375rem;
}
.reviewer-stack .avatar:first-child {
margin-left: 0;
}
.reviewer-stack .avatar :global(img) {
display: block;
outline: 1px solid var(--color-surface-canvas);
}
.reviewer-overflow {
margin-left: 0.25rem;
color: var(--color-text-tertiary);
}
.verdict-accept {
color: var(--color-feedback-success-text);
}
.verdict-reject {
color: var(--color-feedback-error-text);
}
/* Nothing here describes the current changes, so the whole chip recedes
rather than announcing itself with a word. The tooltip has the detail. */
.reviews.outdated {
color: var(--color-text-quaternary);
}
.revision-hint {
color: var(--color-text-quaternary);
}
</style>
{#if state.reviews.length > 0}
<div
class="reviews txt-body-m-regular"
class:borderless
class:outdated={state.outdated}
title={summaryTitle(state)}>
<span
class:verdict-accept={state.allAccept}
class:verdict-reject={state.hasReject}>
<Icon
name={state.outdated
? "clock"
: state.hasReject
? "stop"
: state.allAccept
? "thumbs-up"
: "comment"} />
</span>
<span>{state.reviews.length}</span>
{#if state.outdated}
<span
class="revision-hint"
aria-label="reviewed at revision {state.latestReviewedRevision}">
· r{state.latestReviewedRevision}
</span>
{/if}
<span class="reviewer-stack">
{#each state.authors.slice(0, 3) as author (author.did)}
<span class="avatar">
<UserAvatar nodeId={publicKeyFromDid(author.did)} styleWidth="1rem" />
</span>
{/each}
{#if state.authors.length > 3}
<span class="reviewer-overflow">
+{state.authors.length - 3}
</span>
{/if}
</span>
</div>
{/if}
File diff suppressed because it is too large Load Diff
-30
View File
@@ -1,30 +0,0 @@
<script lang="ts">
import type { Revision } from "@bindings/cob/patch/Revision";
interface Props {
revision: Revision;
revisions: Revision[];
}
/* eslint-disable prefer-const */
let { revision, revisions }: Props = $props();
/* eslint-enable prefer-const */
</script>
{#if revisions.length > 1}
{#if revision.id === revisions[0].id}
<span
class="global-chip"
style:height="1.375rem"
style:color="var(--color-text-primary)">
Initial
</span>
{:else if revision.id === revisions.slice(-1)[0].id}
<span
class="global-chip"
style:height="1.375rem"
style:color="var(--color-text-primary)">
Latest
</span>
{/if}
{/if}
-121
View File
@@ -1,121 +0,0 @@
<script lang="ts">
import type { PatchStatus } from "@app/views/repo/router";
import type { Patch } from "@bindings/cob/patch/Patch";
import type { Review } from "@bindings/cob/patch/Review";
import type { Revision } from "@bindings/cob/patch/Revision";
import type { Config } from "@bindings/config/Config";
import type { DraftReview } from "@app/lib/draftReviewStorage";
import { draftReviewStorage } from "@app/lib/draftReviewStorage";
import { push } from "@app/lib/router";
import {
authorForNodeId,
didFromPublicKey,
verdictIcon,
} from "@app/lib/utils";
import DropdownListItem from "@app/components/DropdownListItem.svelte";
import Icon from "@app/components/Icon.svelte";
import NodeId from "@app/components/NodeId.svelte";
interface Props {
config: Config;
patch: Patch;
revision: Revision;
rid: string;
status: PatchStatus | undefined;
}
const { config, patch, revision, rid, status }: Props = $props();
const reviews: Array<Review | DraftReview> = $derived(
[
draftReviewStorage.getForRevision(revision.id, {
did: didFromPublicKey(config.publicKey),
alias: config.alias,
}),
...(revision.reviews ?? []),
].filter((review): review is Review | DraftReview => Boolean(review)),
);
function unresolvedCommentsCount(review: Review | DraftReview) {
return review.comments.filter(t => {
return t.resolved === false && t.location !== null && t.replyTo === null;
}).length;
}
</script>
<style>
.status {
padding: 0;
}
.accepted {
color: var(--color-feedback-success-text);
}
.rejected {
color: var(--color-feedback-error-text);
}
.no-verdict {
color: var(--color-text-secondary);
}
</style>
{#each reviews as review}
<div style:margin="0.5rem 0">
<DropdownListItem
selected={false}
onclick={() => {
void push({
resource: "repo.patch",
rid,
patch: patch.id,
status,
reviewId: review.id,
});
}}>
<div
class="global-flex"
style:width="100%"
style:gap="0.25rem"
style:padding-left="1.5rem">
<div
style:margin-right="0.25rem"
class:accepted={review.verdict === "accept"}
class:rejected={review.verdict === "reject"}
class:no-verdict={review.verdict === undefined}
class="status">
<Icon name={verdictIcon(review.verdict)} />
</div>
<span class="global-flex" style:gap="0">
<NodeId {...authorForNodeId(review.author)} />'s
</span>
review
{#if "draft" in review}
<span
class="global-chip"
title="This review is not yet visible to your peers">
Draft
</span>
{/if}
<div class="global-flex" style:margin-left="auto">
{#if review.comments.length > 0}
{@const unresolved = unresolvedCommentsCount(review)}
{#if unresolved > 0}
<div class="global-flex" style:gap="0.25rem">
<Icon name="comment-cross" />
{unresolved}
</div>
{/if}
{#if unresolved === 0 || review.comments.length > unresolved}
<div class="global-flex" style:gap="0.25rem">
<Icon name="comment" />{review.comments.length}
</div>
{/if}
{/if}
</div>
</div>
</DropdownListItem>
</div>
{/each}
-104
View File
@@ -1,104 +0,0 @@
<script lang="ts">
import type { PatchStatus } from "@app/views/repo/router";
import type { Patch } from "@bindings/cob/patch/Patch";
import type { Revision } from "@bindings/cob/patch/Revision";
import type { Config } from "@bindings/config/Config";
import orderBy from "lodash/orderBy";
import uniqBy from "lodash/uniqBy";
import { authorForNodeId } from "@app/lib/utils";
import DropdownListItem from "@app/components/DropdownListItem.svelte";
import Icon from "@app/components/Icon.svelte";
import NodeId from "@app/components/NodeId.svelte";
import RevisionBadges from "@app/components/RevisionBadges.svelte";
import RevisionReviews from "@app/components/RevisionReviews.svelte";
interface Props {
config: Config;
patch: Patch;
revisions: Revision[];
rid: string;
selectRevision: (revision: Revision) => void;
selectedRevision: Revision;
status: PatchStatus | undefined;
}
const {
config,
patch,
revisions,
rid,
selectRevision,
selectedRevision,
status,
}: Props = $props();
const revisionAuthors = $derived(
orderBy(
uniqBy(
revisions.map(r => r.author),
"did",
),
[o => o.did === patch.author.did],
["desc"],
),
);
</script>
<style>
.author-revisions:not(:last-of-type) {
margin-bottom: 1.5rem;
}
</style>
{#each revisionAuthors as author}
<div class="author-revisions">
<div style:padding-bottom="0.5rem">
<span class="global-flex txt-body-m-regular" style:gap="0">
<NodeId {...authorForNodeId(author)} />'s revisions
</span>
</div>
{#each orderBy( revisions.filter(r => {
return r.author.did === author.did;
}), "timestamp", ["asc"] ) as revision}
<div style:margin="0.5rem 0">
<DropdownListItem
selected={revision.id === selectedRevision.id}
onclick={() => {
selectRevision(revision);
}}>
<div class="global-flex txt-overflow" style:width="100%">
{#if patch.state.status === "merged" && patch.state.revision === revision.id}
<div style:color="var(--color-brand-bg)">
<Icon name="patch-merged" />
</div>
{:else}
<Icon name="revision" />
{/if}
<span class="txt-id">
{revision.id.substring(0, 4)}
</span>
<RevisionBadges {revision} {revisions} />
<span class="txt-overflow">
{#if revision.description[0].body.trim()}
{revision.description[0].body.split("\n")[0]}
{:else}
<span class="txt-missing">No description.</span>
{/if}
</span>
<div class="global-flex" style:margin-left="auto">
{#if revision.discussion && revision.discussion.length > 0}
<div class="global-flex" style:gap="0.25rem">
<Icon name="comment" />{revision.discussion.length}
</div>
{/if}
</div>
</div>
</DropdownListItem>
</div>
<RevisionReviews {config} {rid} {status} {revision} {patch} />
{/each}
</div>
{/each}
+11 -3
View File
@@ -27,6 +27,7 @@
idLabel: string;
config: Config;
styleHeight?: ComponentProps<typeof Button>["styleHeight"];
variant?: ComponentProps<typeof Button>["variant"];
}
const {
@@ -35,6 +36,7 @@
idLabel,
config,
styleHeight = "2rem",
variant = "ghost",
}: Props = $props();
const url = $derived(explorerUrl(explorerPath, config));
@@ -102,6 +104,12 @@
background-color: var(--color-border-subtle);
border-radius: var(--border-radius-sm);
}
/* Naked buttons are transparent, so drop the divider background that would
otherwise show through and read as a grey fill. */
.split.naked {
background-color: transparent;
gap: 0;
}
</style>
<!-- Hidden anchor used for the "open" action so Tauri's shell plugin opens the
@@ -116,9 +124,9 @@
aria-hidden="true">
</a>
<div class="split">
<div class="split" class:naked={variant === "naked"}>
<Button
variant="ghost"
{variant}
{styleHeight}
flatRight
stylePadding="0 0.75rem"
@@ -135,7 +143,7 @@
bind:expanded={popoverExpanded}>
{#snippet toggle(onclick)}
<Button
variant="ghost"
{variant}
{styleHeight}
styleWidth={styleHeight}
flatLeft
+50 -20
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import type { CommentOrigin } from "@app/components/Comment.svelte";
import type { Author } from "@bindings/cob/Author";
import type { CodeLocation } from "@bindings/cob/thread/CodeLocation";
import type { Embed } from "@bindings/cob/thread/Embed";
@@ -16,7 +17,9 @@
thread: Thread<CodeLocation>;
rid: string;
currentUserNid?: string;
canEditComment: (author: string) => true | undefined;
// Whether the current user may edit or delete a comment by this author.
// The protocol reserves both for the comment's own author.
canModifyComment: (author: string) => true | undefined;
editComment?: (
commentId: string,
body: string,
@@ -33,19 +36,32 @@
reaction: string,
) => Promise<void>;
deleteComment?: (commentId: string) => Promise<void>;
changeCommentStatus?: (
commentId: string,
resolved: boolean,
) => Promise<void>;
canResolve?: boolean;
// Set for threads rendered inside a diff, where there is no surrounding
// activity timeline for the outer rail to connect to.
inline?: boolean;
draft?: boolean;
origin?: CommentOrigin;
}
const {
thread,
rid,
currentUserNid,
canEditComment,
canModifyComment,
editComment,
createReply,
reactOnComment,
deleteComment,
changeCommentStatus,
canResolve = false,
inline = false,
draft = false,
origin,
}: Props = $props();
async function toggleReply() {
@@ -101,9 +117,11 @@
.replies-wrapper::after {
left: 1.25rem;
}
.replies-wrapper-inline {
background-color: var(--color-surface-canvas);
border: 1px solid var(--color-border-subtle);
/* The outer rail continues the surrounding activity timeline down to the
top-level composer. Inline code threads have no timeline around them, so
it would end in mid-air; only the reply indent line is drawn there. */
.replies-wrapper.inline::before {
content: none;
}
.replies-list {
display: flex;
@@ -138,9 +156,12 @@
reactions={reply.reactions}
timestamp={reply.edits[0].timestamp}
body={reply.edits.slice(-1)[0].body}
editComment={canEditComment(reply.author.did) &&
editComment={canModifyComment(reply.author.did) &&
editComment?.bind(null, reply.id)}
reactOnComment={reactOnComment?.bind(null, reply.id)} />
reactOnComment={reactOnComment?.bind(null, reply.id)}
deleteComment={canModifyComment(reply.author.did)
? deleteComment?.bind(null, reply.id)
: undefined} />
</div>
{/each}
{#if createReply && showReplyForm}
@@ -170,37 +191,46 @@
{/snippet}
<div class="comments">
<div class:top-level-comment={!inline}>
<div class="top-level-comment">
<CommentComponent
disallowEmptyBody
{rid}
{currentUserNid}
{draft}
{origin}
id={root.id}
lastEdit={root.edits.length > 1 ? root.edits.at(-1) : undefined}
author={root.author}
reactions={root.reactions}
timestamp={root.edits.slice(-1)[0].timestamp}
body={root.edits.slice(-1)[0].body}
editComment={canEditComment(root.author.did) &&
editComment={canModifyComment(root.author.did) &&
editComment?.bind(null, root.id)}
reactOnComment={reactOnComment?.bind(null, root.id)}
deleteComment={deleteComment?.bind(null, root.id)}>
deleteComment={canModifyComment(root.author.did)
? deleteComment?.bind(null, root.id)
: undefined}>
{#snippet actions()}
{#if changeCommentStatus && canResolve}
<span
class="global-icon-button"
title={root.resolved ? "Mark as unresolved" : "Mark as resolved"}>
<Icon
name={root.resolved ? "comment-checkmark" : "checkmark"}
onclick={() => changeCommentStatus(root.id, !root.resolved)} />
</span>
{/if}
{#if createReply}
<Icon name="reply" onclick={toggleReply} />
<span class="global-icon-button" title="Reply">
<Icon name="reply" onclick={toggleReply} />
</span>
{/if}
{/snippet}
</CommentComponent>
</div>
{#if replies.length > 0 || (createReply && showReplyForm)}
{#if inline}
<div class="replies-wrapper-inline">
{@render repliesSnippet()}
</div>
{:else}
<div class="replies-wrapper">
{@render repliesSnippet()}
</div>
{/if}
<div class="replies-wrapper" class:inline>
{@render repliesSnippet()}
</div>
{/if}
</div>
-61
View File
@@ -1,61 +0,0 @@
<script lang="ts">
import type { Review } from "@bindings/cob/patch/Review";
import type { Snippet } from "svelte";
import capitalize from "lodash/capitalize.js";
import { verdictIcon } from "@app/lib/utils";
import Icon from "@app/components/Icon.svelte";
interface Props {
children?: Snippet;
verdict: Review["verdict"];
hoverable?: boolean;
}
const { children, verdict, hoverable = false }: Props = $props();
</script>
<style>
.badge {
gap: 0.375rem;
padding-right: 0.625rem;
width: fit-content;
font: var(--txt-body-m-regular);
}
.no-verdict {
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
}
.no-verdict.hoverable:hover {
background-color: var(--color-surface-mid);
}
.accepted {
background-color: var(--color-feedback-success-bg);
color: var(--color-feedback-success-text);
}
.accepted.hoverable:hover {
background-color: var(--color-feedback-success-bg);
}
.rejected {
background-color: var(--color-feedback-error-bg);
color: var(--color-feedback-error-text);
}
.rejected.hoverable:hover {
background-color: var(--color-feedback-error-bg);
}
</style>
<span
class="global-chip badge"
class:hoverable
class:no-verdict={verdict === undefined}
class:accepted={verdict === "accept"}
class:rejected={verdict === "reject"}>
<Icon name={verdictIcon(verdict)} />
{verdict ? capitalize(`${verdict}ed`) : "None"}
{@render children?.()}
</span>
-98
View File
@@ -1,98 +0,0 @@
<script lang="ts">
import type { Review } from "@bindings/cob/patch/Review";
import capitalize from "lodash/capitalize.js";
import { verdictIcon } from "@app/lib/utils";
import Button from "@app/components/Button.svelte";
import DropdownList from "@app/components/DropdownList.svelte";
import DropdownListItem from "@app/components/DropdownListItem.svelte";
import Icon from "@app/components/Icon.svelte";
import Popover from "@app/components/Popover.svelte";
import { closeFocused } from "@app/components/Popover.svelte";
interface Props {
onSelect: (selectedVerdict: Review["verdict"]) => Promise<void>;
draft: boolean;
summaryMissing: boolean;
selectedVerdict: Review["verdict"];
}
const { onSelect, draft, summaryMissing, selectedVerdict }: Props = $props();
let popoverExpanded: boolean = $state(false);
function verdictBgColor(verdict: Review["verdict"]): string {
if (verdict === "accept") return "var(--color-feedback-success-bg)";
if (verdict === "reject") return "var(--color-feedback-error-bg)";
return "var(--color-surface-subtle)";
}
function verdictColor(verdict: Review["verdict"]): string {
if (verdict === "accept") return "var(--color-feedback-success-text)";
if (verdict === "reject") return "var(--color-feedback-error-text)";
return "var(--color-text-secondary)";
}
</script>
<Popover
popoverPadding="0"
placement="bottom-start"
bind:expanded={popoverExpanded}>
{#snippet toggle(onclick)}
<Button variant="outline" {onclick} active={popoverExpanded}>
<span
class="global-chip"
style:padding="0"
style:margin-left="-0.25rem"
style:background-color={verdictBgColor(selectedVerdict)}
style:color={verdictColor(selectedVerdict)}>
<Icon name={verdictIcon(selectedVerdict)} />
</span>
<span style:color="var(--color-text-secondary)">
{selectedVerdict ? capitalize(`${selectedVerdict}ed`) : "None"}
</span>
<Icon name={popoverExpanded ? "chevron-up" : "chevron-down"} />
</Button>
{/snippet}
{#snippet popover()}
<div
style:border="1px solid var(--color-border-subtle)"
style:border-radius="var(--border-radius-sm)"
style:display="flex"
style:gap="0.5rem"
style:align-items="center"
style:background-color="var(--color-surface-canvas)">
<DropdownList items={[undefined, "accept", "reject"] as const}>
{#snippet item(verdict)}
<DropdownListItem
title={verdict === undefined && summaryMissing
? "Set a summary to select verdict None"
: undefined}
disabled={draft === false &&
verdict === undefined &&
summaryMissing}
selected={selectedVerdict === verdict}
styleGap="0.5rem"
onclick={async () => {
await onSelect(verdict);
closeFocused();
}}>
<span
class="global-chip"
style:padding="0"
style:margin-left="-0.5rem"
style:background-color={verdictBgColor(verdict)}
style:color={verdictColor(verdict)}>
<Icon name={verdictIcon(verdict)} />
</span>
<span style:color="var(--color-text-secondary)">
{verdict ? capitalize(`${verdict}ed`) : "None"}
</span>
</DropdownListItem>
{/snippet}
</DropdownList>
</div>
{/snippet}
</Popover>
+9
View File
@@ -141,6 +141,15 @@
onRestored?.();
});
/// Scroll a given item into view, rendering it first if virtualisation has
/// it unmounted. Callers reach this through `bind:this`.
export function scrollToIndex(
index: number,
opts?: { align?: "start" | "center" | "end"; smooth?: boolean },
) {
handle?.scrollToIndex(index, opts);
}
function reportState() {
if (!handle || !onState) return;
onState({
+150
View File
@@ -0,0 +1,150 @@
import type { Author } from "@bindings/cob/Author";
import type { Embed } from "@bindings/cob/thread/Embed";
import { draftReviewStorage } from "@app/lib/draftReviewStorage";
import { invoke } from "@app/lib/invoke";
import { publicKeyFromDid } from "@app/lib/utils";
// Which object a code comment hangs off. Editing, deleting, resolving and
// reacting all dispatch on this, because the protocol action differs per kind.
export type CommentOwner =
| { kind: "draft"; draftId: string }
| { kind: "review"; reviewId: string }
| { kind: "revision"; revisionId: string };
export interface CommentActionsContext {
rid: string;
patchId: string;
publicKey: string;
announce: boolean;
// Returns undefined for a comment this view doesn't know about, in which
// case the action is skipped rather than sent with a guessed target.
ownerOf: (commentId: string) => CommentOwner | undefined;
reload: () => Promise<void>;
}
export interface CommentActions {
editComment: (
commentId: string,
body: string,
embeds: Embed[],
) => Promise<void>;
deleteComment: (commentId: string) => Promise<void>;
changeCommentStatus: (commentId: string, resolved: boolean) => Promise<void>;
reactOnComment: (
commentId: string,
authors: Author[],
reaction: string,
) => Promise<void>;
}
export function commentActions(ctx: CommentActionsContext): CommentActions {
const { rid, patchId, publicKey, announce, ownerOf, reload } = ctx;
const opts = { announce };
async function run(
label: string,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
action: any,
): Promise<void> {
try {
await invoke("edit_patch", { rid, cobId: patchId, action, opts });
} catch (error) {
console.error(`${label} failed`, error);
} finally {
await reload();
}
}
return {
async editComment(commentId, body, embeds) {
const owner = ownerOf(commentId);
if (!owner) return;
if (owner.kind === "draft") {
draftReviewStorage.updateComment(owner.draftId, commentId, { body });
await reload();
return;
}
await run(
"Editing comment",
owner.kind === "review"
? {
type: "review.comment.edit",
review: owner.reviewId,
comment: commentId,
body,
embeds,
}
: {
type: "revision.comment.edit",
revision: owner.revisionId,
comment: commentId,
body,
embeds,
},
);
},
async deleteComment(commentId) {
const owner = ownerOf(commentId);
if (!owner) return;
if (owner.kind === "draft") {
draftReviewStorage.deleteComment(owner.draftId, commentId);
await reload();
return;
}
await run(
"Deleting comment",
owner.kind === "review"
? {
type: "review.comment.redact",
review: owner.reviewId,
comment: commentId,
}
: {
type: "revision.comment.redact",
revision: owner.revisionId,
comment: commentId,
},
);
},
async changeCommentStatus(commentId, resolved) {
// Only review comments carry a resolved state; drafts and standalone
// revision comments have no review to attach the change to.
const owner = ownerOf(commentId);
if (owner?.kind !== "review") return;
await run("Changing comment status", {
type: resolved ? "review.comment.resolve" : "review.comment.unresolve",
review: owner.reviewId,
comment: commentId,
});
},
async reactOnComment(commentId, authors, reaction) {
const owner = ownerOf(commentId);
if (!owner || owner.kind === "draft") return;
const active = !authors.find(
({ did }) => publicKeyFromDid(did) === publicKey,
);
await run(
"Reacting on comment",
owner.kind === "review"
? {
type: "review.comment.react",
review: owner.reviewId,
comment: commentId,
reaction,
active,
}
: {
type: "revision.comment.react",
revision: owner.revisionId,
comment: commentId,
reaction,
active,
},
);
},
};
}
+51
View File
@@ -0,0 +1,51 @@
import type { Revision } from "@bindings/cob/patch/Revision";
import { publicKeyFromDid } from "@app/lib/utils";
/// Identifies the bucket of code comments that belong to no review, so the
/// Changes tab can toggle them like it toggles a review. Not a review id, and
/// deliberately not shaped like one.
export const STANDALONE_COMMENTS = "standalone";
/// A togglable layer of code comments on the revision diff: one per review that
/// left any, plus a bucket for the comments that belong to no review.
export interface CommentSource {
id: string;
name: string;
count: number;
// A review has one author; the comments that belong to no review can have
// several, so the row stacks the first few avatars.
nids: string[];
}
export function commentSourcesOf(revision: Revision): CommentSource[] {
const sources: CommentSource[] = [];
for (const review of revision.reviews ?? []) {
const count = (review.comments ?? []).filter(
c => c.location && !c.replyTo,
).length;
if (count === 0) continue;
sources.push({
id: review.id,
name:
review.author.alias ??
publicKeyFromDid(review.author.did).substring(0, 6),
count,
nids: [publicKeyFromDid(review.author.did)],
});
}
// Standalone located comments are a category of their own: a code comment can
// be left on a revision without joining any review.
const standalone = (revision.discussion ?? []).filter(
c => c.location && !c.replyTo,
);
if (standalone.length > 0) {
sources.push({
id: STANDALONE_COMMENTS,
name: "Not part of a review",
count: standalone.length,
nids: [...new Set(standalone.map(c => publicKeyFromDid(c.author.did)))],
});
}
return sources;
}
-248
View File
@@ -1,248 +0,0 @@
import type { Author } from "@bindings/cob/Author";
import type { CodeLocation } from "@bindings/cob/thread/CodeLocation";
import type { Embed } from "@bindings/cob/thread/Embed";
import type { Thread } from "@bindings/cob/thread/Thread";
import type { Config } from "@bindings/config/Config";
import type { FileDiff } from "@bindings/diff/FileDiff";
import type { Modification } from "@bindings/diff/Modification";
export interface CodeComments {
changeCommentStatus?: (commentId: string, resolved: boolean) => Promise<void>;
config: Config;
createComment: (
body: string,
embeds: Embed[],
replyTo?: string,
location?: CodeLocation,
) => Promise<void>;
editComment: (
commentId: string,
body: string,
embeds: Embed[],
) => Promise<void>;
reactOnComment?: (
commentId: string,
authors: Author[],
reaction: string,
) => Promise<void>;
deleteComment?: (commentId: string) => Promise<void>;
// Defaults to `true`.
canReply?: boolean;
// See `ExtendedTextarea`.
disableAttachments?: boolean | string;
repoDelegates: Author[];
rid: string;
threads: Thread<CodeLocation>[];
}
// Everything the interactive (patch-review) diff path needs, bundled so it can
// be threaded through the single changeset-level virtualizer as one prop.
export interface CommentContext {
codeComments: CodeComments;
threadByLine: Map<string, Thread<CodeLocation>>;
// Per-file resolved/unresolved thread tallies for the file-header badges.
threadCountsByFile: Map<string, { resolved: number; unresolved: number }>;
selection: Selection | undefined;
expandedStates: Record<string, boolean>;
onSelectLine: (
fileIdx: number,
side: Side,
line: Modification,
hunkIdx: number,
lineIdx: number,
file: FileDiff,
) => void;
onClearSelection: () => void;
onToggleThread: (threadId: string) => void;
}
export type Side = "left" | "right";
export type SelectionAnchor = { side: Side; lineNumber: number };
export type SelectionRange = { start: SelectionAnchor; end?: SelectionAnchor };
export interface Selection {
file: string;
// Index of the file in the changeset; disambiguates lines across files, since
// hunkIdx/lineIdx are only unique within a single file.
fileIdx: number;
start: SelectionAnchor;
end: SelectionAnchor;
lineIdx: number;
hunkIdx: number;
codeLocation: CodeLocation;
}
export function lineNumber(line: Modification, side: Side): number | undefined {
if (side === "left") {
if (line.type === "context") {
return line.lineNoOld;
}
if (line.type === "deletion") {
return line.lineNo;
}
} else {
if (line.type === "context") {
return line.lineNoNew;
}
if (line.type === "addition") {
return line.lineNo;
}
}
}
export function determineSelectedAnchor(
side: Side,
line: Modification,
): SelectionAnchor {
// When a user tries to select a side with no changes, use opposite side.
if (side === "left" && line.type === "addition") {
return { side: "right", lineNumber: line.lineNo };
} else if (side === "right" && line.type === "deletion") {
return { side: "left", lineNumber: line.lineNo };
} else {
return side === "left"
? { side: "left", lineNumber: lineNumber(line, "left") as number }
: { side: "right", lineNumber: lineNumber(line, "right") as number };
}
}
export function filePath(file: FileDiff, side: Side): string {
if (file.status === "moved" || file.status === "copied") {
if (side === "left") {
return file.oldPath;
} else {
return file.newPath;
}
} else {
return file.path;
}
}
export function buildSelection(
head: string,
file: FileDiff,
fileIdx: number,
side: Side,
line: Modification,
hunkIdx: number,
lineIdx: number,
): Selection {
const commentAnchor = determineSelectedAnchor(side, line);
return {
file: filePath(file, side),
fileIdx,
start: commentAnchor,
end: commentAnchor,
hunkIdx,
lineIdx,
codeLocation: {
commit: head,
path: filePath(file, side),
old:
commentAnchor.side === "left"
? {
type: "lines",
range: {
start: commentAnchor.lineNumber,
end: commentAnchor.lineNumber + 1,
},
}
: null,
new:
commentAnchor.side === "right"
? {
type: "lines",
range: {
start: commentAnchor.lineNumber,
end: commentAnchor.lineNumber + 1,
},
}
: null,
},
};
}
export function rangeAnchorsFromCodeLocation(
location: CodeLocation | null,
): SelectionRange | undefined {
if (location?.old?.type === "lines") {
return {
start: { side: "left", lineNumber: location.old.range.start },
};
} else if (location?.new?.type === "lines") {
return {
start: { side: "right", lineNumber: location.new.range.start },
};
}
}
// Index threads by the file and line they anchor to, so each rendered line
// does an O(1) lookup instead of scanning every thread. Rebuilt wholesale by
// callers and only read, so a plain Map is correct here. Keys are qualified
// by the thread's file path — line numbers alone repeat across files.
export function buildThreadByLine(
threads: Thread<CodeLocation>[],
): Map<string, Thread<CodeLocation>> {
const map = new Map<string, Thread<CodeLocation>>();
for (const t of threads) {
const path = t.root.location?.path;
if (path === undefined) {
continue;
}
const newEnd = t.root.location?.new?.range.end;
const oldEnd = t.root.location?.old?.range.end;
if (newEnd !== undefined && !map.has(`${path}:new:${newEnd}`)) {
map.set(`${path}:new:${newEnd}`, t);
}
if (oldEnd !== undefined && !map.has(`${path}:old:${oldEnd}`)) {
map.set(`${path}:old:${oldEnd}`, t);
}
}
return map;
}
// Per-file resolved/unresolved thread tallies for the file-header badges.
// Like buildThreadByLine, rebuilt wholesale and only read.
export function buildThreadCountsByFile(
threads: Thread<CodeLocation>[],
): Map<string, { resolved: number; unresolved: number }> {
const counts = new Map<string, { resolved: number; unresolved: number }>();
for (const t of threads) {
const path = t.root.location?.path;
if (path === undefined) {
continue;
}
const c = counts.get(path) ?? { resolved: 0, unresolved: 0 };
if (t.root.resolved) {
c.resolved += 1;
} else {
c.unresolved += 1;
}
counts.set(path, c);
}
return counts;
}
export function findLineThread(
map: Map<string, Thread<CodeLocation>>,
file: FileDiff,
line: Modification,
): Thread<CodeLocation> | undefined {
// Comment locations carry a single path, which is ambiguous for renames
// and copies; like the pre-virtualization per-file diff, those files
// don't get inline threads.
if (file.status === "moved" || file.status === "copied") {
return undefined;
}
if (line.type === "addition") {
return map.get(`${file.path}:new:${line.lineNo + 1}`);
} else if (line.type === "deletion") {
return map.get(`${file.path}:old:${line.lineNo + 1}`);
} else if (line.type === "context") {
return (
map.get(`${file.path}:new:${line.lineNoNew + 1}`) ??
map.get(`${file.path}:old:${line.lineNoOld + 1}`)
);
}
}
-108
View File
@@ -1,108 +0,0 @@
import type { Diff } from "@bindings/diff/Diff";
import type { FileDiff } from "@bindings/diff/FileDiff";
import type { Modification } from "@bindings/diff/Modification";
// A changeset flattened into a single stream of rows so it can be rendered
// through one virtualizer. Collapsed files contribute only their header row.
export type DiffRow =
// Spacing between file cards; its own row so file-header cards start flush at
// the row top and line up exactly with the sticky header bar.
| { type: "file-gap"; fileIndex: number }
| {
type: "file-header";
fileIndex: number;
file: FileDiff;
// No body rows follow (collapsed), so the header is a self-contained
// card and needs a full border.
standalone: boolean;
}
| {
type: "hunk-header";
fileIndex: number;
hunkIndex: number;
header: string;
}
// The file's only body row when there are no hunks to render, telling the
// user why (binary content vs. an empty file) instead of a bare header.
| {
type: "file-note";
fileIndex: number;
note: "binary" | "empty";
}
| {
type: "line";
fileIndex: number;
hunkIndex: number;
lineIndex: number;
file: FileDiff;
modification: Modification;
// Last line of the file, so it closes the card (bottom border + radius).
last: boolean;
};
export function flattenDiff(
diff: Diff,
isExpanded: (fileIndex: number) => boolean,
): DiffRow[] {
const rows: DiffRow[] = [];
diff.files.forEach((file, fileIndex) => {
if (fileIndex > 0) {
rows.push({ type: "file-gap", fileIndex });
}
const expanded = isExpanded(fileIndex);
rows.push({ type: "file-header", fileIndex, file, standalone: !expanded });
if (!expanded) {
return;
}
if (file.diff.type !== "plain" || file.diff.hunks.length === 0) {
rows.push({
type: "file-note",
fileIndex,
note: file.diff.type === "binary" ? "binary" : "empty",
});
return;
}
const lineRows: DiffRow[] = [];
file.diff.hunks.forEach((hunk, hunkIndex) => {
lineRows.push({
type: "hunk-header",
fileIndex,
hunkIndex,
header: hunk.header,
});
hunk.lines.forEach((modification, lineIndex) => {
lineRows.push({
type: "line",
fileIndex,
hunkIndex,
lineIndex,
file,
modification,
last: false,
});
});
});
const lastLine = lineRows.findLast(r => r.type === "line");
if (lastLine && lastLine.type === "line") {
lastLine.last = true;
}
rows.push(...lineRows);
});
return rows;
}
export function diffRowKey(row: DiffRow): string {
switch (row.type) {
case "file-gap":
return `g:${row.fileIndex}`;
case "file-header":
return `f:${row.fileIndex}`;
case "hunk-header":
return `h:${row.fileIndex}:${row.hunkIndex}`;
case "file-note":
return `n:${row.fileIndex}`;
case "line":
return `l:${row.fileIndex}:${row.hunkIndex}:${row.lineIndex}`;
}
}
+84 -7
View File
@@ -9,6 +9,7 @@ import type { Comment } from "@bindings/cob/thread/Comment";
import { z } from "zod";
import useLocalStorage from "@app/lib/useLocalStorage.svelte";
import { publicKeyFromDid } from "@app/lib/utils";
import { invoke } from "./invoke";
@@ -24,6 +25,7 @@ export interface DraftReview {
summary?: string;
labels: string[];
comments: Array<Comment<CodeLocation>>;
checkedFiles: string[];
}
const codeRangeSchema: z.Schema<CodeRange> = z.union([
@@ -41,6 +43,14 @@ const codeRangeSchema: z.Schema<CodeRange> = z.union([
const draftReviewStoredSchema = z.object({
id: z.string(),
rid: z.string(),
// Node ID of the identity that wrote the draft. Optional so drafts stored
// before this field existed keep working; those are treated as belonging to
// whoever is signed in, which is how they behaved previously.
nid: z.string().optional(),
// Patch the revision belongs to. Only used to prune drafts whose revision has
// gone away, which can't be done from the revision id alone. Optional for the
// same backwards-compatibility reason.
patchId: z.string().optional(),
revision: z.string(),
verdict: z.union([z.literal("accept"), z.literal("reject")]).optional(),
summary: z.string().default(""),
@@ -59,6 +69,7 @@ const draftReviewStoredSchema = z.object({
.optional(),
}),
),
checkedFiles: z.array(z.string()).default([]),
});
type DraftReviewStored = z.infer<typeof draftReviewStoredSchema>;
@@ -69,10 +80,17 @@ const storage = useLocalStorage(
{},
);
function belongsTo(draft: DraftReviewStored, nid: string): boolean {
return draft.nid === undefined || draft.nid === nid;
}
export const draftReviewStorage = {
get(id: string, author: Author): DraftReview | undefined {
const draftReviewStored = storage.value[id];
if (!draftReviewStored) {
if (
!draftReviewStored ||
!belongsTo(draftReviewStored, publicKeyFromDid(author.did))
) {
return undefined;
}
@@ -80,8 +98,10 @@ export const draftReviewStorage = {
},
getForRevision(revisionId: string, author: Author): DraftReview | undefined {
const nid = publicKeyFromDid(author.did);
const draftReviewStored = Object.values(storage.value).find(
draftReview => draftReview.revision === revisionId,
draftReview =>
draftReview.revision === revisionId && belongsTo(draftReview, nid),
);
if (draftReviewStored) {
@@ -89,28 +109,74 @@ export const draftReviewStorage = {
}
},
create(rid: string, revisionId: string): string {
create(
rid: string,
patchId: string,
revisionId: string,
nid: string,
): string {
const id = crypto.randomUUID();
storage.update(reviews => {
reviews[id] = {
id,
rid,
nid,
patchId,
revision: revisionId,
// Written down rather than defaulted when the bar reads the draft, so
// an absent verdict unambiguously means "comment only".
verdict: "accept",
summary: "",
labels: [],
comments: [],
checkedFiles: [],
};
return reviews;
});
return id;
},
hasForRevision(revisionId: string): boolean {
isFileChecked(id: string, filePath: string): boolean {
return storage.value[id]?.checkedFiles?.includes(filePath) ?? false;
},
toggleCheckedFile(id: string, filePath: string) {
updateStoredDraftReview(id, review => {
const set = new Set(review.checkedFiles);
if (set.has(filePath)) {
set.delete(filePath);
} else {
set.add(filePath);
}
return { ...review, checkedFiles: [...set] };
});
},
hasForRevision(revisionId: string, nid: string): boolean {
return Object.values(storage.value).some(
review => review.revision === revisionId,
review => review.revision === revisionId && belongsTo(review, nid),
);
},
// Drop drafts whose revision is gone — redacted, or a patch deleted from this
// node. Drafts predating `patchId` are skipped: there is no way to tell which
// patch they belong to.
pruneStale(patchId: string, revisionIds: string[], nid: string) {
const live = new Set(revisionIds);
storage.update(reviews => {
for (const [id, review] of Object.entries(reviews)) {
if (
review.patchId === patchId &&
belongsTo(review, nid) &&
!live.has(review.revision)
) {
delete reviews[id];
}
}
return reviews;
});
},
update(
id: string,
props: { summary: string; verdict: Verdict | undefined; labels: string[] },
@@ -131,9 +197,14 @@ export const draftReviewStorage = {
deleteComment(id: string, commentId: string) {
updateStoredDraftReview(id, review => {
// Guard the miss: `splice(-1, 1)` would drop the last comment instead of
// doing nothing.
const index = review.comments.findIndex(
comment => comment.id === commentId,
);
if (index === -1) {
return review;
}
review.comments.splice(index, 1);
return review;
});
@@ -176,19 +247,22 @@ export const draftReviewStorage = {
);
}
storedComment!.body = comment.body;
storedComment.body = comment.body;
return review;
});
},
async publish(id: string) {
const draftReviewStored = draftReviewStorage.delete(id);
const draftReviewStored = storage.value[id];
if (!draftReviewStored) {
throw new Error(
`Failed to publish draft review: Review ${id} does not exist`,
);
}
// Discard the draft only once the review is on the network. Deleting first
// loses every comment if the call fails, and leaves the bar unable to
// retry because the draft it is rendering no longer exists.
await invoke<Patch>("create_patch_review", {
args: {
rid: draftReviewStored.rid,
@@ -202,6 +276,8 @@ export const draftReviewStorage = {
})),
} satisfies CreateReviewArgs,
});
draftReviewStorage.delete(id);
},
};
@@ -233,6 +309,7 @@ function draftReviewFromStored(
revisionId: draftReviewStored.revision,
verdict: draftReviewStored.verdict,
labels: draftReviewStored.labels,
checkedFiles: draftReviewStored.checkedFiles,
comments: draftReviewStored.comments.map(rawComment => ({
id: rawComment.id,
author,
+26
View File
@@ -0,0 +1,26 @@
import type { FileDiff } from "@bindings/diff/FileDiff";
import { fileDiffPath } from "@app/lib/diffText";
// Files that add noise to patch diffs (lockfiles, generated manifests).
// These are hidden from the revision file preview and auto-collapsed in the
// Changes tab. Add new entries here to apply both behaviours.
export const IGNORED_FILENAMES: ReadonlySet<string> = new Set([
"package-lock.json",
"npm-shrinkwrap.json",
"yarn.lock",
"pnpm-lock.yaml",
"bun.lockb",
"Cargo.lock",
"Gemfile.lock",
"poetry.lock",
"composer.lock",
"go.sum",
"flake.lock",
]);
export function isIgnoredFile(file: FileDiff): boolean {
const path = fileDiffPath(file);
const filename = path.slice(path.lastIndexOf("/") + 1);
return IGNORED_FILENAMES.has(filename);
}
+1 -1
View File
@@ -4,7 +4,7 @@ export interface PatchUserActivity {
isAuthor: boolean;
isDelegate: boolean;
revisionCount: number;
commitCount: number;
commentCount: number;
reviewCount: number;
patchesAuthored: number;
issuesAuthored: number;
+30
View File
@@ -0,0 +1,30 @@
import type { Revision } from "@bindings/cob/patch/Revision";
import type { PatchUserActivity } from "@app/lib/patchActivityContext";
/// What one person contributed to a patch, counted from the revisions in hand.
///
/// A revision's discussion holds only real comments — its description is a
/// field of its own — and the same is true of a review's summary versus its
/// code comments, so nothing has to be excluded from either count.
export function patchContributions(
revisions: Revision[],
did: string,
): Pick<PatchUserActivity, "revisionCount" | "commentCount" | "reviewCount"> {
let revisionCount = 0;
let commentCount = 0;
let reviewCount = 0;
for (const rev of revisions) {
if (rev.author.did === did) revisionCount += 1;
for (const comment of rev.discussion ?? []) {
if (comment.author.did === did) commentCount += 1;
}
for (const review of rev.reviews ?? []) {
if (review.author.did === did) reviewCount += 1;
for (const comment of review.comments ?? []) {
if (comment.author.did === did) commentCount += 1;
}
}
}
return { revisionCount, commentCount, reviewCount };
}
+140
View File
@@ -0,0 +1,140 @@
import type { Author } from "@bindings/cob/Author";
import type { Reviewer } from "@bindings/cob/patch/Reviewer";
import type { Revision } from "@bindings/cob/patch/Revision";
import type { Verdict } from "@bindings/cob/patch/Verdict";
// How a patch's reviews are summarised. Shared by the patch header and the
// patch list so the two can't drift: both count the same things, order them the
// same way and go outdated under the same rule.
/// One review, from either source: the patch header builds these from the
/// revisions it has loaded, the patch list from `Patch["reviewers"]`.
export interface ReviewEntry {
author: Author;
verdict?: Verdict;
/// 1-based position of the reviewed revision in the patch timeline.
revisionNumber: number;
delegate: boolean;
/// Only the header links to a specific review; the list has no popover.
reviewId?: string;
}
export function entriesFromReviewers(reviewers: Reviewer[]): ReviewEntry[] {
return reviewers.map(r => ({
author: r.author,
verdict: r.verdict,
revisionNumber: r.revisionNumber,
delegate: r.delegate,
}));
}
export function entriesFromRevisions(
revisions: Revision[],
delegateDids: string[],
): ReviewEntry[] {
const delegates = new Set(delegateDids);
return revisions.flatMap((rev, index) =>
(rev.reviews ?? []).map(review => ({
author: review.author,
verdict: review.verdict,
revisionNumber: index + 1,
delegate: delegates.has(review.author.did),
reviewId: review.id,
})),
);
}
/// Grouped by author so a person's reviews stay together, newest revision first
/// within a group and across groups.
export function orderReviews(entries: ReviewEntry[]): ReviewEntry[] {
const byAuthor = new Map<string, ReviewEntry[]>();
for (const entry of entries) {
const group = byAuthor.get(entry.author.did) ?? [];
group.push(entry);
byAuthor.set(entry.author.did, group);
}
return [...byAuthor.values()]
.map(group =>
[...group].sort((a, b) => b.revisionNumber - a.revisionNumber),
)
.sort((a, b) => b[0].revisionNumber - a[0].revisionNumber)
.flat();
}
export interface ReviewSummaryState {
reviews: ReviewEntry[];
/// People, not reviews — the avatar stack and the "N reviewers" wording.
/// Delegates first, so they survive the stack being truncated.
authors: (Author & { delegate: boolean })[];
hasReject: boolean;
allAccept: boolean;
/// No review covers the newest revision, so nothing here describes the
/// changes as they now stand. The verdict colouring is suppressed in this
/// state: a stale accept must never read as a current approval.
outdated: boolean;
/// Newest revision anyone has reviewed, which is what the outdated pill
/// names ("· r1"). Zero when there are no reviews.
latestReviewedRevision: number;
delegateCount: number;
}
export function reviewSummary(
entries: ReviewEntry[],
revisionCount: number,
): ReviewSummaryState {
const reviews = orderReviews(entries);
const seen = new Map<string, Author & { delegate: boolean }>();
for (const entry of reviews) {
const existing = seen.get(entry.author.did);
if (existing) {
// A person is a delegate or not; if any of their reviews says so, keep it.
existing.delegate ||= entry.delegate;
} else {
seen.set(entry.author.did, { ...entry.author, delegate: entry.delegate });
}
}
const authors = [...seen.values()].sort(
(a, b) => Number(b.delegate) - Number(a.delegate),
);
const outdated =
reviews.length > 0 &&
revisionCount > 0 &&
!reviews.some(r => r.revisionNumber === revisionCount);
return {
reviews,
authors,
hasReject: !outdated && reviews.some(r => r.verdict === "reject"),
allAccept:
!outdated &&
reviews.length > 0 &&
reviews.every(r => r.verdict === "accept"),
outdated,
latestReviewedRevision: reviews.reduce(
(max, r) => Math.max(max, r.revisionNumber),
0,
),
delegateCount: authors.filter(a => a.delegate).length,
};
}
/// A review that no longer covers the current head.
export function isOutdatedReview(
entry: ReviewEntry,
revisionCount: number,
): boolean {
return revisionCount > 0 && entry.revisionNumber !== revisionCount;
}
export function summaryTitle(state: ReviewSummaryState): string {
const reviews = `${state.reviews.length} ${state.reviews.length === 1 ? "review" : "reviews"}`;
const people = `${state.authors.length} ${state.authors.length === 1 ? "reviewer" : "reviewers"}`;
const delegates =
state.delegateCount > 0 ? `, ${state.delegateCount} a delegate` : "";
const outdated = state.outdated
? ` — newest is of revision ${state.latestReviewedRevision}, so these may no longer apply`
: "";
return `${reviews} by ${people}${delegates}${outdated}`;
}
+48
View File
@@ -0,0 +1,48 @@
import type { Revision } from "@bindings/cob/patch/Revision";
import type { RevisionListSettings } from "@app/lib/revisionListSettings";
// How the revision picker presents a patch's revisions. Kept out of the patch
// view so the ordering rules can be read — and tested — on their own.
//
// Revisions arrive in the patch's timeline order and that order is what the
// numbering means; see `revisionPosition` in `utils`. Sorting only reorders the
// dropdown and grouping only buckets it, so neither may change what "Revision
// N of M" refers to.
/// 1-based timeline position per revision id, so the dropdown labels a revision
/// the same way the button above it does no matter how the list is arranged.
export function revisionNumbers(revisions: Revision[]): Record<string, number> {
const numbers: Record<string, number> = {};
revisions.forEach((rev, index) => {
numbers[rev.id] = index + 1;
});
return numbers;
}
export function orderRevisions(
revisions: Revision[],
patchAuthorDid: string,
settings: RevisionListSettings,
): Revision[] {
if (!settings.groupByAuthor) {
return settings.sortDesc ? [...revisions].reverse() : [...revisions];
}
// The patch author's revisions come first, then every other author's in the
// order they first appear in the timeline. The date direction applies within
// each group rather than to the group order.
const groups = new Map<string, Revision[]>();
for (const rev of revisions) {
const group = groups.get(rev.author.did);
if (group) group.push(rev);
else groups.set(rev.author.did, [rev]);
}
const orderedKeys = [...groups.keys()].sort(
(a, b) => Number(b === patchAuthorDid) - Number(a === patchAuthorDid),
);
return orderedKeys.flatMap(key => {
const group = groups.get(key) ?? [];
return settings.sortDesc ? [...group].reverse() : group;
});
}
+37
View File
@@ -0,0 +1,37 @@
import { z } from "zod";
import useLocalStorage from "@app/lib/useLocalStorage.svelte";
// How the revision dropdown is arranged. Kept out of the patch view so the
// choice follows the user across patches and repositories rather than
// resetting every time the view is mounted.
const schema = z.object({
sortDesc: z.boolean().default(false),
// Bucket revisions per author, patch author first.
groupByAuthor: z.boolean().default(false),
// Off by default: the position is rarely what you are scanning for, and
// it is already spelled out on the dropdown's own button.
showNumber: z.boolean().default(false),
showStats: z.boolean().default(false),
showReviewers: z.boolean().default(true),
});
export type RevisionListSettings = z.infer<typeof schema>;
const storage = useLocalStorage("revisionListSettings", schema, {
sortDesc: false,
groupByAuthor: false,
showNumber: false,
showStats: false,
showReviewers: true,
});
export const revisionListSettings = {
get value(): RevisionListSettings {
return storage.value;
},
toggle(key: keyof RevisionListSettings) {
storage.value = { ...storage.value, [key]: !storage.value[key] };
},
};
+2 -2
View File
@@ -96,7 +96,7 @@ export async function loadInbox(): Promise<LoadedInboxRoute> {
export async function loadRoute(
route: Route,
_previousLoaded: LoadedRoute,
previousLoaded: LoadedRoute,
): Promise<LoadedRoute> {
if (route.resource === "inbox") {
return loadInbox();
@@ -113,7 +113,7 @@ export async function loadRoute(
} else if (route.resource === "repo.issues") {
return loadIssues(route);
} else if (route.resource === "repo.patch") {
return loadPatch(route);
return loadPatch(route, previousLoaded);
} else if (route.resource === "repo.patches") {
return loadPatches(route);
}
+64 -32
View File
@@ -70,38 +70,20 @@ export const formatTimestamp = (
timestamp: number,
current = new Date().getTime(),
): string => {
const units: Record<string, number> = {
year: 24 * 60 * 60 * 1000 * 365,
month: (24 * 60 * 60 * 1000 * 365) / 12,
day: 24 * 60 * 60 * 1000,
hour: 60 * 60 * 1000,
minute: 60 * 1000,
second: 1000,
};
const SECOND = 1000;
const MINUTE = 60 * SECOND;
const HOUR = 60 * MINUTE;
const DAY = 24 * HOUR;
const MONTH = (365 * DAY) / 12;
const YEAR = 365 * DAY;
const rtf = new Intl.RelativeTimeFormat("en", {
numeric: "auto",
style: "long",
});
const elapsed = current - timestamp;
if (elapsed > units["year"]) {
return "more than a year ago";
} else if (elapsed < 0) {
return "now"; // If elapsed is a negative number we are dealing with an item from the future, and we return "now"
}
for (const u in units) {
if (elapsed > units[u] || u === "second") {
// We convert the division result to a negative number to get "XX [unit] ago"
return rtf.format(
Math.round(elapsed / units[u]) * -1,
u as Intl.RelativeTimeFormatUnit,
);
}
}
return new Date(timestamp).toUTCString();
if (elapsed < MINUTE) return "now";
if (elapsed < HOUR) return `${Math.floor(elapsed / MINUTE)}m`;
if (elapsed < DAY) return `${Math.floor(elapsed / HOUR)}h`;
if (elapsed < MONTH) return `${Math.floor(elapsed / DAY)}d`;
if (elapsed < YEAR) return `${Math.floor(elapsed / MONTH)}mo`;
return `${Math.floor(elapsed / YEAR)}y`;
};
// Svelte action that swallows mousedown so the activating element does not
@@ -209,7 +191,13 @@ export function authorForNodeId(author: Author): ComponentProps<typeof NodeId> {
}
export function absoluteTimestamp(timestamp: number) {
return new Date(Number(timestamp)).toLocaleString();
return new Date(Number(timestamp)).toLocaleString(undefined, {
year: "numeric",
month: "long",
day: "numeric",
hour: "numeric",
minute: "2-digit",
});
}
export function formatEditedCaption(author: Author, timestamp: number) {
@@ -217,7 +205,11 @@ export function formatEditedCaption(author: Author, timestamp: number) {
}
export function pluralize(singular: string, count: number): string {
return count === 1 ? singular : `${singular}s`;
if (count === 1) return singular;
if (/(?:ch|sh|s|x|z)$/i.test(singular)) {
return `${singular}es`;
}
return `${singular}s`;
}
export function isMac() {
@@ -277,6 +269,46 @@ export function verdictIcon(verdict: Review["verdict"]) {
}
}
// `revisions_by_patch` returns revisions in the patch's timeline order — the
// causal order the COB recorded them in — and that order is what "revision N of
// M" means throughout the UI. Do not re-sort by `timestamp` to recover it: a
// revision's timestamp is supplied by whoever authored it, so a peer with a
// skewed clock would silently renumber everyone's revisions.
export function revisionPosition(
revisions: { id: string }[],
revisionId: string,
): number | undefined {
const index = revisions.findIndex(r => r.id === revisionId);
return index === -1 ? undefined : index + 1;
}
// A review without a verdict is a comment-only review — what `rad patch review`
// produces with neither -a nor -r. The protocol has no "needs changes" or
// "request changes" state, so neither label may imply one: doing so would put
// words into the mouth of every reviewer who ever left a plain comment.
export function verdictAction(verdict: Review["verdict"]): string {
if (verdict === "accept") {
return "Accept";
} else if (verdict === "reject") {
return "Reject";
} else {
return "Comment";
}
}
export function verdictBadge(verdict: Review["verdict"]): {
label: string;
variant: "accept" | "reject" | "comment";
} {
if (verdict === "accept") {
return { label: "Accepted", variant: "accept" };
} else if (verdict === "reject") {
return { label: "Rejected", variant: "reject" };
} else {
return { label: "Reviewed", variant: "comment" };
}
}
export function safeHttpUrl(url: string): string | undefined {
try {
const parsed = new URL(url);
+74 -31
View File
@@ -26,12 +26,16 @@
import AssigneeInput from "@app/components/AssigneeInput.svelte";
import Button from "@app/components/Button.svelte";
import CommentComponent from "@app/components/Comment.svelte";
import Discussion from "@app/components/Discussion.svelte";
import Discussion, {
type ActivityItem,
} from "@app/components/Discussion.svelte";
import EditableTitle from "@app/components/EditableTitle.svelte";
import Icon from "@app/components/Icon.svelte";
import Id from "@app/components/Id.svelte";
import IssueActivityItem, {
type FlattenedIssueOperation,
} from "@app/components/IssueActivityItem.svelte";
import IssueStateButton from "@app/components/IssueStateButton.svelte";
import IssueTimeline from "@app/components/IssueTimeline.svelte";
import LabelInput from "@app/components/LabelInput.svelte";
import ScrollArea from "@app/components/ScrollArea.svelte";
import ShareButton from "@app/components/ShareButton.svelte";
@@ -54,19 +58,62 @@
let labelSaveInProgress: boolean = $state(false);
let assigneesSaveInProgress: boolean = $state(false);
let hideTimeline = $state(true);
$effect(() => {
// The component doesn't get destroyed when we switch between different
// issues in the second column and because of that the top-level state
// gets retained when the issue changes. This reactive statement makes
// sure we always reset the state to defaults.
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
issue.id;
hideTimeline = true;
});
const activityItems: ActivityItem<FlattenedIssueOperation>[] = $derived.by(
() => {
// Actions `IssueActivityItem` has no branch for. Left in, they still
// group under an author, so the timeline grows a heading with nothing
// beneath it.
const skipped = new Set<Action["type"]>([
"comment",
"comment.edit",
"comment.react",
"comment.redact",
]);
const tracker: Partial<Record<Action["type"], Action>> = {};
const items: ActivityItem<FlattenedIssueOperation>[] = [];
activity.forEach(operation => {
operation.actions.forEach((action, actionIndex) => {
if (skipped.has(action.type)) {
tracker[action.type] = action;
return;
}
const previous = tracker[action.type];
// The first `edit` action has nothing to diff against, so the
// renderer skips it. Skip it here too so we don't leave a gap.
if (action.type === "edit" && !previous) {
tracker[action.type] = action;
return;
}
// A label action that neither adds nor removes renders nothing.
if (action.type === "label") {
const prev =
previous && previous.type === "label" ? previous.labels : [];
const added = action.labels.filter(l => !prev.includes(l));
const removed = prev.filter(l => !action.labels.includes(l));
if (added.length === 0 && removed.length === 0) {
tracker[action.type] = action;
return;
}
}
const op: FlattenedIssueOperation = {
...action,
id: operation.id,
author: operation.author,
timestamp: operation.timestamp,
previous,
};
tracker[action.type] = action;
items.push({
key: `${operation.id}:${actionIndex}`,
timestamp: operation.timestamp,
data: op,
});
});
});
return items;
},
);
async function saveLabels(labels: string[]) {
try {
@@ -321,7 +368,7 @@
{issueStatusLabel[issue.state.status]}
</button>
<Icon name="chevron-right" />
<Id id={issue.id} clipboard={issue.id} placement="bottom-start" />
<Id id={issue.id} clipboard={issue.id} label="issue ID" />
</div>
<div style:margin-left="auto" style:display="flex" style:gap="0.5rem">
<ShareButton
@@ -392,29 +439,25 @@
</div>
{/if}
{#snippet renderActivity(
op: FlattenedIssueOperation,
{ hideAuthor }: { hideAuthor: boolean },
)}
<IssueActivityItem {op} {hideAuthor} />
{/snippet}
<Discussion
repoDelegates={repo.delegates}
cobId={issue.id}
commentThreads={threads}
{config}
{createComment}
{editComment}
{reactOnComment}
repoDelegates={repo.delegates}
rid={repo.rid} />
<div class="global-flex" style:margin-top="1rem">
<Button
variant="naked"
onclick={() => (hideTimeline = !hideTimeline)}>
<Icon name={hideTimeline ? "chevron-right" : "chevron-down"} />
</Button>
<div class="txt-body-m-regular global-flex">Timeline</div>
</div>
<div
style:display={hideTimeline ? "none" : "revert"}
style:margin-top="1rem">
<IssueTimeline {activity} />
</div>
rid={repo.rid}
{activityItems}
{renderActivity}
authorOf={op => op.author} />
</div>
<div class="sidebar">
+1256 -353
View File
File diff suppressed because it is too large Load Diff
+6 -14
View File
@@ -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<string, FileStatus>();
/* 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 @@
<span class="txt-selectable">{commit.author.name}</span>
</span>
committed
<Id id={commit.id} clipboard={commit.id} />
<Id id={commit.id} clipboard={commit.id} label="commit hash" />
<span
class="summary-timestamp"
title={absoluteTimestamp(commit.committer.time * 1000)}>
@@ -372,7 +364,7 @@
All commits
</button>
<Icon name="chevron-right" />
<Id id={commit.id} clipboard={commit.id} placement="bottom-start" />
<Id id={commit.id} clipboard={commit.id} label="commit hash" />
</div>
<div class="topbar-right">
<span style:display="inline-flex" style:margin-right="0.5rem">
+5 -2
View File
@@ -213,8 +213,11 @@
<Id
id={blob.commit.id}
clipboard={blob.commit.id}
placement="bottom-start" />
<span class="commit-msg txt-overflow" style:min-width="0">
label="commit hash" />
<span
class="commit-msg txt-overflow"
style:min-width="0"
style:max-width="20rem">
{blob.commit.message}
</span>
</div>
+76 -35
View File
@@ -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<Patch[]>;
status: PatchStatus | undefined;
review: Review | DraftReview | undefined;
view?: PatchView;
review: Review | undefined;
revisions: Revision[];
activity: Operation<PatchAction>[];
sidebarData: SidebarData;
@@ -184,40 +187,67 @@ export type LoadedRepoRoute =
export async function loadPatch(
route: RepoPatchRoute,
): Promise<LoadedRepoPatchRoute> {
const [sidebarData, repo, patch, revisions, activity] = await Promise.all([
loadSidebarData(),
invoke<RepoInfo>("repo_by_id", {
previousLoaded?: LoadedRoute,
): Promise<LoadedRepoPatchRoute | LoadedRepoPatchesRoute> {
// 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<RepoInfo>("repo_by_id", {
rid: route.rid,
}),
invoke<PaginatedQuery<Patch[]>>("list_patches", {
rid: route.rid,
status: route.status,
take: DEFAULT_TAKE,
}),
] as const),
Promise.all([
invoke<Patch | null>("patch_by_id", {
rid: route.rid,
id: route.patch,
}),
invoke<Revision[]>("revisions_by_patch", {
rid: route.rid,
id: route.patch,
}),
invoke<Operation<PatchAction>[]>("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>("patch_by_id", {
rid: route.rid,
id: route.patch,
}),
invoke<Revision[]>("revisions_by_patch", {
rid: route.rid,
id: route.patch,
}),
invoke<Operation<PatchAction>[]>("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 };
+114
View File
@@ -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);
});
});