This commit is contained in:
2026-09-04 16:02:51 +07:00
parent 17de4f6376
commit 1d224218df
38 changed files with 894 additions and 2482 deletions
-1
View File
@@ -8,7 +8,6 @@ publish.workspace = true
gpui.workspace = true
gpui-component.workspace = true
anyhow.workspace = true
log.workspace = true
rust-embed.workspace = true
[dev-dependencies]
-1
View File
@@ -20,7 +20,6 @@ pub const TAB_BAR_HEIGHT: Pixels = px(44.);
/// i18n shim resolving `Dock.*` keys to English, so the crate has no i18n dependency.
pub(crate) fn t(key: &'static str) -> &'static str {
match key {
"Dock.Unnamed" => "Unnamed",
"Dock.Close" => "Close",
"Dock.Zoom In" => "Zoom In",
"Dock.Zoom Out" => "Zoom Out",
+2 -71
View File
@@ -9,9 +9,6 @@ pub const APP_NAME: &str = "Signed";
/// Used in XDG-style paths on Linux and FreeBSD, and the macOS `~/.config` fallback.
pub const APP_NAME_LOWERCASE: &str = "signed";
/// A custom data directory override, set only by [`set_custom_data_dir`].
static CUSTOM_DATA_DIR: OnceLock<PathBuf> = OnceLock::new();
/// The resolved data directory.
/// On macOS, this is `~/Library/Application Support/Signed`.
/// On Linux/FreeBSD, this is `$XDG_DATA_HOME/signed`.
@@ -41,31 +38,10 @@ pub fn documents_dir() -> PathBuf {
dirs::document_dir().unwrap_or_else(|| dirs::home_dir().unwrap_or_default())
}
/// Sets a custom directory for all user data, overriding the default data directory.
/// Must be called before any other path operation.
/// The directory is created when missing and canonicalized to an absolute path.
/// # Panics
/// Panics when called after [`data_dir`] or [`config_dir`] was initialized.
/// Panics when the directory cannot be created or canonicalized.
pub fn set_custom_data_dir(dir: &str) -> &'static PathBuf {
if CURRENT_DATA_DIR.get().is_some() || CONFIG_DIR.get().is_some() {
panic!("set_custom_data_dir called after data_dir or config_dir was initialized");
}
CUSTOM_DATA_DIR.get_or_init(|| {
let path = PathBuf::from(dir);
std::fs::create_dir_all(&path).expect("failed to create custom data directory");
path.canonicalize()
.expect("failed to canonicalize custom data directory")
})
}
/// Returns the path to the configuration directory.
pub fn config_dir() -> &'static PathBuf {
CONFIG_DIR.get_or_init(|| {
if let Some(custom_dir) = CUSTOM_DATA_DIR.get() {
custom_dir.join("config")
} else if cfg!(target_os = "windows") {
if cfg!(target_os = "windows") {
dirs::config_dir()
.expect("failed to determine RoamingAppData directory")
.join(APP_NAME)
@@ -85,9 +61,7 @@ pub fn config_dir() -> &'static PathBuf {
/// Returns the path to the data directory.
pub fn data_dir() -> &'static PathBuf {
CURRENT_DATA_DIR.get_or_init(|| {
if let Some(custom_dir) = CUSTOM_DATA_DIR.get() {
custom_dir.clone()
} else if cfg!(target_os = "macos") {
if cfg!(target_os = "macos") {
home_dir()
.join("Library/Application Support")
.join(APP_NAME)
@@ -108,43 +82,6 @@ pub fn data_dir() -> &'static PathBuf {
})
}
/// Returns the path to the cache directory.
pub fn cache_dir() -> &'static PathBuf {
static CACHE_DIR: OnceLock<PathBuf> = OnceLock::new();
CACHE_DIR.get_or_init(|| {
if cfg!(target_os = "macos") {
dirs::cache_dir()
.expect("failed to determine caches directory")
.join(APP_NAME)
} else if cfg!(target_os = "windows") {
dirs::cache_dir()
.expect("failed to determine LocalAppData directory")
.join(APP_NAME)
} else if cfg!(any(target_os = "linux", target_os = "freebsd")) {
if let Ok(flatpak_xdg_cache) = std::env::var("FLATPAK_XDG_CACHE_HOME") {
flatpak_xdg_cache.into()
} else {
dirs::cache_dir().expect("failed to determine XDG_CACHE_HOME directory")
}
.join(APP_NAME_LOWERCASE)
} else {
home_dir().join(".cache").join(APP_NAME_LOWERCASE)
}
})
}
/// Returns the path to the logs directory.
pub fn logs_dir() -> &'static PathBuf {
static LOGS_DIR: OnceLock<PathBuf> = OnceLock::new();
LOGS_DIR.get_or_init(|| {
if cfg!(target_os = "macos") {
home_dir().join("Library/Logs").join(APP_NAME)
} else {
data_dir().join("logs")
}
})
}
/// Returns the path to the nostr database directory, LMDB.
pub fn nostr_dir() -> &'static PathBuf {
static NOSTR_DIR: OnceLock<PathBuf> = OnceLock::new();
@@ -162,9 +99,3 @@ pub fn settings_file() -> &'static PathBuf {
static SETTINGS_FILE: OnceLock<PathBuf> = OnceLock::new();
SETTINGS_FILE.get_or_init(|| config_dir().join("settings.json"))
}
/// Returns the path to the `keymap.json` file.
pub fn keymap_file() -> &'static PathBuf {
static KEYMAP_FILE: OnceLock<PathBuf> = OnceLock::new();
KEYMAP_FILE.get_or_init(|| config_dir().join("keymap.json"))
}
-164
View File
@@ -1,164 +0,0 @@
use std::collections::{HashMap, HashSet};
use nostr::prelude::*;
/// A NIP-22 comment thread, a top-level comment on the root event,
/// nested replies are ordered oldest first at every level.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommentThread {
/// The thread's top-level comment.
pub comment: Event,
/// Replies to [`Self::comment`], nested recursively.
pub replies: Vec<CommentThread>,
}
/// The direct parent id of a comment, from its NIP-22 lowercase `e` tag.
/// `None` when no `e` tag is present.
fn comment_parent(event: &Event) -> Option<EventId> {
event
.tags
.iter()
.find(|tag| tag.kind() == "e")
.and_then(Tag::content)
.and_then(|id| EventId::parse(id).ok())
}
/// Group the comments on a root issue, patch or PR into NIP-22 threads,
/// a comment whose parent is the root starts a thread.
///
/// Other comments nest under their parent comment.
///
/// Threads and replies are ordered oldest first,
/// replies with a missing parent are made top-level threads, so none are dropped.
pub fn comment_threads(root: &Event, comments: &[Event]) -> Vec<CommentThread> {
// Index comments by their parent id.
// Comments without a parent tag reply to the root event itself.
let mut children: HashMap<EventId, Vec<&Event>> = HashMap::new();
for comment in comments {
let parent = comment_parent(comment).unwrap_or(root.id);
children.entry(parent).or_default().push(comment);
}
for list in children.values_mut() {
list.sort_by_key(|event| event.created_at);
}
let mut visited: HashSet<EventId> = HashSet::new();
fn build(
id: EventId,
children: &HashMap<EventId, Vec<&Event>>,
visited: &mut HashSet<EventId>,
) -> Vec<CommentThread> {
let Some(list) = children.get(&id) else {
return Vec::new();
};
let mut threads = Vec::new();
for event in list {
// Guards against malformed reply cycles.
if visited.insert(event.id) {
threads.push(CommentThread {
comment: (*event).clone(),
replies: build(event.id, children, visited),
});
}
}
threads
}
let mut threads = build(root.id, &children, &mut visited);
// Orphan replies have an unknown parent comment, so they never reach the root tree.
// Surface them as top-level threads so they are not dropped.
let mut orphans: Vec<&Event> = comments
.iter()
.filter(|event| !visited.contains(&event.id))
.collect();
orphans.sort_by_key(|event| event.created_at);
for comment in orphans {
if visited.insert(comment.id) {
threads.push(CommentThread {
comment: comment.clone(),
replies: build(comment.id, &children, &mut visited),
});
}
}
threads
}
#[cfg(test)]
mod tests {
use super::*;
fn comment(keys: &Keys, parent: Option<&Event>, content: &str, created_at: u64) -> Event {
let tags = parent
.map(|parent| vec![Tag::parse(["e", &parent.id.to_hex()]).expect("valid e tag")])
.unwrap_or_default();
EventBuilder::new(Kind::Comment, content)
.tags(tags)
.custom_created_at(Timestamp::from(created_at))
.finalize(keys)
.expect("signed event")
}
fn flatten(threads: &[CommentThread]) -> Vec<String> {
let mut out = Vec::new();
for thread in threads {
out.push(thread.comment.content.clone());
out.extend(flatten(&thread.replies));
}
out
}
#[test]
fn nests_replies_under_their_parents() {
let keys = Keys::generate();
let root = EventBuilder::new(Kind::GitIssue, "issue")
.finalize(&keys)
.expect("signed event");
let a = comment(&keys, Some(&root), "a", 100);
let a1 = comment(&keys, Some(&a), "a1", 200);
let a2 = comment(&keys, Some(&a), "a2", 300);
let b = comment(&keys, Some(&root), "b", 150);
let threads = comment_threads(&root, &[a2, b, a, a1]);
assert_eq!(flatten(&threads), vec!["a", "a1", "a2", "b"]);
}
#[test]
fn comments_without_a_parent_tag_attach_to_the_root() {
let keys = Keys::generate();
let root = EventBuilder::new(Kind::GitIssue, "issue")
.finalize(&keys)
.expect("signed event");
// Old-style comments carried no `e` tag at all.
let orphan = comment(&keys, None, "no parent", 100);
let threads = comment_threads(&root, &[orphan]);
assert_eq!(flatten(&threads), vec!["no parent"]);
}
#[test]
fn orphan_replies_are_surfaced_as_top_level_threads() {
let keys = Keys::generate();
let root = EventBuilder::new(Kind::GitIssue, "issue")
.finalize(&keys)
.expect("signed event");
let a = comment(&keys, Some(&root), "a", 100);
// `missing` is not in the comment set.
// Its reply should still show up.
let missing = EventBuilder::new(Kind::Comment, "missing")
.finalize(&keys)
.expect("signed event");
let reply_to_missing = comment(&keys, Some(&missing), "reply to missing", 200);
let threads = comment_threads(&root, &[a, reply_to_missing]);
assert_eq!(flatten(&threads), vec!["a", "reply to missing"]);
}
}
-2
View File
@@ -1,7 +1,6 @@
pub mod addr;
pub mod annotations;
pub mod clone_url;
pub mod comments;
pub mod deletions;
pub mod filters;
pub mod model;
@@ -11,7 +10,6 @@ pub mod status;
pub use addr::{RepoAddr, identifier_from_name, repo_addr};
pub use annotations::{COVER_NOTE_KIND, cover_note, labels_and_subject, subject_override};
pub use clone_url::{CloneTarget, parse_clone_url};
pub use comments::{CommentThread, comment_threads};
pub use deletions::Deletions;
pub use model::{Announcement, activity_subject, pull_request_patch, pull_request_patches};
pub use state::{build_state, parse_state};
+122 -254
View File
@@ -127,24 +127,13 @@ pub fn clone_repo(clone_urls: &[String], path: &Path) -> Result<()> {
bail!("destination {} already exists", path.display());
}
let mut last_err: Option<anyhow::Error> = None;
for url in clone_urls {
match clone(url, path) {
Ok(repo) => {
// The initial clone uses the default refspecs.
// Also fetch the `refs/nostr/*` PR refs.
fetch_all(&repo).ok();
return Ok(());
}
Err(e) => last_err = Some(e),
}
}
match last_err {
Some(e) => Err(e).context("failed to clone from any mirror"),
None => bail!("no clone URLs provided"),
}
try_each_url(clone_urls, "clone", |url| {
let repo = clone(url, path)?;
// The initial clone uses the default refspecs.
// Also fetch the `refs/nostr/*` PR refs.
fetch_all(&repo).ok();
Ok(())
})
}
/// Fetch all configured refspecs from `origin`, plus the `refs/nostr/*` namespace.
@@ -199,25 +188,14 @@ pub fn apply_patch(repo_path: &Path, patch: &str) -> Result<()> {
///
/// Unresolvable revisions are errors.
pub fn merge_base(repo_path: &Path, a: &str, b: &str) -> Result<Option<String>> {
let output = Command::new("git")
.arg("-C")
.arg(repo_path)
.args(["merge-base", a, b])
.env("GIT_TERMINAL_PROMPT", "0")
.stderr(Stdio::piped())
.output()
.context("failed to spawn `git merge-base`")?;
match output.status.code() {
// Exit 1 means no common ancestor, a valid outcome for a proposal.
Some(1) => Ok(None),
Some(0) => Ok(Some(
String::from_utf8_lossy(&output.stdout).trim().to_owned(),
)),
_ => bail!(
"git merge-base failed: {}",
String::from_utf8_lossy(&output.stderr).trim()
),
let repo = open_with_cache(repo_path)?;
let a = repo.rev_parse_single(a.as_bytes())?;
let b = repo.rev_parse_single(b.as_bytes())?;
match repo.merge_base(a, b) {
Ok(id) => Ok(Some(id.to_string())),
// No common ancestor, a valid outcome for a proposal.
Err(gix::repository::merge_base::Error::NotFound { .. }) => Ok(None),
Err(e) => Err(e.into()),
}
}
@@ -248,34 +226,6 @@ pub fn format_patch_between(repo_path: &Path, base: &str, tip: &str) -> Result<S
Ok(patch)
}
/// Whether `patch` applies to the working tree of `repo_path` without modifying anything.
pub fn patch_applies(repo_path: &Path, patch: &str) -> Result<()> {
let mut child = Command::new("git")
.arg("apply")
.args(["--check", "--3way", "--whitespace=nowarn", "-"])
.current_dir(repo_path)
.stdin(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.context("failed to spawn `git apply --check`")?;
child
.stdin
.as_mut()
.expect("stdin piped")
.write_all(patch.as_bytes())?;
let output = child.wait_with_output()?;
if !output.status.success() {
bail!(
"patch does not apply: {}",
String::from_utf8_lossy(&output.stderr).trim()
);
}
Ok(())
}
/// Push `commit` to `reference` on the server at `url`, from `repo_path`.
pub fn push_commit_ref(repo_path: &Path, url: &str, commit: &str, reference: &str) -> Result<()> {
let output = Command::new("git")
@@ -331,14 +281,7 @@ pub fn split_patch_series(patch: &str) -> Vec<&str> {
///
/// `None` when the repository has no commits yet, an unborn HEAD.
pub fn head_commit_id(repo_path: &Path) -> Result<Option<String>> {
let output = Command::new("git")
.arg("-C")
.arg(repo_path)
.args(["rev-parse", "HEAD"])
.env("GIT_TERMINAL_PROMPT", "0")
.stderr(Stdio::piped())
.output()
.context("failed to spawn `git rev-parse`")?;
let output = git_output(repo_path, &["rev-parse", "HEAD"], "git rev-parse")?;
if !output.status.success() {
return Ok(None);
@@ -371,13 +314,41 @@ pub fn commits_since(repo_path: &Path, base: Option<&str>) -> Result<Vec<String>
.collect())
}
fn clone(url: &str, path: &Path) -> Result<gix::Repository> {
// GRASP servers announce `grasp://<host>/<owner>/<repo>` clone URLs.
// The transport is git smart HTTP, so the scheme is rewritten for gix.
let url = url
.strip_prefix("grasp://")
/// Rewrite a grasp server URL to the https URL the git transport actually uses.
///
/// GRASP servers announce `grasp://<host>/<owner>/<repo>` clone URLs.
/// The transport is git smart HTTP, so the scheme is rewritten for gix.
fn transport_url(url: &str) -> String {
url.strip_prefix("grasp://")
.map(|rest| format!("https://{rest}"))
.unwrap_or_else(|| url.to_owned());
.unwrap_or_else(|| url.to_owned())
}
/// Run `attempt` against each URL in `urls` until one succeeds.
///
/// Returns the last error wrapped in `failed to {verb} from any mirror`,
/// or `no clone URLs provided` when the list is empty.
fn try_each_url<F>(urls: &[String], verb: &str, mut attempt: F) -> Result<()>
where
F: FnMut(&str) -> Result<()>,
{
let mut last_err: Option<anyhow::Error> = None;
for url in urls {
match attempt(url) {
Ok(()) => return Ok(()),
Err(e) => last_err = Some(e),
}
}
match last_err {
Some(e) => Err(e).context(format!("failed to {verb} from any mirror")),
None => bail!("no clone URLs provided"),
}
}
fn clone(url: &str, path: &Path) -> Result<gix::Repository> {
let url = transport_url(url);
let url = gix::url::parse(url).context("invalid clone URL")?;
let mut prepare = gix::prepare_clone(url, path)?;
@@ -435,44 +406,44 @@ pub fn init_repository(path: &Path, name: &str, description: &str) -> Result<Str
/// Push the `main` branch of the repository at `repo_path` to a grasp server.
pub fn push_main(repo_path: &Path, base_url: &str, owner: &str, repo_id: &str) -> Result<()> {
let url = format!("{base_url}/{owner}/{repo_id}.git");
let output = Command::new("git")
.arg("-C")
.arg(repo_path)
.args(["push"])
.arg(&url)
.args(["refs/heads/main:refs/heads/main"])
.env("GIT_TERMINAL_PROMPT", "0")
.stderr(Stdio::piped())
.output()
.context("failed to spawn `git push`")?;
if !output.status.success() {
bail!(
"git push to {base_url} failed: {}",
String::from_utf8_lossy(&output.stderr).trim()
);
}
Ok(())
push_refspecs(
repo_path,
base_url,
owner,
repo_id,
&["refs/heads/main:refs/heads/main"],
)
}
/// Push every local branch and tag of the repository at `repo_path` to a grasp server.
///
/// This mirrors an initialized repository's whole history.
pub fn push_all(repo_path: &Path, base_url: &str, owner: &str, repo_id: &str) -> Result<()> {
push_refspecs(
repo_path,
base_url,
owner,
repo_id,
&["refs/heads/*:refs/heads/*", "refs/tags/*:refs/tags/*"],
)
}
/// Push `refspecs` to the grasp server URL derived from `base_url`, `owner` and `repo_id`.
fn push_refspecs(
repo_path: &Path,
base_url: &str,
owner: &str,
repo_id: &str,
refspecs: &[&str],
) -> Result<()> {
let url = format!("{base_url}/{owner}/{repo_id}.git");
let output = Command::new("git")
.arg("-C")
.arg(repo_path)
.args(["push"])
.arg(&url)
.args(["refs/heads/*:refs/heads/*", "refs/tags/*:refs/tags/*"])
.env("GIT_TERMINAL_PROMPT", "0")
.stderr(Stdio::piped())
.output()
.context("failed to spawn `git push`")?;
let mut args: Vec<&str> = Vec::with_capacity(refspecs.len() + 2);
args.push("push");
args.push(&url);
args.extend_from_slice(refspecs);
let output = git_output(repo_path, &args, "git push")?;
if !output.status.success() {
bail!(
@@ -480,7 +451,6 @@ pub fn push_all(repo_path: &Path, base_url: &str, owner: &str, repo_id: &str) ->
String::from_utf8_lossy(&output.stderr).trim()
);
}
Ok(())
}
@@ -489,14 +459,11 @@ pub fn push_all(repo_path: &Path, base_url: &str, owner: &str, repo_id: &str) ->
///
/// `None` for a repository without commits.
pub fn root_commit(repo_path: &Path) -> Result<Option<String>> {
let output = Command::new("git")
.arg("-C")
.arg(repo_path)
.args(["rev-list", "--max-parents=0", "HEAD"])
.env("GIT_TERMINAL_PROMPT", "0")
.stderr(Stdio::piped())
.output()
.context("failed to spawn `git rev-list`")?;
let output = git_output(
repo_path,
&["rev-list", "--max-parents=0", "HEAD"],
"git rev-list",
)?;
// An unborn HEAD with no commits yet makes `rev-list` fail.
// There is no unique commit to report then.
@@ -519,15 +486,8 @@ pub fn ensure_origin(repo_path: &Path, url: &str) -> Result<()> {
if git_in(repo_path, &["remote", "get-url", "origin"]).is_ok() {
return Ok(());
}
// `git remote add` already configures the default fetch refspec.
git_in(repo_path, &["remote", "add", "origin", url])?;
git_in(
repo_path,
&[
"config",
"remote.origin.fetch",
"+refs/heads/*:refs/remotes/origin/*",
],
)?;
Ok(())
}
@@ -550,38 +510,19 @@ pub fn set_origin(repo_path: &Path, url: &str) -> Result<()> {
///
/// Never touches the checked-out refs or the worktree.
pub fn fetch_repo_refs(repo_path: &Path, urls: &[String], refspec: &str) -> Result<()> {
let mut last_err: Option<anyhow::Error> = None;
try_each_url(urls, "fetch", |url| {
let url = transport_url(url);
for url in urls {
let url = url
.strip_prefix("grasp://")
.map(|rest| format!("https://{rest}"))
.unwrap_or_else(|| url.to_owned());
let output = Command::new("git")
.arg("-C")
.arg(repo_path)
.args(["fetch"])
.arg(&url)
.arg(refspec)
.env("GIT_TERMINAL_PROMPT", "0")
.stderr(Stdio::piped())
.output()
.context("failed to spawn `git fetch`")?;
let output = git_output(repo_path, &["fetch", &url, refspec], "git fetch")?;
if output.status.success() {
return Ok(());
}
last_err = Some(anyhow::anyhow!(
bail!(
"git fetch from {url} failed: {}",
String::from_utf8_lossy(&output.stderr).trim()
));
}
match last_err {
Some(e) => Err(e).context("failed to fetch from any mirror"),
None => bail!("no clone URLs provided"),
}
)
})
}
/// Full ref names under `prefix`, sorted lexicographically, like `git for-each-ref`.
@@ -592,14 +533,11 @@ pub fn refs_with_prefix(repo_path: &Path, prefix: &str) -> Result<Vec<String>> {
// `for-each-ref` patterns match whole path components.
// A trailing slash would silently change what is matched.
let pattern = prefix.trim_end_matches('/');
let output = Command::new("git")
.arg("-C")
.arg(repo_path)
.args(["for-each-ref", "--format=%(refname)", pattern])
.env("GIT_TERMINAL_PROMPT", "0")
.stderr(Stdio::piped())
.output()
.context("failed to spawn `git for-each-ref`")?;
let output = git_output(
repo_path,
&["for-each-ref", "--format=%(refname)", pattern],
"git for-each-ref",
)?;
if !output.status.success() {
bail!(
@@ -659,14 +597,11 @@ pub fn delete_refs_with_prefix(repo_path: &Path, prefix: &str) -> Result<()> {
///
/// `None` when it has no `origin` yet.
pub fn origin_url(workdir: &Path) -> Result<Option<String>> {
let output = Command::new("git")
.arg("-C")
.arg(workdir)
.args(["remote", "get-url", "origin"])
.env("GIT_TERMINAL_PROMPT", "0")
.stderr(Stdio::piped())
.output()
.context("failed to spawn `git remote get-url`")?;
let output = git_output(
workdir,
&["remote", "get-url", "origin"],
"git remote get-url",
)?;
if !output.status.success() {
return Ok(None);
@@ -717,18 +652,25 @@ pub fn fast_forward_branches(workdir: &Path) -> Result<bool> {
Ok(moved)
}
/// Run a git command in `dir`, returning trimmed stdout.
/// Run `git -C dir args`, disabling the terminal prompt and capturing stderr.
///
/// The terminal prompt is disabled so a credential request fails instead of hanging.
fn git_in(dir: &Path, args: &[&str]) -> Result<String> {
let output = Command::new("git")
/// `what` names the command in the spawn error.
fn git_output(dir: &Path, args: &[&str], what: &str) -> Result<std::process::Output> {
Command::new("git")
.arg("-C")
.arg(dir)
.args(args)
.env("GIT_TERMINAL_PROMPT", "0")
.stderr(Stdio::piped())
.output()
.context("failed to spawn `git`")?;
.with_context(|| format!("failed to spawn `{what}`"))
}
/// Run a git command in `dir`, returning trimmed stdout.
///
/// The terminal prompt is disabled so a credential request fails instead of hanging.
fn git_in(dir: &Path, args: &[&str]) -> Result<String> {
let output = git_output(dir, args, "git")?;
if !output.status.success() {
bail!(
@@ -1631,55 +1573,18 @@ fn take_quoted(input: &str) -> Option<(&str, &str)> {
}
/// Undo git's C-style path quoting, `\NNN` octal escapes, `\"` and `\\`.
///
/// Delegates to gitoxide's C-style quote implementation, `gix::quote::ansi_c::undo`.
/// It expects the surrounding double quotes, which are re-added around the interior.
fn unquote_path(path: &str) -> Result<String> {
if !path.contains('\\') {
return Ok(path.to_owned());
}
let mut out = Vec::with_capacity(path.len());
let mut bytes = path.as_bytes();
while let Some((&b, rest)) = bytes.split_first() {
bytes = rest;
if b == b'\\' {
match bytes.split_first() {
Some((&b'"', rest)) | Some((&b'\\', rest)) => {
out.push(b);
bytes = rest;
}
Some((&b'n', rest)) => {
out.push(b'\n');
bytes = rest;
}
Some((&b't', rest)) => {
out.push(b'\t');
bytes = rest;
}
Some((&d1, rest)) if (b'0'..=b'7').contains(&d1) => {
let Some((&d2, rest)) = rest.split_first() else {
bail!("malformed octal escape in quoted path");
};
let Some((&d3, rest)) = rest.split_first() else {
bail!("malformed octal escape in quoted path");
};
if !(b'0'..=b'7').contains(&d2) || !(b'0'..=b'7').contains(&d3) {
bail!("malformed octal escape in quoted path");
}
let code =
(d1 - b'0') as u16 * 64 + (d2 - b'0') as u16 * 8 + (d3 - b'0') as u16;
if code > u8::MAX as u16 {
bail!("octal escape out of range in quoted path");
}
out.push(code as u8);
bytes = rest;
}
_ => bail!("malformed escape in quoted path"),
}
} else {
out.push(b);
}
}
String::from_utf8(out).context("invalid UTF-8 in quoted path")
let quoted = format!("\"{path}\"");
let (unquoted, _) = gix::quote::ansi_c::undo(gix::bstr::BStr::new(quoted.as_bytes()))
.map_err(|e| anyhow::anyhow!("malformed quoted path: {e}"))?;
String::from_utf8(unquoted.into_owned().to_vec()).context("invalid UTF-8 in quoted path")
}
/// Collects the hunks of one blob diff while tracking per-line numbers.
@@ -1807,11 +1712,6 @@ pub fn worktree_branches(workdir: &Path) -> Result<Vec<String>> {
repo_branches(&open_with_cache(workdir)?)
}
/// Short names of tags, `refs/tags/*`, sorted alphabetically.
pub fn worktree_tags(workdir: &Path) -> Result<Vec<String>> {
repo_tags(&open_with_cache(workdir)?)
}
/// Short name of the branch HEAD points to, or `None` when detached.
///
/// Detached after checking out a tag or a commit directly.
@@ -2291,38 +2191,6 @@ mod tests {
assert!(format_patch_between(&path, "feature", "feature").is_err());
}
#[test]
fn patch_applies_checks_without_modifying_the_tree() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("repo");
let initial = init_repository(&path, "My Repo", "desc").expect("init");
git_run(&path, &["checkout", "-b", "feature"]);
std::fs::write(path.join("feature.txt"), "feature\n").expect("write");
commit_all(&gix::open(&path).expect("open"), "feature commit");
let patch = format_patch_between(&path, &initial, "feature").expect("patch");
// A clone of the initial state accepts the series.
let clone = dir.path().join("clone");
git_run(
dir.path(),
&[
"clone",
"-q",
path.to_str().unwrap(),
clone.to_str().unwrap(),
],
);
git_run(&clone, &["checkout", "-q", &initial]);
assert!(patch_applies(&clone, &patch).is_ok());
// The check must not have modified the working tree.
assert!(!clone.join("feature.txt").exists());
// A conflicting file makes the same series fail the check.
std::fs::write(clone.join("feature.txt"), "conflicting\n").expect("write");
assert!(patch_applies(&clone, &patch).is_err());
}
#[test]
fn push_commit_ref_pushes_to_the_event_namespace() {
// A bare server repository reachable via a `file://` URL.
@@ -2977,7 +2845,7 @@ mod tests {
assert!(branches.windows(2).all(|pair| pair[0] <= pair[1]), "sorted");
assert_eq!(
worktree_tags(dir).expect("tags"),
repo_tags(&repo).expect("tags"),
vec!["v0.9".to_string(), "v1.0".to_string()]
);
}
-3
View File
@@ -5,9 +5,6 @@ edition.workspace = true
publish.workspace = true
[dependencies]
signed_core = { path = "../signed_core" }
nostr.workspace = true
nostr-sdk.workspace = true
nostr-connect.workspace = true
nostr-gossip-memory.workspace = true
-2
View File
@@ -7,7 +7,6 @@ pub struct Update {
/// First `a` tag value of the event, if any, for example the repository coordinate.
pub coordinate: Option<Coordinate>,
pub author: PublicKey,
pub event_id: EventId,
}
impl Update {
@@ -19,7 +18,6 @@ impl Update {
kind: event.kind,
coordinate,
author: event.pubkey,
event_id: event.id,
}
}
}
+42 -134
View File
@@ -1,5 +1,6 @@
use std::collections::hash_map::DefaultHasher;
use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
use std::str::FromStr;
@@ -45,8 +46,6 @@ pub enum BackendEvent {
PassphraseRequired,
/// The signer changed on login, logout or account switch.
SignerChanged,
/// Relay bootstrap finished.
Connected,
/// A new event was received from a relay and stored in the database.
NostrUpdate(Update),
/// A negentropy sync completed.
@@ -80,7 +79,6 @@ pub struct Backend {
client: Client,
signer: UniversalSigner,
current_user: Option<PublicKey>,
connected: bool,
sync_progress: Option<(u64, u64)>,
/// True when the stored credential is NIP-49 encrypted.
passphrase_required: bool,
@@ -151,7 +149,6 @@ impl Backend {
client,
signer,
current_user: None,
connected: false,
sync_progress: None,
passphrase_required: false,
recent_fetches: HashMap::new(),
@@ -186,11 +183,7 @@ impl Backend {
self.tasks.push(cx.spawn(async move |this, cx| {
match task.await {
Ok(()) => {
this.update(cx, |this, cx| {
this.connected = true;
cx.emit(BackendEvent::Connected);
cx.notify();
})?;
this.update(cx, |_this, cx| cx.notify())?;
}
Err(e) => {
this.update(cx, |_this, cx| cx.emit(BackendEvent::error(e.to_string())))?;
@@ -993,22 +986,14 @@ impl Backend {
self.tasks.push(cx.spawn(async move |this, cx| {
let result = async {
let events = client.fetch_events(filters::grasp_list(public_key)).await?;
let urls: Vec<String> = events
let events: Vec<Event> = client
.fetch_events(filters::grasp_list(public_key))
.await?
.into_iter()
.max_by_key(|e| e.created_at)
.map(|e| {
e.tags
.iter()
.filter(|t| t.kind() == "g")
.filter_map(|t| t.content().map(str::to_owned))
.collect()
})
.unwrap_or_default();
.collect();
for url in urls {
client.add_relay(&url).await.ok();
for url in latest_grasp_list_servers(events) {
client.add_relay(url.as_str()).await.ok();
}
client.connect().await;
@@ -1049,11 +1034,6 @@ impl Backend {
cx.emit(BackendEvent::error(message));
}
/// Whether the relay bootstrap has completed.
pub fn is_connected(&self) -> bool {
self.connected
}
/// Progress of the in-flight negentropy sync, if any.
pub fn sync_progress(&self) -> Option<(u64, u64)> {
self.sync_progress
@@ -1106,11 +1086,7 @@ impl Backend {
self.tasks.push(cx.spawn(async move |this, cx| {
match task.await {
Ok(()) => {
this.update(cx, |this, cx| {
this.connected = true;
cx.emit(BackendEvent::Connected);
cx.notify();
})?;
this.update(cx, |_this, cx| cx.notify())?;
}
Err(e) => {
this.update(cx, |_this, cx| cx.emit(BackendEvent::error(e.to_string())))?;
@@ -1120,43 +1096,6 @@ impl Backend {
}));
}
/// Add discovery-only relays, e.g. NIP-65 indexers, and connect to them.
pub fn add_discovery_relays(&mut self, urls: Vec<String>, cx: &mut Context<Self>) {
let client = self.client.clone();
let task = cx.background_spawn(async move {
for url in urls {
client
.add_relay(&url)
.capabilities(RelayCapabilities::DISCOVERY)
.await?;
}
client.connect().await;
Ok::<(), Error>(())
});
self.tasks.push(cx.spawn(async move |this, cx| {
if let Err(e) = task.await {
this.update(cx, |_this, cx| cx.emit(BackendEvent::error(e.to_string())))?;
}
Ok(())
}));
}
/// Start a persistent subscription.
pub fn subscribe(&mut self, filter: Filter, cx: &mut Context<Self>) {
let client = self.client.clone();
let task = cx.background_spawn(async move { client.subscribe(filter).await.map(|_| ()) });
self.tasks.push(cx.spawn(async move |this, cx| {
if let Err(e) = task.await {
this.update(cx, |_this, cx| cx.emit(BackendEvent::error(e.to_string())))?;
}
Ok(())
}));
}
/// Whether an identical fetch started within [`FETCH_DEDUP_WINDOW`] is still recent.
///
/// Records the fingerprint when returning `false`, pruning expired entries first.
@@ -1298,44 +1237,11 @@ impl Backend {
let client = self.client.clone();
let signer = self.signer.clone();
cx.spawn(async move |this, cx| {
self.publish_task(cx, async move {
// Sign with the current signer, broadcast and save locally.
// The event is immediately visible to database queries.
let work = cx.background_spawn(async move {
let event = builder.finalize_async(&signer).await?;
let output = client.send_event(&event).await?;
if output.success.is_empty() && !output.failed.is_empty() {
let reasons = output
.failed
.values()
.cloned()
.collect::<Vec<String>>()
.join(", ");
return Err(anyhow!("event not accepted by any relay: {reasons}"));
}
Ok(event)
});
let result = work.await;
match &result {
Ok(event) => {
this.update(cx, |_this, cx| {
cx.emit(BackendEvent::Published(Box::new(event.clone())));
})
.ok();
}
Err(e) => {
this.update(cx, |_this, cx| {
cx.emit(BackendEvent::error(e.to_string()));
})
.ok();
}
}
result
let event = builder.finalize_async(&signer).await?;
broadcast_event(&client, &event).await
})
}
@@ -1346,25 +1252,17 @@ impl Backend {
cx: &mut Context<Self>,
) -> Task<Result<Event, Error>> {
let client = self.client.clone();
self.publish_task(cx, async move { broadcast_event(&client, &event).await })
}
/// Run `work` in the background, then emit its outcome as a [`BackendEvent`].
fn publish_task(
&mut self,
cx: &mut Context<Self>,
work: impl Future<Output = Result<Event, Error>> + 'static + Send,
) -> Task<Result<Event, Error>> {
cx.spawn(async move |this, cx| {
let work = cx.background_spawn(async move {
let output = client.send_event(&event).await?;
if output.success.is_empty() && !output.failed.is_empty() {
let reasons = output
.failed
.values()
.cloned()
.collect::<Vec<String>>()
.join(", ");
return Err(anyhow!("event not accepted by any relay: {reasons}"));
}
Ok(event.clone())
});
let result = work.await;
let result = cx.background_spawn(work).await;
match &result {
Ok(event) => {
@@ -1385,15 +1283,6 @@ impl Backend {
})
}
/// Publish a NIP-34 repository announcement, kind 30617, with the current signer.
pub fn publish_announcement(
&mut self,
announcement: GitRepositoryAnnouncement,
cx: &mut Context<Self>,
) -> Task<Result<Event, Error>> {
self.send(announcement.into_event_builder(), cx)
}
/// Sign, broadcast and store an event without awaiting the result.
fn send_fire_and_forget(&mut self, builder: EventBuilder, cx: &mut Context<Self>) {
let task = self.send(builder, cx);
@@ -1433,6 +1322,25 @@ impl Backend {
}
}
/// Broadcast an event and fail when no relay accepted it.
///
/// The client stores accepted events locally, visible to database queries.
async fn broadcast_event(client: &Client, event: &Event) -> Result<Event, Error> {
let output = client.send_event(event).await?;
if output.success.is_empty() && !output.failed.is_empty() {
let reasons = output
.failed
.values()
.cloned()
.collect::<Vec<String>>()
.join(", ");
return Err(anyhow!("event not accepted by any relay: {reasons}"));
}
Ok(event.clone())
}
/// Fingerprint of a relay and filter set, for fetch dedup.
///
/// Relays and filters are sorted first, so the fingerprint is order-independent.
@@ -1603,8 +1511,8 @@ fn latest_grasp_list_servers(events: Vec<Event>) -> Vec<RelayUrl> {
.unwrap_or_default()
}
/// Resolve the user's published grasp servers.
pub(crate) async fn user_grasp_list_servers(
/// Resolve the user's published grasp servers from the local database.
pub async fn user_grasp_list_servers(
client: Client,
user: PublicKey,
) -> Result<Vec<RelayUrl>, Error> {
+12 -32
View File
@@ -13,6 +13,7 @@ use signed_core::{Announcement, RepoAddr};
use crate::backend::{Backend, BackendEvent};
use crate::git_store::GitStore;
use crate::local_repos::LocalReposStore;
use crate::refresh::{RefreshGate, RefreshRequest};
use crate::repo_list::RepoListStore;
/// Delay between a refresh request and the actual re-computation.
@@ -83,10 +84,8 @@ pub struct CheckoutsStore {
///
/// A recompute defaults the base the same way.
requested_head: HashMap<RepoAddr, Option<String>>,
refreshing: bool,
refresh_dirty: bool,
/// A refresh is waiting out [`REFRESH_DEBOUNCE`].
debouncing: bool,
/// Refresh coalescing, see [`RefreshGate`].
refresh: RefreshGate,
_subscriptions: Vec<Subscription>,
tasks: Vec<Task<Result<(), Error>>>,
}
@@ -144,9 +143,7 @@ impl CheckoutsStore {
push_requested: HashSet::new(),
push_statuses: Arc::new(HashMap::new()),
requested_head: HashMap::new(),
refreshing: false,
refresh_dirty: false,
debouncing: false,
refresh: RefreshGate::default(),
_subscriptions: subscriptions,
tasks: Vec::new(),
};
@@ -236,22 +233,14 @@ impl CheckoutsStore {
///
/// Requests arriving while a pass runs fold into a follow-up.
pub fn refresh(&mut self, cx: &mut Context<Self>) {
if self.refreshing {
self.refresh_dirty = true;
if self.refresh.request() != RefreshRequest::Schedule {
return;
}
if self.debouncing {
return;
}
self.debouncing = true;
let task = cx.spawn(async move |this, cx| {
cx.background_executor().timer(REFRESH_DEBOUNCE).await;
this.update(cx, |this, cx| {
this.debouncing = false;
this.run_refresh(cx);
})
this.update(cx, |this, cx| this.run_refresh(cx))
});
self.tasks.push(task);
@@ -259,7 +248,7 @@ impl CheckoutsStore {
/// One resolve and apply cycle, the debounced entry point.
fn run_refresh(&mut self, cx: &mut Context<Self>) {
self.refreshing = true;
self.refresh.begin();
// Inputs snapshot, all cheap shared reads.
let records = {
@@ -362,7 +351,7 @@ impl CheckoutsStore {
Err(_) => {
// Git reads are best-effort, keep the last results.
return this.update(cx, |this, _cx| {
this.refreshing = false;
this.refresh.abort();
});
}
};
@@ -373,13 +362,7 @@ impl CheckoutsStore {
this.push_statuses = Arc::new(push_statuses);
cx.notify();
this.refreshing = false;
if this.refresh_dirty {
this.refresh_dirty = false;
true
} else {
false
}
this.refresh.finish()
})?;
if again {
@@ -388,8 +371,8 @@ impl CheckoutsStore {
// Keep the statuses current while any repository panel is open.
this.update(cx, |this, cx| {
if poll && !this.debouncing && !this.refreshing {
this.debouncing = true;
if poll && this.refresh.idle() {
this.refresh.debounce();
// Open panels get the fast cadence.
// Each cycle fetches every watched checkout's remote.
let delay = if this.status_requested.is_empty() {
@@ -400,10 +383,7 @@ impl CheckoutsStore {
let task = cx.spawn(async move |this, cx| {
cx.background_executor().timer(delay).await;
this.update(cx, |this, cx| {
this.debouncing = false;
this.run_refresh(cx);
})
this.update(cx, |this, cx| this.run_refresh(cx))
});
this.tasks.push(task);
+2 -2
View File
@@ -3,12 +3,13 @@ mod checkouts;
mod git_store;
mod local_repos;
mod profile;
mod refresh;
mod repo;
mod repo_list;
use std::path::{Path, PathBuf};
pub use backend::{Backend, BackendEvent};
pub use backend::{Backend, BackendEvent, user_grasp_list_servers};
pub use checkouts::{CheckoutStatus, CheckoutsStore, pr_proposes_checkout};
pub use git_store::GitStore;
use gpui::{App, AppContext, Entity};
@@ -18,7 +19,6 @@ pub use profile::{Profile, ProfileStore};
pub use repo::RepoStore;
pub use repo_list::{RepoActivityCounts, RepoListStore};
use signed_nostr::new_backend;
pub use utils::shorten_pubkey;
/// Initialize the backend and stores, and install them as globals.
/// Call once at startup, before opening any window that uses the stores.
+79
View File
@@ -0,0 +1,79 @@
/// Refresh coalescing shared by the event stores.
///
/// [`crate::RepoStore`], [`crate::RepoListStore`] and [`crate::CheckoutsStore`]
/// re-query their inputs on a debounce timer with the same policy:
/// a request arriving while a run is in flight is folded into a follow-up run,
/// a request arriving while the debounce timer is pending is dropped by it.
#[derive(Debug, Default)]
pub struct RefreshGate {
/// A run is in flight.
running: bool,
/// A request arrived while a run was in flight.
dirty: bool,
/// The debounce timer is pending.
debouncing: bool,
}
/// What a refresh request decided.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RefreshRequest {
/// No run or timer covers the request, start the debounce timer.
Schedule,
/// A run or pending timer already covers the request.
Fold,
}
impl RefreshGate {
/// Whether a run is in flight.
pub fn running(&self) -> bool {
self.running
}
/// Whether the debounce timer is pending.
pub fn debouncing(&self) -> bool {
self.debouncing
}
/// Whether no run is in flight and no timer is pending.
pub fn idle(&self) -> bool {
!self.running && !self.debouncing
}
/// A new refresh request arrived.
///
/// Folded into a follow-up run while one is in flight, dropped while the
/// debounce timer is pending, otherwise starts the timer.
pub fn request(&mut self) -> RefreshRequest {
if self.running {
self.dirty = true;
RefreshRequest::Fold
} else if self.debouncing {
RefreshRequest::Fold
} else {
self.debouncing = true;
RefreshRequest::Schedule
}
}
/// A timer was started without a request, e.g. a poll cycle.
pub fn debounce(&mut self) {
self.debouncing = true;
}
/// The debounce timer fired and the run starts now.
pub fn begin(&mut self) {
self.debouncing = false;
self.running = true;
}
/// The run ended. Whether a request arrived while it ran.
pub fn finish(&mut self) -> bool {
self.running = false;
std::mem::take(&mut self.dirty)
}
/// The run was abandoned, e.g. on error. Pending follow-up requests survive.
pub fn abort(&mut self) {
self.running = false;
}
}
+15 -166
View File
@@ -9,15 +9,15 @@ use gpui::{AppContext, AsyncApp, Context, SharedString, Subscription, Task, Weak
use nostr::event::IntoEventBuilder;
use nostr_sdk::prelude::*;
use signed_core::{
Announcement, COVER_NOTE_KIND, Deletions, RepoAddr, RepoStatus, build_state, cover_note,
filters, labels_and_subject, parse_state, pull_request_patch, pull_request_patches,
subject_override,
Announcement, Deletions, RepoAddr, RepoStatus, filters, parse_state, pull_request_patch,
pull_request_patches,
};
use crate::backend::{
Backend, BackendEvent, grasp_base_url, grasp06_prs_url, pr_clone_urls, user_grasp_list_servers,
};
use crate::git_store::GitStore;
use crate::refresh::{RefreshGate, RefreshRequest};
/// Delay between a refresh request and the actual re-query.
const REFRESH_DEBOUNCE: Duration = Duration::from_millis(300);
@@ -34,8 +34,6 @@ const MAX_PATCH_EVENT_BYTES: usize = 60 * 1024;
pub struct RepoStore {
addr: RepoAddr,
pub announcement: Option<Announcement>,
/// `(refname, commit-id)` pairs from the latest state announcement.
pub refs: Vec<(String, String)>,
/// Branch pointed to by `HEAD` in the latest state announcement.
pub head: Option<String>,
pub issues: Vec<Event>,
@@ -49,11 +47,6 @@ pub struct RepoStore {
/// Computed with [`Self::status_by_root`] on every refresh.
open_issue_count: usize,
open_pr_count: usize,
/// Kind-1624 cover notes and kind-1985 label events.
///
/// They reference this repository's roots, used by ngit and GitWorkshop.
cover_notes: Vec<Event>,
labels: Vec<Event>,
/// Incremented on every applied refresh.
///
/// Views key their derived-data caches to it instead of recomputing on every render.
@@ -71,12 +64,9 @@ pub struct RepoStore {
/// Root events, issues, patches and PRs, already fetched per root.
///
/// The per-root fetches cover NIP-22 comments and statuses without an `a` tag.
/// Also kind-1624 cover notes and kind-1985 labels.
root_fetches: HashSet<EventId>,
refreshing: bool,
refresh_dirty: bool,
/// A refresh is waiting out [`REFRESH_DEBOUNCE`].
debouncing: bool,
/// Refresh coalescing, see [`RefreshGate`].
refresh: RefreshGate,
tasks: Vec<Task<Result<(), Error>>>,
_subscription: Subscription,
}
@@ -101,10 +91,8 @@ impl RepoStore {
// Status events may omit their `a` tag, NIP-34.
// Any status event may reference a root of this repository.
let status = RepoStatus::from_kind(update.kind).is_some();
// Cover notes and labels carry no `a` tag either.
let annotation = update.kind == COVER_NOTE_KIND || update.kind == Kind::Label;
deletion || coordinate || (author && kind) || comment || status || annotation
deletion || coordinate || (author && kind) || comment || status
}
BackendEvent::Published(event) => {
let kind = event.kind == Kind::GitRepoAnnouncement;
@@ -128,7 +116,6 @@ impl RepoStore {
let mut store = Self {
addr,
announcement: None,
refs: Vec::new(),
head: None,
issues: Vec::new(),
patches: Vec::new(),
@@ -137,16 +124,12 @@ impl RepoStore {
status_by_root: HashMap::new(),
open_issue_count: 0,
open_pr_count: 0,
cover_notes: Vec::new(),
labels: Vec::new(),
version: 0,
last_error: None,
last_warning: None,
repo_relays: HashSet::new(),
root_fetches: HashSet::new(),
refreshing: false,
refresh_dirty: false,
debouncing: false,
refresh: RefreshGate::default(),
_subscription: subscription,
tasks: Vec::new(),
};
@@ -225,22 +208,14 @@ impl RepoStore {
/// Re-query the local database and update all fields.
pub fn refresh(&mut self, cx: &mut Context<Self>) {
if self.refreshing {
self.refresh_dirty = true;
if self.refresh.request() != RefreshRequest::Schedule {
return;
}
if self.debouncing {
return;
}
self.debouncing = true;
let task = cx.spawn(async move |this, cx| {
cx.background_executor().timer(REFRESH_DEBOUNCE).await;
this.update(cx, |this, cx| {
this.debouncing = false;
this.run_refresh(cx);
})
this.update(cx, |this, cx| this.run_refresh(cx))
});
self.tasks.retain(|task| !task.is_ready());
@@ -248,7 +223,7 @@ impl RepoStore {
}
fn run_refresh(&mut self, cx: &mut Context<Self>) {
self.refreshing = true;
self.refresh.begin();
let backend = Backend::global(cx);
let client = backend.read(cx).client();
@@ -282,7 +257,6 @@ impl RepoStore {
let (mut issues, mut patches, mut pull_requests, mut statuses, mut comments) =
(Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new());
let (mut cover_notes, mut labels): (Vec<Event>, Vec<Event>) = (Vec::new(), Vec::new());
for event in activity {
if deletions.is_deleted(&event) {
@@ -338,35 +312,11 @@ impl RepoStore {
// Cover notes, 1624, and label events, 1985, carry no `a` tag.
// Query them per root like comments and statuses.
let mut seen_cover_notes: HashSet<EventId> = cover_notes.iter().map(|e| e.id).collect();
let mut seen_labels: HashSet<EventId> = labels.iter().map(|e| e.id).collect();
let db = client.database();
let roots = issues
.iter()
.chain(&patches)
.chain(&pull_requests)
.map(|e| e.id);
for root in roots {
for event in db.query(filters::annotations_for([root])).await? {
if deletions.is_deleted(&event) {
continue;
}
if event.kind == COVER_NOTE_KIND && seen_cover_notes.insert(event.id) {
cover_notes.push(event);
} else if event.kind == Kind::Label && seen_labels.insert(event.id) {
labels.push(event);
}
}
}
// The events are only stored for interop and nothing displays them.
sort_newest_first(&mut issues);
sort_newest_first(&mut patches);
sort_newest_first(&mut pull_requests);
sort_oldest_first(&mut comments);
sort_newest_first(&mut cover_notes);
sort_newest_first(&mut labels);
// Resolve every root's status once here.
// Render paths do HashMap lookups instead of per-root status scans.
@@ -402,8 +352,6 @@ impl RepoStore {
open_issue_count,
open_pr_count,
comments,
cover_notes,
labels,
))
});
@@ -420,13 +368,11 @@ impl RepoStore {
open_issue_count,
open_pr_count,
comments,
cover_notes,
labels,
) = match work.await {
Ok(data) => data,
Err(e) => {
return this.update(cx, |this, cx| {
this.refreshing = false;
this.refresh.abort();
this.last_error = Some(e.to_string());
cx.notify();
});
@@ -445,8 +391,7 @@ impl RepoStore {
.unwrap_or_default();
this.connect_announced_relays(&relays, cx);
if let Some((refs, head)) = state {
this.refs = refs;
if let Some((_, head)) = state {
this.head = head;
}
@@ -457,11 +402,9 @@ impl RepoStore {
this.status_by_root = status_by_root;
this.open_issue_count = open_issue_count;
this.open_pr_count = open_pr_count;
this.cover_notes = cover_notes;
this.labels = labels;
this.version = this.version.wrapping_add(1);
// Comments, statuses without an `a` tag, cover notes and labels.
// Comments and statuses without an `a` tag.
// None are addressed to the repository.
// Fetch them by the root events they reference.
// Use the bootstrap relays and the relays this repository announced.
@@ -482,11 +425,9 @@ impl RepoStore {
if !new_roots.is_empty() {
this.root_fetches.extend(new_roots.iter().copied());
// Batch the per-root filters.
// One statuses filter and one annotations filter cover all new roots.
// One filter per root costs a negentropy reconciliation per relay.
let mut root_filters = filters::comments_for(new_roots.clone());
root_filters.push(filters::statuses_for(new_roots.iter().copied()));
root_filters.push(filters::annotations_for(new_roots));
let announced: Vec<RelayUrl> = this.repo_relays.iter().cloned().collect();
let backend = Backend::global(cx);
@@ -498,13 +439,7 @@ impl RepoStore {
cx.notify();
this.refreshing = false;
if this.refresh_dirty {
this.refresh_dirty = false;
true
} else {
false
}
this.refresh.finish()
})?;
// Requests that arrived while the refresh was running.
@@ -528,40 +463,6 @@ impl RepoStore {
self.version
}
/// The effective cover note of `root`, kind 1624, if any.
pub fn cover_note_of(&self, root: &Event) -> Option<&Event> {
let maintainers = self
.announcement
.as_ref()
.map(Announcement::effective_maintainers)
.unwrap_or_default();
cover_note(root, &self.cover_notes, &maintainers)
}
/// The effective hashtag labels of `root`.
pub fn labels_of(&self, root: &Event) -> Vec<String> {
let maintainers = self
.announcement
.as_ref()
.map(Announcement::effective_maintainers)
.unwrap_or_default();
let (labels, _) = labels_and_subject(root, &self.labels, &maintainers);
labels
}
/// The effective subject or title override of `root`, if any.
pub fn subject_of(&self, root: &Event) -> Option<String> {
let maintainers = self
.announcement
.as_ref()
.map(Announcement::effective_maintainers)
.unwrap_or_default();
subject_override(root, &self.labels, &maintainers)
}
/// Number of open issues.
///
/// Issues whose resolved status is [`RepoStatus::Open`].
@@ -1067,58 +968,6 @@ impl RepoStore {
self.send(builder, cx);
}
/// Publish a repository state announcement
pub fn publish_state(&mut self, cx: &mut Context<Self>) {
self.last_error = None;
let backend = Backend::global(cx);
let Some(user) = backend.read(cx).current_user() else {
self.last_error = Some("Sign in to publish repository state".into());
cx.notify();
return;
};
if !self.is_author(&user) {
self.last_error = Some("Only the repository owner can publish state".into());
cx.notify();
return;
}
let cache = GitStore::global(cx).cache().clone();
let addr = self.addr.clone();
let clone_urls: Vec<String> = self
.announcement
.as_ref()
.map(|a| a.clone.iter().map(ToString::to_string).collect())
.unwrap_or_default();
let work = cx.background_spawn(async move {
let repo = cache.ensure_clone(&addr, &clone_urls)?;
signed_git::repo_ref_state(&repo)
});
self.tasks.push(cx.spawn(async move |this, cx| {
let state = match work.await {
Ok(state) => state,
Err(e) => {
return this.update(cx, |this, cx| {
this.last_error = Some(e.to_string());
cx.notify();
});
}
};
this.update(cx, |this, cx| {
let builder =
build_state(&this.addr.identifier, &state.refs, state.head.as_deref());
this.send(builder, cx);
})?;
Ok(())
}));
}
/// Merge a pull request.
pub fn merge_pull_request(&mut self, root: &Event, cx: &mut Context<Self>) {
self.last_error = None;
+12 -36
View File
@@ -8,6 +8,7 @@ use nostr_sdk::prelude::*;
use signed_core::{Announcement, Deletions, RepoAddr, filters, repo_addr};
use crate::backend::{Backend, BackendEvent};
use crate::refresh::{RefreshGate, RefreshRequest};
/// Delay between a refresh request and the actual re-query.
///
@@ -53,10 +54,8 @@ pub struct RepoListStore {
/// Used for the Popular ranking of the explore list.
pub counts: Arc<HashMap<RepoAddr, RepoActivityCounts>>,
author: Option<PublicKey>,
refreshing: bool,
refresh_dirty: bool,
/// A refresh is waiting out [`REFRESH_DEBOUNCE`].
debouncing: bool,
/// Refresh coalescing, see [`RefreshGate`].
refresh: RefreshGate,
tasks: Vec<Task<Result<(), Error>>>,
_subscription: Subscription,
}
@@ -118,9 +117,7 @@ impl RepoListStore {
last_activity: Arc::new(HashMap::new()),
counts: Arc::new(HashMap::new()),
author,
refreshing: false,
refresh_dirty: false,
debouncing: false,
refresh: RefreshGate::default(),
_subscription: subscription,
tasks: Vec::new(),
};
@@ -132,13 +129,6 @@ impl RepoListStore {
store
}
/// Scope the list to an author, or clear the scope with `None`.
pub fn set_author(&mut self, author: Option<PublicKey>, cx: &mut Context<Self>) {
self.author = author;
self.subscribe_remote(cx);
self.refresh(cx);
}
/// Negentropy-sync announcements with the bootstrap relays.
fn subscribe_remote(&mut self, cx: &mut Context<Self>) {
let backend = Backend::global(cx);
@@ -160,9 +150,9 @@ impl RepoListStore {
/// Query the local database immediately, no debounce.
/// Stored announcements appear as soon as the app opens.
fn refresh_initial(&mut self, cx: &mut Context<Self>) {
debug_assert!(!self.debouncing);
if self.refreshing {
self.refresh_dirty = true;
debug_assert!(!self.refresh.debouncing());
if self.refresh.running() {
self.refresh.request();
return;
}
self.run_refresh(cx);
@@ -170,22 +160,14 @@ impl RepoListStore {
/// Re-query the local database.
pub fn refresh(&mut self, cx: &mut Context<Self>) {
if self.refreshing {
self.refresh_dirty = true;
if self.refresh.request() != RefreshRequest::Schedule {
return;
}
if self.debouncing {
return;
}
self.debouncing = true;
let task = cx.spawn(async move |this, cx| {
cx.background_executor().timer(REFRESH_DEBOUNCE).await;
this.update(cx, |this, cx| {
this.debouncing = false;
this.run_refresh(cx);
})
this.update(cx, |this, cx| this.run_refresh(cx))
});
self.tasks.push(task);
@@ -193,7 +175,7 @@ impl RepoListStore {
/// One query and apply cycle, the debounced entry point.
fn run_refresh(&mut self, cx: &mut Context<Self>) {
self.refreshing = true;
self.refresh.begin();
let backend = Backend::global(cx);
let client = backend.read(cx).client();
@@ -315,7 +297,7 @@ impl RepoListStore {
// Database errors are transient, keep the last list.
Err(_) => {
return this.update(cx, |this, _cx| {
this.refreshing = false;
this.refresh.abort();
});
}
};
@@ -326,13 +308,7 @@ impl RepoListStore {
this.counts = Arc::new(counts);
cx.notify();
this.refreshing = false;
if this.refresh_dirty {
this.refresh_dirty = false;
true
} else {
false
}
this.refresh.finish()
})?;
// Requests that arrived while the refresh was running.
-139
View File
@@ -1,139 +0,0 @@
use std::collections::{HashMap, VecDeque};
use std::mem::take;
use futures::FutureExt;
use gpui::{
App, AppContext, Asset, AssetLogger, ElementId, Entity, ImageAssetLoader, ImageCache,
ImageCacheItem, ImageCacheProvider, ImageSource, Resource, hash,
};
/// Default number of images each view's cache retains.
/// Loading a new image evicts the least recently used entry once this is reached.
pub const MAX_IMAGES: usize = 128;
pub fn image_cache(id: impl Into<ElementId>, max_items: usize) -> AppImageCacheProvider {
AppImageCacheProvider {
id: id.into(),
max_items,
}
}
pub struct AppImageCacheProvider {
id: ElementId,
max_items: usize,
}
impl ImageCacheProvider for AppImageCacheProvider {
fn provide(&mut self, window: &mut gpui::Window, cx: &mut App) -> gpui::AnyImageCache {
window
.with_global_id(self.id.clone(), |id, window| {
window.with_element_state(id, |cache, _| {
let cache = cache.unwrap_or_else(|| AppImageCache::new(self.max_items, cx));
(cache.clone(), cache)
})
})
.into()
}
}
pub struct AppImageCache {
max_items: usize,
usage_list: VecDeque<u64>,
cache: HashMap<u64, (ImageCacheItem, Resource)>,
}
impl AppImageCache {
pub fn new(max_items: usize, cx: &mut App) -> Entity<Self> {
cx.new(|cx| {
log::info!("Creating AppImageCacheProvider");
cx.on_release(|this: &mut Self, cx| {
for (ix, (mut image, resource)) in take(&mut this.cache) {
if let Some(Ok(image)) = image.get() {
log::info!("Dropping image {ix}");
cx.drop_image(image, None);
}
ImageSource::Resource(resource).remove_asset(cx);
}
})
.detach();
AppImageCache {
max_items,
usage_list: VecDeque::with_capacity(max_items),
cache: HashMap::with_capacity(max_items),
}
})
}
}
impl ImageCache for AppImageCache {
fn load(
&mut self,
resource: &Resource,
window: &mut gpui::Window,
cx: &mut gpui::App,
) -> Option<Result<std::sync::Arc<gpui::RenderImage>, gpui::ImageCacheError>> {
let hash = hash(resource);
if let Some(item) = self.cache.get_mut(&hash) {
let current_idx = self
.usage_list
.iter()
.position(|item| *item == hash)
.expect("cache has an item usage_list doesn't");
self.usage_list.remove(current_idx);
self.usage_list.push_front(hash);
return item.0.get();
}
let load_future = AssetLogger::<ImageAssetLoader>::load(resource.clone(), cx);
let task = cx.background_executor().spawn(load_future).shared();
if self.usage_list.len() >= self.max_items {
log::info!("Image cache is full, evicting oldest item");
if let Some(oldest) = self.usage_list.pop_back() {
let mut image = self
.cache
.remove(&oldest)
.expect("usage_list has an item cache doesn't");
if let Some(Ok(image)) = image.0.get() {
log::info!("requesting image to be dropped");
cx.drop_image(image, Some(window));
}
ImageSource::Resource(image.1).remove_asset(cx);
}
}
self.cache.insert(
hash,
(
gpui::ImageCacheItem::Loading(task.clone()),
resource.clone(),
),
);
self.usage_list.push_front(hash);
let entity = window.current_view();
window
.spawn(cx, async move |cx| {
let result = task.await;
if let Err(err) = result {
log::error!("error loading image into cache: {:?}", err);
}
cx.on_next_frame(move |_, cx| {
cx.notify(entity);
});
})
.detach();
None
}
}
-2
View File
@@ -10,12 +10,10 @@ mod tree_row;
mod user_avatar;
pub mod copy_row;
pub mod image_cache;
pub mod util;
pub use copy_row::{copy_row, menu_copy_row};
pub use dropdown_button::DropdownButton;
pub use image_cache::{MAX_IMAGES, image_cache};
pub use nav_item::NavItem;
pub use pixel_avatar::PixelAvatar;
pub use placeholder::placeholder;
-1
View File
@@ -23,6 +23,5 @@ gix.workspace = true
nostr.workspace = true
anyhow.workspace = true
chrono.workspace = true
futures.workspace = true
log.workspace = true
-1
View File
@@ -3,7 +3,6 @@ mod workspace;
use gpui::{App, AppContext, Entity, Window};
use gpui_component::Root;
pub use signed_ui::image_cache;
pub use views::{RepoListView, SidebarPanel};
pub use workspace::Workspace;
@@ -0,0 +1,36 @@
use gpui::prelude::*;
use gpui::{AnyElement, App, SharedString, div};
use gpui_component::ActiveTheme;
/// Progress of an async dialog action: a busy flag disabling the form,
/// and an error line shown under it.
#[derive(Debug, Default)]
pub struct DialogProgress {
pub busy: bool,
pub error: Option<SharedString>,
}
impl DialogProgress {
/// An action started, disable the form and clear the previous error.
pub fn begin(&mut self) {
self.busy = true;
self.error = None;
}
/// An action failed, re-enable the form and surface `message`.
pub fn fail(&mut self, message: impl Into<SharedString>) {
self.busy = false;
self.error = Some(message.into());
}
}
/// The shared error line under a dialog form, `None` when there is no error.
pub fn error_row(error: &Option<SharedString>, cx: &App) -> Option<AnyElement> {
error.as_ref().map(|message| {
div()
.text_sm()
.text_color(cx.theme().danger)
.child(message.clone())
.into_any_element()
})
}
+1
View File
@@ -1,3 +1,4 @@
mod dialog_state;
mod repo_detail;
mod repo_list;
pub(crate) mod sidebar;
@@ -325,7 +325,7 @@ pub struct CommitDiffView {
error: Option<SharedString>,
/// Changed-files explorer and per-file diff, also used by the new PR panel's compare view.
pane: Entity<DiffPane>,
/// In-flight tasks, pruned on every push, see [`helpers::track`].
/// In-flight tasks, pruned on every push.
tasks: Vec<gpui::Task<Result<(), anyhow::Error>>>,
}
@@ -1,15 +1,22 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use assets::CustomIconName;
use gpui::prelude::*;
use gpui::{AnyElement, App, SharedString, div, px};
use gpui::{AnyElement, App, Entity, SharedString, div, px};
use gpui_component::button::{Button, ButtonVariants};
use gpui_component::input::{Textarea, TextareaState};
use gpui_component::menu::PopupMenu;
use gpui_component::tag::Tag;
use gpui_component::tree::TreeItem;
use gpui_component::{ActiveTheme, h_flex};
use gpui_component::{ActiveTheme, Icon, Sizable, StyledExt, h_flex, v_flex};
use nostr::nips::nip19::{Nip19Coordinate, ToBech32};
use nostr::prelude::{Event, EventId, PublicKey};
use signed_core::Announcement;
use signed_git::{DiffHunk, DiffLine, DiffLineKind, FileDiff};
use signed_ui::{menu_copy_row, middle_truncate};
use signed_state::{ProfileStore, RepoStore};
use signed_ui::{UserAvatar, menu_copy_row, middle_truncate};
use utils::relative_time;
pub(super) struct TreeItemSeed {
/// Path of the node, relative to the worktree root.
@@ -348,6 +355,229 @@ pub(super) fn find_item<'a>(items: &'a [TreeItem], id: Option<&str>) -> Option<&
})
}
/// The root issue events of a repo store, for the shared detail sections.
pub(super) fn issue_roots(store: &RepoStore) -> &[Event] {
&store.issues
}
/// The root pull request events of a repo store, for the shared detail sections.
pub(super) fn pr_roots(store: &RepoStore) -> &[Event] {
&store.pull_requests
}
/// Section heading of a detail sidebar, shared by the issue and PR panels.
pub(super) fn sidebar_title(text: &str, cx: &App) -> AnyElement {
div()
.text_xs()
.font_semibold()
.text_color(cx.theme().muted_foreground)
.child(text.to_string())
.into_any_element()
}
/// Right sidebar with participants and labels of a root event, issue or PR.
pub(super) fn sidebar_section(
store: &Entity<RepoStore>,
id: EventId,
roots: fn(&RepoStore) -> &[Event],
top_gap: bool,
cx: &App,
) -> AnyElement {
let store = store.read(cx);
let Some(root) = roots(store).iter().find(|event| event.id == id) else {
// The caller bails out when the root is missing.
return div().into_any_element();
};
let profile_store = ProfileStore::global(cx);
// Participants, the root author plus everyone who commented.
let mut participants: Vec<PublicKey> = vec![root.pubkey];
participants.extend(store.comments_of(&root.id).map(|comment| comment.pubkey));
participants.sort_by_key(PublicKey::to_hex);
participants.dedup();
// Labels are NIP-34 `t` hashtag tags on the event.
let labels: Vec<String> = root.tags.hashtags().map(|tag| tag.to_string()).collect();
v_flex()
.w(px(240.))
.h_full()
.flex_none()
.px_4()
.gap_4()
.border_l(px(1.))
.border_color(cx.theme().sidebar_border)
.child(
v_flex()
.when(top_gap, |this| this.mt_4())
.gap_2()
.child(sidebar_title("Participants", cx))
.children(participants.iter().map(|pubkey| {
let profile = profile_store.read(cx).get(pubkey);
let name = profile.name();
let picture = profile.picture();
h_flex()
.gap_1()
.items_center()
.child(UserAvatar::new(name.clone()).picture(picture))
.child(div().text_sm().truncate().text_ellipsis().child(name))
.into_any_element()
})),
)
.child(
v_flex()
.gap_2()
.child(sidebar_title("Labels", cx))
.map(|this| {
if labels.is_empty() {
this.child(
div()
.text_sm()
.text_color(cx.theme().muted_foreground)
.child("None yet."),
)
} else {
this.child(h_flex().gap_1().children({
let mut items = vec![];
for label in labels.iter() {
items.push(
Tag::secondary()
.outline()
.xsmall()
.child(SharedString::from(label)),
);
}
items
}))
}
}),
)
.into_any_element()
}
/// The comments on a root event, issue or PR, one card per comment.
///
/// Comment bodies become shared strings once per comment, not per render.
pub(super) fn comments_section(
store: &Entity<RepoStore>,
root: EventId,
contents: &mut HashMap<EventId, SharedString>,
cx: &App,
) -> AnyElement {
let store = store.read(cx);
let comments: Vec<&Event> = store.comments_of(&root).collect();
let title = SharedString::from(format!("Discussions {}", comments.len()));
v_flex()
.gap_4()
.child(div().text_xs().font_semibold().child(title))
.children(comments.iter().map(|comment| {
let profile = ProfileStore::global(cx).read(cx).get(&comment.pubkey);
let author = profile.name();
let picture = profile.picture();
let age = relative_time(comment.created_at);
let content = contents
.entry(comment.id)
.or_insert_with(|| SharedString::from(comment.content.clone()))
.clone();
v_flex()
.gap_1()
.p_3()
.border_1()
.border_color(cx.theme().border)
.rounded(cx.theme().radius)
.child(
h_flex()
.gap_2()
.text_sm()
.child(
h_flex()
.gap_1()
.child(UserAvatar::new(author.clone()).picture(picture))
.child(author),
)
.child(
div()
.text_color(cx.theme().muted_foreground)
.child("commented"),
)
.child(
div()
.text_color(cx.theme().muted_foreground)
.child(SharedString::from(age)),
),
)
.child(div().text_sm().child(content))
}))
.into_any_element()
}
/// The comment form posting to an issue or PR root event.
///
/// `roots` selects the root's list within the store, issues or pull requests.
pub(super) fn comment_form(
store: &Entity<RepoStore>,
root: EventId,
roots: fn(&RepoStore) -> &[Event],
comment_input: &Entity<TextareaState>,
button_id: &'static str,
cx: &App,
) -> AnyElement {
let comment_input = comment_input.clone();
let store = store.clone();
v_flex()
.gap_2()
.child(
Textarea::new(&comment_input)
.h_24()
.text_color(cx.theme().muted_foreground)
.bg(cx.theme().muted),
)
.child(
h_flex()
.justify_between()
.child(
h_flex()
.gap_1()
.text_xs()
.text_color(cx.theme().muted_foreground)
.child(Icon::new(CustomIconName::Markdown).small())
.child("Markdown is supported"),
)
.child(
Button::new(button_id)
.primary()
.label("Comment")
.tooltip("Post comment")
.on_click(move |_event, window, cx| {
let content = comment_input.read(cx).value().trim().to_string();
if content.is_empty() {
return;
}
let Some(root) = roots(store.read(cx))
.iter()
.find(|event| event.id == root)
.cloned()
else {
return;
};
store.update(cx, |store, cx| {
store.comment(&root, content, cx);
});
comment_input.update(cx, |input, cx| {
input.set_value("", window, cx);
});
}),
),
)
.into_any_element()
}
#[cfg(test)]
mod tests {
use super::*;
@@ -2,7 +2,7 @@ use std::path::PathBuf;
use assets::CustomIconName;
use gpui::prelude::*;
use gpui::{App, Entity, SharedString, WeakEntity, Window, div, px};
use gpui::{App, Entity, WeakEntity, Window, px};
use gpui_base::h_flex;
use gpui_base::input::TextareaState;
use gpui_component::button::{Button, ButtonVariants};
@@ -14,16 +14,13 @@ use settings::SettingsStore;
use signed_state::Backend;
use super::RepoDetailView;
use crate::views::dialog_state::{DialogProgress, error_row};
use crate::views::sidebar::grasp_servers::{
GraspServersState, grasp_servers_field, load_user_grasp_servers,
};
/// Shared state for the Init dialog, so async results can be rendered.
#[derive(Default)]
pub struct InitRepoState {
pub busy: bool,
pub error: Option<SharedString>,
}
pub type InitRepoState = DialogProgress;
/// Open the Init dialog for the local repository at `local_path`.
pub fn open(
@@ -113,9 +110,7 @@ pub fn open(
)
.child(grasp_servers_field(&grasp_state, &relay_input, cx)),
)
.children(error.map(|message| {
div().text_sm().text_color(cx.theme().danger).child(message)
}))
.children(error_row(&error, cx))
.child(
DialogFooter::new().justify_end().child(
Button::new("init")
@@ -169,23 +164,16 @@ fn init_repository(
let servers = grasp_state.read(cx).grasp_servers.clone();
if name.is_empty() {
state.update(cx, |state, _| {
state.error = Some("Repository name is required".into());
});
state.update(cx, |state, _| state.fail("Repository name is required"));
return;
}
if servers.is_empty() {
state.update(cx, |state, _| {
state.error = Some("Add at least one grasp server".into());
});
state.update(cx, |state, _| state.fail("Add at least one grasp server"));
return;
}
state.update(cx, |state, _| {
state.busy = true;
state.error = None;
});
state.update(cx, |state, _| state.begin());
let backend = Backend::global(cx);
let task = backend.update(cx, |backend, cx| {
@@ -210,10 +198,7 @@ fn init_repository(
}
Err(e) => {
cx.update_window(handle, |_, _window, cx| {
state.update(cx, |state, _| {
state.busy = false;
state.error = Some(e.to_string().into());
});
state.update(cx, |state, _| state.fail(e.to_string()));
})
.ok();
}
@@ -1,24 +1,22 @@
use std::collections::HashMap;
use assets::CustomIconName;
use dock::{BasePanel, Panel, PanelEvent};
use gpui::prelude::*;
use gpui::{
AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, Render, SharedString,
Window, div, px, relative,
App, Context, Entity, EventEmitter, FocusHandle, Focusable, Render, SharedString, Window, div,
relative,
};
use gpui_component::button::{Button, ButtonVariants};
use gpui_component::input::{Textarea, TextareaState};
use gpui_component::input::TextareaState;
use gpui_component::scroll::ScrollableElement;
use gpui_component::tag::Tag;
use gpui_component::{ActiveTheme, Icon, Sizable, StyledExt, h_flex, v_flex};
use nostr::prelude::{Event, EventId, PublicKey};
use gpui_component::{ActiveTheme, StyledExt, h_flex, v_flex};
use nostr::prelude::EventId;
use signed_core::activity_subject;
use signed_state::{ProfileStore, RepoStore};
use signed_ui::image_cache::{MAX_IMAGES, image_cache};
use signed_ui::{UserAvatar, placeholder, status_badge};
use utils::relative_time;
use super::helpers::{comment_form, comments_section, issue_roots, sidebar_section};
/// Detail panel of a single issue.
pub struct IssueDetailView {
/// Repo store holding the issues and their statuses.
@@ -48,189 +46,6 @@ impl IssueDetailView {
contents: HashMap::new(),
}
}
fn render_sidebar(&self, cx: &mut Context<Self>) -> impl IntoElement {
let profile_store = ProfileStore::global(cx);
let store = self.store.read(cx);
let Some(issue) = store.issues.iter().find(|issue| issue.id == self.issue_id) else {
// `render` already bails out when the issue is missing.
return div().into_any_element();
};
// Participants, the issue author plus everyone who commented.
let mut participants: Vec<PublicKey> = vec![issue.pubkey];
participants.extend(store.comments_of(&issue.id).map(|comment| comment.pubkey));
participants.sort_by_key(PublicKey::to_hex);
participants.dedup();
// Issue labels are NIP-34 `t` hashtag tags on the event.
let labels: Vec<String> = issue.tags.hashtags().map(|tag| tag.to_string()).collect();
v_flex()
.w(px(240.))
.h_full()
.flex_none()
.px_4()
.gap_4()
.border_l(px(1.))
.border_color(cx.theme().sidebar_border)
.child(
v_flex()
.gap_2()
.child(sidebar_title("Participants", cx))
.children(participants.iter().map(|pubkey| {
let profile = profile_store.read(cx).get(pubkey);
let name = profile.name();
let picture = profile.picture();
h_flex()
.gap_1()
.items_center()
.child(UserAvatar::new(name.clone()).picture(picture))
.child(div().text_sm().truncate().text_ellipsis().child(name))
.into_any_element()
})),
)
.child(
v_flex()
.gap_2()
.child(sidebar_title("Labels", cx))
.map(|this| {
if labels.is_empty() {
this.child(
div()
.text_sm()
.text_color(cx.theme().muted_foreground)
.child("None yet."),
)
} else {
this.child(h_flex().gap_1().children({
let mut items = vec![];
for label in labels.iter() {
items.push(
Tag::secondary()
.outline()
.xsmall()
.child(SharedString::from(label)),
);
}
items
}))
}
}),
)
.into_any_element()
}
fn render_comments(&mut self, id: &EventId, cx: &mut Context<Self>) -> impl IntoElement {
let store = self.store.read(cx);
let comments: Vec<&Event> = store.comments_of(id).collect();
let title = SharedString::from(format!("Discussions {}", comments.len()));
v_flex()
.gap_4()
.child(div().text_xs().font_semibold().child(title))
.children(comments.iter().map(|comment| {
let profile = ProfileStore::global(cx).read(cx).get(&comment.pubkey);
let author = profile.name();
let picture = profile.picture();
let age = relative_time(comment.created_at);
// Comment bodies become shared strings once per comment, not per render.
let content = self
.contents
.entry(comment.id)
.or_insert_with(|| SharedString::from(comment.content.clone()))
.clone();
v_flex()
.gap_1()
.p_3()
.border_1()
.border_color(cx.theme().border)
.rounded(cx.theme().radius)
.child(
h_flex()
.gap_2()
.text_sm()
.child(
h_flex()
.gap_1()
.child(UserAvatar::new(author.clone()).picture(picture))
.child(author),
)
.child(
div()
.text_color(cx.theme().muted_foreground)
.child("commented"),
)
.child(
div()
.text_color(cx.theme().muted_foreground)
.child(SharedString::from(age)),
),
)
.child(div().text_sm().child(content))
}))
.into_any_element()
}
fn render_form(&mut self, id: &EventId, cx: &mut Context<Self>) -> impl IntoElement {
let comment_input = self.comment_input.clone();
let store = self.store.clone();
let id = id.to_owned();
v_flex()
.gap_2()
.child(
Textarea::new(&self.comment_input)
.h_24()
.text_color(cx.theme().muted_foreground)
.bg(cx.theme().muted),
)
.child(
h_flex()
.justify_between()
.child(
h_flex()
.gap_1()
.text_xs()
.text_color(cx.theme().muted_foreground)
.child(Icon::new(CustomIconName::Markdown).small())
.child("Markdown is supported"),
)
.child(
Button::new("comment")
.primary()
.label("Comment")
.tooltip("Post comment")
.on_click(move |_event, window, cx| {
let content = comment_input.read(cx).value().trim().to_string();
if content.is_empty() {
return;
}
let Some(root) = store
.read(cx)
.issues
.iter()
.find(|issue| issue.id == id)
.cloned()
else {
return;
};
store.update(cx, |store, cx| {
store.comment(&root, content, cx);
});
comment_input.update(cx, |input, cx| {
input.set_value("", window, cx);
});
}),
),
)
.into_any_element()
}
}
impl BasePanel for IssueDetailView {
@@ -300,7 +115,7 @@ impl Render for IssueDetailView {
};
h_flex()
.image_cache(image_cache("issue-detail", MAX_IMAGES))
.image_cache(gpui::retain_all("issue-detail"))
.id("issue-detail")
.size_full()
.child(
@@ -357,20 +172,29 @@ impl Render for IssueDetailView {
)
.child(div().text_sm().child(content)),
)
.child(self.render_comments(&issue_id, cx))
.child(self.render_form(&issue_id, cx)),
.child(comments_section(
&self.store,
issue_id,
&mut self.contents,
cx,
))
.child(comment_form(
&self.store,
issue_id,
issue_roots,
&self.comment_input,
"comment",
cx,
)),
),
)
.child(self.render_sidebar(cx))
.child(sidebar_section(
&self.store,
issue_id,
issue_roots,
false,
cx,
))
.into_any_element()
}
}
fn sidebar_title(text: &str, cx: &App) -> AnyElement {
div()
.text_xs()
.font_semibold()
.text_color(cx.theme().muted_foreground)
.child(text.to_string())
.into_any_element()
}
@@ -18,7 +18,6 @@ use gpui_component::{
use nostr::prelude::EventId;
use signed_core::{RepoStatus, activity_subject};
use signed_state::{ProfileStore, RepoStore};
use signed_ui::image_cache::{MAX_IMAGES, image_cache};
use signed_ui::{SegmentButton, UserAvatar, placeholder, status_badge};
use utils::relative_time;
@@ -363,7 +362,7 @@ impl Render for IssuesView {
v_flex()
.size_full()
.image_cache(image_cache("issues", MAX_IMAGES))
.image_cache(gpui::retain_all("issues"))
.child(self.render_header(cx))
.child(
v_flex()
@@ -33,7 +33,6 @@ use signed_state::{
Backend, CheckoutStatus, CheckoutsStore, GitStore, LocalReposStore, ProfileStore,
RepoListStore, RepoStore, pr_proposes_checkout,
};
use signed_ui::image_cache::{MAX_IMAGES, image_cache};
use signed_ui::{DropdownButton, PixelAvatar, UserAvatar, copy_row};
mod about;
@@ -2345,7 +2344,7 @@ impl Render for RepoDetailView {
.or_else(|| self.render_push_banner(cx));
v_flex()
.image_cache(image_cache("repo", MAX_IMAGES))
.image_cache(gpui::retain_all("repo"))
.id("repo")
.size_full()
.child(self.render_header(cx))
@@ -7,38 +7,30 @@ use dock::{BasePanel, DockArea, DockPlacement, Panel, PanelEvent, panel_handle};
use gpui::prelude::*;
use gpui::{
AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, Pixels, Render,
ScrollStrategy, SharedString, Size, Task, WeakEntity, Window, div, px, relative, size,
SharedString, Size, Task, WeakEntity, Window, div, px, relative, size,
};
use gpui_component::button::{Button, ButtonVariants};
use gpui_component::clipboard::Clipboard;
use gpui_component::dialog::{DialogDescription, DialogFooter, DialogHeader, DialogTitle};
use gpui_component::form::{field, v_form};
use gpui_component::input::{Textarea, TextareaState};
use gpui_component::list::ListItem;
use gpui_component::scroll::{ScrollableElement, Scrollbar};
use gpui_component::spinner::Spinner;
use gpui_component::tab::{Tab, TabBar};
use gpui_component::tag::Tag;
use gpui_component::tree::{TreeEntry, TreeState, tree};
use gpui_component::{
ActiveTheme, Icon, Sizable, StyledExt, VirtualListScrollHandle, WindowExt, h_flex, v_flex,
ActiveTheme, Sizable, StyledExt, VirtualListScrollHandle, WindowExt, h_flex, v_flex,
v_virtual_list,
};
use nostr::prelude::{Event, EventId, Kind, Nip34Tag, PublicKey};
use nostr::prelude::{Event, EventId, Kind, Nip34Tag};
use signed_core::{activity_subject, pull_request_patch};
use signed_git::{CommitDiff, FileCommit, FileDiff, patch_commits, patch_diffs};
use signed_git::{FileCommit, patch_commits, patch_diffs};
use signed_state::{Backend, GitStore, ProfileStore, RepoStore};
use signed_ui::image_cache::{MAX_IMAGES, image_cache};
use signed_ui::{UserAvatar, placeholder, status_badge, tree_row};
use signed_ui::{UserAvatar, placeholder, status_badge};
use utils::{relative_time, relative_time_secs};
use super::diff::CommitDiffView;
use super::helpers::{
DIFF_ROW_HEIGHT, DiffRow, build_tree_items, diff_rows, find_item, render_diff_row, tree_items,
};
/// Width of the changed-files column.
const TREE_WIDTH: f32 = 260.;
use super::diff::{CommitDiffView, DiffPane};
use super::helpers::{comment_form, comments_section, pr_roots, sidebar_section};
/// Height of one commit row in the commits tab's virtual list.
const ROW_HEIGHT: f32 = 37.;
@@ -65,23 +57,13 @@ pub struct PullRequestDetailView {
current_commit: Option<SharedString>,
/// Commits of the patch series, in patch order, oldest first.
commits: Vec<FileCommit>,
/// Parsed file changes of the patch, `None` while loading or on failure.
diff: Option<CommitDiff>,
/// The patch is being parsed on a background task.
loading: bool,
error: Option<SharedString>,
/// Active header tab, 0 = Discussion, 1 = Files, 2 = Commits.
active_tab: usize,
/// Changed-files explorer state.
tree_state: Entity<TreeState>,
/// Path of the file whose diff is shown in the detail column.
selected_file: Option<SharedString>,
/// Rows of the selected file's diff, hunk headers and lines.
rows: Vec<DiffRow>,
/// Per-row heights of [`Self::rows`].
item_sizes: Rc<Vec<Size<Pixels>>>,
/// Virtual list state of the diff rows.
scroll_handle: VirtualListScrollHandle,
/// Changed-files explorer and per-file diff, like the commit and compare views.
pane: Entity<DiffPane>,
/// Per-row heights of the commits tab's virtual list, built when the patch series loads.
commit_item_sizes: Rc<Vec<Size<Pixels>>>,
/// Virtual list state of the commits tab.
@@ -101,7 +83,7 @@ impl PullRequestDetailView {
cx: &mut Context<Self>,
) -> Self {
let repo_name = store.read(cx).name();
let tree_state = cx.new(|cx| TreeState::new(cx));
let pane = cx.new(DiffPane::new);
let comment_input =
cx.new(|cx| TextareaState::new(window, cx).placeholder("Leave a comment..."));
@@ -122,15 +104,10 @@ impl PullRequestDetailView {
description: SharedString::default(),
current_commit: None,
commits: Vec::new(),
diff: None,
loading: true,
error: None,
active_tab: 0,
tree_state,
selected_file: None,
rows: Vec::new(),
item_sizes: Rc::new(Vec::new()),
scroll_handle: VirtualListScrollHandle::new(),
pane,
commit_item_sizes: Rc::new(Vec::new()),
commit_scroll_handle: VirtualListScrollHandle::new(),
contents: HashMap::new(),
@@ -270,27 +247,7 @@ impl PullRequestDetailView {
match diff {
Ok(diff) => {
let mut paths: Vec<PathBuf> = diff
.files
.iter()
.map(|file| PathBuf::from(&file.path))
.collect();
paths.sort();
let items = tree_items(build_tree_items(&paths), true);
let first = diff
.files
.first()
.map(|file| SharedString::from(file.path.as_str()));
this.tree_state.update(cx, |state, cx| {
state.set_items(items.clone(), cx);
let item = find_item(&items, first.as_deref());
state.set_selected_item(item, cx);
});
this.selected_file = first.clone();
this.diff = Some(diff);
if let Some(path) = first {
this.set_diff_rows(path.as_ref());
}
this.pane.update(cx, |pane, cx| pane.set_diff(diff, cx));
}
Err(error) => {
this.error = Some(error.to_string().into());
@@ -307,26 +264,6 @@ impl PullRequestDetailView {
self.tasks.push(task);
}
/// Show the diff of the file at `path`, selected in the tree.
fn select_file(&mut self, path: &str, cx: &mut Context<Self>) {
self.selected_file = Some(path.into());
self.set_diff_rows(path);
cx.notify();
}
/// Rebuild the virtual list state for the file at `path` and scroll back to the top.
fn set_diff_rows(&mut self, path: &str) {
let Some(diff) = self.diff.as_ref() else {
return;
};
let Some(file) = diff.files.iter().find(|file| file.path == path) else {
return;
};
self.rows = diff_rows(file);
self.item_sizes = Rc::new(vec![size(px(0.), px(DIFF_ROW_HEIGHT)); self.rows.len()]);
self.scroll_handle.scroll_to_item(0, ScrollStrategy::Top);
}
/// Open the diff of `commit_id` in the bottom dock of the area.
fn open_commit_diff(
&mut self,
@@ -354,206 +291,9 @@ impl PullRequestDetailView {
});
}
/// One row of the changed-files tree, icon and name, indented by depth.
fn render_tree_item(
ix: usize,
entry: &TreeEntry,
selected: bool,
view: &WeakEntity<Self>,
) -> ListItem {
let view = view.clone();
let id = entry.item().id.clone();
tree_row(ix, entry, selected, move |_window, cx| {
if let Some(view) = view.upgrade() {
view.update(cx, |this, cx| this.select_file(&id, cx));
}
})
}
fn render_tree_column(&self, cx: &mut Context<Self>) -> AnyElement {
let tree_state = self.tree_state.clone();
let view = cx.entity().downgrade();
v_flex()
.h_full()
.w(px(TREE_WIDTH))
.flex_none()
.border_r_1()
.border_color(cx.theme().border)
.child(
div()
.flex_1()
.min_h_0()
.when(self.diff.is_some(), |this| {
this.child(
tree(&tree_state, move |ix, entry, selected, _window, _cx| {
Self::render_tree_item(ix, entry, selected, &view)
})
.p_2(),
)
})
.when(self.diff.is_none() && !self.loading, |this| {
this.child(placeholder("Failed to load diff", cx))
}),
)
.into_any_element()
}
fn render_detail_column(&self, cx: &mut Context<Self>) -> AnyElement {
if self.loading {
return v_flex()
.size_full()
.items_center()
.justify_center()
.child(Spinner::new().small())
.into_any_element();
}
if let Some(error) = self.error.clone() {
return placeholder(&error, cx);
}
let Some(diff) = self.diff.as_ref() else {
return placeholder("Failed to load diff", cx);
};
let Some(path) = self.selected_file.clone() else {
return if diff.files.is_empty() {
placeholder("No files changed in this pull request", cx)
} else {
placeholder("Select a file", cx)
};
};
let Some(file) = diff.files.iter().find(|file| file.path == path.as_ref()) else {
return placeholder("File not found", cx);
};
self.render_file_diff(file, cx.entity(), cx)
}
fn render_file_diff(&self, file: &FileDiff, view: Entity<Self>, cx: &App) -> AnyElement {
let status_label = match file.status {
signed_git::DiffStatus::Added => "A",
signed_git::DiffStatus::Modified => "M",
signed_git::DiffStatus::Deleted => "D",
signed_git::DiffStatus::Renamed => "R",
signed_git::DiffStatus::Copied => "C",
};
let status_color = match file.status {
signed_git::DiffStatus::Added => cx.theme().success,
signed_git::DiffStatus::Modified => cx.theme().info,
signed_git::DiffStatus::Deleted => cx.theme().danger,
signed_git::DiffStatus::Renamed | signed_git::DiffStatus::Copied => {
cx.theme().muted_foreground
}
};
let title = match &file.old_path {
Some(old) => format!("{old}{}", file.path),
None => file.path.clone(),
};
let body: AnyElement = if file.binary {
placeholder("Diff not available", cx)
} else if file.hunks.is_empty() {
placeholder("No content changes", cx)
} else {
let sizes = self.item_sizes.clone();
let scroll_handle = self.scroll_handle.clone();
v_flex()
.size_full()
.relative()
.child(
v_virtual_list(
view,
"pr-diff-rows",
sizes,
move |this, range, _window, cx| {
let Some(diff) = this.diff.as_ref() else {
return Vec::new();
};
let Some(path) = this.selected_file.as_deref() else {
return Vec::new();
};
let Some(file) = diff.files.iter().find(|file| file.path == path)
else {
return Vec::new();
};
range
.map(|ix| render_diff_row(&file.hunks, this.rows[ix], cx))
.collect()
},
)
.track_scroll(&scroll_handle)
.size_full(),
)
.child(
div()
.absolute()
.top_0()
.left_0()
.right_0()
.bottom_0()
.child(Scrollbar::vertical(&scroll_handle)),
)
.into_any_element()
};
v_flex()
.flex_1()
.min_w_0()
.h_full()
.child(
h_flex()
.px_3()
.h_9()
.gap_2()
.items_center()
.child(
div()
.text_xs()
.font_semibold()
.text_color(status_color)
.child(status_label),
)
.child(
div()
.flex_1()
.min_w_0()
.text_xs()
.font_semibold()
.text_ellipsis()
.whitespace_nowrap()
.child(title),
)
.when(!file.binary, |this| {
this.child(
h_flex()
.gap_2()
.text_xs()
.child(
div()
.text_color(cx.theme().success)
.child(format!("+{}", file.insertions)),
)
.child(
div()
.text_color(cx.theme().danger)
.child(format!("-{}", file.deletions)),
),
)
}),
)
.child(div().id("pr-diff-body").flex_1().min_h_0().child(body))
.into_any_element()
}
fn render_tabs(&self, cx: &mut Context<Self>) -> AnyElement {
let active = self.active_tab;
let files_count = self.diff.as_ref().map(|diff| diff.files.len());
let files_count = self.pane.read(cx).diff().map(|diff| diff.files.len());
let commits_count = if self.commits.is_empty() {
None
} else {
@@ -670,104 +410,48 @@ impl PullRequestDetailView {
this.child(div().text_sm().child(self.description.clone()))
}),
)
.child(self.render_comments(&root_id, cx))
.child(self.render_form(&root_id, cx)),
.child(comments_section(
&self.store,
root_id,
&mut self.contents,
cx,
))
.child(comment_form(
&self.store,
root_id,
pr_roots,
&self.comment_input,
"pr-comment",
cx,
)),
),
)
.child(self.render_sidebar(cx))
.into_any_element()
}
/// Right sidebar with participants and labels, like the issue panel.
fn render_sidebar(&self, cx: &mut Context<Self>) -> AnyElement {
let profile_store = ProfileStore::global(cx);
let store = self.store.read(cx);
let Some(root) = store
.pull_requests
.iter()
.find(|pr| pr.id == self.pr_id && pr.kind == Kind::GitPullRequest)
else {
// `render_discussion` already bails out when the PR is missing.
return div().into_any_element();
};
// Participants, the PR author plus everyone who commented.
let mut participants: Vec<PublicKey> = vec![root.pubkey];
participants.extend(store.comments_of(&root.id).map(|comment| comment.pubkey));
participants.sort_by_key(PublicKey::to_hex);
participants.dedup();
// PR labels are NIP-34 `t` hashtag tags on the event.
let labels: Vec<String> = root.tags.hashtags().map(|tag| tag.to_string()).collect();
v_flex()
.w(px(240.))
.h_full()
.flex_none()
.px_4()
.gap_4()
.border_l(px(1.))
.border_color(cx.theme().sidebar_border)
.child(
v_flex()
.mt_4()
.gap_2()
.child(sidebar_title("Participants", cx))
.children(participants.iter().map(|pubkey| {
let profile = profile_store.read(cx).get(pubkey);
let name = profile.name();
let picture = profile.picture();
h_flex()
.gap_1()
.items_center()
.child(UserAvatar::new(name.clone()).picture(picture))
.child(div().text_sm().truncate().text_ellipsis().child(name))
.into_any_element()
})),
)
.child(
v_flex()
.gap_2()
.child(sidebar_title("Labels", cx))
.map(|this| {
if labels.is_empty() {
this.child(
div()
.text_sm()
.text_color(cx.theme().muted_foreground)
.child("None yet."),
)
} else {
this.child(h_flex().gap_1().children({
let mut items = vec![];
for label in labels.iter() {
items.push(
Tag::secondary()
.outline()
.xsmall()
.child(SharedString::from(label)),
);
}
items
}))
}
}),
)
.child(sidebar_section(&self.store, root_id, pr_roots, true, cx))
.into_any_element()
}
fn render_files_tab(&self, cx: &mut Context<Self>) -> AnyElement {
if self.loading {
return v_flex()
.flex_1()
.w_full()
.min_h_0()
.items_center()
.justify_center()
.child(Spinner::new().small())
.into_any_element();
}
if let Some(error) = self.error.clone() {
return placeholder(&error, cx);
}
h_flex()
.flex_1()
.w_full()
.min_h_0()
.overflow_hidden()
.child(self.render_tree_column(cx))
.child(self.render_detail_column(cx))
.child(self.pane.clone())
.into_any_element()
}
@@ -876,114 +560,6 @@ impl PullRequestDetailView {
.into_any_element()
}
/// One comment card, same design as the issue panel.
fn render_comments(&mut self, id: &EventId, cx: &mut Context<Self>) -> AnyElement {
let store = self.store.read(cx);
let comments: Vec<&Event> = store.comments_of(id).collect();
let title = SharedString::from(format!("Discussions {}", comments.len()));
v_flex()
.gap_4()
.child(div().text_xs().font_semibold().child(title))
.children(comments.iter().map(|comment| {
let profile = ProfileStore::global(cx).read(cx).get(&comment.pubkey);
let author = profile.name();
let picture = profile.picture();
let age = relative_time(comment.created_at);
// Comment bodies become shared strings once per comment, not per render.
let content = self
.contents
.entry(comment.id)
.or_insert_with(|| SharedString::from(comment.content.clone()))
.clone();
v_flex()
.gap_1()
.p_3()
.border_1()
.border_color(cx.theme().border)
.rounded(cx.theme().radius)
.child(
h_flex()
.gap_2()
.text_sm()
.child(
h_flex()
.gap_1()
.child(UserAvatar::new(author.clone()).picture(picture))
.child(author),
)
.child(
div()
.text_color(cx.theme().muted_foreground)
.child("commented"),
)
.child(
div()
.text_color(cx.theme().muted_foreground)
.child(SharedString::from(age)),
),
)
.child(div().text_sm().child(content))
}))
.into_any_element()
}
fn render_form(&mut self, id: &EventId, cx: &mut Context<Self>) -> AnyElement {
let comment_input = self.comment_input.clone();
let store = self.store.clone();
let id = id.to_owned();
v_flex()
.gap_2()
.child(
Textarea::new(&self.comment_input)
.h_24()
.text_color(cx.theme().muted_foreground)
.bg(cx.theme().muted),
)
.child(
h_flex()
.justify_between()
.child(
h_flex()
.gap_1()
.text_xs()
.text_color(cx.theme().muted_foreground)
.child(Icon::new(CustomIconName::Markdown).small())
.child("Markdown is supported"),
)
.child(
Button::new("pr-comment")
.primary()
.label("Comment")
.tooltip("Post comment")
.on_click(move |_event, window, cx| {
let content = comment_input.read(cx).value().trim().to_string();
if content.is_empty() {
return;
}
let Some(root) = store
.read(cx)
.pull_requests
.iter()
.find(|pr| pr.id == id)
.cloned()
else {
return;
};
store.update(cx, |store, cx| {
store.comment(&root, content, cx);
});
comment_input.update(cx, |input, cx| {
input.set_value("", window, cx);
});
}),
),
)
.into_any_element()
}
/// Always-visible header with a status badge and title, like the issue panel.
fn render_header(&self, cx: &mut Context<Self>) -> AnyElement {
let current_commit = self.current_commit.clone();
@@ -1147,20 +723,9 @@ fn open_update_pull_request_dialog(
});
}
/// One sidebar section title.
fn sidebar_title(text: &str, cx: &App) -> AnyElement {
div()
.text_xs()
.font_semibold()
.text_color(cx.theme().muted_foreground)
.child(text.to_string())
.into_any_element()
}
/// The `c` tag of a PR event, the tip of the proposed branch, as hex.
fn current_commit_of(event: &Event) -> Option<String> {
event
.tags
/// The `c` tag of a PR event, the commit the proposal points at.
fn current_commit_of(root: &Event) -> Option<String> {
root.tags
.iter()
.find_map(|tag| match Nip34Tag::parse(tag.as_slice()) {
Ok(Nip34Tag::CurrentCommit(commit)) => Some(commit.to_string()),
@@ -1263,7 +828,7 @@ impl Focusable for PullRequestDetailView {
impl Render for PullRequestDetailView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
v_flex()
.image_cache(image_cache("pull-request-detail", MAX_IMAGES))
.image_cache(gpui::retain_all("pull-request-detail"))
.id("pull-request-detail")
.size_full()
.min_h_0()
@@ -16,7 +16,6 @@ use gpui_component::{
use nostr::prelude::{EventId, Kind};
use signed_core::{RepoStatus, activity_subject};
use signed_state::{ProfileStore, RepoStore};
use signed_ui::image_cache::{MAX_IMAGES, image_cache};
use signed_ui::{DropdownButton, SegmentButton, UserAvatar, placeholder, status_badge};
use utils::relative_time;
@@ -387,7 +386,7 @@ impl Render for PullRequestsView {
v_flex()
.size_full()
.image_cache(image_cache("pull-requests", MAX_IMAGES))
.image_cache(gpui::retain_all("pull-requests"))
.on_action(cx.listener(|this, action: &RepoAction, window, cx| {
if action == &RepoAction::SendPatch {
open_send_patch_panel(this.dock_area.clone(), this.store.clone(), window, cx);
+1 -2
View File
@@ -15,7 +15,6 @@ use gpui_component::{
};
use signed_core::Announcement;
use signed_state::{ProfileStore, RepoListStore, Timestamp};
use signed_ui::image_cache::{MAX_IMAGES, image_cache};
use signed_ui::{SegmentButton, UserAvatar};
use utils::relative_time;
@@ -397,7 +396,7 @@ impl Render for RepoListView {
v_flex()
.relative()
.image_cache(image_cache("repos", MAX_IMAGES))
.image_cache(gpui::retain_all("repos"))
.size_full()
.child(self.render_header(count, cx))
.when(!has_repos, |this| {
@@ -2,26 +2,23 @@ use std::path::PathBuf;
use dock::DockArea;
use gpui::prelude::*;
use gpui::{App, Entity, PathPromptOptions, SharedString, WeakEntity, Window, div, px};
use gpui::{App, Entity, PathPromptOptions, WeakEntity, Window, div, px};
use gpui_base::input::TextareaState;
use gpui_component::button::{Button, ButtonVariants};
use gpui_component::dialog::{DialogDescription, DialogFooter, DialogHeader, DialogTitle};
use gpui_component::form::{field, v_form};
use gpui_component::input::{Input, InputState, Textarea};
use gpui_component::{ActiveTheme, Disableable, IconName, WindowExt, h_flex};
use gpui_component::{Disableable, IconName, WindowExt, h_flex};
use settings::SettingsStore;
use signed_core::Announcement;
use signed_state::{Backend, CheckoutsStore};
use super::super::open_repo_panel;
use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers};
use crate::views::dialog_state::{DialogProgress, error_row};
/// Shared state for the Create Repository dialog, so async results can be rendered.
#[derive(Default)]
pub struct CreateRepoState {
pub busy: bool,
pub error: Option<SharedString>,
}
pub type CreateRepoState = DialogProgress;
/// Open the Create Repository dialog.
pub fn open(dock_area: WeakEntity<DockArea>, window: &mut Window, cx: &mut App) {
@@ -117,9 +114,7 @@ pub fn open(dock_area: WeakEntity<DockArea>, window: &mut Window, cx: &mut App)
)
.child(grasp_servers_field(&grasp_state, &relay_input, cx)),
)
.children(error.map(|message| {
div().text_sm().text_color(cx.theme().danger).child(message)
}))
.children(error_row(&error, cx))
.child(
DialogFooter::new().justify_end().child(
Button::new("create")
@@ -211,22 +206,15 @@ fn create_repository(
let servers = grasp_state.read(cx).grasp_servers.clone();
if name.is_empty() {
state.update(cx, |state, _| {
state.error = Some("Repository name is required".into());
});
state.update(cx, |state, _| state.fail("Repository name is required"));
return;
}
if servers.is_empty() {
state.update(cx, |state, _| {
state.error = Some("Add at least one grasp server".into());
});
state.update(cx, |state, _| state.fail("Add at least one grasp server"));
return;
}
state.update(cx, |state, _| {
state.busy = true;
state.error = None;
});
state.update(cx, |state, _| state.begin());
let backend = Backend::global(cx);
let task = backend.update(cx, |backend, cx| {
@@ -254,10 +242,7 @@ fn create_repository(
}
Err(e) => {
cx.update_window(handle, |_, _window, cx| {
state.update(cx, |state, _| {
state.busy = false;
state.error = Some(e.to_string().into());
});
state.update(cx, |state, _| state.fail(e.to_string()));
})
.ok();
}
@@ -6,7 +6,6 @@ use gpui_component::input::{Input, InputState};
use gpui_component::{ActiveTheme, IconName, Sizable, h_flex, v_flex};
use nostr::prelude::*;
use settings::{DEFAULT_GRASP_SERVERS, GraspServersSettings};
use signed_core::filters;
use signed_state::Backend;
/// State of the grasp-server section of a publish dialog, so async results can be rendered.
@@ -238,30 +237,7 @@ pub fn load_user_grasp_servers(
let handle = window.window_handle();
cx.spawn(async move |cx| {
let result: anyhow::Result<Vec<RelayUrl>> = async {
let mut events: Vec<Event> = client
.database()
.query(filters::grasp_list(user))
.await?
.into_iter()
.collect();
events.sort_by_key(|event| event.created_at);
Ok(events
.into_iter()
.last()
.map(|event| {
event
.tags
.iter()
.filter(|tag| tag.kind() == "g")
.filter_map(|tag| tag.content())
.filter_map(|url| RelayUrl::parse(url).ok())
.collect()
})
.unwrap_or_default())
}
.await;
let result = signed_state::user_grasp_list_servers(client, user).await;
let _ = cx.update_window(handle, |_, _window, cx| {
state.update(cx, |state, _| {
+1 -2
View File
@@ -18,7 +18,6 @@ use signed_core::{Announcement, identifier_from_name};
use signed_state::{
Backend, BackendEvent, CheckoutsStore, LocalReposStore, Profile, ProfileStore, RepoListStore,
};
use signed_ui::image_cache::{MAX_IMAGES, image_cache};
use signed_ui::{CountBadge, NavItem, PixelAvatar, UserAvatar, title_bar_drag_handlers};
use super::{RepoDetailView, RepoListView, open_repo_panel};
@@ -559,7 +558,7 @@ impl Render for SidebarPanel {
v_flex()
.size_full()
.justify_between()
.image_cache(image_cache("sidebar", MAX_IMAGES))
.image_cache(gpui::retain_all("sidebar"))
.bg(cx.theme().sidebar)
.text_color(cx.theme().sidebar_foreground)
.child(
@@ -1,18 +1,16 @@
use gpui::prelude::*;
use gpui::{App, Entity, SharedString, Window, div, px};
use gpui::{App, Entity, Window, px};
use gpui_component::button::{Button, ButtonVariants};
use gpui_component::dialog::{DialogDescription, DialogFooter, DialogHeader, DialogTitle};
use gpui_component::form::{field, v_form};
use gpui_component::input::{Input, InputState};
use gpui_component::{ActiveTheme, Disableable, WindowExt};
use gpui_component::{Disableable, WindowExt};
use signed_state::Backend;
use crate::views::dialog_state::{DialogProgress, error_row};
/// Shared state for the Onboarding dialog, so async results can be rendered.
#[derive(Default)]
pub struct OnboardingState {
pub busy: bool,
pub error: Option<SharedString>,
}
pub type OnboardingState = DialogProgress;
/// Open the Onboarding dialog for creating a new identity.
pub fn open(
@@ -62,9 +60,7 @@ pub fn open(
)
.child(field().required(true).child(Input::new(&repass_input))),
)
.children(error.map(|message| {
div().text_sm().text_color(cx.theme().danger).child(message)
}))
.children(error_row(&error, cx))
.child(
DialogFooter::new().justify_end().child(
Button::new("continue")
@@ -87,17 +83,12 @@ pub fn open(
if pass != repass {
state.update(cx, |state, _| {
state.busy = false;
state.error =
Some("Passphrases do not match".into());
state.fail("Passphrases do not match");
});
return;
}
state.update(cx, |state, _| {
state.busy = true;
state.error = None;
});
state.update(cx, |state, _| state.begin());
let task = backend.update(cx, |backend, cx| {
backend.create_identity(&name, &pass, cx)
@@ -115,8 +106,7 @@ pub fn open(
Err(e) => {
cx.update_window(handle, |_, _window, cx| {
state.update(cx, |state, _| {
state.busy = false;
state.error = Some(e.to_string().into());
state.fail(e.to_string());
});
})
.ok();
@@ -1,18 +1,20 @@
use assets::CustomIconName;
use gpui::prelude::*;
use gpui::{AnyWindowHandle, App, Entity, SharedString, Subscription, Window, div};
use gpui::{AnyWindowHandle, App, Entity, Subscription, Window};
use gpui_component::button::{Button, ButtonVariants};
use gpui_component::dialog::{DialogDescription, DialogFooter, DialogHeader, DialogTitle};
use gpui_component::form::{field, v_form};
use gpui_component::input::{Input, InputEvent, InputState};
use gpui_component::{ActiveTheme, Disableable, WindowExt};
use gpui_component::{Disableable, WindowExt};
use signed_state::Backend;
use crate::views::dialog_state::{DialogProgress, error_row};
/// Shared state for the passphrase dialog, so async results can be rendered.
#[derive(Default)]
pub struct PassphraseState {
pub busy: bool,
pub error: Option<SharedString>,
/// Progress of the unlock flow.
pub progress: DialogProgress,
/// Keeps the Enter-to-submit subscription alive while the dialog is open.
_enter_subscription: Option<Subscription>,
}
@@ -50,8 +52,8 @@ pub fn open(window: &mut Window, cx: &mut App) {
.overlay_closable(false)
.keyboard(false)
.content(move |content, _window, cx| {
let busy = state.read(cx).busy;
let error = state.read(cx).error.clone();
let busy = state.read(cx).progress.busy;
let error = state.read(cx).progress.error.clone();
content
.child(
@@ -70,9 +72,7 @@ pub fn open(window: &mut Window, cx: &mut App) {
.child(Input::new(&pass_input)),
),
)
.children(error.map(|message| {
div().text_sm().text_color(cx.theme().danger).child(message)
}))
.children(error_row(&error, cx))
.child(
DialogFooter::new().justify_end().child(
Button::new("unlock")
@@ -107,15 +107,12 @@ fn unlock(
if pass.is_empty() {
state.update(cx, |state, _| {
state.error = Some("Passphrase must not be empty".into());
state.progress.fail("Passphrase must not be empty");
});
return;
}
state.update(cx, |state, _| {
state.busy = true;
state.error = None;
});
state.update(cx, |state, _| state.progress.begin());
let task = backend.update(cx, |backend, cx| backend.restore_with_passphrase(&pass, cx));
let handle = *handle;
@@ -130,10 +127,7 @@ fn unlock(
}
Err(e) => {
cx.update_window(handle, |_this, _window, cx| {
state.update(cx, |state, _| {
state.busy = false;
state.error = Some(e.to_string().into());
});
state.update(cx, |state, _| state.progress.fail(e.to_string()));
})
.ok();
}