From 83d24351cdbe5794c3d65268584b6ba1daf983a6 Mon Sep 17 00:00:00 2001 From: reya Date: Sat, 26 Oct 2024 17:24:39 +0700 Subject: [PATCH] update --- src-tauri/capabilities/column.json | 55 ---- src-tauri/capabilities/main.json | 10 +- src-tauri/gen/schemas/capabilities.json | 2 +- src-tauri/src/commands/event.rs | 27 +- src-tauri/src/commands/sync.rs | 121 +-------- src-tauri/src/commands/window.rs | 104 +++++++- src-tauri/src/common.rs | 8 + src-tauri/src/main.rs | 245 +++++------------- src/commands.gen.ts | 20 +- src/components/column.tsx | 29 +-- src/routes/__root.tsx | 17 -- .../columns/_layout/events.$id.lazy.tsx | 25 +- .../columns/_layout/newsfeed.$id.lazy.tsx | 24 +- 13 files changed, 191 insertions(+), 496 deletions(-) delete mode 100644 src-tauri/capabilities/column.json diff --git a/src-tauri/capabilities/column.json b/src-tauri/capabilities/column.json deleted file mode 100644 index 2de039f3..00000000 --- a/src-tauri/capabilities/column.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "column", - "description": "Capability for the column", - "platforms": [ - "linux", - "macOS", - "windows" - ], - "windows": [ - "column-*" - ], - "permissions": [ - "core:resources:default", - "core:tray:default", - "os:allow-locale", - "os:allow-os-type", - "clipboard-manager:allow-write-text", - "dialog:allow-open", - "dialog:allow-ask", - "dialog:allow-message", - "fs:allow-read-file", - "core:menu:default", - "core:menu:allow-new", - "core:menu:allow-popup", - "http:default", - "shell:allow-open", - "store:allow-get", - "store:allow-set", - "store:allow-delete", - "theme:default", - { - "identifier": "http:default", - "allow": [ - { - "url": "http://**/" - }, - { - "url": "https://**/" - } - ] - }, - { - "identifier": "fs:allow-read-text-file", - "allow": [ - { - "path": "$RESOURCE/locales/*" - }, - { - "path": "$RESOURCE/resources/*" - } - ] - } - ] -} diff --git a/src-tauri/capabilities/main.json b/src-tauri/capabilities/main.json index a6810e4e..9cf4b330 100644 --- a/src-tauri/capabilities/main.json +++ b/src-tauri/capabilities/main.json @@ -7,15 +7,7 @@ "windows" ], "windows": [ - "main", - "panel", - "settings", - "search-*", - "zap-*", - "event-*", - "user-*", - "editor-*", - "popup-*" + "*" ], "permissions": [ "core:path:default", diff --git a/src-tauri/gen/schemas/capabilities.json b/src-tauri/gen/schemas/capabilities.json index ecf98500..dd4f5433 100644 --- a/src-tauri/gen/schemas/capabilities.json +++ b/src-tauri/gen/schemas/capabilities.json @@ -1 +1 @@ -{"column":{"identifier":"column","description":"Capability for the column","local":true,"windows":["column-*"],"permissions":["core:resources:default","core:tray:default","os:allow-locale","os:allow-os-type","clipboard-manager:allow-write-text","dialog:allow-open","dialog:allow-ask","dialog:allow-message","fs:allow-read-file","core:menu:default","core:menu:allow-new","core:menu:allow-popup","http:default","shell:allow-open","store:allow-get","store:allow-set","store:allow-delete","theme:default",{"identifier":"http:default","allow":[{"url":"http://**/"},{"url":"https://**/"}]},{"identifier":"fs:allow-read-text-file","allow":[{"path":"$RESOURCE/locales/*"},{"path":"$RESOURCE/resources/*"}]}],"platforms":["linux","macOS","windows"]},"window":{"identifier":"window","description":"Capability for the desktop","local":true,"windows":["main","panel","settings","search-*","zap-*","event-*","user-*","editor-*","popup-*"],"permissions":["core:path:default","core:event:default","core:window:default","core:app:default","core:resources:default","core:menu:default","core:tray:default","notification:allow-is-permission-granted","notification:allow-request-permission","notification:default","os:allow-locale","os:allow-platform","os:allow-os-type","updater:default","updater:allow-check","updater:allow-download-and-install","core:window:allow-create","core:window:allow-close","core:window:allow-destroy","core:window:allow-set-focus","core:window:allow-center","core:window:allow-minimize","core:window:allow-maximize","core:window:allow-set-size","core:window:allow-start-dragging","core:window:allow-toggle-maximize","decorum:allow-show-snap-overlay","clipboard-manager:allow-write-text","clipboard-manager:allow-read-text","core:webview:allow-create-webview-window","core:webview:allow-create-webview","core:webview:allow-set-webview-size","core:webview:allow-set-webview-position","core:webview:allow-webview-close","dialog:allow-open","dialog:allow-ask","dialog:allow-message","process:allow-restart","process:allow-exit","fs:allow-read-file","core:menu:allow-new","core:menu:allow-popup","shell:allow-open","store:default","prevent-default:default","theme:default",{"identifier":"http:default","allow":[{"url":"http://**/"},{"url":"https://**/"}]},{"identifier":"fs:allow-read-text-file","allow":[{"path":"$RESOURCE/locales/*"},{"path":"$RESOURCE/resources/*"}]}],"platforms":["macOS","windows"]}} \ No newline at end of file +{"window":{"identifier":"window","description":"Capability for the desktop","local":true,"windows":["*"],"permissions":["core:path:default","core:event:default","core:window:default","core:app:default","core:resources:default","core:menu:default","core:tray:default","notification:allow-is-permission-granted","notification:allow-request-permission","notification:default","os:allow-locale","os:allow-platform","os:allow-os-type","updater:default","updater:allow-check","updater:allow-download-and-install","core:window:allow-create","core:window:allow-close","core:window:allow-destroy","core:window:allow-set-focus","core:window:allow-center","core:window:allow-minimize","core:window:allow-maximize","core:window:allow-set-size","core:window:allow-start-dragging","core:window:allow-toggle-maximize","decorum:allow-show-snap-overlay","clipboard-manager:allow-write-text","clipboard-manager:allow-read-text","core:webview:allow-create-webview-window","core:webview:allow-create-webview","core:webview:allow-set-webview-size","core:webview:allow-set-webview-position","core:webview:allow-webview-close","dialog:allow-open","dialog:allow-ask","dialog:allow-message","process:allow-restart","process:allow-exit","fs:allow-read-file","core:menu:allow-new","core:menu:allow-popup","shell:allow-open","store:default","prevent-default:default","theme:default",{"identifier":"http:default","allow":[{"url":"http://**/"},{"url":"https://**/"}]},{"identifier":"fs:allow-read-text-file","allow":[{"path":"$RESOURCE/locales/*"},{"path":"$RESOURCE/resources/*"}]}],"platforms":["macOS","windows"]}} \ No newline at end of file diff --git a/src-tauri/src/commands/event.rs b/src-tauri/src/commands/event.rs index c1328ff3..57ac03b2 100644 --- a/src-tauri/src/commands/event.rs +++ b/src-tauri/src/commands/event.rs @@ -84,28 +84,6 @@ pub async fn get_replies(id: String, state: State<'_, Nostr>) -> Result) -> Result<(), String> { - let client = &state.client; - - let subscription_id = SubscriptionId::new(&id); - let event_id = EventId::parse(&id).map_err(|err| err.to_string())?; - - let filter = Filter::new() - .kinds(vec![Kind::TextNote]) - .event(event_id) - .since(Timestamp::now()); - - match client - .subscribe_with_id(subscription_id, vec![filter], None) - .await - { - Ok(_) => Ok(()), - Err(e) => Err(e.to_string()), - } -} - #[tauri::command] #[specta::specta] pub async fn get_all_events_by_author( @@ -178,10 +156,7 @@ pub async fn get_all_events_by_hashtags( .until(as_of) .hashtags(hashtags); - match client - .fetch_events(vec![filter], Some(Duration::from_secs(5))) - .await - { + match client.database().query(vec![filter]).await { Ok(events) => Ok(process_event(client, events, false).await), Err(err) => Err(err.to_string()), } diff --git a/src-tauri/src/commands/sync.rs b/src-tauri/src/commands/sync.rs index bfbb02a2..b14bca6f 100644 --- a/src-tauri/src/commands/sync.rs +++ b/src-tauri/src/commands/sync.rs @@ -1,126 +1,9 @@ use nostr_sdk::prelude::*; -use serde::{Deserialize, Serialize}; -use specta::Type; -use std::{ - collections::HashSet, - fs::{self, File}, - str::FromStr, -}; -use tauri::{ipc::Channel, AppHandle, Manager, State}; -use tauri_specta::Event as TauriEvent; +use std::fs::{self, File}; +use tauri::{ipc::Channel, Manager, State}; use crate::Nostr; -#[derive(Clone, Serialize, Type, TauriEvent)] -pub struct NegentropyEvent { - kind: NegentropyKind, - total_event: i32, -} - -#[derive(Clone, Serialize, Deserialize, Type)] -pub enum NegentropyKind { - Profile, - Metadata, - Events, - EventIds, - Global, - Notification, - Others, -} - -pub fn sync_all(accounts: Vec, app_handle: AppHandle) { - if accounts.is_empty() { - return; - }; - - let public_keys: Vec = accounts - .iter() - .filter_map(|acc| { - if let Ok(pk) = PublicKey::from_str(acc) { - Some(pk) - } else { - None - } - }) - .collect(); - - tauri::async_runtime::spawn(async move { - let state = app_handle.state::(); - let client = &state.client; - let bootstrap_relays = state.bootstrap_relays.lock().unwrap().clone(); - - // NEG: Sync events for all pubkeys in local database - // - if let Ok(events) = client - .database() - .query(vec![Filter::new() - .authors(public_keys) - .kinds(vec![Kind::ContactList, Kind::FollowSet])]) - .await - { - let set: HashSet = events - .iter() - .flat_map(|ev| ev.tags.public_keys().copied()) - .collect(); - - let pubkeys: Vec = set.into_iter().collect(); - - for chunk in pubkeys.chunks(500) { - if chunk.is_empty() { - break; - } - - let authors = chunk.to_owned(); - - // NEG: Sync event - // - let events = Filter::new() - .authors(authors.clone()) - .kinds(vec![Kind::TextNote, Kind::Repost]) - .limit(500); - - if let Ok(output) = client - .sync_with(&bootstrap_relays, events, &SyncOptions::default()) - .await - { - NegentropyEvent { - kind: NegentropyKind::Events, - total_event: output.received.len() as i32, - } - .emit(&app_handle) - .unwrap(); - } - - // NEG: Sync metadata - // - let events = Filter::new() - .authors(authors.clone()) - .kinds(vec![ - Kind::Metadata, - Kind::InterestSet, - Kind::Interests, - Kind::FollowSet, - Kind::EventDeletion, - Kind::Custom(30315), - ]) - .limit(500); - - if let Ok(output) = client - .sync_with(&bootstrap_relays, events, &SyncOptions::default()) - .await - { - NegentropyEvent { - kind: NegentropyKind::Metadata, - total_event: output.received.len() as i32, - } - .emit(&app_handle) - .unwrap(); - } - } - } - }); -} - #[tauri::command] #[specta::specta] pub fn is_account_sync(id: String, app_handle: tauri::AppHandle) -> Result { diff --git a/src-tauri/src/commands/window.rs b/src-tauri/src/commands/window.rs index fb2a8a80..98743c2e 100644 --- a/src-tauri/src/commands/window.rs +++ b/src-tauri/src/commands/window.rs @@ -1,7 +1,9 @@ use std::path::PathBuf; +use std::str::FromStr; #[cfg(target_os = "macos")] use border::WebviewWindowExt as BorderWebviewWindowExt; +use nostr_sdk::prelude::*; use serde::{Deserialize, Serialize}; use specta::Type; use tauri::utils::config::WindowEffectsConfig; @@ -14,6 +16,9 @@ use tauri::{WebviewBuilder, WebviewWindowBuilder}; #[cfg(target_os = "windows")] use tauri_plugin_decorum::WebviewWindowExt; +use crate::common::get_last_segment; +use crate::Nostr; + #[derive(Serialize, Deserialize, Type)] pub struct NewWindow { label: String, @@ -55,8 +60,101 @@ pub async fn create_column( .transparent(true) .on_page_load(|webview, payload| match payload.event() { PageLoadEvent::Started => { - let url = payload.url(); - println!("#TODO, preload: {}", url) + if let Ok(id) = get_last_segment(payload.url()) { + if let Ok(public_key) = PublicKey::from_str(&id) { + let is_newsfeed = payload.url().to_string().contains("newsfeed"); + + tauri::async_runtime::spawn(async move { + let state = webview.state::(); + let client = &state.client; + let relays = &state.bootstrap_relays.lock().unwrap().clone(); + + if is_newsfeed { + if let Ok(contact_list) = + client.database().contacts_public_keys(public_key).await + { + let opts = SyncOptions::default(); + let subscription_id = + SubscriptionId::new(webview.label()); + let filter = + Filter::new().authors(contact_list).kinds(vec![ + Kind::TextNote, + Kind::Repost, + Kind::EventDeletion, + ]); + + if let Err(e) = client + .subscribe_with_id( + subscription_id, + vec![filter.clone().since(Timestamp::now())], + None, + ) + .await + { + println!("Subscription error: {}", e); + } + + if let Ok(output) = client + .sync_with(relays, filter.limit(1000), &opts) + .await + { + println!("Success: {:?}", output.success.len()); + } + } + } else { + let opts = SyncOptions::default(); + let filter = Filter::new() + .author(public_key) + .kinds(vec![ + Kind::Interests, + Kind::InterestSet, + Kind::FollowSet, + Kind::Bookmarks, + Kind::BookmarkSet, + Kind::TextNote, + Kind::Repost, + Kind::Custom(30315), + ]) + .limit(500); + + if let Ok(output) = + client.sync_with(relays, filter, &opts).await + { + println!("Success: {:?}", output.success.len()); + } + } + }); + } else if let Ok(event_id) = EventId::from_str(&id) { + tauri::async_runtime::spawn(async move { + let state = webview.state::(); + let client = &state.client; + let relays = &state.bootstrap_relays.lock().unwrap().clone(); + + let opts = SyncOptions::default(); + let subscription_id = SubscriptionId::new(webview.label()); + let filter = Filter::new() + .event(event_id) + .kinds(vec![Kind::TextNote, Kind::Custom(1111)]); + + if let Err(e) = client + .subscribe_with_id( + subscription_id, + vec![filter.clone().since(Timestamp::now())], + None, + ) + .await + { + println!("Subscription error: {}", e); + } + + if let Ok(output) = + client.sync_with(relays, filter, &opts).await + { + println!("Success: {:?}", output.success.len()); + } + }); + } + } } PageLoadEvent::Finished => { println!("{} finished loading", payload.url()); @@ -80,7 +178,7 @@ pub async fn create_column( pub async fn close_column(label: String, app_handle: tauri::AppHandle) -> Result { match app_handle.get_webview(&label) { Some(webview) => Ok(webview.close().is_ok()), - None => Err("Cannot close, column not found.".into()), + None => Err(format!("Cannot close, column not found: {}", label)), } } diff --git a/src-tauri/src/common.rs b/src-tauri/src/common.rs index 3585d47d..7c9c64d6 100644 --- a/src-tauri/src/common.rs +++ b/src-tauri/src/common.rs @@ -143,6 +143,14 @@ pub fn get_all_accounts() -> Vec { accounts.into_iter().collect() } +pub fn get_last_segment(url: &Url) -> Result { + url.path_segments() + .ok_or("No segments".to_string())? + .last() + .ok_or("No items".into()) + .map(String::from) +} + pub async fn process_event(client: &Client, events: Events, is_reply: bool) -> Vec { // Remove event thread if event is TextNote let events: Vec = if !is_reply { diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 047ef217..cc2db04c 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -12,7 +12,6 @@ use serde::{Deserialize, Serialize}; use specta::Type; use specta_typescript::Typescript; use std::{ - collections::HashSet, fs, io::{self, BufRead}, str::FromStr, @@ -22,7 +21,7 @@ use std::{ use tauri::{path::BaseDirectory, Emitter, EventTarget, Manager}; use tauri_plugin_decorum::WebviewWindowExt; use tauri_plugin_notification::{NotificationExt, PermissionState}; -use tauri_specta::{collect_commands, collect_events, Builder, Event as TauriEvent}; +use tauri_specta::{collect_commands, Builder, Event as TauriEvent}; pub mod commands; pub mod common; @@ -32,7 +31,6 @@ pub struct Nostr { settings: Mutex, accounts: Mutex>, bootstrap_relays: Mutex>, - subscriptions: Mutex>, } #[derive(Clone, Serialize, Deserialize, Type)] @@ -66,20 +64,6 @@ impl Default for Settings { } } -#[derive(Serialize, Deserialize, Type)] -enum SubscriptionMethod { - Subscribe, - Unsubscribe, -} - -#[derive(Serialize, Deserialize, Type, TauriEvent)] -struct Subscription { - label: String, - kind: SubscriptionMethod, - event_id: Option, - contacts: Option>, -} - #[derive(Serialize, Deserialize, Type, TauriEvent)] struct Sync { id: String, @@ -92,72 +76,69 @@ pub const NOTIFICATION_SUB_ID: &str = "lume_notification"; fn main() { tracing_subscriber::fmt::init(); - let builder = Builder::::new() - .commands(collect_commands![ - sync_account, - is_account_sync, - get_relays, - connect_relay, - remove_relay, - get_bootstrap_relays, - save_bootstrap_relays, - get_accounts, - watch_account, - import_account, - connect_account, - get_private_key, - delete_account, - reset_password, - has_signer, - set_signer, - get_profile, - set_profile, - get_contact_list, - set_contact_list, - is_contact, - toggle_contact, - get_all_profiles, - set_group, - get_group, - get_all_groups, - set_interest, - get_interest, - get_all_interests, - set_wallet, - load_wallet, - remove_wallet, - zap_profile, - zap_event, - copy_friend, - get_notifications, - get_user_settings, - set_user_settings, - verify_nip05, - get_meta_from_event, - get_event, - get_replies, - subscribe_to, - get_all_events_by_author, - get_all_events_by_authors, - get_all_events_by_hashtags, - get_local_events, - get_global_events, - search, - publish, - reply, - repost, - is_reposted, - request_delete, - is_deleted_event, - event_to_bech32, - user_to_bech32, - create_column, - update_column, - reload_column, - close_column, - open_window, - ]) - .events(collect_events![Subscription, NegentropyEvent]); + let builder = Builder::::new().commands(collect_commands![ + sync_account, + is_account_sync, + get_relays, + connect_relay, + remove_relay, + get_bootstrap_relays, + save_bootstrap_relays, + get_accounts, + watch_account, + import_account, + connect_account, + get_private_key, + delete_account, + reset_password, + has_signer, + set_signer, + get_profile, + set_profile, + get_contact_list, + set_contact_list, + is_contact, + toggle_contact, + get_all_profiles, + set_group, + get_group, + get_all_groups, + set_interest, + get_interest, + get_all_interests, + set_wallet, + load_wallet, + remove_wallet, + zap_profile, + zap_event, + copy_friend, + get_notifications, + get_user_settings, + set_user_settings, + verify_nip05, + get_meta_from_event, + get_event, + get_replies, + get_all_events_by_author, + get_all_events_by_authors, + get_all_events_by_hashtags, + get_local_events, + get_global_events, + search, + publish, + reply, + repost, + is_reposted, + request_delete, + is_deleted_event, + event_to_bech32, + user_to_bech32, + create_column, + update_column, + reload_column, + close_column, + open_window, + ]); #[cfg(debug_assertions)] builder @@ -170,12 +151,8 @@ fn main() { tauri_builder .invoke_handler(builder.invoke_handler()) .setup(move |app| { - builder.mount_events(app); - let handle = app.handle(); let handle_clone = handle.clone(); - let handle_clone_child = handle_clone.clone(); - let handle_clone_child_child = handle_clone_child.clone(); let main_window = app.get_webview_window("main").unwrap(); let config_dir = handle @@ -261,8 +238,6 @@ fn main() { }); let accounts = get_all_accounts(); - // Run sync for all accounts - sync_all(accounts.clone(), handle_clone_child_child); // Create global state app.manage(Nostr { @@ -270,98 +245,6 @@ fn main() { accounts: Mutex::new(accounts), settings: Mutex::new(Settings::default()), bootstrap_relays: Mutex::new(bootstrap_relays), - subscriptions: Mutex::new(HashSet::new()), - }); - - // Handle subscription request - Subscription::listen_any(app, move |event| { - let handle = handle_clone_child.to_owned(); - let payload = event.payload; - - tauri::async_runtime::spawn(async move { - let state = handle.state::(); - let client = &state.client; - - match payload.kind { - SubscriptionMethod::Subscribe => { - let subscription_id = SubscriptionId::new(payload.label); - - if !client - .pool() - .subscriptions() - .await - .contains_key(&subscription_id) - { - // Update state - state - .subscriptions - .lock() - .unwrap() - .insert(subscription_id.clone()); - - println!( - "Total subscriptions: {}", - state.subscriptions.lock().unwrap().len() - ); - - if let Some(id) = payload.event_id { - let event_id = EventId::from_str(&id).unwrap(); - let filter = - Filter::new().event(event_id).since(Timestamp::now()); - - if let Err(e) = client - .subscribe_with_id( - subscription_id.clone(), - vec![filter], - None, - ) - .await - { - println!("Subscription error: {}", e) - } - } - - if let Some(ids) = payload.contacts { - let authors: Vec = ids - .iter() - .filter_map(|item| { - if let Ok(pk) = PublicKey::from_str(item) { - Some(pk) - } else { - None - } - }) - .collect(); - - if let Err(e) = client - .subscribe_with_id( - subscription_id, - vec![Filter::new() - .kinds(vec![Kind::TextNote, Kind::Repost]) - .authors(authors) - .since(Timestamp::now())], - None, - ) - .await - { - println!("Subscription error: {}", e) - } - } - } - } - SubscriptionMethod::Unsubscribe => { - let subscription_id = SubscriptionId::new(payload.label); - - println!( - "Total subscriptions: {}", - state.subscriptions.lock().unwrap().len() - ); - - state.subscriptions.lock().unwrap().remove(&subscription_id); - client.unsubscribe(subscription_id).await; - } - } - }); }); // Run notification thread diff --git a/src/commands.gen.ts b/src/commands.gen.ts index 30ad4faa..76ac3e11 100644 --- a/src/commands.gen.ts +++ b/src/commands.gen.ts @@ -336,14 +336,6 @@ async getReplies(id: string) : Promise> { else return { status: "error", error: e as any }; } }, -async subscribeTo(id: string) : Promise> { - try { - return { status: "ok", data: await TAURI_INVOKE("subscribe_to", { id }) }; -} catch (e) { - if(e instanceof Error) throw e; - else return { status: "error", error: e as any }; -} -}, async getAllEventsByAuthor(publicKey: string, limit: number) : Promise> { try { return { status: "ok", data: await TAURI_INVOKE("get_all_events_by_author", { publicKey, limit }) }; @@ -501,13 +493,6 @@ async openWindow(window: NewWindow) : Promise> { /** user-defined events **/ -export const events = __makeEvents__<{ -negentropyEvent: NegentropyEvent, -subscription: Subscription -}>({ -negentropyEvent: "negentropy-event", -subscription: "subscription" -}) /** user-defined constants **/ @@ -518,15 +503,12 @@ subscription: "subscription" export type Column = { label: string; url: string; x: number; y: number; width: number; height: number } export type Mention = { pubkey: string; avatar: string; display_name: string; name: string } export type Meta = { content: string; images: string[]; events: string[]; mentions: string[]; hashtags: string[] } -export type NegentropyEvent = { kind: NegentropyKind; total_event: number } -export type NegentropyKind = "Profile" | "Metadata" | "Events" | "EventIds" | "Global" | "Notification" | "Others" export type NewWindow = { label: string; title: string; url: string; width: number; height: number; maximizable: boolean; minimizable: boolean; hidden_title: boolean; closable: boolean } export type Profile = { name: string; display_name: string; about: string | null; picture: string; banner: string | null; nip05: string | null; lud16: string | null; website: string | null } export type Relays = { connected: string[]; read: string[] | null; write: string[] | null; both: string[] | null } export type RichEvent = { raw: string; parsed: Meta | null } export type Settings = { proxy: string | null; image_resize_service: string | null; use_relay_hint: boolean; content_warning: boolean; trusted_only: boolean; display_avatar: boolean; display_zap_button: boolean; display_repost_button: boolean; display_media: boolean; transparent: boolean } -export type Subscription = { label: string; kind: SubscriptionMethod; event_id: string | null; contacts: string[] | null } -export type SubscriptionMethod = "Subscribe" | "Unsubscribe" +export type TAURI_CHANNEL = null /** tauri-specta globals **/ diff --git a/src/components/column.tsx b/src/components/column.tsx index 5fcbc3e4..bd6a77d6 100644 --- a/src/components/column.tsx +++ b/src/components/column.tsx @@ -4,18 +4,10 @@ import type { LumeColumn } from "@/types"; import { CaretDown, Check } from "@phosphor-icons/react"; import { Menu, MenuItem, PredefinedMenuItem } from "@tauri-apps/api/menu"; import { getCurrentWindow } from "@tauri-apps/api/window"; -import { - useCallback, - useEffect, - useLayoutEffect, - useMemo, - useState, -} from "react"; +import { useCallback, useEffect, useLayoutEffect, useState } from "react"; import { User } from "./user"; export function Column({ column }: { column: LumeColumn }) { - const webviewLabel = useMemo(() => `column-${column.label}`, [column.label]); - const [rect, ref] = useRect(); const [_error, setError] = useState(""); @@ -23,7 +15,7 @@ export function Column({ column }: { column: LumeColumn }) { (async () => { if (rect) { const res = await commands.updateColumn( - webviewLabel, + column.label, rect.width, rect.height, rect.x, @@ -31,7 +23,7 @@ export function Column({ column }: { column: LumeColumn }) { ); if (res.status === "ok") { - console.log("webview is updated: ", webviewLabel); + console.log("webview is updated: ", column.label); } else { console.log("webview error: ", res.error); } @@ -40,12 +32,13 @@ export function Column({ column }: { column: LumeColumn }) { }, [rect]); useLayoutEffect(() => { + console.log(column.label); if (ref.current) { const initialRect = ref.current.getBoundingClientRect(); commands .createColumn({ - label: webviewLabel, + label: column.label, x: initialRect.x, y: initialRect.y, width: initialRect.width, @@ -54,16 +47,16 @@ export function Column({ column }: { column: LumeColumn }) { }) .then((res) => { if (res.status === "ok") { - console.log("webview is created: ", webviewLabel); + console.log("webview is created: ", column.label); } else { setError(res.error); } }); return () => { - commands.closeColumn(webviewLabel).then((res) => { + commands.closeColumn(column.label).then((res) => { if (res.status === "ok") { - console.log("webview is closed: ", webviewLabel); + console.log("webview is closed: ", column.label); } else { console.log("webview error: ", res.error); } @@ -77,7 +70,6 @@ export function Column({ column }: { column: LumeColumn }) {
@@ -89,10 +81,9 @@ export function Column({ column }: { column: LumeColumn }) { function Header({ label, - webviewLabel, name, account, -}: { label: string; webviewLabel: string; name: string; account?: string }) { +}: { label: string; name: string; account?: string }) { const [title, setTitle] = useState(""); const [isChanged, setIsChanged] = useState(false); @@ -105,7 +96,7 @@ function Header({ MenuItem.new({ text: "Reload", action: async () => { - await commands.reloadColumn(webviewLabel); + await commands.reloadColumn(label); }, }), PredefinedMenuItem.new({ item: "Separator" }), diff --git a/src/routes/__root.tsx b/src/routes/__root.tsx index 19a95913..4ea3ade4 100644 --- a/src/routes/__root.tsx +++ b/src/routes/__root.tsx @@ -1,9 +1,7 @@ -import { events } from "@/commands.gen"; import { Spinner } from "@/components"; import type { QueryClient } from "@tanstack/react-query"; import { Outlet, createRootRouteWithContext } from "@tanstack/react-router"; import type { OsType } from "@tauri-apps/plugin-os"; -import { useEffect } from "react"; interface RouterContext { queryClient: QueryClient; @@ -17,21 +15,6 @@ export const Route = createRootRouteWithContext()({ }); function Screen() { - const { queryClient } = Route.useRouteContext(); - - useEffect(() => { - const unlisten = events.negentropyEvent.listen(async (data) => { - const queryKey = [data.payload.kind.toLowerCase()]; - console.info("invalidate: ", queryKey); - - await queryClient.refetchQueries({ queryKey }); - }); - - return () => { - unlisten.then((f) => f()); - }; - }, []); - return ; } diff --git a/src/routes/columns/_layout/events.$id.lazy.tsx b/src/routes/columns/_layout/events.$id.lazy.tsx index 60682dfd..4ad0000a 100644 --- a/src/routes/columns/_layout/events.$id.lazy.tsx +++ b/src/routes/columns/_layout/events.$id.lazy.tsx @@ -1,4 +1,4 @@ -import { events, commands } from "@/commands.gen"; +import { commands } from "@/commands.gen"; import { Note, ReplyNote, Spinner } from "@/components"; import { LumeEvent, useEvent } from "@/system"; import type { EventPayload } from "@/types"; @@ -91,7 +91,6 @@ function RootEvent() { } function ReplyList() { - const { label } = Route.useSearch(); const { id } = Route.useParams(); const { queryClient } = Route.useRouteContext(); const { data, isLoading } = useQuery({ @@ -179,28 +178,6 @@ function ReplyList() { refetchOnWindowFocus: false, }); - useEffect(() => { - events.subscription - .emit({ - label: label || id, - kind: "Subscribe", - event_id: id, - contacts: null, - }) - .then(() => console.log("Subscribe: ", label)); - - return () => { - events.subscription - .emit({ - label: label || id, - kind: "Unsubscribe", - event_id: id, - contacts: null, - }) - .then(() => console.log("Unsubscribe: ", label)); - }; - }, []); - useEffect(() => { const unlisten = getCurrentWindow().listen( "event", diff --git a/src/routes/columns/_layout/newsfeed.$id.lazy.tsx b/src/routes/columns/_layout/newsfeed.$id.lazy.tsx index cafb19ea..3493de5f 100644 --- a/src/routes/columns/_layout/newsfeed.$id.lazy.tsx +++ b/src/routes/columns/_layout/newsfeed.$id.lazy.tsx @@ -1,4 +1,4 @@ -import { events, commands } from "@/commands.gen"; +import { commands } from "@/commands.gen"; import { toLumeEvents } from "@/commons"; import { RepostNote, Spinner, TextNote } from "@/components"; import type { LumeEvent } from "@/system"; @@ -83,28 +83,6 @@ export function Screen() { [data], ); - useEffect(() => { - events.subscription - .emit({ - label: search.label as string, - kind: "Subscribe", - event_id: null, - contacts, - }) - .then(() => console.log("Subscribe: ", search.label)); - - return () => { - events.subscription - .emit({ - label: search.label as string, - kind: "Unsubscribe", - event_id: null, - contacts, - }) - .then(() => console.log("Unsubscribe: ", search.label)); - }; - }, []); - useEffect(() => { const unlisten = listen("synchronized", async () => { await queryClient.refetchQueries({