This commit is contained in:
2024-10-26 17:24:39 +07:00
parent 470dc1c759
commit 83d24351cd
13 changed files with 191 additions and 496 deletions

View File

@@ -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/*"
}
]
}
]
}

View File

@@ -7,15 +7,7 @@
"windows" "windows"
], ],
"windows": [ "windows": [
"main", "*"
"panel",
"settings",
"search-*",
"zap-*",
"event-*",
"user-*",
"editor-*",
"popup-*"
], ],
"permissions": [ "permissions": [
"core:path:default", "core:path:default",

View File

@@ -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"]}} {"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"]}}

View File

@@ -84,28 +84,6 @@ pub async fn get_replies(id: String, state: State<'_, Nostr>) -> Result<Vec<Rich
} }
} }
#[tauri::command]
#[specta::specta]
pub async fn subscribe_to(id: String, state: State<'_, Nostr>) -> 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] #[tauri::command]
#[specta::specta] #[specta::specta]
pub async fn get_all_events_by_author( pub async fn get_all_events_by_author(
@@ -178,10 +156,7 @@ pub async fn get_all_events_by_hashtags(
.until(as_of) .until(as_of)
.hashtags(hashtags); .hashtags(hashtags);
match client match client.database().query(vec![filter]).await {
.fetch_events(vec![filter], Some(Duration::from_secs(5)))
.await
{
Ok(events) => Ok(process_event(client, events, false).await), Ok(events) => Ok(process_event(client, events, false).await),
Err(err) => Err(err.to_string()), Err(err) => Err(err.to_string()),
} }

View File

@@ -1,126 +1,9 @@
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use serde::{Deserialize, Serialize}; use std::fs::{self, File};
use specta::Type; use tauri::{ipc::Channel, Manager, State};
use std::{
collections::HashSet,
fs::{self, File},
str::FromStr,
};
use tauri::{ipc::Channel, AppHandle, Manager, State};
use tauri_specta::Event as TauriEvent;
use crate::Nostr; 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<String>, app_handle: AppHandle) {
if accounts.is_empty() {
return;
};
let public_keys: Vec<PublicKey> = 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::<Nostr>();
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<PublicKey> = events
.iter()
.flat_map(|ev| ev.tags.public_keys().copied())
.collect();
let pubkeys: Vec<PublicKey> = 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] #[tauri::command]
#[specta::specta] #[specta::specta]
pub fn is_account_sync(id: String, app_handle: tauri::AppHandle) -> Result<bool, String> { pub fn is_account_sync(id: String, app_handle: tauri::AppHandle) -> Result<bool, String> {

View File

@@ -1,7 +1,9 @@
use std::path::PathBuf; use std::path::PathBuf;
use std::str::FromStr;
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
use border::WebviewWindowExt as BorderWebviewWindowExt; use border::WebviewWindowExt as BorderWebviewWindowExt;
use nostr_sdk::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use specta::Type; use specta::Type;
use tauri::utils::config::WindowEffectsConfig; use tauri::utils::config::WindowEffectsConfig;
@@ -14,6 +16,9 @@ use tauri::{WebviewBuilder, WebviewWindowBuilder};
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
use tauri_plugin_decorum::WebviewWindowExt; use tauri_plugin_decorum::WebviewWindowExt;
use crate::common::get_last_segment;
use crate::Nostr;
#[derive(Serialize, Deserialize, Type)] #[derive(Serialize, Deserialize, Type)]
pub struct NewWindow { pub struct NewWindow {
label: String, label: String,
@@ -55,8 +60,101 @@ pub async fn create_column(
.transparent(true) .transparent(true)
.on_page_load(|webview, payload| match payload.event() { .on_page_load(|webview, payload| match payload.event() {
PageLoadEvent::Started => { PageLoadEvent::Started => {
let url = payload.url(); if let Ok(id) = get_last_segment(payload.url()) {
println!("#TODO, preload: {}", 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::<Nostr>();
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::<Nostr>();
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 => { PageLoadEvent::Finished => {
println!("{} finished loading", payload.url()); 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<bool, String> { pub async fn close_column(label: String, app_handle: tauri::AppHandle) -> Result<bool, String> {
match app_handle.get_webview(&label) { match app_handle.get_webview(&label) {
Some(webview) => Ok(webview.close().is_ok()), Some(webview) => Ok(webview.close().is_ok()),
None => Err("Cannot close, column not found.".into()), None => Err(format!("Cannot close, column not found: {}", label)),
} }
} }

View File

@@ -143,6 +143,14 @@ pub fn get_all_accounts() -> Vec<String> {
accounts.into_iter().collect() accounts.into_iter().collect()
} }
pub fn get_last_segment(url: &Url) -> Result<String, String> {
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<RichEvent> { pub async fn process_event(client: &Client, events: Events, is_reply: bool) -> Vec<RichEvent> {
// Remove event thread if event is TextNote // Remove event thread if event is TextNote
let events: Vec<Event> = if !is_reply { let events: Vec<Event> = if !is_reply {

View File

@@ -12,7 +12,6 @@ use serde::{Deserialize, Serialize};
use specta::Type; use specta::Type;
use specta_typescript::Typescript; use specta_typescript::Typescript;
use std::{ use std::{
collections::HashSet,
fs, fs,
io::{self, BufRead}, io::{self, BufRead},
str::FromStr, str::FromStr,
@@ -22,7 +21,7 @@ use std::{
use tauri::{path::BaseDirectory, Emitter, EventTarget, Manager}; use tauri::{path::BaseDirectory, Emitter, EventTarget, Manager};
use tauri_plugin_decorum::WebviewWindowExt; use tauri_plugin_decorum::WebviewWindowExt;
use tauri_plugin_notification::{NotificationExt, PermissionState}; 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 commands;
pub mod common; pub mod common;
@@ -32,7 +31,6 @@ pub struct Nostr {
settings: Mutex<Settings>, settings: Mutex<Settings>,
accounts: Mutex<Vec<String>>, accounts: Mutex<Vec<String>>,
bootstrap_relays: Mutex<Vec<Url>>, bootstrap_relays: Mutex<Vec<Url>>,
subscriptions: Mutex<HashSet<SubscriptionId>>,
} }
#[derive(Clone, Serialize, Deserialize, Type)] #[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<String>,
contacts: Option<Vec<String>>,
}
#[derive(Serialize, Deserialize, Type, TauriEvent)] #[derive(Serialize, Deserialize, Type, TauriEvent)]
struct Sync { struct Sync {
id: String, id: String,
@@ -92,72 +76,69 @@ pub const NOTIFICATION_SUB_ID: &str = "lume_notification";
fn main() { fn main() {
tracing_subscriber::fmt::init(); tracing_subscriber::fmt::init();
let builder = Builder::<tauri::Wry>::new() let builder = Builder::<tauri::Wry>::new().commands(collect_commands![
.commands(collect_commands![ sync_account,
sync_account, is_account_sync,
is_account_sync, get_relays,
get_relays, connect_relay,
connect_relay, remove_relay,
remove_relay, get_bootstrap_relays,
get_bootstrap_relays, save_bootstrap_relays,
save_bootstrap_relays, get_accounts,
get_accounts, watch_account,
watch_account, import_account,
import_account, connect_account,
connect_account, get_private_key,
get_private_key, delete_account,
delete_account, reset_password,
reset_password, has_signer,
has_signer, set_signer,
set_signer, get_profile,
get_profile, set_profile,
set_profile, get_contact_list,
get_contact_list, set_contact_list,
set_contact_list, is_contact,
is_contact, toggle_contact,
toggle_contact, get_all_profiles,
get_all_profiles, set_group,
set_group, get_group,
get_group, get_all_groups,
get_all_groups, set_interest,
set_interest, get_interest,
get_interest, get_all_interests,
get_all_interests, set_wallet,
set_wallet, load_wallet,
load_wallet, remove_wallet,
remove_wallet, zap_profile,
zap_profile, zap_event,
zap_event, copy_friend,
copy_friend, get_notifications,
get_notifications, get_user_settings,
get_user_settings, set_user_settings,
set_user_settings, verify_nip05,
verify_nip05, get_meta_from_event,
get_meta_from_event, get_event,
get_event, get_replies,
get_replies, get_all_events_by_author,
subscribe_to, get_all_events_by_authors,
get_all_events_by_author, get_all_events_by_hashtags,
get_all_events_by_authors, get_local_events,
get_all_events_by_hashtags, get_global_events,
get_local_events, search,
get_global_events, publish,
search, reply,
publish, repost,
reply, is_reposted,
repost, request_delete,
is_reposted, is_deleted_event,
request_delete, event_to_bech32,
is_deleted_event, user_to_bech32,
event_to_bech32, create_column,
user_to_bech32, update_column,
create_column, reload_column,
update_column, close_column,
reload_column, open_window,
close_column, ]);
open_window,
])
.events(collect_events![Subscription, NegentropyEvent]);
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
builder builder
@@ -170,12 +151,8 @@ fn main() {
tauri_builder tauri_builder
.invoke_handler(builder.invoke_handler()) .invoke_handler(builder.invoke_handler())
.setup(move |app| { .setup(move |app| {
builder.mount_events(app);
let handle = app.handle(); let handle = app.handle();
let handle_clone = handle.clone(); 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 main_window = app.get_webview_window("main").unwrap();
let config_dir = handle let config_dir = handle
@@ -261,8 +238,6 @@ fn main() {
}); });
let accounts = get_all_accounts(); let accounts = get_all_accounts();
// Run sync for all accounts
sync_all(accounts.clone(), handle_clone_child_child);
// Create global state // Create global state
app.manage(Nostr { app.manage(Nostr {
@@ -270,98 +245,6 @@ fn main() {
accounts: Mutex::new(accounts), accounts: Mutex::new(accounts),
settings: Mutex::new(Settings::default()), settings: Mutex::new(Settings::default()),
bootstrap_relays: Mutex::new(bootstrap_relays), 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::<Nostr>();
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<PublicKey> = 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 // Run notification thread

View File

@@ -336,14 +336,6 @@ async getReplies(id: string) : Promise<Result<RichEvent[], string>> {
else return { status: "error", error: e as any }; else return { status: "error", error: e as any };
} }
}, },
async subscribeTo(id: string) : Promise<Result<null, string>> {
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<Result<RichEvent[], string>> { async getAllEventsByAuthor(publicKey: string, limit: number) : Promise<Result<RichEvent[], string>> {
try { try {
return { status: "ok", data: await TAURI_INVOKE("get_all_events_by_author", { publicKey, limit }) }; return { status: "ok", data: await TAURI_INVOKE("get_all_events_by_author", { publicKey, limit }) };
@@ -501,13 +493,6 @@ async openWindow(window: NewWindow) : Promise<Result<string, string>> {
/** user-defined events **/ /** user-defined events **/
export const events = __makeEvents__<{
negentropyEvent: NegentropyEvent,
subscription: Subscription
}>({
negentropyEvent: "negentropy-event",
subscription: "subscription"
})
/** user-defined constants **/ /** 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 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 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 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 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 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 Relays = { connected: string[]; read: string[] | null; write: string[] | null; both: string[] | null }
export type RichEvent = { raw: string; parsed: Meta | 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 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 TAURI_CHANNEL<TSend> = null
export type SubscriptionMethod = "Subscribe" | "Unsubscribe"
/** tauri-specta globals **/ /** tauri-specta globals **/

