8 Commits
Author SHA1 Message Date
reya 6a7bf17e6e fix multithread 2026-09-01 08:18:26 +07:00
reya 3290f71fa4 update gpui 2026-09-01 07:58:40 +07:00
reya f7f1ea7438 fix web performance 2026-08-31 21:11:18 +07:00
reya 070c6a7e87 fix assets 2026-08-31 17:51:31 +07:00
reya 963a641f39 fix build 2026-08-31 17:23:59 +07:00
reya ff20e51729 fix build 2026-08-31 17:23:50 +07:00
reya 2f834a0bcc chore: update deps 2026-08-31 16:54:38 +07:00
reya 49cd5cb9a0 chore: clean up 2026-08-03 09:53:12 +07:00
32 changed files with 1192 additions and 960 deletions
Generated
+493 -653
View File
File diff suppressed because it is too large Load Diff
+1 -2
View File
@@ -4,7 +4,7 @@ members = ["crates/*", "desktop", "web"]
default-members = ["desktop"] default-members = ["desktop"]
[workspace.package] [workspace.package]
version = "1.0.0-beta5" version = "1.0.0"
edition = "2024" edition = "2024"
publish = false publish = false
@@ -43,7 +43,6 @@ smallvec = "1.14.0"
smol = "2" smol = "2"
webbrowser = "1.0.4" webbrowser = "1.0.4"
tracing-subscriber = { version = "0.3.18", features = ["fmt"] } tracing-subscriber = { version = "0.3.18", features = ["fmt"] }
errno = { version = "0.3.14", default-features = false }
instant = "0.1" instant = "0.1"
[patch.crates-io] [patch.crates-io]
-62
View File
@@ -1,62 +0,0 @@
[workspace]
resolver = "2"
members = ["crates/*", "desktop", "web"]
default-members = ["desktop"]
[workspace.package]
version = "1.0.0-beta5"
edition = "2024"
publish = false
[workspace.dependencies]
# GPUI
gpui = { git = "https://github.com/zed-industries/zed" }
gpui_platform = { git = "https://github.com/zed-industries/zed", features = ["font-kit", "x11", "wayland"] }
gpui_linux = { git = "https://github.com/zed-industries/zed" }
gpui_windows = { git = "https://github.com/zed-industries/zed" }
gpui_macos = { git = "https://github.com/zed-industries/zed" }
gpui_tokio = { git = "https://github.com/zed-industries/zed" }
reqwest_client = { git = "https://github.com/zed-industries/zed" }
# Nostr
nostr-lmdb = { git = "https://github.com/rust-nostr/nostr" }
nostr-memory = { git = "https://github.com/rust-nostr/nostr" }
nostr-blossom = { git = "https://github.com/rust-nostr/nostr" }
nostr-gossip-memory = { git = "https://github.com/rust-nostr/nostr" }
nostr-connect = { git = "https://github.com/rust-nostr/nostr" }
nostr-sdk = { git = "https://github.com/rust-nostr/nostr" }
nostr = { git = "https://github.com/rust-nostr/nostr", features = [ "nip59", "nip49", "nip44" ] }
# Others
anyhow = "1.0.44"
chrono = { version = "0.4.38", features = ["wasmbind"] }
futures = "0.3"
itertools = "0.13.0"
log = "0.4"
oneshot = "0.1.10"
flume = { version = "0.11.1", default-features = false, features = ["async", "select"] }
rust-embed = { version = "8.5", features = ["include-exclude"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
schemars = "1"
smallvec = "1.14.0"
smol = "2"
webbrowser = "1.0.4"
tracing-subscriber = { version = "0.3.18", features = ["fmt"] }
errno = { version = "0.3.14", default-features = false }
instant = "0.1"
[patch.crates-io]
# Use stacker's psm version which may have better WASM support
psm = { git = "https://github.com/rust-lang/stacker", branch = "master" }
[profile.release]
strip = true
opt-level = "z"
lto = true
codegen-units = 1
panic = "abort"
[profile.profiling]
inherits = "release"
debug = true
+8
View File
@@ -8,4 +8,12 @@ publish.workspace = true
gpui.workspace = true gpui.workspace = true
anyhow.workspace = true anyhow.workspace = true
log.workspace = true log.workspace = true
[target.'cfg(not(target_family = "wasm"))'.dependencies]
rust-embed.workspace = true rust-embed.workspace = true
[target.'cfg(target_family = "wasm")'.dependencies]
futures.workspace = true
reqwest = { version = "0.12", default-features = false }
wasm-bindgen-futures = "0.4"
web-sys = { version = "0.3", features = ["Window", "Location"] }
+58
View File
@@ -0,0 +1,58 @@
//! Generates a compile-time manifest of the asset files served on wasm, so
//! the web entrypoint can preload them before the first frame.
//!
//! `WASM_ASSETS` is emitted into `OUT_DIR` and included by
//! `src/wasm_assets.rs` on wasm targets. Native builds keep using
//! `rust-embed` and ignore it.
use std::path::Path;
use std::{env, fs};
fn main() {
let manifest_dir = env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set by cargo");
let assets_dir = Path::new(&manifest_dir).join("../../assets");
let mut paths = Vec::new();
for dir in ["icons", "brand"] {
let dir_path = assets_dir.join(dir);
let entries = fs::read_dir(&dir_path).unwrap_or_else(|error| {
panic!(
"expected asset directory {} to exist: {error}",
dir_path.display()
)
});
for entry in entries {
let entry = entry.expect("failed to read asset directory entry");
if entry.file_type().is_ok_and(|t| t.is_file()) {
let name = entry.file_name().to_string_lossy().into_owned();
if !name.starts_with('.') {
paths.push(format!("{dir}/{name}"));
}
}
}
}
paths.sort();
let manifest = format!(
"/// Asset files served by the wasm asset loader. Generated by build.rs.\npub const WASM_ASSETS: &[&str] = &[\n{}\n];\n",
paths
.iter()
.map(|path| format!(" \"{path}\","))
.collect::<Vec<_>>()
.join("\n")
);
let out_dir = env::var("OUT_DIR").expect("OUT_DIR not set by cargo");
fs::write(Path::new(&out_dir).join("wasm_assets.rs"), manifest)
.expect("failed to write wasm asset manifest");
// Rerun when the asset files change (adding/removing files updates the
// directory mtime).
for dir in ["icons", "brand"] {
if let Ok(canonical) = assets_dir.join(dir).canonicalize() {
println!("cargo:rerun-if-changed={}", canonical.display());
}
}
println!("cargo:rerun-if-changed=build.rs");
}
+16 -48
View File
@@ -1,51 +1,19 @@
use anyhow::Context; //! Application assets for Coop.
use gpui::{App, AssetSource, Result, SharedString}; //!
use rust_embed::RustEmbed; //! ## Platform differences
//!
//! - **Native (desktop)**: assets are embedded into the binary at compile time
//! with `rust-embed`.
//! - **WASM (web)**: assets are downloaded on demand from `{endpoint}/assets/{path}`
//! and cached in memory. This keeps the WASM bundle size small.
#[derive(RustEmbed)] #[cfg(not(target_family = "wasm"))]
#[folder = "../../assets"] mod native_assets;
#[include = "fonts/**/*"]
#[include = "brand/**/*"]
#[include = "icons/**/*"]
#[include = "themes/**/*"]
#[exclude = "*.DS_Store"]
pub struct Assets;
impl AssetSource for Assets { #[cfg(target_family = "wasm")]
fn load(&self, path: &str) -> Result<Option<std::borrow::Cow<'static, [u8]>>> { mod wasm_assets;
Self::get(path)
.map(|f| Some(f.data))
.with_context(|| format!("loading asset at path {path:?}"))
}
fn list(&self, path: &str) -> Result<Vec<SharedString>> { #[cfg(not(target_family = "wasm"))]
Ok(Self::iter() pub use native_assets::Assets;
.filter_map(|p| { #[cfg(target_family = "wasm")]
if p.starts_with(path) { pub use wasm_assets::Assets;
Some(p.into())
} else {
None
}
})
.collect())
}
}
impl Assets {
/// Populate the [`TextSystem`] of the given [`AppContext`] with all `.ttf` fonts in the `fonts` directory.
pub fn load_fonts(&self, cx: &App) -> anyhow::Result<()> {
let font_paths = self.list("fonts")?;
let mut embedded_fonts = Vec::new();
for font_path in font_paths {
if font_path.ends_with(".ttf") {
let font_bytes = cx
.asset_source()
.load(&font_path)?
.expect("Assets should never return None");
embedded_fonts.push(font_bytes);
}
}
cx.text_system().add_fonts(embedded_fonts)
}
}
+63
View File
@@ -0,0 +1,63 @@
use std::borrow::Cow;
use anyhow::Context;
use gpui::{App, AssetSource, Result, SharedString};
use rust_embed::RustEmbed;
/// Native implementation using `rust-embed`: assets are embedded into the
/// binary at compile time.
#[derive(RustEmbed)]
#[folder = "../../assets"]
#[include = "fonts/**/*"]
#[include = "brand/**/*"]
#[include = "icons/**/*"]
#[include = "themes/**/*"]
#[exclude = "*.DS_Store"]
pub struct Assets;
impl Assets {
/// Create a new Assets instance. The endpoint parameter is ignored for
/// native builds.
pub fn new(_endpoint: impl Into<SharedString>) -> Self {
Self
}
}
impl AssetSource for Assets {
fn load(&self, path: &str) -> Result<Option<Cow<'static, [u8]>>> {
Self::get(path)
.map(|f| Some(f.data))
.with_context(|| format!("loading asset at path {path:?}"))
}
fn list(&self, path: &str) -> Result<Vec<SharedString>> {
Ok(Self::iter()
.filter_map(|p| {
if p.starts_with(path) {
Some(p.into())
} else {
None
}
})
.collect())
}
}
impl Assets {
/// Populate the [`TextSystem`] of the given [`AppContext`] with all `.ttf` fonts in the `fonts` directory.
pub fn load_fonts(&self, cx: &App) -> anyhow::Result<()> {
let font_paths = self.list("fonts")?;
let mut embedded_fonts = Vec::new();
for font_path in font_paths {
if font_path.ends_with(".ttf") {
let font_bytes = cx
.asset_source()
.load(&font_path)?
.expect("Assets should never return None");
embedded_fonts.push(font_bytes);
}
}
cx.text_system().add_fonts(embedded_fonts)
}
}
+176
View File
@@ -0,0 +1,176 @@
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use gpui::{AssetSource, Result, SharedString};
use wasm_bindgen_futures::spawn_local;
// Compile-time manifest of every asset file served on wasm (see build.rs).
include!(concat!(env!("OUT_DIR"), "/wasm_assets.rs"));
/// Path prefixes that the wasm loader serves. Fonts and themes are not
/// downloaded on web: the web platform bundles its own fonts, and the theme
/// registry falls back to the built-in default theme.
const SERVED_PREFIXES: [&str; 2] = ["icons/", "brand/"];
/// WASM implementation - download assets on demand.
///
/// Assets are fetched from `{endpoint}/assets/{path}` and cached in memory
/// after the first successful download. This keeps the WASM bundle small
/// while still providing the full asset set at runtime.
pub struct Assets {
endpoint: SharedString,
cache: Arc<RwLock<HashMap<String, Vec<u8>>>>,
pending: Arc<RwLock<HashMap<String, bool>>>,
}
impl Assets {
/// Create a new Assets instance backed by the given endpoint.
///
/// Assets are resolved as `{endpoint}/assets/{path}`. An empty endpoint
/// resolves against the current page origin (e.g. `/assets/icons/foo.svg`).
pub fn new(endpoint: impl Into<SharedString>) -> Self {
Self {
endpoint: endpoint.into(),
cache: Arc::new(RwLock::new(HashMap::new())),
pending: Arc::new(RwLock::new(HashMap::new())),
}
}
/// Absolute URL of the given asset path.
///
/// `reqwest` requires absolute URLs, so a relative endpoint is resolved
/// against the current page origin.
fn asset_url(&self, path: &str) -> String {
let endpoint = if self.endpoint.is_empty() {
web_sys::window()
.and_then(|window| window.location().origin().ok())
.unwrap_or_default()
} else {
self.endpoint.to_string()
};
format!("{endpoint}/assets/{path}")
}
/// Download every asset in [`WASM_ASSETS`] into the cache, in parallel,
/// before the app starts.
///
/// Preloading is required for two reasons:
/// - Assets loaded through GPUI's [`gpui::Asset`] machinery (e.g. `img()`)
/// cache failed loads and never retry them.
/// - SVG painting only re-attempts an empty load on the next repaint, so
/// an icon would stay invisible until the window happens to redraw.
pub async fn preload(&self) {
let downloads = WASM_ASSETS.iter().map(|path| async move {
let result = reqwest::get(self.asset_url(path)).await;
match result {
Ok(response) if response.status().is_success() => match response.bytes().await {
Ok(bytes) => {
if let Ok(mut cache) = self.cache.write() {
cache.insert(path.to_string(), bytes.to_vec());
}
}
Err(e) => {
log::warn!("Failed to read asset {}: {}", path, e);
}
},
Ok(response) => {
log::warn!(
"Failed to download asset {}: HTTP {}",
path,
response.status()
);
}
Err(e) => {
log::warn!("Failed to fetch asset {}: {}", path, e);
}
}
});
futures::future::join_all(downloads).await;
}
}
impl AssetSource for Assets {
fn load(&self, path: &str) -> Result<Option<Cow<'static, [u8]>>> {
if path.is_empty() {
return Ok(None);
}
// Only serve paths the web build actually ships.
if !SERVED_PREFIXES
.iter()
.any(|prefix| path.starts_with(prefix))
{
return Ok(None);
}
// Serve from the in-memory cache when available.
if let Ok(cache) = self.cache.read() {
if let Some(data) = cache.get(path) {
return Ok(Some(Cow::Owned(data.clone())));
}
}
// Kick off a single download per path; concurrent requests for the
// same path share it.
let is_pending = self
.pending
.read()
.map(|pending| pending.contains_key(path))
.unwrap_or(false);
if !is_pending {
if let Ok(mut pending) = self.pending.write() {
pending.insert(path.to_string(), true);
}
let url = self.asset_url(path);
let path_clone = path.to_string();
let cache = self.cache.clone();
let pending = self.pending.clone();
spawn_local(async move {
match reqwest::get(&url).await {
Ok(response) if response.status().is_success() => {
match response.bytes().await {
Ok(bytes) => {
if let Ok(mut cache) = cache.write() {
cache.insert(path_clone.clone(), bytes.to_vec());
}
}
Err(e) => {
log::warn!("Failed to read asset {}: {}", path_clone, e);
}
}
}
Ok(response) => {
log::warn!(
"Failed to download asset {}: HTTP {}",
path_clone,
response.status()
);
}
Err(e) => {
log::warn!("Failed to fetch asset {}: {}", path_clone, e);
}
}
// Allow retrying failed downloads on subsequent requests.
if let Ok(mut pending) = pending.write() {
pending.remove(&path_clone);
}
});
}
// The asset is not available yet. GPUI's SVG atlas does not cache
// empty loads, so the next repaint will call `load` again and find
// the asset in the cache once the download completes.
Ok(None)
}
fn list(&self, _path: &str) -> Result<Vec<SharedString>> {
// The asset manifest is not available at runtime on web; embedded
// directories are not listed.
Ok(Vec::new())
}
}
+1 -1
View File
@@ -11,7 +11,7 @@ publish = false
atomic-destructor = "0.2" atomic-destructor = "0.2"
event-listener = "5" event-listener = "5"
nostr.workspace = true nostr.workspace = true
opaquerr = "0.1" opaquerr = { version = "0.1", features = ["alloc"] }
serde.workspace = true serde.workspace = true
serde_json.workspace = true serde_json.workspace = true
smol.workspace = true smol.workspace = true
+34 -17
View File
@@ -290,34 +290,38 @@ impl ChatRegistry {
self.signal_consumer = Some(cx.spawn(async move |this, cx| { self.signal_consumer = Some(cx.spawn(async move |this, cx| {
while let Ok(message) = rx.recv_async().await { while let Ok(message) = rx.recv_async().await {
this.update(cx, |this, cx| {
// Drain the whole queue in a single update so a burst of
// events (e.g. history sync after login) collapses into
// one repaint instead of one per message (important on
// wasm, where everything runs on the main thread).
let mut batch = vec![message];
while let Ok(extra) = rx.try_recv() {
batch.push(extra);
}
for message in batch {
match message { match message {
Signal::Message(message) => { Signal::Message(message) => {
this.update(cx, |this, cx| {
this.new_message(message, cx); this.new_message(message, cx);
})?;
} }
Signal::InboxReady => { Signal::InboxReady => {
this.update(cx, |this, cx| {
this.get_messages(cx); this.get_messages(cx);
})?;
} }
Signal::Eose => { Signal::Eose => {
this.update(cx, |this, _cx| {
this.tracking.store(false, Ordering::Release); this.tracking.store(false, Ordering::Release);
})?;
this.update(cx, |this, cx| {
this.get_rooms(cx); this.get_rooms(cx);
})?;
} }
Signal::Error(failed) => { Signal::Error(failed) => {
trash.update(cx, |this, cx| { let _ = trash.update(cx, |this, cx| {
this.insert(failed); this.insert(failed);
cx.notify(); cx.notify();
})?; });
} }
}; };
} }
})?;
}
Ok(()) Ok(())
})); }));
@@ -365,7 +369,8 @@ impl ChatRegistry {
.query(filter) .query(filter)
.await .await
.unwrap_or_default() .unwrap_or_default()
.first_owned() .into_iter()
.next()
.is_some(); .is_some();
if !found { if !found {
@@ -397,7 +402,8 @@ impl ChatRegistry {
.database() .database()
.query(filter) .query(filter)
.await? .await?
.first_owned() .into_iter()
.next()
.ok_or(anyhow::anyhow!("No inbox relays found"))?; .ok_or(anyhow::anyhow!("No inbox relays found"))?;
let relays: Vec<RelayUrl> = nip17::extract_relay_list(&event).collect(); let relays: Vec<RelayUrl> = nip17::extract_relay_list(&event).collect();
@@ -656,15 +662,26 @@ impl ChatRegistry {
cx.background_spawn(async move { cx.background_spawn(async move {
let public_key = signer.get_public_key_async().await?; let public_key = signer.get_public_key_async().await?;
let contacts = client
// Query the latest contact list (previously `NostrDatabaseExt::contacts_public_keys`)
let filter = Filter::new()
.author(public_key)
.kind(Kind::ContactList)
.limit(1);
let contacts: HashSet<PublicKey> = client
.database() .database()
.contacts_public_keys(public_key) .query(filter)
.await .await
.unwrap_or_default()
.into_iter()
.next()
.map(|event| event.tags.public_keys().collect())
.unwrap_or_default(); .unwrap_or_default();
let filter = Filter::new() let filter = Filter::new()
.kind(Kind::ApplicationSpecificData) .kind(Kind::ApplicationSpecificData)
.custom_tag(SingleLetterTag::lowercase(Alphabet::K), "14"); .custom_tag(SingleLetterTag::LOWERCASE_K, "14");
let events = client.database().query(filter).await?; let events = client.database().query(filter).await?;
let mut grouped: HashMap<u64, Vec<UnsignedEvent>> = HashMap::new(); let mut grouped: HashMap<u64, Vec<UnsignedEvent>> = HashMap::new();
@@ -827,7 +844,7 @@ async fn set_rumor(client: &Client, id: EventId, rumor: &UnsignedEvent) -> Resul
async fn get_rumor(client: &Client, gift_wrap: EventId) -> Result<UnsignedEvent, Error> { async fn get_rumor(client: &Client, gift_wrap: EventId) -> Result<UnsignedEvent, Error> {
let filter = Filter::new().identifier(gift_wrap).limit(1); let filter = Filter::new().identifier(gift_wrap).limit(1);
if let Some(event) = client.database().query(filter).await?.first_owned() { if let Some(event) = client.database().query(filter).await?.into_iter().next() {
UnsignedEvent::from_json(event.content).map_err(|e| anyhow!(e)) UnsignedEvent::from_json(event.content).map_err(|e| anyhow!(e))
} else { } else {
Err(anyhow!("Event is not cached yet.")) Err(anyhow!("Event is not cached yet."))
+3 -6
View File
@@ -403,7 +403,7 @@ impl Room {
cx.background_spawn(async move { cx.background_spawn(async move {
let filter = Filter::new() let filter = Filter::new()
.kind(Kind::ApplicationSpecificData) .kind(Kind::ApplicationSpecificData)
.custom_tag(SingleLetterTag::lowercase(Alphabet::R), room_id); .custom_tag(SingleLetterTag::LOWERCASE_R, room_id);
let messages = client let messages = client
.database() .database()
@@ -461,13 +461,10 @@ impl Room {
// Add all receiver tags (no intermediate allocation) // Add all receiver tags (no intermediate allocation)
for public_key in self.members.iter().filter(|pk| *pk != &sender) { for public_key in self.members.iter().filter(|pk| *pk != &sender) {
let member = persons.read(cx).get(public_key, cx); let member = persons.read(cx).get(public_key, cx);
tags.push( tags.push(Tag::from(Nip01Tag::PublicKey {
Nip01Tag::PublicKey {
public_key: member.public_key(), public_key: member.public_key(),
relay_hint: member.messaging_relay_hint(), relay_hint: member.messaging_relay_hint(),
} }));
.to_tag(),
);
} }
// Construct a direct message rumor event // Construct a direct message rumor event
+11
View File
@@ -242,6 +242,16 @@ impl ChatPanel {
while let Ok(status) = rx.recv_async().await { while let Ok(status) = rx.recv_async().await {
{ {
let mut map = reports.write().unwrap(); let mut map = reports.write().unwrap();
// Drain the whole queue in a single update so bursts of
// send statuses collapse into one repaint (important on
// wasm, where everything runs on the main thread).
let mut statuses = vec![status];
while let Ok(extra) = rx.try_recv() {
statuses.push(extra);
}
for status in statuses {
let status_id = match &*status { let status_id = match &*status {
SendStatus::Ok { id, .. } => *id, SendStatus::Ok { id, .. } => *id,
SendStatus::Failed { id, .. } => *id, SendStatus::Failed { id, .. } => *id,
@@ -268,6 +278,7 @@ impl ChatPanel {
} }
} }
} }
}
this.update(cx, |_, cx| cx.notify()).ok(); this.update(cx, |_, cx| cx.notify()).ok();
} }
Ok(()) Ok(())
+2 -2
View File
@@ -4,13 +4,13 @@ use std::path::PathBuf;
use std::rc::Rc; use std::rc::Rc;
use std::sync::Arc; use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use instant::Duration;
use anyhow::{Context as AnyhowContext, Error, anyhow}; use anyhow::{Context as AnyhowContext, Error, anyhow};
use gpui::{ use gpui::{
App, AppContext, Context, Entity, EventEmitter, Global, IntoElement, ParentElement, App, AppContext, Context, Entity, EventEmitter, Global, IntoElement, ParentElement,
SharedString, Styled, Subscription, Task, Window, div, relative, SharedString, Styled, Subscription, Task, Window, div, relative,
}; };
use instant::Duration;
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use person::PersonRegistry; use person::PersonRegistry;
use settings::AppSettings; use settings::AppSettings;
@@ -414,7 +414,7 @@ impl DeviceRegistry {
.pubkey(app_pubkey) .pubkey(app_pubkey)
.limit(1); .limit(1);
match client.database().query(filter).await?.first_owned() { match client.database().query(filter).await?.into_iter().next() {
// Found an approval event // Found an approval event
Some(event) => Ok(Some(event)), Some(event) => Ok(Some(event)),
// No approval event found, construct a request event // No approval event found, construct a request event
+1
View File
@@ -15,3 +15,4 @@ anyhow.workspace = true
smallvec.workspace = true smallvec.workspace = true
flume.workspace = true flume.workspace = true
log.workspace = true log.workspace = true
futures.workspace = true
+42 -16
View File
@@ -3,7 +3,8 @@ use std::sync::RwLock;
use anyhow::{Error, anyhow}; use anyhow::{Error, anyhow};
use common::EventExt; use common::EventExt;
use gpui::{App, AppContext, Context, Entity, Global, Task, Window}; use futures::FutureExt;
use gpui::{App, AppContext, BackgroundExecutor, Context, Entity, Global, Task, Window};
use instant::Duration; use instant::Duration;
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use smallvec::{SmallVec, smallvec}; use smallvec::{SmallVec, smallvec};
@@ -72,13 +73,24 @@ impl PersonRegistry {
})); }));
let client3 = client.clone(); let client3 = client.clone();
let executor = cx.background_executor().clone();
tasks.push(cx.background_spawn(async move { tasks.push(cx.background_spawn(async move {
Self::handle_requests(&client3, &metadata_rx).await; Self::handle_requests(&client3, &metadata_rx, &executor).await;
})); }));
tasks.push(cx.spawn(async move |this, cx| { tasks.push(cx.spawn(async move |this, cx| {
while let Ok(event) = rx.recv_async().await { while let Ok(event) = rx.recv_async().await {
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
// Drain the whole queue in a single update so a burst of
// events collapses into one repaint instead of one per
// event (important on wasm, where everything runs on the
// main thread).
let mut dispatch = vec![event];
while let Ok(extra) = rx.try_recv() {
dispatch.push(extra);
}
for event in dispatch {
match event { match event {
Dispatch::Person(person) => { Dispatch::Person(person) => {
this.insert(person, cx); this.insert(person, cx);
@@ -90,6 +102,7 @@ impl PersonRegistry {
this.set_messaging_relays(&event, cx); this.set_messaging_relays(&event, cx);
} }
}; };
}
}) })
.ok(); .ok();
} }
@@ -156,24 +169,39 @@ impl PersonRegistry {
} }
/// Handle request for metadata /// Handle request for metadata
async fn handle_requests(client: &Client, rx: &flume::Receiver<PublicKey>) { ///
/// Requests are collected into batches and flushed when the batch is
/// full or the timeout expires.
///
/// Note: `flume::Selector::wait_timeout` is intentionally not used here:
/// it relies on `std::time::Instant` and `thread::park_timeout`, which are
/// unavailable on `wasm32-unknown-unknown` (the former panics, the latter
/// is a no-op that would turn the wait into a busy loop on the main
/// thread).
async fn handle_requests(
client: &Client,
rx: &flume::Receiver<PublicKey>,
executor: &BackgroundExecutor,
) {
let mut batch: HashSet<PublicKey> = HashSet::new(); let mut batch: HashSet<PublicKey> = HashSet::new();
loop { loop {
match flume::Selector::new() // Wait for the next request, or the batch timeout.
.recv(rx, |result| result.ok()) futures::select! {
.wait_timeout(Duration::from_secs(TIMEOUT)) result = rx.recv_async() => match result {
{ Ok(public_key) => {
Ok(Some(public_key)) => {
batch.insert(public_key); batch.insert(public_key);
// Process the batch if it's full // Keep collecting until the batch is full
if batch.len() >= 20 if batch.len() < 20 {
&& let Err(e) = get_metadata(client, std::mem::take(&mut batch)).await continue;
{
log::warn!("Failed to get metadata batch: {e}");
} }
} }
_ => { Err(_) => return,
},
_ = executor.timer(Duration::from_secs(TIMEOUT)).fuse() => {}
}
// Flush the batch
if !batch.is_empty() if !batch.is_empty()
&& let Err(e) = get_metadata(client, std::mem::take(&mut batch)).await && let Err(e) = get_metadata(client, std::mem::take(&mut batch)).await
{ {
@@ -181,8 +209,6 @@ impl PersonRegistry {
} }
} }
} }
}
}
/// Load all user profiles from the database /// Load all user profiles from the database
fn load(&mut self, cx: &mut Context<Self>) { fn load(&mut self, cx: &mut Context<Self>) {
+3 -3
View File
@@ -105,7 +105,7 @@ impl Person {
/// Get profile avatar /// Get profile avatar
pub fn avatar(&self) -> SharedString { pub fn avatar(&self) -> SharedString {
self.metadata() self.metadata
.picture .picture
.as_ref() .as_ref()
.filter(|picture| !picture.is_empty()) .filter(|picture| !picture.is_empty())
@@ -115,13 +115,13 @@ impl Person {
/// Get profile name /// Get profile name
pub fn name(&self) -> SharedString { pub fn name(&self) -> SharedString {
if let Some(display_name) = self.metadata().display_name.as_ref() if let Some(display_name) = self.metadata.display_name.as_ref()
&& !display_name.is_empty() && !display_name.is_empty()
{ {
return SharedString::from(display_name.trim()); return SharedString::from(display_name.trim());
} }
if let Some(name) = self.metadata().name.as_ref() if let Some(name) = self.metadata.name.as_ref()
&& !name.is_empty() && !name.is_empty()
{ {
return SharedString::from(name.trim()); return SharedString::from(name.trim());
+2
View File
@@ -3,8 +3,10 @@ use std::collections::HashMap;
use anyhow::{Error, anyhow}; use anyhow::{Error, anyhow};
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
use browser_signer_proxy::prelude::*; use browser_signer_proxy::prelude::*;
#[cfg(not(target_arch = "wasm32"))]
use common::config_dir; use common::config_dir;
use gpui::{App, AppContext, Context, Entity, EventEmitter, Global, Task, Window}; use gpui::{App, AppContext, Context, Entity, EventEmitter, Global, Task, Window};
#[cfg(not(target_arch = "wasm32"))]
use gpui_tokio::Tokio; use gpui_tokio::Tokio;
use instant::Duration; use instant::Duration;
use nostr_connect::prelude::*; use nostr_connect::prelude::*;
+3 -2
View File
@@ -14,15 +14,16 @@ chat = { path = "../chat" }
chat_ui = { path = "../chat_ui" } chat_ui = { path = "../chat_ui" }
settings = { path = "../settings" } settings = { path = "../settings" }
person = { path = "../person" } person = { path = "../person" }
auto_update = { path = "../auto_update" }
gpui.workspace = true gpui.workspace = true
nostr-sdk.workspace = true nostr-sdk.workspace = true
instant.workspace = true instant.workspace = true
nostr-connect.workspace = true nostr-connect.workspace = true
browser-signer-proxy = { path = "../browser-signer-proxy" }
anyhow.workspace = true anyhow.workspace = true
serde.workspace = true serde.workspace = true
log.workspace = true log.workspace = true
smallvec.workspace = true smallvec.workspace = true
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
auto_update = { path = "../auto_update" }
+6 -1
View File
@@ -172,6 +172,11 @@ impl ImportIdentity {
}); });
} }
// The "Connect via Web Extension" button is hidden on wasm (`is_wasm`),
// so this stub is never invoked in the browser.
#[cfg(target_arch = "wasm32")]
fn proxy(&mut self, _cx: &mut Context<Self>) {}
fn set_loading(&mut self, status: bool, cx: &mut Context<Self>) { fn set_loading(&mut self, status: bool, cx: &mut Context<Self>) {
self.loading = status; self.loading = status;
cx.notify(); cx.notify();
@@ -266,7 +271,7 @@ impl Render for ImportIdentity {
this.login(window, cx); this.login(window, cx);
})), })),
) )
.child(divider(cx)) .when(cfg!(target_arch = "wasm32"), |this| this.child(divider(cx)))
.when(!is_wasm, |this| { .when(!is_wasm, |this| {
this.child( this.child(
Button::new("proxy") Button::new("proxy")
+16 -5
View File
@@ -84,8 +84,20 @@ impl Screening {
let task: Task<Result<bool, Error>> = cx.background_spawn(async move { let task: Task<Result<bool, Error>> = cx.background_spawn(async move {
// Check if user is in contact list // Check if user is in contact list
let contacts = client.database().contacts_public_keys(current_user).await; let filter = Filter::new()
let followed = contacts.unwrap_or_default().contains(&public_key); .author(current_user)
.kind(Kind::ContactList)
.limit(1);
let followed = client
.database()
.query(filter)
.await
.unwrap_or_default()
.into_iter()
.next()
.map(|event| event.tags.public_keys().any(|k| k == public_key))
.unwrap_or(false);
Ok(followed) Ok(followed)
}); });
@@ -228,11 +240,10 @@ impl Screening {
let public_key = self.public_key; let public_key = self.public_key;
let task: Task<Result<(), Error>> = cx.background_spawn(async move { let task: Task<Result<(), Error>> = cx.background_spawn(async move {
let tag = Nip56Tag::PublicKey { let tag = Tag::from(Nip56Tag::PublicKey {
public_key, public_key,
report: Report::Impersonation, report: Report::Impersonation,
} });
.to_tag();
let event = EventBuilder::new(Kind::Reporting, "") let event = EventBuilder::new(Kind::Reporting, "")
.tag(tag) .tag(tag)
+27 -10
View File
@@ -2,6 +2,7 @@ use std::sync::Arc;
use ::settings::AppSettings; use ::settings::AppSettings;
use anyhow::Error; use anyhow::Error;
#[cfg(not(target_arch = "wasm32"))]
use auto_update::AutoUpdater; use auto_update::AutoUpdater;
use chat::{ChatEvent, ChatRegistry}; use chat::{ChatEvent, ChatRegistry};
use common::{CoopImageCache, download_dir}; use common::{CoopImageCache, download_dir};
@@ -379,6 +380,7 @@ impl Workspace {
Command::ImportEncryption => { Command::ImportEncryption => {
self.import_encryption(window, cx); self.import_encryption(window, cx);
} }
#[cfg(not(target_arch = "wasm32"))]
Command::Update => { Command::Update => {
let auto_updater = AutoUpdater::global(cx); let auto_updater = AutoUpdater::global(cx);
auto_updater.update(cx, |this, cx| { auto_updater.update(cx, |this, cx| {
@@ -387,6 +389,9 @@ impl Workspace {
}); });
}); });
} }
// Auto-update is a desktop-only feature; no-op in the browser.
#[cfg(target_arch = "wasm32")]
Command::Update => {}
} }
} }
@@ -563,7 +568,8 @@ impl Workspace {
let avatar = avatar.clone(); let avatar = avatar.clone();
let name = name.clone(); let name = name.clone();
this.min_w(px(256.)) let menu = this
.min_w(px(256.))
.item(PopupMenuItem::element(move |_window, cx| { .item(PopupMenuItem::element(move |_window, cx| {
h_flex() h_flex()
.gap_1p5() .gap_1p5()
@@ -593,13 +599,17 @@ impl Workspace {
IconName::Sun, IconName::Sun,
Box::new(Command::ToggleTheme), Box::new(Command::ToggleTheme),
) )
.separator() .separator();
.menu_with_icon(
// Auto-update is a desktop-only feature; there is no updater in the browser.
#[cfg(not(target_arch = "wasm32"))]
let menu = menu.menu_with_icon(
"Check for Updates", "Check for Updates",
IconName::Device, IconName::Device,
Box::new(Command::Update), Box::new(Command::Update),
) );
.menu_with_icon(
menu.menu_with_icon(
"Settings", "Settings",
IconName::Settings, IconName::Settings,
Box::new(Command::ShowSettings), Box::new(Command::ShowSettings),
@@ -610,7 +620,6 @@ impl Workspace {
} }
fn titlebar_right(&mut self, cx: &mut Context<Self>) -> impl IntoElement { fn titlebar_right(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
let updater = AutoUpdater::global(cx);
let chat = ChatRegistry::global(cx); let chat = ChatRegistry::global(cx);
let nip4e_enabled = AppSettings::get_nip4e(cx); let nip4e_enabled = AppSettings::get_nip4e(cx);
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
@@ -622,15 +631,23 @@ impl Workspace {
let persons = PersonRegistry::global(cx); let persons = PersonRegistry::global(cx);
let profile = persons.read(cx).get(&public_key, cx); let profile = persons.read(cx).get(&public_key, cx);
let announcement = profile.announcement(); let announcement = profile.announcement();
let updater_idle = updater.read(cx).idle(cx);
h_flex() let titlebar = h_flex()
.when(!cx.theme().platform.is_mac(), |this| this.pr_2()) .when(!cx.theme().platform.is_mac(), |this| this.pr_2())
.gap_2() .gap_2();
.when(!updater_idle, |this| {
// Auto-update is a desktop-only feature; there is no updater in the browser.
#[cfg(not(target_arch = "wasm32"))]
let titlebar = {
let updater = AutoUpdater::global(cx);
let updater_idle = updater.read(cx).idle(cx);
titlebar.when(!updater_idle, |this| {
let status = updater.read(cx).status(cx); let status = updater.read(cx).status(cx);
this.child(div().text_xs().italic().child(status)) this.child(div().text_xs().italic().child(status))
}) })
};
titlebar
.when(nip4e_enabled, |this| { .when(nip4e_enabled, |this| {
this.child( this.child(
Button::new("key") Button::new("key")
+14 -1
View File
@@ -88,7 +88,20 @@ impl ContactListPanel {
}; };
let task: Task<Result<HashSet<PublicKey>, Error>> = cx.background_spawn(async move { let task: Task<Result<HashSet<PublicKey>, Error>> = cx.background_spawn(async move {
let contact_list = client.database().contacts_public_keys(public_key).await?; let filter = Filter::new()
.author(public_key)
.kind(Kind::ContactList)
.limit(1);
let contact_list: HashSet<PublicKey> = client
.database()
.query(filter)
.await?
.into_iter()
.next()
.map(|event| event.tags.public_keys().collect())
.unwrap_or_default();
Ok(contact_list) Ok(contact_list)
}); });
@@ -93,7 +93,7 @@ impl MessagingRelayPanel {
.author(public_key) .author(public_key)
.limit(1); .limit(1);
if let Some(event) = client.database().query(filter).await?.first_owned() { if let Some(event) = client.database().query(filter).await?.into_iter().next() {
Ok(nip17::extract_relay_list(&event).collect()) Ok(nip17::extract_relay_list(&event).collect())
} else { } else {
Err(anyhow!("Not found.")) Err(anyhow!("Not found."))
@@ -177,7 +177,7 @@ impl MessagingRelayPanel {
let tags: Vec<Tag> = self let tags: Vec<Tag> = self
.relays .relays
.iter() .iter()
.map(|relay| Nip17Tag::Relay(relay.to_owned()).to_tag()) .map(|relay| Tag::from(Nip17Tag::Relay(relay.to_owned())))
.collect(); .collect();
// Set updating state // Set updating state
+1 -1
View File
@@ -111,7 +111,7 @@ impl RelayListPanel {
.author(public_key) .author(public_key)
.limit(1); .limit(1);
if let Some(event) = client.database().query(filter).await?.first_owned() { if let Some(event) = client.database().query(filter).await?.into_iter().next() {
Ok(nip65::extract_relay_list(&event).collect()) Ok(nip65::extract_relay_list(&event).collect())
} else { } else {
Err(anyhow!("Not found.")) Err(anyhow!("Not found."))
+14 -1
View File
@@ -158,7 +158,20 @@ impl Sidebar {
}; };
let task: Task<Result<HashSet<PublicKey>, Error>> = cx.background_spawn(async move { let task: Task<Result<HashSet<PublicKey>, Error>> = cx.background_spawn(async move {
let contacts = client.database().contacts_public_keys(public_key).await?; let filter = Filter::new()
.author(public_key)
.kind(Kind::ContactList)
.limit(1);
let contacts: HashSet<PublicKey> = client
.database()
.query(filter)
.await?
.into_iter()
.next()
.map(|event| event.tags.public_keys().collect())
.unwrap_or_default();
Ok(contacts) Ok(contacts)
}); });
+1 -1
View File
@@ -14,7 +14,7 @@ product-name = "Coop"
description = "Chat Freely, Stay Private on Nostr" description = "Chat Freely, Stay Private on Nostr"
identifier = "su.reya.coop" identifier = "su.reya.coop"
category = "SocialNetworking" category = "SocialNetworking"
version = "1.0.0-beta5" version = "1.0.0"
out-dir = "../dist" out-dir = "../dist"
before-packaging-command = "cargo build --release" before-packaging-command = "cargo build --release"
resources = ["Cargo.toml", "src"] resources = ["Cargo.toml", "src"]
-51
View File
@@ -1,51 +0,0 @@
[package]
name = "coop"
version.workspace = true
edition.workspace = true
publish.workspace = true
[[bin]]
name = "coop"
path = "src/main.rs"
[package.metadata.packager]
name = "Coop"
product-name = "Coop"
description = "Chat Freely, Stay Private on Nostr"
identifier = "su.reya.coop"
category = "SocialNetworking"
version = "1.0.0-beta5"
out-dir = "../dist"
before-packaging-command = "cargo build --release"
resources = ["Cargo.toml", "src"]
icons = [
"resources/32x32.png",
"resources/128x128.png",
"resources/128x128@2x.png",
"resources/icon.icns",
"resources/icon.ico",
]
[dependencies]
assets = { path = "../crates/assets" }
workspace = { path = "../crates/workspace" }
ui = { path = "../crates/ui" }
theme = { path = "../crates/theme" }
common = { path = "../crates/common" }
state = { path = "../crates/state" }
device = { path = "../crates/device" }
chat = { path = "../crates/chat" }
settings = { path = "../crates/settings" }
auto_update = { path = "../crates/auto_update" }
person = { path = "../crates/person" }
gpui.workspace = true
gpui_platform.workspace = true
gpui_linux.workspace = true
gpui_windows.workspace = true
gpui_macos.workspace = true
reqwest_client.workspace = true
log.workspace = true
tracing-subscriber.workspace = true
nostr-sdk.workspace = true
+4 -4
View File
@@ -55,8 +55,8 @@ flatpak run --command=flatpak-builder-lint org.flatpak.Builder repo repo
Ensure you have: Ensure you have:
- [ ] Committed all changes - [ ] Committed all changes
- [ ] Tagged the release: `git tag -a v1.0.0-beta2 -m "Release v1.0.0-beta2"` - [ ] Tagged the release: `git tag -a v1.0.0 -m "Release v1.0.0"`
- [ ] Pushed the tag: `git push origin v1.0.0-beta2` - [ ] Pushed the tag: `git push origin v1.0.0`
- [ ] Run `./script/prepare-flathub.sh` to regenerate files - [ ] Run `./script/prepare-flathub.sh` to regenerate files
### 2. Fork and Submit ### 2. Fork and Submit
@@ -101,8 +101,8 @@ git push origin su.reya.coop
To release a new version: To release a new version:
1. Update version in workspace `Cargo.toml` 1. Update version in workspace `Cargo.toml`
2. Tag the new release: `git tag -a v1.0.0-beta3 -m "Release v1.0.0-beta3"` 2. Tag the new release: `git tag -a v1.0.0 -m "Release v1.0.0"`
3. Push the tag: `git push origin v1.0.0-beta3` 3. Push the tag: `git push origin v1.0.0`
4. Run `./script/prepare-flathub.sh` to regenerate 4. Run `./script/prepare-flathub.sh` to regenerate
5. Clone the flathub repo: `git clone https://github.com/flathub/su.reya.coop.git` 5. Clone the flathub repo: `git clone https://github.com/flathub/su.reya.coop.git`
6. Update the manifest with new commit/tag and hashes 6. Update the manifest with new commit/tag and hashes
+3
View File
@@ -30,6 +30,9 @@ console_error_panic_hook = "0.1"
tracing-wasm = "0.2" tracing-wasm = "0.2"
console_log = "1.0" console_log = "1.0"
wasm-bindgen = "0.2" wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
web-sys = { version = "0.3", features = ["Window", "Performance"] }
universal-time = { git = "https://github.com/shadowylab/universal-time" } universal-time = { git = "https://github.com/shadowylab/universal-time" }
[target.'cfg(target_arch = "wasm32")'.dependencies] [target.'cfg(target_arch = "wasm32")'.dependencies]
+5
View File
@@ -36,6 +36,11 @@ if [[ "$(uname)" == "Darwin" ]]; then
fi fi
# Step 1: Build WASM # Step 1: Build WASM
#
# Single-threaded build: `+bulk-memory` only. The multithreaded web backend
# is disabled in `web/src/lib.rs` (gpui's wasm workers freeze their JS event
# loop in `Atomics.wait`, which breaks nostr-sdk's spawn_local-driven client
# and the WebSocket transport), so no atomics/shared-memory flags here.
echo -e "${GREEN}Step 1: Building WASM...${NC}" echo -e "${GREEN}Step 1: Building WASM...${NC}"
cd "$PROJECT_ROOT" cd "$PROJECT_ROOT"
export CARGO_TARGET_DIR="$PROJECT_ROOT/target" export CARGO_TARGET_DIR="$PROJECT_ROOT/target"
+117 -10
View File
@@ -1,4 +1,8 @@
use std::borrow::Cow;
use std::cell::RefCell;
use gpui::*; use gpui::*;
use theme::{Theme, ThemeMode};
use ui::Root; use ui::Root;
use universal_time::{Instant, MonotonicClock, SystemTime, WallClock, define_time_provider}; use universal_time::{Instant, MonotonicClock, SystemTime, WallClock, define_time_provider};
use wasm_bindgen::prelude::*; use wasm_bindgen::prelude::*;
@@ -7,20 +11,64 @@ struct CustomTimeProvider;
impl WallClock for CustomTimeProvider { impl WallClock for CustomTimeProvider {
fn system_time(&self) -> SystemTime { fn system_time(&self) -> SystemTime {
SystemTime::from_unix_duration(instant::Duration::from_secs(0)) // Browser wall clock: milliseconds since the Unix epoch.
let millis = js_sys::Date::now();
SystemTime::from_unix_duration(instant::Duration::from_millis(millis as u64))
} }
} }
impl MonotonicClock for CustomTimeProvider { impl MonotonicClock for CustomTimeProvider {
fn instant(&self) -> Instant { fn instant(&self) -> Instant {
Instant::from_ticks(instant::Duration::from_secs(0)) // `performance.now()` is monotonic; fall back to the wall clock if
// it's unavailable.
let millis = web_sys::window()
.and_then(|window| window.performance())
.map(|performance| performance.now())
.unwrap_or_else(js_sys::Date::now);
Instant::from_ticks(instant::Duration::from_millis(millis as u64))
} }
} }
define_time_provider!(CustomTimeProvider); define_time_provider!(CustomTimeProvider);
thread_local! {
static APPLICATION: RefCell<Option<ApplicationHandle>> = const { RefCell::new(None) };
}
/// Applies a theme mode and restores the bundled web fonts.
///
/// `Theme::change` reapplies the theme config, which can carry its own font
/// family; host system fonts are unavailable in wasm, so the bundled Inter
/// fonts are put back afterwards.
fn apply_theme(mode: ThemeMode, cx: &mut App) {
Theme::change(mode, None, cx);
Theme::global_mut(cx).font_family = "Inter".into();
}
/// Switches the app between light and dark after it is running.
///
/// The embedding page calls this to keep the app in sync with its own
/// appearance.
#[cfg(target_family = "wasm")]
#[wasm_bindgen] #[wasm_bindgen]
pub fn run() -> Result<(), JsValue> { pub fn set_theme(dark: bool) {
let mode = if dark {
ThemeMode::Dark
} else {
ThemeMode::Light
};
APPLICATION.with(|application| {
if let Some(handle) = application.borrow().as_ref() {
handle.update(|cx| {
apply_theme(mode, cx);
cx.refresh_windows();
});
}
});
}
#[wasm_bindgen]
pub async fn run() -> Result<(), JsValue> {
console_error_panic_hook::set_once(); console_error_panic_hook::set_once();
// Initialize logging to browser console // Initialize logging to browser console
@@ -37,16 +85,67 @@ pub fn run() -> Result<(), JsValue> {
#[cfg(target_family = "wasm")] #[cfg(target_family = "wasm")]
let app = { let app = {
let app = gpui_platform::single_threaded_web(); // Assets are not embedded in the WASM bundle; they are served from
// the `/assets/...` URL prefix (see `web/www/vite.config.js`) and
// downloaded by the `assets` crate.
let assets = assets::Assets::new("");
// Temporary fix: intentionally leak the `Rc<AppCell>` to keep the application alive // Download every icon and brand asset before the first frame: brand
struct WasmApplication(std::rc::Rc<AppCell>); // images are loaded through GPUI's image cache, which does not retry
let wasm_app = unsafe { std::mem::transmute::<Application, WasmApplication>(app) }; // failed loads, and pre-caching the icons lets them render
std::mem::forget(wasm_app.0.clone()); // immediately instead of waiting for a repaint.
unsafe { std::mem::transmute::<WasmApplication, Application>(wasm_app) } assets.preload().await;
// NOTE: the multithreaded web backend (application_with_web_backend)
// cannot host this app's backend. gpui's wasm background workers
// block on `Atomics.wait` while idle, freezing their JS event loop,
// so `spawn_local`-driven tasks (nostr-sdk's client actor, the
// WebSocket transport) and fetch promises never make progress on a
// worker thread. Everything must run on the main thread.
gpui_platform::single_threaded_web().with_assets(assets)
}; };
app.run(|cx| { let launch = move |cx: &mut App| {
// Load the embedded Inter font stack for WASM, where host system
// fonts are unavailable. Inter is the app's UI font on Linux; the
// wasm build reuses it so the web app matches the desktop look.
let inter_regular =
Cow::Borrowed(include_bytes!("../../assets/fonts/Inter/Inter-Regular.ttf").as_slice());
let inter_italic =
Cow::Borrowed(include_bytes!("../../assets/fonts/Inter/Inter-Italic.ttf").as_slice());
let inter_medium =
Cow::Borrowed(include_bytes!("../../assets/fonts/Inter/Inter-Medium.ttf").as_slice());
let inter_medium_italic = Cow::Borrowed(
include_bytes!("../../assets/fonts/Inter/Inter-MediumItalic.ttf").as_slice(),
);
let inter_semibold =
Cow::Borrowed(include_bytes!("../../assets/fonts/Inter/Inter-SemiBold.ttf").as_slice());
let inter_semibold_italic = Cow::Borrowed(
include_bytes!("../../assets/fonts/Inter/Inter-SemiBoldItalic.ttf").as_slice(),
);
let inter_bold =
Cow::Borrowed(include_bytes!("../../assets/fonts/Inter/Inter-Bold.ttf").as_slice());
let inter_bold_italic = Cow::Borrowed(
include_bytes!("../../assets/fonts/Inter/Inter-BoldItalic.ttf").as_slice(),
);
cx.text_system()
.add_fonts(vec![
inter_regular,
inter_italic,
inter_medium,
inter_medium_italic,
inter_semibold,
inter_semibold_italic,
inter_bold,
inter_bold_italic,
])
.expect("Failed to load fonts");
// Apply the system appearance before the first frame, so the app
// never flashes the default light theme.
apply_theme(cx.window_appearance().into(), cx);
// Open the root window // Open the root window
cx.open_window(WindowOptions::default(), |window, cx| { cx.open_window(WindowOptions::default(), |window, cx| {
// Initialize components // Initialize components
@@ -78,7 +177,15 @@ pub fn run() -> Result<(), JsValue> {
.expect("Failed to open window. Please restart the application."); .expect("Failed to open window. Please restart the application.");
cx.activate(true); cx.activate(true);
};
#[cfg(target_family = "wasm")]
APPLICATION.with(|application| {
*application.borrow_mut() = Some(app.run_embedded(launch));
}); });
#[cfg(not(target_family = "wasm"))]
app.run(launch);
Ok(()) Ok(())
} }
+7 -3
View File
@@ -10,7 +10,11 @@ export default defineConfig({
viteStaticCopy({ viteStaticCopy({
targets: [ targets: [
{ {
src: path.resolve(__dirname, "../../../assets/icons"), src: path.resolve(__dirname, "../../assets/icons"),
dest: "assets",
},
{
src: path.resolve(__dirname, "../../assets/brand"),
dest: "assets", dest: "assets",
}, },
], ],
@@ -19,9 +23,9 @@ export default defineConfig({
name: "serve-assets", name: "serve-assets",
configureServer(server) { configureServer(server) {
server.middlewares.use( server.middlewares.use(
"/coop/assets", "/assets",
(req, res, next) => { (req, res, next) => {
const assetsPath = path.resolve(__dirname, "../../../assets"); const assetsPath = path.resolve(__dirname, "../../assets");
const filePath = path.join( const filePath = path.join(
assetsPath, assetsPath,
req.url.replace("/assets", ""), req.url.replace("/assets", ""),