wip: i'm tired

This commit is contained in:
2024-11-05 10:19:51 +07:00
parent 605b847a66
commit 8525ac3fdd
9 changed files with 973 additions and 1009 deletions

66
src-tauri/Cargo.lock generated
View File

@@ -2,39 +2,6 @@
# It is not intended for manual editing.
version = 3
[[package]]
name = "COOP"
version = "0.2.0"
dependencies = [
"border",
"futures",
"itertools 0.13.0",
"keyring",
"keyring-search",
"nostr-connect",
"nostr-sdk",
"serde",
"serde_json",
"specta",
"specta-typescript",
"tauri",
"tauri-build",
"tauri-plugin-clipboard-manager",
"tauri-plugin-decorum",
"tauri-plugin-dialog",
"tauri-plugin-fs",
"tauri-plugin-notification",
"tauri-plugin-os",
"tauri-plugin-prevent-default",
"tauri-plugin-process",
"tauri-plugin-shell",
"tauri-plugin-store",
"tauri-plugin-updater",
"tauri-specta",
"tokio",
"tracing-subscriber",
]
[[package]]
name = "Inflector"
version = "0.11.4"
@@ -1006,6 +973,39 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e"
[[package]]
name = "coop"
version = "0.2.0"
dependencies = [
"border",
"futures",
"itertools 0.13.0",
"keyring",
"keyring-search",
"nostr-connect",
"nostr-sdk",
"serde",
"serde_json",
"specta",
"specta-typescript",
"tauri",
"tauri-build",
"tauri-plugin-clipboard-manager",
"tauri-plugin-decorum",
"tauri-plugin-dialog",
"tauri-plugin-fs",
"tauri-plugin-notification",
"tauri-plugin-os",
"tauri-plugin-prevent-default",
"tauri-plugin-process",
"tauri-plugin-shell",
"tauri-plugin-store",
"tauri-plugin-updater",
"tauri-specta",
"tokio",
"tracing-subscriber",
]
[[package]]
name = "core-foundation"
version = "0.9.4"

View File

@@ -1,5 +1,5 @@
[package]
name = "COOP"
name = "coop"
version = "0.2.0"
description = "direct message client for desktop"
authors = ["npub1zfss807aer0j26mwp2la0ume0jqde3823rmu97ra6sgyyg956e0s6xw445"]

View File

@@ -328,6 +328,13 @@ pub async fn login(
for url in urls.iter() {
let _ = client.add_relay(url).await;
let _ = client.connect_relay(url).await;
// Workaround for https://github.com/rust-nostr/nostr/issues/509
// TODO: remove
let filter = Filter::new().kind(Kind::TextNote).limit(0);
let _ = client
.fetch_events_from(vec![url], vec![filter], Some(Duration::from_secs(3)))
.await;
}
let mut inbox_relays = state.inbox_relays.write().await;
@@ -341,34 +348,32 @@ pub async fn login(
let inbox_relays = state.inbox_relays.read().await;
let relays = inbox_relays.get(&public_key).unwrap().to_owned();
let sub_id = SubscriptionId::new(SUBSCRIPTION_ID);
let subscription_id = SubscriptionId::new(SUBSCRIPTION_ID);
// Create a filter for getting new message
let new_message = Filter::new()
.kind(Kind::GiftWrap)
.pubkey(public_key)
.limit(0);
// Subscribe for new message
if let Err(e) = client
.subscribe_with_id_to(&relays, sub_id, vec![new_message], None)
.subscribe_with_id_to(&relays, subscription_id, vec![new_message], None)
.await
{
println!("Subscribe error: {}", e)
};
let filter = Filter::new()
.kind(Kind::GiftWrap)
.pubkey(public_key)
.limit(200);
// Create a filter for getting all gift wrapped events send to current user
let filter = Filter::new().kind(Kind::GiftWrap).pubkey(public_key);
let mut rx = client
.stream_events_from(&relays, vec![filter], Some(Duration::from_secs(40)))
.await
.unwrap();
let opts = SubscribeAutoCloseOptions::default().filter(
FilterOptions::WaitDurationAfterEOSE(Duration::from_secs(10)),
);
while let Some(event) = rx.next().await {
println!("Event: {}", event.as_json());
if let Ok(output) = client.subscribe_to(&relays, vec![filter], Some(opts)).await {
println!("Output: {:?}", output)
}
// handle.emit("synchronized", ()).unwrap();
});
Ok(public_key.to_hex())

View File

@@ -175,6 +175,17 @@ pub async fn connect_inbox_relays(
let _ = client.add_relay(&url).await;
let _ = client.connect_relay(&url).await;
// Workaround for https://github.com/rust-nostr/nostr/issues/509
// TODO: remove
let filter = Filter::new().kind(Kind::TextNote).limit(0);
let _ = client
.fetch_events_from(
vec![url.clone()],
vec![filter],
Some(Duration::from_secs(3)),
)
.await;
relays.push(url)
}
}

View File