View File

@@ -4,18 +4,10 @@ import type { LumeColumn } from "@/types";
import { CaretDown, Check } from "@phosphor-icons/react"; import { CaretDown, Check } from "@phosphor-icons/react";
import { Menu, MenuItem, PredefinedMenuItem } from "@tauri-apps/api/menu"; import { Menu, MenuItem, PredefinedMenuItem } from "@tauri-apps/api/menu";
import { getCurrentWindow } from "@tauri-apps/api/window"; import { getCurrentWindow } from "@tauri-apps/api/window";
import { import { useCallback, useEffect, useLayoutEffect, useState } from "react";
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useState,
} from "react";
import { User } from "./user"; import { User } from "./user";
export function Column({ column }: { column: LumeColumn }) { export function Column({ column }: { column: LumeColumn }) {
const webviewLabel = useMemo(() => `column-${column.label}`, [column.label]);
const [rect, ref] = useRect(); const [rect, ref] = useRect();
const [_error, setError] = useState<string>(""); const [_error, setError] = useState<string>("");
@@ -23,7 +15,7 @@ export function Column({ column }: { column: LumeColumn }) {
(async () => { (async () => {
if (rect) { if (rect) {
const res = await commands.updateColumn( const res = await commands.updateColumn(
webviewLabel, column.label,
rect.width, rect.width,
rect.height, rect.height,
rect.x, rect.x,
@@ -31,7 +23,7 @@ export function Column({ column }: { column: LumeColumn }) {
); );
if (res.status === "ok") { if (res.status === "ok") {
console.log("webview is updated: ", webviewLabel); console.log("webview is updated: ", column.label);
} else { } else {
console.log("webview error: ", res.error); console.log("webview error: ", res.error);
} }
@@ -40,12 +32,13 @@ export function Column({ column }: { column: LumeColumn }) {
}, [rect]); }, [rect]);
useLayoutEffect(() => { useLayoutEffect(() => {
console.log(column.label);
if (ref.current) { if (ref.current) {
const initialRect = ref.current.getBoundingClientRect(); const initialRect = ref.current.getBoundingClientRect();
commands commands
.createColumn({ .createColumn({
label: webviewLabel, label: column.label,
x: initialRect.x, x: initialRect.x,
y: initialRect.y, y: initialRect.y,
width: initialRect.width, width: initialRect.width,
@@ -54,16 +47,16 @@ export function Column({ column }: { column: LumeColumn }) {
}) })
.then((res) => { .then((res) => {
if (res.status === "ok") { if (res.status === "ok") {
console.log("webview is created: ", webviewLabel); console.log("webview is created: ", column.label);
} else { } else {
setError(res.error); setError(res.error);
} }
}); });
return () => { return () => {
commands.closeColumn(webviewLabel).then((res) => { commands.closeColumn(column.label).then((res) => {
if (res.status === "ok") { if (res.status === "ok") {
console.log("webview is closed: ", webviewLabel); console.log("webview is closed: ", column.label);
} else { } else {
console.log("webview error: ", res.error); console.log("webview error: ", res.error);
} }
@@ -77,7 +70,6 @@ export function Column({ column }: { column: LumeColumn }) {
<div className="flex flex-col gap-px size-full"> <div className="flex flex-col gap-px size-full">
<Header <Header
label={column.label} label={column.label}
webviewLabel={webviewLabel}
name={column.name} name={column.name}
account={column.account} account={column.account}
/> />
@@ -89,10 +81,9 @@ export function Column({ column }: { column: LumeColumn }) {
function Header({ function Header({
label, label,
webviewLabel,
name, name,
account, account,
}: { label: string; webviewLabel: string; name: string; account?: string }) { }: { label: string; name: string; account?: string }) {
const [title, setTitle] = useState(""); const [title, setTitle] = useState("");
const [isChanged, setIsChanged] = useState(false); const [isChanged, setIsChanged] = useState(false);
@@ -105,7 +96,7 @@ function Header({
MenuItem.new({ MenuItem.new({
text: "Reload", text: "Reload",
action: async () => { action: async () => {
await commands.reloadColumn(webviewLabel); await commands.reloadColumn(label);
}, },
}), }),
PredefinedMenuItem.new({ item: "Separator" }), PredefinedMenuItem.new({ item: "Separator" }),

View File

@@ -1,9 +1,7 @@
import { events } from "@/commands.gen";
import { Spinner } from "@/components"; import { Spinner } from "@/components";
import type { QueryClient } from "@tanstack/react-query"; import type { QueryClient } from "@tanstack/react-query";
import { Outlet, createRootRouteWithContext } from "@tanstack/react-router"; import { Outlet, createRootRouteWithContext } from "@tanstack/react-router";
import type { OsType } from "@tauri-apps/plugin-os"; import type { OsType } from "@tauri-apps/plugin-os";
import { useEffect } from "react";
interface RouterContext { interface RouterContext {
queryClient: QueryClient; queryClient: QueryClient;
@@ -17,21 +15,6 @@ export const Route = createRootRouteWithContext<RouterContext>()({
}); });
function Screen() { 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 <Outlet />; return <Outlet />;
} }

View File

@@ -1,4 +1,4 @@
import { events, commands } from "@/commands.gen"; import { commands } from "@/commands.gen";
import { Note, ReplyNote, Spinner } from "@/components"; import { Note, ReplyNote, Spinner } from "@/components";
import { LumeEvent, useEvent } from "@/system"; import { LumeEvent, useEvent } from "@/system";
import type { EventPayload } from "@/types"; import type { EventPayload } from "@/types";
@@ -91,7 +91,6 @@ function RootEvent() {
} }
function ReplyList() { function ReplyList() {
const { label } = Route.useSearch();
const { id } = Route.useParams(); const { id } = Route.useParams();
const { queryClient } = Route.useRouteContext(); const { queryClient } = Route.useRouteContext();
const { data, isLoading } = useQuery({ const { data, isLoading } = useQuery({
@@ -179,28 +178,6 @@ function ReplyList() {
refetchOnWindowFocus: false, 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(() => { useEffect(() => {
const unlisten = getCurrentWindow().listen<EventPayload>( const unlisten = getCurrentWindow().listen<EventPayload>(
"event", "event",

View File

@@ -1,4 +1,4 @@
import { events, commands } from "@/commands.gen"; import { commands } from "@/commands.gen";
import { toLumeEvents } from "@/commons"; import { toLumeEvents } from "@/commons";
import { RepostNote, Spinner, TextNote } from "@/components"; import { RepostNote, Spinner, TextNote } from "@/components";
import type { LumeEvent } from "@/system"; import type { LumeEvent } from "@/system";
@@ -83,28 +83,6 @@ export function Screen() {
[data], [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(() => { useEffect(() => {
const unlisten = listen("synchronized", async () => { const unlisten = listen("synchronized", async () => {
await queryClient.refetchQueries({ await queryClient.refetchQueries({