feat(tauri): custom windows titlebar

- add fake windows window snapping overlay like a native titlebar
- add sync status inside the titlebar
- upgrade framer-motion package to motion
- add service worker tauri exceptions 
- add automatically generated tauri typescript bindings
This commit is contained in:
hazre committed 2026-03-12 16:57:24 +01:00
1 parent e01c01cfca
commit 6932dcbcb1
28 files changed
+1720 -100

No files matched your search

+2
View File
@@ -38,6 +38,7 @@
"@tauri-apps/api": "2.10.1",
"@tauri-apps/plugin-deep-link": "2.4.7",
"@tauri-apps/plugin-opener": "2.5.3",
"@tauri-apps/plugin-os": "2.3.2",
"@use-gesture/react": "10.3.1",
"@vanilla-extract/css": "^1.18.0",
"@vanilla-extract/recipes": "^0.5.7",
@@ -71,6 +72,7 @@
"matrix-js-sdk": "^38.4.0",
"matrix-widget-api": "1.13.0",
"millify": "^6.1.0",
"motion": "12.35.0",
"pdfjs-dist": "^5.4.624",
"prismjs": "^1.30.0",
"react": "^18.3.1",
+320
View File
@@ -2,6 +2,12 @@
# It is not intended for manual editing.
version = 3
[[package]]
name = "Inflector"
version = "0.11.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe438c63458706e03479442743baae6c88256498e6431708f6dfc520a26515d3"
[[package]]
name = "adler2"
version = "2.0.1"
@@ -79,14 +85,22 @@ checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
name = "app"
version = "0.1.0"
dependencies = [
"enigo",
"log",
"serde",
"serde_json",
"specta",
"specta-typescript",
"tauri",
"tauri-build",
"tauri-plugin-deep-link",
"tauri-plugin-log",
"tauri-plugin-opener",
"tauri-plugin-os",
"tauri-plugin-single-instance",
"tauri-specta",
"tokio",
"windows",
]
[[package]]
@@ -951,6 +965,27 @@ version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"
[[package]]
name = "enigo"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "71744ff36f35a4276e8827add8102d0e792378c574fd93cb4e1c8e0505f96b7c"
dependencies = [
"core-foundation",
"core-graphics",
"foreign-types-shared",
"libc",
"log",
"nom",
"objc2",
"objc2-app-kit",
"objc2-foundation",
"windows",
"x11rb",
"xkbcommon",
"xkeysym",
]
[[package]]
name = "enumflags2"
version = "0.7.12"
@@ -1346,6 +1381,16 @@ dependencies = [
"version_check",
]
[[package]]
name = "gethostname"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"
dependencies = [
"rustix",
"windows-link 0.2.1",
]
[[package]]
name = "getrandom"
version = "0.1.16"
@@ -2139,6 +2184,15 @@ version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
[[package]]
name = "memmap2"
version = "0.9.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "714098028fe011992e1c3962653c96b2d578c4b4bce9036e15ff220319b1e0e3"
dependencies = [
"libc",
]
[[package]]
name = "memoffset"
version = "0.9.1"
@@ -2232,12 +2286,33 @@ version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
[[package]]
name = "nix"
version = "0.30.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74523f3a35e05aba87a1d978330aef40f67b0304ac79c1c00b294c9830543db6"
dependencies = [
"bitflags 2.11.0",
"cfg-if",
"cfg_aliases",
"libc",
]
[[package]]
name = "nodrop"
version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb"
[[package]]
name = "nom"
version = "8.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405"
dependencies = [
"memchr",
]
[[package]]
name = "num-conv"
version = "0.2.0"
@@ -2307,6 +2382,27 @@ dependencies = [
"objc2-foundation",
]
[[package]]
name = "objc2-cloud-kit"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c"
dependencies = [
"bitflags 2.11.0",
"objc2",
"objc2-foundation",
]
[[package]]
name = "objc2-core-data"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa"
dependencies = [
"objc2",
"objc2-foundation",
]
[[package]]
name = "objc2-core-foundation"
version = "0.3.2"
@@ -2331,6 +2427,38 @@ dependencies = [
"objc2-io-surface",
]
[[package]]
name = "objc2-core-image"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006"
dependencies = [
"objc2",
"objc2-foundation",
]
[[package]]
name = "objc2-core-location"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca347214e24bc973fc025fd0d36ebb179ff30536ed1f80252706db19ee452009"
dependencies = [
"objc2",
"objc2-foundation",
]
[[package]]
name = "objc2-core-text"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d"
dependencies = [
"bitflags 2.11.0",
"objc2",
"objc2-core-foundation",
"objc2-core-graphics",
]
[[package]]
name = "objc2-encode"
version = "4.1.0"
@@ -2354,6 +2482,7 @@ checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
dependencies = [
"bitflags 2.11.0",
"block2",
"libc",
"objc2",
"objc2-core-foundation",
]
@@ -2388,8 +2517,27 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22"
dependencies = [
"bitflags 2.11.0",
"block2",
"objc2",
"objc2-cloud-kit",
"objc2-core-data",
"objc2-core-foundation",
"objc2-core-graphics",
"objc2-core-image",
"objc2-core-location",
"objc2-core-text",
"objc2-foundation",
"objc2-quartz-core",
"objc2-user-notifications",
]
[[package]]
name = "objc2-user-notifications"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9df9128cbbfef73cda168416ccf7f837b62737d748333bfe9ab71c245d76613e"
dependencies = [
"objc2",
"objc2-foundation",
]
@@ -2451,6 +2599,22 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "os_info"
version = "3.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4022a17595a00d6a369236fdae483f0de7f0a339960a53118b818238e132224"
dependencies = [
"android_system_properties",
"log",
"nix",
"objc2",
"objc2-foundation",
"objc2-ui-kit",
"serde",
"windows-sys 0.61.2",
]
[[package]]
name = "pango"
version = "0.18.3"
@@ -2505,6 +2669,12 @@ dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "paste"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "pathdiff"
version = "0.2.3"
@@ -3545,6 +3715,50 @@ dependencies = [
"system-deps",
]
[[package]]
name = "specta"
version = "2.0.0-rc.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab7f01e9310a820edd31c80fde3cae445295adde21a3f9416517d7d65015b971"
dependencies = [
"paste",
"specta-macros",
"thiserror 1.0.69",
]
[[package]]
name = "specta-macros"
version = "2.0.0-rc.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0074b9e30ed84c6924eb63ad8d2fe71cdc82628525d84b1fcb1f2fd40676517"
dependencies = [
"Inflector",
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "specta-serde"
version = "0.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77216504061374659e7245eac53d30c7b3e5fe64b88da97c753e7184b0781e63"
dependencies = [
"specta",
"thiserror 1.0.69",
]
[[package]]
name = "specta-typescript"
version = "0.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3220a0c365e51e248ac98eab5a6a32f544ff6f961906f09d3ee10903a4f52b2d"
dependencies = [
"specta",
"specta-serde",
"thiserror 1.0.69",
]
[[package]]
name = "stable_deref_trait"
version = "1.2.1"
@@ -3635,6 +3849,15 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "sys-locale"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4"
dependencies = [
"libc",
]
[[package]]
name = "system-deps"
version = "6.2.2"
@@ -3744,6 +3967,7 @@ dependencies = [
"serde_json",
"serde_repr",
"serialize-to-javascript",
"specta",
"swift-rs",
"tauri-build",
"tauri-macros",
@@ -3905,6 +4129,40 @@ dependencies = [
"zbus",
]
[[package]]
name = "tauri-plugin-os"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8f08346c8deb39e96f86973da0e2d76cbb933d7ac9b750f6dc4daf955a6f997"
dependencies = [
"gethostname",
"log",
"os_info",
"serde",
"serde_json",
"serialize-to-javascript",
"sys-locale",
"tauri",
"tauri-plugin",
"thiserror 2.0.18",
]
[[package]]
name = "tauri-plugin-single-instance"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc61e4822b8f74d68278e09161d3e3fdd1b14b9eb781e24edccaabf10c420e8c"
dependencies = [
"serde",
"serde_json",
"tauri",
"tauri-plugin-deep-link",
"thiserror 2.0.18",
"tracing",
"windows-sys 0.60.2",
"zbus",
]
[[package]]
name = "tauri-runtime"
version = "2.10.1"
@@ -3956,6 +4214,34 @@ dependencies = [
"wry",
]
[[package]]
name = "tauri-specta"
version = "2.0.0-rc.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b23c0132dd3cf6064e5cd919b82b3f47780e9280e7b5910babfe139829b76655"
dependencies = [
"heck 0.5.0",
"serde",
"serde_json",
"specta",
"specta-typescript",
"tauri",
"tauri-specta-macros",
"thiserror 2.0.18",
]
[[package]]
name = "tauri-specta-macros"
version = "2.0.0-rc.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a4aa93823e07859546aa796b8a5d608190cd8037a3a5dce3eb63d491c34bda8"
dependencies = [
"heck 0.5.0",
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "tauri-utils"
version = "2.8.3"
@@ -5425,6 +5711,40 @@ dependencies = [
"pkg-config",
]
[[package]]
name = "x11rb"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414"
dependencies = [
"gethostname",
"rustix",
"x11rb-protocol",
]
[[package]]
name = "x11rb-protocol"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
[[package]]
name = "xkbcommon"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d66ca9352cbd4eecbbc40871d8a11b4ac8107cfc528a6e14d7c19c69d0e1ac9"
dependencies = [
"libc",
"memmap2",
"xkeysym",
]
[[package]]
name = "xkeysym"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"
[[package]]
name = "yoke"
version = "0.8.1"
+22 -2
View File
@@ -21,7 +21,27 @@ tauri-build = { version = "2.5.6", features = [] }
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
log = "0.4"
tauri = { version = "2.10.3", features = [] }
tokio = { version = "1", features = ["time"] }
tauri = { version = "2.10.3", features = ["tray-icon"] }
specta = "2.0.0-rc.22"
specta-typescript = "0.0.9"
tauri-specta = { version = "2.0.0-rc.21", features = ["derive", "typescript"] }
tauri-plugin-log = "2"
tauri-plugin-deep-link = "2.4.7"
tauri-plugin-opener = "2.5.3"
tauri-plugin-os = "2.3.2"
tauri-plugin-deep-link = "2.4.7"
[target.'cfg(target_os = "windows")'.dependencies]
enigo = "0.5.0"
windows = { version = "0.61", features = [
"Win32_Foundation",
"Win32_UI_WindowsAndMessaging",
"Win32_System_Threading",
"Win32_System_ProcessStatus"
] }
[target.'cfg(any(target_os = "macos", windows, target_os = "linux"))'.dependencies]
tauri-plugin-single-instance = { version = "2.4.0", features = ["deep-link"] }
+3 -3
View File
@@ -1,3 +1,3 @@
fn main() {
tauri_build::build()
}
fn main() {
tauri_build::build()
}
+14 -7
View File
@@ -1,13 +1,20 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "enables the default permissions",
"windows": [
"main"
],
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "enables the default permissions",
"windows": ["main"],
"permissions": [
"core:default",
"core:window:allow-close",
"core:window:allow-minimize",
"core:window:allow-maximize",
"core:window:allow-set-focus",
"core:window:allow-show",
"core:window:allow-is-maximized",
"core:window:allow-toggle-maximize",
"core:window:allow-start-dragging",
"deep-link:default",
"os:default",
"opener:default"
]
}
+66 -17
View File
@@ -1,18 +1,67 @@
#[cfg_attr(mobile, tauri::mobile_entry_point)]
mod desktop_tray;
mod windows;
use std::sync::Arc;
#[cfg(debug_assertions)]
use specta_typescript::Typescript;
use tauri::Manager;
use tauri_specta::{collect_commands, Builder};
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_deep_link::init())
.setup(|app| {
if cfg!(debug_assertions) {
app.handle().plugin(
tauri_plugin_log::Builder::default()
.level(log::LevelFilter::Info)
.build(),
)?;
}
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
let specta_builder = Builder::<tauri::Wry>::new().commands(collect_commands![
desktop_tray::set_close_to_tray_enabled,
windows::snap_overlay::show_snap_overlay,
windows::snap_overlay::hide_snap_overlay,
windows::window_tracking::start_window_tracking_with_target,
windows::window_tracking::stop_window_tracking,
windows::window_tracking::is_window_tracking_active,
]);
#[cfg(debug_assertions)]
specta_builder
.export(
Typescript::default().header("/* eslint-disable */"),
"../src/app/generated/tauri.ts",
)
.expect("Failed to export tauri-specta bindings");
let invoke_handler = specta_builder.invoke_handler();
tauri::Builder::default()
.manage(desktop_tray::DesktopSettingsState::new(true))
.manage(Arc::new(windows::window_tracking::TrackingState::new()))
.plugin(tauri_plugin_single_instance::init(|app, _argv, _cwd| {
let _ = desktop_tray::show_or_create_main_window(app);
}))
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_deep_link::init())
.plugin(tauri_plugin_os::init())
.setup(|app| {
#[cfg(any(target_os = "linux", all(debug_assertions, windows)))]
{
use tauri_plugin_deep_link::DeepLinkExt;
app.deep_link().register_all()?;
}
if let Some(window) = app.get_webview_window(desktop_tray::MAIN_WINDOW_LABEL) {
desktop_tray::configure_main_window(&window);
}
desktop_tray::create_system_tray(app.handle())?;
if cfg!(debug_assertions) {
app.handle().plugin(
tauri_plugin_log::Builder::default()
.level(log::LevelFilter::Info)
.build(),
)?;
}
Ok(())
})
.invoke_handler(invoke_handler)
.build(tauri::generate_context!())
.expect("error while building tauri application")
.run(desktop_tray::handle_run_event);
}
+6 -6
View File
@@ -1,6 +1,6 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
app_lib::run();
}
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
app_lib::run();
}
+13
View File
@@ -0,0 +1,13 @@
#[cfg(windows)]
#[path = "snap_overlay.rs"]
pub mod snap_overlay;
#[cfg(not(windows))]
#[path = "snap_overlay_stub.rs"]
pub mod snap_overlay;
#[cfg(windows)]
#[path = "window_tracking.rs"]
pub mod window_tracking;
#[cfg(not(windows))]
#[path = "window_tracking_stub.rs"]
pub mod window_tracking;
+26
View File
@@ -0,0 +1,26 @@
use enigo::{
Direction::{Click, Press, Release},
Enigo, Key, Keyboard, Settings,
};
#[tauri::command]
#[specta::specta]
pub async fn show_snap_overlay() {
let mut enigo = Enigo::new(&Settings::default()).unwrap();
enigo.key(Key::Meta, Press).unwrap();
enigo.key(Key::Unicode('z'), Click).unwrap();
enigo.key(Key::Meta, Release).unwrap();
std::thread::sleep(std::time::Duration::from_millis(100));
enigo.key(Key::Alt, Click).unwrap();
}
#[tauri::command]
#[specta::specta]
pub async fn hide_snap_overlay() {
let mut enigo = Enigo::new(&Settings::default()).unwrap();
enigo.key(Key::Escape, Click).unwrap();
}
@@ -0,0 +1,7 @@
#[tauri::command]
#[specta::specta]
pub async fn show_snap_overlay() {}
#[tauri::command]
#[specta::specta]
pub async fn hide_snap_overlay() {}
+298
View File
@@ -0,0 +1,298 @@
use std::{
ffi::OsString,
os::windows::ffi::OsStringExt,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
time::{Duration, Instant},
};
use serde::{Deserialize, Serialize};
use specta::Type;
use tauri::{AppHandle, Emitter, State};
use windows::Win32::{
Foundation::{CloseHandle, HWND, POINT},
System::{
ProcessStatus::GetModuleBaseNameW,
Threading::{OpenProcess, PROCESS_QUERY_INFORMATION, PROCESS_VM_READ},
},
UI::WindowsAndMessaging::{
GetClassNameW, GetCursorPos, GetWindowThreadProcessId, WindowFromPoint,
},
};
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Type)]
pub struct WindowInfo {
pub mouse_x: i32,
pub mouse_y: i32,
pub window_class: Option<String>,
pub exe_name: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Type)]
pub struct WindowTarget {
pub window_class: Option<String>,
pub exe_name: Option<String>,
}
impl WindowTarget {
pub fn new(window_class: Option<String>, exe_name: Option<String>) -> Self {
Self {
window_class,
exe_name,
}
}
pub fn matches(&self, window_info: &WindowInfo) -> bool {
let class_matches = match &self.window_class {
Some(target_class) => window_info
.window_class
.as_ref()
.map(|class| class.eq_ignore_ascii_case(target_class))
.unwrap_or(false),
None => true,
};
let exe_matches = match &self.exe_name {
Some(target_exe) => window_info
.exe_name
.as_ref()
.map(|exe| exe.eq_ignore_ascii_case(target_exe))
.unwrap_or(false),
None => true,
};
class_matches && exe_matches
}
}
impl WindowInfo {
pub fn matches_target(&self, target: &WindowTarget) -> bool {
target.matches(self)
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Type)]
pub enum EventType {
Started,
TargetLost,
Timeout,
Stopped,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Type)]
pub struct TrackingEvent {
pub event_type: EventType,
pub window_info: Option<WindowInfo>,
pub target: WindowTarget,
pub message: String,
}
pub struct TrackingState {
active: AtomicBool,
}
impl TrackingState {
pub fn new() -> Self {
Self {
active: AtomicBool::new(false),
}
}
pub fn is_active(&self) -> bool {
self.active.load(Ordering::Relaxed)
}
pub fn set_active(&self, active: bool) {
self.active.store(active, Ordering::Relaxed);
}
}
impl Default for TrackingState {
fn default() -> Self {
Self::new()
}
}
fn get_window_class_name(hwnd: HWND) -> Result<String, Box<dyn std::error::Error>> {
let mut buffer = [0u16; 256];
let len = unsafe { GetClassNameW(hwnd, &mut buffer) };
if len == 0 {
return Err("Failed to get class name".into());
}
Ok(OsString::from_wide(&buffer[..len as usize])
.to_string_lossy()
.into_owned())
}
fn get_exe_name_from_window(hwnd: HWND) -> Result<String, Box<dyn std::error::Error>> {
let mut process_id = 0;
unsafe {
GetWindowThreadProcessId(hwnd, Some(&mut process_id));
}
if process_id == 0 {
return Err("Failed to get process id".into());
}
let process_handle = unsafe {
OpenProcess(
PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
false,
process_id,
)
}?;
let mut buffer = [0u16; 260];
let len = unsafe { GetModuleBaseNameW(process_handle, None, &mut buffer) };
let _ = unsafe { CloseHandle(process_handle) };
if len == 0 {
return Err("Failed to get process name".into());
}
Ok(OsString::from_wide(&buffer[..len as usize])
.to_string_lossy()
.into_owned())
}
fn get_window_info() -> Result<WindowInfo, Box<dyn std::error::Error>> {
let mut point = POINT { x: 0, y: 0 };
unsafe { GetCursorPos(&raw mut point) }?;
let hwnd = unsafe { WindowFromPoint(point) };
let window_class = if !hwnd.0.is_null() {
get_window_class_name(hwnd).ok()
} else {
None
};
let exe_name = if !hwnd.0.is_null() {
get_exe_name_from_window(hwnd).ok()
} else {
None
};
Ok(WindowInfo {
mouse_x: point.x,
mouse_y: point.y,
window_class,
exe_name,
})
}
async fn track_window_hover_with_target(
app_handle: AppHandle,
target: WindowTarget,
tracking_state: Arc<TrackingState>,
) {
let start_time = Instant::now();
let timeout_duration = Duration::from_millis(200);
let check_interval = Duration::from_millis(100);
let mut was_on_target = false;
while tracking_state.is_active() {
if start_time.elapsed() >= timeout_duration && !was_on_target {
let event = TrackingEvent {
event_type: EventType::Timeout,
window_info: None,
target: target.clone(),
message: "Tracking timed out before reaching target".to_owned(),
};
let _ = app_handle.emit("window-tracking", &event);
tracking_state.set_active(false);
break;
}
if let Ok(window_info) = get_window_info() {
let is_on_target = window_info.matches_target(&target);
if was_on_target && !is_on_target {
let event = TrackingEvent {
event_type: EventType::TargetLost,
window_info: Some(window_info),
target: target.clone(),
message: "Pointer moved away from snap popup".to_owned(),
};
let _ = app_handle.emit("window-tracking", &event);
tracking_state.set_active(false);
break;
}
was_on_target = is_on_target;
}
tokio::time::sleep(check_interval).await;
}
}
#[tauri::command]
#[specta::specta]
pub async fn start_window_tracking_with_target(
app_handle: AppHandle,
target: WindowTarget,
tracking_state: State<'_, Arc<TrackingState>>,
) -> Result<(), String> {
if tracking_state.is_active() {
return Ok(());
}
tracking_state.set_active(true);
let event = TrackingEvent {
event_type: EventType::Started,
window_info: None,
target: target.clone(),
message: "Window tracking started".to_owned(),
};
app_handle
.emit("window-tracking", &event)
.map_err(|error| format!("Failed to emit start event: {error}"))?;
let app_handle_clone = app_handle.clone();
let tracking_state_clone = tracking_state.inner().clone();
tauri::async_runtime::spawn(async move {
track_window_hover_with_target(app_handle_clone, target, tracking_state_clone).await;
});
Ok(())
}
#[tauri::command]
#[specta::specta]
pub async fn stop_window_tracking(
app_handle: AppHandle,
tracking_state: State<'_, Arc<TrackingState>>,
) -> Result<(), String> {
if !tracking_state.is_active() {
return Ok(());
}
tracking_state.set_active(false);
let event = TrackingEvent {
event_type: EventType::Stopped,
window_info: None,
target: WindowTarget::new(None, None),
message: "Window tracking stopped".to_owned(),
};
app_handle
.emit("window-tracking", &event)
.map_err(|error| format!("Failed to emit stop event: {error}"))?;
Ok(())
}
#[tauri::command]
#[specta::specta]
pub async fn is_window_tracking_active(
tracking_state: State<'_, Arc<TrackingState>>,
) -> Result<bool, String> {
Ok(tracking_state.is_active())
}
@@ -0,0 +1,98 @@
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};
use serde::{Deserialize, Serialize};
use specta::Type;
use tauri::{AppHandle, State};
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Type)]
pub struct WindowInfo {
pub mouse_x: i32,
pub mouse_y: i32,
pub window_class: Option<String>,
pub exe_name: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Type)]
pub struct WindowTarget {
pub window_class: Option<String>,
pub exe_name: Option<String>,
}
impl WindowTarget {
pub fn new(window_class: Option<String>, exe_name: Option<String>) -> Self {
Self {
window_class,
exe_name,
}
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Type)]
pub enum EventType {
Started,
TargetLost,
Timeout,
Stopped,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Type)]
pub struct TrackingEvent {
pub event_type: EventType,
pub window_info: Option<WindowInfo>,
pub target: WindowTarget,
pub message: String,
}
pub struct TrackingState {
active: AtomicBool,
}
impl TrackingState {
pub fn new() -> Self {
Self {
active: AtomicBool::new(false),
}
}
pub fn is_active(&self) -> bool {
self.active.load(Ordering::Relaxed)
}
}
impl Default for TrackingState {
fn default() -> Self {
Self::new()
}
}
#[tauri::command]
#[specta::specta]
pub async fn start_window_tracking_with_target(
app_handle: AppHandle,
target: WindowTarget,
tracking_state: State<'_, Arc<TrackingState>>,
) -> Result<(), String> {
let _ = (app_handle, target, tracking_state);
Ok(())
}
#[tauri::command]
#[specta::specta]
pub async fn stop_window_tracking(
app_handle: AppHandle,
tracking_state: State<'_, Arc<TrackingState>>,
) -> Result<(), String> {
let _ = (app_handle, tracking_state);
Ok(())
}
#[tauri::command]
#[specta::specta]
pub async fn is_window_tracking_active(
tracking_state: State<'_, Arc<TrackingState>>,
) -> Result<bool, String> {
Ok(tracking_state.is_active())
}
+2 -3
View File
@@ -15,6 +15,7 @@
"title": "sable",
"width": 1280,
"height": 720,
"visible": false,
"resizable": true,
"fullscreen": false
}
@@ -37,9 +38,7 @@
"plugins": {
"deep-link": {
"desktop": {
"schemes": [
"sable"
]
"schemes": ["sable"]
}
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
import { ReactNode } from 'react';
import { motion, useMotionValue, useSpring } from 'framer-motion';
import { motion, useMotionValue, useSpring } from 'motion/react';
import { useDrag } from '@use-gesture/react';
import { useAtomValue } from 'jotai';
import { settingsAtom, RightSwipeAction } from '$state/settings';
@@ -1,4 +1,4 @@
import { useMotionValue, useSpring, useTransform, motion } from 'framer-motion';
import { useMotionValue, useSpring, useTransform, motion } from 'motion/react';
import { useDrag } from '@use-gesture/react';
import { ReactNode, useMemo, useState } from 'react';
import { useAtomValue } from 'jotai';
@@ -1,5 +1,5 @@
import { ReactNode } from 'react';
import { motion, useMotionValue, useSpring } from 'framer-motion';
import { motion, useMotionValue, useSpring } from 'motion/react';
import { useDrag } from '@use-gesture/react';
import { useAtomValue } from 'jotai';
import { settingsAtom } from '$state/settings';
+162
View File
@@ -0,0 +1,162 @@
import classNames from 'classnames';
import { Box, config, Line, Text } from 'folds';
import { AnimatePresence, motion, useReducedMotion } from 'motion/react';
import { SyncState } from '$types/matrix-sdk';
import { type TitlebarStatusView } from '$state/titlebarStatus';
import { ContainerColor } from '$styles/ContainerColor.css';
const TITLEBAR_EASE_OUT: [number, number, number, number] = [0.32, 0.72, 0, 1];
const TITLEBAR_EASE_OUT_SOFT: [number, number, number, number] = [0.24, 0.72, 0.08, 1];
type SyncConnectionStatusProps = {
status: TitlebarStatusView | null;
};
export function getSyncConnectionStatusView(
current: SyncState | null,
previous: SyncState | null | undefined
): TitlebarStatusView | null {
if (
(current === SyncState.Prepared ||
current === SyncState.Syncing ||
current === SyncState.Catchup) &&
previous !== SyncState.Syncing
) {
return { text: 'Connecting...', variant: 'Success' };
}
if (current === SyncState.Reconnecting) {
return { text: 'Connection Lost! Reconnecting...', variant: 'Warning' };
}
if (current === SyncState.Error) {
return { text: 'Connection Lost!', variant: 'Critical' };
}
return null;
}
export function SyncConnectionStatusBanner({ status }: SyncConnectionStatusProps) {
if (!status) return null;
return (
<Box direction="Column" shrink="No">
<Box
className={ContainerColor({ variant: status.variant })}
style={{ padding: `${config.space.S100} 0` }}
alignItems="Center"
justifyContent="Center"
>
<Text size="L400">{status.text}</Text>
</Box>
<Line variant={status.variant} size="300" />
</Box>
);
}
export function SyncConnectionStatusTitlebar({ status }: SyncConnectionStatusProps) {
const shouldReduceMotion = useReducedMotion();
const pillVariants = shouldReduceMotion
? {
hidden: { opacity: 0 },
visible: {
opacity: 1,
transition: { duration: 0.18, ease: TITLEBAR_EASE_OUT },
},
exit: {
opacity: 0,
transition: {
when: 'afterChildren' as const,
opacity: { duration: 0.1, delay: 0.08, ease: TITLEBAR_EASE_OUT_SOFT },
},
},
}
: {
hidden: {
y: -2,
scaleX: 0.98,
scaleY: 0.96,
opacity: 0,
clipPath: 'inset(0 50% 0 50% round 999px)',
},
visible: {
y: 0,
scaleX: 1,
scaleY: 1,
opacity: 1,
clipPath: 'inset(0 0% 0 0% round 999px)',
transition: { duration: 0.2, ease: TITLEBAR_EASE_OUT },
},
exit: {
y: -2,
scaleX: 0.98,
scaleY: 0.96,
opacity: 0,
clipPath: 'inset(0 50% 0 50% round 999px)',
transition: {
when: 'afterChildren' as const,
y: { duration: 0.2, ease: TITLEBAR_EASE_OUT },
scaleX: { duration: 0.2, ease: TITLEBAR_EASE_OUT },
scaleY: { duration: 0.2, ease: TITLEBAR_EASE_OUT },
clipPath: { duration: 0.2, ease: TITLEBAR_EASE_OUT },
opacity: { duration: 0.1, delay: 0.08, ease: TITLEBAR_EASE_OUT_SOFT },
},
},
};
const textVariants = shouldReduceMotion
? {
hidden: { opacity: 0 },
visible: {
opacity: 1,
transition: { duration: 0.12, ease: TITLEBAR_EASE_OUT },
},
exit: {
opacity: 0,
transition: { duration: 0.1, ease: TITLEBAR_EASE_OUT_SOFT },
},
}
: {
hidden: { opacity: 0 },
visible: {
opacity: 1,
transition: { duration: 0.12, delay: 0.04, ease: TITLEBAR_EASE_OUT_SOFT },
},
exit: {
opacity: 0,
transition: { duration: 0.1, ease: TITLEBAR_EASE_OUT_SOFT },
},
};
return (
<AnimatePresence mode="sync" initial={false}>
{status && (
<motion.span
key={`${status.variant}-${status.text}`}
className={classNames(
'tauri-titlebar-status__label',
status.variant === 'Success' && 'tauri-titlebar-status__label--success',
status.variant === 'Warning' && 'tauri-titlebar-status__label--warning',
status.variant === 'Critical' && 'tauri-titlebar-status__label--critical'
)}
style={{
transformOrigin: 'center top',
willChange: shouldReduceMotion ? 'opacity' : 'transform, opacity, clip-path',
}}
variants={pillVariants}
initial="hidden"
animate="visible"
exit="exit"
>
<motion.span
className="tauri-titlebar-status__text"
style={{ willChange: 'opacity' }}
variants={textVariants}
>
{status.text}
</motion.span>
</motion.span>
)}
</AnimatePresence>
);
}
@@ -0,0 +1,42 @@
import { useEffect } from 'react';
import { getCurrentWindow } from '@tauri-apps/api/window';
import { isTauri } from '@tauri-apps/api/core';
import { useSetting } from '$state/hooks/settings';
import { settingsAtom } from '$state/settings';
import { createLogger } from '$utils/debug';
import { commands } from '$generated/tauri';
const log = createLogger('TauriFrontendReady');
export function TauriFrontendReady() {
const [closeToTray] = useSetting(settingsAtom, 'closeToTray');
useEffect(() => {
if (!isTauri()) return undefined;
const appWindow = getCurrentWindow();
const showWindow = () => {
appWindow.show().catch((error) => {
log.warn('Failed to show main window after frontend mount:', error);
});
};
const rafId = window.requestAnimationFrame(showWindow);
return () => {
window.cancelAnimationFrame(rafId);
};
}, []);
useEffect(() => {
if (!isTauri()) return undefined;
commands.setCloseToTrayEnabled(closeToTray).catch((error) => {
log.warn('Failed to sync desktop close behavior:', error);
});
return undefined;
}, [closeToTray]);
return null;
}
@@ -0,0 +1,279 @@
import { useEffect, useRef, useState } from 'react';
import { isTauri } from '@tauri-apps/api/core';
import { getCurrentWindow, type Window } from '@tauri-apps/api/window';
import { listen } from '@tauri-apps/api/event';
import { type as osType } from '@tauri-apps/plugin-os';
import { useAtomValue } from 'jotai';
import { createLogger } from '$utils/debug';
import { titlebarStatusAtom } from '$state/titlebarStatus';
import { SyncConnectionStatusTitlebar } from '$components/SyncConnectionStatus';
import { commands } from '$generated/tauri';
const log = createLogger('WindowsTitleBar');
const SNAP_OVERLAY_DELAY_MS = 620;
const SNAP_POPUP_WINDOW_CLASS = 'Xaml_WindowedPopupClass';
const SNAP_POPUP_EXE = 'explorer.exe';
type TrackingEventType = 'Started' | 'TargetLost' | 'Timeout' | 'Stopped';
type TrackingEventPayload = {
event_type: TrackingEventType;
};
function MinimizeIcon() {
return (
<svg
viewBox="0 0 12 12"
aria-hidden
focusable="false"
fill="none"
stroke="currentColor"
strokeWidth="1"
shapeRendering="crispEdges"
>
<path d="M1.5 6.5h9" strokeLinecap="square" />
</svg>
);
}
function MaximizeIcon() {
return (
<svg
viewBox="0 0 12 12"
aria-hidden
focusable="false"
fill="none"
stroke="currentColor"
strokeWidth="1"
shapeRendering="crispEdges"
>
<rect x="1.5" y="1.5" width="9" height="9" />
</svg>
);
}
function RestoreIcon() {
return (
<svg
viewBox="0 0 12 12"
aria-hidden
focusable="false"
fill="none"
stroke="currentColor"
strokeWidth="1"
shapeRendering="crispEdges"
>
<rect x="1.5" y="3.5" width="7" height="7" />
<path d="M3.5 1.5h5a2 2 0 0 1 2 2v5" />
</svg>
);
}
function CloseIcon() {
return (
<svg
viewBox="0 0 12 12"
aria-hidden
focusable="false"
fill="none"
stroke="currentColor"
strokeWidth="1"
shapeRendering="crispEdges"
>
<path d="M1.5 1.5l9 9M10.5 1.5l-9 9" strokeLinecap="square" />
</svg>
);
}
export function WindowsTitleBar() {
const [maximized, setMaximized] = useState(false);
const appWindowRef = useRef<Window | null>(null);
const snapTimerRef = useRef<number | undefined>(undefined);
const isWindowsDesktopTauri = isTauri() && osType() === 'windows';
const titlebarStatus = useAtomValue(titlebarStatusAtom);
const hideSnapOverlay = async () => {
try {
await commands.hideSnapOverlay();
} catch (error) {
log.warn('Failed to hide snap overlay:', error);
}
};
useEffect(() => {
if (!isWindowsDesktopTauri) return undefined;
const appWindow = getCurrentWindow();
appWindowRef.current = appWindow;
let mounted = true;
let unlistenResize: (() => void) | undefined;
let unlistenTracking: (() => void) | undefined;
const syncMaximized = async () => {
try {
const isMaximizedState = await appWindow.isMaximized();
if (mounted) setMaximized(isMaximizedState);
} catch (error) {
log.warn('Failed to sync maximized state:', error);
}
};
syncMaximized().catch((error) => {
log.warn('Failed to sync maximized state:', error);
});
appWindow
.onResized(() => {
syncMaximized().catch((error) => {
log.warn('Failed to sync maximized state:', error);
});
})
.then((removeListener) => {
unlistenResize = removeListener;
})
.catch((error) => {
log.warn('Failed to subscribe to window resize:', error);
});
listen<TrackingEventPayload>('window-tracking', (event) => {
const eventType = event.payload?.event_type;
if (eventType === 'TargetLost' || eventType === 'Timeout') {
hideSnapOverlay();
}
})
.then((removeListener) => {
unlistenTracking = removeListener;
})
.catch((error) => {
log.warn('Failed to subscribe to window-tracking event:', error);
});
return () => {
mounted = false;
if (snapTimerRef.current !== undefined) {
window.clearTimeout(snapTimerRef.current);
}
commands.stopWindowTracking().catch(() => {});
hideSnapOverlay();
unlistenResize?.();
unlistenTracking?.();
};
}, [isWindowsDesktopTauri]);
if (!isWindowsDesktopTauri) return null;
const minimize = () => {
if (!isWindowsDesktopTauri) return;
commands.stopWindowTracking().catch(() => {});
hideSnapOverlay();
appWindowRef.current?.minimize().catch((error) => {
log.warn('Failed to minimize window:', error);
});
};
const toggleMaximize = () => {
if (!isWindowsDesktopTauri) return;
if (snapTimerRef.current !== undefined) {
window.clearTimeout(snapTimerRef.current);
snapTimerRef.current = undefined;
}
commands.stopWindowTracking().catch(() => {});
hideSnapOverlay();
appWindowRef.current?.toggleMaximize().catch((error) => {
log.warn('Failed to toggle maximize:', error);
});
};
const close = () => {
if (!isWindowsDesktopTauri) return;
commands.stopWindowTracking().catch(() => {});
hideSnapOverlay();
appWindowRef.current?.close().catch((error) => {
log.warn('Failed to close window:', error);
});
};
const showSnapOverlay = () => {
if (!isWindowsDesktopTauri) return;
if (snapTimerRef.current !== undefined) {
window.clearTimeout(snapTimerRef.current);
}
commands.stopWindowTracking().catch(() => {});
snapTimerRef.current = window.setTimeout(() => {
appWindowRef.current
?.setFocus()
.then(() => commands.showSnapOverlay())
.catch((error) => {
log.warn('Failed to show snap overlay:', error);
});
}, SNAP_OVERLAY_DELAY_MS);
};
const cancelSnapOverlay = () => {
if (!isWindowsDesktopTauri) return;
if (snapTimerRef.current !== undefined) {
window.clearTimeout(snapTimerRef.current);
snapTimerRef.current = undefined;
}
commands
.stopWindowTracking()
.then(() =>
commands.startWindowTrackingWithTarget({
window_class: SNAP_POPUP_WINDOW_CLASS,
exe_name: SNAP_POPUP_EXE,
})
)
.catch((error) => {
log.warn('Failed to start snap popup tracking:', error);
});
};
return (
<nav className="tauri-titlebar">
<div className="tauri-titlebar__drag" data-tauri-drag-region>
<span className="tauri-titlebar__title" data-tauri-drag-region>
sable
</span>
</div>
<div className="tauri-titlebar__status" data-tauri-drag-region>
<SyncConnectionStatusTitlebar status={titlebarStatus} />
</div>
<div className="tauri-titlebar__controls">
<button
type="button"
className="tauri-titlebar__control"
onClick={minimize}
aria-label="Minimize"
>
<MinimizeIcon />
</button>
<button
type="button"
className="tauri-titlebar__control"
onClick={toggleMaximize}
onMouseEnter={showSnapOverlay}
onMouseLeave={cancelSnapOverlay}
aria-label={maximized ? 'Restore' : 'Maximize'}
>
{maximized ? <RestoreIcon /> : <MaximizeIcon />}
</button>
<button
type="button"
className="tauri-titlebar__control tauri-titlebar__control--close"
onClick={close}
aria-label="Close"
>
<CloseIcon />
</button>
</div>
</nav>
);
}
+113
View File
@@ -0,0 +1,113 @@
/* eslint-disable */
// This file was generated by [tauri-specta](https://github.com/oscartbeaumont/tauri-specta). Do not edit this file manually.
/** user-defined commands **/
export const commands = {
async setCloseToTrayEnabled(enabled: boolean) : Promise<void> {
await TAURI_INVOKE("set_close_to_tray_enabled", { enabled });
},
async showSnapOverlay() : Promise<void> {
await TAURI_INVOKE("show_snap_overlay");
},
async hideSnapOverlay() : Promise<void> {
await TAURI_INVOKE("hide_snap_overlay");
},
async startWindowTrackingWithTarget(target: WindowTarget) : Promise<Result<null, string>> {
try {
return { status: "ok", data: await TAURI_INVOKE("start_window_tracking_with_target", { target }) };
} catch (e) {
if(e instanceof Error) throw e;
else return { status: "error", error: e as any };
}
},
async stopWindowTracking() : Promise<Result<null, string>> {
try {
return { status: "ok", data: await TAURI_INVOKE("stop_window_tracking") };
} catch (e) {
if(e instanceof Error) throw e;
else return { status: "error", error: e as any };
}
},
async isWindowTrackingActive() : Promise<Result<boolean, string>> {
try {
return { status: "ok", data: await TAURI_INVOKE("is_window_tracking_active") };
} catch (e) {
if(e instanceof Error) throw e;
else return { status: "error", error: e as any };
}
}
}
/** user-defined events **/
/** user-defined constants **/
/** user-defined types **/
export type WindowTarget = { window_class: string | null; exe_name: string | null }
/** tauri-specta globals **/
import {
invoke as TAURI_INVOKE,
Channel as TAURI_CHANNEL,
} from "@tauri-apps/api/core";
import * as TAURI_API_EVENT from "@tauri-apps/api/event";
import { type WebviewWindow as __WebviewWindow__ } from "@tauri-apps/api/webviewWindow";
type __EventObj__<T> = {
listen: (
cb: TAURI_API_EVENT.EventCallback<T>,
) => ReturnType<typeof TAURI_API_EVENT.listen<T>>;
once: (
cb: TAURI_API_EVENT.EventCallback<T>,
) => ReturnType<typeof TAURI_API_EVENT.once<T>>;
emit: null extends T
? (payload?: T) => ReturnType<typeof TAURI_API_EVENT.emit>
: (payload: T) => ReturnType<typeof TAURI_API_EVENT.emit>;
};
export type Result<T, E> =
| { status: "ok"; data: T }
| { status: "error"; error: E };
function __makeEvents__<T extends Record<string, any>>(
mappings: Record<keyof T, string>,
) {
return new Proxy(
{} as unknown as {
[K in keyof T]: __EventObj__<T[K]> & {
(handle: __WebviewWindow__): __EventObj__<T[K]>;
};
},
{
get: (_, event) => {
const name = mappings[event as keyof T];
return new Proxy((() => {}) as any, {
apply: (_, __, [window]: [__WebviewWindow__]) => ({
listen: (arg: any) => window.listen(name, arg),
once: (arg: any) => window.once(name, arg),
emit: (arg: any) => window.emit(name, arg),
}),
get: (_, command: keyof __EventObj__<any>) => {
switch (command) {
case "listen":
return (arg: any) => TAURI_API_EVENT.listen(name, arg);
case "once":
return (arg: any) => TAURI_API_EVENT.once(name, arg);
case "emit":
return (arg: any) => TAURI_API_EVENT.emit(name, arg);
}
},
});
},
},
);
}
+20 -1
View File
@@ -3,8 +3,12 @@ import { OverlayContainerProvider, PopOutContainerProvider, TooltipContainerProv
import { RouterProvider } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { isTauri } from '@tauri-apps/api/core';
import { type as osType } from '@tauri-apps/plugin-os';
import { ClientConfigLoader } from '$components/ClientConfigLoader';
import { TauriFrontendReady } from '$components/tauri/TauriFrontendReady';
import { WindowsTitleBar } from '$components/tauri/WindowsTitleBar';
import { ClientConfigProvider } from '$hooks/useClientConfig';
import { ScreenSizeProvider, useScreenSize } from '$hooks/useScreenSize';
import { useCompositionEndTracking } from '$hooks/useComposingCheck';
@@ -17,6 +21,7 @@ const queryClient = new QueryClient();
function App() {
const screenSize = useScreenSize();
useCompositionEndTracking();
const useCustomWindowsTitleBar = isTauri() && osType() === 'windows';
const portalContainer = document.getElementById('portalContainer') ?? undefined;
@@ -36,7 +41,21 @@ function App() {
<ClientConfigProvider value={clientConfig}>
<QueryClientProvider client={queryClient}>
<JotaiProvider>
<RouterProvider router={createRouter(clientConfig, screenSize)} />
<TauriFrontendReady />
{useCustomWindowsTitleBar && <WindowsTitleBar />}
<div
style={{
display: 'flex',
flexDirection: 'column',
width: '100%',
minHeight: 0,
height: useCustomWindowsTitleBar
? 'calc(100% - var(--tauri-titlebar-height))'
: '100%',
}}
>
<RouterProvider router={createRouter(clientConfig, screenSize)} />
</div>
</JotaiProvider>
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
+7 -1
View File
@@ -18,6 +18,8 @@ import FocusTrap from 'focus-trap-react';
import { useRef, MouseEventHandler, ReactNode, useCallback, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAtom, useAtomValue, useSetAtom } from 'jotai';
import { isTauri } from '@tauri-apps/api/core';
import { type as osType } from '@tauri-apps/plugin-os';
import {
clearCacheAndReload,
clearLoginData,
@@ -74,6 +76,10 @@ type ClientRootOptionsProps = {
};
function ClientRootOptions({ mx, onLogout }: ClientRootOptionsProps) {
const [menuAnchor, setMenuAnchor] = useState<RectCords>();
const isWindowsTauri = isTauri() && osType() === 'windows';
const topOffset = isWindowsTauri
? `calc(var(--tauri-titlebar-height) + ${config.space.S100})`
: config.space.S100;
const handleToggle: MouseEventHandler<HTMLButtonElement> = (evt) => {
const cords = evt.currentTarget.getBoundingClientRect();
@@ -87,7 +93,7 @@ function ClientRootOptions({ mx, onLogout }: ClientRootOptionsProps) {
<IconButton
style={{
position: 'absolute',
top: config.space.S100,
top: topOffset,
right: config.space.S100,
}}
variant="Background"
+58 -57
View File
@@ -1,8 +1,14 @@
import { MatrixClient, SyncState } from '$types/matrix-sdk';
import { useCallback, useState } from 'react';
import { Box, config, Line, Text } from 'folds';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useSetAtom } from 'jotai';
import { isTauri } from '@tauri-apps/api/core';
import { type as osType } from '@tauri-apps/plugin-os';
import { useSyncState } from '$hooks/useSyncState';
import { ContainerColor } from '$styles/ContainerColor.css';
import { titlebarStatusAtom, type TitlebarStatusView } from '$state/titlebarStatus';
import {
getSyncConnectionStatusView,
SyncConnectionStatusBanner,
} from '$components/SyncConnectionStatus';
type StateData = {
current: SyncState | null;
@@ -12,76 +18,71 @@ type StateData = {
type SyncStatusProps = {
mx: MatrixClient;
};
const DEMO_STATUS_STEP_MS = 1500;
const DEMO_STATUS_SEQUENCE: readonly (TitlebarStatusView | null)[] = [
{ text: 'Connecting...', variant: 'Success' },
null,
{ text: 'Connection Lost! Reconnecting...', variant: 'Warning' },
null,
{ text: 'Connection Lost!', variant: 'Critical' },
null,
];
const isSyncStatusDemoEnabled = (): boolean => {
if (import.meta.env.VITE_DEMO_SYNC_STATUS === '1') return true;
if (typeof window === 'undefined') return false;
return new URLSearchParams(window.location.search).get('demoSyncStatus') === '1';
};
export function SyncStatus({ mx }: SyncStatusProps) {
const [stateData, setStateData] = useState<StateData>({
current: null,
previous: undefined,
});
const [demoIndex, setDemoIndex] = useState(0);
const useDemoStatusLoop = isSyncStatusDemoEnabled();
const setTitlebarStatus = useSetAtom(titlebarStatusAtom);
const { current, previous } = stateData;
useSyncState(
mx,
useCallback((current, previous) => {
useCallback((nextCurrent, nextPrevious) => {
setStateData((s) => {
if (s.current === current && s.previous === previous) {
if (s.current === nextCurrent && s.previous === nextPrevious) {
return s;
}
return { current, previous };
return { current: nextCurrent, previous: nextPrevious };
});
}, [])
);
if (
(stateData.current === SyncState.Prepared ||
stateData.current === SyncState.Syncing ||
stateData.current === SyncState.Catchup) &&
stateData.previous !== SyncState.Syncing
) {
return (
<Box direction="Column" shrink="No">
<Box
className={ContainerColor({ variant: 'Success' })}
style={{ padding: `${config.space.S100} 0` }}
alignItems="Center"
justifyContent="Center"
>
<Text size="L400">Connecting...</Text>
</Box>
<Line variant="Success" size="300" />
</Box>
);
}
useEffect(() => {
if (!useDemoStatusLoop) return undefined;
const intervalId = window.setInterval(() => {
setDemoIndex((index) => (index + 1) % DEMO_STATUS_SEQUENCE.length);
}, DEMO_STATUS_STEP_MS);
if (stateData.current === SyncState.Reconnecting) {
return (
<Box direction="Column" shrink="No">
<Box
className={ContainerColor({ variant: 'Warning' })}
style={{ padding: `${config.space.S100} 0` }}
alignItems="Center"
justifyContent="Center"
>
<Text size="L400">Connection Lost! Reconnecting...</Text>
</Box>
<Line variant="Warning" size="300" />
</Box>
);
}
return () => {
window.clearInterval(intervalId);
};
}, [useDemoStatusLoop]);
if (stateData.current === SyncState.Error) {
return (
<Box direction="Column" shrink="No">
<Box
className={ContainerColor({ variant: 'Critical' })}
style={{ padding: `${config.space.S100} 0` }}
alignItems="Center"
justifyContent="Center"
>
<Text size="L400">Connection Lost!</Text>
</Box>
<Line variant="Critical" size="300" />
</Box>
);
}
const statusView = useMemo(() => {
if (useDemoStatusLoop) return DEMO_STATUS_SEQUENCE[demoIndex];
return getSyncConnectionStatusView(current, previous);
}, [current, demoIndex, previous, useDemoStatusLoop]);
return null;
const useTitlebarSlot = isTauri() && osType() === 'windows';
useEffect(() => {
if (!useTitlebarSlot) return undefined;
setTitlebarStatus(statusView);
return () => {
setTitlebarStatus(null);
};
}, [statusView, setTitlebarStatus, useTitlebarSlot]);
if (useTitlebarSlot) return null;
return <SyncConnectionStatusBanner status={statusView} />;
}
+9
View File
@@ -0,0 +1,9 @@
import { atom } from 'jotai';
export type TitlebarStatusVariant = 'Success' | 'Warning' | 'Critical';
export type TitlebarStatusView = {
text: string;
variant: TitlebarStatusVariant;
};
export const titlebarStatusAtom = atom<TitlebarStatusView | null>(null);
+145
View File
@@ -0,0 +1,145 @@
:root {
--tauri-titlebar-height: 32px;
--tauri-titlebar-icon-size: 12px;
}
.tauri-titlebar {
height: var(--tauri-titlebar-height);
display: grid;
grid-template-columns: 1fr auto;
align-items: stretch;
position: relative;
background: var(--sable-bg-container);
border-bottom: 1px solid var(--sable-bg-container-line);
user-select: none;
flex-shrink: 0;
}
.tauri-titlebar [data-tauri-drag-region] {
app-region: drag;
-webkit-app-region: drag;
}
.tauri-titlebar__drag {
display: flex;
align-items: center;
min-width: 0;
padding-inline: 12px;
}
.tauri-titlebar__title {
color: var(--sable-bg-on-container);
font-size: 12px;
line-height: 1;
letter-spacing: 0.02em;
text-transform: lowercase;
}
.tauri-titlebar__controls {
display: flex;
app-region: no-drag;
-webkit-app-region: no-drag;
}
.tauri-titlebar__status {
position: absolute;
left: 50%;
top: 0;
transform: translateX(-50%);
height: 100%;
min-width: 220px;
display: flex;
align-items: center;
justify-content: center;
padding-inline: 8px;
}
.tauri-titlebar-status__label {
display: inline-flex;
align-items: center;
justify-content: center;
overflow: hidden;
font-size: 12px;
font-weight: 600;
line-height: 1;
padding: 4px 10px;
border-radius: 999px;
color: var(--sable-bg-on-container);
background: color-mix(in srgb, var(--sable-bg-on-container) 10%, transparent);
white-space: nowrap;
}
.tauri-titlebar-status__label--success {
background: rgb(34 197 94 / 28%);
}
.tauri-titlebar-status__label--warning {
background: rgb(245 158 11 / 28%);
}
.tauri-titlebar-status__label--critical {
background: rgb(239 68 68 / 28%);
}
.tauri-titlebar__control {
appearance: none;
-webkit-appearance: none;
border: 0;
margin: 0;
padding: 0;
border-radius: 0;
font: inherit;
line-height: 0;
outline: none;
width: 46px;
height: var(--tauri-titlebar-height);
display: inline-flex;
align-items: center;
justify-content: center;
color: var(--sable-bg-on-container);
background: transparent;
cursor: default;
transition:
background-color 80ms linear,
color 80ms linear;
transform: none;
}
.tauri-titlebar__control:hover {
background: color-mix(in srgb, var(--sable-bg-on-container) 14%, transparent);
transform: none;
}
.tauri-titlebar__control:active {
background: color-mix(in srgb, var(--sable-bg-on-container) 20%, transparent);
transform: none;
}
.tauri-titlebar__control:focus-visible {
transform: none;
}
.tauri-titlebar__control svg {
display: block;
width: var(--tauri-titlebar-icon-size);
height: var(--tauri-titlebar-icon-size);
fill: none;
stroke: currentColor;
stroke-width: 1;
shape-rendering: crispEdges;
pointer-events: none;
}
.tauri-titlebar__control svg * {
vector-effect: non-scaling-stroke;
}
.tauri-titlebar__control--close:hover {
background: rgb(232 17 35 / 90%);
color: #fff;
}
.tauri-titlebar__control--close:active {
background: rgb(232 17 35 / 80%);
color: #fff;
}
+1
View File
@@ -17,6 +17,7 @@ import './index.css';
import './app/styles/themes.css';
import './app/styles/overrides/General.css';
import './app/styles/overrides/Privacy.css';
import './app/styles/overrides/TauriDesktop.css';
import { pushSessionToSW } from './sw-session';
import {
getFallbackSession,
+1
View File
@@ -19,6 +19,7 @@
"$styles/*": ["src/app/styles/*"],
"$utils/*": ["src/app/utils/*"],
"$pages/*": ["src/app/pages/*"],
"$generated/*": ["src/app/generated/*"],
"$types/*": ["src/types/*"],
"$public/*": ["public/*"],
"$client/*": ["src/client/*"]
+3
View File
@@ -140,6 +140,7 @@ export default defineConfig({
$styles: path.resolve(__dirname, 'src/app/styles'),
$utils: path.resolve(__dirname, 'src/app/utils'),
$pages: path.resolve(__dirname, 'src/app/pages'),
$generated: path.resolve(__dirname, 'src/app/generated'),
$types: path.resolve(__dirname, 'src/types'),
$public: path.resolve(__dirname, 'public'),
$client: path.resolve(__dirname, 'src/client'),
@@ -209,6 +210,8 @@ export default defineConfig({
}),
],
optimizeDeps: {
// Include service worker entry so worker-only imports are discovered during startup.
entries: ['index.html', 'src/sw.ts'],
// Rebuild dep optimizer cache on each dev start to avoid stale API shapes.
force: true,
// Keep matrix-widget-api prebundled so matrix-js-sdk can import its named exports in dev.