diff --git a/crates/radicle-tauri/capabilities/default.json b/crates/radicle-tauri/capabilities/default.json index e7b13eb96..c00a2be8d 100644 --- a/crates/radicle-tauri/capabilities/default.json +++ b/crates/radicle-tauri/capabilities/default.json @@ -4,19 +4,20 @@ "description": "Capability for the main window", "windows": ["main"], "permissions": [ - "core:path:default", - "core:event:default", - "core:window:default", - "core:webview:default", - "core:app:default", - "core:image:default", - "core:resources:default", - "core:menu:default", - "core:tray:default", - "shell:allow-open", - "clipboard-manager:default", "clipboard-manager:allow-write-text", + "clipboard-manager:default", + "core:app:default", + "core:event:default", + "core:image:default", + "core:menu:default", + "core:path:default", + "core:resources:default", + "core:tray:default", + "core:webview:default", + "core:window:allow-set-badge-count", + "core:window:default", + "dialog:default", "log:default", - "dialog:default" + "shell:allow-open" ] } diff --git a/crates/radicle-tauri/src/commands/inbox.rs b/crates/radicle-tauri/src/commands/inbox.rs index 44b817398..d3aea9d63 100644 --- a/crates/radicle-tauri/src/commands/inbox.rs +++ b/crates/radicle-tauri/src/commands/inbox.rs @@ -1,12 +1,9 @@ -use std::collections::BTreeMap; - use radicle::identity; use radicle::issue::cache::Issues; use radicle::node; use radicle::patch::cache::Patches; use radicle::storage::{ReadRepository, ReadStorage}; -use radicle_types::cobs::PaginatedQuery; use radicle_types::domain::inbox::models::notification::{self, RepoGroupByItem}; use radicle_types::domain::inbox::service::Service; use radicle_types::domain::inbox::traits::InboxService; @@ -19,145 +16,181 @@ pub fn list_notifications( ctx: tauri::State, sqlite_service: tauri::State>, params: notification::RepoGroupParams, -) -> Result, Error> { +) -> Result { let profile = &ctx.profile; let aliases = profile.aliases(); - let cursor = params.skip.unwrap_or(0); - let take = params.take.unwrap_or(20); + let repos_with_groups = sqlite_service.repo_group(params.clone())?; - let all = sqlite_service.repo_group(params.clone())?; - let more = cursor + take < all.len(); - let repo = profile.storage.repository(params.repo)?; - let patches = profile.patches(&repo)?; - let issues = profile.issues(&repo)?; + let mut repo_counts = std::collections::HashMap::new(); + for (repo_id, count) in (sqlite_service.counts_by_repo()?).flatten() { + repo_counts.insert(repo_id, count); + } - let content = all - .into_iter() - .skip(cursor) - .take(take) - .map(|(qualified, n)| { - let items = n - .into_iter() - .filter_map(|s| { - let update: notification::RefUpdate = - (qualified.clone().into_refstring(), s.new, s.old).into(); - let update: radicle::storage::RefUpdate = update.into(); - let kind = - node::notifications::NotificationKind::try_from(qualified.clone()).ok()?; + let take = if params.all.unwrap_or(false) { + usize::MAX + } else { + params.take.unwrap_or(20) + }; - match kind { - node::notifications::NotificationKind::Cob { ref typed_id } => { - if typed_id.is_patch() { - let actions = notification::actions( - typed_id.type_name.clone(), - typed_id.id, - update.old(), - update.new(), - &repo, - &aliases, - ) - .unwrap_or_default(); + let mut grouped_repos = std::collections::HashMap::new(); + for (repo_id, group) in repos_with_groups { + grouped_repos + .entry(repo_id) + .or_insert_with(Vec::new) + .extend(group); + } - match patches.get(&typed_id.id) { - Ok(Some(p)) => Some(notification::NotificationItem::Patch( - notification::Patch { - row_id: s.row_id, - id: typed_id.id, - update: update.into(), - timestamp: s.timestamp, - title: p.title().to_string(), - status: (p.state().clone()).into(), - actions, - }, - )), - Ok(None) => { - log::error!("No patch found"); - None + let mut result = Vec::new(); + + for (repo_id, all) in grouped_repos { + let repo = match profile.storage.repository(repo_id) { + Ok(r) => r, + Err(e) => { + log::error!("Failed to open repository {}: {}", repo_id, e); + continue; + } + }; + + let name = match repo.identity_doc() { + Ok(identity::DocAt { doc, .. }) => match doc.project() { + Ok(project) => project.name().to_string(), + Err(_) => format!("Unknown project in {}", repo_id), + }, + Err(_) => format!("Unknown project in {}", repo_id), + }; + + let patches = match profile.patches(&repo) { + Ok(p) => p, + Err(e) => { + log::error!("Failed to get patches for {}: {}", repo_id, e); + continue; + } + }; + let issues = match profile.issues(&repo) { + Ok(i) => i, + Err(e) => { + log::error!("Failed to get issues for {}: {}", repo_id, e); + continue; + } + }; + + let content = all + .into_iter() + .take(take) + .map(|(qualified, n)| { + let items = n + .into_iter() + .filter_map(|s| { + let update: notification::RefUpdate = + (qualified.clone().into_refstring(), s.new, s.old).into(); + let update: radicle::storage::RefUpdate = update.into(); + let kind = + node::notifications::NotificationKind::try_from(qualified.clone()) + .ok()?; + + match kind { + node::notifications::NotificationKind::Cob { ref typed_id } => { + if typed_id.is_patch() { + let actions = notification::actions( + typed_id.type_name.clone(), + typed_id.id, + update.old(), + update.new(), + &repo, + &aliases, + ) + .unwrap_or_default(); + + match patches.get(&typed_id.id) { + Ok(Some(p)) => Some(notification::NotificationItem::Patch( + notification::Patch { + row_id: s.row_id, + id: typed_id.id, + update: update.into(), + timestamp: s.timestamp, + title: p.title().to_string(), + status: (p.state().clone()).into(), + actions, + repo_id: Some(repo_id), + }, + )), + Ok(None) => { + log::error!("No patch found"); + None + } + Err(e) => { + log::error!("{}", e); + None + } } - Err(e) => { - log::error!("{}", e); - None + } else if typed_id.is_issue() { + let actions = notification::actions( + typed_id.type_name.clone(), + typed_id.id, + update.old(), + update.new(), + &repo, + &aliases, + ) + .unwrap_or_default(); + + match issues.get(&typed_id.id) { + Ok(Some(i)) => Some(notification::NotificationItem::Issue( + notification::Issue { + row_id: s.row_id, + id: typed_id.id, + update: update.into(), + timestamp: s.timestamp, + title: i.title().to_string(), + status: (*i.state()).into(), + actions, + repo_id: Some(repo_id), + }, + )), + Ok(None) => { + log::error!("No issue found"); + None + } + Err(e) => { + log::error!("{}", e); + None + } } + } else { + None } - } else if typed_id.is_issue() { - let actions = notification::actions( - typed_id.type_name.clone(), - typed_id.id, - update.old(), - update.new(), - &repo, - &aliases, - ) - .unwrap_or_default(); - - match issues.get(&typed_id.id) { - Ok(Some(i)) => Some(notification::NotificationItem::Issue( - notification::Issue { - row_id: s.row_id, - id: typed_id.id, - update: update.into(), - timestamp: s.timestamp, - title: i.title().to_string(), - status: (*i.state()).into(), - actions, - }, - )), - Ok(None) => { - log::error!("No issue found"); - None - } - Err(e) => { - log::error!("{}", e); - None - } - } - } else { - None } + _ => None, } - _ => None, - } - }) - .collect::>(); + }) + .collect::>(); - (qualified, items) - }) - .filter(|(_, v)| !v.is_empty()) - .collect::(); + items + }) + .filter(|v| !v.is_empty()) + .collect::(); - Ok(PaginatedQuery { - cursor, - more, - content, - }) + if !content.is_empty() { + let count = repo_counts + .get(&repo_id) + .copied() + .unwrap_or_else(|| content.iter().map(|items| items.len()).sum()); + + result.push(notification::NotificationsByRepo { + rid: repo_id, + name, + notifications: content, + count, + }); + } + } + + Ok(result) } #[tauri::command] -pub fn count_notifications_by_repo( - ctx: tauri::State, - inbox: tauri::State>, -) -> Result, Error> { - let profile = &ctx.profile; - let result = inbox - .counts_by_repo()? - .filter_map(|s| { - let (rid, count) = s.ok()?; - let repo = profile.storage.repository(rid).ok()?; - let identity::DocAt { doc, .. } = repo.identity_doc().ok()?; - let project = doc.project().ok()?; - - Some(( - rid, - notification::NotificationCount { - rid, - name: project.name().to_string(), - count, - }, - )) - }) - .collect::>(); - - Ok(result) +pub fn notification_count(inbox: tauri::State>) -> Result { + inbox.notification_count().map_err(Error::from) } #[tauri::command] diff --git a/crates/radicle-tauri/src/lib.rs b/crates/radicle-tauri/src/lib.rs index 666b19235..0e7198a06 100644 --- a/crates/radicle-tauri/src/lib.rs +++ b/crates/radicle-tauri/src/lib.rs @@ -46,7 +46,7 @@ pub fn run() { cob::save_embed_to_disk, diff::get_diff, inbox::clear_notifications, - inbox::count_notifications_by_repo, + inbox::notification_count, inbox::list_notifications, profile::alias, profile::config, diff --git a/crates/radicle-types/bindings/cob/inbox/Issue.ts b/crates/radicle-types/bindings/cob/inbox/Issue.ts index d76e908d2..279659355 100644 --- a/crates/radicle-types/bindings/cob/inbox/Issue.ts +++ b/crates/radicle-types/bindings/cob/inbox/Issue.ts @@ -12,4 +12,5 @@ export type Issue = { timestamp: number; status: State; actions: Array>; + repoId: string; }; diff --git a/crates/radicle-types/bindings/cob/inbox/NotificationsByRepo.ts b/crates/radicle-types/bindings/cob/inbox/NotificationsByRepo.ts new file mode 100644 index 000000000..582543095 --- /dev/null +++ b/crates/radicle-types/bindings/cob/inbox/NotificationsByRepo.ts @@ -0,0 +1,9 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { NotificationItem } from "./NotificationItem"; + +export type NotificationsByRepo = { + rid: string; + name: string; + notifications: Array>; + count: number; +}; diff --git a/crates/radicle-types/bindings/cob/inbox/Patch.ts b/crates/radicle-types/bindings/cob/inbox/Patch.ts index 599f26af1..b8762b7f8 100644 --- a/crates/radicle-types/bindings/cob/inbox/Patch.ts +++ b/crates/radicle-types/bindings/cob/inbox/Patch.ts @@ -12,4 +12,5 @@ export type Patch = { title: string; status: State; actions: Array>; + repoId: string; }; diff --git a/crates/radicle-types/src/domain/inbox/models/notification.rs b/crates/radicle-types/src/domain/inbox/models/notification.rs index 2cf1d1db6..603b59835 100644 --- a/crates/radicle-types/src/domain/inbox/models/notification.rs +++ b/crates/radicle-types/src/domain/inbox/models/notification.rs @@ -31,10 +31,12 @@ pub struct NotificationRow { pub remote: storage::RemoteId, pub old: Option, pub new: Option, + pub repo: Option, } pub type RepoGroup = Vec<(git::Qualified<'static>, Vec)>; -pub type RepoGroupByItem = Vec<(git::Qualified<'static>, Vec)>; +pub type RepoGroupByItem = Vec>; + pub type CountByRepo = (identity::RepoId, usize); #[derive(Clone, Debug)] @@ -44,9 +46,9 @@ pub struct CountsByRepoParams { #[derive(Clone, Debug, serde::Deserialize)] pub struct RepoGroupParams { - pub repo: identity::RepoId, - pub skip: Option, + pub repos: Option>, pub take: Option, + pub all: Option, } #[derive(Debug, thiserror::Error)] @@ -96,18 +98,21 @@ where Ok(iter.filter_map(|a| a.ok()).collect::>()) } -#[derive(Serialize, TS)] +#[derive(Serialize, Debug, TS)] #[serde(rename_all = "camelCase")] #[ts(export)] #[ts(export_to = "cob/inbox/")] -pub struct NotificationCount { +pub struct NotificationsByRepo { #[ts(as = "String")] pub rid: identity::RepoId, pub name: String, + pub notifications: RepoGroupByItem, #[ts(type = "number")] pub count: usize, } +pub type NotificationsByRepoList = Vec; + #[derive(Debug, Serialize, TS)] #[serde(rename_all = "camelCase")] #[serde(tag = "type")] @@ -132,6 +137,8 @@ pub struct Issue { pub timestamp: localtime::LocalTime, pub status: cobs::issue::State, pub actions: Vec>, + #[ts(as = "String")] + pub repo_id: Option, } #[derive(Debug, Serialize, TS, Deserialize)] @@ -161,6 +168,8 @@ pub struct Patch { pub title: String, pub status: models::patch::State, pub actions: Vec>, + #[ts(as = "String")] + pub repo_id: Option, } /// Type of notification. diff --git a/crates/radicle-types/src/domain/inbox/service.rs b/crates/radicle-types/src/domain/inbox/service.rs index dd0c960d0..0e4a3b01d 100644 --- a/crates/radicle-types/src/domain/inbox/service.rs +++ b/crates/radicle-types/src/domain/inbox/service.rs @@ -1,3 +1,5 @@ +use radicle::identity; + use crate::domain::inbox::models::notification::{ CountByRepo, ListNotificationsError, RepoGroup, RepoGroupParams, }; @@ -33,7 +35,14 @@ where self.inbox.counts_by_repo() } - fn repo_group(&self, params: RepoGroupParams) -> Result { + fn notification_count(&self) -> Result { + self.inbox.notification_count() + } + + fn repo_group( + &self, + params: RepoGroupParams, + ) -> Result, ListNotificationsError> { self.inbox.repo_group(params) } } diff --git a/crates/radicle-types/src/domain/inbox/traits.rs b/crates/radicle-types/src/domain/inbox/traits.rs index 69b24093f..8b25abc66 100644 --- a/crates/radicle-types/src/domain/inbox/traits.rs +++ b/crates/radicle-types/src/domain/inbox/traits.rs @@ -1,3 +1,5 @@ +use radicle::identity; + use crate::domain::inbox::models::notification::{ CountByRepo, ListNotificationsError, RepoGroupParams, }; @@ -12,7 +14,12 @@ pub trait InboxStorage { ListNotificationsError, >; - fn repo_group(&self, params: RepoGroupParams) -> Result; + fn notification_count(&self) -> Result; + + fn repo_group( + &self, + params: RepoGroupParams, + ) -> Result, ListNotificationsError>; } pub trait InboxService { @@ -24,5 +31,11 @@ pub trait InboxService { ListNotificationsError, >; - fn repo_group(&self, params: RepoGroupParams) -> Result; + /// Get the total notification count. + fn notification_count(&self) -> Result; + + fn repo_group( + &self, + params: RepoGroupParams, + ) -> Result, ListNotificationsError>; } diff --git a/crates/radicle-types/src/outbound/sqlite.rs b/crates/radicle-types/src/outbound/sqlite.rs index 0a4d4cd27..080afb9ae 100644 --- a/crates/radicle-types/src/outbound/sqlite.rs +++ b/crates/radicle-types/src/outbound/sqlite.rs @@ -133,12 +133,37 @@ impl InboxStorage for Sqlite { })) } + fn notification_count(&self) -> Result { + let stmt = self.db.prepare( + "SELECT COUNT(DISTINCT substr(ref, 66)) as count + FROM `repository-notifications` + WHERE new NOT NULL AND (ref LIKE '%cobs/xyz.radicle.patch%' OR ref LIKE '%cobs/xyz.radicle.issue%')", + )?; + + match stmt.into_iter().next() { + Some(Ok(row)) => Ok(row.try_read::("count")? as usize), + _ => Ok(0), + } + } + fn repo_group( &self, params: notification::RepoGroupParams, - ) -> Result { - let mut stmt = self.db.prepare( - "SELECT ref, substr(ref, 66) ref_without_namespace, + ) -> Result< + Vec<(identity::RepoId, notification::RepoGroup)>, + notification::ListNotificationsError, + > { + let repos_clause = match ¶ms.repos { + Some(repos) if !repos.is_empty() => { + let placeholders: Vec = + (1..=repos.len()).map(|i| format!("?{}", i)).collect(); + format!("WHERE repo IN ({})", placeholders.join(",")) + } + _ => String::from(""), + }; + + let query = format!( + "SELECT repo, ref, substr(ref, 66) ref_without_namespace, json_group_array( json_object( 'row_id', rowid, @@ -150,22 +175,52 @@ impl InboxStorage for Sqlite { ) as value, MAX(timestamp) AS latest_timestamp FROM 'repository-notifications' - WHERE repo = ? - GROUP BY ref_without_namespace + {} + GROUP BY repo, ref_without_namespace ORDER BY latest_timestamp DESC", - )?; - stmt.bind((1, ¶ms.repo))?; + repos_clause + ); - stmt.into_iter() - .map(|row| { - let row = row?; - let refstr = row.try_read::<&str, _>("ref")?; - let value = row.try_read::<&str, _>("value")?; - let items = serde_json::from_str::>(value)?; - let (_, reference) = git::parse_ref::(refstr)?; + let mut stmt = self.db.prepare(&query)?; - Ok((reference.to_owned(), items)) - }) - .collect::>() + if let Some(repos) = ¶ms.repos { + if !repos.is_empty() { + for (i, repo) in repos.iter().enumerate() { + stmt.bind((i + 1, repo))?; + } + } + } + + let mut result: Vec<(identity::RepoId, notification::RepoGroup)> = Vec::new(); + let mut current_repo: Option = None; + let mut current_group: notification::RepoGroup = Vec::new(); + + for row_result in stmt.into_iter() { + let row = row_result?; + let repo_id = row.try_read::("repo")?; + let refstr = row.try_read::<&str, _>("ref")?; + let value = row.try_read::<&str, _>("value")?; + let items = serde_json::from_str::>(value)?; + let (_, reference) = git::parse_ref::(refstr)?; + + if let Some(current) = current_repo { + if current != repo_id { + result.push((current, std::mem::take(&mut current_group))); + current_repo = Some(repo_id); + } + } else { + current_repo = Some(repo_id); + } + + current_group.push((reference.to_owned(), items)); + } + + if let Some(repo) = current_repo { + if !current_group.is_empty() { + result.push((repo, current_group)); + } + } + + Ok(result) } } diff --git a/crates/test-http-api/src/api.rs b/crates/test-http-api/src/api.rs index 1f7a882fb..e85cef6d8 100644 --- a/crates/test-http-api/src/api.rs +++ b/crates/test-http-api/src/api.rs @@ -17,7 +17,6 @@ use radicle_types::cobs::issue; use radicle_types::cobs::issue::NewIssue; use radicle_types::cobs::CobOptions; use radicle_types::cobs::{self, FromRadicleAction}; -use radicle_types::domain::inbox::models::notification::NotificationCount; use radicle_types::domain::patch::models; use radicle_types::domain::patch::service::Service; use radicle_types::domain::patch::traits::PatchService; @@ -59,10 +58,6 @@ pub fn router(ctx: Context) -> Router { Router::new() .route("/config", post(config_handler)) .route("/authenticate", post(auth_handler)) - .route( - "/count_notifications_by_repo", - post(repo_count_notifications_handler), - ) .route("/repo_count", post(repo_count_handler)) .route("/list_repos", post(repo_root_handler)) .route("/repo_by_id", post(repo_handler)) @@ -128,10 +123,6 @@ async fn repo_count_handler(State(ctx): State) -> impl IntoResponse { Ok::<_, Error>(Json(repos)) } -async fn repo_count_notifications_handler() -> impl IntoResponse { - Ok::<_, Error>(Json(Vec::::new())) -} - #[derive(Serialize, Deserialize)] struct RepoBody { pub rid: identity::RepoId, diff --git a/src/App.svelte b/src/App.svelte index ee8c48cea..781a0e5cc 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -22,7 +22,6 @@ import Auth from "@app/views/booting/Auth.svelte"; import CreateIdentity from "@app/views/booting/CreateIdentity.svelte"; import CreateIssue from "@app/views/repo/CreateIssue.svelte"; - import Inbox from "@app/views/home/Inbox.svelte"; import Issue from "@app/views/repo/Issue.svelte"; import Issues from "@app/views/repo/Issues.svelte"; import Patch from "@app/views/repo/Patch.svelte"; @@ -108,8 +107,6 @@ {/if} {:else if $activeRouteStore.resource === "home"} -{:else if $activeRouteStore.resource === "inbox"} - {:else if $activeRouteStore.resource === "repo.home"} {:else if $activeRouteStore.resource === "repo.createIssue"} diff --git a/src/components/ConfirmClear.svelte b/src/components/ConfirmClear.svelte index e817316cd..59fe682b5 100644 --- a/src/components/ConfirmClear.svelte +++ b/src/components/ConfirmClear.svelte @@ -1,50 +1,36 @@ - - {#snippet toggle(onclick)} - - - - {/snippet} - - {#snippet popover()} - -
-
- Clear all {subject} notifications? -
-
- - Cancel - - -
-
-
- {/snippet} -
+{#if closed} + (closed = false)}> + + +{:else} +
+
+ + (closed = true)}> + Cancel + +
+
+{/if} diff --git a/src/components/Header.svelte b/src/components/Header.svelte index 713d7294d..811ef68a3 100644 --- a/src/components/Header.svelte +++ b/src/components/Header.svelte @@ -13,6 +13,7 @@ import Avatar from "@app/components/Avatar.svelte"; import Icon from "@app/components/Icon.svelte"; + import InboxPopover from "@app/components/InboxPopover.svelte"; import InfoButton from "@app/components/InfoButton.svelte"; import NakedButton from "@app/components/NakedButton.svelte"; import NodeStatusButton from "@app/components/NodeStatusButton.svelte"; @@ -29,10 +30,9 @@ interface Props { config: Config; center?: Snippet; + notificationCount: number; } - const { center, config }: Props = $props(); - onMount(async () => { try { await checkRadicleCLI(); @@ -46,6 +46,8 @@ firstLaunchStorage.value = false; } }); + + const { center, notificationCount, config }: Props = $props();
-
- {#if activeTab.type === "inbox"} - - - -
router.push({ resource: "inbox" })}> -
Inbox
-
- {sum(Array.from(notificationCount.values()).map(c => c.count))} -
-
- {#each notificationCount.entries() as [_, n]} - - -
- router.push({ - resource: "inbox", - activeTab: n, - })} - class:active={activeTab.repo?.rid === n.rid}> -
- {n.name} -
-
- {n.count} -
-
- {/each} -
- {:else} - - -
router.push({ resource: "inbox" })} - style:color="var(--color-foreground-contrast)" - style:padding-left="12px"> -
Inbox
-
- {sum(Array.from(notificationCount.values()).map(c => c.count))} -
+ + + +
router.push({ resource: "home", activeTab: "all" })}> +
Repositories
+
+ {repoCount.total}
- {/if} -
- - {#if activeTab.type === "repos"} - - - -
router.push({ resource: "home" })}> -
Repositories
-
- {repoCount.total} -
-
- - -
- router.push({ - resource: "home", - activeTab: "delegate", - })}> -
- -
Delegate
-
-
{repoCount.delegate}
-
- - -
- router.push({ - resource: "home", - activeTab: "contributor", - })}> -
- -
Contributor
-
-
{repoCount.contributor}
-
- - -
- router.push({ - resource: "home", - activeTab: "private", - })}> -
- -
Private
-
-
{repoCount.private}
-
-
- {:else} - - + + +
+ router.push({ resource: "home", - }}> -
-
- - Repositories -
-
- {repoCount.total} -
-
- - - {/if} + activeTab: "delegate", + })}> +
+ +
Delegate
+
+
{repoCount.delegate}
+
+ + +
+ router.push({ + resource: "home", + activeTab: "contributor", + })}> +
+ +
Contributor
+
+
{repoCount.contributor}
+
+ + +
+ router.push({ + resource: "home", + activeTab: "private", + })}> +
+ +
Private
+
+
{repoCount.private}
+
+
+ {:else if name === "eye-closed"} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {:else if name === "face"} @@ -966,6 +1003,29 @@ + {:else if name === "pin"} + + + + + + + + + + + + {:else if name === "pin-hollow"} + + + + + + + + + + {:else if name === "plus"} @@ -1134,6 +1194,25 @@ + {:else if name === "thumb-up"} + + + + + + + + + + + + + + + + + + {:else if name === "user"} diff --git a/src/components/InboxPopover.svelte b/src/components/InboxPopover.svelte new file mode 100644 index 000000000..369d5ecbd --- /dev/null +++ b/src/components/InboxPopover.svelte @@ -0,0 +1,147 @@ + + + + {#snippet toggle(onclick)} + { + buttonActive = true; + await loadNotifications(); + onclick(); + }} + variant={notificationCount && notificationCount > 0 + ? "secondary" + : "ghost"} + active={buttonActive}> + + {#if notificationCount !== undefined && notificationCount > 0} + {notificationCount} + {/if} + + {/snippet} + + {#snippet popover()} + + + + {/snippet} + diff --git a/src/components/NotificationTeaser.svelte b/src/components/NotificationTeaser.svelte index 1f8b4f21e..1e425e546 100644 --- a/src/components/NotificationTeaser.svelte +++ b/src/components/NotificationTeaser.svelte @@ -27,7 +27,7 @@ rid: string; kind: "issue" | "patch"; oid: string; - clearByIds: (rid: string, ids: string[]) => Promise; + clearByIds: (ids: string[]) => Promise; notificationItems: NotificationItem[]; selected?: boolean; } @@ -201,7 +201,11 @@ {/if}
{#each uniqueActions as action} -
+
{@html action.summary} {formatTimestamp(action.items[0].timestamp)} @@ -216,10 +220,7 @@ variant="ghost" onclick={e => { e.stopPropagation(); - void clearByIds( - rid, - notificationItems.map(n => n.rowId), - ); + void clearByIds(notificationItems.map(n => n.rowId)); }}> diff --git a/src/components/NotificationsByRepo.svelte b/src/components/NotificationsByRepo.svelte new file mode 100644 index 000000000..f4a904e62 --- /dev/null +++ b/src/components/NotificationsByRepo.svelte @@ -0,0 +1,153 @@ + + + + +
+
+ + {name} + + {count} + + {#if count > 0 && !hidden} +
+ { + void clearByRepo(rid); + }} /> +
+ {/if} +
+ + {#if !hidden} +
+ {#if groupedNotifications.length > 0} + {#each groupedNotifications as notificationGroup} + + {/each} + {:else} +
+
+ + No notifications. +
+
+ {/if} +
+ + {#if groupedNotifications.length > 0 && groupedNotifications.length < count} +
+
+ +
+
+ {/if} + {/if} +
diff --git a/src/components/OutlineButton.svelte b/src/components/OutlineButton.svelte index 44253f4ba..db2c45028 100644 --- a/src/components/OutlineButton.svelte +++ b/src/components/OutlineButton.svelte @@ -28,7 +28,9 @@ `--button-color-2: var(--color-fill-${variant}-hover);` + `--button-color-3: var(--color-fill-${variant}-shade);` + // The ghost colors are called --color-fill-counter and --color-fill-counter-emphasized. - `--button-color-4: var(--color-fill${variant === "ghost" ? "" : `-${variant}`}-counter)`, + `--button-color-4: var(--color-fill${variant === "ghost" ? "" : `-${variant}`}-counter);` + + `--text-color-hover: ${variant === "ghost" ? "var(--color-foreground-contrast)" : "var(--color-foreground-white)"};` + + `--text-color-active: ${variant === "ghost" ? "var(--color-foreground-emphasized)" : "var(--color-foreground-white)"};`, ); @@ -229,8 +231,12 @@ background-color: var(--button-color-1); } + .container:hover:not(.disabled) { + color: var(--text-color-hover); + } + .container.active:not(.disabled) { - color: var(--color-foreground-emphasized); + color: var(--text-color-active); } .container.disabled { diff --git a/src/components/RepoNotifications.svelte b/src/components/RepoNotifications.svelte deleted file mode 100644 index bca1cce7e..000000000 --- a/src/components/RepoNotifications.svelte +++ /dev/null @@ -1,84 +0,0 @@ - - - - -{#if Object.entries(items).length > 0} -
-
- - {repo.name} - - {repo.count} -
- { - void clearByRepo(repo.rid); - }} /> -
-{/if} - -
- {#each items.sort((a, b) => b[1][0].timestamp - a[1][0].timestamp) as [_, notificationItems]} - - {/each} -
-{#if all === false && more} -
-
- -
-
-{/if} diff --git a/src/lib/auth.svelte.ts b/src/lib/auth.svelte.ts index 3366d3c2f..4c1b6b18c 100644 --- a/src/lib/auth.svelte.ts +++ b/src/lib/auth.svelte.ts @@ -22,7 +22,7 @@ export async function checkAuth() { import.meta.env.VITE_AUTH_LONG_DELAY || 30_000, ); if (get(router.activeRouteStore).resource === "booting") { - void router.push({ resource: "home" }); + void router.push({ resource: "home", activeTab: "all" }); } } catch (err) { const error = err as ErrorWrapper; diff --git a/src/lib/router.ts b/src/lib/router.ts index d1af1b379..6c8b3724b 100644 --- a/src/lib/router.ts +++ b/src/lib/router.ts @@ -47,7 +47,7 @@ async function navigateToUrl( await navigate(action, route); } else { console.error("Could not resolve route for URL: ", url); - await navigate(action, { resource: "home" }); + await navigate(action, { resource: "home", activeTab: "all" }); } } @@ -105,11 +105,9 @@ function urlToRoute(url: URL): Route | null { case "": { return { resource: "home", + activeTab: "all", }; } - case "inbox": { - return { resource: "inbox" }; - } case "repos": { return repoUrlToRoute(segments, url.searchParams); } @@ -122,8 +120,6 @@ function urlToRoute(url: URL): Route | null { export function routeToPath(route: Route): string { if (route.resource === "home") { return "/"; - } else if (route.resource === "inbox") { - return "/inbox"; } else if ( route.resource === "repo.home" || route.resource === "repo.createIssue" || diff --git a/src/lib/router/definitions.ts b/src/lib/router/definitions.ts index 9e38fde33..75cafddac 100644 --- a/src/lib/router/definitions.ts +++ b/src/lib/router/definitions.ts @@ -1,14 +1,7 @@ -import type { Config } from "@bindings/config/Config"; -import type { NotificationItem } from "@bindings/cob/inbox/NotificationItem"; -import type { PaginatedQuery } from "@bindings/cob/PaginatedQuery"; -import type { NotificationCount } from "@bindings/cob/inbox/NotificationCount"; -import type { RepoInfo } from "@bindings/repo/RepoInfo"; -import type { RepoCount } from "@bindings/repo/RepoCount"; +import type { LoadedHomeRoute, HomeRoute } from "@app/views/home/router"; import type { LoadedRepoRoute, RepoRoute } from "@app/views/repo/router"; -import { invoke } from "@app/lib/invoke"; -import { SvelteMap } from "svelte/reactivity"; - +import { loadHome } from "@app/views/home/router"; import { loadCreateIssue, loadIssue, @@ -18,142 +11,19 @@ import { loadRepoHome, } from "@app/views/repo/router"; -export type HomeReposTab = "delegate" | "private" | "contributor"; - -export interface HomeInboxTab { - rid: string; - name: string; - count: number; -} - interface BootingRoute { resource: "booting"; } -interface HomeRoute { - resource: "home"; - activeTab?: HomeReposTab; -} - -interface InboxRoute { - resource: "inbox"; - activeTab?: HomeInboxTab; -} - -interface LoadedInboxRoute { - resource: "inbox"; - params: { - activeTab?: HomeInboxTab; - repoCount: RepoCount; - notificationCount: SvelteMap; - notifications: SvelteMap< - string, - { - repo: HomeInboxTab; - items: [string, NotificationItem[]][]; - pagination: { cursor: number; more: boolean }; - } - >; - config: Config; - }; -} - -interface LoadedHomeRoute { - resource: "home"; - params: { - activeTab?: HomeReposTab; - repoCount: RepoCount; - notificationCount: Map; - repos: RepoInfo[]; - config: Config; - }; -} - -export type Route = InboxRoute | BootingRoute | HomeRoute | RepoRoute; - -export type LoadedRoute = - | LoadedInboxRoute - | BootingRoute - | LoadedHomeRoute - | LoadedRepoRoute; +export type Route = BootingRoute | HomeRoute | RepoRoute; +export type LoadedRoute = BootingRoute | LoadedHomeRoute | LoadedRepoRoute; export async function loadRoute( route: Route, _previousLoaded: LoadedRoute, ): Promise { - const [count, repoCount, config] = await Promise.all([ - invoke>("count_notifications_by_repo"), - invoke("repo_count"), - invoke("config"), - ]); - const notificationCount = new SvelteMap(Object.entries(count)); if (route.resource === "home") { - let show = "all"; - - if (route.resource === "home") { - if (route.activeTab === "delegate") { - show = "delegate"; - } else if (route.activeTab === "contributor") { - show = "contributor"; - } else if (route.activeTab === "private") { - show = "private"; - } - } - - const repos = await invoke("list_repos", { show }); - return { - resource: "home", - params: { - activeTab: route.activeTab, - repoCount, - notificationCount, - repos, - config, - }, - }; - } else if (route.resource === "inbox") { - const notifications: LoadedInboxRoute["params"]["notifications"] = - new SvelteMap(); - if (route.activeTab) { - const items = await invoke< - PaginatedQuery<[string, NotificationItem[]][]> - >("list_notifications", { - params: { - repo: route.activeTab.rid, - }, - }); - notifications.set(route.activeTab.rid, { - repo: route.activeTab, - items: items.content, - pagination: { cursor: items.cursor, more: items.more }, - }); - } else { - for (const [rid, item] of notificationCount) { - const result = await invoke< - PaginatedQuery<[string, NotificationItem[]][]> - >("list_notifications", { - params: { - repo: rid, - }, - }); - notifications.set(item.rid, { - repo: { name: item.name, rid: item.rid, count: item.count }, - items: result.content, - pagination: { cursor: result.cursor, more: result.more }, - }); - } - } - - return { - resource: "inbox", - params: { - activeTab: route.activeTab, - repoCount, - notifications, - notificationCount, - config, - }, - }; + return loadHome(route); } else if (route.resource === "repo.home") { return loadRepoHome(route); } else if (route.resource === "repo.issue") { diff --git a/src/views/booting/Auth.svelte b/src/views/booting/Auth.svelte index 8ebe50b6e..9db92562c 100644 --- a/src/views/booting/Auth.svelte +++ b/src/views/booting/Auth.svelte @@ -33,7 +33,7 @@ await createEventEmittersOnce(); } passphrase = " ".repeat(passphrase.length); - await router.push({ resource: "home" }); + await router.push({ resource: "home", activeTab: "all" }); } catch (err) { error = err as ErrorWrapper; } finally { diff --git a/src/views/home/Inbox.svelte b/src/views/home/Inbox.svelte index bfb319eaa..9ab0c9194 100644 --- a/src/views/home/Inbox.svelte +++ b/src/views/home/Inbox.svelte @@ -1,217 +1,187 @@ - { - if (activeTab) { - await loadMoreContent(); - } - }} - hideSidebar - styleSecondColumnOverflow="visible"> - {#snippet headerCenter()} - - {/snippet} - {#snippet secondColumn()} - - {/snippet} -
-
-
Inbox
- {#if notifications.size > 0} - +
+
+
+ Inbox + {#if notificationCount !== undefined && notificationCount > 0} + {notificationCount} {/if}
- {#each notifications.values() as { repo, pagination, items }} - - {:else} - -
-
- - No notifications. -
-
-
- {/each} + {#if notificationCount === undefined || notificationCount === 0} +
+ + Yay, inbox zero! +
+ {/if} + {#if notificationCount !== undefined && notificationCount > loadedNotificationCount()} +
+ + See {notificationCount - loadedNotificationCount()} new + +
+ {/if} + {#if notificationCount && notificationCount > 0} +
+ +
+ {/if}
- + + {#if notificationCount !== undefined && notificationCount > 0} +
+ {#each sortedRepos(notificationsByRepo, pinnedRepos, hiddenRepos) as repo} +
+ {/if} +
diff --git a/src/views/home/Repos.svelte b/src/views/home/Repos.svelte index 426cce5dc..646667f48 100644 --- a/src/views/home/Repos.svelte +++ b/src/views/home/Repos.svelte @@ -1,8 +1,7 @@ @@ -37,7 +38,11 @@ } - + {#snippet headerCenter()} {/snippet} diff --git a/src/views/repo/router.ts b/src/views/repo/router.ts index e690e9d46..1ea92a1fa 100644 --- a/src/views/repo/router.ts +++ b/src/views/repo/router.ts @@ -42,6 +42,7 @@ export interface LoadedRepoHomeRoute { repo: RepoInfo; config: Config; readme: Readme | null; + notificationCount: number; }; } @@ -55,6 +56,7 @@ export interface LoadedRepoIssueRoute { status: IssueStatus; activity: Operation[]; threads: Thread[]; + notificationCount: number; }; } @@ -65,6 +67,7 @@ export interface LoadedRepoCreateIssueRoute { config: Config; issues: Issue[]; status: IssueStatus; + notificationCount: number; }; } @@ -81,6 +84,7 @@ export interface LoadedRepoIssuesRoute { config: Config; issues: Issue[]; status: IssueStatus; + notificationCount: number; }; } @@ -105,6 +109,7 @@ export interface LoadedRepoPatchRoute { review: Review | undefined; revisions: Revision[]; activity: Operation[]; + notificationCount: number; }; } @@ -121,6 +126,7 @@ export interface LoadedRepoPatchesRoute { config: Config; patches: PaginatedQuery; status: PatchStatus | undefined; + notificationCount: number; }; } @@ -142,8 +148,9 @@ export type LoadedRepoRoute = export async function loadPatch( route: RepoPatchRoute, ): Promise { - const [config, repo, patches, patch, revisions, activity] = await Promise.all( - [ + const [notificationCount, config, repo, patches, patch, revisions, activity] = + await Promise.all([ + invoke("notification_count"), invoke("config"), invoke("repo_by_id", { rid: route.rid, @@ -165,8 +172,7 @@ export async function loadPatch( rid: route.rid, id: route.patch, }), - ], - ); + ]); const review = revisions .flatMap(r => r.reviews || []) @@ -183,6 +189,7 @@ export async function loadPatch( status: route.status, review, activity, + notificationCount, }, }; } @@ -190,7 +197,8 @@ export async function loadPatch( export async function loadPatches( route: RepoPatchesRoute, ): Promise { - const [config, repo, patches] = await Promise.all([ + const [notificationCount, config, repo, patches] = await Promise.all([ + invoke("notification_count"), invoke("config"), invoke("repo_by_id", { rid: route.rid, @@ -204,14 +212,15 @@ export async function loadPatches( return { resource: "repo.patches", - params: { repo, config, patches, status: route.status }, + params: { notificationCount, repo, config, patches, status: route.status }, }; } export async function loadRepoHome( route: RepoHomeRoute, ): Promise { - const [config, repo, readme] = await Promise.all([ + const [notificationCount, config, repo, readme] = await Promise.all([ + invoke("notification_count"), invoke("config"), invoke("repo_by_id", { rid: route.rid, @@ -223,14 +232,15 @@ export async function loadRepoHome( return { resource: "repo.home", - params: { repo, config, readme }, + params: { notificationCount, repo, config, readme }, }; } export async function loadCreateIssue( route: RepoCreateIssueRoute, ): Promise { - const [config, repo, issues] = await Promise.all([ + const [notificationCount, config, repo, issues] = await Promise.all([ + invoke("notification_count"), invoke("config"), invoke("repo_by_id", { rid: route.rid, @@ -243,39 +253,42 @@ export async function loadCreateIssue( return { resource: "repo.createIssue", - params: { repo, config, issues, status: route.status }, + params: { notificationCount, repo, config, issues, status: route.status }, }; } export async function loadIssue( route: RepoIssueRoute, ): Promise { - const [config, repo, issue, activity, issues, threads] = await Promise.all([ - invoke("config"), - invoke("repo_by_id", { - rid: route.rid, - }), - invoke("issue_by_id", { - rid: route.rid, - id: route.issue, - }), - invoke[]>("activity_by_issue", { - rid: route.rid, - id: route.issue, - }), - invoke("list_issues", { - rid: route.rid, - status: route.status, - }), - invoke("comment_threads_by_issue_id", { - rid: route.rid, - id: route.issue, - }), - ]); + const [notificationCount, config, repo, issue, activity, issues, threads] = + await Promise.all([ + invoke("notification_count"), + invoke("config"), + invoke("repo_by_id", { + rid: route.rid, + }), + invoke("issue_by_id", { + rid: route.rid, + id: route.issue, + }), + invoke[]>("activity_by_issue", { + rid: route.rid, + id: route.issue, + }), + invoke("list_issues", { + rid: route.rid, + status: route.status, + }), + invoke("comment_threads_by_issue_id", { + rid: route.rid, + id: route.issue, + }), + ]); return { resource: "repo.issue", params: { + notificationCount, repo, config, issue, @@ -290,7 +303,8 @@ export async function loadIssue( export async function loadIssues( route: RepoIssuesRoute, ): Promise { - const [config, repo, issues] = await Promise.all([ + const [notificationCount, config, repo, issues] = await Promise.all([ + invoke("notification_count"), invoke("config"), invoke("repo_by_id", { rid: route.rid, @@ -303,7 +317,7 @@ export async function loadIssues( return { resource: "repo.issues", - params: { repo, config, issues, status: route.status }, + params: { notificationCount, repo, config, issues, status: route.status }, }; }