@@ -104,51 +104,51 @@ fn main() {
main_window.add_border(None);
// Setup tray menu item
let open_i = MenuItem::with_id(app, "open", "Open COOP", true, None::<&str>)?;
let quit_i = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?;
// Create tray menu
let menu = Menu::with_items(app, &[&open_i, &quit_i])?;
// Get main tray
let tray = app.tray_by_id("main").unwrap();
// Set menu
tray.set_menu(Some(menu)).unwrap();
// Listen to tray events
tray.on_menu_event(|handle, event| match event.id().as_ref() {
"open" => {
if let Some(window) = handle.get_webview_window("main") {
if window.is_visible().unwrap_or_default() {
let _ = window.set_focus();
} else {
let _ = window.show();
let _ = window.set_focus();
};
} else {
let window = WebviewWindowBuilder::from_config(
handle,
handle.config().app.windows.first().unwrap(),
)
.unwrap()
.build()
.unwrap();
let open_i = MenuItem::with_id(app, "open", "Open COOP", true, None::<&str>)?;
let quit_i = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?;
// Create tray menu
let menu = Menu::with_items(app, &[&open_i, &quit_i])?;
// Get main tray
let tray = app.tray_by_id("main").unwrap();
// Set menu
tray.set_menu(Some(menu)).unwrap();
// Listen to tray events
tray.on_menu_event(|handle, event| match event.id().as_ref() {
"open" => {
if let Some(window) = handle.get_webview_window("main") {
if window.is_visible().unwrap_or_default() {
let _ = window.set_focus();
} else {
let _ = window.show();
let _ = window.set_focus();
};
} else {
let window = WebviewWindowBuilder::from_config(
handle,
handle.config().app.windows.first().unwrap(),
)
.unwrap()
.build()
.unwrap();
// Set decoration
#[cfg(target_os = "windows")]
window.create_overlay_titlebar().unwrap();
// Set decoration
#[cfg(target_os = "windows")]
window.create_overlay_titlebar().unwrap();
// Restore native border
#[cfg(target_os = "macos")]
window.add_border(None);
// Restore native border
#[cfg(target_os = "macos")]
window.add_border(None);
// Set a custom inset to the traffic lights
#[cfg(target_os = "macos")]
window.set_traffic_lights_inset(12.0, 18.0).unwrap();
}
}
"quit" => {
std::process::exit(0);
}
_ => {}
});
// Set a custom inset to the traffic lights
#[cfg(target_os = "macos")]
window.set_traffic_lights_inset(12.0, 18.0).unwrap();
}
}
"quit" => {
std::process::exit(0);
}
_ => {}
});
let client = tauri::async_runtime::block_on(async move {
// Get config directory
@@ -163,10 +163,7 @@ fn main() {
.expect("Error: cannot create database.");
// Config
let opts = Options::new()
.gossip(true)
.automatic_authentication(false)
.max_avg_latency(Duration::from_millis(500));
let opts = Options::new().gossip(true).max_avg_latency(Duration::from_millis(500));
// Setup nostr client
let client = ClientBuilder::default()
@@ -207,6 +204,7 @@ fn main() {
// Connect
client.connect().await;
// Return nostr client
client
});
@@ -271,30 +269,13 @@ fn main() {
let _ = client
.handle_notifications(|notification| async {
#[allow(clippy::collapsible_match)]
if let RelayPoolNotification::Message { message, relay_url, .. } = notification {
if let RelayMessage::Auth { challenge } = message {
match client.auth(challenge, relay_url.clone()).await {
Ok(..) => {
if let Ok(relay) = client.relay(relay_url).await {
if let Err(e) = relay.resubscribe().await {
println!("Resubscribe error: {}", e)
}
// Workaround for https://github.com/rust-nostr/nostr/issues/509
// TODO: remove
let filter = Filter::new().kind(Kind::TextNote).limit(0);
let _ = client.fetch_events(vec![filter], Some(Duration::from_secs(1))).await;
}
}
Err(e) => {
println!("Auth error: {}", e)
}
}
} else if let RelayMessage::Event { event, .. } = message {
if let RelayPoolNotification::Message { message, .. } = notification {
if let RelayMessage::Event { event, subscription_id, .. } = message {
if event.kind == Kind::GiftWrap {
if let Ok(UnwrappedGift { rumor, sender }) =
client.unwrap_gift_wrap(&event).await
{
let subscription_id = subscription_id.to_string();
let mut rumor_clone = rumor.clone();
// Compute event id if not exist
@@ -312,25 +293,32 @@ fn main() {
// Save rumor to database to further query
if let Err(e) = client.database().save_event(&ev).await {
println!("[save event] error: {}", e)
println!("Error: {}", e)
}
// Emit new event to frontend
if let Err(e) = handle.emit(
"event",
EventPayload {
event: rumor.as_json(),
sender: sender.to_hex(),
},
) {
println!("[emit] error: {}", e)
if subscription_id == SUBSCRIPTION_ID {
// Emit new message to current chat screen
if let Err(e) = handle.emit(
"event",
EventPayload {
event: rumor.as_json(),
sender: sender.to_hex(),
},
) {
println!("Emit error: {}", e)
}
} else {
// Emit new message to home screen
if let Err(e) = handle.emit("synchronized", ()) {
println!("Emit error: {}", e)
}
}
}
} else if event.kind == Kind::Metadata {
if let Err(e) = handle.emit("metadata", event.as_json()) {
println!("Emit error: {}", e)
}
}
if let Err(e) = handle.emit("metadata", event.as_json()) {
println!("Emit error: {}", e)
}
}
}
}
Ok(false)

View File

@@ -1,86 +1,85 @@
{
"productName": "COOP",
"version": "0.2.0",
"identifier": "su.reya.coop",
"build": {
"beforeDevCommand": "pnpm dev",
"devUrl": "http://localhost:1420",
"beforeBuildCommand": "pnpm build",
"frontendDist": "../dist"
},
"app": {
"macOSPrivateApi": true,
"withGlobalTauri": true,
"security": {
"assetProtocol": {
"enable": true,
"scope": [
"$APPDATA/*",
"$DATA/*",
"$LOCALDATA/*",
"$DESKTOP/*",
"$DOCUMENT/*",
"$DOWNLOAD/*",
"$HOME/*",
"$PICTURE/*",
"$PUBLIC/*",
"$VIDEO/*",
"$APPCONFIG/*",
"$RESOURCE/*"
]
}
},
"trayIcon": {
"id": "main",
"iconPath": "./icons/32x32.png",
"iconAsTemplate": true,
"menuOnLeftClick": true
}
},
"bundle": {
"homepage": "https://coop.reya.su",
"longDescription": "A direct message nostr client for desktop.",
"shortDescription": "Nostr NIP-17 client",
"targets": "all",
"active": true,
"category": "SocialNetworking",
"resources": [
"resources/*"
],
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"linux": {
"appimage": {
"bundleMediaFramework": true,
"files": {}
},
"deb": {
"files": {}
},
"rpm": {
"epoch": 0,
"files": {},
"release": "1"
}
},
"macOS": {
"minimumSystemVersion": "10.15"
},
"createUpdaterArtifacts": true
},
"plugins": {
"updater": {
"active": true,
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEY2OUJBNzZDOUYwNzREOApSV1RZZFBESmRycHBEMDV0NVZodllibXZNT21YTXBVOG1kRjdpUEpVS1ZkOGVuT295RENrWkpBRAo=",
"endpoints": [
"https://releases.coop-updater-service.workers.dev/check/lumehq/coop/{{target}}/{{arch}}/{{current_version}}",
"https://github.com/lumehq/coop/releases/latest/download/latest.json"
]
}
}
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"productName": "Coop",
"version": "0.2.0",
"identifier": "su.reya.coop",
"build": {
"beforeDevCommand": "pnpm dev",
"devUrl": "http://localhost:1420",
"beforeBuildCommand": "pnpm build",
"frontendDist": "../dist"
},
"app": {
"macOSPrivateApi": true,
"withGlobalTauri": true,
"security": {
"assetProtocol": {
"enable": true,
"scope": [
"$APPDATA/*",
"$DATA/*",
"$LOCALDATA/*",
"$DESKTOP/*",
"$DOCUMENT/*",
"$DOWNLOAD/*",
"$HOME/*",
"$PICTURE/*",
"$PUBLIC/*",
"$VIDEO/*",
"$APPCONFIG/*",
"$RESOURCE/*"
]
}
},
"trayIcon": {
"id": "main",
"iconPath": "./icons/32x32.png",
"iconAsTemplate": true,
"menuOnLeftClick": true
}
},
"bundle": {
"homepage": "https://coop.reya.su",
"longDescription": "A direct message nostr client for desktop.",
"shortDescription": "Nostr NIP-17 client",
"targets": "all",
"active": true,
"category": "SocialNetworking",
"resources": ["resources/*"],
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"linux": {
"appimage": {
"bundleMediaFramework": true,
"files": {}
},
"deb": {
"files": {}
},
"rpm": {
"epoch": 0,
"files": {},
"release": "1"
}
},
"macOS": {
"minimumSystemVersion": "10.15"
},
"createUpdaterArtifacts": true
},
"plugins": {
"updater": {
"active": true,
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEY2OUJBNzZDOUYwNzREOApSV1RZZFBESmRycHBEMDV0NVZodllibXZNT21YTXBVOG1kRjdpUEpVS1ZkOGVuT295RENrWkpBRAo=",
"endpoints": [
"https://releases.coop-updater-service.workers.dev/check/lumehq/coop/{{target}}/{{arch}}/{{current_version}}",
"https://github.com/lumehq/coop/releases/latest/download/latest.json"
]
}
}
}

View File

@@ -11,399 +11,399 @@ import { listen } from "@tauri-apps/api/event";
import { message } from "@tauri-apps/plugin-dialog";
import type { NostrEvent } from "nostr-tools";
import {
type Dispatch,
type RefObject,
type SetStateAction,
useCallback,
useRef,
useState,
useTransition,
type Dispatch,
type RefObject,
type SetStateAction,
useCallback,
useRef,
useState,
useTransition,
} from "react";
import { useEffect } from "react";
import { Virtualizer, type VirtualizerHandle } from "virtua";
type EventPayload = {
event: string;
sender: string;
event: string;
sender: string;
};
export const Route = createLazyFileRoute("/$account/_layout/chats/$id")({
component: Screen,
component: Screen,
});
function Screen() {
return (
<div className="size-full flex flex-col">
<Header />
<List />
<Form />
</div>
);
return (
<div className="size-full flex flex-col">
<Header />
<List />
<Form />
</div>
);
}
function Header() {
const { account, id } = Route.useParams();
const { platform } = Route.useRouteContext();
const { account, id } = Route.useParams();
const { platform } = Route.useRouteContext();
return (
<div
data-tauri-drag-region
className={cn(
"h-12 shrink-0 flex items-center justify-between border-b border-neutral-100 dark:border-neutral-800",
platform === "windows" ? "pl-3.5 pr-[150px]" : "px-3.5",
)}
>
<div className="z-[200]">
<div className="flex -space-x-1 overflow-hidden">
<User.Provider pubkey={account}>
<User.Root className="size-8 rounded-full inline-block ring-2 ring-white dark:ring-neutral-900">
<User.Avatar className="size-8 rounded-full" />
</User.Root>
</User.Provider>
<User.Provider pubkey={id}>
<User.Root className="size-8 rounded-full inline-block ring-2 ring-white dark:ring-neutral-900">
<User.Avatar className="size-8 rounded-full" />
</User.Root>
</User.Provider>
</div>
</div>
<div className="flex items-center gap-2">
<div className="h-7 inline-flex items-center justify-center gap-1.5 px-2 rounded-full bg-neutral-100 dark:bg-neutral-900">
<span className="relative flex size-2">
<span className="animate-ping absolute inline-flex size-full rounded-full bg-teal-400 opacity-75" />
<span className="relative inline-flex rounded-full size-2 bg-teal-500" />
</span>
<div className="text-xs leading-tight">Connected</div>
</div>
</div>
</div>
);
return (
<div
data-tauri-drag-region
className={cn(
"h-12 shrink-0 flex items-center justify-between border-b border-neutral-100 dark:border-neutral-800",
platform === "windows" ? "pl-3.5 pr-[150px]" : "px-3.5",
)}
>
<div className="z-[200]">
<div className="flex -space-x-1 overflow-hidden">
<User.Provider pubkey={account}>
<User.Root className="size-8 rounded-full inline-block ring-2 ring-white dark:ring-neutral-900">
<User.Avatar className="size-8 rounded-full" />
</User.Root>
</User.Provider>
<User.Provider pubkey={id}>
<User.Root className="size-8 rounded-full inline-block ring-2 ring-white dark:ring-neutral-900">
<User.Avatar className="size-8 rounded-full" />
</User.Root>
</User.Provider>
</div>
</div>
<div className="flex items-center gap-2">
<div className="h-7 inline-flex items-center justify-center gap-1.5 px-2 rounded-full bg-neutral-100 dark:bg-neutral-900">
<span className="relative flex size-2">
<span className="animate-ping absolute inline-flex size-full rounded-full bg-teal-400 opacity-75" />
<span className="relative inline-flex rounded-full size-2 bg-teal-500" />
</span>
<div className="text-xs leading-tight">Connected</div>
</div>
</div>
</div>
);
}
function List() {
const { account, id } = Route.useParams();
const { isLoading, isError, data } = useQuery({
queryKey: ["chats", id],
queryFn: async () => {
const res = await commands.getChatMessages(id);
const { account, id } = Route.useParams();
const { isLoading, isError, data } = useQuery({
queryKey: ["chats", id],
queryFn: async () => {
const res = await commands.getChatMessages(id);
if (res.status === "ok") {
const raw = res.data;
const events: NostrEvent[] = raw.map((item) => JSON.parse(item));
if (res.status === "ok") {
const raw = res.data;
const events: NostrEvent[] = raw.map((item) => JSON.parse(item));
return events;
} else {
throw new Error(res.error);
}
},
select: (data) => {
const groups = groupEventByDate(data);
return Object.entries(groups).reverse();
},
refetchOnWindowFocus: false,
});
return events;
} else {
throw new Error(res.error);
}
},
select: (data) => {
const groups = groupEventByDate(data);
return Object.entries(groups).reverse();
},
refetchOnWindowFocus: false,
});
const queryClient = useQueryClient();
const scrollRef = useRef<HTMLDivElement>(null);
const ref = useRef<VirtualizerHandle>(null);
const shouldStickToBottom = useRef(true);
const queryClient = useQueryClient();
const scrollRef = useRef<HTMLDivElement>(null);
const ref = useRef<VirtualizerHandle>(null);
const shouldStickToBottom = useRef(true);
const renderItem = useCallback(
(item: NostrEvent, idx: number) => {
const self = account === item.pubkey;
const renderItem = useCallback(
(item: NostrEvent, idx: number) => {
const self = account === item.pubkey;
return (
<div
key={idx + item.id}
className="flex items-center justify-between gap-3 my-1.5 px-3 border-l-2 border-transparent hover:border-blue-400"
>
<div
className={cn(
"flex-1 min-w-0 inline-flex",
self ? "justify-end" : "justify-start",
)}
>
<div
className={cn(
"select-text py-2 px-3 w-fit max-w-[400px] text-pretty break-message",
!self
? "bg-neutral-100 dark:bg-neutral-800 rounded-tl-3xl rounded-tr-3xl rounded-br-3xl rounded-bl-md"
: "bg-blue-500 text-white rounded-tl-3xl rounded-tr-3xl rounded-br-md rounded-bl-3xl",
)}
>
<Message text={item.content} />
</div>
</div>
<div className="shrink-0 w-16 flex items-center justify-end">
<span className="text-xs text-right text-neutral-600 dark:text-neutral-400">
{time(item.created_at)}
</span>
</div>
</div>
);
},
[data],
);
return (
<div
key={idx + item.id}
className="flex items-center justify-between gap-3 my-1.5 px-3 border-l-2 border-transparent hover:border-blue-400"
>
<div
className={cn(
"flex-1 min-w-0 inline-flex",
self ? "justify-end" : "justify-start",
)}
>
<div
className={cn(
"select-text py-2 px-3 w-fit max-w-[400px] text-pretty break-message",
!self
? "bg-neutral-100 dark:bg-neutral-800 rounded-tl-3xl rounded-tr-3xl rounded-br-3xl rounded-bl-md"
: "bg-blue-500 text-white rounded-tl-3xl rounded-tr-3xl rounded-br-md rounded-bl-3xl",
)}
>
<Message text={item.content} />
</div>
</div>
<div className="shrink-0 w-16 flex items-center justify-end">
<span className="text-xs text-right text-neutral-600 dark:text-neutral-400">
{time(item.created_at)}
</span>
</div>
</div>
);
},
[data],
);
useEffect(() => {
const unlisten = listen<EventPayload>("event", async (data) => {
const event: NostrEvent = JSON.parse(data.payload.event);
const sender = data.payload.sender;
const receivers = getReceivers(event.tags);
const group = [account, id];
useEffect(() => {
const unlisten = listen<EventPayload>("event", async (data) => {
const event: NostrEvent = JSON.parse(data.payload.event);
const sender = data.payload.sender;
const receivers = getReceivers(event.tags);
const group = [account, id];
if (!group.includes(sender)) return;
if (!group.some((item) => receivers.includes(item))) return;
if (!group.includes(sender)) return;
if (!group.some((item) => receivers.includes(item))) return;
queryClient.setQueryData(["chats", id], (prevEvents: NostrEvent[]) => {
if (!prevEvents) return [event];
return [event, ...prevEvents];
});
queryClient.setQueryData(["chats", id], (prevEvents: NostrEvent[]) => {
if (!prevEvents) return [event];
return [event, ...prevEvents];
});
await queryClient.invalidateQueries({ queryKey: ["chats", id] });
});
await queryClient.invalidateQueries({ queryKey: ["chats", id] });
});
return () => {
unlisten.then((f) => f());
};
}, [account, id]);
return () => {
unlisten.then((f) => f());
};
}, [account, id]);
useEffect(() => {
if (!data?.length) return;
if (!ref.current) return;
if (!shouldStickToBottom.current) return;
useEffect(() => {
if (!data?.length) return;
if (!ref.current) return;
if (!shouldStickToBottom.current) return;
ref.current.scrollToIndex(data.length - 1, {
align: "end",
});
}, [data]);
ref.current.scrollToIndex(data.length - 1, {
align: "end",
});
}, [data]);
return (
<ScrollArea.Root
type={"scroll"}
scrollHideDelay={300}
className="overflow-hidden flex-1 w-full"
>
<ScrollArea.Viewport
ref={scrollRef}
className="relative h-full py-2 [&>div]:!flex [&>div]:flex-col [&>div]:justify-end [&>div]:min-h-full"
>
<Virtualizer
scrollRef={scrollRef as unknown as RefObject<HTMLElement>}
ref={ref}
shift={true}
onScroll={(offset) => {
if (!ref.current) return;
shouldStickToBottom.current =
offset - ref.current.scrollSize + ref.current.viewportSize >=
-1.5;
}}
>
{isLoading ? (
<>
<div className="flex items-center gap-3 my-1.5 px-3">
<div className="flex-1 min-w-0 inline-flex">
<div className="w-44 h-[35px] py-2 max-w-[400px] bg-neutral-100 dark:bg-neutral-800 animate-pulse rounded-tl-3xl rounded-tr-3xl rounded-br-3xl rounded-bl-md" />
</div>
</div>
<div className="flex items-center gap-3 my-1.5 px-3">
<div className="flex-1 min-w-0 inline-flex justify-end">
<div className="w-44 h-[35px] py-2 max-w-[400px] bg-blue-500 text-white animate-pulse rounded-tl-3xl rounded-tr-3xl rounded-br-md rounded-bl-3xl" />
</div>
</div>
</>
) : isError ? (
<div className="w-full h-56 flex items-center justify-center">
<div className="text-sm flex items-center gap-1.5">
Cannot load message. Please try again later.
</div>
</div>
) : !data?.length ? (
<div className="h-20 flex items-center justify-center">
<CoopIcon className="size-10 text-neutral-200 dark:text-neutral-800" />
</div>
) : (
data?.map((item) => (
<div
key={item[0]}
className="w-full flex flex-col items-center mt-3 gap-3"
>
<div className="text-xs text-center text-neutral-600 dark:text-neutral-400">
{item[0]}
</div>
<div className="w-full">
{item[1]
? item[1]
.sort((a, b) => a.created_at - b.created_at)
.map((item, idx) => renderItem(item, idx))
: null}
</div>
</div>
))
)}
</Virtualizer>
</ScrollArea.Viewport>
<ScrollArea.Scrollbar
className="flex select-none touch-none p-0.5 duration-[160ms] ease-out data-[orientation=vertical]:w-2"
orientation="vertical"
>
<ScrollArea.Thumb className="flex-1 bg-black/40 dark:bg-white/40 rounded-full relative before:content-[''] before:absolute before:top-1/2 before:left-1/2 before:-translate-x-1/2 before:-translate-y-1/2 before:w-full before:h-full before:min-w-[44px] before:min-h-[44px]" />
</ScrollArea.Scrollbar>
<ScrollArea.Corner className="bg-transparent" />
</ScrollArea.Root>
);
return (
<ScrollArea.Root
type={"scroll"}
scrollHideDelay={300}
className="overflow-hidden flex-1 w-full"
>
<ScrollArea.Viewport
ref={scrollRef}
className="relative h-full py-2 [&>div]:!flex [&>div]:flex-col [&>div]:justify-end"
>
<Virtualizer
scrollRef={scrollRef as unknown as RefObject<HTMLElement>}
ref={ref}
shift={true}
onScroll={(offset) => {
if (!ref.current) return;
shouldStickToBottom.current =
offset - ref.current.scrollSize + ref.current.viewportSize >=
-1.5;
}}
>
{isLoading ? (
<>
<div className="flex items-center gap-3 my-1.5 px-3">
<div className="flex-1 min-w-0 inline-flex">
<div className="w-44 h-[35px] py-2 max-w-[400px] bg-neutral-100 dark:bg-neutral-800 animate-pulse rounded-tl-3xl rounded-tr-3xl rounded-br-3xl rounded-bl-md" />
</div>
</div>
<div className="flex items-center gap-3 my-1.5 px-3">
<div className="flex-1 min-w-0 inline-flex justify-end">
<div className="w-44 h-[35px] py-2 max-w-[400px] bg-blue-500 text-white animate-pulse rounded-tl-3xl rounded-tr-3xl rounded-br-md rounded-bl-3xl" />
</div>
</div>
</>
) : isError ? (
<div className="w-full h-56 flex items-center justify-center">
<div className="text-sm flex items-center gap-1.5">
Cannot load message. Please try again later.
</div>
</div>
) : !data?.length ? (
<div className="h-20 flex items-center justify-center">
<CoopIcon className="size-10 text-neutral-200 dark:text-neutral-800" />
</div>
) : (
data?.map((item) => (
<div
key={item[0]}
className="w-full flex flex-col items-center mt-3 gap-3"
>
<div className="text-xs text-center text-neutral-600 dark:text-neutral-400">
{item[0]}
</div>
<div className="w-full">
{item[1]
? item[1]
.sort((a, b) => a.created_at - b.created_at)
.map((item, idx) => renderItem(item, idx))
: null}
</div>
</div>
))
)}
</Virtualizer>
</ScrollArea.Viewport>
<ScrollArea.Scrollbar
className="flex select-none touch-none p-0.5 duration-[160ms] ease-out data-[orientation=vertical]:w-2"
orientation="vertical"
>
<ScrollArea.Thumb className="flex-1 bg-black/40 dark:bg-white/40 rounded-full relative before:content-[''] before:absolute before:top-1/2 before:left-1/2 before:-translate-x-1/2 before:-translate-y-1/2 before:w-full before:h-full before:min-w-[44px] before:min-h-[44px]" />
</ScrollArea.Scrollbar>
<ScrollArea.Corner className="bg-transparent" />
</ScrollArea.Root>
);
}
function Message({ text }: { text: string }) {
const delimiter =
/((?:https?:\/\/)?(?:(?:[a-z0-9]?(?:[a-z0-9\-]{1,61}[a-z0-9])?\.[^\.|\s])+[a-z\.]*[a-z]+|(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3})(?::\d{1,5})*[a-z0-9.,_\/~#&=;%+?\-\\(\\)]*)/gi;
const delimiter =
/((?:https?:\/\/)?(?:(?:[a-z0-9]?(?:[a-z0-9\-]{1,61}[a-z0-9])?\.[^\.|\s])+[a-z\.]*[a-z]+|(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3})(?::\d{1,5})*[a-z0-9.,_\/~#&=;%+?\-\\(\\)]*)/gi;
return (
<>
{text.split(delimiter).map((word) => {
const match = word.match(delimiter);
if (match) {
const url = match[0];
return (
<a
href={url.startsWith("http") ? url : `http://${url}`}
target="_blank"
rel="noreferrer"
className="underline"
>
{url}
</a>
);
}
return word;
})}
</>
);
return (
<>
{text.split(delimiter).map((word) => {
const match = word.match(delimiter);
if (match) {
const url = match[0];
return (
<a
href={url.startsWith("http") ? url : `http://${url}`}
target="_blank"
rel="noreferrer"
className="underline"
>
{url}
</a>
);
}
return word;
})}
</>
);
}
function Form() {
const { id } = Route.useParams();
const inboxRelays = Route.useLoaderData();
const { id } = Route.useParams();
const inboxRelays = Route.useLoaderData();
const [newMessage, setNewMessage] = useState("");
const [attaches, setAttaches] = useState<string[]>([]);
const [isPending, startTransition] = useTransition();
const [newMessage, setNewMessage] = useState("");
const [attaches, setAttaches] = useState<string[]>([]);
const [isPending, startTransition] = useTransition();
const remove = (item: string) => {
setAttaches((prev) => prev.filter((att) => att !== item));
};
const remove = (item: string) => {
setAttaches((prev) => prev.filter((att) => att !== item));
};
const submit = () => {
startTransition(async () => {
if (!newMessage.length) return;
const submit = () => {
startTransition(async () => {
if (!newMessage.length) return;
const content = `${newMessage}\r\n${attaches.join("\r\n")}`;
const res = await commands.sendMessage(id, content);
const content = `${newMessage}\r\n${attaches.join("\r\n")}`;
const res = await commands.sendMessage(id, content);
if (res.status === "error") {
await message(res.error, {
title: "Send mesaage failed",
kind: "error",
});
return;
}
if (res.status === "error") {
await message(res.error, {
title: "Send mesaage failed",
kind: "error",
});
return;
}
setNewMessage("");
setAttaches([]);
});
};
setNewMessage("");
setAttaches([]);
});
};
return (
<div className="shrink-0 flex items-center justify-center px-3.5">
{!inboxRelays.length ? (
<div className="text-xs">
This user doesn't have inbox relays. You cannot send messages to them.
</div>
) : (
<div className="flex-1 flex flex-col justify-end">
{attaches?.length ? (
<div className="flex items-center gap-2">
{attaches.map((item, index) => (
<button
type="button"
key={item}
onClick={() => remove(item)}
className="relative"
>
<img
src={item}
alt={`File ${index}`}
className="aspect-square w-16 object-cover rounded-lg outline outline-1 -outline-offset-1 outline-black/10 dark:outline-black/50"
loading="lazy"
decoding="async"
/>
<span className="absolute -top-2 -right-2 size-4 flex items-center justify-center bg-neutral-100 dark:bg-neutral-900 rounded-full border border-neutral-200 dark:border-neutral-800">
<X className="size-2" />
</span>
</button>
))}
</div>
) : null}
<div className="h-12 w-full flex items-center gap-2">
<div className="inline-flex gap-1">
<AttachMedia onUpload={setAttaches} />
</div>
<input
placeholder="Message..."
value={newMessage}
onChange={(e) => setNewMessage(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") submit();
}}
className="flex-1 h-9 rounded-full px-3.5 bg-transparent border border-neutral-200 dark:border-neutral-800 focus:outline-none focus:border-blue-500 placeholder:text-neutral-400 dark:placeholder:text-neutral-600"
/>
<button
type="button"
title="Send message"
disabled={isPending}
onClick={() => submit()}
className="rounded-full size-9 inline-flex items-center justify-center bg-blue-300 hover:bg-blue-500 dark:bg-blue-700 dark:hover:bg-blue-800 text-white"
>
{isPending ? <Spinner /> : <ArrowUp className="size-5" />}
</button>
</div>
</div>
)}
</div>
);
return (
<div className="shrink-0 flex items-center justify-center px-3.5">
{!inboxRelays.length ? (
<div className="text-xs">
This user doesn't have inbox relays. You cannot send messages to them.
</div>
) : (
<div className="flex-1 flex flex-col justify-end">
{attaches?.length ? (
<div className="flex items-center gap-2">
{attaches.map((item, index) => (
<button
type="button"
key={item}
onClick={() => remove(item)}
className="relative"
>
<img
src={item}
alt={`File ${index}`}
className="aspect-square w-16 object-cover rounded-lg outline outline-1 -outline-offset-1 outline-black/10 dark:outline-black/50"
loading="lazy"
decoding="async"
/>
<span className="absolute -top-2 -right-2 size-4 flex items-center justify-center bg-neutral-100 dark:bg-neutral-900 rounded-full border border-neutral-200 dark:border-neutral-800">
<X className="size-2" />
</span>
</button>
))}
</div>
) : null}
<div className="h-12 w-full flex items-center gap-2">
<div className="inline-flex gap-1">
<AttachMedia onUpload={setAttaches} />
</div>
<input
placeholder="Message..."
value={newMessage}
onChange={(e) => setNewMessage(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") submit();
}}
className="flex-1 h-9 rounded-full px-3.5 bg-transparent border border-neutral-200 dark:border-neutral-800 focus:outline-none focus:border-blue-500 placeholder:text-neutral-400 dark:placeholder:text-neutral-600"
/>
<button
type="button"
title="Send message"
disabled={isPending}
onClick={() => submit()}
className="rounded-full size-9 inline-flex items-center justify-center bg-blue-300 hover:bg-blue-500 dark:bg-blue-700 dark:hover:bg-blue-800 text-white"
>
{isPending ? <Spinner /> : <ArrowUp className="size-5" />}
</button>
</div>
</div>
)}
</div>
);
}
function AttachMedia({
onUpload,
onUpload,
}: {
onUpload: Dispatch<SetStateAction<string[]>>;
onUpload: Dispatch<SetStateAction<string[]>>;
}) {
const [isPending, startTransition] = useTransition();
const [isPending, startTransition] = useTransition();
const attach = () => {
startTransition(async () => {
const file = await upload();
const attach = () => {
startTransition(async () => {
const file = await upload();
if (file) {
onUpload((prev) => [...prev, file]);
} else {
return;
}
});
};
if (file) {
onUpload((prev) => [...prev, file]);
} else {
return;
}
});
};
return (
<button
type="button"
title="Attach media"
onClick={() => attach()}
className="size-9 inline-flex items-center justify-center hover:bg-neutral-100 dark:hover:bg-neutral-800 rounded-full"
>
{isPending ? (
<Spinner className="size-4" />
) : (
<Paperclip className="size-5" />
)}
</button>
);
return (
<button
type="button"
title="Attach media"
onClick={() => attach()}
className="size-9 inline-flex items-center justify-center hover:bg-neutral-100 dark:hover:bg-neutral-800 rounded-full"
>
{isPending ? (
<Spinner className="size-4" />
) : (
<Paperclip className="size-5" />
)}
</button>
);
}

View File

@@ -3,14 +3,13 @@ import { ago, cn } from "@/commons";
import { Spinner } from "@/components/spinner";
import { User } from "@/components/user";
import {
ArrowRight,
CaretDown,
CirclesFour,
Plus,
X,
ArrowRight,
CaretDown,
CirclesFour,
Plus,
X,
} from "@phosphor-icons/react";
import * as Dialog from "@radix-ui/react-dialog";
import * as Progress from "@radix-ui/react-progress";
import * as ScrollArea from "@radix-ui/react-scroll-area";
import { useQuery } from "@tanstack/react-query";
import { Link, Outlet, createLazyFileRoute } from "@tanstack/react-router";
@@ -21,500 +20,462 @@ import { message } from "@tauri-apps/plugin-dialog";
import { open } from "@tauri-apps/plugin-shell";
import { type NostrEvent, nip19 } from "nostr-tools";
import {
type RefObject,
useCallback,
useEffect,
useRef,
useState,
useTransition,
type RefObject,
useCallback,
useEffect,
useRef,
useState,
useTransition,
} from "react";
import { Virtualizer } from "virtua";
type EventPayload = {
event: string;
sender: string;
event: string;
sender: string;
};
export const Route = createLazyFileRoute("/$account/_layout/chats")({
component: Screen,
component: Screen,
});
function Screen() {
return (
<div className="size-full flex">
<div
data-tauri-drag-region
className="shrink-0 w-[280px] h-full flex flex-col justify-between border-r border-black/5 dark:border-white/5"
>
<Header />
<ChatList />
</div>
<div className="flex-1 min-w-0 min-h-0 bg-white dark:bg-neutral-900 overflow-auto">
<Outlet />
</div>
</div>
);
return (
<div className="size-full flex">
<div
data-tauri-drag-region
className="shrink-0 w-[280px] h-full flex flex-col justify-between border-r border-black/5 dark:border-white/5"
>
<Header />
<ChatList />
</div>
<div className="flex-1 min-w-0 min-h-0 bg-white dark:bg-neutral-900 overflow-auto">
<Outlet />
</div>
</div>
);
}
function Header() {
const { platform } = Route.useRouteContext();
const { account } = Route.useParams();
const { platform } = Route.useRouteContext();
const { account } = Route.useParams();
return (
<div
data-tauri-drag-region
className={cn(
"z-[200] shrink-0 h-12 flex items-center justify-between",
platform === "macos" ? "pl-[78px] pr-3.5" : "px-3.5",
)}
>
<CurrentUser />
<div className="flex items-center justify-end gap-2">
<Link
to="/$account/contacts"
params={{ account }}
className="size-8 rounded-full inline-flex items-center justify-center bg-black/5 hover:bg-black/10 dark:bg-white/5 dark:hover:bg-white/10"
>
<CirclesFour className="size-4" />
</Link>
<Compose />
</div>
</div>
);
return (
<div
data-tauri-drag-region
className={cn(
"z-[200] shrink-0 h-12 flex items-center justify-between",
platform === "macos" ? "pl-[78px] pr-3.5" : "px-3.5",
)}
>
<CurrentUser />
<div className="flex items-center justify-end gap-2">
<Link
to="/$account/contacts"
params={{ account }}
className="size-8 rounded-full inline-flex items-center justify-center bg-black/5 hover:bg-black/10 dark:bg-white/5 dark:hover:bg-white/10"
>
<CirclesFour className="size-4" />
</Link>
<Compose />
</div>
</div>
);
}
function ChatList() {
const { account } = Route.useParams();
const { queryClient } = Route.useRouteContext();
const { isLoading, data } = useQuery({
queryKey: ["chats"],
queryFn: async () => {
const res = await commands.getChats();
const { account } = Route.useParams();
const { queryClient } = Route.useRouteContext();
const { isLoading, data } = useQuery({
queryKey: ["chats"],
queryFn: async () => {
const res = await commands.getChats();
if (res.status === "ok") {
const raw = res.data;
const events = raw.map((item) => JSON.parse(item) as NostrEvent);
if (res.status === "ok") {
const raw = res.data;
const events = raw.map((item) => JSON.parse(item) as NostrEvent);
return events;
} else {
throw new Error(res.error);
}
},
select: (data) => data.sort((a, b) => b.created_at - a.created_at),
refetchOnMount: false,
refetchOnWindowFocus: false,
});
return events;
} else {
throw new Error(res.error);
}
},
select: (data) => data.sort((a, b) => b.created_at - a.created_at),
refetchOnMount: false,
refetchOnWindowFocus: false,
});
const [isSync, setIsSync] = useState(false);
const [progress, setProgress] = useState(0);
useEffect(() => {
const unlisten = listen("synchronized", async () => {
await queryClient.invalidateQueries({ queryKey: ["chats"] });
});
useEffect(() => {
const timer = setInterval(
() => setProgress((prev) => (prev <= 100 ? prev + 4 : 100)),
1200,
);
return () => clearInterval(timer);
}, []);
return () => {
unlisten.then((f) => f());
};
}, []);
useEffect(() => {
const unlisten = listen("synchronized", async () => {
await queryClient.refetchQueries({ queryKey: ["chats"] });
setIsSync(true);
});
useEffect(() => {
const unlisten = listen<EventPayload>("event", async (data) => {
const chats: NostrEvent[] | undefined = await queryClient.getQueryData([
"chats",
]);
return () => {
unlisten.then((f) => f());
};
}, []);
if (chats) {
const event: NostrEvent = JSON.parse(data.payload.event);
const index = chats.findIndex((item) => item.pubkey === event.pubkey);
useEffect(() => {
const unlisten = listen<EventPayload>("event", async (data) => {
const chats: NostrEvent[] | undefined = await queryClient.getQueryData([
"chats",
]);
if (index === -1) {
queryClient.setQueryData(["chats"], (prevEvents: NostrEvent[]) => {
if (!prevEvents) return prevEvents;
if (event.pubkey === account) return;
if (chats) {
const event: NostrEvent = JSON.parse(data.payload.event);
const index = chats.findIndex((item) => item.pubkey === event.pubkey);
return [event, ...prevEvents];
});
} else {
const newEvents = [...chats];
if (index === -1) {
await queryClient.setQueryData(
["chats"],
(prevEvents: NostrEvent[]) => {
if (!prevEvents) return prevEvents;
if (event.pubkey === account) return;
newEvents[index] = {
...event,
};
return [event, ...prevEvents];
},
);
} else {
const newEvents = [...chats];
queryClient.setQueryData(["chats"], newEvents);
}
newEvents[index] = {
...event,
};
await queryClient.invalidateQueries({ queryKey: ["chats"] });
}
});
queryClient.setQueryData(["chats"], newEvents);
await queryClient.invalidateQueries({ queryKey: ["chats"] });
}
}
});
return () => {
unlisten.then((f) => f());
};
}, []);
return () => {
unlisten.then((f) => f());
};
}, []);
return (
<ScrollArea.Root
type={"scroll"}
scrollHideDelay={300}
className="relative overflow-hidden flex-1 w-full"
>
<ScrollArea.Viewport className="relative h-full px-1.5">
{isLoading ? (
<>
{[...Array(5).keys()].map((i) => (
<div
key={i}
className="flex items-center rounded-lg p-2 mb-1 gap-2"
>
<div className="size-9 rounded-full animate-pulse bg-black/10 dark:bg-white/10" />
<div className="size-4 w-20 rounded animate-pulse bg-black/10 dark:bg-white/10" />
</div>
))}
</>
) : isSync && !data?.length ? (
<div className="p-2">
<div className="px-2 h-12 w-full rounded-lg bg-black/5 dark:bg-white/5 flex items-center justify-center text-sm">
No chats.
</div>
</div>
) : (
data?.map((item) => (
<Link
key={item.id + item.pubkey}
to="/$account/chats/$id"
params={{ account, id: item.pubkey }}
>
{({ isActive, isTransitioning }) => (
<User.Provider pubkey={item.pubkey}>
<User.Root
className={cn(
"flex items-center rounded-lg p-2 mb-1 gap-2 hover:bg-black/5 dark:hover:bg-white/5",
isActive ? "bg-black/5 dark:bg-white/5" : "",
)}
>
<User.Avatar className="size-8 rounded-full" />
<div className="flex-1 inline-flex items-center justify-between text-sm">
<div className="inline-flex leading-tight">
<User.Name className="max-w-[8rem] truncate font-semibold" />
<span className="ml-1.5 text-neutral-500">
{account === item.pubkey ? "(you)" : ""}
</span>
</div>
{isTransitioning ? (
<Spinner className="size-4" />
) : (
<span className="leading-tight text-right text-neutral-600 dark:text-neutral-400">
{ago(item.created_at)}
</span>
)}
</div>
</User.Root>
</User.Provider>
)}
</Link>
))
)}
</ScrollArea.Viewport>
{!isSync ? <SyncPopup progress={progress} /> : null}
<ScrollArea.Scrollbar
className="flex select-none touch-none p-0.5 duration-[160ms] ease-out data-[orientation=vertical]:w-2"
orientation="vertical"
>
<ScrollArea.Thumb className="flex-1 bg-black/40 dark:bg-white/40 rounded-full relative before:content-[''] before:absolute before:top-1/2 before:left-1/2 before:-translate-x-1/2 before:-translate-y-1/2 before:w-full before:h-full before:min-w-[44px] before:min-h-[44px]" />
</ScrollArea.Scrollbar>
<ScrollArea.Corner className="bg-transparent" />
</ScrollArea.Root>
);
}
function SyncPopup({ progress }: { progress: number }) {
return (
<div className="absolute bottom-0 w-full h-36 flex flex-col justify-end">
<div className="absolute left-0 bottom-0 w-full h-32 gradient-mask-t-10 bg-white dark:bg-black" />
<div className="relative flex flex-col items-center gap-1.5 p-4">
<Progress.Root
className="relative overflow-hidden bg-black/20 dark:bg-white/20 rounded-full w-full h-1"
style={{
transform: "translateZ(0)",
}}
value={progress}
>
<Progress.Indicator
className="bg-blue-500 size-full transition-transform duration-[660ms] ease-[cubic-bezier(0.65, 0, 0.35, 1)]"
style={{ transform: `translateX(-${100 - progress}%)` }}
/>
</Progress.Root>
<span className="text-center text-xs">Syncing message...</span>
</div>
</div>
);
return (
<ScrollArea.Root
type={"scroll"}
scrollHideDelay={300}
className="relative overflow-hidden flex-1 w-full"
>
<ScrollArea.Viewport className="relative h-full px-1.5">
{isLoading ? (
<>
{[...Array(5).keys()].map((i) => (
<div
key={i}
className="flex items-center rounded-lg p-2 mb-1 gap-2"
>
<div className="size-9 rounded-full animate-pulse bg-black/10 dark:bg-white/10" />
<div className="size-4 w-20 rounded animate-pulse bg-black/10 dark:bg-white/10" />
</div>
))}
</>
) : !data?.length ? (
<div className="p-2">
<div className="px-2 h-12 w-full rounded-lg bg-black/5 dark:bg-white/5 flex items-center justify-center text-sm">
No chats.
</div>
</div>
) : (
data?.map((item) => (
<Link
key={item.id + item.pubkey}
to="/$account/chats/$id"
params={{ account, id: item.pubkey }}
>
{({ isActive, isTransitioning }) => (
<User.Provider pubkey={item.pubkey}>
<User.Root
className={cn(
"flex items-center rounded-lg p-2 mb-1 gap-2 hover:bg-black/5 dark:hover:bg-white/5",
isActive ? "bg-black/5 dark:bg-white/5" : "",
)}
>
<User.Avatar className="size-8 rounded-full" />
<div className="flex-1 inline-flex items-center justify-between text-sm">
<div className="inline-flex leading-tight">
<User.Name className="max-w-[8rem] truncate font-semibold" />
<span className="ml-1.5 text-neutral-500">
{account === item.pubkey ? "(you)" : ""}
</span>
</div>
{isTransitioning ? (
<Spinner className="size-4" />
) : (
<span className="leading-tight text-right text-neutral-600 dark:text-neutral-400">
{ago(item.created_at)}
</span>
)}
</div>
</User.Root>
</User.Provider>
)}
</Link>
))
)}
</ScrollArea.Viewport>
<ScrollArea.Scrollbar
className="flex select-none touch-none p-0.5 duration-[160ms] ease-out data-[orientation=vertical]:w-2"
orientation="vertical"
>
<ScrollArea.Thumb className="flex-1 bg-black/40 dark:bg-white/40 rounded-full relative before:content-[''] before:absolute before:top-1/2 before:left-1/2 before:-translate-x-1/2 before:-translate-y-1/2 before:w-full before:h-full before:min-w-[44px] before:min-h-[44px]" />
</ScrollArea.Scrollbar>
<ScrollArea.Corner className="bg-transparent" />
</ScrollArea.Root>
);
}
function Compose() {
const [isOpen, setIsOpen] = useState(false);
const [target, setTarget] = useState("");
const [newMessage, setNewMessage] = useState("");
const [isPending, startTransition] = useTransition();
const [isOpen, setIsOpen] = useState(false);
const [target, setTarget] = useState("");
const [newMessage, setNewMessage] = useState("");
const [isPending, startTransition] = useTransition();
const { account } = Route.useParams();
const { isLoading, data: contacts } = useQuery({
queryKey: ["contacts", account],
queryFn: async () => {
const res = await commands.getContactList();
const { account } = Route.useParams();
const { isLoading, data: contacts } = useQuery({
queryKey: ["contacts", account],
queryFn: async () => {
const res = await commands.getContactList();
if (res.status === "ok") {
return res.data;
} else {
return [];
}
},
refetchOnWindowFocus: false,
enabled: isOpen,
});
if (res.status === "ok") {
return res.data;
} else {
return [];
}
},
refetchOnWindowFocus: false,
enabled: isOpen,
});
const navigate = Route.useNavigate();
const scrollRef = useRef<HTMLDivElement>(null);
const navigate = Route.useNavigate();
const scrollRef = useRef<HTMLDivElement>(null);
const pasteFromClipboard = async () => {
const val = await readText();
setTarget(val);
};
const pasteFromClipboard = async () => {
const val = await readText();
setTarget(val);
};
const sendMessage = () => {
startTransition(async () => {
if (!newMessage.length) return;
if (!target.length) return;
if (!target.startsWith("npub1")) {
await message("You must enter the public key as npub", {
title: "Send Message",
kind: "error",
});
return;
}
const sendMessage = () => {
startTransition(async () => {
if (!newMessage.length) return;
if (!target.length) return;
if (!target.startsWith("npub1")) {
await message("You must enter the public key as npub", {
title: "Send Message",
kind: "error",
});
return;
}
const decoded = nip19.decode(target);
let id: string;
const decoded = nip19.decode(target);
let id: string;
if (decoded.type !== "npub") {
await message("You must enter the public key as npub", {
title: "Send Message",
kind: "error",
});
return;
} else {
id = decoded.data;
}
if (decoded.type !== "npub") {
await message("You must enter the public key as npub", {
title: "Send Message",
kind: "error",
});
return;
} else {
id = decoded.data;
}
// Connect to user's inbox relays
const connect = await commands.connectInboxRelays(target, false);
// Connect to user's inbox relays
const connect = await commands.connectInboxRelays(target, false);
// Send message
if (connect.status === "ok") {
const res = await commands.sendMessage(id, newMessage);
// Send message
if (connect.status === "ok") {
const res = await commands.sendMessage(id, newMessage);
if (res.status === "ok") {
setTarget("");
setNewMessage("");
setIsOpen(false);
if (res.status === "ok") {
setTarget("");
setNewMessage("");
setIsOpen(false);
navigate({
to: "/$account/chats/$id",
params: { account, id },
});
} else {
await message(res.error, { title: "Send Message", kind: "error" });
return;
}
} else {
await message(connect.error, {
title: "Connect Inbox Relays",
kind: "error",
});
return;
}
});
};
navigate({
to: "/$account/chats/$id",
params: { account, id },
});
} else {
await message(res.error, { title: "Send Message", kind: "error" });
return;
}
} else {
await message(connect.error, {
title: "Connect Inbox Relays",
kind: "error",
});
return;
}
});
};
return (
<Dialog.Root open={isOpen} onOpenChange={setIsOpen}>
<Dialog.Trigger asChild>
<button
type="button"
className="size-8 rounded-full inline-flex items-center justify-center bg-black/10 hover:bg-black/20 dark:bg-white/10 dark:hover:bg-white/20"
>
<Plus className="size-4" weight="bold" />
</button>
</Dialog.Trigger>
<Dialog.Portal>
<Dialog.Overlay className="bg-black/20 dark:bg-white/20 data-[state=open]:animate-overlay fixed inset-0" />
<Dialog.Content className="flex flex-col data-[state=open]:animate-content fixed top-[50%] left-[50%] w-full h-full max-h-[500px] max-w-[400px] translate-x-[-50%] translate-y-[-50%] rounded-xl bg-white dark:bg-neutral-900 shadow-[hsl(206_22%_7%_/_35%)_0px_10px_38px_-10px,_hsl(206_22%_7%_/_20%)_0px_10px_20px_-15px] focus:outline-none">
<div className="h-28 shrink-0 flex flex-col justify-end">
<div className="h-10 inline-flex items-center justify-between px-3.5 text-sm font-semibold text-neutral-600 dark:text-neutral-400">
<Dialog.Title>Send to</Dialog.Title>
<Dialog.Close asChild>
<button type="button">
<X className="size-4" />
</button>
</Dialog.Close>
</div>
<div className="flex items-center gap-1 px-3.5 border-b border-neutral-100 dark:border-neutral-800">
<span className="shrink-0 font-medium">To:</span>
<div className="flex-1 relative">
<input
placeholder="npub1..."
value={target}
onChange={(e) => setTarget(e.target.value)}
disabled={isPending}
className="w-full pr-14 h-9 bg-transparent focus:outline-none placeholder:text-neutral-400 dark:placeholder:text-neutral-600"
/>
<button
type="button"
onClick={() => pasteFromClipboard()}
className="absolute uppercase top-1/2 right-2 transform -translate-y-1/2 text-xs font-semibold text-blue-500"
>
Paste
</button>
</div>
</div>
<div className="flex items-center gap-1 px-3.5 border-b border-neutral-100 dark:border-neutral-800">
<span className="shrink-0 font-medium">Message:</span>
<input
placeholder="hello..."
value={newMessage}
onChange={(e) => setNewMessage(e.target.value)}
disabled={isPending}
className="flex-1 h-9 bg-transparent focus:outline-none placeholder:text-neutral-400 dark:placeholder:text-neutral-600"
/>
<button
type="button"
disabled={isPending || isLoading || !newMessage.length}
onClick={() => sendMessage()}
className="rounded-full size-7 inline-flex items-center justify-center bg-blue-300 hover:bg-blue-500 dark:bg-blue-700 dark:hover:bg-blue-800 text-white"
>
{isPending ? (
<Spinner className="size-4" />
) : (
<ArrowRight className="size-4" />
)}
</button>
</div>
</div>
<ScrollArea.Root
type={"scroll"}
scrollHideDelay={300}
className="overflow-hidden flex-1 size-full"
>
<ScrollArea.Viewport
ref={scrollRef}
className="relative h-full p-2"
>
<Virtualizer
scrollRef={scrollRef as unknown as RefObject<HTMLElement>}
overscan={1}
>
{isLoading ? (
<div className="h-[400px] flex items-center justify-center">
<Spinner className="size-4" />
</div>
) : !contacts?.length ? (
<div className="h-[400px] flex items-center justify-center">
<p className="text-sm">Contact is empty.</p>
</div>
) : (
contacts?.map((contact) => (
<button
key={contact}
type="button"
onClick={() => setTarget(contact)}
className="block w-full p-2 rounded-lg hover:bg-neutral-100 dark:hover:bg-neutral-800"
>
<User.Provider pubkey={contact}>
<User.Root className="flex items-center gap-2">
<User.Avatar className="size-8 rounded-full" />
<User.Name className="text-sm font-medium" />
</User.Root>
</User.Provider>
</button>
))
)}
</Virtualizer>
</ScrollArea.Viewport>
<ScrollArea.Scrollbar
className="flex select-none touch-none p-0.5 duration-[160ms] ease-out data-[orientation=vertical]:w-2"
orientation="vertical"
>
<ScrollArea.Thumb className="flex-1 bg-black/40 dark:bg-white/40 rounded-full relative before:content-[''] before:absolute before:top-1/2 before:left-1/2 before:-translate-x-1/2 before:-translate-y-1/2 before:w-full before:h-full before:min-w-[44px] before:min-h-[44px]" />
</ScrollArea.Scrollbar>
<ScrollArea.Corner className="bg-transparent" />
</ScrollArea.Root>
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
);
return (
<Dialog.Root open={isOpen} onOpenChange={setIsOpen}>
<Dialog.Trigger asChild>
<button
type="button"
className="size-8 rounded-full inline-flex items-center justify-center bg-black/10 hover:bg-black/20 dark:bg-white/10 dark:hover:bg-white/20"
>
<Plus className="size-4" weight="bold" />
</button>
</Dialog.Trigger>
<Dialog.Portal>
<Dialog.Overlay className="bg-black/20 dark:bg-white/20 data-[state=open]:animate-overlay fixed inset-0" />
<Dialog.Content className="flex flex-col data-[state=open]:animate-content fixed top-[50%] left-[50%] w-full h-full max-h-[500px] max-w-[400px] translate-x-[-50%] translate-y-[-50%] rounded-xl bg-white dark:bg-neutral-900 shadow-[hsl(206_22%_7%_/_35%)_0px_10px_38px_-10px,_hsl(206_22%_7%_/_20%)_0px_10px_20px_-15px] focus:outline-none">
<div className="h-28 shrink-0 flex flex-col justify-end">
<div className="h-10 inline-flex items-center justify-between px-3.5 text-sm font-semibold text-neutral-600 dark:text-neutral-400">
<Dialog.Title>Send to</Dialog.Title>
<Dialog.Close asChild>
<button type="button">
<X className="size-4" />
</button>
</Dialog.Close>
</div>
<div className="flex items-center gap-1 px-3.5 border-b border-neutral-100 dark:border-neutral-800">
<span className="shrink-0 font-medium">To:</span>
<div className="flex-1 relative">
<input
placeholder="npub1..."
value={target}
onChange={(e) => setTarget(e.target.value)}
disabled={isPending}
className="w-full pr-14 h-9 bg-transparent focus:outline-none placeholder:text-neutral-400 dark:placeholder:text-neutral-600"
/>
<button
type="button"
onClick={() => pasteFromClipboard()}
className="absolute uppercase top-1/2 right-2 transform -translate-y-1/2 text-xs font-semibold text-blue-500"
>
Paste
</button>
</div>
</div>
<div className="flex items-center gap-1 px-3.5 border-b border-neutral-100 dark:border-neutral-800">
<span className="shrink-0 font-medium">Message:</span>
<input
placeholder="hello..."
value={newMessage}
onChange={(e) => setNewMessage(e.target.value)}
disabled={isPending}
className="flex-1 h-9 bg-transparent focus:outline-none placeholder:text-neutral-400 dark:placeholder:text-neutral-600"
/>
<button
type="button"
disabled={isPending || isLoading || !newMessage.length}
onClick={() => sendMessage()}
className="rounded-full size-7 inline-flex items-center justify-center bg-blue-300 hover:bg-blue-500 dark:bg-blue-700 dark:hover:bg-blue-800 text-white"
>
{isPending ? (
<Spinner className="size-4" />
) : (
<ArrowRight className="size-4" />
)}
</button>
</div>
</div>
<ScrollArea.Root
type={"scroll"}
scrollHideDelay={300}
className="overflow-hidden flex-1 size-full"
>
<ScrollArea.Viewport
ref={scrollRef}
className="relative h-full p-2"
>
<Virtualizer
scrollRef={scrollRef as unknown as RefObject<HTMLElement>}
overscan={1}
>
{isLoading ? (
<div className="h-[400px] flex items-center justify-center">
<Spinner className="size-4" />
</div>
) : !contacts?.length ? (
<div className="h-[400px] flex items-center justify-center">
<p className="text-sm">Contact is empty.</p>
</div>
) : (
contacts?.map((contact) => (
<button
key={contact}
type="button"
onClick={() => setTarget(contact)}
className="block w-full p-2 rounded-lg hover:bg-neutral-100 dark:hover:bg-neutral-800"
>
<User.Provider pubkey={contact}>
<User.Root className="flex items-center gap-2">
<User.Avatar className="size-8 rounded-full" />
<User.Name className="text-sm font-medium" />
</User.Root>
</User.Provider>
</button>
))
)}
</Virtualizer>
</ScrollArea.Viewport>
<ScrollArea.Scrollbar
className="flex select-none touch-none p-0.5 duration-[160ms] ease-out data-[orientation=vertical]:w-2"
orientation="vertical"
>
<ScrollArea.Thumb className="flex-1 bg-black/40 dark:bg-white/40 rounded-full relative before:content-[''] before:absolute before:top-1/2 before:left-1/2 before:-translate-x-1/2 before:-translate-y-1/2 before:w-full before:h-full before:min-w-[44px] before:min-h-[44px]" />
</ScrollArea.Scrollbar>
<ScrollArea.Corner className="bg-transparent" />
</ScrollArea.Root>
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
);
}
function CurrentUser() {
const params = Route.useParams();
const navigate = Route.useNavigate();
const params = Route.useParams();
const navigate = Route.useNavigate();
const showContextMenu = useCallback(async (e: React.MouseEvent) => {
e.preventDefault();
const showContextMenu = useCallback(async (e: React.MouseEvent) => {
e.preventDefault();
const menuItems = await Promise.all([
MenuItem.new({
text: "Copy Public Key",
action: async () => {
const npub = nip19.npubEncode(params.account);
await writeText(npub);
},
}),
MenuItem.new({
text: "Settings",
action: () => navigate({ to: "/" }),
}),
MenuItem.new({
text: "Feedback",
action: async () => await open("https://github.com/lumehq/coop/issues"),
}),
PredefinedMenuItem.new({ item: "Separator" }),
MenuItem.new({
text: "Switch account",
action: () => navigate({ to: "/" }),
}),
]);
const menuItems = await Promise.all([
MenuItem.new({
text: "Copy Public Key",
action: async () => {
const npub = nip19.npubEncode(params.account);
await writeText(npub);
},
}),
MenuItem.new({
text: "Settings",
action: () => navigate({ to: "/" }),
}),
MenuItem.new({
text: "Feedback",
action: async () => await open("https://github.com/lumehq/coop/issues"),
}),
PredefinedMenuItem.new({ item: "Separator" }),
MenuItem.new({
text: "Switch account",
action: () => navigate({ to: "/" }),
}),
]);
const menu = await Menu.new({
items: menuItems,
});
const menu = await Menu.new({
items: menuItems,
});
await menu.popup().catch((e) => console.error(e));
}, []);
await menu.popup().catch((e) => console.error(e));
}, []);
return (
<button
type="button"
onClick={(e) => showContextMenu(e)}
className="h-8 inline-flex items-center gap-1.5"
>
<User.Provider pubkey={params.account}>
<User.Root className="shrink-0">
<User.Avatar className="size-8 rounded-full" />
</User.Root>
</User.Provider>
<CaretDown className="size-3 text-neutral-600 dark:text-neutral-400" />
</button>
);
return (
<button
type="button"
onClick={(e) => showContextMenu(e)}
className="h-8 inline-flex items-center gap-1.5"
>
<User.Provider pubkey={params.account}>
<User.Root className="shrink-0">
<User.Avatar className="size-8 rounded-full" />
</User.Root>
</User.Provider>
<CaretDown className="size-3 text-neutral-600 dark:text-neutral-400" />
</button>
);
}

View File

@@ -1,9 +1,9 @@
import { CoopIcon } from '@/icons/coop'
import { createLazyFileRoute } from '@tanstack/react-router'
import { CoopIcon } from "@/icons/coop";
import { createLazyFileRoute } from "@tanstack/react-router";
export const Route = createLazyFileRoute('/$account/_layout/chats/new')({
export const Route = createLazyFileRoute("/$account/_layout/chats/new")({
component: Screen,
})
});
function Screen() {
return (
@@ -13,8 +13,8 @@ function Screen() {
>
<CoopIcon className="size-10 text-neutral-200 dark:text-neutral-800" />
<h1 className="text-center font-bold text-neutral-300 dark:text-neutral-700">
coop on nostr.
let's gathering on nostr.
</h1>
</div>
)
);
}