From a2abfb2f27648c16c2baf83fdb8163a76dededea Mon Sep 17 00:00:00 2001 From: Ren Amamiya Date: Tue, 24 Nov 2026 03:42:54 +0000 Subject: [PATCH] feat: rework window layout around panel stack (#36) Reviewed-on: https://git.reya.info/reya/signed/pulls/36 --- Cargo.lock | 136 +- crates/signed_app/src/app/helpers.rs | 7 +- crates/signed_app/src/app/mod.rs | 142 +-- crates/signed_app/src/app/placeholder.rs | 9 +- crates/signed_app/src/app/sign_in.rs | 112 -- crates/signed_app/src/explore/helpers.rs | 32 +- crates/signed_app/src/explore/mod.rs | 155 ++- crates/signed_app/src/identity/onboarding.rs | 25 +- crates/signed_app/src/identity/passphrase.rs | 28 +- crates/signed_app/src/inbox/helpers.rs | 4 +- crates/signed_app/src/inbox/mod.rs | 10 +- crates/signed_app/src/issues/detail.rs | 15 +- crates/signed_app/src/issues/helpers.rs | 40 +- crates/signed_app/src/issues/mod.rs | 15 +- crates/signed_app/src/issues/new_issue.rs | 23 +- crates/signed_app/src/lib.rs | 12 +- crates/signed_app/src/pull_requests/detail.rs | 61 +- .../src/pull_requests/dialogs/update.rs | 23 +- .../signed_app/src/pull_requests/helpers.rs | 12 +- crates/signed_app/src/pull_requests/mod.rs | 26 +- crates/signed_app/src/pull_requests/new.rs | 508 +++++++- .../src/pull_requests/new/source.rs | 397 ------ .../src/pull_requests/send_patch.rs | 16 +- crates/signed_app/src/repo/actions.rs | 6 +- crates/signed_app/src/repo/commit_diff.rs | 67 +- crates/signed_app/src/repo/dialogs/create.rs | 37 +- crates/signed_app/src/repo/dialogs/init.rs | 30 +- crates/signed_app/src/repo/files.rs | 67 +- crates/signed_app/src/repo/header.rs | 455 ------- crates/signed_app/src/repo/helpers.rs | 244 ++-- crates/signed_app/src/repo/history.rs | 15 +- crates/signed_app/src/repo/mod.rs | 471 ++++++- crates/signed_app/src/settings/helpers.rs | 216 ++-- crates/signed_app/src/shared/event_list.rs | 212 ++-- crates/signed_app/src/shared/mod.rs | 2 +- crates/signed_app/src/shared/panels.rs | 88 +- crates/signed_app/src/shared/progress.rs | 32 +- crates/signed_app/src/shared/tree.rs | 188 --- crates/signed_app/src/shared/widgets.rs | 81 -- crates/signed_app/src/titlebar/mod.rs | 205 +-- .../src/titlebar/repository_switcher.rs | 15 +- crates/signed_app/src/workspace.rs | 243 ---- crates/ui/src/components/alert.rs | 9 +- crates/ui/src/components/avatar.rs | 117 +- crates/ui/src/components/badge.rs | 16 +- crates/ui/src/components/button.rs | 24 +- crates/ui/src/components/clipboard.rs | 76 +- crates/ui/src/components/code.rs | 366 +++--- crates/ui/src/components/combobox.rs | 334 ++--- crates/ui/src/components/command_palette.rs | 192 ++- crates/ui/src/components/common.rs | 56 +- crates/ui/src/components/context_menu.rs | 145 --- crates/ui/src/components/dialog.rs | 2 +- crates/ui/src/components/diff.rs | 720 ----------- crates/ui/src/components/dropdown_menu.rs | 248 ++-- crates/ui/src/components/empty_state.rs | 17 +- crates/ui/src/components/grain.rs | 10 +- crates/ui/src/components/highlight.rs | 16 +- crates/ui/src/components/input.rs | 156 +-- crates/ui/src/components/kbd.rs | 105 +- crates/ui/src/components/link.rs | 154 --- crates/ui/src/components/list.rs | 290 ----- crates/ui/src/components/markdown.rs | 550 ++++---- crates/ui/src/components/menu.rs | 674 +++++----- crates/ui/src/components/mod.rs | 8 - crates/ui/src/components/popover.rs | 169 +-- crates/ui/src/components/progress.rs | 132 -- crates/ui/src/components/radio.rs | 259 ---- crates/ui/src/components/scroll_area.rs | 44 +- crates/ui/src/components/scrollbar.rs | 96 +- crates/ui/src/components/select.rs | 9 +- crates/ui/src/components/sidebar.rs | 486 ++++--- crates/ui/src/components/slider.rs | 341 ----- crates/ui/src/components/speech.rs | 1126 ----------------- crates/ui/src/components/spinner.rs | 20 +- crates/ui/src/components/status_dot.rs | 23 +- crates/ui/src/components/tabs.rs | 634 +++++----- crates/ui/src/components/toast.rs | 228 +--- crates/ui/src/components/tree.rs | 413 ++++-- crates/ui/src/components/utils.rs | 31 +- crates/ui/src/icons/assets/maximize.svg | 3 + crates/ui/src/icons/assets/minimize.svg | 3 + crates/ui/src/icons/mod.rs | 26 +- crates/ui/src/layout/mod.rs | 4 +- crates/ui/src/layout/panel.rs | 746 +++++++++-- crates/ui/src/layout/resizable.rs | 77 +- crates/ui/src/layout/root.rs | 194 +++ crates/ui/src/layout/shell.rs | 132 -- crates/ui/src/layout/titlebar.rs | 12 +- crates/ui/src/lib.rs | 2 +- crates/ui/src/theme/colors.rs | 28 +- crates/ui/src/theme/mod.rs | 6 - crates/ui/src/theme/ramps.rs | 20 +- crates/ui/src/theme/source/linux.rs | 178 +-- crates/ui/src/theme/source/macos.rs | 18 +- crates/ui/src/theme/source/windows.rs | 38 +- crates/ui/tests/panel.rs | 754 ++++++++++- desktop/src/main.rs | 10 +- docs/gpui-native-kit-gaps.md | 7 +- 99 files changed, 6145 insertions(+), 8891 deletions(-) delete mode 100644 crates/signed_app/src/app/sign_in.rs delete mode 100644 crates/signed_app/src/pull_requests/new/source.rs delete mode 100644 crates/signed_app/src/repo/header.rs delete mode 100644 crates/signed_app/src/shared/tree.rs delete mode 100644 crates/signed_app/src/workspace.rs delete mode 100644 crates/ui/src/components/context_menu.rs delete mode 100644 crates/ui/src/components/diff.rs delete mode 100644 crates/ui/src/components/link.rs delete mode 100644 crates/ui/src/components/list.rs delete mode 100644 crates/ui/src/components/progress.rs delete mode 100644 crates/ui/src/components/radio.rs delete mode 100644 crates/ui/src/components/slider.rs delete mode 100644 crates/ui/src/components/speech.rs create mode 100644 crates/ui/src/icons/assets/maximize.svg create mode 100644 crates/ui/src/icons/assets/minimize.svg create mode 100644 crates/ui/src/layout/root.rs delete mode 100644 crates/ui/src/layout/shell.rs diff --git a/Cargo.lock b/Cargo.lock index 98e8e31..d8636f7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -553,7 +553,7 @@ checksum = "efbd3e1070bbdf4cd88a75264e18e8a26f7cb5c6949eadf0ceb85fb159cf08f8" [[package]] name = "bench_metrics" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#ad1058d78d802f2fa857dee20aa2f5e123ef1ece" +source = "git+https://github.com/zed-industries/zed#f4fe0be1f8c7974db07e01c5cd05bee0cf4eb8d9" dependencies = [ "anyhow", "criterion", @@ -1054,7 +1054,7 @@ dependencies = [ [[package]] name = "collections" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#ad1058d78d802f2fa857dee20aa2f5e123ef1ece" +source = "git+https://github.com/zed-industries/zed#f4fe0be1f8c7974db07e01c5cd05bee0cf4eb8d9" dependencies = [ "gpui_util", "indexmap", @@ -1507,7 +1507,7 @@ dependencies = [ [[package]] name = "derive_refineable" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#ad1058d78d802f2fa857dee20aa2f5e123ef1ece" +source = "git+https://github.com/zed-industries/zed#f4fe0be1f8c7974db07e01c5cd05bee0cf4eb8d9" dependencies = [ "proc-macro2", "quote", @@ -1520,7 +1520,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e3dc2f773b6aaa63b1a7684b8589f670a8a0146a510b74d23a401c882364b49" dependencies = [ - "hashbrown 0.17.1", + "hashbrown 0.17.2", ] [[package]] @@ -1655,7 +1655,7 @@ dependencies = [ "cc", "memchr", "rustc_version", - "toml 1.2.1+spec-1.1.0", + "toml 1.2.2+spec-1.1.0", "vswhom", "winreg", ] @@ -1999,9 +1999,9 @@ checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -2552,7 +2552,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c55bff2f32f6f5a95bdd43e5e5e01b0656250cffbc48eda19db0afa3d73adf2f" dependencies = [ "gix-hash", - "hashbrown 0.17.1", + "hashbrown 0.17.2", "parking_lot", ] @@ -2576,7 +2576,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7518b930f6aeb75e871d32ce873c2ae46e35cef19b5a0b039d4337f651d897cd" dependencies = [ "bstr", - "hashbrown 0.17.1", + "hashbrown 0.17.2", ] [[package]] @@ -2599,7 +2599,7 @@ dependencies = [ "gix-traverse", "gix-utils", "gix-validate", - "hashbrown 0.17.1", + "hashbrown 0.17.2", "itoa", "libc", "memmap2", @@ -3173,7 +3173,7 @@ dependencies = [ [[package]] name = "gpui" version = "0.2.2" -source = "git+https://github.com/zed-industries/zed#ad1058d78d802f2fa857dee20aa2f5e123ef1ece" +source = "git+https://github.com/zed-industries/zed#f4fe0be1f8c7974db07e01c5cd05bee0cf4eb8d9" dependencies = [ "accesskit", "anyhow", @@ -3244,7 +3244,7 @@ dependencies = [ [[package]] name = "gpui_apple" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#ad1058d78d802f2fa857dee20aa2f5e123ef1ece" +source = "git+https://github.com/zed-industries/zed#f4fe0be1f8c7974db07e01c5cd05bee0cf4eb8d9" dependencies = [ "anyhow", "async-task", @@ -3283,7 +3283,7 @@ dependencies = [ [[package]] name = "gpui_ios" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#ad1058d78d802f2fa857dee20aa2f5e123ef1ece" +source = "git+https://github.com/zed-industries/zed#f4fe0be1f8c7974db07e01c5cd05bee0cf4eb8d9" dependencies = [ "anyhow", "block2 0.6.2", @@ -3304,7 +3304,7 @@ dependencies = [ [[package]] name = "gpui_linux" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#ad1058d78d802f2fa857dee20aa2f5e123ef1ece" +source = "git+https://github.com/zed-industries/zed#f4fe0be1f8c7974db07e01c5cd05bee0cf4eb8d9" dependencies = [ "accesskit", "anyhow", @@ -3331,7 +3331,7 @@ dependencies = [ [[package]] name = "gpui_macos" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#ad1058d78d802f2fa857dee20aa2f5e123ef1ece" +source = "git+https://github.com/zed-industries/zed#f4fe0be1f8c7974db07e01c5cd05bee0cf4eb8d9" dependencies = [ "accesskit", "accesskit_macos", @@ -3372,7 +3372,7 @@ dependencies = [ [[package]] name = "gpui_macros" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#ad1058d78d802f2fa857dee20aa2f5e123ef1ece" +source = "git+https://github.com/zed-industries/zed#f4fe0be1f8c7974db07e01c5cd05bee0cf4eb8d9" dependencies = [ "heck 0.5.0", "proc-macro2", @@ -3383,7 +3383,7 @@ dependencies = [ [[package]] name = "gpui_platform" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#ad1058d78d802f2fa857dee20aa2f5e123ef1ece" +source = "git+https://github.com/zed-industries/zed#f4fe0be1f8c7974db07e01c5cd05bee0cf4eb8d9" dependencies = [ "anyhow", "console_error_panic_hook", @@ -3398,7 +3398,7 @@ dependencies = [ [[package]] name = "gpui_shared_string" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#ad1058d78d802f2fa857dee20aa2f5e123ef1ece" +source = "git+https://github.com/zed-industries/zed#f4fe0be1f8c7974db07e01c5cd05bee0cf4eb8d9" dependencies = [ "schemars", "serde", @@ -3408,7 +3408,7 @@ dependencies = [ [[package]] name = "gpui_util" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#ad1058d78d802f2fa857dee20aa2f5e123ef1ece" +source = "git+https://github.com/zed-industries/zed#f4fe0be1f8c7974db07e01c5cd05bee0cf4eb8d9" dependencies = [ "anyhow", "log", @@ -3418,7 +3418,7 @@ dependencies = [ [[package]] name = "gpui_web" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#ad1058d78d802f2fa857dee20aa2f5e123ef1ece" +source = "git+https://github.com/zed-industries/zed#f4fe0be1f8c7974db07e01c5cd05bee0cf4eb8d9" dependencies = [ "anyhow", "async-channel", @@ -3447,7 +3447,7 @@ dependencies = [ [[package]] name = "gpui_wgpu" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#ad1058d78d802f2fa857dee20aa2f5e123ef1ece" +source = "git+https://github.com/zed-industries/zed#f4fe0be1f8c7974db07e01c5cd05bee0cf4eb8d9" dependencies = [ "anyhow", "bytemuck", @@ -3473,7 +3473,7 @@ dependencies = [ [[package]] name = "gpui_windows" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#ad1058d78d802f2fa857dee20aa2f5e123ef1ece" +source = "git+https://github.com/zed-industries/zed#f4fe0be1f8c7974db07e01c5cd05bee0cf4eb8d9" dependencies = [ "accesskit", "accesskit_windows", @@ -3571,9 +3571,9 @@ dependencies = [ [[package]] name = "hashbrown" -version = "0.17.1" +version = "0.17.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" dependencies = [ "allocator-api2", "equivalent", @@ -3739,7 +3739,7 @@ dependencies = [ [[package]] name = "http_client" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#ad1058d78d802f2fa857dee20aa2f5e123ef1ece" +source = "git+https://github.com/zed-industries/zed#f4fe0be1f8c7974db07e01c5cd05bee0cf4eb8d9" dependencies = [ "anyhow", "bytes", @@ -3757,7 +3757,7 @@ dependencies = [ [[package]] name = "http_client_tls" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#ad1058d78d802f2fa857dee20aa2f5e123ef1ece" +source = "git+https://github.com/zed-industries/zed#f4fe0be1f8c7974db07e01c5cd05bee0cf4eb8d9" dependencies = [ "log", "rustls", @@ -4083,7 +4083,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", - "hashbrown 0.17.1", + "hashbrown 0.17.2", "serde", "serde_core", ] @@ -4719,7 +4719,7 @@ dependencies = [ "cfg_aliases", "codespan-reporting", "half", - "hashbrown 0.17.1", + "hashbrown 0.17.2", "indexmap", "libm", "log", @@ -4737,7 +4737,7 @@ name = "naga-types" version = "30.0.0" source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" dependencies = [ - "hashbrown 0.17.1", + "hashbrown 0.17.2", "indexmap", "rustc-hash 1.1.0", "thiserror 2.0.21", @@ -4817,7 +4817,7 @@ checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8" [[package]] name = "nostr" version = "0.45.7" -source = "git+https://github.com/rust-nostr/nostr#ab27af501225334e60673bb4f7d03d111e34e407" +source = "git+https://github.com/rust-nostr/nostr#1d2c6b1aecab0bc657dc27a1374512260af380ba" dependencies = [ "aes", "base64 0.22.1", @@ -4843,7 +4843,7 @@ dependencies = [ [[package]] name = "nostr-connect" version = "0.45.3" -source = "git+https://github.com/rust-nostr/nostr#ab27af501225334e60673bb4f7d03d111e34e407" +source = "git+https://github.com/rust-nostr/nostr#1d2c6b1aecab0bc657dc27a1374512260af380ba" dependencies = [ "async-utility", "nostr", @@ -4856,7 +4856,7 @@ dependencies = [ [[package]] name = "nostr-database" version = "0.45.2" -source = "git+https://github.com/rust-nostr/nostr#ab27af501225334e60673bb4f7d03d111e34e407" +source = "git+https://github.com/rust-nostr/nostr#1d2c6b1aecab0bc657dc27a1374512260af380ba" dependencies = [ "nostr", "opaquerr", @@ -4865,7 +4865,7 @@ dependencies = [ [[package]] name = "nostr-gossip" version = "0.45.1" -source = "git+https://github.com/rust-nostr/nostr#ab27af501225334e60673bb4f7d03d111e34e407" +source = "git+https://github.com/rust-nostr/nostr#1d2c6b1aecab0bc657dc27a1374512260af380ba" dependencies = [ "nostr", "opaquerr", @@ -4874,7 +4874,7 @@ dependencies = [ [[package]] name = "nostr-gossip-memory" version = "0.45.1" -source = "git+https://github.com/rust-nostr/nostr#ab27af501225334e60673bb4f7d03d111e34e407" +source = "git+https://github.com/rust-nostr/nostr#1d2c6b1aecab0bc657dc27a1374512260af380ba" dependencies = [ "indexmap", "lru", @@ -4886,7 +4886,7 @@ dependencies = [ [[package]] name = "nostr-lmdb" version = "0.45.3" -source = "git+https://github.com/rust-nostr/nostr#ab27af501225334e60673bb4f7d03d111e34e407" +source = "git+https://github.com/rust-nostr/nostr#1d2c6b1aecab0bc657dc27a1374512260af380ba" dependencies = [ "async-utility", "flatbuffers", @@ -4901,7 +4901,7 @@ dependencies = [ [[package]] name = "nostr-sdk" version = "0.45.6" -source = "git+https://github.com/rust-nostr/nostr#ab27af501225334e60673bb4f7d03d111e34e407" +source = "git+https://github.com/rust-nostr/nostr#1d2c6b1aecab0bc657dc27a1374512260af380ba" dependencies = [ "async-utility", "async-wsocket", @@ -4951,7 +4951,7 @@ dependencies = [ "mac-notification-sys", "serde", "tauri-winrt-notification", - "zbus 6.4.0", + "zbus 6.5.0", ] [[package]] @@ -5948,7 +5948,7 @@ version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" dependencies = [ - "toml_edit 0.25.19+spec-1.1.0", + "toml_edit 0.25.20+spec-1.1.0", ] [[package]] @@ -6404,7 +6404,7 @@ dependencies = [ [[package]] name = "refineable" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#ad1058d78d802f2fa857dee20aa2f5e123ef1ece" +source = "git+https://github.com/zed-industries/zed#f4fe0be1f8c7974db07e01c5cd05bee0cf4eb8d9" dependencies = [ "derive_refineable", ] @@ -6487,7 +6487,7 @@ dependencies = [ [[package]] name = "reqwest_client" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#ad1058d78d802f2fa857dee20aa2f5e123ef1ece" +source = "git+https://github.com/zed-industries/zed#f4fe0be1f8c7974db07e01c5cd05bee0cf4eb8d9" dependencies = [ "anyhow", "bytes", @@ -6791,7 +6791,7 @@ dependencies = [ [[package]] name = "scheduler" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#ad1058d78d802f2fa857dee20aa2f5e123ef1ece" +source = "git+https://github.com/zed-industries/zed#f4fe0be1f8c7974db07e01c5cd05bee0cf4eb8d9" dependencies = [ "async-task", "backtrace", @@ -7417,7 +7417,7 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "sum_tree" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#ad1058d78d802f2fa857dee20aa2f5e123ef1ece" +source = "git+https://github.com/zed-industries/zed#f4fe0be1f8c7974db07e01c5cd05bee0cf4eb8d9" dependencies = [ "heapless 0.9.4", "rayon", @@ -7845,9 +7845,9 @@ dependencies = [ [[package]] name = "toml" -version = "1.2.1+spec-1.1.0" +version = "1.2.2+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7" +checksum = "5426cb1b964690d913f6c5c1a1ae0b42f428ec506bb4d452876d7a209c9bca3b" dependencies = [ "indexmap", "serde_core", @@ -7892,9 +7892,9 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.25.19+spec-1.1.0" +version = "0.25.20+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218" +checksum = "e76360e201d6dbd6583e17795ba71a88f47365a9139c8450a7979c32303b8e73" dependencies = [ "indexmap", "toml_datetime 1.1.3+spec-1.1.0", @@ -7904,9 +7904,9 @@ dependencies = [ [[package]] name = "toml_parser" -version = "1.1.5+spec-1.1.0" +version = "1.1.6+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31" dependencies = [ "winnow 1.0.5", ] @@ -8280,9 +8280,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", @@ -8428,9 +8428,9 @@ checksum = "317211a0dc0ceedd78fb2ca9a44aed3d7b9b26f81870d485c07122b4350673b7" [[package]] name = "walkdir" -version = "2.5.0" +version = "2.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403" dependencies = [ "same-file", "winapi-util", @@ -8631,7 +8631,7 @@ dependencies = [ "cfg-if", "cfg_aliases", "document-features", - "hashbrown 0.17.1", + "hashbrown 0.17.2", "js-sys", "log", "naga", @@ -8660,7 +8660,7 @@ dependencies = [ "bytemuck", "cfg_aliases", "document-features", - "hashbrown 0.17.1", + "hashbrown 0.17.2", "indexmap", "log", "naga", @@ -8740,7 +8740,7 @@ dependencies = [ "glow", "glutin_wgl_sys", "gpu-allocator", - "hashbrown 0.17.1", + "hashbrown 0.17.2", "js-sys", "khronos-egl", "libc", @@ -9471,9 +9471,9 @@ dependencies = [ [[package]] name = "zbus" -version = "6.4.0" +version = "6.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "970c652becf38216d39997ec1335d57bcf7fc7de8ac6447c576de5951d894ec1" +checksum = "9a7f9f5dd97fa527c1202ba1cb35d48e07f77d4de8542317c854f7aef22b0668" dependencies = [ "async-trait", "bitflags 2.13.2", @@ -9490,7 +9490,7 @@ dependencies = [ "uuid", "windows-sys 0.61.2", "winnow 1.0.5", - "zbus_macros 6.4.0", + "zbus_macros 6.5.0", "zbus_utils", "zcheapstr", "zruntime", @@ -9513,9 +9513,9 @@ dependencies = [ [[package]] name = "zbus_macros" -version = "6.4.0" +version = "6.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ab2435eef3e274c1727af87c31da148dc6cb2c613f5eecfac33d7952cf0e6f8" +checksum = "2f5aa7f2c4ea81b7ccfb26bafefdb4d1a44dd9d4f82c8426173a3727311743e4" dependencies = [ "proc-macro2", "quote", @@ -9549,9 +9549,9 @@ dependencies = [ [[package]] name = "zcheapstr" -version = "1.3.0" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2347b6f50c4f669a282af57bf950debeacb9ce86de21b5b12932178dda691315" +checksum = "2da34e7164b75d803c3197b86e6cf61b874106fbd472c5082575a8bc5fbd0907" dependencies = [ "serde", ] @@ -9650,18 +9650,18 @@ checksum = "6df3dc4292935e51816d896edcd52aa30bc297907c26167fec31e2b0c6a32524" [[package]] name = "zerocopy" -version = "0.8.63" +version = "0.8.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.63" +version = "0.8.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9" dependencies = [ "proc-macro2", "quote", @@ -9772,7 +9772,7 @@ dependencies = [ [[package]] name = "ztracing" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#ad1058d78d802f2fa857dee20aa2f5e123ef1ece" +source = "git+https://github.com/zed-industries/zed#f4fe0be1f8c7974db07e01c5cd05bee0cf4eb8d9" dependencies = [ "tracing", "ztracing_macro", @@ -9781,7 +9781,7 @@ dependencies = [ [[package]] name = "ztracing_macro" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#ad1058d78d802f2fa857dee20aa2f5e123ef1ece" +source = "git+https://github.com/zed-industries/zed#f4fe0be1f8c7974db07e01c5cd05bee0cf4eb8d9" [[package]] name = "zune-core" diff --git a/crates/signed_app/src/app/helpers.rs b/crates/signed_app/src/app/helpers.rs index 98ff04b..224eb0b 100644 --- a/crates/signed_app/src/app/helpers.rs +++ b/crates/signed_app/src/app/helpers.rs @@ -1,12 +1,7 @@ use gpui::App; -use settings::{AppearanceMode, Settings}; +use settings::AppearanceMode; use ui::theme::{ThemeVariant, follow_system, set_mode_override}; -/// Applies the persisted light/dark/system preference to the kit theme. -pub fn apply_appearance(settings: &Settings, cx: &mut App) { - apply_appearance_mode(settings.appearance, cx); -} - /// Applies one appearance mode to the kit theme. pub fn apply_appearance_mode(mode: AppearanceMode, cx: &mut App) { match mode { diff --git a/crates/signed_app/src/app/mod.rs b/crates/signed_app/src/app/mod.rs index a1e2bfb..599cc7a 100644 --- a/crates/signed_app/src/app/mod.rs +++ b/crates/signed_app/src/app/mod.rs @@ -1,25 +1,22 @@ pub mod helpers; mod placeholder; -mod sign_in; use gpui::prelude::FluentBuilder as _; use gpui::{ - AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, - Render, Styled as _, Subscription, Window, div, px, + App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, + ParentElement as _, Render, Styled as _, Subscription, WeakEntity, Window, div, }; -use helpers::apply_appearance; +use helpers::apply_appearance_mode; use settings::SettingsStore; use signed_state::{Backend, BackendEvent}; -use ui::common::h_flex; +use ui::common::{h_flex, v_flex}; use ui::icons::IconRole; -use ui::layout::panel::PanelRow; -use ui::layout::shell::Shell; +use ui::layout::panel::PanelStack; +use ui::layout::root::RootContext as _; use ui::layout::titlebar::Titlebar; -use ui::theme::ActiveTheme as _; -use ui::toast::{Toast, Toasts}; +use ui::toast::Toast; use crate::app::placeholder::PlaceholderView; -use crate::app::sign_in::SignedOutView; use crate::explore::ExploreView; use crate::identity::passphrase::PassphraseDialog; use crate::shared::log_dropped; @@ -27,15 +24,10 @@ use crate::titlebar::{ CreateRepository, REPOSITORY_KEY_CONTEXT, SwitchRepository, TitlebarView, bind_repository_shortcuts, }; -use crate::workspace::Workspace; pub struct AppRoot { - workspace: Entity, + panels: Entity, titlebar: Entity, - toasts: Entity, - sign_in: Entity, - explore: Entity, - empty: Entity, passphrase: Option>, _subscriptions: Vec, } @@ -44,13 +36,11 @@ impl AppRoot { pub fn new(window: &mut Window, cx: &mut Context) -> Self { bind_repository_shortcuts(cx); - let workspace = cx.new(|_| Workspace::new()); - let titlebar = cx.new(|cx| TitlebarView::new(workspace.downgrade(), window, cx)); - - let toasts = cx.new(|_| Toasts::default()); - let sign_in = cx.new(|_| SignedOutView::new()); - let explore = cx.new(|cx| ExploreView::new(workspace.downgrade(), cx)); + let app = cx.entity().downgrade(); + let panels = cx.new(|cx| PanelStack::new("signed-panel", cx)); + let titlebar = cx.new(|cx| TitlebarView::new(app.clone(), window, cx)); let empty = cx.new(|_| PlaceholderView::new("Select a repository")); + panels.update(cx, |panels, cx| panels.set_empty(empty, None, cx)); let backend = Backend::global(cx); let settings = SettingsStore::global(cx); @@ -59,22 +49,18 @@ impl AppRoot { subscriptions.push(cx.subscribe_in( &backend, window, - |this, backend, event, window, cx| match event { + |this, _backend, event, window, cx| match event { BackendEvent::PassphraseRequired => { this.open_passphrase(cx); } BackendEvent::Error(message) => { - this.toasts.update(cx, |toasts, cx| { - toasts.push(Toast::new(message.clone()).icon(IconRole::Warning), cx); - }); + cx.toast(Toast::new(message.clone()).icon(IconRole::Warning)); } BackendEvent::SignerChanged => { - this.workspace.update(cx, |workspace, cx| { - workspace.clear(cx); + let app = cx.entity().downgrade(); + window.defer(cx, move |window, cx| { + Self::reset_to_explore(&app, window, cx) }); - if backend.read(cx).current_user().is_some() { - ExploreView::open(&this.workspace.downgrade(), window, cx); - } } _ => {} }, @@ -82,60 +68,56 @@ impl AppRoot { subscriptions.push(cx.observe(&settings, |_this, store, cx| { let settings = store.read(cx).settings().clone(); - apply_appearance(&settings, cx); + apply_appearance_mode(settings.appearance, cx); })); - let app = cx.entity().downgrade(); - window.defer(cx, move |_window, cx| { + window.defer(cx, move |window, cx| { if backend.read(cx).passphrase_required() { log_dropped(app.update(cx, |this, cx| this.open_passphrase(cx))); } + Self::reset_to_explore(&app, window, cx); }); Self { - workspace, + panels, titlebar, - toasts, - sign_in, - explore, - empty, passphrase: None, _subscriptions: subscriptions, } } fn open_passphrase(&mut self, cx: &mut Context) { - self.passphrase = Some(PassphraseDialog::new(cx)); - cx.notify(); + if self.passphrase.is_some() { + return; + } + let dialog = PassphraseDialog::new(cx); + self.passphrase = Some(dialog.clone()); + cx.open_dialog(dialog); + } + + /// The panel stack: the main stack, the split stack, and the divider between them. + pub fn panels(&self) -> &Entity { + &self.panels + } + + /// Empties the stack and opens it on the explore panel, where every session starts. + fn reset_to_explore(app: &WeakEntity, window: &mut Window, cx: &mut App) { + let result = app.update(cx, |this, cx| { + this.panels.update(cx, |panels, cx| panels.clear(cx)) + }); + log_dropped(result); + ExploreView::open(app, window, cx); } } impl Render for AppRoot { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { - let backend = Backend::global(cx); - let signed_in = backend.read(cx).current_user().is_some(); - + let repo_tabs = PanelStack::main_tabs(self.panels.clone(), cx); let titlebar_view = self.titlebar.read(cx); - let workspace = self.workspace.read(cx); - let main = workspace.active_main(); - - let prefix = h_flex() - .gap_1() - .child(titlebar_view.render_new_repository()) - .child(titlebar_view.render_explore()) - .child(titlebar_view.repository_switcher()); - - let tab_bar = h_flex() - .gap_1() - .when_some(titlebar_view.render_repo_tabs(workspace), |bar, tabs| { - bar.child(tabs) - }); div() .relative() .size_full() - .font_family(cx.theme().ui_font()) - .text_color(cx.theme().colors.foreground) .key_context(REPOSITORY_KEY_CONTEXT) .on_action(cx.listener(|this, action: &SwitchRepository, window, cx| { this.titlebar.update(cx, |titlebar, cx| { @@ -148,34 +130,28 @@ impl Render for AppRoot { }); })) .child( - Shell::new("signed-shell") - .titlebar( + v_flex() + .size_full() + .overflow_hidden() + .child( Titlebar::new("signed-titlebar") - .prefix(prefix) - .tab_bar(tab_bar) + .prefix( + h_flex() + .gap_1() + .child(titlebar_view.render_new_repository()) + .child(titlebar_view.render_explore()) + .child(titlebar_view.repository_switcher()), + ) + .tab_bar( + h_flex() + .gap_1() + .when_some(repo_tabs, |bar, tabs| bar.child(tabs)), + ) .when_some(titlebar_view.render_user_menu(cx), |titlebar, menu| { titlebar.suffix(menu) }), ) - .panel( - PanelRow::new("signed-panel") - .when_some(main.as_ref(), |row, main| { - row.main(main.clone()).when(workspace.has_details(), |row| { - row.split(self.workspace.clone()) - }) - }) - .when(!main.is_some() && signed_in, |row| { - row.main(self.empty.clone()) - }) - .when(!main.is_some() && !signed_in, |row| { - row.main(self.sign_in.clone()) - .split_at(self.explore.clone(), px(300.)) - }), - ) - .toasts(self.toasts.clone()), + .child(self.panels.clone()), ) - .child(titlebar_view.palette()) - .children(titlebar_view.dialogs()) - .when_some(self.passphrase.clone(), |el, view| el.child(view)) } } diff --git a/crates/signed_app/src/app/placeholder.rs b/crates/signed_app/src/app/placeholder.rs index e9b7c0e..92e3a6d 100644 --- a/crates/signed_app/src/app/placeholder.rs +++ b/crates/signed_app/src/app/placeholder.rs @@ -1,8 +1,7 @@ use gpui::{ - App, Context, IntoElement, ParentElement as _, Render, SharedString, Styled as _, Window, div, + Context, IntoElement, ParentElement as _, Render, SharedString, Styled as _, Window, div, }; use ui::empty_state::EmptyState; -use ui::layout::panel::Panel; /// A tab that stands in for a screen that is not ported yet. pub struct PlaceholderView { @@ -17,12 +16,6 @@ impl PlaceholderView { } } -impl Panel for PlaceholderView { - fn title(&self, _cx: &App) -> SharedString { - self.title.clone() - } -} - impl Render for PlaceholderView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { div().size_full().child(EmptyState::new(self.title.clone())) diff --git a/crates/signed_app/src/app/sign_in.rs b/crates/signed_app/src/app/sign_in.rs deleted file mode 100644 index d394f7c..0000000 --- a/crates/signed_app/src/app/sign_in.rs +++ /dev/null @@ -1,112 +0,0 @@ -use std::time::{SystemTime, UNIX_EPOCH}; - -use gpui::prelude::FluentBuilder as _; -use gpui::{ - App, Context, Entity, IntoElement, ObjectFit, ParentElement as _, Render, SharedString, - Styled as _, StyledImage as _, Window, div, img, -}; -use ui::button::{Button, ButtonVariant}; -use ui::common::v_flex; -use ui::layout::panel::Panel; -use ui::theme::ActiveTheme as _; - -use crate::identity::import::ImportDialog; -use crate::identity::onboarding::OnboardingDialog; - -pub struct SignedOutView { - banner: SharedString, - onboarding: Option>, - import: Option>, -} - -impl SignedOutView { - pub fn new() -> Self { - Self { - banner: pick_banner(), - onboarding: None, - import: None, - } - } - - fn open_onboarding(&mut self, cx: &mut Context) { - self.onboarding = Some(OnboardingDialog::new(cx)); - cx.notify(); - } - - fn open_import(&mut self, cx: &mut Context) { - self.import = Some(ImportDialog::new(cx)); - cx.notify(); - } -} - -impl Panel for SignedOutView { - fn title(&self, _cx: &App) -> SharedString { - SharedString::from("Signed") - } -} - -/// One of the three banner photos, picked per process launch. -fn pick_banner() -> SharedString { - let nanos = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|now| now.subsec_nanos()) - .unwrap_or(0); - format!("backgrounds/banner{}.jpg", nanos % 3 + 1).into() -} - -impl Render for SignedOutView { - fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { - let theme = cx.theme(); - let colors = theme.colors; - - v_flex() - .size_full() - .child( - v_flex() - .size_full() - .relative() - .bg(colors.background) - .rounded(theme.radius.overlay) - .overflow_hidden() - .child( - div().absolute().inset_0().child( - img(self.banner.clone()) - .size_full() - .object_fit(ObjectFit::Cover) - .rounded(theme.radius.overlay), - ), - ) - .child( - v_flex() - .size_full() - .justify_end() - .p_4() - .gap_6() - .child(img("backgrounds/headline.png").max_w_48()) - .child( - v_flex() - .gap_2() - .w_full() - .child( - Button::new("join") - .label("Join now") - .variant(ButtonVariant::Primary) - .on_click(cx.listener(|this, _, _, cx| { - this.open_onboarding(cx) - })), - ) - .child( - Button::new("import") - .label("Import identity") - .variant(ButtonVariant::Secondary) - .on_click( - cx.listener(|this, _, _, cx| this.open_import(cx)), - ), - ), - ), - ), - ) - .when_some(self.onboarding.clone(), |el, view| el.child(view)) - .when_some(self.import.clone(), |el, view| el.child(view)) - } -} diff --git a/crates/signed_app/src/explore/helpers.rs b/crates/signed_app/src/explore/helpers.rs index 140c43b..e381ff6 100644 --- a/crates/signed_app/src/explore/helpers.rs +++ b/crates/signed_app/src/explore/helpers.rs @@ -1,3 +1,6 @@ +use std::sync::LazyLock; +use std::time::{SystemTime, UNIX_EPOCH}; + use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, Entity, InteractiveElement as _, IntoElement, ParentElement as _, SharedString, @@ -12,12 +15,24 @@ use ui::icons::{Icon, IconRole}; use ui::theme::ActiveTheme as _; use utils::relative_time; +use crate::app::AppRoot; use crate::repo::actions::open_repo_panel; -use crate::repo::helpers::announcement_display_name; -use crate::workspace::Workspace; +use crate::repo::helpers::{announcement_display_name, upstream_display_name}; const RECENT_COUNT: usize = 10; +/// One of the three banner photos, picked per process launch. +pub fn pick_banner() -> SharedString { + static BANNER: LazyLock = LazyLock::new(|| { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|now| now.subsec_nanos()) + .unwrap_or(0); + SharedString::from(format!("backgrounds/banner{}.jpg", nanos % 3 + 1)) + }); + BANNER.clone() +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub(super) enum RepoFilter { #[default] @@ -55,7 +70,7 @@ pub(super) fn render_card( last_activity: Option, announcements: &[Announcement], directory: &Entity, - workspace: &WeakEntity, + workspace: &WeakEntity, cx: &mut gpui::App, ) -> AnyElement { let owner = directory.read(cx).profile(&announcement.owner, cx); @@ -78,16 +93,7 @@ pub(super) fn render_card( let fork_label: Option = announcement.upstream.as_ref().and_then(|upstream| { let addr = upstream.addr.as_ref()?; - let name = announcements - .iter() - .find(|a| a.addr() == *addr) - .map(|a| { - a.name - .as_deref() - .map(SharedString::from) - .unwrap_or_else(|| SharedString::from(a.id.clone())) - }) - .unwrap_or_else(|| SharedString::from(addr.identifier().to_owned())); + let name = upstream_display_name(addr, announcements); Some(SharedString::from(format!("forked from {name}"))) }); diff --git a/crates/signed_app/src/explore/mod.rs b/crates/signed_app/src/explore/mod.rs index 1ae7bf0..e7aaaef 100644 --- a/crates/signed_app/src/explore/mod.rs +++ b/crates/signed_app/src/explore/mod.rs @@ -1,24 +1,32 @@ -mod helpers; +use std::sync::Arc; use gpui::{ AnyElement, App, AppContext as _, Context, Entity, IntoElement, ListAlignment, ListState, - ParentElement as _, Render, SharedString, Styled as _, Subscription, WeakEntity, Window, div, - list, px, + ObjectFit, ParentElement as _, Pixels, Render, SharedString, Styled as _, StyledImage as _, + Subscription, WeakEntity, Window, div, img, list, px, }; use helpers::{RepoFilter, render_card}; use metadata::ProfileDirectory; use nostr::prelude::PublicKey; -use signed_state::RepoListStore; +use signed_state::{Backend, RepoListStore}; +use ui::button::{Button, ButtonVariant}; use ui::common::{h_flex, v_flex}; use ui::empty_state::EmptyState; use ui::icons::{Icon, IconRole}; use ui::input::{Input, InputState, InputStateEvent}; -use ui::layout::panel::Panel; +use ui::layout::panel::{Panel, PanelSlot, SplitSide}; +use ui::layout::root::RootContext as _; +use ui::scrollbar::Scrollbar; use ui::segmented::{Segmented, SegmentedOption}; use ui::theme::ActiveTheme as _; +use crate::app::AppRoot; +use crate::explore::helpers::pick_banner; +use crate::identity::import::ImportDialog; +use crate::identity::onboarding::OnboardingDialog; use crate::shared::panels; -use crate::workspace::Workspace; + +mod helpers; const COLUMNS: usize = 2; // Name row, avatar strip, meta row, and their borders and gaps, in px. @@ -26,7 +34,7 @@ const CARD_HEIGHT: f32 = 40. + 64. + 48. + 2. + 6.; pub struct ExploreView { store: Entity, - workspace: WeakEntity, + workspace: WeakEntity, scroll_handle: ListState, filter: RepoFilter, /// Indices matching [`Self::filter`] into the store's `announcements`. @@ -36,6 +44,8 @@ pub struct ExploreView { directory: Entity, _search_subscription: Subscription, _store_subscription: Subscription, + /// Observes the panel stack for the onboarding sidebar, set once this view is in it. + _stack_subscription: Option, } impl ExploreView { @@ -43,7 +53,7 @@ impl ExploreView { pub(crate) const PANEL_ID: &'static str = "Explore"; /// Opens the explore panel in the main panel, reusing it when it is already cached. - pub(crate) fn open(workspace: &WeakEntity, window: &mut Window, cx: &mut App) { + pub(crate) fn open(workspace: &WeakEntity, window: &mut Window, cx: &mut App) { panels::open_primary( workspace, Self::PANEL_ID, @@ -56,7 +66,7 @@ impl ExploreView { ); } - pub fn new(workspace: WeakEntity, cx: &mut Context) -> Self { + pub fn new(workspace: WeakEntity, cx: &mut Context) -> Self { let store = RepoListStore::global(cx); let directory = ProfileDirectory::new(cx); @@ -73,9 +83,13 @@ impl ExploreView { this.rebuild_rows(cx); }); + // The root and the stack are still being updated while this view is built. cx.defer(move |cx| { - if let Err(error) = weak.update(cx, |this, cx| this.rebuild_rows(cx)) { - log::warn!("failed to load explore rows: {error}"); + if let Err(error) = weak.update(cx, |this, cx| { + this.rebuild_rows(cx); + this.watch_stack(cx); + }) { + log::warn!("failed to set up the explore panel: {error}"); } }); @@ -89,6 +103,7 @@ impl ExploreView { directory, _search_subscription: search_subscription, _store_subscription: store_subscription, + _stack_subscription: None, } } @@ -123,6 +138,50 @@ impl ExploreView { } } + /// Observes the panel stack so the onboarding sidebar follows the shown panel. + fn watch_stack(&mut self, cx: &mut Context) { + let Ok(stack) = self + .workspace + .read_with(cx, |workspace, _| workspace.panels().clone()) + else { + log::warn!("failed to watch the panel stack: the app root is gone"); + return; + }; + self._stack_subscription = + Some(cx.observe(&stack, |this, _stack, cx| this.sync_sidebar(cx))); + self.sync_sidebar(cx); + } + + /// Shows the onboarding sidebar while signed out and an explore panel is shown, and closes it otherwise. + fn sync_sidebar(&mut self, cx: &mut Context) { + let signed_out = Backend::global(cx).read(cx).current_user().is_none(); + let explore = SharedString::from(Self::PANEL_ID); + let sidebar = SharedString::from(OnboardingSidebar::PANEL_ID); + + let result = self.workspace.update(cx, |workspace, cx| { + workspace.panels().clone().update(cx, |stack, cx| { + let shown = signed_out && stack.is_active(PanelSlot::Main, &explore); + + if shown && !stack.is_open(PanelSlot::Split, &sidebar) { + let view = Arc::new(cx.new(|_| OnboardingSidebar)); + stack.insert_split_at( + sidebar.clone(), + OnboardingSidebar::WIDTH, + SplitSide::Leading, + view, + cx, + ); + } else if !shown { + stack.close(PanelSlot::Split, &sidebar, cx); + } + }) + }); + + if let Err(error) = result { + log::warn!("failed to update the onboarding sidebar: {error}"); + } + } + fn render_header( search: Entity, filter: RepoFilter, @@ -256,9 +315,75 @@ impl Render for ExploreView { }) .size_full(), ) - .child(crate::shared::widgets::scroll_overlay( - "explore-scroll", - scroll_handle, - )) + .child(Scrollbar::vertical("explore-scroll", scroll_handle)) + } +} + +/// The onboarding sidebar shown beside the explore panel while signed out. +struct OnboardingSidebar; + +impl OnboardingSidebar { + /// The identifier of the sidebar in the panel stack; shown as its tab label. + const PANEL_ID: &'static str = "Onboarding"; + /// The width the sidebar opens at. + const WIDTH: Pixels = px(300.); +} + +impl Panel for OnboardingSidebar { + fn title(&self, _cx: &App) -> SharedString { + SharedString::from(Self::PANEL_ID) + } +} + +impl Render for OnboardingSidebar { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let theme = cx.theme(); + let colors = theme.colors; + + v_flex() + .size_full() + .relative() + .bg(colors.background) + .rounded(theme.radius.overlay) + .overflow_hidden() + .child( + div().absolute().inset_0().child( + img(pick_banner()) + .size_full() + .object_fit(ObjectFit::Cover) + .rounded(theme.radius.overlay), + ), + ) + .child( + v_flex() + .size_full() + .justify_end() + .p_4() + .gap_6() + .child(img("backgrounds/headline.png").max_w_48()) + .child( + v_flex() + .gap_2() + .w_full() + .child( + Button::new("join") + .label("Join now") + .variant(ButtonVariant::Primary) + .on_click(|_, _, cx| { + let dialog = OnboardingDialog::new(cx); + cx.open_dialog(dialog) + }), + ) + .child( + Button::new("import") + .label("Import identity") + .variant(ButtonVariant::Secondary) + .on_click(|_, _, cx| { + let dialog = ImportDialog::new(cx); + cx.open_dialog(dialog) + }), + ), + ), + ) } } diff --git a/crates/signed_app/src/identity/onboarding.rs b/crates/signed_app/src/identity/onboarding.rs index c8ba544..b2e356b 100644 --- a/crates/signed_app/src/identity/onboarding.rs +++ b/crates/signed_app/src/identity/onboarding.rs @@ -4,14 +4,13 @@ use gpui::{ Styled as _, Window, div, px, }; use signed_state::Backend; -use ui::button::Button; use ui::common::v_flex; use ui::dialog::{Dialog, DialogHandle}; use ui::field::Field; use ui::input::{Input, InputState}; use ui::theme::ActiveTheme as _; -use crate::shared::progress::{DialogProgress, error_row, run_dialog_task}; +use crate::shared::progress::{DialogProgress, dialog_submit_button, error_row, run_dialog_task}; pub struct OnboardingDialog { handle: DialogHandle, @@ -108,16 +107,18 @@ impl Render for OnboardingDialog { let busy = action_state.read(cx).busy; let this = this.clone(); - let create: AnyElement = Button::new("create-identity") - .label("Create new identity") - .loading(busy) - .disabled(busy) - .on_click(move |_, _, cx| { - crate::shared::log_dropped( - this.update(cx, |this, cx| this.create_identity(cx)), - ); - }) - .into_any_element(); + let create: AnyElement = dialog_submit_button( + "create-identity", + "Create new identity", + None, + busy, + &this, + |this, _window, cx| { + this.create_identity(cx); + Ok(()) + }, + ) + .into_any_element(); vec![create] }) diff --git a/crates/signed_app/src/identity/passphrase.rs b/crates/signed_app/src/identity/passphrase.rs index 91947f9..bfc2f24 100644 --- a/crates/signed_app/src/identity/passphrase.rs +++ b/crates/signed_app/src/identity/passphrase.rs @@ -4,14 +4,15 @@ use gpui::{ Styled as _, Subscription, Window, px, }; use signed_state::Backend; -use ui::button::Button; use ui::common::v_flex; use ui::dialog::{Dialog, DialogHandle}; use ui::field::Field; -use ui::icons::{Icon, IconRole}; +use ui::icons::IconRole; use ui::input::{Input, InputState, InputStateEvent}; -use crate::shared::progress::{DialogProgress, error_row, push_steps_row, run_dialog_task}; +use crate::shared::progress::{ + DialogProgress, dialog_submit_button, error_row, push_steps_row, run_dialog_task, +}; pub struct PassphraseDialog { handle: DialogHandle, @@ -102,15 +103,18 @@ impl Render for PassphraseDialog { let busy = action_state.read(cx).busy; let this = this.clone(); - let unlock: AnyElement = Button::new("unlock") - .label("Unlock") - .icon(Icon::named(IconRole::Unlock)) - .loading(busy) - .disabled(busy) - .on_click(move |_, _, cx| { - crate::shared::log_dropped(this.update(cx, |this, cx| this.unlock(cx))); - }) - .into_any_element(); + let unlock: AnyElement = dialog_submit_button( + "unlock", + "Unlock", + Some(IconRole::Unlock), + busy, + &this, + |this, _window, cx| { + this.unlock(cx); + Ok(()) + }, + ) + .into_any_element(); vec![unlock] }) diff --git a/crates/signed_app/src/inbox/helpers.rs b/crates/signed_app/src/inbox/helpers.rs index dcffbe7..478e9da 100644 --- a/crates/signed_app/src/inbox/helpers.rs +++ b/crates/signed_app/src/inbox/helpers.rs @@ -9,6 +9,7 @@ use ui::avatar::Avatar; use ui::badge::Badge; use ui::common::{Sizable as _, h_flex, v_flex}; use ui::icons::{Icon, IconRole}; +use ui::status_dot::{StatusDot, StatusDotVariant}; use ui::theme::ActiveTheme as _; use utils::relative_time; @@ -101,8 +102,7 @@ pub fn thread( .child(div().flex_1()) .when(unread, |this| { this.child( - ui::status_dot::StatusDot::new(("inbox-unread", ix)) - .variant(ui::status_dot::StatusDotVariant::Accent), + StatusDot::new(("inbox-unread", ix)).variant(StatusDotVariant::Accent), ) }), ) diff --git a/crates/signed_app/src/inbox/mod.rs b/crates/signed_app/src/inbox/mod.rs index dbeb362..35fd648 100644 --- a/crates/signed_app/src/inbox/mod.rs +++ b/crates/signed_app/src/inbox/mod.rs @@ -15,6 +15,7 @@ use signed_state::{Backend, BackendEvent, Inbox, RefreshGate, RefreshRequest, Re use ui::alert::{Alert, AlertSeverity, AlertStyle}; use ui::button::Button; use ui::common::{StyledExt as _, h_flex, v_flex}; +use ui::empty_state::EmptyState; use ui::icons::{Icon, IconRole}; use ui::layout::panel::Panel; use ui::scroll_area::ScrollArea; @@ -23,10 +24,9 @@ mod helpers; use helpers::{empty_section_row, repo_header, thread}; +use crate::app::AppRoot; use crate::repo::actions::{RepoItem, open_repo_item}; use crate::repo::helpers::announcement_display_name; -use crate::shared::widgets::empty_state; -use crate::workspace::Workspace; const MAX_SUB_ACTIVITIES: usize = 5; @@ -45,7 +45,7 @@ struct InboxSection { } pub struct InboxView { - workspace: WeakEntity, + workspace: WeakEntity, threads: Arc>, sections: Arc>, rows: Arc>, @@ -60,7 +60,7 @@ pub struct InboxView { } impl InboxView { - pub fn new(workspace: WeakEntity, cx: &mut Context) -> Self { + pub fn new(workspace: WeakEntity, cx: &mut Context) -> Self { let backend = Backend::global(cx); let inbox = backend.read(cx).inbox(); @@ -470,7 +470,7 @@ impl Render for InboxView { .min_h_0() .px_4() .child(if rows.is_empty() { - empty_state("You're all caught up.") + EmptyState::centered("You're all caught up.") } else { ScrollArea::new("inbox-scroll") .flex_1() diff --git a/crates/signed_app/src/issues/detail.rs b/crates/signed_app/src/issues/detail.rs index 71115a9..d4c3e56 100644 --- a/crates/signed_app/src/issues/detail.rs +++ b/crates/signed_app/src/issues/detail.rs @@ -8,13 +8,16 @@ use signed_core::GitEvent; use signed_state::RepoStore; use ui::avatar::Avatar; use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex}; +use ui::empty_state::EmptyState; use ui::input::InputState; use ui::layout::panel::Panel; use ui::scroll_area::ScrollArea; +use ui::spinner::Spinner; use ui::theme::ActiveTheme as _; use utils::relative_time; -use crate::issues::helpers::{comment_form, comments_section, issue_roots, sidebar_section}; +use crate::issues::helpers::{comment_form, comments_section, sidebar_section}; +use crate::shared::log_dropped; use crate::shared::widgets::status_badge; pub struct IssueDetailView { @@ -39,7 +42,7 @@ impl IssueDetailView { let directory = ProfileDirectory::new(cx); let weak = cx.entity().downgrade(); cx.defer(move |cx| { - crate::shared::log_dropped(weak.update(cx, |this, cx| this.track_participants(cx))); + log_dropped(weak.update(cx, |this, cx| this.track_participants(cx))); }); Self { @@ -94,9 +97,9 @@ impl Render for IssueDetailView { let Some(issue) = store.issues.iter().find(|issue| issue.id == self.issue_id) else { // A not-yet-loaded store is not the same as a missing issue. return if store.loaded { - crate::shared::widgets::empty_state("Issue not found") + EmptyState::centered("Issue not found") } else { - crate::shared::widgets::centered_spinner("issue-loading") + Spinner::centered("issue-loading") }; }; @@ -189,7 +192,7 @@ impl Render for IssueDetailView { .child(comment_form( &self.store, issue_id, - issue_roots, + &store.issues, &self.comment_input, "comment", cx, @@ -200,7 +203,7 @@ impl Render for IssueDetailView { .child(sidebar_section( &self.store, issue_id, - issue_roots, + &store.issues, true, &self.directory, cx, diff --git a/crates/signed_app/src/issues/helpers.rs b/crates/signed_app/src/issues/helpers.rs index 260fcfc..31258ad 100644 --- a/crates/signed_app/src/issues/helpers.rs +++ b/crates/signed_app/src/issues/helpers.rs @@ -76,24 +76,16 @@ pub(crate) fn filter_by_status<'a>( (visible, counts) } -pub(crate) fn issue_roots(store: &RepoStore) -> &[Event] { - &store.issues -} - -pub(crate) fn pr_roots(store: &RepoStore) -> &[Event] { - &store.pull_requests -} - pub(crate) fn sidebar_section( store: &Entity, id: EventId, - roots: fn(&RepoStore) -> &[Event], + roots: &[Event], top_gap: bool, directory: &Entity, cx: &App, ) -> AnyElement { let store = store.read(cx); - let Some(root) = roots(store).iter().find(|event| event.id == id) else { + let Some(root) = roots.iter().find(|event| event.id == id) else { return div().into_any_element(); }; @@ -116,7 +108,13 @@ pub(crate) fn sidebar_section( v_flex() .when(top_gap, |this| this.mt_4()) .gap_2() - .child(crate::shared::widgets::section_label("Participants", cx)) + .child( + div() + .text_xs() + .font_medium() + .text_color(cx.theme().colors.muted_foreground) + .child("Participants"), + ) .children(participants.iter().map(|pubkey| { let profile = directory.read(cx).profile(pubkey, cx); let name = profile.name(); @@ -136,7 +134,13 @@ pub(crate) fn sidebar_section( .child( v_flex() .gap_2() - .child(crate::shared::widgets::section_label("Labels", cx)) + .child( + div() + .text_xs() + .font_medium() + .text_color(cx.theme().colors.muted_foreground) + .child("Labels"), + ) .map(|this| { if labels.is_empty() { this.child( @@ -215,11 +219,14 @@ pub(crate) fn comments_section( pub(crate) fn comment_form( store: &Entity, root: EventId, - roots: fn(&RepoStore) -> &[Event], + roots: &[Event], comment_input: &Entity, button_id: &'static str, cx: &App, ) -> AnyElement { + let Some(root) = roots.iter().find(|event| event.id == root).cloned() else { + return div().into_any_element(); + }; let comment_input = comment_input.clone(); let store = store.clone(); @@ -254,13 +261,6 @@ pub(crate) fn comment_form( if content.is_empty() { return; } - let Some(root) = roots(store.read(cx)) - .iter() - .find(|event| event.id == root) - .cloned() - else { - return; - }; store.update(cx, |store, cx| { store.comment(&root, content, cx); }); diff --git a/crates/signed_app/src/issues/mod.rs b/crates/signed_app/src/issues/mod.rs index 7169421..fbc1922 100644 --- a/crates/signed_app/src/issues/mod.rs +++ b/crates/signed_app/src/issues/mod.rs @@ -19,17 +19,18 @@ use utils::relative_time; use std::rc::Rc; use self::detail::IssueDetailView; +use crate::app::AppRoot; use crate::repo::helpers::short_id; -use crate::shared::event_list::{EventList, EventRow}; +use crate::shared::event_list::{EventHandler, EventList, EventRow, filter_toolbar}; +use crate::shared::log_dropped; use crate::shared::panels; -use crate::workspace::Workspace; pub mod detail; pub(crate) mod helpers; pub mod new_issue; pub struct IssuesView { - workspace: WeakEntity, + workspace: WeakEntity, store: Entity, new_issue: Option>, filter: IssueFilter, @@ -45,7 +46,7 @@ pub struct IssuesView { impl IssuesView { pub fn new( - workspace: WeakEntity, + workspace: WeakEntity, store: Entity, cx: &mut Context, ) -> Self { @@ -54,7 +55,7 @@ impl IssuesView { }); let weak = cx.entity().downgrade(); cx.defer(move |cx| { - crate::shared::log_dropped(weak.update(cx, |this, cx| this.rebuild(cx))); + log_dropped(weak.update(cx, |this, cx| this.rebuild(cx))); }); Self { @@ -128,7 +129,7 @@ impl IssuesView { let muted = cx.theme().colors.muted_foreground; let weak = cx.entity().downgrade(); - crate::shared::event_list::filter_toolbar( + filter_toolbar( cx, [ Segmented::new("issue-filter", self.filter) @@ -190,7 +191,7 @@ impl Render for IssuesView { let id_hex = issue.id.to_hex(); let status = store.read(cx).status_of(issue); - let on_click: crate::shared::event_list::EventHandler = { + let on_click: EventHandler = { let workspace = workspace.clone(); let store = store.clone(); Rc::new(move |_, window, cx| { diff --git a/crates/signed_app/src/issues/new_issue.rs b/crates/signed_app/src/issues/new_issue.rs index 6c11980..45c20f7 100644 --- a/crates/signed_app/src/issues/new_issue.rs +++ b/crates/signed_app/src/issues/new_issue.rs @@ -3,14 +3,13 @@ use gpui::{ Styled as _, Window, div, }; use signed_state::RepoStore; -use ui::button::Button; use ui::common::v_flex; use ui::dialog::{Dialog, DialogHandle}; use ui::field::Field; use ui::input::{Input, InputState}; use ui::theme::ActiveTheme as _; -use crate::shared::progress::DialogProgress; +use crate::shared::progress::{DialogProgress, dialog_submit_button}; pub struct NewIssueDialog { handle: DialogHandle, @@ -87,14 +86,18 @@ impl Render for NewIssueDialog { let this = this.clone(); let busy = action_state.read(cx).busy; vec![ - Button::new("create-issue") - .label("Create issue") - .loading(busy) - .disabled(busy) - .on_click(move |_, _, cx| { - crate::shared::log_dropped(this.update(cx, |this, cx| this.submit(cx))); - }) - .into_any_element() as AnyElement, + dialog_submit_button( + "create-issue", + "Create issue", + None, + busy, + &this, + |this, _window, cx| { + this.submit(cx); + Ok(()) + }, + ) + .into_any_element() as AnyElement, ] }) } diff --git a/crates/signed_app/src/lib.rs b/crates/signed_app/src/lib.rs index 2147dfa..43c1ae1 100644 --- a/crates/signed_app/src/lib.rs +++ b/crates/signed_app/src/lib.rs @@ -9,12 +9,16 @@ mod repo; mod settings; mod shared; mod titlebar; -mod workspace; pub use app::AppRoot; -pub use app::helpers::{apply_appearance, apply_appearance_mode}; +pub use app::helpers::apply_appearance_mode; use gpui::{App, AppContext as _, Entity, Window}; +use ui::layout::root::Root; -pub fn root(window: &mut Window, cx: &mut App) -> Entity { - cx.new(|cx| AppRoot::new(window, cx)) +pub fn root(window: &mut Window, cx: &mut App) -> Entity { + let root = cx.new(|cx| Root::new(window, cx)); + let content: Entity = cx.new(|cx| AppRoot::new(window, cx)); + + root.update(cx, |root, cx| root.set_content(content, cx)); + root } diff --git a/crates/signed_app/src/pull_requests/detail.rs b/crates/signed_app/src/pull_requests/detail.rs index 9d87c59..22e9ad1 100644 --- a/crates/signed_app/src/pull_requests/detail.rs +++ b/crates/signed_app/src/pull_requests/detail.rs @@ -16,19 +16,24 @@ use ui::avatar::Avatar; use ui::button::Button; use ui::clipboard::ClipboardButton; use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex}; +use ui::empty_state::EmptyState; use ui::icons::{Icon, IconRole}; use ui::input::InputState; use ui::layout::panel::Panel; use ui::scroll_area::ScrollArea; +use ui::spinner::Spinner; use ui::tabs::{Tab, Tabs}; use ui::theme::ActiveTheme as _; use utils::relative_time; use super::dialogs; -use crate::issues::helpers::{comment_form, comments_section, pr_roots, sidebar_section}; +use crate::app::AppRoot; +use crate::issues::helpers::{comment_form, comments_section, sidebar_section}; use crate::repo::commit_diff::{CommitDiffView, DiffPane}; -use crate::shared::widgets::{empty_state, status_badge}; -use crate::workspace::Workspace; +use crate::shared::event_list::commit_list; +use crate::shared::log_dropped; +use crate::shared::panels::open_detail; +use crate::shared::widgets::status_badge; const NOT_FOUND: &str = "Pull request not found"; @@ -44,7 +49,7 @@ struct PrBinding { } pub struct PullRequestDetailView { - workspace: WeakEntity, + workspace: WeakEntity, store: Entity, pr_id: EventId, update_dialog: Option>, @@ -67,7 +72,7 @@ pub struct PullRequestDetailView { impl PullRequestDetailView { pub fn new( - workspace: WeakEntity, + workspace: WeakEntity, store: Entity, pr_id: EventId, _window: &mut Window, @@ -82,7 +87,7 @@ impl PullRequestDetailView { }); cx.defer(move |cx| { - crate::shared::log_dropped(weak.update(cx, |this, cx| this.sync(cx))); + log_dropped(weak.update(cx, |this, cx| this.sync(cx))); }); Self { @@ -300,7 +305,7 @@ impl PullRequestDetailView { }; let workspace = self.workspace.clone(); let commit_id = commit_id.to_owned(); - crate::shared::panels::open_detail( + open_detail( &workspace, id, move |window, cx| { @@ -336,7 +341,7 @@ impl PullRequestDetailView { ] }) .on_change(move |index, _, cx| { - crate::shared::log_dropped(weak.update(cx, |this, cx| { + log_dropped(weak.update(cx, |this, cx| { this.active_tab = index; cx.notify(); })); @@ -346,10 +351,10 @@ impl PullRequestDetailView { fn render_discussion(&mut self, cx: &mut Context) -> AnyElement { if self.loading { - return centered_spinner(); + return Spinner::centered("pr-loading"); } if let Some(error) = self.error.clone() { - return empty_state(error); + return EmptyState::centered(error); } let (author, picture, age, root_id, pubkey) = { let store = self.store.read(cx); @@ -358,7 +363,7 @@ impl PullRequestDetailView { .iter() .find(|pr| pr.id == self.pr_id && pr.kind == Kind::GitPullRequest) else { - return empty_state(NOT_FOUND); + return EmptyState::centered(NOT_FOUND); }; let profile = self.directory.read(cx).profile(&root.pubkey, cx); ( @@ -370,6 +375,8 @@ impl PullRequestDetailView { ) }; + let store = self.store.read(cx); + h_flex() .size_full() .min_h_0() @@ -416,7 +423,7 @@ impl PullRequestDetailView { .child(comment_form( &self.store, root_id, - pr_roots, + &store.pull_requests, &self.comment_input, "pr-comment", cx, @@ -426,7 +433,7 @@ impl PullRequestDetailView { .child(sidebar_section( &self.store, root_id, - pr_roots, + &store.pull_requests, true, &self.directory, cx, @@ -436,29 +443,29 @@ impl PullRequestDetailView { fn render_files(&self, _cx: &mut Context) -> AnyElement { if self.loading { - return centered_spinner(); + return Spinner::centered("pr-loading"); } if let Some(error) = self.error.clone() { - return empty_state(error); + return EmptyState::centered(error); } self.pane.clone().into_any_element() } fn render_commits(&self, cx: &mut Context) -> AnyElement { if self.loading { - return centered_spinner(); + return Spinner::centered("pr-loading"); } if let Some(error) = self.error.clone() { - return empty_state(error); + return EmptyState::centered(error); } if self.commits.is_empty() { - return empty_state("No commits found"); + return EmptyState::centered("No commits found"); } let commits = Arc::clone(&self.commits); let worktree = self.worktree.clone(); let view = cx.entity().downgrade(); - crate::shared::event_list::commit_list( + commit_list( "pr-commits", "pr-commits-scroll", commits, @@ -467,12 +474,11 @@ impl PullRequestDetailView { move |commit, window, cx| { if let Some(worktree) = worktree.clone() { let id = commit.id.clone(); - crate::shared::log_dropped(view.update(cx, |this, cx| { + log_dropped(view.update(cx, |this, cx| { this.open_commit_diff(worktree, &id, window, cx); })); } }, - cx, ) } @@ -503,8 +509,9 @@ impl PullRequestDetailView { .px_4() .py_2() .gap_2() + // The top right corner is the panel toolbar's. .child( - h_flex().gap_2().child(status_badge(status)).child( + h_flex().gap_2().pr_16().child(status_badge(status)).child( div() .flex_1() .min_w_0() @@ -528,7 +535,7 @@ impl PullRequestDetailView { .when(can_update, |this| { this.child(Button::new("update-pr").label("Update").small().on_click( move |_, _, cx| { - crate::shared::log_dropped(weak.update(cx, |this, cx| { + log_dropped(weak.update(cx, |this, cx| { let root = this .store .read(cx) @@ -577,6 +584,10 @@ impl Panel for PullRequestDetailView { fn loading(&self, _cx: &App) -> bool { self.loading } + + fn toolbar(&self, _cx: &App) -> bool { + true + } } impl Render for PullRequestDetailView { @@ -595,7 +606,3 @@ impl Render for PullRequestDetailView { }) } } - -fn centered_spinner() -> AnyElement { - crate::shared::widgets::centered_spinner("pr-loading") -} diff --git a/crates/signed_app/src/pull_requests/dialogs/update.rs b/crates/signed_app/src/pull_requests/dialogs/update.rs index 388d6f6..7684f18 100644 --- a/crates/signed_app/src/pull_requests/dialogs/update.rs +++ b/crates/signed_app/src/pull_requests/dialogs/update.rs @@ -4,14 +4,13 @@ use gpui::{ }; use nostr::prelude::Event; use signed_state::RepoStore; -use ui::button::Button; use ui::common::v_flex; use ui::dialog::{Dialog, DialogHandle}; use ui::field::Field; use ui::input::{Input, InputState}; use ui::theme::ActiveTheme as _; -use crate::shared::progress::DialogProgress; +use crate::shared::progress::{DialogProgress, dialog_submit_button}; pub struct UpdatePrDialog { handle: DialogHandle, @@ -80,14 +79,18 @@ impl Render for UpdatePrDialog { let this = this.clone(); let busy = action_state.read(cx).busy; vec![ - Button::new("submit-update") - .label("Update pull request") - .loading(busy) - .disabled(busy) - .on_click(move |_, _, cx| { - crate::shared::log_dropped(this.update(cx, |this, cx| this.submit(cx))); - }) - .into_any_element() as AnyElement, + dialog_submit_button( + "submit-update", + "Update pull request", + None, + busy, + &this, + |this, _window, cx| { + this.submit(cx); + Ok(()) + }, + ) + .into_any_element() as AnyElement, ] }) } diff --git a/crates/signed_app/src/pull_requests/helpers.rs b/crates/signed_app/src/pull_requests/helpers.rs index c484503..912e99a 100644 --- a/crates/signed_app/src/pull_requests/helpers.rs +++ b/crates/signed_app/src/pull_requests/helpers.rs @@ -7,6 +7,7 @@ use ui::menu::MenuItem; use utils::middle_truncate; use super::NewPullRequestView; +use crate::repo::helpers::announcement_display_name; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PullRequestFilter { @@ -77,8 +78,10 @@ pub fn source_menu_items( .file_name() .map(|name| name.to_string_lossy().into_owned()) .unwrap_or_else(|| path.display().to_string()); + let target = view.clone(); let path_for_action = path.clone(); + items.push( MenuItem::new(truncate_label(&label)) .checked(active_path.as_ref() == Some(&path)) @@ -113,14 +116,12 @@ pub fn source_menu_items( } else { SharedString::from(format!("by {}", shorten_owner(&candidate.owner))) }; - let title = format!( - "{} — {}", - crate::repo::helpers::announcement_display_name(&candidate), - subtitle - ); + + let title = format!("{} — {}", announcement_display_name(&candidate), subtitle); let target = view.clone(); let checked = active_fork == Some(candidate.addr()); let announcement = candidate; + items.push( MenuItem::new(truncate_label(&title)) .checked(checked) @@ -135,5 +136,6 @@ pub fn source_menu_items( ); } } + items } diff --git a/crates/signed_app/src/pull_requests/mod.rs b/crates/signed_app/src/pull_requests/mod.rs index fd7c7a8..3ad6cff 100644 --- a/crates/signed_app/src/pull_requests/mod.rs +++ b/crates/signed_app/src/pull_requests/mod.rs @@ -29,13 +29,15 @@ use helpers::PullRequestFilter; pub use new::NewPullRequestView; pub use send_patch::SendPatchView; +use crate::app::AppRoot; use crate::issues::helpers::{StatusCounts, filter_by_status}; use crate::repo::helpers::short_id; -use crate::shared::event_list::{EventList, EventRow}; -use crate::workspace::Workspace; +use crate::shared::event_list::{EventHandler, EventList, EventRow, filter_toolbar}; +use crate::shared::log_dropped; +use crate::shared::panels::open_detail; pub struct PullRequestsView { - workspace: WeakEntity, + workspace: WeakEntity, store: Entity, filter: PullRequestFilter, visible_prs: Vec, @@ -49,7 +51,7 @@ pub struct PullRequestsView { impl PullRequestsView { pub fn new( - workspace: WeakEntity, + workspace: WeakEntity, store: Entity, cx: &mut Context, ) -> Self { @@ -59,7 +61,7 @@ impl PullRequestsView { }); cx.defer(move |cx| { - crate::shared::log_dropped(weak.update(cx, |this, cx| { + log_dropped(weak.update(cx, |this, cx| { this.rebuild(cx); })); }); @@ -139,7 +141,7 @@ impl PullRequestsView { let workspace_for_build = workspace.clone(); let store = self.store.clone(); - crate::shared::panels::open_detail( + open_detail( &workspace, id.clone(), move |window, cx| { @@ -168,7 +170,7 @@ impl PullRequestsView { let workspace_for_build = workspace.clone(); let store = self.store.clone(); - crate::shared::panels::open_detail( + open_detail( &workspace, id.clone(), move |window, cx| { @@ -195,7 +197,7 @@ impl PullRequestsView { let menu_open_weak = cx.entity().downgrade(); let patch_weak = cx.entity().downgrade(); - crate::shared::event_list::filter_toolbar( + filter_toolbar( cx, [ Segmented::new("pr-filter", self.filter) @@ -248,7 +250,7 @@ impl PullRequestsView { } }) .on_open_change(move |open, _, cx| { - crate::shared::log_dropped(menu_open_weak.update(cx, |this, cx| { + log_dropped(menu_open_weak.update(cx, |this, cx| { this.new_pr_menu_open = open; cx.notify(); })); @@ -257,7 +259,7 @@ impl PullRequestsView { vec![MenuItem::new("Send Patch").handler({ let weak = patch_weak.clone(); move |window, cx| { - crate::shared::log_dropped(weak.update(cx, |this, cx| { + log_dropped(weak.update(cx, |this, cx| { this.open_send_patch(window, cx); })); } @@ -302,14 +304,14 @@ impl Render for PullRequestsView { let id_hex = pr.id.to_hex(); let status = store.read(cx).status_of(pr); - let on_click: crate::shared::event_list::EventHandler = { + let on_click: EventHandler = { let workspace = workspace.clone(); let store = store.clone(); Rc::new(move |_, window, cx| { let id = SharedString::from(format!("pr:{pr_id}")); let workspace_for_build = workspace.clone(); let store = store.clone(); - crate::shared::panels::open_detail( + open_detail( &workspace, id, move |window, cx| { diff --git a/crates/signed_app/src/pull_requests/new.rs b/crates/signed_app/src/pull_requests/new.rs index 265b4c1..7827be1 100644 --- a/crates/signed_app/src/pull_requests/new.rs +++ b/crates/signed_app/src/pull_requests/new.rs @@ -1,32 +1,38 @@ -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::sync::Arc; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, - ParentElement as _, Render, SharedString, Styled as _, Subscription, UniformListScrollHandle, - WeakEntity, Window, div, px, + ParentElement as _, PathPromptOptions, Render, SharedString, Styled as _, Subscription, + UniformListScrollHandle, WeakEntity, Window, div, px, }; -use signed_state::{CheckoutsStore, RepoStore}; -use ui::button::Button; +use nostr::prelude::Url; +use signed_core::Announcement; +use signed_git::{GitCache, Repo}; +use signed_state::{Backend, CheckoutsStore, Mirrors, RepoListStore, RepoStore}; +use ui::button::{Button, ButtonVariant}; use ui::combobox::{Combobox, ComboboxState}; use ui::common::{StyledExt as _, h_flex, v_flex}; +use ui::empty_state::EmptyState; use ui::icons::{Icon, IconRole}; use ui::input::{Input, InputState}; use ui::layout::panel::Panel; use ui::menu::Menu; +use ui::spinner::Spinner; use ui::tabs::{Tab, Tabs}; use super::helpers::{ForkCompare, truncate_label}; +use crate::app::AppRoot; use crate::repo::commit_diff::{CommitDiffView, DiffPane}; +use crate::repo::helpers::announcement_display_name; +use crate::shared::event_list::commit_list; +use crate::shared::log_dropped; +use crate::shared::panels::{close_detail, open_detail}; use crate::shared::progress::error_row; -use crate::shared::widgets::empty_state; -use crate::workspace::Workspace; - -mod source; pub struct NewPullRequestView { - workspace: WeakEntity, + workspace: WeakEntity, panel_id: SharedString, pub(super) store: Entity, pub(super) repo_path: Option, @@ -55,7 +61,7 @@ pub struct NewPullRequestView { impl NewPullRequestView { pub fn new( - workspace: WeakEntity, + workspace: WeakEntity, panel_id: SharedString, store: Entity, window: &mut Window, @@ -73,7 +79,7 @@ impl NewPullRequestView { let weak = weak.clone(); move |value, _window, cx| { if let Some(base) = value { - crate::shared::log_dropped(weak.update(cx, |this, cx| { + log_dropped(weak.update(cx, |this, cx| { if this.base == base { return; } @@ -94,7 +100,7 @@ impl NewPullRequestView { let weak = weak.clone(); move |value, _window, cx| { if let Some(compare) = value { - crate::shared::log_dropped(weak.update(cx, |this, cx| { + log_dropped(weak.update(cx, |this, cx| { if this.compare == compare { return; } @@ -110,7 +116,7 @@ impl NewPullRequestView { }); window.defer(cx, move |window, cx| { - crate::shared::log_dropped(weak.update(cx, |this, cx| { + log_dropped(weak.update(cx, |this, cx| { let Some(addr) = this.store.read(cx).addr().cloned() else { return; }; @@ -209,9 +215,7 @@ impl NewPullRequestView { this.update(cx, |this, _cx| { this.submitting = false; })?; - crate::shared::log_dropped( - workspace.update(cx, |workspace, cx| workspace.close_detail(&panel_id, cx)), - ); + close_detail(&workspace, &panel_id, cx); Ok(()) }); self.push_task(task); @@ -227,7 +231,7 @@ impl NewPullRequestView { }; let workspace = self.workspace.clone(); let commit_id = commit_id.to_owned(); - crate::shared::panels::open_detail( + open_detail( &workspace, id, move |window, cx| { @@ -270,9 +274,7 @@ impl NewPullRequestView { let active_fork = self.fork.as_ref().map(|fork| fork.announcement.addr()); let can_submit = self.submit_enabled(cx); let source_label = match &self.fork { - Some(fork) => truncate_label(&crate::repo::helpers::announcement_display_name( - &fork.announcement, - )), + Some(fork) => truncate_label(&announcement_display_name(&fork.announcement)), None => self.repo_path.as_ref().map_or_else( || SharedString::from("No source"), |path| truncate_label(&path.display().to_string()), @@ -289,42 +291,45 @@ impl NewPullRequestView { .child( v_flex() .gap_1() - .child(label("Merge Into")) + .child(div().text_xs().font_medium().child("Merge Into")) .child(div().w(px(160.)).child(self.base_select.clone())), ) .child( v_flex() .gap_1() - .child(label("Pull From")) + .child(div().text_xs().font_medium().child("Pull From")) .child(div().w(px(160.)).child(self.compare_select.clone())), ) .child( - v_flex().gap_1().child(label("Source")).child( - Menu::new("pr-source") - .open(self.source_open) - .on_change(move |open, _, cx| { - crate::shared::log_dropped(weak_menu.update(cx, |this, cx| { - this.source_open = open; - cx.notify(); - })); - }) - .trigger(move |_, _| { - Button::new("compare-source") - .label(source_label.clone()) - .variant(ui::button::ButtonVariant::Secondary) - .into_any_element() - }) - .items(move |_, _| { - super::helpers::source_menu_items( - source_view.clone(), - associated.clone(), - active_path.clone(), - candidates.clone(), - user, - active_fork.clone(), - ) - }), - ), + v_flex() + .gap_1() + .child(div().text_xs().font_medium().child("Source")) + .child( + Menu::new("pr-source") + .open(self.source_open) + .on_change(move |open, _, cx| { + log_dropped(weak_menu.update(cx, |this, cx| { + this.source_open = open; + cx.notify(); + })); + }) + .trigger(move |_, _| { + Button::new("compare-source") + .label(source_label.clone()) + .variant(ButtonVariant::Secondary) + .into_any_element() + }) + .items(move |_, _| { + super::helpers::source_menu_items( + source_view.clone(), + associated.clone(), + active_path.clone(), + candidates.clone(), + user, + active_fork.clone(), + ) + }), + ), ) .when_some(refresh_fork, |this, fork| { this.child( @@ -343,9 +348,7 @@ impl NewPullRequestView { .loading(self.submitting) .disabled(!can_submit) .on_click(move |_, window, cx| { - crate::shared::log_dropped( - weak.update(cx, |this, cx| this.submit(window, cx)), - ); + log_dropped(weak.update(cx, |this, cx| this.submit(window, cx))); }), ) .into_any_element() @@ -366,7 +369,7 @@ impl NewPullRequestView { ] }) .on_change(move |index, _, cx| { - crate::shared::log_dropped(weak.update(cx, |this, cx| { + log_dropped(weak.update(cx, |this, cx| { this.active_tab = index; cx.notify(); })); @@ -376,13 +379,13 @@ impl NewPullRequestView { fn render_content(&self, cx: &mut Context) -> AnyElement { if self.loading { - return crate::shared::widgets::centered_spinner("new-pr-loading"); + return Spinner::centered("new-pr-loading"); } if !self.has_source() { - return empty_state("Choose a local checkout or an announced fork to compare"); + return EmptyState::centered("Choose a local checkout or an announced fork to compare"); } if self.commits.is_none() && self.error.is_some() { - return empty_state("Nothing to compare"); + return EmptyState::centered("Nothing to compare"); } match self.active_tab { 0 => self.pane.clone().into_any_element(), @@ -392,15 +395,15 @@ impl NewPullRequestView { fn render_commits(&self, cx: &mut Context) -> AnyElement { let Some(commits) = self.commits.as_ref() else { - return empty_state("No commits"); + return EmptyState::centered("No commits"); }; if commits.is_empty() { - return empty_state("No commits between the branches"); + return EmptyState::centered("No commits between the branches"); } let commits = Arc::clone(commits); let view = cx.entity().downgrade(); - crate::shared::event_list::commit_list( + commit_list( "new-pr-commits", "new-pr-commits-scroll", commits, @@ -408,13 +411,383 @@ impl NewPullRequestView { |_, _, _| None, move |commit, window, cx| { let id = commit.id.clone(); - crate::shared::log_dropped(view.update(cx, |this, cx| { + log_dropped(view.update(cx, |this, cx| { this.open_commit_diff(&id, window, cx); })); }, - cx, ) } + + pub(super) fn has_source(&self) -> bool { + self.repo_path.is_some() || self.fork.is_some() + } + + pub(super) fn work_path(&self) -> Option { + match &self.fork { + Some(fork) => Some(fork.mirror_path.clone()), + None => self.repo_path.clone(), + } + } + + pub(super) fn base_ref(&self) -> String { + match &self.fork { + Some(_) => ForkCompare::base_ref(&self.base), + None => self.base.to_string(), + } + } + + pub(super) fn compare_ref(&self) -> String { + match &self.fork { + Some(fork) => fork.compare_ref(&self.compare), + None => self.compare.to_string(), + } + } + + pub(crate) fn choose_checkout(&mut self, window: &mut Window, cx: &mut Context) { + let prompt = cx.prompt_for_paths(PathPromptOptions { + files: false, + directories: true, + multiple: false, + prompt: Some("Choose local checkout".into()), + }); + let task: gpui::Task> = + cx.spawn_in(window, async move |this, cx| { + let picked = match prompt.await { + Ok(Ok(Some(mut paths))) => paths.pop(), + _ => None, + }; + let Some(path) = picked else { + return Ok(()); + }; + this.update_in(cx, |this, window, cx| { + this.apply_folder_path(path, window, cx) + })?; + Ok(()) + }); + self.push_task(task); + } + + pub(crate) fn apply_folder_path( + &mut self, + path: PathBuf, + window: &mut Window, + cx: &mut Context, + ) { + self.fork_generation = self.fork_generation.wrapping_add(1); + let generation = self.fork_generation; + let path_string = path.to_string_lossy().to_string(); + let task: gpui::Task> = + cx.spawn_in(window, async move |this, cx| { + let info = cx + .background_spawn({ + let path = path.clone(); + async move { + let repo = Repo::try_open(&path)?; + match repo.branches() { + Ok(branches) => Some((branches, repo.current_branch())), + Err(error) => { + log::warn!("failed to list branches: {error}"); + None + } + } + } + }) + .await; + this.update_in(cx, |this, window, cx| { + if generation != this.fork_generation { + return; + } + this.apply_checkout(path_string, info, window, cx); + })?; + Ok(()) + }); + self.push_task(task); + } + + fn apply_checkout( + &mut self, + path: String, + info: Option<(Vec, Option)>, + window: &mut Window, + cx: &mut Context, + ) { + self.fork = None; + let Some((branches, current)) = info else { + self.error = Some("The chosen folder is not a git repository".into()); + self.repo_path = None; + self.branches.clear(); + self.merge_base = None; + self.commits = None; + self.pane.update(cx, |pane, cx| pane.clear(cx)); + cx.notify(); + return; + }; + if branches.is_empty() { + self.error = Some("The repository has no branches yet".into()); + self.repo_path = None; + self.branches.clear(); + self.merge_base = None; + self.commits = None; + self.pane.update(cx, |pane, cx| pane.clear(cx)); + cx.notify(); + return; + } + + let announced = self.store.read(cx).head.clone(); + let base = preferred_branch(&branches, announced); + let compare = current + .filter(|branch| branches.contains(branch)) + .unwrap_or_else(|| base.clone()); + + self.repo_path = Some(PathBuf::from(&path)); + self.error = None; + self.branches = branches.into_iter().map(SharedString::from).collect(); + + if let Some(addr) = self.store.read(cx).addr().cloned() { + CheckoutsStore::global(cx).update(cx, |store, cx| { + store.record(PathBuf::from(&path), addr, cx); + }); + } + + self.base = SharedString::from(base); + self.compare = SharedString::from(compare); + self.sync_selectors(window, cx); + self.reload_compare(cx); + } + + fn sync_selectors(&mut self, window: &mut Window, cx: &mut Context) { + let options: Vec<(SharedString, SharedString)> = self + .branches + .iter() + .map(|branch| (branch.clone(), branch.clone())) + .collect(); + let base = self.base.clone(); + let compare = self.compare.clone(); + + self.base_select.update(cx, |state, cx| { + state.set_options(options.clone(), cx); + state.set_selected(Some(base), window, cx); + }); + self.compare_select.update(cx, |state, cx| { + state.set_options(options, cx); + state.set_selected(Some(compare), window, cx); + }); + } + + pub(super) fn fork_candidates(&self, cx: &App) -> Vec { + let Some(addr) = self.store.read(cx).addr().cloned() else { + return Vec::new(); + }; + let euc = self + .store + .read(cx) + .announcement + .as_ref() + .and_then(|a| a.euc.clone()); + let user = Backend::global(cx).read(cx).current_user(); + let announcements = RepoListStore::global(cx).read(cx).announcements.clone(); + Announcement::forks_in(&announcements, &addr, euc.as_deref(), user) + .into_iter() + .cloned() + .collect() + } + + pub(crate) fn choose_fork( + &mut self, + announcement: Announcement, + window: &mut Window, + cx: &mut Context, + ) { + let Some(base) = self.store.read(cx).addr().cloned() else { + return; + }; + let mirror_path = Mirrors::path(&base); + let namespace = GitCache::fork_namespace(&announcement); + let clone_urls: Vec = announcement.clone.clone(); + let base_clone_urls: Vec = self + .store + .read(cx) + .announcement + .as_ref() + .map(|a| a.clone.clone()) + .unwrap_or_default(); + self.fork_generation = self.fork_generation.wrapping_add(1); + let generation = self.fork_generation; + let handle = window.window_handle(); + + self.loading = true; + self.error = None; + cx.notify(); + + let task: gpui::Task> = cx.spawn(async move |this, cx| { + let result = cx + .background_spawn({ + let namespace = namespace.clone(); + let mirror_path = mirror_path.clone(); + async move { + Mirrors::ensure(&base, &base_clone_urls)?; + let repo = Repo::open(&mirror_path)?; + repo.delete_refs_with_prefix("refs/fork")?; + repo.fetch_refs( + &clone_urls, + &format!("+refs/heads/*:refs/fork/{namespace}/*"), + )?; + let strip = |refs: Vec, prefix: &str| { + let mut names: Vec = refs + .into_iter() + .filter_map(|name| { + name.strip_prefix(prefix) + .map(|rest| rest.trim_start_matches('/').to_owned()) + }) + .filter(|name| !name.is_empty()) + .collect(); + names.sort(); + names + }; + let base_branches = strip( + repo.refs_with_prefix("refs/remotes/origin")?, + "refs/remotes/origin", + ); + let compare_branches = strip( + repo.refs_with_prefix(&format!("refs/fork/{namespace}"))?, + &format!("refs/fork/{namespace}"), + ); + Ok::<_, anyhow::Error>((base_branches, compare_branches)) + } + }) + .await; + + if let Err(error) = cx.update_window(handle, |_, window, cx| { + this.update(cx, |this, cx| { + if generation != this.fork_generation { + return; + } + this.apply_fork(announcement, mirror_path, namespace, result, window, cx); + }) + }) { + log::warn!("failed to apply fork: {error}"); + } + Ok(()) + }); + self.push_task(task); + } + + fn apply_fork( + &mut self, + announcement: Announcement, + mirror_path: PathBuf, + namespace: String, + result: Result<(Vec, Vec), anyhow::Error>, + window: &mut Window, + cx: &mut Context, + ) { + self.loading = false; + let (base_branches, compare_branches) = match result { + Ok(branches) => branches, + Err(error) => { + self.error = Some(format!("Could not compare against the fork: {error}").into()); + cx.notify(); + return; + } + }; + if compare_branches.is_empty() { + self.error = Some("The fork has no branches to compare".into()); + cx.notify(); + return; + } + if base_branches.is_empty() { + self.error = Some("Could not list the target repository's branches.".into()); + cx.notify(); + return; + } + + let announced = self.store.read(cx).head.clone(); + let base = preferred_branch(&base_branches, announced); + let compare = compare_branches + .iter() + .find(|branch| branch.as_str() == "main") + .map(|branch| SharedString::from(branch.clone())) + .unwrap_or_else(|| SharedString::from(compare_branches[0].clone())); + + self.fork = Some(ForkCompare { + announcement, + namespace, + mirror_path, + }); + self.error = None; + self.base = SharedString::from(base); + self.compare = compare; + self.branches = base_branches.into_iter().map(SharedString::from).collect(); + self.sync_selectors(window, cx); + self.reload_compare(cx); + } + + pub(super) fn reload_compare(&mut self, cx: &mut Context) { + let Some(repo_path) = self.work_path() else { + return; + }; + let base = self.base_ref(); + let compare = self.compare_ref(); + let base_name = self.base.to_string(); + let compare_name = self.compare.to_string(); + + self.loading = true; + self.error = None; + self.compare_generation += 1; + let generation = self.compare_generation; + cx.notify(); + + if base == compare { + self.loading = false; + self.merge_base = None; + self.commits = None; + self.pane.update(cx, |pane, cx| pane.clear(cx)); + self.error = Some("Choose different base and compare branches".into()); + cx.notify(); + return; + } + + let task: gpui::Task> = cx.spawn(async move |this, cx| { + let result = cx + .background_spawn({ + async move { + let repo = Repo::open(Path::new(&repo_path))?; + let merge_base = repo.merge_base(&base, &compare)?.ok_or_else(|| { + anyhow::anyhow!( + "{base_name} and {compare_name} share no common ancestor" + ) + })?; + let commits = repo.commit_range(&merge_base, &compare)?; + let diff = repo.range_diff(&merge_base, &compare)?; + Ok::<_, anyhow::Error>((merge_base, commits, diff)) + } + }) + .await; + + this.update(cx, |this, cx| { + if generation != this.compare_generation { + return; + } + this.loading = false; + match result { + Ok((merge_base, commits, diff)) => { + this.merge_base = Some(merge_base); + this.commits = Some(Arc::new(commits)); + this.pane.update(cx, |pane, cx| pane.set_diff(diff, cx)); + } + Err(error) => { + this.merge_base = None; + this.commits = None; + this.pane.update(cx, |pane, cx| pane.clear(cx)); + this.error = Some(error.to_string().into()); + } + } + cx.notify(); + })?; + Ok(()) + }); + self.push_task(task); + } } impl Panel for NewPullRequestView { @@ -462,6 +835,15 @@ impl Render for NewPullRequestView { } } -fn label(text: &'static str) -> AnyElement { - div().text_xs().font_medium().child(text).into_any_element() +/// The announced head when listed, else `main`, else the first branch. +fn preferred_branch(branches: &[String], announced: Option) -> String { + announced + .filter(|branch| branches.contains(branch)) + .or_else(|| { + branches + .iter() + .find(|branch| branch.as_str() == "main") + .cloned() + }) + .unwrap_or_else(|| branches[0].clone()) } diff --git a/crates/signed_app/src/pull_requests/new/source.rs b/crates/signed_app/src/pull_requests/new/source.rs deleted file mode 100644 index 49f3298..0000000 --- a/crates/signed_app/src/pull_requests/new/source.rs +++ /dev/null @@ -1,397 +0,0 @@ -use std::path::{Path, PathBuf}; -use std::sync::Arc; - -use gpui::{App, AppContext as _, Context, PathPromptOptions, SharedString, Window}; -use nostr::prelude::Url; -use signed_core::Announcement; -use signed_git::{GitCache, Repo}; -use signed_state::{Backend, CheckoutsStore, Mirrors, RepoListStore}; - -use super::NewPullRequestView; -use crate::pull_requests::helpers::ForkCompare; - -/// The announced head when listed, else `main`, else the first branch. -fn preferred_branch(branches: &[String], announced: Option) -> String { - announced - .filter(|branch| branches.contains(branch)) - .or_else(|| { - branches - .iter() - .find(|branch| branch.as_str() == "main") - .cloned() - }) - .unwrap_or_else(|| branches[0].clone()) -} - -impl NewPullRequestView { - pub(super) fn has_source(&self) -> bool { - self.repo_path.is_some() || self.fork.is_some() - } - - pub(super) fn work_path(&self) -> Option { - match &self.fork { - Some(fork) => Some(fork.mirror_path.clone()), - None => self.repo_path.clone(), - } - } - - pub(super) fn base_ref(&self) -> String { - match &self.fork { - Some(_) => ForkCompare::base_ref(&self.base), - None => self.base.to_string(), - } - } - - pub(super) fn compare_ref(&self) -> String { - match &self.fork { - Some(fork) => fork.compare_ref(&self.compare), - None => self.compare.to_string(), - } - } - - pub(crate) fn choose_checkout(&mut self, window: &mut Window, cx: &mut Context) { - let prompt = cx.prompt_for_paths(PathPromptOptions { - files: false, - directories: true, - multiple: false, - prompt: Some("Choose local checkout".into()), - }); - let task: gpui::Task> = - cx.spawn_in(window, async move |this, cx| { - let picked = match prompt.await { - Ok(Ok(Some(mut paths))) => paths.pop(), - _ => None, - }; - let Some(path) = picked else { - return Ok(()); - }; - this.update_in(cx, |this, window, cx| { - this.apply_folder_path(path, window, cx) - })?; - Ok(()) - }); - self.push_task(task); - } - - pub(crate) fn apply_folder_path( - &mut self, - path: PathBuf, - window: &mut Window, - cx: &mut Context, - ) { - self.fork_generation = self.fork_generation.wrapping_add(1); - let generation = self.fork_generation; - let path_string = path.to_string_lossy().to_string(); - let task: gpui::Task> = - cx.spawn_in(window, async move |this, cx| { - let info = cx - .background_spawn({ - let path = path.clone(); - async move { - let repo = Repo::try_open(&path)?; - match repo.branches() { - Ok(branches) => Some((branches, repo.current_branch())), - Err(error) => { - log::warn!("failed to list branches: {error}"); - None - } - } - } - }) - .await; - this.update_in(cx, |this, window, cx| { - if generation != this.fork_generation { - return; - } - this.apply_checkout(path_string, info, window, cx); - })?; - Ok(()) - }); - self.push_task(task); - } - - fn apply_checkout( - &mut self, - path: String, - info: Option<(Vec, Option)>, - window: &mut Window, - cx: &mut Context, - ) { - self.fork = None; - let Some((branches, current)) = info else { - self.error = Some("The chosen folder is not a git repository".into()); - self.repo_path = None; - self.branches.clear(); - self.merge_base = None; - self.commits = None; - self.pane.update(cx, |pane, cx| pane.clear(cx)); - cx.notify(); - return; - }; - if branches.is_empty() { - self.error = Some("The repository has no branches yet".into()); - self.repo_path = None; - self.branches.clear(); - self.merge_base = None; - self.commits = None; - self.pane.update(cx, |pane, cx| pane.clear(cx)); - cx.notify(); - return; - } - - let announced = self.store.read(cx).head.clone(); - let base = preferred_branch(&branches, announced); - let compare = current - .filter(|branch| branches.contains(branch)) - .unwrap_or_else(|| base.clone()); - - self.repo_path = Some(PathBuf::from(&path)); - self.error = None; - self.branches = branches.into_iter().map(SharedString::from).collect(); - - if let Some(addr) = self.store.read(cx).addr().cloned() { - CheckoutsStore::global(cx).update(cx, |store, cx| { - store.record(PathBuf::from(&path), addr, cx); - }); - } - - self.base = SharedString::from(base); - self.compare = SharedString::from(compare); - self.sync_selectors(window, cx); - self.reload_compare(cx); - } - - fn sync_selectors(&mut self, window: &mut Window, cx: &mut Context) { - let options: Vec<(SharedString, SharedString)> = self - .branches - .iter() - .map(|branch| (branch.clone(), branch.clone())) - .collect(); - let base = self.base.clone(); - let compare = self.compare.clone(); - - self.base_select.update(cx, |state, cx| { - state.set_options(options.clone(), cx); - state.set_selected(Some(base), window, cx); - }); - self.compare_select.update(cx, |state, cx| { - state.set_options(options, cx); - state.set_selected(Some(compare), window, cx); - }); - } - - pub(super) fn fork_candidates(&self, cx: &App) -> Vec { - let Some(addr) = self.store.read(cx).addr().cloned() else { - return Vec::new(); - }; - let euc = self - .store - .read(cx) - .announcement - .as_ref() - .and_then(|a| a.euc.clone()); - let user = Backend::global(cx).read(cx).current_user(); - let announcements = RepoListStore::global(cx).read(cx).announcements.clone(); - Announcement::forks_in(&announcements, &addr, euc.as_deref(), user) - .into_iter() - .cloned() - .collect() - } - - pub(crate) fn choose_fork( - &mut self, - announcement: Announcement, - window: &mut Window, - cx: &mut Context, - ) { - let Some(base) = self.store.read(cx).addr().cloned() else { - return; - }; - let mirror_path = Mirrors::path(&base); - let namespace = GitCache::fork_namespace(&announcement); - let clone_urls: Vec = announcement.clone.clone(); - let base_clone_urls: Vec = self - .store - .read(cx) - .announcement - .as_ref() - .map(|a| a.clone.clone()) - .unwrap_or_default(); - self.fork_generation = self.fork_generation.wrapping_add(1); - let generation = self.fork_generation; - let handle = window.window_handle(); - - self.loading = true; - self.error = None; - cx.notify(); - - let task: gpui::Task> = cx.spawn(async move |this, cx| { - let result = cx - .background_spawn({ - let namespace = namespace.clone(); - let mirror_path = mirror_path.clone(); - async move { - Mirrors::ensure(&base, &base_clone_urls)?; - let repo = Repo::open(&mirror_path)?; - repo.delete_refs_with_prefix("refs/fork")?; - repo.fetch_refs( - &clone_urls, - &format!("+refs/heads/*:refs/fork/{namespace}/*"), - )?; - let strip = |refs: Vec, prefix: &str| { - let mut names: Vec = refs - .into_iter() - .filter_map(|name| { - name.strip_prefix(prefix) - .map(|rest| rest.trim_start_matches('/').to_owned()) - }) - .filter(|name| !name.is_empty()) - .collect(); - names.sort(); - names - }; - let base_branches = strip( - repo.refs_with_prefix("refs/remotes/origin")?, - "refs/remotes/origin", - ); - let compare_branches = strip( - repo.refs_with_prefix(&format!("refs/fork/{namespace}"))?, - &format!("refs/fork/{namespace}"), - ); - Ok::<_, anyhow::Error>((base_branches, compare_branches)) - } - }) - .await; - - if let Err(error) = cx.update_window(handle, |_, window, cx| { - this.update(cx, |this, cx| { - if generation != this.fork_generation { - return; - } - this.apply_fork(announcement, mirror_path, namespace, result, window, cx); - }) - }) { - log::warn!("failed to apply fork: {error}"); - } - Ok(()) - }); - self.push_task(task); - } - - fn apply_fork( - &mut self, - announcement: Announcement, - mirror_path: PathBuf, - namespace: String, - result: Result<(Vec, Vec), anyhow::Error>, - window: &mut Window, - cx: &mut Context, - ) { - self.loading = false; - let (base_branches, compare_branches) = match result { - Ok(branches) => branches, - Err(error) => { - self.error = Some(format!("Could not compare against the fork: {error}").into()); - cx.notify(); - return; - } - }; - if compare_branches.is_empty() { - self.error = Some("The fork has no branches to compare".into()); - cx.notify(); - return; - } - if base_branches.is_empty() { - self.error = Some("Could not list the target repository's branches.".into()); - cx.notify(); - return; - } - - let announced = self.store.read(cx).head.clone(); - let base = preferred_branch(&base_branches, announced); - let compare = compare_branches - .iter() - .find(|branch| branch.as_str() == "main") - .map(|branch| SharedString::from(branch.clone())) - .unwrap_or_else(|| SharedString::from(compare_branches[0].clone())); - - self.fork = Some(ForkCompare { - announcement, - namespace, - mirror_path, - }); - self.error = None; - self.base = SharedString::from(base); - self.compare = compare; - self.branches = base_branches.into_iter().map(SharedString::from).collect(); - self.sync_selectors(window, cx); - self.reload_compare(cx); - } - - pub(super) fn reload_compare(&mut self, cx: &mut Context) { - let Some(repo_path) = self.work_path() else { - return; - }; - let base = self.base_ref(); - let compare = self.compare_ref(); - let base_name = self.base.to_string(); - let compare_name = self.compare.to_string(); - - self.loading = true; - self.error = None; - self.compare_generation += 1; - let generation = self.compare_generation; - cx.notify(); - - if base == compare { - self.loading = false; - self.merge_base = None; - self.commits = None; - self.pane.update(cx, |pane, cx| pane.clear(cx)); - self.error = Some("Choose different base and compare branches".into()); - cx.notify(); - return; - } - - let task: gpui::Task> = cx.spawn(async move |this, cx| { - let result = cx - .background_spawn({ - async move { - let repo = Repo::open(Path::new(&repo_path))?; - let merge_base = repo.merge_base(&base, &compare)?.ok_or_else(|| { - anyhow::anyhow!( - "{base_name} and {compare_name} share no common ancestor" - ) - })?; - let commits = repo.commit_range(&merge_base, &compare)?; - let diff = repo.range_diff(&merge_base, &compare)?; - Ok::<_, anyhow::Error>((merge_base, commits, diff)) - } - }) - .await; - - this.update(cx, |this, cx| { - if generation != this.compare_generation { - return; - } - this.loading = false; - match result { - Ok((merge_base, commits, diff)) => { - this.merge_base = Some(merge_base); - this.commits = Some(Arc::new(commits)); - this.pane.update(cx, |pane, cx| pane.set_diff(diff, cx)); - } - Err(error) => { - this.merge_base = None; - this.commits = None; - this.pane.update(cx, |pane, cx| pane.clear(cx)); - this.error = Some(error.to_string().into()); - } - } - cx.notify(); - })?; - Ok(()) - }); - self.push_task(task); - } -} diff --git a/crates/signed_app/src/pull_requests/send_patch.rs b/crates/signed_app/src/pull_requests/send_patch.rs index 595bb0e..30e99e2 100644 --- a/crates/signed_app/src/pull_requests/send_patch.rs +++ b/crates/signed_app/src/pull_requests/send_patch.rs @@ -11,11 +11,13 @@ use ui::input::{Input, InputState}; use ui::layout::panel::Panel; use ui::theme::ActiveTheme as _; +use crate::app::AppRoot; +use crate::shared::log_dropped; +use crate::shared::panels::close_detail; use crate::shared::progress::error_row; -use crate::workspace::Workspace; pub struct SendPatchView { - workspace: WeakEntity, + workspace: WeakEntity, panel_id: SharedString, store: Entity, subject: Entity, @@ -27,7 +29,7 @@ pub struct SendPatchView { impl SendPatchView { pub fn new( - workspace: WeakEntity, + workspace: WeakEntity, panel_id: SharedString, store: Entity, _window: &mut Window, @@ -82,11 +84,7 @@ impl SendPatchView { cx.spawn(async move |this, cx| match task.await { Ok(()) => { this.update(cx, |this, cx| { - let panel_id = this.panel_id.clone(); - crate::shared::log_dropped( - this.workspace - .update(cx, |workspace, cx| workspace.close_detail(&panel_id, cx)), - ); + close_detail(&this.workspace, &this.panel_id, cx) }) .log_err(); } @@ -122,7 +120,7 @@ impl SendPatchView { .loading(self.submitting) .disabled(!can_submit) .on_click(move |_, _, cx| { - crate::shared::log_dropped(weak.update(cx, |this, cx| this.submit(cx))); + log_dropped(weak.update(cx, |this, cx| this.submit(cx))); }), ) .into_any_element() diff --git a/crates/signed_app/src/repo/actions.rs b/crates/signed_app/src/repo/actions.rs index 9794660..66c1922 100644 --- a/crates/signed_app/src/repo/actions.rs +++ b/crates/signed_app/src/repo/actions.rs @@ -3,9 +3,9 @@ use nostr::prelude::EventId; use signed_core::{Announcement, RepoAddr}; use signed_state::RepoStore; +use crate::app::AppRoot; use crate::repo::RepoDetailView; use crate::shared::panels; -use crate::workspace::Workspace; /// An item of a repository to open from outside its detail panel. pub enum RepoItem { @@ -16,7 +16,7 @@ pub enum RepoItem { /// Opens a repository as the main panel, keyed by its address. pub fn open_repo_panel( - workspace: &WeakEntity, + workspace: &WeakEntity, addr: &RepoAddr, hint: Option<&Announcement>, window: &mut Window, @@ -42,7 +42,7 @@ pub fn open_repo_panel( /// Opens an issue or pull request using a store built here. pub fn open_repo_item( - workspace: &WeakEntity, + workspace: &WeakEntity, addr: &RepoAddr, hint: Option<&Announcement>, item: RepoItem, diff --git a/crates/signed_app/src/repo/commit_diff.rs b/crates/signed_app/src/repo/commit_diff.rs index dc23e02..02e1bcf 100644 --- a/crates/signed_app/src/repo/commit_diff.rs +++ b/crates/signed_app/src/repo/commit_diff.rs @@ -14,20 +14,21 @@ use ui::badge::GroupedBadge; use ui::button::{Button, ButtonVariant}; use ui::clipboard::ClipboardButton; use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex}; +use ui::empty_state::EmptyState; use ui::icons::{Icon, IconRole}; use ui::layout::panel::Panel; use ui::layout::resizable::{Resizable, ResizableState}; +use ui::scrollbar::Scrollbar; use ui::separator::Separator; +use ui::spinner::Spinner; use ui::switch::Switch; use ui::theme::ActiveTheme as _; use ui::toggle::Toggle; use ui::tooltip::Tooltip; -use ui::tree::{Tree, TreeItem}; +use ui::tree::{Tree, TreeItem, TreeItemSeed}; use utils::relative_time_secs; -use super::helpers::{DiffRow, co_authors, diff_rows, render_diff_row, short_id}; -use crate::shared::tree::{TreeItemSeed, TreeRow, build_tree_items, collect_expanded, flatten}; -use crate::shared::widgets::{centered_spinner, empty_state, scroll_overlay}; +use super::helpers::{DiffRow, co_authors, diff_rows, short_id}; /// Emitted when the user activates the Download commit button. pub enum DiffPaneEvent { @@ -59,7 +60,7 @@ pub struct DiffPane { diff: Option, seeds: Vec, expanded: HashSet, - rows: Vec, + rows: Vec, selected_index: Option, tree_visible: bool, split: Entity, @@ -103,9 +104,9 @@ impl DiffPane { .collect(); paths.sort(); - self.seeds = build_tree_items(&paths); - self.expanded = collect_expanded(&self.seeds); - self.rows = flatten(&self.seeds, &self.expanded); + self.seeds = TreeItemSeed::from_paths(&paths); + self.expanded = TreeItemSeed::collect_expanded(&self.seeds); + self.rows = TreeItemSeed::flatten_all(&self.seeds, &self.expanded); self.selected_index = None; self.diff = Some(diff); @@ -172,7 +173,10 @@ impl DiffPane { } fn select_tree_file(&mut self, path: &str, cx: &mut Context) { - self.selected_index = self.rows.iter().position(|row| row.id == path); + self.selected_index = self + .rows + .iter() + .position(|row| row.key().to_string() == path); if self.expanded_files.insert(path.to_owned()) { self.rebuild_rows(); } @@ -249,7 +253,7 @@ impl DiffPane { if !self.expanded.remove(id) { self.expanded.insert(id.to_owned()); } - self.rows = flatten(&self.seeds, &self.expanded); + self.rows = TreeItemSeed::flatten_all(&self.seeds, &self.expanded); self.selected_index = self .selected_index .and_then(|index| self.rows.get(index).map(|_| index)); @@ -269,22 +273,7 @@ impl DiffPane { .child( Tree::new("commit-diff-tree") .selected(selected) - .items(move |_, _| { - rows.iter() - .map(|row| { - let item = TreeItem::new(row.id.clone(), row.label.clone()) - .depth(row.depth) - .expandable(row.expandable) - .expanded(row.expanded); - - if row.expandable { - item.icon(Icon::named(IconRole::Folder)) - } else { - item.icon(Icon::named(IconRole::File)) - } - }) - .collect() - }) + .items(move |_, _| rows.clone()) .on_change(move |index, window, cx| { if let Some(index) = index && let Err(error) = change_view.update(cx, |this, cx| { @@ -298,7 +287,7 @@ impl DiffPane { let view = view; move |index, _, cx| { if let Err(error) = view.update(cx, |this, cx| { - let id = this.rows.get(index).map(|row| row.id.clone()); + let id = this.rows.get(index).map(|row| row.key().to_string()); if let Some(id) = id { this.toggle_folder(&id, cx); } @@ -315,8 +304,8 @@ impl DiffPane { let Some(row) = self.rows.get(index) else { return; }; - let id = row.id.clone(); - let expandable = row.expandable; + let id = row.key().to_string(); + let expandable = row.is_expandable(); self.selected_index = Some(index); if expandable { @@ -427,7 +416,7 @@ impl DiffPane { fn render_file_list(&self, cx: &mut Context) -> AnyElement { let Some(diff) = self.diff.as_ref() else { - return empty_state("No changes"); + return EmptyState::centered("No changes"); }; let files = diff.files.clone(); @@ -451,7 +440,7 @@ impl DiffPane { .size_full() .p_2(), ) - .child(scroll_overlay("commit-diff-files", self.list.clone())) + .child(Scrollbar::vertical("commit-diff-files", self.list.clone())) .into_any_element() } } @@ -562,7 +551,7 @@ fn render_pane_row( .border_color(border) .bg(surface) .when(*last, |this| this.border_b_1().rounded_b_lg()) - .child(render_diff_row(&file.hunks, *row, wrap, cx)) + .child(row.render(&file.hunks, wrap, cx)) .into_any_element() } } @@ -571,13 +560,13 @@ fn render_pane_row( impl Render for DiffPane { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { if self.diff.is_none() { - return empty_state("No changes"); + return EmptyState::centered("No changes"); } let diff = self.diff.as_ref().expect("diff checked above"); if diff.files.is_empty() { - return empty_state("No files changed"); + return EmptyState::centered("No files changed"); } let toolbar = self.render_toolbar(cx); @@ -785,9 +774,11 @@ impl CommitDiffView { .gap_2() .border_b_1() .border_color(cx.theme().colors.border) + // The top right corner is the panel toolbar's. .child( div() .min_w_0() + .pr_16() .font_semibold() .truncate() .text_ellipsis() @@ -893,14 +884,18 @@ impl Panel for CommitDiffView { fn loading(&self, _cx: &App) -> bool { self.loading } + + fn toolbar(&self, _cx: &App) -> bool { + true + } } impl Render for CommitDiffView { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let body = if self.loading { - centered_spinner("commit-diff-loading") + Spinner::centered("commit-diff-loading") } else if let Some(error) = self.error.clone() { - empty_state(error) + EmptyState::centered(error) } else { self.pane.clone().into_any_element() }; diff --git a/crates/signed_app/src/repo/dialogs/create.rs b/crates/signed_app/src/repo/dialogs/create.rs index 9598d83..611c2d3 100644 --- a/crates/signed_app/src/repo/dialogs/create.rs +++ b/crates/signed_app/src/repo/dialogs/create.rs @@ -16,13 +16,15 @@ use ui::input::{Input, InputState}; use ui::tooltip::Tooltip; use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers}; +use crate::app::AppRoot; use crate::repo::actions::open_repo_panel; -use crate::shared::progress::{DialogProgress, error_row, push_steps_row, run_dialog_task_with}; -use crate::workspace::Workspace; +use crate::shared::progress::{ + DialogProgress, dialog_submit_button, error_row, push_steps_row, run_dialog_task_with, +}; /// Progress of the create-repository flow, so async results can be rendered. pub struct CreateRepoDialog { - workspace: WeakEntity, + workspace: WeakEntity, handle: DialogHandle, name_input: Entity, desc_input: Entity, @@ -35,11 +37,7 @@ pub struct CreateRepoDialog { } impl CreateRepoDialog { - pub fn new( - workspace: WeakEntity, - window: &mut Window, - cx: &mut App, - ) -> Entity { + pub fn new(workspace: WeakEntity, window: &mut Window, cx: &mut App) -> Entity { let settings = SettingsStore::global(cx); let grasp_settings = settings.read(cx).settings().grasp_servers.clone(); @@ -229,17 +227,18 @@ impl Render for CreateRepoDialog { let busy = action_state.read(cx).busy; let this = this.clone(); - let create: AnyElement = Button::new("create-repository") - .label("Create repository") - .icon(Icon::named(IconRole::Plus)) - .loading(busy) - .disabled(busy) - .on_click(move |_, window, cx| { - crate::shared::log_dropped( - this.update(cx, |this, cx| this.create(window, cx)), - ); - }) - .into_any_element(); + let create: AnyElement = dialog_submit_button( + "create-repository", + "Create repository", + Some(IconRole::Plus), + busy, + &this, + |this, window, cx| { + this.create(window, cx); + Ok(()) + }, + ) + .into_any_element(); vec![create] }) diff --git a/crates/signed_app/src/repo/dialogs/init.rs b/crates/signed_app/src/repo/dialogs/init.rs index ede1124..5aa19c3 100644 --- a/crates/signed_app/src/repo/dialogs/init.rs +++ b/crates/signed_app/src/repo/dialogs/init.rs @@ -9,11 +9,10 @@ use settings::SettingsStore; use signed_core::RepoAddr; use signed_git::Repo; use signed_state::Backend; -use ui::button::Button; use ui::common::{ResultLogErr as _, v_flex}; use ui::dialog::{Dialog, DialogHandle}; use ui::field::Field; -use ui::icons::{Icon, IconRole}; +use ui::icons::IconRole; use ui::input::{Input, InputState}; use ui::layout::h_flex; use ui::select::{Select, SelectOption}; @@ -21,7 +20,9 @@ use ui::theme::ActiveTheme as _; use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers}; use crate::repo::RepoDetailView; -use crate::shared::progress::{DialogProgress, error_row, push_steps_row, run_dialog_task_with}; +use crate::shared::progress::{ + DialogProgress, dialog_submit_button, error_row, push_steps_row, run_dialog_task_with, +}; pub struct InitRepoDialog { handle: DialogHandle, @@ -246,17 +247,18 @@ impl Render for InitRepoDialog { let busy = action_state.read(cx).busy; let this = this.clone(); - let init: AnyElement = Button::new("initialize-repository") - .label("Initialize") - .icon(Icon::named(IconRole::Plus)) - .loading(busy) - .disabled(busy) - .on_click(move |_, window, cx| { - crate::shared::log_dropped( - this.update(cx, |this, cx| this.init_repository(window, cx)), - ); - }) - .into_any_element(); + let init: AnyElement = dialog_submit_button( + "initialize-repository", + "Initialize", + Some(IconRole::Plus), + busy, + &this, + |this, window, cx| { + this.init_repository(window, cx); + Ok(()) + }, + ) + .into_any_element(); vec![init] }) diff --git a/crates/signed_app/src/repo/files.rs b/crates/signed_app/src/repo/files.rs index a916727..d26ab5a 100644 --- a/crates/signed_app/src/repo/files.rs +++ b/crates/signed_app/src/repo/files.rs @@ -10,15 +10,14 @@ use gpui::{ use signed_git::{FileCommit, Repo, WorktreeSnapshot}; use ui::code::CodeViewState; use ui::common::{StyledExt as _, h_flex, v_flex}; -use ui::icons::{Icon, IconRole}; +use ui::empty_state::EmptyState; use ui::markdown::MarkdownViewState; +use ui::spinner::Spinner; use ui::theme::ActiveTheme as _; -use ui::tree::{Tree, TreeItem}; +use ui::tree::{Tree, TreeItem, TreeItemSeed}; -use super::helpers::{code_language, is_markdown_path, preview_spinner, source_hash}; +use super::helpers::{code_language, is_markdown_path, source_hash}; use crate::repo::helpers::short_id; -use crate::shared::tree::{TreeItemSeed, TreeRow, collect_expanded, flatten}; -use crate::shared::widgets::empty_state; const MAX_PREVIEW_BYTES: usize = 1024 * 1024; const MAX_PREVIEWED_FILES: usize = 32; @@ -56,7 +55,7 @@ struct CodeView { pub struct RepoFilesView { seeds: Vec, expanded: HashSet, - rows: Vec, + rows: Vec, selected_index: Option, worktree: Option, worktree_paths: Vec, @@ -112,18 +111,19 @@ impl RepoFilesView { ) { self.worktree_paths = paths; self.seeds = tree; - let folder_ids = collect_expanded(&self.seeds); + let folder_ids = TreeItemSeed::collect_expanded(&self.seeds); self.expanded.retain(|id| folder_ids.contains(id)); self.rebuild_rows(); cx.notify(); } fn rebuild_rows(&mut self) { - self.rows = flatten(&self.seeds, &self.expanded); - self.selected_index = self - .selected_file - .as_ref() - .and_then(|path| self.rows.iter().position(|row| row.id == path.as_ref())); + self.rows = TreeItemSeed::flatten_all(&self.seeds, &self.expanded); + self.selected_index = self.selected_file.as_ref().and_then(|path| { + self.rows + .iter() + .position(|row| row.key().to_string() == path.as_ref()) + }); } fn toggle_folder(&mut self, id: &str) { @@ -235,8 +235,8 @@ impl RepoFilesView { let Some(row) = self.rows.get(index) else { return; }; - let id = row.id.clone(); - let expandable = row.expandable; + let id = row.key().to_string(); + let expandable = row.is_expandable(); self.selected_index = Some(index); @@ -261,22 +261,7 @@ impl RepoFilesView { .child( Tree::new("repo-tree") .selected(selected) - .items(move |_, _| { - rows.iter() - .map(|row| { - let item = TreeItem::new(row.id.clone(), row.label.clone()) - .depth(row.depth) - .expandable(row.expandable) - .expanded(row.expanded); - - if row.expandable { - item.icon(Icon::named(IconRole::Folder)) - } else { - item.icon(Icon::named(IconRole::File)) - } - }) - .collect() - }) + .items(move |_, _| rows.clone()) .on_change({ let view = change_view; move |index, window, cx| { @@ -293,7 +278,7 @@ impl RepoFilesView { let view = disclosure_view; move |index, _, cx| { if let Err(error) = view.update(cx, |this, cx| { - let id = this.rows.get(index).map(|row| row.id.clone()); + let id = this.rows.get(index).map(|row| row.key().to_string()); if let Some(id) = id { this.toggle_folder(&id); cx.emit(RepoFilesEvent::Activated); @@ -319,15 +304,17 @@ impl RepoFilesView { self.code_element(path.as_ref()) } } - Some(FileContent::Binary) => empty_state("Binary file - preview not supported"), - Some(FileContent::TooLarge) => empty_state("File is too large to preview"), - Some(FileContent::Failed(message)) => empty_state(message), - None => preview_spinner(), + Some(FileContent::Binary) => { + EmptyState::centered("Binary file - preview not supported") + } + Some(FileContent::TooLarge) => EmptyState::centered("File is too large to preview"), + Some(FileContent::Failed(message)) => EmptyState::centered(message), + None => Spinner::centered("repo-preview-spinner"), } } else if self.readme_name.is_some() { self.markdown_element(None) } else { - empty_state("No README found") + EmptyState::centered("No README found") }; let commit = match &self.selected_file { @@ -426,7 +413,7 @@ impl RepoFilesView { fn markdown_element(&self, path: Option<&str>) -> AnyElement { let Some(md) = &self.md else { - return preview_spinner(); + return Spinner::centered("repo-preview-spinner"); }; let ready = match path { @@ -435,7 +422,7 @@ impl RepoFilesView { }; if !ready { - return preview_spinner(); + return Spinner::centered("repo-preview-spinner"); } div() @@ -481,10 +468,10 @@ impl RepoFilesView { fn code_element(&self, path: &str) -> AnyElement { let Some(code) = &self.code else { - return preview_spinner(); + return Spinner::centered("repo-preview-spinner"); }; if code.path.as_ref() != path { - return preview_spinner(); + return Spinner::centered("repo-preview-spinner"); } div() diff --git a/crates/signed_app/src/repo/header.rs b/crates/signed_app/src/repo/header.rs deleted file mode 100644 index 68064eb..0000000 --- a/crates/signed_app/src/repo/header.rs +++ /dev/null @@ -1,455 +0,0 @@ -use std::collections::HashSet; - -use gpui::prelude::FluentBuilder as _; -use gpui::{ - AnyElement, Context, InteractiveElement as _, IntoElement, ParentElement as _, SharedString, - StatefulInteractiveElement as _, Styled as _, Window, div, px, -}; -use signed_state::{Backend, Nip34Kind}; -use ui::avatar::Avatar; -use ui::button::{Button, ButtonVariant}; -use ui::common::{Sizable, StyledExt as _, h_flex, v_flex}; -use ui::dropdown_menu::DropdownMenu; -use ui::icons::{Icon, IconRole}; -use ui::menu::MenuItem; -use ui::popover::Popover; -use ui::theme::ActiveTheme as _; -use ui::tooltip::Tooltip; -use utils::relative_time_secs; - -use super::helpers::{bound_repo_label, clone_group, fork_row, nostr_clone_url, repo_display_name}; -use super::{RepoDetailView, actions, dialogs}; -use crate::shared::widgets::clone_row; - -impl RepoDetailView { - pub(super) fn open_upstream(&mut self, window: &mut Window, cx: &mut Context) { - let Some(addr) = self - .announcement(cx) - .and_then(|announcement| announcement.upstream.as_ref()) - .and_then(|upstream| upstream.addr.clone()) - else { - return; - }; - - actions::open_repo_panel(&self.workspace, &addr, None, window, cx); - } - - /// Open the dialog that publishes the local repository to NIP-34. - fn open_init_dialog(&mut self, window: &mut Window, cx: &mut Context) { - let Some(local_path) = self.store.read(cx).path.clone() else { - return; - }; - self.init = Some(dialogs::init::InitRepoDialog::new( - local_path, - cx.entity().downgrade(), - window, - cx, - )); - cx.notify(); - } - - pub(super) fn render_about(&mut self, cx: &mut Context) -> AnyElement { - if self.store.read(cx).addr().is_none() { - return self.render_init_banner(cx); - } - - let backend = Backend::global(cx); - let store = self.store.read(cx); - let pushing = store.pushing; - let cloning = store.cloning; - - let Some(announcement) = store.announcement.clone() else { - return div().into_any_element(); - }; - - let nip05 = self - .directory - .read(cx) - .profile(&announcement.owner, cx) - .metadata() - .nip05 - .clone() - .filter(|nip05| !nip05.trim().is_empty()); - - let nostr_url = nostr_clone_url(&announcement, nip05.as_deref()); - let ngit_command = SharedString::from(format!("git clone {nostr_url}")); - let nak_command = SharedString::from(format!("nak git clone {nostr_url}")); - let git_commands: Vec = announcement.clone_urls(); - - let name = repo_display_name(self.store.read(cx)); - let description = announcement.description(); - let avatar = Avatar::new(format!("{}:{}", announcement.owner, announcement.id)); - - let announcement_for_menu = announcement.clone(); - let weak_menu_open = cx.entity().downgrade(); - let weak_menu_items = cx.entity().downgrade(); - let weak_clone = cx.entity().downgrade(); - let weak_download = cx.entity().downgrade(); - let ngit_for_popover = ngit_command.clone(); - let nak_for_popover = nak_command.clone(); - let git_for_popover = git_commands.clone(); - - h_flex() - .p_6() - .w_full() - .gap_6() - .items_start() - .justify_between() - .child( - v_flex() - .flex_1() - .min_w_0() - .gap_2() - .child( - h_flex() - .gap_2() - .text_sm() - .font_semibold() - .child(avatar) - .child(name), - ) - .child( - div() - .min_w_0() - .text_sm() - .text_color(cx.theme().colors.muted_foreground) - .line_clamp(3) - .child(description), - ) - .when_some(fork_row(&announcement, cx), |this, row| this.child(row)), - ) - .child( - h_flex() - .flex_none() - .gap_2() - .justify_end() - .child( - Popover::new("code-popover") - .open(self.clone_open) - .on_change(move |open, _, cx| { - if let Err(error) = weak_clone.update(cx, |this, cx| { - this.clone_open = open; - cx.notify(); - }) { - log::warn!("failed to update clone popover: {error}"); - } - }) - .trigger(move |_, _| { - Button::new("code") - .label("Code") - .icon(Icon::named(IconRole::GitClone)) - .tooltip(Tooltip::text("Clone repository")) - .loading(cloning) - .disabled(cloning) - .into_any_element() - }) - .content(move |_, cx| { - v_flex() - .w(px(440.)) - .p_3() - .gap_4() - .child(clone_group( - "Clone with ngit", - "copy-ngit".into(), - &ngit_for_popover, - cx, - )) - .child(clone_group( - "Clone with nak", - "copy-nak".into(), - &nak_for_popover, - cx, - )) - .child( - v_flex() - .gap_1() - .child( - div() - .text_xs() - .font_semibold() - .child("Grasp Servers"), - ) - .when(git_for_popover.is_empty(), |this| { - this.child( - div() - .text_xs() - .text_center() - .text_color( - cx.theme().colors.muted_foreground, - ) - .child("No git clone urls."), - ) - }) - .children(git_for_popover.iter().enumerate().map( - |(ix, command)| { - clone_row( - SharedString::from(format!( - "copy-git-{ix}" - )), - command.clone().into(), - cx, - ) - }, - )), - ) - .child( - h_flex().justify_end().child( - Button::new("download") - .icon(Icon::named(IconRole::GitClone)) - .label("Download") - .on_click({ - let weak = weak_download.clone(); - move |_, window, cx| { - if let Err(error) = - weak.update(cx, |this, cx| { - this.clone_to_folder(window, cx); - }) - { - log::warn!("failed to clone: {error}"); - } - } - }), - ), - ) - .into_any_element() - }), - ) - .child( - DropdownMenu::new("repo-menu") - .icon(IconRole::EllipsisVertical) - .variant(ButtonVariant::Ghost) - .disabled(pushing) - .open(self.repo_menu_open) - .on_open_change(move |open, _, cx| { - if let Err(error) = weak_menu_open.update(cx, |this, cx| { - this.repo_menu_open = open; - cx.notify(); - }) { - log::warn!("failed to update repo menu: {error}"); - } - }) - .items(move |_, cx| { - let owner = backend.read(cx).current_user() - == Some(announcement_for_menu.owner); - - let mut items = vec![MenuItem::new("About").handler({ - let weak = weak_menu_items.clone(); - let announcement = announcement_for_menu.clone(); - move |_, cx| { - if let Err(error) = weak.update(cx, |this, cx| { - this.about = Some(dialogs::about::AboutDialog::new( - announcement.clone(), - this.directory.clone(), - cx, - )); - cx.notify(); - }) { - log::warn!("failed to open about: {error}"); - } - } - })]; - - if owner { - items.push(MenuItem::new("Republish").handler({ - let weak = weak_menu_items.clone(); - move |window, cx| { - if let Err(error) = weak.update(cx, |this, cx| { - this.push_repository(window, cx); - }) { - log::warn!("failed to republish: {error}"); - } - } - })); - items.push(MenuItem::new("Reset remote to local").handler({ - let weak = weak_menu_items.clone(); - move |window, cx| { - if let Err(error) = weak.update(cx, |this, cx| { - this.reset_remote(window, cx); - }) { - log::warn!("failed to reset remote: {error}"); - } - } - })); - items.push(MenuItem::separator()); - items.push(MenuItem::new("Delete").destructive(true).handler( - { - let weak = weak_menu_items.clone(); - move |window, cx| { - if let Err(error) = weak.update(cx, |this, cx| { - this.delete_repository(window, cx); - }) { - log::warn!("failed to delete: {error}"); - } - } - }, - )); - } - - items - }), - ), - ) - .into_any_element() - } - - fn render_init_banner(&self, cx: &mut Context) -> AnyElement { - let binding = self - .store - .read(cx) - .nip34 - .as_ref() - .filter(|binding| binding.kind == Nip34Kind::Initialized); - - let path = self - .store - .read(cx) - .path - .as_ref() - .map(|path| path.display().to_string()) - .unwrap_or_default(); - - v_flex() - .flex_none() - .p_6() - .h_32() - .w_full() - .items_center() - .justify_center() - .gap_2() - .map(|this| match binding { - Some(binding) => this.child(bound_repo_label(binding, &self.directory, cx)), - None => this.child( - Button::new("init") - .icon(Icon::named(IconRole::ArrowUp)) - .label("Initialize on Nostr") - .tooltip(Tooltip::text("Publish this repository to Nostr")) - .on_click(cx.listener(|this, _, window, cx| { - this.open_init_dialog(window, cx); - })), - ), - }) - .child( - div() - .min_w_0() - .text_xs() - .text_color(cx.theme().colors.muted_foreground) - .child(path), - ) - .into_any_element() - } - - pub(super) fn render_metadata(&self, cx: &mut Context) -> AnyElement { - h_flex() - .px_6() - .h_12() - .w_full() - .gap_4() - .items_center() - .justify_between() - .child(self.render_maintainers(cx)) - .child(self.render_ref_controls(cx)) - .into_any_element() - } - - fn render_ref_controls(&self, cx: &mut Context) -> AnyElement { - h_flex() - .justify_end() - .flex_none() - .gap_2() - .when_some(self.render_last_commit(cx), |this, commit| { - this.child(commit) - }) - .child(self.refs.branch_select.clone()) - .child(self.refs.tag_select.clone()) - .into_any_element() - } - - fn render_last_commit(&self, cx: &mut Context) -> Option { - let commit = self.head_commit.as_ref()?; - let short = commit.id.get(..8).unwrap_or(&commit.id).to_owned(); - let history = self.history.clone(); - let commit_id = commit.id.clone(); - - Some( - h_flex() - .id("last-commit") - .h_8() - .px_2() - .gap_2() - .min_w_0() - .rounded(cx.theme().radius.control) - .hover(|this| this.bg(cx.theme().colors.muted_hover)) - .tooltip(Tooltip::text("View latest commit")) - .on_click(move |_, window, cx| { - history.update(cx, |history, cx| { - history.open_commit_diff(&commit_id, window, cx); - }); - }) - .child(Icon::named(IconRole::GitCommit).color(cx.theme().colors.muted_foreground)) - .child( - div() - .font_family(cx.theme().mono_font) - .text_sm() - .text_color(cx.theme().colors.muted_foreground) - .child(SharedString::from(short)), - ) - .child( - div() - .max_w(px(220.)) - .text_sm() - .text_ellipsis() - .whitespace_nowrap() - .child(commit.summary.clone()), - ) - .child( - div() - .text_sm() - .text_color(cx.theme().colors.muted_foreground) - .child(relative_time_secs(commit.time)), - ) - .into_any_element(), - ) - } - - fn render_maintainers(&self, cx: &mut Context) -> AnyElement { - let Some(announcement) = self.announcement(cx) else { - return div().into_any_element(); - }; - - let mut seen = HashSet::new(); - - let rest: Vec<_> = announcement - .maintainers - .iter() - .copied() - .filter(|key| key != &announcement.owner && seen.insert(*key)) - .collect(); - - let owner = self.directory.read(cx).profile(&announcement.owner, cx); - let owner_name = owner.name(); - - h_flex() - .min_w_0() - .gap_2() - .child( - h_flex() - .gap_2() - .child( - Avatar::new(announcement.owner) - .name(owner_name.clone()) - .picture(owner.picture()) - .small(), - ) - .child(div().text_xs().whitespace_nowrap().child(owner_name)), - ) - .when(!rest.is_empty(), |this| { - this.child( - div() - .text_xs() - .text_color(cx.theme().colors.muted_foreground) - .child(SharedString::from(format!("+{}", rest.len()))), - ) - }) - .into_any_element() - } -} diff --git a/crates/signed_app/src/repo/helpers.rs b/crates/signed_app/src/repo/helpers.rs index aab8867..18a1157 100644 --- a/crates/signed_app/src/repo/helpers.rs +++ b/crates/signed_app/src/repo/helpers.rs @@ -8,22 +8,92 @@ use gpui::{ }; use metadata::ProfileDirectory; use nostr::prelude::{RelayUrl, ToBech32}; -use signed_core::Announcement; +use signed_core::{Announcement, RepoAddr}; use signed_git::{DiffHunk, DiffLine, DiffLineKind, FileCommit, FileDiff, Repo, WorktreeSnapshot}; use signed_state::{Nip34Binding, RepoListStore, RepoStore}; use ui::avatar::Avatar; +use ui::clipboard::CopyRow; use ui::combobox::ComboboxState; use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex}; use ui::icons::{Icon, IconRole}; use ui::theme::ActiveTheme as _; -use utils::relative_time_secs; use super::RepoDetailView; -use crate::shared::tree::{TreeItemSeed, build_tree_items, sorted_worktree_paths}; +use ui::tree::TreeItemSeed; const GUTTER_WIDTH: f32 = 44.; pub const DIFF_ROW_HEIGHT: f32 = 20.; -pub const COMMIT_ROW_HEIGHT: f32 = 56.; + +#[derive(Clone, Copy)] +pub(super) enum DiffRow { + Hunk { + old_start: u32, + old_lines: u32, + new_start: u32, + new_lines: u32, + }, + Line { + hunk: usize, + line: usize, + }, +} + +impl DiffRow { + /// Renders one diff row against the file's hunks. + pub(super) fn render(self, hunks: &[DiffHunk], wrap: bool, cx: &App) -> AnyElement { + match self { + DiffRow::Hunk { + old_start, + old_lines, + new_start, + new_lines, + } => div() + .px_2() + .w_full() + .h(px(DIFF_ROW_HEIGHT)) + .font_family(cx.theme().mono_font) + .text_xs() + .bg(cx.theme().colors.muted) + .border_y_1() + .border_color(cx.theme().colors.border) + .text_color(cx.theme().colors.muted_foreground) + .child(SharedString::from(format!( + "@@ -{},{} +{},{} @@", + old_start, old_lines, new_start, new_lines + ))) + .into_any_element(), + DiffRow::Line { hunk, line } => { + match hunks.get(hunk).and_then(|h| h.lines.get(line)) { + Some(line) => render_diff_line(line, wrap, cx), + // A stale row index renders as a blank row rather than panicking. + None => div().w_full().h(px(DIFF_ROW_HEIGHT)).into_any_element(), + } + } + } + } +} + +pub(super) struct RepoData { + pub(super) tree: Vec, + pub(super) entries: Vec, + pub(super) readme_path: Option, + pub(super) readme: Option>, + pub(super) worktree: Option, + pub(super) branches: Vec, + pub(super) tags: Vec, + pub(super) current_branch: Option, + pub(super) head_commit: Option, +} + +/// Sorted relative paths of a worktree snapshot. +pub(crate) fn sorted_worktree_paths(entries: &[PathBuf]) -> Vec { + let mut paths: Vec = entries + .iter() + .map(|path| path.to_string_lossy().into_owned()) + .collect(); + paths.sort(); + paths +} /// The announcement's name, falling back to its id. pub fn announcement_display_name(announcement: &Announcement) -> SharedString { @@ -67,43 +137,12 @@ pub(super) fn snapshot_worktree( worktree: PathBuf, ) -> Result<(WorktreeSnapshot, Vec, Vec), Error> { let snapshot = Repo::open(&worktree)?.snapshot()?; - let tree = build_tree_items(&snapshot.entries); + let tree = TreeItemSeed::from_paths(&snapshot.entries); let paths = sorted_worktree_paths(&snapshot.entries); Ok((snapshot, tree, paths)) } -#[derive(Clone, Copy)] -pub(super) enum DiffRow { - Hunk { - old_start: u32, - old_lines: u32, - new_start: u32, - new_lines: u32, - }, - Line { - hunk: usize, - line: usize, - }, -} - -pub(super) struct RepoData { - pub(super) tree: Vec, - pub(super) entries: Vec, - pub(super) readme_path: Option, - pub(super) readme: Option>, - pub(super) worktree: Option, - pub(super) branches: Vec, - pub(super) tags: Vec, - pub(super) current_branch: Option, - pub(super) head_commit: Option, -} - -pub(super) fn clone_group( - label: &str, - id: SharedString, - command: &SharedString, - cx: &App, -) -> AnyElement { +pub(super) fn clone_group(label: &str, id: SharedString, command: &SharedString) -> AnyElement { v_flex() .gap_1() .min_w_0() @@ -113,7 +152,7 @@ pub(super) fn clone_group( .font_semibold() .child(SharedString::from(label)), ) - .child(crate::shared::widgets::clone_row(id, command.clone(), cx)) + .child(CopyRow::new(id, command.clone())) .into_any_element() } @@ -134,6 +173,23 @@ pub(super) fn nostr_clone_url(announcement: &Announcement, nip05: Option<&str>) SharedString::from(url) } +/// The display name of the announcement addressing `addr`, falling back to its identifier. +pub(crate) fn upstream_display_name( + addr: &RepoAddr, + announcements: &[Announcement], +) -> SharedString { + announcements + .iter() + .find(|a| a.addr() == *addr) + .map(|a| { + a.name + .as_deref() + .map(SharedString::from) + .unwrap_or_else(|| SharedString::from(a.id.clone())) + }) + .unwrap_or_else(|| SharedString::from(addr.identifier().to_owned())) +} + pub(super) fn fork_row( announcement: &Announcement, cx: &mut Context, @@ -142,18 +198,8 @@ pub(super) fn fork_row( let (label, clickable) = match &upstream.addr { Some(addr) => { - let name = RepoListStore::global(cx) - .read(cx) - .announcements - .iter() - .find(|a| a.addr() == *addr) - .map(|a| { - a.name - .as_deref() - .map(SharedString::from) - .unwrap_or_else(|| SharedString::from(a.id.clone())) - }) - .unwrap_or_else(|| SharedString::from(addr.identifier().to_owned())); + let name = + upstream_display_name(addr, &RepoListStore::global(cx).read(cx).announcements); (SharedString::from(format!("Forked from {name}")), true) } None => (SharedString::from(upstream.display().as_str()), false), @@ -180,7 +226,7 @@ pub(super) fn fork_row( pub(super) fn load_repo_data(repo: &Repo) -> Result { let snapshot = repo.snapshot()?; let worktree = repo.workdir().map(Path::to_path_buf); - let tree = build_tree_items(&snapshot.entries); + let tree = TreeItemSeed::from_paths(&snapshot.entries); Ok(RepoData { tree, @@ -267,10 +313,6 @@ pub(super) fn source_hash(text: &str) -> u64 { hasher.finish() } -pub(super) fn preview_spinner() -> AnyElement { - crate::shared::widgets::centered_spinner("repo-preview-spinner") -} - /// The kit grammar for a path; only four languages are supported. pub(super) fn code_language(path: &str) -> ui::highlight::Language { use ui::highlight::Language; @@ -318,41 +360,6 @@ pub(super) fn diff_rows(file: &FileDiff) -> Vec { rows } -pub(super) fn render_diff_row( - hunks: &[DiffHunk], - row: DiffRow, - wrap: bool, - cx: &App, -) -> AnyElement { - match row { - DiffRow::Hunk { - old_start, - old_lines, - new_start, - new_lines, - } => div() - .px_2() - .w_full() - .h(px(DIFF_ROW_HEIGHT)) - .font_family(cx.theme().mono_font) - .text_xs() - .bg(cx.theme().colors.muted) - .border_y_1() - .border_color(cx.theme().colors.border) - .text_color(cx.theme().colors.muted_foreground) - .child(SharedString::from(format!( - "@@ -{},{} +{},{} @@", - old_start, old_lines, new_start, new_lines - ))) - .into_any_element(), - DiffRow::Line { hunk, line } => match hunks.get(hunk).and_then(|h| h.lines.get(line)) { - Some(line) => render_diff_line(line, wrap, cx), - // A stale row index renders as a blank row rather than panicking. - None => div().w_full().h(px(DIFF_ROW_HEIGHT)).into_any_element(), - }, - } -} - fn render_diff_line(line: &DiffLine, wrap: bool, cx: &App) -> AnyElement { let bg = match line.kind { DiffLineKind::Addition => Some(cx.theme().ramps.success.base.opacity(0.2)), @@ -399,63 +406,6 @@ fn render_diff_line(line: &DiffLine, wrap: bool, cx: &App) -> AnyElement { .into_any_element() } -pub(crate) fn commit_row( - ix: usize, - commit: &FileCommit, - action: Option, - on_click: impl Fn(&mut Window, &mut gpui::App) + 'static, - cx: &gpui::App, -) -> gpui::AnyElement { - h_flex() - .id(ix) - .px_4() - .h(px(COMMIT_ROW_HEIGHT)) - .w_full() - .gap_3() - .border_b_1() - .border_color(cx.theme().colors.border) - .hover(|this| this.bg(cx.theme().colors.muted_hover)) - .child( - v_flex() - .flex_1() - .min_w_0() - .gap_1() - .justify_center() - .child( - h_flex() - .gap_2() - .overflow_hidden() - .child( - div() - .font_family(cx.theme().mono_font) - .text_sm() - .text_color(cx.theme().colors.muted_foreground) - .child(short_id(&commit.id)), - ) - .child( - div() - .flex_1() - .min_w_0() - .text_sm() - .text_ellipsis() - .whitespace_nowrap() - .child(commit.summary.clone()), - ), - ) - .child( - h_flex() - .gap_2() - .text_xs() - .text_color(cx.theme().colors.muted_foreground) - .child(commit.author.clone()) - .child(relative_time_secs(commit.time)), - ), - ) - .when_some(action, |row, action| row.child(action)) - .on_click(move |_, window, cx| on_click(window, cx)) - .into_any_element() -} - pub(super) fn sync_selector( select: &Entity>, cached: &mut Vec, diff --git a/crates/signed_app/src/repo/history.rs b/crates/signed_app/src/repo/history.rs index 2827ec4..362fa5d 100644 --- a/crates/signed_app/src/repo/history.rs +++ b/crates/signed_app/src/repo/history.rs @@ -12,19 +12,21 @@ use signed_state::{Backend, RepoStore, SyncStatusDirectory}; use ui::alert::{Alert, AlertSeverity, AlertStyle}; use ui::button::{Button, ButtonVariant}; use ui::common::{Sizable as _, v_flex}; +use ui::empty_state::EmptyState; use ui::icons::{Icon, IconRole}; +use ui::spinner::Spinner; use ui::theme::ActiveTheme as _; use ui::tooltip::Tooltip; use super::RepoDetailView; use super::commit_diff::CommitDiffView; +use crate::app::AppRoot; use crate::shared::event_list::commit_list; use crate::shared::panels; -use crate::workspace::Workspace; pub struct RepoHistoryView { store: Entity, - workspace: WeakEntity, + workspace: WeakEntity, detail: WeakEntity, sync_directory: Entity, worktree: Option, @@ -41,7 +43,7 @@ pub struct RepoHistoryView { impl RepoHistoryView { pub fn new( store: Entity, - workspace: WeakEntity, + workspace: WeakEntity, detail: WeakEntity, sync_directory: Entity, ) -> Self { @@ -159,7 +161,7 @@ impl Render for RepoHistoryView { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let Some(list) = self.all_commits.as_ref() else { return if self.loading_all_commits { - crate::shared::widgets::centered_spinner("commits-loading") + Spinner::centered("commits-loading") } else if let Some(error) = self.error.clone() { let weak = cx.entity().downgrade(); v_flex() @@ -183,12 +185,12 @@ impl Render for RepoHistoryView { ) .into_any_element() } else { - crate::shared::widgets::empty_state("Failed to load commits") + EmptyState::centered("Failed to load commits") }; }; if self.commits.is_empty() { - return crate::shared::widgets::empty_state("No commits found"); + return EmptyState::centered("No commits found"); } let commits = Arc::clone(&self.commits); @@ -261,7 +263,6 @@ impl Render for RepoHistoryView { log::warn!("failed to open commit diff: {error}"); } }, - cx, ); v_flex() diff --git a/crates/signed_app/src/repo/mod.rs b/crates/signed_app/src/repo/mod.rs index 1654dfc..beb6deb 100644 --- a/crates/signed_app/src/repo/mod.rs +++ b/crates/signed_app/src/repo/mod.rs @@ -5,48 +5,56 @@ use anyhow::Error; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, - ParentElement as _, PathPromptOptions, Render, SharedString, Styled as _, Subscription, - SystemNotification, Task, WeakEntity, Window, div, + ParentElement as _, PathPromptOptions, Render, SharedString, StatefulInteractiveElement as _, + Styled as _, Subscription, SystemNotification, Task, WeakEntity, Window, div, px, }; use metadata::ProfileDirectory; use nostr::prelude::{PublicKey, Url}; use signed_core::{Announcement, RepoAddr}; use signed_git::{FileCommit, GitCache, Repo}; use signed_state::{ - Backend, BackendEvent, LocalReposStore, Mirrors, Nip34Binding, PushStepStatus, RepoStore, - SyncStatusDirectory, + Backend, BackendEvent, LocalReposStore, Mirrors, Nip34Binding, Nip34Kind, PushStepStatus, + RepoStore, SyncStatusDirectory, }; use ui::alert::{Alert, AlertSeverity}; use ui::avatar::Avatar; use ui::badge::Badge; use ui::button::{Button, ButtonVariant}; -use ui::common::{Sizable as _, h_flex, v_flex}; +use ui::clipboard::CopyRow; +use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex}; use ui::dialog::Dialog; +use ui::dropdown_menu::DropdownMenu; use ui::icons::{Icon, IconRole}; use ui::layout::panel::Panel; +use ui::menu::MenuItem; +use ui::popover::Popover; use ui::sidebar::{Sidebar, SidebarEntry}; use ui::spinner::Spinner; use ui::theme::ActiveTheme as _; +use ui::tooltip::Tooltip; pub mod actions; pub mod commit_diff; pub mod dialogs; pub mod files; -mod header; pub mod helpers; pub mod history; pub mod refs; use files::RepoFilesView; -use helpers::{RepoData, announcement_display_name, load_repo_data, snapshot_worktree}; +use helpers::{ + RepoData, announcement_display_name, bound_repo_label, clone_group, fork_row, load_repo_data, + nostr_clone_url, repo_display_name, snapshot_worktree, +}; use history::RepoHistoryView; use refs::RefSwitcher; +use utils::relative_time_secs; +use crate::app::AppRoot; use crate::issues::IssuesView; use crate::pull_requests::PullRequestsView; +use crate::repo::helpers::{short_id, sorted_worktree_paths}; use crate::shared::log_dropped; -use crate::shared::tree::sorted_worktree_paths; -use crate::workspace::Workspace; #[derive(Clone, Copy, PartialEq, Eq)] pub(super) enum RepoSection { @@ -65,7 +73,7 @@ pub enum RefKind { } pub struct RepoDetailView { - pub(super) workspace: WeakEntity, + pub(super) workspace: WeakEntity, pub(super) store: Entity, about: Option>, init: Option>, @@ -104,7 +112,7 @@ pub struct RepoDetailView { impl RepoDetailView { pub fn new( - workspace: WeakEntity, + workspace: WeakEntity, addr: RepoAddr, hint: Option, window: &mut Window, @@ -115,7 +123,7 @@ impl RepoDetailView { } pub fn new_local( - workspace: WeakEntity, + workspace: WeakEntity, local_path: PathBuf, nip34: Option, window: &mut Window, @@ -127,7 +135,7 @@ impl RepoDetailView { /// A local repository whose detected binding matches an announcement. pub fn new_local_announced( - workspace: WeakEntity, + workspace: WeakEntity, announcement: Announcement, local_path: PathBuf, window: &mut Window, @@ -139,7 +147,7 @@ impl RepoDetailView { } fn new_common( - workspace: WeakEntity, + workspace: WeakEntity, store: Entity, window: &mut Window, cx: &mut Context, @@ -193,7 +201,7 @@ impl RepoDetailView { let store_for_attach = store.clone(); window.defer(cx, move |window, cx| { - crate::shared::log_dropped(weak.update(cx, |this, cx| { + log_dropped(weak.update(cx, |this, cx| { this.attach_store(&store_for_attach, window, cx); this.load_repo(window, cx); })); @@ -470,6 +478,7 @@ impl RepoDetailView { if let Ok(Some((moved, snapshot))) = refresh { let branches: Vec = snapshot.branches.iter().map(Into::into).collect(); + let tags: Vec = snapshot.tags.iter().map(Into::into).collect(); let current_branch = snapshot.current_branch.clone(); let head_commit = snapshot.head_commit.clone(); @@ -828,7 +837,7 @@ impl RepoDetailView { match result { Ok(()) => { if let Some(tag) = &tag { - let short = crate::repo::helpers::short_id(&commit); + let short = short_id(&commit); let (title, body) = match store.read(cx).last_push_warning.clone() { Some(warning) => ("Sync partially failed", warning), None => ("Sync complete", format!("Synced up to {short}")), @@ -978,7 +987,7 @@ impl RepoDetailView { (Some(2), true) => RepoSection::PullRequests, _ => return, }; - crate::shared::log_dropped(weak.update(cx, |this, cx| { + log_dropped(weak.update(cx, |this, cx| { this.active_section = section; cx.notify(); })); @@ -1028,6 +1037,434 @@ impl RepoDetailView { RepoSection::PullRequests => self.pulls.clone().into_any_element(), } } + + pub(super) fn open_upstream(&mut self, window: &mut Window, cx: &mut Context) { + let Some(addr) = self + .announcement(cx) + .and_then(|announcement| announcement.upstream.as_ref()) + .and_then(|upstream| upstream.addr.clone()) + else { + return; + }; + + actions::open_repo_panel(&self.workspace, &addr, None, window, cx); + } + + /// Open the dialog that publishes the local repository to NIP-34. + fn open_init_dialog(&mut self, window: &mut Window, cx: &mut Context) { + let Some(local_path) = self.store.read(cx).path.clone() else { + return; + }; + self.init = Some(dialogs::init::InitRepoDialog::new( + local_path, + cx.entity().downgrade(), + window, + cx, + )); + cx.notify(); + } + + pub(super) fn render_about(&mut self, cx: &mut Context) -> AnyElement { + if self.store.read(cx).addr().is_none() { + return self.render_init_banner(cx); + } + + let backend = Backend::global(cx); + let store = self.store.read(cx); + let pushing = store.pushing; + let cloning = store.cloning; + + let Some(announcement) = store.announcement.clone() else { + return div().into_any_element(); + }; + + let nip05 = self + .directory + .read(cx) + .profile(&announcement.owner, cx) + .metadata() + .nip05 + .clone() + .filter(|nip05| !nip05.trim().is_empty()); + + let nostr_url = nostr_clone_url(&announcement, nip05.as_deref()); + let ngit_command = SharedString::from(format!("git clone {nostr_url}")); + let nak_command = SharedString::from(format!("nak git clone {nostr_url}")); + let git_commands: Vec = announcement.clone_urls(); + + let name = repo_display_name(self.store.read(cx)); + let description = announcement.description(); + let avatar = Avatar::new(format!("{}:{}", announcement.owner, announcement.id)); + + let announcement_for_menu = announcement.clone(); + let weak_menu_open = cx.entity().downgrade(); + let weak_menu_items = cx.entity().downgrade(); + let weak_clone = cx.entity().downgrade(); + let weak_download = cx.entity().downgrade(); + let ngit_for_popover = ngit_command.clone(); + let nak_for_popover = nak_command.clone(); + let git_for_popover = git_commands.clone(); + + h_flex() + .p_6() + .w_full() + .gap_6() + .items_start() + .justify_between() + .child( + v_flex() + .flex_1() + .min_w_0() + .gap_2() + .child( + h_flex() + .gap_2() + .text_sm() + .font_semibold() + .child(avatar) + .child(name), + ) + .child( + div() + .min_w_0() + .text_sm() + .text_color(cx.theme().colors.muted_foreground) + .line_clamp(3) + .child(description), + ) + .when_some(fork_row(&announcement, cx), |this, row| this.child(row)), + ) + .child( + h_flex() + .flex_none() + .gap_2() + .justify_end() + .child( + Popover::new("code-popover") + .open(self.clone_open) + .on_change(move |open, _, cx| { + if let Err(error) = weak_clone.update(cx, |this, cx| { + this.clone_open = open; + cx.notify(); + }) { + log::warn!("failed to update clone popover: {error}"); + } + }) + .trigger(move |_, _| { + Button::new("code") + .label("Code") + .icon(Icon::named(IconRole::GitClone)) + .tooltip(Tooltip::text("Clone repository")) + .loading(cloning) + .disabled(cloning) + .into_any_element() + }) + .content(move |_, cx| { + v_flex() + .w(px(440.)) + .p_3() + .gap_4() + .child(clone_group( + "Clone with ngit", + "copy-ngit".into(), + &ngit_for_popover, + )) + .child(clone_group( + "Clone with nak", + "copy-nak".into(), + &nak_for_popover, + )) + .child( + v_flex() + .gap_1() + .child( + div() + .text_xs() + .font_semibold() + .child("Grasp Servers"), + ) + .when(git_for_popover.is_empty(), |this| { + this.child( + div() + .text_xs() + .text_center() + .text_color( + cx.theme().colors.muted_foreground, + ) + .child("No git clone urls."), + ) + }) + .children(git_for_popover.iter().enumerate().map( + |(ix, command)| { + CopyRow::new( + SharedString::from(format!( + "copy-git-{ix}" + )), + command.clone(), + ) + }, + )), + ) + .child( + h_flex().justify_end().child( + Button::new("download") + .icon(Icon::named(IconRole::GitClone)) + .label("Download") + .on_click({ + let weak = weak_download.clone(); + move |_, window, cx| { + if let Err(error) = + weak.update(cx, |this, cx| { + this.clone_to_folder(window, cx); + }) + { + log::warn!("failed to clone: {error}"); + } + } + }), + ), + ) + .into_any_element() + }), + ) + .child( + DropdownMenu::new("repo-menu") + .icon(IconRole::EllipsisVertical) + .variant(ButtonVariant::Ghost) + .disabled(pushing) + .open(self.repo_menu_open) + .on_open_change(move |open, _, cx| { + if let Err(error) = weak_menu_open.update(cx, |this, cx| { + this.repo_menu_open = open; + cx.notify(); + }) { + log::warn!("failed to update repo menu: {error}"); + } + }) + .items(move |_, cx| { + let owner = backend.read(cx).current_user() + == Some(announcement_for_menu.owner); + + let mut items = vec![MenuItem::new("About").handler({ + let weak = weak_menu_items.clone(); + let announcement = announcement_for_menu.clone(); + move |_, cx| { + if let Err(error) = weak.update(cx, |this, cx| { + this.about = Some(dialogs::about::AboutDialog::new( + announcement.clone(), + this.directory.clone(), + cx, + )); + cx.notify(); + }) { + log::warn!("failed to open about: {error}"); + } + } + })]; + + if owner { + items.push(MenuItem::new("Republish").handler({ + let weak = weak_menu_items.clone(); + move |window, cx| { + if let Err(error) = weak.update(cx, |this, cx| { + this.push_repository(window, cx); + }) { + log::warn!("failed to republish: {error}"); + } + } + })); + items.push(MenuItem::new("Reset remote to local").handler({ + let weak = weak_menu_items.clone(); + move |window, cx| { + if let Err(error) = weak.update(cx, |this, cx| { + this.reset_remote(window, cx); + }) { + log::warn!("failed to reset remote: {error}"); + } + } + })); + items.push(MenuItem::separator()); + items.push(MenuItem::new("Delete").destructive(true).handler( + { + let weak = weak_menu_items.clone(); + move |window, cx| { + if let Err(error) = weak.update(cx, |this, cx| { + this.delete_repository(window, cx); + }) { + log::warn!("failed to delete: {error}"); + } + } + }, + )); + } + + items + }), + ), + ) + .into_any_element() + } + + fn render_init_banner(&self, cx: &mut Context) -> AnyElement { + let binding = self + .store + .read(cx) + .nip34 + .as_ref() + .filter(|binding| binding.kind == Nip34Kind::Initialized); + + let path = self + .store + .read(cx) + .path + .as_ref() + .map(|path| path.display().to_string()) + .unwrap_or_default(); + + v_flex() + .flex_none() + .p_6() + .h_32() + .w_full() + .items_center() + .justify_center() + .gap_2() + .map(|this| match binding { + Some(binding) => this.child(bound_repo_label(binding, &self.directory, cx)), + None => this.child( + Button::new("init") + .icon(Icon::named(IconRole::ArrowUp)) + .label("Initialize on Nostr") + .tooltip(Tooltip::text("Publish this repository to Nostr")) + .on_click(cx.listener(|this, _, window, cx| { + this.open_init_dialog(window, cx); + })), + ), + }) + .child( + div() + .min_w_0() + .text_xs() + .text_color(cx.theme().colors.muted_foreground) + .child(path), + ) + .into_any_element() + } + + pub(super) fn render_metadata(&self, cx: &mut Context) -> AnyElement { + h_flex() + .px_6() + .h_12() + .w_full() + .gap_4() + .items_center() + .justify_between() + .child(self.render_maintainers(cx)) + .child(self.render_ref_controls(cx)) + .into_any_element() + } + + fn render_ref_controls(&self, cx: &mut Context) -> AnyElement { + h_flex() + .justify_end() + .flex_none() + .gap_2() + .when_some(self.render_last_commit(cx), |this, commit| { + this.child(commit) + }) + .child(self.refs.branch_select.clone()) + .child(self.refs.tag_select.clone()) + .into_any_element() + } + + fn render_last_commit(&self, cx: &mut Context) -> Option { + let commit = self.head_commit.as_ref()?; + let short = commit.id.get(..8).unwrap_or(&commit.id).to_owned(); + let history = self.history.clone(); + let commit_id = commit.id.clone(); + + Some( + h_flex() + .id("last-commit") + .h_8() + .px_2() + .gap_2() + .min_w_0() + .rounded(cx.theme().radius.control) + .hover(|this| this.bg(cx.theme().colors.muted_hover)) + .tooltip(Tooltip::text("View latest commit")) + .on_click(move |_, window, cx| { + history.update(cx, |history, cx| { + history.open_commit_diff(&commit_id, window, cx); + }); + }) + .child(Icon::named(IconRole::GitCommit).color(cx.theme().colors.muted_foreground)) + .child( + div() + .font_family(cx.theme().mono_font) + .text_sm() + .text_color(cx.theme().colors.muted_foreground) + .child(SharedString::from(short)), + ) + .child( + div() + .max_w(px(220.)) + .text_sm() + .text_ellipsis() + .whitespace_nowrap() + .child(commit.summary.clone()), + ) + .child( + div() + .text_sm() + .text_color(cx.theme().colors.muted_foreground) + .child(relative_time_secs(commit.time)), + ) + .into_any_element(), + ) + } + + fn render_maintainers(&self, cx: &mut Context) -> AnyElement { + let Some(announcement) = self.announcement(cx) else { + return div().into_any_element(); + }; + + let mut seen = HashSet::new(); + + let rest: Vec<_> = announcement + .maintainers + .iter() + .copied() + .filter(|key| key != &announcement.owner && seen.insert(*key)) + .collect(); + + let owner = self.directory.read(cx).profile(&announcement.owner, cx); + let owner_name = owner.name(); + + h_flex() + .min_w_0() + .gap_2() + .child( + h_flex() + .gap_2() + .child( + Avatar::new(announcement.owner) + .name(owner_name.clone()) + .picture(owner.picture()) + .small(), + ) + .child(div().text_xs().whitespace_nowrap().child(owner_name)), + ) + .when(!rest.is_empty(), |this| { + this.child( + div() + .text_xs() + .text_color(cx.theme().colors.muted_foreground) + .child(SharedString::from(format!("+{}", rest.len()))), + ) + }) + .into_any_element() + } } impl Panel for RepoDetailView { diff --git a/crates/signed_app/src/settings/helpers.rs b/crates/signed_app/src/settings/helpers.rs index e98838d..17e30f2 100644 --- a/crates/signed_app/src/settings/helpers.rs +++ b/crates/signed_app/src/settings/helpers.rs @@ -1,11 +1,11 @@ use std::path::PathBuf; use gpui::{ - AnyElement, App, AppContext as _, Entity, IntoElement, ParentElement as _, PathPromptOptions, - SharedString, Styled as _, Window, div, px, + AnyElement, App, AppContext as _, Div, Entity, IntoElement, ParentElement as _, + PathPromptOptions, SharedString, Styled as _, Window, div, px, }; use settings::{AppearanceMode, EventFetchingStrategy, SettingsStore}; -use ui::button::Button; +use ui::button::{Button, ButtonVariant}; use ui::common::{StyledExt as _, h_flex, v_flex}; use ui::icons::{Icon, IconRole}; use ui::input::{Input, InputState}; @@ -13,8 +13,26 @@ use ui::select::{Select, SelectOption}; use ui::theme::ActiveTheme as _; use ui::tooltip::Tooltip; +use crate::apply_appearance_mode; use crate::repo::dialogs::grasp_servers::{normalize_server, server_host}; +/// The title and description a settings row or block opens with. +fn setting_header( + cx: &App, + title: impl Into, + description: impl Into, +) -> Div { + v_flex() + .gap_1() + .child(div().text_sm().font_semibold().child(title.into())) + .child( + div() + .text_xs() + .text_color(cx.theme().colors.muted_foreground) + .child(description.into()), + ) +} + /// A settings row with the label and description on the left and the control on the right. pub fn setting_row( cx: &App, @@ -26,19 +44,7 @@ pub fn setting_row( .w_full() .justify_between() .gap_4() - .child( - v_flex() - .flex_1() - .min_w_0() - .gap_1() - .child(div().text_sm().font_semibold().child(title.into())) - .child( - div() - .text_xs() - .text_color(cx.theme().colors.muted_foreground) - .child(description.into()), - ), - ) + .child(setting_header(cx, title, description)) .child(div().w(px(200.)).flex_shrink_0().child(control)) .into_any_element() } @@ -53,17 +59,7 @@ pub fn setting_block( v_flex() .w_full() .gap_3() - .child( - v_flex() - .gap_1() - .child(div().text_sm().font_semibold().child(title.into())) - .child( - div() - .text_xs() - .text_color(cx.theme().colors.muted_foreground) - .child(description.into()), - ), - ) + .child(setting_header(cx, title, description)) .child(control) .into_any_element() } @@ -84,7 +80,7 @@ pub fn appearance_select(cx: &App) -> Select { SettingsStore::global(cx).update(cx, |store, cx| { store.edit(|settings| settings.appearance = mode, cx); }); - crate::apply_appearance_mode(mode, cx); + apply_appearance_mode(mode, cx); }) } @@ -106,6 +102,36 @@ pub fn event_fetching_select(cx: &App) -> Select { }) } +/// One editable value: a muted row with a trailing remove button. +fn editor_value_row( + id: String, + text: SharedString, + on_remove: impl Fn(&mut App) + 'static, + cx: &App, +) -> AnyElement { + h_flex() + .gap_1() + .child( + h_flex() + .flex_1() + .h_8() + .px_2() + .bg(cx.theme().colors.muted) + .text_color(cx.theme().colors.muted_foreground) + .text_xs() + .rounded(cx.theme().radius.control) + .child(text), + ) + .child( + Button::new(id) + .icon(Icon::named(IconRole::Close)) + .variant(ButtonVariant::Ghost) + .tooltip(Tooltip::text("Remove")) + .on_click(move |_, _, cx| on_remove(cx)), + ) + .into_any_element() +} + pub fn grasp_servers_editor(input: &Entity, cx: &App) -> AnyElement { let store = SettingsStore::global(cx); let servers = store @@ -119,48 +145,30 @@ pub fn grasp_servers_editor(input: &Entity, cx: &App) -> AnyElement .gap_2() .children(servers.iter().enumerate().map(|(ix, server)| { let server = server.clone(); - h_flex() - .gap_1() - .child( - h_flex() - .flex_1() - .h_8() - .px_2() - .bg(cx.theme().colors.muted) - .text_color(cx.theme().colors.muted_foreground) - .text_xs() - .rounded(cx.theme().radius.control) - .child(display_server(&server)), - ) - .child( - Button::new(format!("settings-remove-server:{ix}")) - .icon(Icon::named(IconRole::Close)) - .variant(ui::button::ButtonVariant::Ghost) - .tooltip(Tooltip::text("Remove")) - .on_click({ - let store = store.clone(); - move |_, _, cx| { - store.update(cx, |store, cx| { - store.edit( - |settings| { - // A row's index can desync after a prior - // removal; match by value. - if let Some(at) = settings - .grasp_servers - .default_servers - .iter() - .position(|known| known == &server) - { - settings.grasp_servers.default_servers.remove(at); - } - }, - cx, - ); - }); - } - }), - ) - .into_any_element() + editor_value_row( + format!("settings-remove-server:{ix}"), + display_server(&server), + move |cx| { + let store = SettingsStore::global(cx); + store.update(cx, |store, cx| { + store.edit( + |settings| { + // A row's index can desync after a prior removal; match by value. + if let Some(at) = settings + .grasp_servers + .default_servers + .iter() + .position(|known| known == &server) + { + settings.grasp_servers.default_servers.remove(at); + } + }, + cx, + ); + }); + }, + cx, + ) })) .child( h_flex() @@ -173,7 +181,7 @@ pub fn grasp_servers_editor(input: &Entity, cx: &App) -> AnyElement .child( Button::new("settings-add-server") .icon(Icon::named(IconRole::Plus)) - .variant(ui::button::ButtonVariant::Ghost) + .variant(ButtonVariant::Ghost) .tooltip(Tooltip::text("Add grasp server")) .on_click({ let input = input.clone(); @@ -229,46 +237,30 @@ pub fn scan_paths_editor(cx: &App) -> AnyElement { .gap_2() .children(scan_paths.iter().enumerate().map(|(ix, path)| { let path = path.clone(); - h_flex() - .gap_1() - .child( - h_flex() - .flex_1() - .h_8() - .px_2() - .bg(cx.theme().colors.muted) - .text_color(cx.theme().colors.muted_foreground) - .text_xs() - .rounded(cx.theme().radius.control) - .child(path.display().to_string()), - ) - .child( - Button::new(format!("settings-remove-path:{ix}")) - .icon(Icon::named(IconRole::Close)) - .variant(ui::button::ButtonVariant::Ghost) - .tooltip(Tooltip::text("Remove")) - .on_click(move |_, _, cx| { - let store = SettingsStore::global(cx); - store.update(cx, |store, cx| { - store.edit( - |settings| { - // A row's index can desync after a prior - // removal; match by value. - if let Some(at) = settings - .local_repos - .scan_paths - .iter() - .position(|known| known == &path) - { - settings.local_repos.scan_paths.remove(at); - } - }, - cx, - ); - }); - }), - ) - .into_any_element() + editor_value_row( + format!("settings-remove-path:{ix}"), + SharedString::from(path.display().to_string()), + move |cx| { + let store = SettingsStore::global(cx); + store.update(cx, |store, cx| { + store.edit( + |settings| { + // A row's index can desync after a prior removal; match by value. + if let Some(at) = settings + .local_repos + .scan_paths + .iter() + .position(|known| known == &path) + { + settings.local_repos.scan_paths.remove(at); + } + }, + cx, + ); + }); + }, + cx, + ) })) .child( h_flex().justify_end().child( @@ -328,7 +320,7 @@ pub fn default_folder_selector(default_folder: &Entity) -> AnyElemen .child( Button::new("settings-choose-folder") .icon(Icon::named(IconRole::Folder)) - .variant(ui::button::ButtonVariant::Ghost) + .variant(ButtonVariant::Ghost) .tooltip(Tooltip::text("Choose folder")) .on_click(move |_, window, cx| { choose_default_folder(&folder, window, cx); diff --git a/crates/signed_app/src/shared/event_list.rs b/crates/signed_app/src/shared/event_list.rs index f602d7c..8d63d90 100644 --- a/crates/signed_app/src/shared/event_list.rs +++ b/crates/signed_app/src/shared/event_list.rs @@ -15,30 +15,22 @@ use signed_core::RepoStatus; use signed_git::FileCommit; use ui::avatar::Avatar; use ui::common::{Sizable as _, h_flex, v_flex}; +use ui::empty_state::EmptyState; +use ui::scrollbar::Scrollbar; use ui::theme::ActiveTheme as _; +use utils::relative_time_secs; -use crate::repo::helpers::commit_row; -use crate::shared::widgets::{empty_state, scroll_overlay, status_badge}; +use crate::repo::helpers::short_id; +use crate::shared::widgets::status_badge; /// The height of one issue or pull-request row. pub const ROW_HEIGHT: f32 = 73.; +/// The height of one commit row in the commit list. +pub const COMMIT_ROW_HEIGHT: f32 = 56.; /// A row's activation handler. pub type EventHandler = Rc; -/// The toolbar above the issue and pull-request lists: a filter and its actions. -pub fn filter_toolbar(cx: &App, children: impl IntoIterator) -> AnyElement { - h_flex() - .px_4() - .w_full() - .gap_3() - .border_b_1() - .border_color(cx.theme().colors.border) - .bg(cx.theme().colors.muted) - .children(children) - .into_any_element() -} - /// One issue or pull-request row's display data and click handler. pub struct EventRow { pub id: ElementId, @@ -52,8 +44,68 @@ pub struct EventRow { pub on_click: EventHandler, } -/// The shared issue and pull-request list: toolbar, uniform rows, scrollbar -/// overlay, and empty state. +impl EventRow { + /// Renders one issue or pull-request row. + fn render(&self, row_height: Pixels, cx: &App) -> AnyElement { + h_flex() + .id(self.id.clone()) + .w_full() + .h(row_height) + .gap_4() + .px_4() + .border_b_1() + .border_color(cx.theme().colors.border) + .hover(|this| this.bg(cx.theme().colors.muted_hover)) + .on_click({ + let on_click = self.on_click.clone(); + move |event, window, cx| on_click(event, window, cx) + }) + .child(status_badge(self.status)) + .child( + v_flex() + .flex_1() + .min_w_0() + .gap_1() + .child( + div() + .text_base() + .text_ellipsis() + .whitespace_nowrap() + .child(self.title.clone()), + ) + .child(self.meta_row(cx)), + ) + .into_any_element() + } + + /// The author, age, and id line under a row's title. + fn meta_row(&self, cx: &App) -> AnyElement { + h_flex() + .gap_2() + .text_xs() + .child( + h_flex() + .gap_1() + .child( + Avatar::new(self.pubkey) + .name(self.author.clone()) + .picture(self.picture.clone()) + .small(), + ) + .child(div().child(self.author.clone())), + ) + .child(SharedString::from("opened")) + .child( + div() + .text_color(cx.theme().colors.muted_foreground) + .child(self.short_id.clone()), + ) + .child(self.age.clone()) + .into_any_element() + } +} + +/// The shared issue and pull-request list, pub struct EventList { id: ElementId, toolbar: Option, @@ -118,86 +170,39 @@ impl EventList { let Some(row) = rows.get(ix) else { return div().into_any_element(); }; - event_row(row, row_height, cx) + row.render(row_height, cx) }) .collect() }) .track_scroll(&self.scroll_handle) .size_full(), ) - .child(scroll_overlay( + .child(Scrollbar::vertical( (self.id.clone(), "scroll"), self.scroll_handle.clone(), )) }) .when(count == 0, |this| { - this.child(empty_state(self.empty_message)) + this.child(EmptyState::centered(self.empty_message)) }) .into_any_element() } } -/// Renders one issue or pull-request row. -pub fn event_row(row: &EventRow, row_height: Pixels, cx: &App) -> AnyElement { +/// The toolbar above the issue and pull-request lists: a filter and its actions. +pub fn filter_toolbar(cx: &App, children: impl IntoIterator) -> AnyElement { h_flex() - .id(row.id.clone()) - .w_full() - .h(row_height) - .gap_4() .px_4() + .w_full() + .gap_3() .border_b_1() .border_color(cx.theme().colors.border) - .hover(|this| this.bg(cx.theme().colors.muted_hover)) - .on_click({ - let on_click = row.on_click.clone(); - move |event, window, cx| on_click(event, window, cx) - }) - .child(status_badge(row.status)) - .child( - v_flex() - .flex_1() - .min_w_0() - .gap_1() - .child( - div() - .text_base() - .text_ellipsis() - .whitespace_nowrap() - .child(row.title.clone()), - ) - .child(event_meta_row(row, cx)), - ) - .into_any_element() -} - -/// The author, age, and id line under a row's title. -pub fn event_meta_row(row: &EventRow, cx: &App) -> AnyElement { - h_flex() - .gap_2() - .text_xs() - .child( - h_flex() - .gap_1() - .child( - Avatar::new(row.pubkey) - .name(row.author.clone()) - .picture(row.picture.clone()) - .small(), - ) - .child(div().child(row.author.clone())), - ) - .child(SharedString::from("opened")) - .child( - div() - .text_color(cx.theme().colors.muted_foreground) - .child(row.short_id.clone()), - ) - .child(row.age.clone()) + .bg(cx.theme().colors.muted) + .children(children) .into_any_element() } /// A scrollable commit list: uniform `commit_row`s under a scrollbar overlay. -#[allow(clippy::too_many_arguments)] pub fn commit_list( id: &'static str, scroll_id: &'static str, @@ -205,7 +210,6 @@ pub fn commit_list( scroll_handle: UniformListScrollHandle, action: impl Fn(usize, &FileCommit, &App) -> Option + 'static, on_click: impl Fn(&FileCommit, &mut Window, &mut App) + Clone + 'static, - _cx: &App, ) -> AnyElement { let count = commits.len(); @@ -234,6 +238,64 @@ pub fn commit_list( .track_scroll(&scroll_handle) .size_full(), ) - .child(scroll_overlay(scroll_id, scroll_handle)) + .child(Scrollbar::vertical(scroll_id, scroll_handle)) + .into_any_element() +} + +/// One copyable commit summary row: id, subject, author, and age. +pub(crate) fn commit_row( + ix: usize, + commit: &FileCommit, + action: Option, + on_click: impl Fn(&mut Window, &mut gpui::App) + 'static, + cx: &gpui::App, +) -> gpui::AnyElement { + h_flex() + .id(ix) + .px_4() + .h(px(COMMIT_ROW_HEIGHT)) + .w_full() + .gap_3() + .border_b_1() + .border_color(cx.theme().colors.border) + .hover(|this| this.bg(cx.theme().colors.muted_hover)) + .child( + v_flex() + .flex_1() + .min_w_0() + .gap_1() + .justify_center() + .child( + h_flex() + .gap_2() + .overflow_hidden() + .child( + div() + .font_family(cx.theme().mono_font) + .text_sm() + .text_color(cx.theme().colors.muted_foreground) + .child(short_id(&commit.id)), + ) + .child( + div() + .flex_1() + .min_w_0() + .text_sm() + .text_ellipsis() + .whitespace_nowrap() + .child(commit.summary.clone()), + ), + ) + .child( + h_flex() + .gap_2() + .text_xs() + .text_color(cx.theme().colors.muted_foreground) + .child(commit.author.clone()) + .child(relative_time_secs(commit.time)), + ), + ) + .when_some(action, |row, action| row.child(action)) + .on_click(move |_, window, cx| on_click(window, cx)) .into_any_element() } diff --git a/crates/signed_app/src/shared/mod.rs b/crates/signed_app/src/shared/mod.rs index 4c39d39..c520504 100644 --- a/crates/signed_app/src/shared/mod.rs +++ b/crates/signed_app/src/shared/mod.rs @@ -5,7 +5,7 @@ use nostr::prelude::PublicKey; pub mod event_list; pub mod panels; pub mod progress; -pub mod tree; + pub mod widgets; /// Logs a discarded `Result` with its source location instead of dropping it silently. diff --git a/crates/signed_app/src/shared/panels.rs b/crates/signed_app/src/shared/panels.rs index 4912f36..4c55b45 100644 --- a/crates/signed_app/src/shared/panels.rs +++ b/crates/signed_app/src/shared/panels.rs @@ -1,13 +1,35 @@ -use std::sync::Arc; +use gpui::{App, AppContext, Entity, SharedString, WeakEntity, Window}; +use ui::layout::panel::{Panel, PanelSlot}; -use gpui::{App, Entity, SharedString, WeakEntity, Window}; -use ui::layout::panel::{Panel, PanelView}; +use crate::app::AppRoot; +use crate::shared::log_dropped; -use crate::workspace::Workspace; +/// Opens a panel in `slot`, reusing it when it is already open. +fn open_slot( + slot: PanelSlot, + workspace: &WeakEntity, + id: impl Into, + build: F, + window: &mut Window, + cx: &mut App, +) where + P: Panel + 'static, + F: Fn(&mut Window, &mut App) -> Entity

+ 'static, +{ + let result = workspace.update(cx, |workspace, cx| { + workspace + .panels() + .clone() + .update(cx, |panels, cx| panels.open(slot, id, build, window, cx)) + }); + if let Err(error) = result { + log::warn!("failed to open panel: {error}"); + } +} -/// Opens a repository in the main panel, reusing it when it is already cached. +/// Opens a repository in the main panel, reusing it when it is already open. pub fn open_primary( - workspace: &WeakEntity, + workspace: &WeakEntity, id: impl Into, build: F, window: &mut Window, @@ -16,30 +38,12 @@ pub fn open_primary( P: Panel + 'static, F: Fn(&mut Window, &mut App) -> Entity

+ 'static, { - let id = id.into(); - - if workspace - .read_with(cx, |workspace, _| workspace.has_main(&id)) - .unwrap_or(false) - { - if let Err(error) = workspace.update(cx, |workspace, cx| workspace.activate_main(&id, cx)) { - log::warn!("failed to activate repository {id}: {error}"); - } - return; - } - - let view: Arc = Arc::new(build(window, cx)); - - if let Err(error) = workspace.update(cx, |workspace, cx| { - workspace.show_main(id.clone(), view, cx) - }) { - log::warn!("failed to open repository {id}: {error}"); - } + open_slot(PanelSlot::Main, workspace, id, build, window, cx); } -/// Opens a detail panel beside the main panel, reusing it when it is already cached. +/// Opens a detail panel beside the main panel, reusing it when it is already open. pub fn open_detail( - workspace: &WeakEntity, + workspace: &WeakEntity, id: impl Into, build: F, window: &mut Window, @@ -48,24 +52,16 @@ pub fn open_detail( P: Panel + 'static, F: Fn(&mut Window, &mut App) -> Entity

+ 'static, { - let id = id.into(); + open_slot(PanelSlot::Split, workspace, id, build, window, cx); +} - if workspace - .read_with(cx, |workspace, _| workspace.has_detail(&id)) - .unwrap_or(false) - { - if let Err(error) = workspace.update(cx, |workspace, cx| workspace.activate_detail(&id, cx)) - { - log::warn!("failed to activate detail panel {id}: {error}"); - } - return; - } - - let view: Arc = Arc::new(build(window, cx)); - - if let Err(error) = workspace.update(cx, |workspace, cx| { - workspace.show_detail(id.clone(), view, cx) - }) { - log::warn!("failed to open detail panel {id}: {error}"); - } +/// Closes the detail panel open under `id`. +pub fn close_detail(workspace: &WeakEntity, id: &SharedString, cx: &mut impl AppContext) { + let result = workspace.update(cx, |workspace, cx| { + workspace + .panels() + .clone() + .update(cx, |panels, cx| panels.close(PanelSlot::Split, id, cx)) + }); + log_dropped(result); } diff --git a/crates/signed_app/src/shared/progress.rs b/crates/signed_app/src/shared/progress.rs index b633245..4a148af 100644 --- a/crates/signed_app/src/shared/progress.rs +++ b/crates/signed_app/src/shared/progress.rs @@ -1,15 +1,45 @@ use gpui::{ AnyElement, App, AsyncApp, Context, Entity, IntoElement as _, ParentElement as _, SharedString, - Styled as _, Subscription, Task, div, + Styled as _, Subscription, Task, WeakEntity, Window, div, }; use signed_core::RepoAddr; use signed_state::{Backend, BackendEvent, PushStepStatus}; +use ui::button::Button; use ui::common::{h_flex, v_flex}; use ui::dialog::DialogHandle; use ui::icons::{Icon, IconRole}; use ui::spinner::Spinner; use ui::theme::ActiveTheme as _; +use super::log_dropped; + +/// The dialog's submit button: loading/disabled while busy, closing over the dialog's submit. +pub fn dialog_submit_button( + id: &'static str, + label: impl Into, + icon: Option, + busy: bool, + this: &WeakEntity, + submit: F, +) -> Button +where + T: 'static, + F: Fn(&mut T, &mut Window, &mut Context) -> Result<(), anyhow::Error> + 'static, +{ + let mut button = Button::new(id).label(label); + if let Some(icon) = icon { + button = button.icon(Icon::named(icon)); + } + + let this = this.clone(); + button + .loading(busy) + .disabled(busy) + .on_click(move |_, window, cx| { + log_dropped(this.update(cx, |this, cx| submit(this, window, cx))); + }) +} + /// Progress of an async dialog action: a busy flag that disables the form and an error shown below it. #[derive(Debug, Default)] pub struct DialogProgress { diff --git a/crates/signed_app/src/shared/tree.rs b/crates/signed_app/src/shared/tree.rs deleted file mode 100644 index d1f38bf..0000000 --- a/crates/signed_app/src/shared/tree.rs +++ /dev/null @@ -1,188 +0,0 @@ -use std::collections::{HashMap, HashSet}; -use std::path::PathBuf; - -pub struct TreeItemSeed { - /// Path of the node, relative to the worktree root. - pub id: String, - pub label: String, - pub children: Vec, -} - -/// One visible row of the flattened tree. -#[derive(Clone)] -pub struct TreeRow { - pub id: String, - pub label: String, - pub depth: usize, - pub expandable: bool, - pub expanded: bool, -} - -/// Flattens the seeds into the rows a flat tree renders, honoring `expanded`. -pub fn flatten(seeds: &[TreeItemSeed], expanded: &HashSet) -> Vec { - fn push( - seed: &TreeItemSeed, - depth: usize, - expanded: &HashSet, - rows: &mut Vec, - ) { - let is_expanded = expanded.contains(&seed.id); - rows.push(TreeRow { - id: seed.id.clone(), - label: seed.label.clone(), - depth, - expandable: !seed.children.is_empty(), - expanded: is_expanded, - }); - - if is_expanded { - for child in &seed.children { - push(child, depth + 1, expanded, rows); - } - } - } - - let mut rows = Vec::new(); - for seed in seeds { - push(seed, 0, expanded, &mut rows); - } - rows -} - -/// Every folder id, for starting with the tree fully expanded. -pub fn collect_expanded(seeds: &[TreeItemSeed]) -> HashSet { - fn push(seed: &TreeItemSeed, expanded: &mut HashSet) { - if !seed.children.is_empty() { - expanded.insert(seed.id.clone()); - for child in &seed.children { - push(child, expanded); - } - } - } - - let mut expanded = HashSet::new(); - for seed in seeds { - push(seed, &mut expanded); - } - expanded -} - -/// Build nested tree items from a flat entry list sorted dirs-first. -pub fn build_tree_items(entries: &[PathBuf]) -> Vec { - // Node indices by full path, so parents resolve in constant time while inserting. - let mut index: HashMap = HashMap::new(); - let mut nodes: Vec<(String, String, Vec)> = Vec::new(); - let mut roots: Vec = Vec::new(); - - for entry in entries { - let mut parent: Option = None; - let mut path = String::new(); - for part in entry.components() { - let label = part.as_os_str().to_string_lossy().into_owned(); - path = if path.is_empty() { - label.clone() - } else { - format!("{path}/{label}") - }; - let ix = *index.entry(path.clone()).or_insert_with(|| { - let ix = nodes.len(); - nodes.push((path.clone(), label.clone(), Vec::new())); - match parent { - Some(parent) => nodes[parent].2.push(ix), - None => roots.push(ix), - } - ix - }); - parent = Some(ix); - } - } - - fn assemble(ix: usize, nodes: &[(String, String, Vec)]) -> TreeItemSeed { - let (id, label, children) = &nodes[ix]; - TreeItemSeed { - id: id.clone(), - label: label.clone(), - children: children - .iter() - .map(|child| assemble(*child, nodes)) - .collect(), - } - } - - roots.iter().map(|root| assemble(*root, &nodes)).collect() -} - -/// Sorted relative paths of a worktree snapshot. -pub fn sorted_worktree_paths(entries: &[PathBuf]) -> Vec { - let mut paths: Vec = entries - .iter() - .map(|path| path.to_string_lossy().into_owned()) - .collect(); - paths.sort(); - paths -} - -#[cfg(test)] -mod tests { - use super::*; - - fn ids(rows: &[TreeRow]) -> Vec<(&str, usize)> { - rows.iter() - .map(|row| (row.id.as_str(), row.depth)) - .collect() - } - - #[test] - fn collapsed_folders_hide_children() { - let seeds = build_tree_items(&[ - PathBuf::from("src"), - PathBuf::from("src/lib.rs"), - PathBuf::from("README.md"), - ]); - - let rows = flatten(&seeds, &HashSet::new()); - - assert_eq!(ids(&rows), vec![("src", 0), ("README.md", 0)]); - assert!(rows[0].expandable); - assert!(!rows[0].expanded); - } - - #[test] - fn expanding_a_folder_shows_children_in_order() { - let seeds = build_tree_items(&[ - PathBuf::from("src"), - PathBuf::from("src/lib.rs"), - PathBuf::from("src/views/mod.rs"), - PathBuf::from("README.md"), - ]); - let expanded = HashSet::from(["src".to_owned(), "src/views".to_owned()]); - - let rows = flatten(&seeds, &expanded); - - assert_eq!( - ids(&rows), - vec![ - ("src", 0), - ("src/lib.rs", 1), - ("src/views", 1), - ("src/views/mod.rs", 2), - ("README.md", 0), - ] - ); - } - - #[test] - fn indices_map_to_row_ids() { - let seeds = build_tree_items(&[ - PathBuf::from("docs"), - PathBuf::from("docs/guide.md"), - PathBuf::from("README.md"), - ]); - let expanded = HashSet::from(["docs".to_owned()]); - let rows = flatten(&seeds, &expanded); - - assert_eq!(rows[0].id, "docs"); - assert_eq!(rows[1].id, "docs/guide.md"); - assert_eq!(rows[2].id, "README.md"); - } -} diff --git a/crates/signed_app/src/shared/widgets.rs b/crates/signed_app/src/shared/widgets.rs index 8783a6f..0014432 100644 --- a/crates/signed_app/src/shared/widgets.rs +++ b/crates/signed_app/src/shared/widgets.rs @@ -1,15 +1,6 @@ -use gpui::{ - AnyElement, App, ElementId, IntoElement, ParentElement as _, SharedString, Styled as _, div, -}; use signed_core::RepoStatus; use ui::badge::{Badge, BadgeVariant}; -use ui::clipboard::ClipboardButton; -use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex}; -use ui::empty_state::EmptyState; use ui::icons::{Icon, IconRole}; -use ui::scrollbar::{Scrollbar, ScrollbarHandle}; -use ui::spinner::Spinner; -use ui::theme::ActiveTheme as _; use ui::tooltip::Tooltip; /// The status pill shown on issue and pull-request rows. @@ -26,75 +17,3 @@ pub fn status_badge(status: RepoStatus) -> Badge { .icon(Icon::named(icon)) .tooltip(Tooltip::text(label)) } - -/// A centered empty-state message filling the available space. -pub fn empty_state(message: impl Into) -> AnyElement { - let message = message.into(); - v_flex() - .size_full() - .items_center() - .justify_center() - .child(EmptyState::new(message)) - .into_any_element() -} - -/// A centered spinner filling the available space. -pub fn centered_spinner(id: impl Into) -> AnyElement { - v_flex() - .size_full() - .items_center() - .justify_center() - .child(Spinner::new(id)) - .into_any_element() -} - -/// The vertical scrollbar pinned over a uniform list's full extent. -pub fn scroll_overlay(id: I, handle: H) -> AnyElement -where - I: Into, - H: ScrollbarHandle, -{ - div() - .absolute() - .top_0() - .left_0() - .right_0() - .bottom_0() - .child(Scrollbar::vertical(id, handle)) - .into_any_element() -} - -/// One copyable clone command with its text visible next to the copy icon. -pub fn clone_row(id: SharedString, command: SharedString, cx: &App) -> AnyElement { - h_flex() - .h_8() - .px_2() - .gap_2() - .min_w_0() - .bg(cx.theme().colors.secondary) - .rounded(cx.theme().radius.control) - .text_color(cx.theme().colors.secondary_foreground) - .child( - div() - .flex_1() - .min_w_0() - .overflow_hidden() - .whitespace_nowrap() - .text_ellipsis() - .font_family(cx.theme().mono_font) - .text_xs() - .child(command.clone()), - ) - .child(ClipboardButton::new(id, command).xsmall()) - .into_any_element() -} - -/// A one-line muted label used by section headers. -pub fn section_label(text: impl Into, cx: &App) -> AnyElement { - div() - .text_xs() - .font_medium() - .text_color(cx.theme().colors.muted_foreground) - .child(text.into()) - .into_any_element() -} diff --git a/crates/signed_app/src/titlebar/mod.rs b/crates/signed_app/src/titlebar/mod.rs index bc3ad64..0a1ba1d 100644 --- a/crates/signed_app/src/titlebar/mod.rs +++ b/crates/signed_app/src/titlebar/mod.rs @@ -2,7 +2,7 @@ use std::rc::Rc; use std::sync::Arc; use gpui::{ - AnyElement, AnyView, App, AppContext as _, Context, Entity, IntoElement, KeyBinding, + AnyElement, App, AppContext as _, Context, Entity, IntoElement, KeyBinding, KeyBindingContextPredicate, ParentElement as _, SharedString, Subscription, WeakEntity, Window, }; use metadata::{Profile, ProfileDirectory}; @@ -15,17 +15,16 @@ use ui::avatar::Avatar; use ui::button::{Button, ButtonVariant}; use ui::command_palette::{Command, CommandPalette, CommandPaletteState}; use ui::icons::{Icon, IconRole}; -use ui::layout::panel::PanelView; +use ui::layout::root::RootContext as _; use ui::menu::{Menu, MenuItem}; -use ui::tabs::{Tab, Tabs, TabsVariant}; use ui::tooltip::Tooltip; +use crate::app::AppRoot; use crate::explore::ExploreView; use crate::identity::exit::ExitDialog; use crate::repo::{RepoDetailView, actions, dialogs}; use crate::settings::SettingsDialog; use crate::shared::{log_dropped, panels}; -use crate::workspace::Workspace; mod repository_switcher; @@ -56,83 +55,33 @@ pub(crate) struct SwitchRepository { #[action(namespace = signed, no_json)] pub(crate) struct CreateRepository; -pub(crate) fn bind_repository_shortcuts(cx: &mut App) { - let context = match KeyBindingContextPredicate::parse(REPOSITORY_KEY_CONTEXT) { - Ok(context) => Some(Rc::new(context)), - Err(error) => { - log::error!("failed to parse repository key context: {error}"); - return; - } - }; - - let bindings = REPOSITORY_KEYSTROKES - .into_iter() - .enumerate() - .map(|(index, keystroke)| { - KeyBinding::load( - keystroke, - Box::new(SwitchRepository { index }), - context.clone(), - false, - None, - cx, - ) - }) - .chain(std::iter::once(KeyBinding::load( - CREATE_KEYSTROKE, - Box::new(CreateRepository), - context.clone(), - false, - None, - cx, - ))) - .collect::, _>>(); - - let bindings = match bindings { - Ok(bindings) => bindings, - Err(error) => { - log::error!("failed to parse repository shortcut keystrokes: {error}"); - return; - } - }; - - cx.bind_keys(bindings); -} - pub struct TitlebarView { weak: WeakEntity, - workspace: WeakEntity, + app: WeakEntity, /// User's announced repositories. announcements: Arc>, /// Local repositories found by the scan that are not announced yet. local_repos: Arc>, /// Profiles rendered by the repository switcher. directory: Entity, - /// The command palette opened from the titlebar. - palette: Entity, repository_switcher: Entity, - settings: Option>, - exit: Option>, - create: Option>, user_menu_open: bool, _subscriptions: Vec, } impl TitlebarView { - pub fn new( - workspace: WeakEntity, - window: &mut Window, - cx: &mut Context, - ) -> Self { + pub fn new(app: WeakEntity, window: &mut Window, cx: &mut Context) -> Self { let backend = Backend::global(cx); let repos = RepoListStore::global(cx); let local = LocalReposStore::global(cx); - - let weak = cx.entity().downgrade(); - let palette = Self::new_palette(weak.clone(), window, cx); let directory = ProfileDirectory::new(cx); let entity = cx.entity(); + let weak = entity.downgrade(); + + let palette = Self::new_palette(weak.clone(), window, cx); + cx.open_palette(palette); + let mut subscriptions = Vec::new(); let repository_switcher = cx.new(|cx| { @@ -195,15 +144,11 @@ impl TitlebarView { Self { weak: cx.entity().downgrade(), - workspace, + app, announcements: Arc::new(Vec::new()), local_repos: Arc::new(Vec::new()), directory, - palette, repository_switcher, - settings: None, - exit: None, - create: None, user_menu_open: false, _subscriptions: subscriptions, } @@ -258,10 +203,6 @@ impl TitlebarView { ] } - pub fn palette(&self) -> Entity { - self.palette.clone() - } - fn refresh(&mut self, cx: &mut Context) -> bool { let backend = Backend::global(cx); let user = backend.read(cx).current_user(); @@ -351,57 +292,6 @@ impl TitlebarView { self.repository_switcher.clone() } - /// Tabs for the repositories opened in the main panel. - pub fn render_repo_tabs(&self, workspace: &Workspace) -> Option { - let open = workspace.open_mains(); - - if open.is_empty() { - return None; - } - - let tabs: Vec<_> = open - .iter() - .map(|id| (id.clone(), workspace.main_view(id))) - .collect(); - - let selected = workspace - .active_main_id() - .and_then(|id| open.iter().position(|open_id| open_id == id)) - .unwrap_or(usize::MAX); - - let change_workspace = self.workspace.clone(); - let close_workspace = self.workspace.clone(); - let open_for_change = open.to_vec(); - - Some( - Tabs::new("signed-repo-tabs") - .variant(TabsVariant::Titlebar) - .overflow_scroll(true) - .selected(selected) - .tabs(move |_, cx| { - tabs.iter() - .map(|(id, view)| match view { - Some(view) => view.tab(id.clone().into(), cx).closeable(true), - None => Tab::new(id.clone(), id.clone()).closeable(true), - }) - .collect() - }) - .on_change(move |index, _, cx| { - let Some(id) = open_for_change.get(index).cloned() else { - return; - }; - log_dropped(change_workspace.update(cx, |workspace, cx| { - workspace.activate_main(&id, cx); - })); - }) - .on_close(move |index, _, cx| { - log_dropped(close_workspace.update(cx, |workspace, cx| { - workspace.close_main_at(index, cx); - })); - }), - ) - } - pub(crate) fn activate_shortcut( &mut self, index: usize, @@ -420,37 +310,27 @@ impl TitlebarView { } fn open_settings(&mut self, cx: &mut Context) { - self.settings = Some(SettingsDialog::new(cx)); + let dialog = SettingsDialog::new(cx); + cx.open_dialog(dialog); cx.notify(); } fn open_exit(&mut self, cx: &mut Context) { - self.exit = Some(ExitDialog::new(cx)); + let dialog = ExitDialog::new(cx); + cx.open_dialog(dialog); cx.notify(); } fn open_create(&mut self, window: &mut Window, cx: &mut Context) { - let view = dialogs::create::CreateRepoDialog::new(self.workspace.clone(), window, cx); - self.create = Some(view); + let view = dialogs::create::CreateRepoDialog::new(self.app.clone(), window, cx); + cx.open_dialog(view); cx.notify(); } - /// The dialogs this titlebar opens, rendered at the window root. - pub fn dialogs(&self) -> Vec { - [ - self.settings.clone().map(Into::into), - self.exit.clone().map(Into::into), - self.create.clone().map(Into::into), - ] - .into_iter() - .flatten() - .collect() - } - fn activate(&mut self, index: usize, window: &mut Window, cx: &mut Context) { if let Some(announcement) = self.announcements.get(index) { let addr = announcement.addr(); - actions::open_repo_panel(&self.workspace, &addr, Some(announcement), window, cx); + actions::open_repo_panel(&self.app, &addr, Some(announcement), window, cx); return; } @@ -479,7 +359,7 @@ impl TitlebarView { if let Some(announcement) = announcement { let id = SharedString::from(format!("repo:{}", announcement.addr())); - let workspace = self.workspace.clone(); + let workspace = self.app.clone(); let workspace_for_build = workspace.clone(); panels::open_primary( &workspace, @@ -502,7 +382,7 @@ impl TitlebarView { } let id = SharedString::from(format!("repo-local:{}", path.display())); - let workspace = self.workspace.clone(); + let workspace = self.app.clone(); let workspace_for_build = workspace.clone(); panels::open_primary( @@ -534,7 +414,7 @@ impl TitlebarView { } pub fn render_explore(&self) -> AnyElement { - let workspace = self.workspace.clone(); + let workspace = self.app.clone(); Button::new("open-explore") .icon(IconRole::Grid) @@ -626,3 +506,46 @@ fn local_key(entry: &ResolvedLocalRepo) -> SharedString { None => SharedString::from(format!("repo-local:{}", entry.path.display())), } } + +pub(crate) fn bind_repository_shortcuts(cx: &mut App) { + let context = match KeyBindingContextPredicate::parse(REPOSITORY_KEY_CONTEXT) { + Ok(context) => Some(Rc::new(context)), + Err(error) => { + log::error!("failed to parse repository key context: {error}"); + return; + } + }; + + let bindings = REPOSITORY_KEYSTROKES + .into_iter() + .enumerate() + .map(|(index, keystroke)| { + KeyBinding::load( + keystroke, + Box::new(SwitchRepository { index }), + context.clone(), + false, + None, + cx, + ) + }) + .chain(std::iter::once(KeyBinding::load( + CREATE_KEYSTROKE, + Box::new(CreateRepository), + context.clone(), + false, + None, + cx, + ))) + .collect::, _>>(); + + let bindings = match bindings { + Ok(bindings) => bindings, + Err(error) => { + log::error!("failed to parse repository shortcut keystrokes: {error}"); + return; + } + }; + + cx.bind_keys(bindings); +} diff --git a/crates/signed_app/src/titlebar/repository_switcher.rs b/crates/signed_app/src/titlebar/repository_switcher.rs index 4190776..99a1721 100644 --- a/crates/signed_app/src/titlebar/repository_switcher.rs +++ b/crates/signed_app/src/titlebar/repository_switcher.rs @@ -165,12 +165,6 @@ impl Render for RepositorySwitcher { let list_weak = row_weak.clone(); let list_on_open = on_open.clone(); let list_scroll_handle = scroll_handle.clone(); - let create_hint = Kbd::binding_for_action( - &CreateRepository, - Some(REPOSITORY_KEY_CONTEXT), - window, - ); - v_flex() .w(px(380.)) .p_2() @@ -265,7 +259,14 @@ impl Render for RepositorySwitcher { .full_width(true) .icon(Icon::named(IconRole::CirclePlus)) .child(div().flex_1().child("Create Repository")) - .when_some(create_hint, |button, hint| button.child(hint)) + .when_some( + Kbd::binding_for_action( + &CreateRepository, + Some(REPOSITORY_KEY_CONTEXT), + window, + ), + |button, hint| button.child(hint), + ) .on_click(move |_, window, cx| { log_dropped(create_weak.update(cx, |this, cx| { this.close(cx); diff --git a/crates/signed_app/src/workspace.rs b/crates/signed_app/src/workspace.rs deleted file mode 100644 index d23ef91..0000000 --- a/crates/signed_app/src/workspace.rs +++ /dev/null @@ -1,243 +0,0 @@ -use std::collections::HashMap; -use std::sync::Arc; - -use gpui::prelude::FluentBuilder as _; -use gpui::{ - App, Context, IntoElement, ParentElement as _, Render, SharedString, Styled as _, Window, div, -}; -use ui::common::v_flex; -use ui::layout::panel::{Panel, PanelView}; -use ui::tabs::{Tab, Tabs, TabsVariant}; - -use crate::shared::log_dropped; - -/// The repository shown in the main panel and the detail panels opened beside it. -#[derive(Default)] -pub struct Workspace { - main: Option, - main_order: Vec, - main_views: HashMap>, - details: Vec, - detail_views: HashMap>, - active_detail: Option, -} - -impl Workspace { - pub fn new() -> Self { - Self::default() - } - - pub fn active_main(&self) -> Option> { - self.main - .as_ref() - .and_then(|id| self.main_views.get(id)) - .cloned() - } - - pub fn active_main_id(&self) -> Option<&SharedString> { - self.main.as_ref() - } - - pub fn open_mains(&self) -> &[SharedString] { - &self.main_order - } - - /// The open main panel with this id. - pub fn main_view(&self, id: &SharedString) -> Option> { - self.main_views.get(id).cloned() - } - - pub fn active_detail(&self) -> Option> { - self.active_detail - .as_ref() - .and_then(|id| self.detail_views.get(id)) - .cloned() - } - - pub fn has_main(&self, id: &SharedString) -> bool { - self.main_views.contains_key(id) - } - - pub fn has_details(&self) -> bool { - !self.details.is_empty() - } - - pub fn has_detail(&self, id: &SharedString) -> bool { - self.detail_views.contains_key(id) - } - - pub fn show_main( - &mut self, - id: SharedString, - view: Arc, - cx: &mut Context, - ) { - if self.main.as_ref() != Some(&id) { - self.clear_details(); - } - if !self.main_views.contains_key(&id) { - self.main_order.push(id.clone()); - } - self.main_views.insert(id.clone(), view); - self.main = Some(id); - cx.notify(); - } - - pub fn activate_main(&mut self, id: &SharedString, cx: &mut Context) { - if self.main.as_ref() != Some(id) { - self.clear_details(); - } - self.main = Some(id.clone()); - cx.notify(); - } - - pub fn activate_detail(&mut self, id: &SharedString, cx: &mut Context) { - if self.detail_views.contains_key(id) { - self.active_detail = Some(id.clone()); - cx.notify(); - } - } - - pub fn show_detail( - &mut self, - id: SharedString, - view: Arc, - cx: &mut Context, - ) { - if !self.details.contains(&id) { - self.details.push(id.clone()); - } - self.detail_views.insert(id.clone(), view); - self.active_detail = Some(id); - cx.notify(); - } - - pub fn close_detail(&mut self, id: &SharedString, cx: &mut Context) { - let Some(index) = self.details.iter().position(|open| open == id) else { - return; - }; - self.close_detail_at(index, cx); - } - - pub fn close_main_at(&mut self, index: usize, cx: &mut Context) { - if index >= self.main_order.len() { - return; - } - - let id = self.main_order.remove(index); - self.main_views.remove(&id); - - if self.main.as_ref() == Some(&id) { - self.main = self - .main_order - .get(index) - .or_else(|| { - index - .checked_sub(1) - .and_then(|prev| self.main_order.get(prev)) - }) - .cloned(); - self.clear_details(); - } - - cx.notify(); - } - - pub fn clear(&mut self, cx: &mut Context) { - self.main = None; - self.main_order.clear(); - self.main_views.clear(); - self.clear_details(); - cx.notify(); - } - - fn clear_details(&mut self) { - self.details.clear(); - self.detail_views.clear(); - self.active_detail = None; - } - - fn close_detail_at(&mut self, index: usize, cx: &mut Context) { - if index >= self.details.len() { - return; - } - - let id = self.details.remove(index); - self.detail_views.remove(&id); - - if self.active_detail.as_ref() == Some(&id) { - self.active_detail = self - .details - .get(index) - .or_else(|| index.checked_sub(1).and_then(|prev| self.details.get(prev))) - .cloned(); - } - - cx.notify(); - } - - fn activate_detail_at(&mut self, index: usize, cx: &mut Context) { - let Some(id) = self.details.get(index) else { - return; - }; - self.active_detail = Some(id.clone()); - cx.notify(); - } -} - -impl Panel for Workspace { - fn title(&self, _cx: &App) -> SharedString { - SharedString::from("Workspace") - } -} - -impl Render for Workspace { - fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { - let selected = self - .active_detail - .as_ref() - .and_then(|active| self.details.iter().position(|id| id == active)) - .unwrap_or(usize::MAX); - - let details: Vec<_> = self - .details - .iter() - .map(|id| (id.clone(), self.detail_views.get(id).cloned())) - .collect(); - - let weak = cx.entity().downgrade(); - let body = self.active_detail().map(|view| view.view()); - - v_flex() - .size_full() - .gap_2() - .when(self.details.len() > 1, |this| { - let close_weak = weak.clone(); - let tabs = Tabs::new("signed-detail-tabs") - .variant(TabsVariant::Pill) - .overflow_scroll(true) - .selected(selected) - .tabs(move |_, cx| { - details - .iter() - .map(|(id, view)| match view { - Some(view) => view.tab(id.clone().into(), cx).closeable(true), - None => Tab::new(id.clone(), id.clone()).closeable(true), - }) - .collect() - }) - .on_change(move |index, _, cx| { - log_dropped(weak.update(cx, |workspace, cx| { - workspace.activate_detail_at(index, cx); - })); - }) - .on_close(move |index, _, cx| { - log_dropped(close_weak.update(cx, |workspace, cx| { - workspace.close_detail_at(index, cx); - })); - }); - this.child(tabs) - }) - .child(div().flex_1().min_h_0().w_full().children(body)) - } -} diff --git a/crates/ui/src/components/alert.rs b/crates/ui/src/components/alert.rs index 13af3f0..6f4ce9f 100644 --- a/crates/ui/src/components/alert.rs +++ b/crates/ui/src/components/alert.rs @@ -269,7 +269,7 @@ impl RenderOnce for Alert { /// One pushed alert, with its identity in the stack. #[derive(Clone)] -pub struct AlertEntry { +struct AlertEntry { /// The id [`Alerts::push`] returned. pub id: usize, /// The alert as pushed. @@ -338,14 +338,9 @@ impl Alerts { } /// The stacked alerts, oldest first. - pub fn entries(&self) -> &[AlertEntry] { + fn entries(&self) -> &[AlertEntry] { &self.entries } - - /// How many alerts are stacked. - pub fn count(&self) -> usize { - self.entries.len() - } } /// The floating stack of pushed alerts, topmost right. diff --git a/crates/ui/src/components/avatar.rs b/crates/ui/src/components/avatar.rs index 1c2eb80..22279da 100644 --- a/crates/ui/src/components/avatar.rs +++ b/crates/ui/src/components/avatar.rs @@ -14,6 +14,7 @@ use std::collections::HashMap; use std::fmt::Display; +use gpui::prelude::FluentBuilder as _; use gpui::{ App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, div, @@ -140,6 +141,78 @@ impl RenderOnce for Avatar { } } +/// An avatar with the display name beside it. +#[derive(IntoElement)] +#[must_use] +pub struct IdentityRow { + id: SharedString, + name: SharedString, + picture: Option, + size: Size, + truncate: bool, + style: StyleRefinement, +} + +impl IdentityRow { + /// Creates the row for `id` (the pixel-fallback seed) showing `name`. + pub fn new(id: ID, name: N, picture: Option) -> Self + where + ID: Into, + N: Into, + { + Self { + id: id.into(), + name: name.into(), + picture, + size: Size::default(), + truncate: false, + style: StyleRefinement::default(), + } + } + + /// Truncates the name to one line inside the available width. + pub fn truncate(mut self) -> Self { + self.truncate = true; + self + } +} + +impl Sizable for IdentityRow { + fn apply_size(&mut self, size: Size) { + self.size = size; + } +} + +impl gpui::Styled for IdentityRow { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for IdentityRow { + fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + h_flex() + .refine_style(&self.style) + .child( + Avatar::new(self.id.clone()) + .name(self.name.clone()) + .picture(self.picture) + .with_size(self.size), + ) + .child( + div() + .when(self.truncate, |name| { + name.flex_1() + .min_w_0() + .overflow_hidden() + .whitespace_nowrap() + .text_ellipsis() + }) + .child(self.name), + ) + } +} + /// A deterministic, offline pixel-art avatar. #[derive(IntoElement)] struct PixelAvatar { @@ -218,6 +291,28 @@ thread_local! { std::cell::RefCell::new(HashMap::new()); } +/// Tiny xorshift64* PRNG for deriving the pattern from the seed. +struct PixelRng(u64); + +impl PixelRng { + fn new(seed: u64) -> Self { + Self(seed.max(1)) + } + + fn next(&mut self) -> u64 { + let mut x = self.0; + x ^= x >> 12; + x ^= x << 25; + x ^= x >> 27; + self.0 = x; + x.wrapping_mul(0x2545_f491_4f6c_dd1d) + } + + fn chance(&mut self, probability: f32) -> bool { + self.next() as f32 / (u64::MAX as f32) < probability + } +} + fn pattern(seed: u64) -> [u8; GRID_SIZE * GRID_SIZE] { let cached = PATTERN_CACHE.with(|cache| cache.borrow().get(&seed).copied()); if let Some(cached) = cached { @@ -284,25 +379,3 @@ fn fnv1a(bytes: &[u8]) -> u64 { } hash } - -/// Tiny xorshift64* PRNG for deriving the pattern from the seed. -struct PixelRng(u64); - -impl PixelRng { - fn new(seed: u64) -> Self { - Self(seed.max(1)) - } - - fn next(&mut self) -> u64 { - let mut x = self.0; - x ^= x >> 12; - x ^= x << 25; - x ^= x >> 27; - self.0 = x; - x.wrapping_mul(0x2545_f491_4f6c_dd1d) - } - - fn chance(&mut self, probability: f32) -> bool { - self.next() as f32 / (u64::MAX as f32) < probability - } -} diff --git a/crates/ui/src/components/badge.rs b/crates/ui/src/components/badge.rs index 30b44d7..4a9d8f4 100644 --- a/crates/ui/src/components/badge.rs +++ b/crates/ui/src/components/badge.rs @@ -153,7 +153,7 @@ impl RenderOnce for Badge { let size = self.size; let (background, foreground, border) = self.variant.tokens(theme); - let badge = h_flex() + h_flex() .id(self.id.clone()) .flex_none() .justify_center() @@ -163,14 +163,12 @@ impl RenderOnce for Badge { .border_color(border) .bg(background) .text_color(foreground) - .control_caption_text(size); - let badge = match size { - Size::XSmall | Size::Small => badge.h_5().min_w_5().px_1(), - Size::Medium => badge.h_6().min_w_6().px_1p5(), - Size::Large => badge.h_7().min_w_7().px_2(), - }; - - badge + .control_caption_text(size) + .map(|badge| match size { + Size::XSmall | Size::Small => badge.h_5().min_w_5().px_1(), + Size::Medium => badge.h_6().min_w_6().px_1p5(), + Size::Large => badge.h_7().min_w_7().px_2(), + }) .when_some(self.icon, |badge, icon| { badge.child(icon.size(size.dense_icon_rems()).color(foreground)) }) diff --git a/crates/ui/src/components/button.rs b/crates/ui/src/components/button.rs index 32969bc..b4515cc 100644 --- a/crates/ui/src/components/button.rs +++ b/crates/ui/src/components/button.rs @@ -46,18 +46,6 @@ pub enum ButtonVariant { Destructive, } -/// The variant colors a button paints with, resolved from the active theme. -pub struct ButtonChrome { - /// The resting background, `None` for unpainted variants like `Ghost`. - pub background: Option, - pub foreground: Hsla, - pub hover: Hsla, - pub pressed: Hsla, - pub border: Hsla, - pub hover_border: Hsla, - pub pressed_border: Hsla, -} - impl ButtonVariant { /// The variant's colors from the active theme. pub fn chrome(&self, cx: &App) -> ButtonChrome { @@ -117,6 +105,18 @@ pub enum ButtonSide { Right, } +/// The variant colors a button paints with, resolved from the active theme. +pub struct ButtonChrome { + /// The resting background, `None` for unpainted variants like `Ghost`. + pub background: Option, + pub foreground: Hsla, + pub hover: Hsla, + pub pressed: Hsla, + pub border: Hsla, + pub hover_border: Hsla, + pub pressed_border: Hsla, +} + /// A push button that renders a label, an icon, or both, and fires /// [`Button::on_click`] on click, Enter, or Space. #[derive(IntoElement)] diff --git a/crates/ui/src/components/clipboard.rs b/crates/ui/src/components/clipboard.rs index 54e32c2..a7966ff 100644 --- a/crates/ui/src/components/clipboard.rs +++ b/crates/ui/src/components/clipboard.rs @@ -15,21 +15,20 @@ use std::time::Duration; use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyView, App, ClipboardItem, ElementId, Entity, IntoElement, RenderOnce, SharedString, - StyleRefinement, Task, Window, + AnyView, App, ClipboardItem, ElementId, Entity, IntoElement, ParentElement as _, RenderOnce, + SharedString, StyleRefinement, Styled as _, Task, Window, div, }; use crate::components::button::{Button, ButtonVariant}; -use crate::components::common::{ResultLogErr as _, Sizable, StyledExt as _}; +use crate::components::common::{ResultLogErr as _, Sizable, StyledExt as _, h_flex}; use crate::icons::IconRole; -use crate::theme::Size; +use crate::theme::{ActiveTheme as _, Size}; /// How long the check mark shows before reverting to the copy icon. -pub const COPIED_DURATION: Duration = Duration::from_secs(1); +const COPIED_DURATION: Duration = Duration::from_secs(1); /// The tooltip view builder gpui's `.tooltip(...)` expects. type TooltipBuilder = Rc AnyView>; - /// Runs after the value lands on the clipboard. type CopiedHandler = Box; @@ -184,3 +183,68 @@ impl RenderOnce for ClipboardButton { }) } } + +/// A copyable value shown as a boxed row with a trailing copy button. +#[derive(IntoElement)] +#[must_use] +pub struct CopyRow { + id: SharedString, + value: SharedString, + large_text: bool, +} + +impl CopyRow { + /// Monospace `value` in a secondary-background row (the clone-command look). + pub fn new(id: ID, value: V) -> Self + where + ID: Into, + V: Into, + { + Self { + id: id.into(), + value: value.into(), + large_text: false, + } + } + + /// Base-size label and default-size copy button (the about-dialog list look). + pub fn text_base(mut self) -> Self { + self.large_text = true; + self + } +} + +impl RenderOnce for CopyRow { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + + h_flex() + .h_8() + .px_2() + .gap_2() + .min_w_0() + .bg(theme.colors.secondary) + .rounded(theme.radius.control) + .text_color(theme.colors.secondary_foreground) + .child( + div() + .flex_1() + .min_w_0() + .overflow_hidden() + .whitespace_nowrap() + .text_ellipsis() + .when(self.large_text, |text| text.text_base()) + .when(!self.large_text, |text| { + text.font_family(theme.mono_font).text_xs() + }) + .child(self.value.clone()), + ) + .child(if self.large_text { + ClipboardButton::new(self.id, self.value).into_any_element() + } else { + ClipboardButton::new(self.id, self.value) + .xsmall() + .into_any_element() + }) + } +} diff --git a/crates/ui/src/components/code.rs b/crates/ui/src/components/code.rs index f256639..f7e01b4 100644 --- a/crates/ui/src/components/code.rs +++ b/crates/ui/src/components/code.rs @@ -47,34 +47,13 @@ actions!(code_view, [Copy]); /// The key context the code view declares while it holds focus. pub const CODE_VIEW_CONTEXT: &str = "CodeView"; -/// Binds the code view's copy chord: cmd-c on macOS, ctrl-c elsewhere. -/// -/// Call once at startup. Without it, selection copy has no key. -pub fn bind_code_view_keys(cx: &mut App) { - let context = match KeyBindingContextPredicate::parse(CODE_VIEW_CONTEXT) { - Ok(context) => Some(Rc::new(context)), - Err(error) => { - log::error!("failed to parse code view key context: {error}"); - return; - } - }; - let binding = match KeyBinding::load("secondary-c", Box::new(Copy), context, false, None, cx) { - Ok(binding) => binding, - Err(error) => { - log::error!("failed to parse code view copy keystroke: {error}"); - return; - } - }; - cx.bind_keys([binding]); -} - /// A point in the source, in lines and characters (not bytes). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct SelectionPoint { +struct SelectionPoint { /// The zero-based line index. - pub row: usize, + row: usize, /// The zero-based character offset within the line. - pub col: usize, + col: usize, } impl SelectionPoint { @@ -235,24 +214,8 @@ impl CodeViewState { self.active_line } - /// Selects a range, endpoints in lines and characters. - pub fn select_range( - &mut self, - start: SelectionPoint, - end: SelectionPoint, - cx: &mut Context, - ) { - self.selection = if start.earlier_than(&end) { - Some((start, end)) - } else { - Some((end, start)) - }; - self.selecting = false; - cx.notify(); - } - /// The selected range, endpoints in document order, when there is one. - pub fn selection(&self) -> Option<(SelectionPoint, SelectionPoint)> { + fn selection(&self) -> Option<(SelectionPoint, SelectionPoint)> { self.selection.map(|(anchor, head)| { if anchor.earlier_than(&head) { (anchor, head) @@ -263,7 +226,7 @@ impl CodeViewState { } /// The selected text, or `None` when nothing is selected. - pub fn selected_text(&self) -> Option { + fn selected_text(&self) -> Option { let (start, end) = self.selection()?; let lines: Vec<&str> = self.source.split('\n').collect(); @@ -325,6 +288,128 @@ impl CodeViewState { SelectionPoint { row, col } } + + #[allow(clippy::too_many_arguments)] + fn render_row( + &self, + id: &ElementId, + line_ix: usize, + active: bool, + selection: Option<(SelectionPoint, SelectionPoint)>, + mono_font: &'static str, + colors: ColorTokens, + ramps: Ramps, + text_size: Pixels, + line_height: Pixels, + cx: &App, + ) -> gpui::AnyElement { + let layout = self.line_layouts.get(line_ix); + let text = layout.map_or("", |layout| layout.text.as_str()); + let roles = layout.map_or(&[][..], |layout| layout.roles.as_slice()); + let char_count = text.chars().count(); + + let mut selected = vec![false; char_count]; + + if let Some((start, end)) = selection + && line_ix >= start.row + && line_ix <= end.row + { + let start_col = if line_ix == start.row { + start.col.min(char_count) + } else { + 0 + }; + + let end_col = if line_ix == end.row { + end.col.min(char_count) + } else { + char_count + }; + + for slot in &mut selected[start_col..end_col] { + *slot = true; + } + } + + let mut highlights: Vec<(std::ops::Range, HighlightStyle)> = Vec::new(); + let mut run_start = 0usize; + let mut run_end = 0usize; + let mut run_role = Role::Text; + let mut run_selected = false; + + for (char_ix, (byte_ix, character)) in text.char_indices().enumerate() { + let fresh = + char_ix == 0 || roles[char_ix] != run_role || selected[char_ix] != run_selected; + if fresh { + if char_ix > 0 { + highlights.push(( + run_start..run_end, + run_role.run_style(run_selected, colors, ramps), + )); + } + run_start = byte_ix; + run_role = roles[char_ix]; + run_selected = selected[char_ix]; + } + run_end = byte_ix + character.len_utf8(); + } + + if run_end > run_start || !text.is_empty() { + highlights.push(( + run_start..run_end, + run_role.run_style(run_selected, colors, ramps), + )); + } + + let style = TextStyle { + color: colors.foreground, + font_family: SharedString::from(mono_font), + font_size: text_size.into(), + line_height: line_height.into(), + white_space: gpui::WhiteSpace::Nowrap, + ..Default::default() + }; + + div() + .debug_selector(move || format!("{id}-row-{line_ix}")) + .id(("code-row", line_ix)) + .w_full() + .text_xs() + .h(line_height) + .flex() + .items_center() + .overflow_hidden() + .when(active, |row| { + row.bg(Hsla { + a: colors.muted.a * WASH_ALPHA_SOFT, + ..colors.muted + }) + }) + .child( + gutter_cell( + cx, + if active { + colors.foreground + } else { + colors.muted_foreground + }, + format!("{}", line_ix + 1), + ) + .justify_end() + .pr_2() + .whitespace_nowrap(), + ) + .child( + div() + .flex_1() + .min_w_0() + .ml_4() + .overflow_hidden() + .whitespace_nowrap() + .child(gpui::StyledText::new(text).with_default_highlights(&style, highlights)), + ) + .into_any_element() + } } impl gpui::Focusable for CodeViewState { @@ -352,37 +437,6 @@ impl Render for CodeViewState { let bounds_cell: std::rc::Rc>>> = std::rc::Rc::new(std::cell::RefCell::new(None)); - let rows = uniform_list((id.clone(), "rows"), line_count, { - let id = id.clone(); - let state = state.clone(); - move |range, _window, cx| { - let code = state.read(cx); - let active_line = code.active_line; - let theme = cx.theme(); - - range - .map(|line_ix| { - render_row( - code, - &id, - line_ix, - active_line == Some(line_ix), - selection, - theme.mono_font, - theme.colors, - theme.ramps, - text_size, - line_height, - cx, - ) - }) - .collect() - } - }) - .track_scroll(&self.handle) - .h_full() - .w_full(); - div() .id((id.clone(), "view")) .relative() @@ -512,7 +566,37 @@ impl Render for CodeViewState { .absolute() .inset_0(), ) - .child(rows) + .child( + uniform_list((id.clone(), "rows"), line_count, { + let id = id.clone(); + let state = state.clone(); + move |range, _window, cx| { + let code = state.read(cx); + let active_line = code.active_line; + let theme = cx.theme(); + + range + .map(|line_ix| { + code.render_row( + &id, + line_ix, + active_line == Some(line_ix), + selection, + theme.mono_font, + theme.colors, + theme.ramps, + text_size, + line_height, + cx, + ) + }) + .collect() + } + }) + .track_scroll(&self.handle) + .h_full() + .w_full(), + ) .child( Scrollbar::vertical((self.id.clone(), "v-scrollbar"), self.handle.clone()) .visibility(ScrollbarVisibility::Platform), @@ -523,123 +607,23 @@ impl Render for CodeViewState { } } -#[allow(clippy::too_many_arguments)] -fn render_row( - code: &CodeViewState, - id: &ElementId, - line_ix: usize, - active: bool, - selection: Option<(SelectionPoint, SelectionPoint)>, - mono_font: &'static str, - colors: ColorTokens, - ramps: Ramps, - text_size: Pixels, - line_height: Pixels, - cx: &App, -) -> gpui::AnyElement { - let layout = code.line_layouts.get(line_ix); - let text = layout.map_or("", |layout| layout.text.as_str()); - let roles = layout.map_or(&[][..], |layout| layout.roles.as_slice()); - let char_count = text.chars().count(); - - let mut selected = vec![false; char_count]; - - if let Some((start, end)) = selection - && line_ix >= start.row - && line_ix <= end.row - { - let start_col = if line_ix == start.row { - start.col.min(char_count) - } else { - 0 - }; - - let end_col = if line_ix == end.row { - end.col.min(char_count) - } else { - char_count - }; - - for slot in &mut selected[start_col..end_col] { - *slot = true; +/// Binds the code view's copy chord: cmd-c on macOS, ctrl-c elsewhere. +/// +/// Call once at startup. Without it, selection copy has no key. +pub fn bind_code_view_keys(cx: &mut App) { + let context = match KeyBindingContextPredicate::parse(CODE_VIEW_CONTEXT) { + Ok(context) => Some(Rc::new(context)), + Err(error) => { + log::error!("failed to parse code view key context: {error}"); + return; } - } - - let mut highlights: Vec<(std::ops::Range, HighlightStyle)> = Vec::new(); - let mut run_start = 0usize; - let mut run_end = 0usize; - let mut run_role = Role::Text; - let mut run_selected = false; - - for (char_ix, (byte_ix, character)) in text.char_indices().enumerate() { - let fresh = char_ix == 0 || roles[char_ix] != run_role || selected[char_ix] != run_selected; - if fresh { - if char_ix > 0 { - highlights.push(( - run_start..run_end, - run_role.run_style(run_selected, colors, ramps), - )); - } - run_start = byte_ix; - run_role = roles[char_ix]; - run_selected = selected[char_ix]; - } - run_end = byte_ix + character.len_utf8(); - } - - if run_end > run_start || !text.is_empty() { - highlights.push(( - run_start..run_end, - run_role.run_style(run_selected, colors, ramps), - )); - } - - let style = TextStyle { - color: colors.foreground, - font_family: SharedString::from(mono_font), - font_size: text_size.into(), - line_height: line_height.into(), - white_space: gpui::WhiteSpace::Nowrap, - ..Default::default() }; - - div() - .debug_selector(move || format!("{id}-row-{line_ix}")) - .id(("code-row", line_ix)) - .w_full() - .text_xs() - .h(line_height) - .flex() - .items_center() - .overflow_hidden() - .when(active, |row| { - row.bg(Hsla { - a: colors.muted.a * WASH_ALPHA_SOFT, - ..colors.muted - }) - }) - .child( - gutter_cell( - cx, - if active { - colors.foreground - } else { - colors.muted_foreground - }, - format!("{}", line_ix + 1), - ) - .justify_end() - .pr_2() - .whitespace_nowrap(), - ) - .child( - div() - .flex_1() - .min_w_0() - .ml_4() - .overflow_hidden() - .whitespace_nowrap() - .child(gpui::StyledText::new(text).with_default_highlights(&style, highlights)), - ) - .into_any_element() + let binding = match KeyBinding::load("secondary-c", Box::new(Copy), context, false, None, cx) { + Ok(binding) => binding, + Err(error) => { + log::error!("failed to parse code view copy keystroke: {error}"); + return; + } + }; + cx.bind_keys([binding]); } diff --git a/crates/ui/src/components/combobox.rs b/crates/ui/src/components/combobox.rs index 4f9fd31..5fb457e 100644 --- a/crates/ui/src/components/combobox.rs +++ b/crates/ui/src/components/combobox.rs @@ -2,9 +2,8 @@ //! //! The state is the view: [`ComboboxState`] owns the query field and the //! options, and the owner renders the entity itself. Typing filters, the -//! arrow keys move a highlight, Enter commits, and what happens to unmatched -//! text when the field loses focus is decided by [`UnmatchedText`], which -//! reverts by default. +//! arrow keys move a highlight, Enter commits, and unmatched text reverts to +//! the chosen option's label (or empties the field) when focus is lost. //! //! # Examples //! @@ -33,13 +32,12 @@ use gpui::{ App, Bounds, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding, MouseButton, MouseDownEvent, ParentElement as _, Pixels, Render, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Subscription, Task, - UniformListScrollHandle, Window, actions, anchored, canvas, deferred, div, point, px, - uniform_list, + UniformListScrollHandle, Window, actions, canvas, div, uniform_list, }; use crate::components::common::{ - ControlSizing, OVERLAY_LAYER, ResultLogErr as _, Sizable, StyledExt as _, floating_panel, - h_flex, paint_highlighted_row, v_flex, wrapping_adjacent_selectable, + ControlSizing, ResultLogErr as _, Sizable, StyledExt as _, floating_panel, h_flex, + paint_highlighted_row, v_flex, wrapping_adjacent_selectable, }; use crate::components::empty_state::EmptyState; use crate::components::input::{Input, InputState, InputStateEvent}; @@ -54,41 +52,10 @@ actions!( /// The key context the combobox's wrapper declares. pub const COMBOBOX_CONTEXT: &str = "Combobox"; -/// Binds the combobox's four keys: down, up, enter, and escape. -pub fn bind_combobox_keys(cx: &mut App) { - let under_input = Some("Combobox > Input"); - cx.bind_keys([ - KeyBinding::new("down", HighlightNext, under_input), - KeyBinding::new("up", HighlightPrevious, under_input), - KeyBinding::new("enter", Choose, under_input), - KeyBinding::new("escape", Dismiss, under_input), - KeyBinding::new("down", HighlightNext, Some(COMBOBOX_CONTEXT)), - KeyBinding::new("up", HighlightPrevious, Some(COMBOBOX_CONTEXT)), - KeyBinding::new("enter", Choose, Some(COMBOBOX_CONTEXT)), - KeyBinding::new("escape", Dismiss, Some(COMBOBOX_CONTEXT)), - ]); -} - -/// What happens to text that matches no option when the field loses focus. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum UnmatchedText { - /// Restore the chosen option's label, or empty the field. - #[default] - Revert, - /// Leave the text and leave the value cleared. - Keep, - /// Hand the text to the `on_create` handler. - Create, -} - /// An option for a [`Combobox`]: a value and the label the filter matches on. pub type ComboboxOption = (T, SharedString); /// Reports the value whenever it changes. pub type ComboboxHandler = Rc, &mut Window, &mut App)>; -/// Receives unmatched text when the field loses focus in create mode. -pub type ComboboxCreateHandler = Rc; -/// Decides which options survive a query: the query, the value, the label. -pub type ComboboxFilter = Rc bool>; /// Builder for a combobox, consumed by [`ComboboxState::new`]. #[must_use] @@ -102,9 +69,6 @@ where selected: Option, placeholder: SharedString, on_change: Option>, - on_create: Option, - filter: Option>, - unmatched: UnmatchedText, size: Size, /// Icon shown at the field's leading edge while a value is selected. selected_icon: Option, @@ -127,9 +91,6 @@ where selected: None, placeholder: SharedString::from("Select..."), on_change: None, - on_create: None, - filter: None, - unmatched: UnmatchedText::default(), size: Size::default(), selected_icon: None, style: StyleRefinement::default(), @@ -169,31 +130,6 @@ where self } - /// Hands unmatched text to `handler` when the field loses focus. - pub fn on_create(mut self, handler: F) -> Self - where - F: Fn(SharedString, &mut Window, &mut App) + 'static, - { - self.on_create = Some(Rc::new(handler)); - self.unmatched = UnmatchedText::Create; - self - } - - /// Sets the matcher that decides which options survive a query. - pub fn filter(mut self, filter: F) -> Self - where - F: Fn(&str, &T, &SharedString) -> bool + 'static, - { - self.filter = Some(Rc::new(filter)); - self - } - - /// Leaves unmatched text in the field on blur. - pub fn keep_unmatched_text(mut self) -> Self { - self.unmatched = UnmatchedText::Keep; - self - } - /// Overrides the accessibility label. pub fn accessibility_label(mut self, label: L) -> Self where @@ -250,9 +186,6 @@ where /// The highlighted popup *row*, when the popup is open. highlight: Option, on_change: Option>, - on_create: Option, - filter: ComboboxFilter, - unmatched: UnmatchedText, size: Size, /// Width refinements from the builder, applied to the wrapper each render. style: StyleRefinement, @@ -312,11 +245,6 @@ where visible, highlight: None, on_change: combobox.on_change, - on_create: combobox.on_create, - filter: combobox.filter.unwrap_or_else(|| { - Rc::new(|query, _value, label| label.to_lowercase().contains(&query.to_lowercase())) - }), - unmatched: combobox.unmatched, size: combobox.size, style: combobox.style, selected_icon: combobox.selected_icon, @@ -326,21 +254,6 @@ where } } - /// The text currently in the field. - pub fn text(&self, cx: &App) -> String { - self.query.read(cx).value().to_string() - } - - /// Focuses the query field. - pub fn focus(&self, window: &mut Window, cx: &mut App) { - window.focus(&self.query.read(cx).focus_handle(), cx); - } - - /// Whether the option list is showing. - pub fn is_open(&self) -> bool { - self.highlight.is_some() - } - /// The chosen value. pub fn selected(&self) -> Option<&T> { self.selected.as_ref() @@ -367,11 +280,6 @@ where cx.notify(); } - /// A copy of the current choice list. - pub fn options_snapshot(&self) -> Vec> { - self.options.clone() - } - /// The label of the chosen option, if there is one. fn selected_label(&self) -> Option { let selected = self.selected.as_ref()?; @@ -383,12 +291,12 @@ where /// Recomputes `visible` for `query` and clamps the highlight onto it. fn refilter(&mut self, query: &str) { - let filter = self.filter.clone(); + let needle = query.to_lowercase(); self.visible = self .options .iter() .enumerate() - .filter(|(_, (value, label))| filter(query, value, label)) + .filter(|(_, (_, label))| label.to_lowercase().contains(&needle)) .map(|(index, _)| index) .collect(); self.highlight = self.highlight.filter(|row| *row < self.visible.len()); @@ -452,7 +360,7 @@ where cx.notify(); } - /// Losing focus. [`UnmatchedText`] decides what the text becomes. + /// Losing focus: unmatched text reverts to the chosen option's label. fn blurred(&mut self, window: &mut Window, cx: &mut Context) { self.highlight = None; let text = self.query_text(cx); @@ -462,26 +370,10 @@ where return; } - match self.unmatched { - UnmatchedText::Revert => { - let restored = self.selected_label().unwrap_or_default().to_string(); - self.query - .update(cx, |query, cx| query.set_value_silent(restored, window, cx)); - } - UnmatchedText::Keep => {} - UnmatchedText::Create => { - if !text.is_empty() - && let Some(on_create) = self.on_create.clone() - { - let text = SharedString::from(text); - let task = window.spawn(cx, async move |cx| { - cx.update(|window, cx| on_create(text, window, cx)) - .log_err(); - }); - self.task.replace(task); - } - } - } + let restored = self.selected_label().unwrap_or_default().to_string(); + self.query.update(cx, |query, cx| { + query.set_value_silent(restored, window, cx); + }); cx.notify(); } @@ -536,37 +428,6 @@ where let state = cx.entity(); let open = self.highlight.is_some(); - let chevron = h_flex() - .id((id.clone(), "chevron")) - .cursor_pointer() - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_click({ - let state = state.clone(); - move |_, window, cx| { - let focus = state.read(cx).query.read(cx).focus_handle(); - window.focus(&focus, cx); - state.update(cx, |state, cx| { - if state.highlight.is_some() { - state.highlight = None; - } else { - if state.selected.is_some() { - state.refilter(""); - } else { - let query = state.query.read(cx).value().to_string(); - state.refilter(&query); - } - state.highlight = Some(0); - } - cx.notify(); - }); - } - }) - .child( - icon(IconRole::ChevronDown) - .size(self.size.dense_icon_rems()) - .color(colors.muted_foreground), - ); - let wrapper_bounds: Rc>>> = Rc::new(RefCell::new(None)); div() @@ -633,7 +494,39 @@ where .top_0() .bottom_0() .items_center() - .child(chevron), + .child( + h_flex() + .id((id.clone(), "chevron")) + .cursor_pointer() + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click({ + let state = state.clone(); + move |_, window, cx| { + let focus = state.read(cx).query.read(cx).focus_handle(); + window.focus(&focus, cx); + state.update(cx, |state, cx| { + if state.highlight.is_some() { + state.highlight = None; + } else { + if state.selected.is_some() { + state.refilter(""); + } else { + let query = + state.query.read(cx).value().to_string(); + state.refilter(&query); + } + state.highlight = Some(0); + } + cx.notify(); + }); + } + }) + .child( + icon(IconRole::ChevronDown) + .size(self.size.dense_icon_rems()) + .color(colors.muted_foreground), + ), + ), ) .when(open, |wrapper| { let visible = self.visible.clone(); @@ -741,67 +634,84 @@ where .map(|bounds| bounds.size.width) .unwrap_or(COMBOBOX_WIDTH); - let panel = floating_panel( - cx, - radius.overlay, - v_flex() - .id((id.clone(), "panel")) - .debug_selector({ - let id = id.clone(); - move || format!("{id}-panel") - }) - .w(popup_width) - .p_1() - .text_color(colors.foreground), - shadows, - ) - .overflow_hidden() - .child(rows) - .child( - canvas( - { - let cell = panel_bounds.clone(); - move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) - }, - { - let state = state.clone(); - let panel_bounds = panel_bounds.clone(); - let wrapper_bounds = wrapper_bounds.clone(); - move |_, _, window, _cx| { - window.on_mouse_event({ - let state = state.clone(); - let panel_bounds = panel_bounds.clone(); - let wrapper_bounds = wrapper_bounds.clone(); - move |event: &MouseDownEvent, phase, _window, cx| { - if phase != gpui::DispatchPhase::Bubble { - return; - } - let on_panel = panel_bounds - .borrow() - .is_some_and(|bounds| bounds.contains(&event.position)); - let on_wrapper = wrapper_bounds - .borrow() - .is_some_and(|bounds| bounds.contains(&event.position)); - if on_panel || on_wrapper { - return; - } - state.update(cx, |state, cx| { - state.highlight = None; - cx.notify(); - }); - } - }); - } - }, + wrapper.child(crate::components::menu::anchored_overlay( + None, + floating_panel( + cx, + radius.overlay, + v_flex() + .id((id.clone(), "panel")) + .debug_selector({ + let id = id.clone(); + move || format!("{id}-panel") + }) + .w(popup_width) + .p_1() + .text_color(colors.foreground), + shadows, ) - .absolute() - .inset_0(), - ); - - wrapper.child( - deferred(anchored().offset(point(px(0.), px(4.))).child(panel)) - .with_priority(OVERLAY_LAYER), - ) + .overflow_hidden() + .child(rows) + .child( + canvas( + { + let cell = panel_bounds.clone(); + move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) + }, + { + let state = state.clone(); + let panel_bounds = panel_bounds.clone(); + let wrapper_bounds = wrapper_bounds.clone(); + move |_, _, window, _cx| { + window.on_mouse_event({ + let state = state.clone(); + let panel_bounds = panel_bounds.clone(); + let wrapper_bounds = wrapper_bounds.clone(); + move |event: &MouseDownEvent, phase, _window, cx| { + if phase != gpui::DispatchPhase::Bubble { + return; + } + let on_panel = + panel_bounds.borrow().is_some_and(|bounds| { + bounds.contains(&event.position) + }); + let on_wrapper = + wrapper_bounds.borrow().is_some_and(|bounds| { + bounds.contains(&event.position) + }); + if on_panel || on_wrapper { + return; + } + state.update(cx, |state, cx| { + state.highlight = None; + cx.notify(); + }); + } + }); + } + }, + ) + .absolute() + .inset_0(), + ) + .into_any_element(), + None, + )) }) } } + +/// Binds the combobox's four keys: down, up, enter, and escape. +pub fn bind_combobox_keys(cx: &mut App) { + let under_input = Some("Combobox > Input"); + cx.bind_keys([ + KeyBinding::new("down", HighlightNext, under_input), + KeyBinding::new("up", HighlightPrevious, under_input), + KeyBinding::new("enter", Choose, under_input), + KeyBinding::new("escape", Dismiss, under_input), + KeyBinding::new("down", HighlightNext, Some(COMBOBOX_CONTEXT)), + KeyBinding::new("up", HighlightPrevious, Some(COMBOBOX_CONTEXT)), + KeyBinding::new("enter", Choose, Some(COMBOBOX_CONTEXT)), + KeyBinding::new("escape", Dismiss, Some(COMBOBOX_CONTEXT)), + ]); +} diff --git a/crates/ui/src/components/command_palette.rs b/crates/ui/src/components/command_palette.rs index 154132f..5dd709a 100644 --- a/crates/ui/src/components/command_palette.rs +++ b/crates/ui/src/components/command_palette.rs @@ -30,8 +30,8 @@ use gpui::prelude::FluentBuilder; use gpui::{ AnyElement, App, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding, MouseButton, ParentElement as _, Render, Role, SharedString, StatefulInteractiveElement as _, - StyleRefinement, Styled as _, Subscription, UniformListScrollHandle, Window, actions, canvas, - deferred, div, relative, rems, uniform_list, + StyleRefinement, Styled as _, Subscription, UniformListScrollHandle, Window, actions, deferred, + div, relative, rems, uniform_list, }; use crate::components::common::{ @@ -51,20 +51,10 @@ actions!( /// The key context the palette's panel declares. pub const COMMAND_PALETTE_CONTEXT: &str = "CommandPalette"; -/// Binds the palette's four keys: down, up, enter, and escape. -pub fn bind_command_palette_keys(cx: &mut App) { - let under_input = Some("CommandPalette > Input"); - cx.bind_keys([ - KeyBinding::new("down", HighlightNext, under_input), - KeyBinding::new("up", HighlightPrevious, under_input), - KeyBinding::new("enter", Choose, under_input), - KeyBinding::new("escape", Dismiss, under_input), - KeyBinding::new("down", HighlightNext, Some(COMMAND_PALETTE_CONTEXT)), - KeyBinding::new("up", HighlightPrevious, Some(COMMAND_PALETTE_CONTEXT)), - KeyBinding::new("enter", Choose, Some(COMMAND_PALETTE_CONTEXT)), - KeyBinding::new("escape", Dismiss, Some(COMMAND_PALETTE_CONTEXT)), - ]); -} +/// Filters and ranks the commands for a query. +pub type CommandMatcher = Rc Vec>; +/// Runs the chosen command. +pub type CommandHandler = Rc; /// A command the palette can run: a stable id and the label the matcher sees. #[derive(Clone)] @@ -117,11 +107,6 @@ impl Command { // Command is a data builder, not an element, adopt the combinators explicitly. impl FluentBuilder for Command {} -/// Filters and ranks the commands for a query. -pub type CommandMatcher = Rc Vec>; -/// Runs the chosen command. -pub type CommandHandler = Rc; - /// Builder for a command palette, consumed by [`CommandPaletteState::new`]. #[must_use] pub struct CommandPalette { @@ -474,83 +459,6 @@ impl Render for CommandPaletteState { .into_any_element() }; - let panel = floating_panel( - cx, - radius.overlay, - v_flex() - .id((id.clone(), "panel")) - .debug_selector({ - let id = id.clone(); - move || format!("{id}-panel") - }) - .key_context(COMMAND_PALETTE_CONTEXT) - .role(Role::Dialog) - .aria_label(self.name.clone()) - .w_full() - .max_w(relative(0.6)) - .p_2() - .gap_2() - .text_color(colors.foreground), - shadows, - ) - .overflow_hidden() - .refine_style(&self.style) - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_action({ - let state = state.clone(); - move |_: &HighlightNext, _window, cx| { - state.update(cx, |state, cx| state.move_highlight(1, cx)); - } - }) - .on_action({ - let state = state.clone(); - move |_: &HighlightPrevious, _window, cx| { - state.update(cx, |state, cx| state.move_highlight(-1, cx)); - } - }) - .on_action({ - let state = state.clone(); - move |_: &Choose, window, cx| { - state.update(cx, |state, cx| state.choose(window, cx)); - } - }) - .on_action({ - let state = state.clone(); - move |_: &Dismiss, window, cx| { - state.update(cx, |state, cx| state.dismiss(window, cx)); - } - }) - .child( - Input::new((id.clone(), "query"), self.query.clone()) - .placeholder(self.placeholder.clone()), - ) - .child(rows) - .child( - canvas(|_, _, _| {}, { - let focus = query_focus.clone(); - move |_, _, window, cx| { - if !focus.contains_focused(window, cx) { - window.focus(&focus, cx); - } - } - }) - .absolute() - .inset_0(), - ); - - let scrim = div() - .absolute() - .inset_0() - .bg(colors.overlay) - .occlude() - .on_mouse_down(MouseButton::Left, { - let state = state.clone(); - move |_, _window, cx| { - state.update(cx, |state, cx| state.close(cx)); - cx.stop_propagation(); - } - }); - deferred( div() .absolute() @@ -559,10 +467,94 @@ impl Render for CommandPaletteState { .justify_center() .items_start() .pt(titlebar_height) - .child(scrim) - .child(panel), + .child( + div() + .absolute() + .inset_0() + .bg(colors.overlay) + .occlude() + .on_mouse_down(MouseButton::Left, { + let state = state.clone(); + move |_, _window, cx| { + state.update(cx, |state, cx| state.close(cx)); + cx.stop_propagation(); + } + }), + ) + .child( + floating_panel( + cx, + radius.overlay, + v_flex() + .id((id.clone(), "panel")) + .debug_selector({ + let id = id.clone(); + move || format!("{id}-panel") + }) + .key_context(COMMAND_PALETTE_CONTEXT) + .role(Role::Dialog) + .aria_label(self.name.clone()) + .w_full() + .max_w(relative(0.6)) + .p_2() + .gap_2() + .text_color(colors.foreground), + shadows, + ) + .overflow_hidden() + .refine_style(&self.style) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_action({ + let state = state.clone(); + move |_: &HighlightNext, _window, cx| { + state.update(cx, |state, cx| state.move_highlight(1, cx)); + } + }) + .on_action({ + let state = state.clone(); + move |_: &HighlightPrevious, _window, cx| { + state.update(cx, |state, cx| state.move_highlight(-1, cx)); + } + }) + .on_action({ + let state = state.clone(); + move |_: &Choose, window, cx| { + state.update(cx, |state, cx| state.choose(window, cx)); + } + }) + .on_action({ + let state = state.clone(); + move |_: &Dismiss, window, cx| { + state.update(cx, |state, cx| state.dismiss(window, cx)); + } + }) + .child( + Input::new((id.clone(), "query"), self.query.clone()) + .placeholder(self.placeholder.clone()), + ) + .child(rows) + .child(crate::components::menu::focus_capture( + query_focus.clone(), + move |window, cx| !query_focus.contains_focused(window, cx), + )), + ), ) .with_priority(DIALOG_LAYER) .into_any_element() } } + +/// Binds the palette's four keys: down, up, enter, and escape. +pub fn bind_command_palette_keys(cx: &mut App) { + let under_input = Some("CommandPalette > Input"); + cx.bind_keys([ + KeyBinding::new("down", HighlightNext, under_input), + KeyBinding::new("up", HighlightPrevious, under_input), + KeyBinding::new("enter", Choose, under_input), + KeyBinding::new("escape", Dismiss, under_input), + KeyBinding::new("down", HighlightNext, Some(COMMAND_PALETTE_CONTEXT)), + KeyBinding::new("up", HighlightPrevious, Some(COMMAND_PALETTE_CONTEXT)), + KeyBinding::new("enter", Choose, Some(COMMAND_PALETTE_CONTEXT)), + KeyBinding::new("escape", Dismiss, Some(COMMAND_PALETTE_CONTEXT)), + ]); +} diff --git a/crates/ui/src/components/common.rs b/crates/ui/src/components/common.rs index fa90204..006c3a7 100644 --- a/crates/ui/src/components/common.rs +++ b/crates/ui/src/components/common.rs @@ -19,8 +19,33 @@ use gpui::{ WindowId, div, px, rems, }; -pub use crate::theme::Size; -use crate::theme::{ActiveTheme as _, FOCUS_RING_ALPHA, FOCUS_RING_SPREAD}; +use crate::theme::{ActiveTheme as _, FOCUS_RING_ALPHA, FOCUS_RING_SPREAD, Size}; + +/// Deferred draw priority of window-modal surfaces; default layer 0 stays for in-flow chrome like resize handles. +pub const DIALOG_LAYER: usize = 1; +/// Deferred draw priority of floating panels, so controls inside a dialog open above it. +pub const OVERLAY_LAYER: usize = 2; +/// Deferred draw priority of passive notifications, so they stay visible over dialogs. +pub const TOAST_LAYER: usize = 3; + +/// A handler told to clean up after a dismissed surface. +pub type DismissHandler = std::rc::Rc; + +/// The painted bounds of elements that tooltips anchor to, per window and element id. +#[derive(Default)] +struct AnchorBoundsRegistry(HashMap<(WindowId, ElementId), Bounds>); + +impl Global for AnchorBoundsRegistry {} + +impl AnchorBoundsRegistry { + fn record(&mut self, window: WindowId, id: ElementId, bounds: Bounds) { + self.0.insert((window, id), bounds); + } + + fn get(&self, window: WindowId, id: &ElementId) -> Option> { + self.0.get(&(window, id.clone())).copied() + } +} /// A row whose children center on the cross axis. #[must_use] @@ -87,23 +112,6 @@ pub fn focus_handle(id: &ElementId, window: &mut Window, cx: &mut App) -> FocusH .clone() } -/// The painted bounds of elements that tooltips anchor to, per window and element id. -/// Entries are never evicted: bounds are bounded by live windows, though long-lived processes minting dynamic per-item ids could accumulate. -#[derive(Default)] -struct AnchorBoundsRegistry(HashMap<(WindowId, ElementId), Bounds>); - -impl Global for AnchorBoundsRegistry {} - -impl AnchorBoundsRegistry { - fn record(&mut self, window: WindowId, id: ElementId, bounds: Bounds) { - self.0.insert((window, id), bounds); - } - - fn get(&self, window: WindowId, id: &ElementId) -> Option> { - self.0.get(&(window, id.clone())).copied() - } -} - /// The last bounds an element painted at, in the given window. pub fn anchor_bounds(window: WindowId, id: &ElementId, cx: &App) -> Option> { cx.try_global::() @@ -250,16 +258,6 @@ where }) } -/// A handler told to clean up after a dismissed surface. -pub type DismissHandler = std::rc::Rc; - -/// Deferred draw priority of window-modal surfaces; default layer 0 stays for in-flow chrome like resize handles. -pub const DIALOG_LAYER: usize = 1; -/// Deferred draw priority of floating panels, so controls inside a dialog open above it. -pub const OVERLAY_LAYER: usize = 2; -/// Deferred draw priority of passive notifications, so they stay visible over dialogs. -pub const TOAST_LAYER: usize = 3; - /// A component that can be told which size to render at. pub trait Sizable: Sized { /// Sets the size. diff --git a/crates/ui/src/components/context_menu.rs b/crates/ui/src/components/context_menu.rs deleted file mode 100644 index a41d89e..0000000 --- a/crates/ui/src/components/context_menu.rs +++ /dev/null @@ -1,145 +0,0 @@ -//! Renders a menu at the pointer when its target element is right-clicked. -//! -//! # Examples -//! -//! ```no_run -//! use gpui::{IntoElement as _, ParentElement as _, SharedString, div}; -//! use ui::context_menu::ContextMenu; -//! use ui::menu::MenuItem; -//! -//! let context = ContextMenu::new("project-context") -//! .target(|_window, _cx| { -//! div() -//! .child(SharedString::from("project.el")) -//! .into_any_element() -//! }) -//! .items(|_window, _cx| vec![MenuItem::new("Delete").handler(|_window, _cx| {})]); -//! ``` - -use gpui::prelude::FluentBuilder as _; -use gpui::{ - App, ElementId, InteractiveElement as _, IntoElement, MouseButton, MouseDownEvent, - ParentElement as _, RenderOnce, SharedString, StyleRefinement, Window, div, -}; - -use crate::components::common::StyledExt as _; -use crate::components::menu::{Menu, MenuItem}; - -/// Builds the element that opens the menu on right-click. -type TargetFn = Box gpui::AnyElement>; -/// Builds the menu's items fresh each render. -type ItemsFn = Box Vec>; - -/// A menu that opens at the pointer when its target is right-clicked. -/// -/// Open state is owned internally by design, unlike the controlled [`Menu`]. -#[derive(IntoElement)] -#[must_use] -pub struct ContextMenu { - id: ElementId, - target: Option, - items: Option, - a11y_label: Option, - style: StyleRefinement, -} - -impl ContextMenu { - /// Creates a context menu over a target set with [`ContextMenu::target`]. - pub fn new(id: I) -> Self - where - I: Into, - { - Self { - id: id.into(), - target: None, - items: None, - a11y_label: None, - style: StyleRefinement::default(), - } - } - - /// Sets the element that opens the menu on right-click. - pub fn target(mut self, target: F) -> Self - where - F: Fn(&mut Window, &mut App) -> gpui::AnyElement + 'static, - { - self.target = Some(Box::new(target)); - self - } - - /// Sets the menu's items, built fresh each render. - pub fn items(mut self, items: F) -> Self - where - F: Fn(&mut Window, &mut App) -> Vec + 'static, - { - self.items = Some(Box::new(items)); - self - } - - /// Overrides the menu's accessibility label. - pub fn accessibility_label(mut self, label: L) -> Self - where - L: Into, - { - self.a11y_label = Some(label.into()); - self - } -} - -impl RenderOnce for ContextMenu { - fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { - let open = window.with_element_namespace(self.id.clone(), |window| { - window - .use_keyed_state("context-open", cx, |_, _| false) - .clone() - }); - - let at = window.with_element_namespace(self.id.clone(), |window| { - window - .use_keyed_state("context-position", cx, |_, _| None) - .clone() - }); - - let is_open = *open.read(cx); - let position = *at.read(cx); - - let target = self.target; - let at_for_target = at.clone(); - - let trigger = move |window: &mut Window, cx: &mut App| { - let base = target - .as_ref() - .map(|build| build(window, cx)) - .unwrap_or_else(|| div().into_any_element()); - - div() - .on_mouse_down(MouseButton::Right, { - let at = at_for_target.clone(); - move |event: &MouseDownEvent, _window, cx| { - at.update(cx, |at, _| *at = Some(event.position)); - } - }) - .child(base) - .into_any_element() - }; - - let items = move |window: &mut Window, cx: &mut App| { - self.items - .as_ref() - .map(|build| build(window, cx)) - .unwrap_or_default() - }; - - Menu::new(self.id) - .open(is_open) - .on_change(move |next, _window, cx| open.update(cx, |open, _| *open = next)) - .open_at(position) - .trigger_button(MouseButton::Right) - .trigger(trigger) - .items(items) - .refine_style(&self.style) - .when_some(self.a11y_label.clone(), |menu, label| { - menu.accessibility_label(label) - }) - } -} diff --git a/crates/ui/src/components/dialog.rs b/crates/ui/src/components/dialog.rs index 9f62145..090dff5 100644 --- a/crates/ui/src/components/dialog.rs +++ b/crates/ui/src/components/dialog.rs @@ -42,7 +42,7 @@ use crate::icons::IconRole; use crate::theme::{ActiveTheme as _, DIALOG_MIN_WIDTH}; /// Requests the dialog's close: `false` closes. -pub type ChangeHandler = Rc; +type ChangeHandler = Rc; type ContentFn = Box AnyElement>; type ActionsFn = Box Vec>; diff --git a/crates/ui/src/components/diff.rs b/crates/ui/src/components/diff.rs deleted file mode 100644 index a7fe65c..0000000 --- a/crates/ui/src/components/diff.rs +++ /dev/null @@ -1,720 +0,0 @@ -//! Renders a unified, syntax-highlighted diff of two versions of a file: -//! change bars or `+`/`-` markers, tinted number gutters, word-level -//! intra-line highlights, and collapsed hunk separators. -//! -//! Rows reuse the code view's highlighting. Consumers that already hold a -//! git diff can build [`DiffRow`]s themselves instead of calling -//! [`DiffViewState::diff_rows`]. -//! -//! # Examples -//! -//! ```no_run -//! use gpui::{App, AppContext as _}; -//! use ui::diff::{DiffIndicators, DiffViewState}; -//! use ui::highlight::Language; -//! -//! fn patch(cx: &mut App) -> gpui::Entity { -//! let state = DiffViewState::new( -//! "patch", -//! "# gpui\nA UI kit for gpui.", -//! "# gpui\nA UI toolkit for gpui.", -//! Language::Rust, -//! ) -//! .indicators(DiffIndicators::Bars); -//! -//! cx.new(|_| state) -//! } -//! ``` - -use std::ops::Range; - -use gpui::prelude::FluentBuilder as _; -use gpui::{ - App, Context, ElementId, HighlightStyle, InteractiveElement as _, IntoElement, - ListHorizontalSizingBehavior, ParentElement as _, Pixels, Render, ScrollStrategy, SharedString, - StatefulInteractiveElement as _, Styled as _, TextStyle, UniformListScrollHandle, Window, div, - point, px, rems, uniform_list, -}; -use similar::{Change, ChangeTag, TextDiff}; - -use crate::components::highlight::{HighlightedCode, Language, Line, Role, highlight}; -use crate::components::scrollbar::{Scrollbar, ScrollbarHandle, ScrollbarVisibility}; -use crate::components::utils::{gutter_cell, wash, wash_gutter, wash_strong}; -use crate::theme::{ActiveTheme as _, CODE_GUTTER_WIDTH, CODE_LINE_HEIGHT, MONO_ADVANCE_RATIO}; - -/// The left change-indicator bar's width, four hairlines. -const CHANGE_BAR_WIDTH: Pixels = px(4.0); - -/// What a diff row did to the file. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum DiffRowKind { - /// Present in both versions. - Context, - /// Only in the new version. - Added, - /// Only in the old version. - Removed, - /// A hunk separator introducing the rows after it. - Hunk, -} - -/// One row of a unified diff: a diff line or a hunk separator. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct DiffRow { - pub kind: DiffRowKind, - /// The highlighted line content; empty for hunk separators. - pub content: Line, - /// 1-based line number in the old version, when the row exists there. - pub old_number: Option, - /// 1-based line number in the new version, when the row exists there. - pub new_number: Option, - /// Byte ranges of intra-line word changes, tinted on changed rows. - pub changed_ranges: Vec>, - /// The `@@ -a,b +c,d @@` header, for hunk separator rows. - pub header: SharedString, - /// Unchanged lines collapsed into this separator row; zero elsewhere. - pub hidden_lines: usize, -} - -/// How changed rows are marked. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum DiffIndicators { - /// A two-pixel bar on the row's left edge. - #[default] - Bars, - /// Classic `+`/`-` glyphs in a marker column. - Classic, - /// Only the background washes. - None, -} - -/// How collapsed regions between hunks render. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum HunkSeparator { - /// The collapsed unchanged line count, centered. - #[default] - LineInfo, - /// The patch-style `@@ -a,b +c,d @@` header. - Metadata, - /// A minimal `···` bar. - Simple, -} - -/// Presentation options for the diff view. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct DiffViewOptions { - /// How changed rows are marked. - pub indicators: DiffIndicators, - /// How collapsed regions between hunks render. - pub separator: HunkSeparator, - /// Whether the line-number gutter renders. - pub line_numbers: bool, -} - -impl Default for DiffViewOptions { - fn default() -> Self { - Self { - indicators: DiffIndicators::Bars, - separator: HunkSeparator::LineInfo, - line_numbers: true, - } - } -} - -impl DiffRow { - /// Assembles a diff line row from a `similar` change. - pub(crate) fn from_change( - change: &Change<&str>, - code: &HighlightedCode, - changed_ranges: Vec>, - ) -> DiffRow { - let content = match change.tag() { - ChangeTag::Equal => change - .new_index() - .and_then(|ix| code.lines.get(ix)) - .cloned() - .unwrap_or_default(), - ChangeTag::Delete => change - .old_index() - .and_then(|ix| code.lines.get(ix)) - .cloned() - .unwrap_or_default(), - ChangeTag::Insert => change - .new_index() - .and_then(|ix| code.lines.get(ix)) - .cloned() - .unwrap_or_default(), - }; - - let (old_number, new_number) = match change.tag() { - ChangeTag::Equal => ( - change.old_index().map(|ix| ix + 1), - change.new_index().map(|ix| ix + 1), - ), - ChangeTag::Delete => (change.old_index().map(|ix| ix + 1), None), - ChangeTag::Insert => (None, change.new_index().map(|ix| ix + 1)), - }; - - DiffRow { - kind: match change.tag() { - ChangeTag::Equal => DiffRowKind::Context, - ChangeTag::Delete => DiffRowKind::Removed, - ChangeTag::Insert => DiffRowKind::Added, - }, - content, - old_number, - new_number, - changed_ranges, - header: Default::default(), - hidden_lines: 0, - } - } - - /// The row's text length, in characters. - fn char_count(&self) -> usize { - self.content.text().chars().count() - } - - /// Stable element id: the kind and line numbers packed into one integer. - fn element_id(&self, hunk_ordinal: usize) -> ElementId { - let kind = match self.kind { - DiffRowKind::Context => 0u64, - DiffRowKind::Added => 1, - DiffRowKind::Removed => 2, - DiffRowKind::Hunk => { - return ElementId::named_usize("diff-hunk", hunk_ordinal); - } - }; - // Line numbers saturate at 2^31 so the two fields never overlap. - let old = self.old_number.unwrap_or(0).min((1 << 31) - 1) as u64; - let new = self.new_number.unwrap_or(0).min((1 << 31) - 1) as u64; - ElementId::named_usize("diff-row", ((kind << 62) | (old << 31) | new) as usize) - } -} - -/// Retained state for a diff view. -/// -/// Build one in a [`gpui::Entity`], render the entity, and call its setters -/// to update the rendered view. -pub struct DiffViewState { - id: ElementId, - rows: Vec, - /// Cached per-row id and text length, parallel to `rows`. - row_layouts: Vec, - /// The row whose width drives horizontal scroll extent, `rows`-derived. - widest_row: Option, - options: DiffViewOptions, - /// Drives both scroll axes of the virtualized row list. - handle: UniformListScrollHandle, - a11y_label: Option, -} - -/// Cached per-row render data, computed once when the rows are set. -struct RowLayout { - id: ElementId, - char_count: usize, -} - -impl DiffViewState { - /// Builds the state, diffing `old` against `new`. - pub fn new(id: I, old: O, new: N, language: Language) -> Self - where - I: Into, - O: AsRef, - N: AsRef, - { - let mut state = Self { - id: id.into(), - rows: Vec::new(), - row_layouts: Vec::new(), - widest_row: None, - options: DiffViewOptions::default(), - handle: UniformListScrollHandle::new(), - a11y_label: None, - }; - state.set_rows(old, new, language); - state - } - - /// Replaces the rows, recomputing the per-row layout cache with them. - fn set_rows(&mut self, old: O, new: N, language: Language) - where - O: AsRef, - N: AsRef, - { - self.rows = Self::diff_rows(old.as_ref(), new.as_ref(), language); - - let mut hunk_ordinal = 0usize; - self.row_layouts = self - .rows - .iter() - .map(|row| { - let ordinal = if row.kind == DiffRowKind::Hunk { - hunk_ordinal += 1; - hunk_ordinal - } else { - 0 - }; - RowLayout { - id: row.element_id(ordinal), - char_count: row.char_count(), - } - }) - .collect(); - - self.widest_row = self - .rows - .iter() - .zip(&self.row_layouts) - .enumerate() - .filter(|(_, (row, _))| row.kind != DiffRowKind::Hunk) - .max_by_key(|(_, (_, layout))| layout.char_count) - .map(|(widest, _)| widest); - } - - /// Computes unified rows between two texts, highlighting every line with - /// `language`. Rows include [`DiffRowKind::Hunk`] separators between - /// hunks. - pub fn diff_rows(old: &str, new: &str, language: Language) -> Vec { - let old_code = highlight(old, language); - let new_code = highlight(new, language); - let diff = TextDiff::from_lines(old, new); - - let mut rows = Vec::new(); - let mut collapsed_before = 0usize; - - for group in diff.grouped_ops(3) { - let (Some(first), Some(last)) = (group.first(), group.last()) else { - continue; - }; - - let old_range = first.old_range().start..last.old_range().end; - let new_range = first.new_range().start..last.new_range().end; - - // git prints the line before a pure insertion when the count is zero. - let old_start = if old_range.is_empty() { - old_range.start - } else { - old_range.start + 1 - }; - - let new_start = if new_range.is_empty() { - new_range.start - } else { - new_range.start + 1 - }; - - let collapsed = first.old_range().start.saturating_sub(collapsed_before); - if collapsed > 0 { - rows.push(DiffRow { - kind: DiffRowKind::Hunk, - content: Line::default(), - old_number: None, - new_number: None, - changed_ranges: Vec::new(), - header: format!( - "@@ -{},{} +{},{} @@", - old_start, - old_range.len(), - new_start, - new_range.len() - ) - .into(), - hidden_lines: collapsed, - }); - } - collapsed_before = last.old_range().end; - - for op in &group { - let changes: Vec<_> = diff.iter_changes(op).collect(); - let mut index = 0; - - while index < changes.len() { - if changes[index].tag() == ChangeTag::Equal { - rows.push(DiffRow::from_change(&changes[index], &new_code, Vec::new())); - index += 1; - continue; - } - - let deletions = changes[index..] - .iter() - .take_while(|change| change.tag() == ChangeTag::Delete) - .count(); - - let insertions = changes[index + deletions..] - .iter() - .take_while(|change| change.tag() == ChangeTag::Insert) - .count(); - - let mut deletion_ranges = vec![Vec::new(); deletions]; - let mut insertion_ranges = vec![Vec::new(); insertions]; - - for pair in 0..deletions.min(insertions) { - let old_text = changes[index + pair].value().trim_end_matches('\n'); - let new_text = changes[index + deletions + pair] - .value() - .trim_end_matches('\n'); - let words = TextDiff::from_words(old_text, new_text); - - let (mut old_offset, mut new_offset) = (0usize, 0usize); - - for word in words.iter_all_changes() { - let len = word.value().len(); - - match word.tag() { - ChangeTag::Delete => { - deletion_ranges[pair].push(old_offset..old_offset + len); - old_offset += len; - } - ChangeTag::Insert => { - insertion_ranges[pair].push(new_offset..new_offset + len); - new_offset += len; - } - ChangeTag::Equal => { - old_offset += len; - new_offset += len; - } - } - } - } - - for pair in 0..deletions { - rows.push(DiffRow::from_change( - &changes[index + pair], - &old_code, - deletion_ranges[pair].clone(), - )); - } - - for pair in 0..insertions { - rows.push(DiffRow::from_change( - &changes[index + deletions + pair], - &new_code, - insertion_ranges[pair].clone(), - )); - } - - index += deletions + insertions; - } - } - } - - rows - } - - /// Sets how changed rows are marked. - pub fn indicators(mut self, indicators: DiffIndicators) -> Self { - self.options.indicators = indicators; - self - } - - /// Sets how collapsed regions between hunks render. - pub fn hunk_separator(mut self, separator: HunkSeparator) -> Self { - self.options.separator = separator; - self - } - - /// Shows or hides the line-number gutter. - pub fn line_numbers(mut self, show: bool) -> Self { - self.options.line_numbers = show; - self - } - - /// Replaces the versions and re-diffs them. - pub fn set_versions(&mut self, old: O, new: N, language: Language, cx: &mut Context) - where - O: AsRef, - N: AsRef, - { - self.set_rows(old, new, language); - self.handle.scroll_to_item(0, ScrollStrategy::Top); - // The replaced versions rarely share the old width; start at the left. - let offset = ScrollbarHandle::offset(&self.handle); - ScrollbarHandle::set_offset(&self.handle, point(Pixels::ZERO, offset.y)); - cx.notify(); - } - - /// The diff rows. - pub fn rows(&self) -> &[DiffRow] { - &self.rows - } - - /// Scrolls the first added or removed row to the top of the view. - pub fn scroll_to_first_change(&self) { - let Some(row) = self - .rows - .iter() - .position(|row| matches!(row.kind, DiffRowKind::Added | DiffRowKind::Removed)) - else { - return; - }; - self.handle.scroll_to_item(row, ScrollStrategy::Top); - } - - /// Overrides the accessibility label of the view. - pub fn accessibility_label(mut self, label: L) -> Self - where - L: Into, - { - self.a11y_label = Some(label.into()); - self - } -} - -impl Render for DiffViewState { - fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { - let text_size = rems(0.75).to_pixels(window.rem_size()); - - let id = self.id.clone(); - let state = cx.entity(); - let row_count = self.rows.len(); - let options = self.options; - let widest_row = self.widest_row; - - let mut rows = uniform_list((id.clone(), "rows"), row_count, { - move |range, _window, cx| { - let diff = state.read(cx); - range - .map(|row_index| { - render_row( - &diff.rows[row_index], - &diff.row_layouts[row_index], - row_index, - options, - text_size, - cx, - ) - }) - .collect() - } - }) - .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained) - .with_width_from_item(widest_row) - .track_scroll(&self.handle) - .h_full(); - - // Lock each gesture to its initial axis - rows.interactivity().base_style.restrict_scroll_to_axis = Some(true); - - div() - .id((id.clone(), "view")) - .relative() - .size_full() - .text_xs() - .when_some(self.a11y_label.clone(), |view, label| { - view.aria_label(label) - }) - .child(rows) - .child( - Scrollbar::vertical((self.id.clone(), "v-scrollbar"), self.handle.clone()) - .visibility(ScrollbarVisibility::Platform), - ) - .child( - Scrollbar::horizontal((self.id.clone(), "h-scrollbar"), self.handle.clone()) - .visibility(ScrollbarVisibility::Platform), - ) - } -} - -fn render_row( - row: &DiffRow, - layout: &RowLayout, - row_index: usize, - options: DiffViewOptions, - text_size: Pixels, - cx: &App, -) -> gpui::AnyElement { - let theme = cx.theme(); - let mono_font = theme.mono_font; - let colors = theme.colors; - let ramps = theme.ramps; - let line_height = text_size * CODE_LINE_HEIGHT; - let char_width = text_size * MONO_ADVANCE_RATIO; - - let frame = div() - .debug_selector(move || format!("diff-row-{row_index}")) - .id(layout.id.clone()) - .w_full() - .h(line_height) - .font_family(mono_font) - .text_xs() - .overflow_hidden(); - - if row.kind == DiffRowKind::Hunk { - let content = match options.separator { - HunkSeparator::LineInfo => { - SharedString::from(format!("{} unchanged lines", row.hidden_lines)) - } - HunkSeparator::Metadata => row.header.clone(), - HunkSeparator::Simple => SharedString::from("···"), - }; - - return frame - .flex() - .items_center() - .text_color(colors.muted_foreground) - .when( - options.indicators == DiffIndicators::Classic, - |row_element| row_element.child(div().w(CODE_GUTTER_WIDTH).flex_none()), - ) - .when(options.line_numbers, |row_element| { - row_element.child(div().w(CODE_GUTTER_WIDTH).flex_none()) - }) - .when( - options.indicators == DiffIndicators::Bars && !options.line_numbers, - |row_element| { - row_element.child( - div() - .flex_none() - .border_l(CHANGE_BAR_WIDTH) - .border_color(gpui::transparent_black()), - ) - }, - ) - .child(div().flex_none().ml_2().child(content)) - .into_any_element(); - } - - let change_color = match row.kind { - DiffRowKind::Added => ramps.success.base, - DiffRowKind::Removed => ramps.destructive.base, - DiffRowKind::Context | DiffRowKind::Hunk => gpui::transparent_black(), - }; - - let wash = match row.kind { - DiffRowKind::Added => Some(wash(ramps.success.base)), - DiffRowKind::Removed => Some(wash(ramps.destructive.base)), - DiffRowKind::Context | DiffRowKind::Hunk => None, - }; - - let mut text = String::new(); - let mut spans: Vec<(Range, Role)> = Vec::new(); - - for span in &row.content.spans { - let start = text.len(); - text.push_str(&span.text); - if span.role != Role::Text { - spans.push((start..text.len(), span.role)); - } - } - - let mut boundaries: Vec = spans - .iter() - .flat_map(|(range, _)| [range.start, range.end]) - .chain( - row.changed_ranges - .iter() - .flat_map(|range| [range.start, range.end]), - ) - .collect(); - - boundaries.sort_unstable(); - boundaries.dedup(); - - let mut highlights: Vec<(std::ops::Range, HighlightStyle)> = Vec::new(); - let mut span_ix = 0; - - for window in boundaries.windows(2) { - let (start, end) = (window[0], window[1]); - while span_ix < spans.len() && spans[span_ix].0.end <= start { - span_ix += 1; - } - - let mut segment = HighlightStyle::default(); - if let Some((range, role)) = spans.get(span_ix) - && range.contains(&start) - && *role != Role::Text - { - segment = segment.highlight(HighlightStyle { - color: Some(role.color(colors, ramps)), - ..Default::default() - }); - } - - if row - .changed_ranges - .iter() - .any(|range| range.contains(&start)) - { - segment = segment.highlight(HighlightStyle { - background_color: Some(wash_strong(change_color)), - ..Default::default() - }); - } - - highlights.push((start..end, segment)); - } - - let style = TextStyle { - color: colors.foreground, - font_family: SharedString::from(mono_font), - font_size: text_size.into(), - line_height: line_height.into(), - ..Default::default() - }; - - frame - .flex() - .items_center() - .when_some(wash, |row_element, tint| row_element.bg(tint)) - .when( - options.indicators == DiffIndicators::Classic, - |row_element| { - row_element.child(gutter_cell( - cx, - if row.kind == DiffRowKind::Context { - gpui::transparent_black() - } else { - change_color - }, - match row.kind { - DiffRowKind::Added => "+", - DiffRowKind::Removed => "-", - _ => "", - }, - )) - }, - ) - .when(options.line_numbers, |row_element| { - row_element.child( - gutter_cell( - cx, - colors.muted_foreground, - row.new_number - .or(row.old_number) - .map(|number| number.to_string()) - .unwrap_or_default(), - ) - .w(CODE_GUTTER_WIDTH) - .whitespace_nowrap() - .bg(match row.kind { - DiffRowKind::Context => wash_gutter(&colors), - _ => wash_strong(change_color), - }) - .when(options.indicators == DiffIndicators::Bars, |number| { - number.border_l(CHANGE_BAR_WIDTH).border_color(change_color) - }), - ) - }) - .when( - options.indicators == DiffIndicators::Bars && !options.line_numbers, - |row_element| { - row_element.child( - div() - .h_full() - .flex_none() - .border_l(CHANGE_BAR_WIDTH) - .border_color(change_color), - ) - }, - ) - .child( - div() - .flex_none() - .ml_2() - .w(char_width * layout.char_count as f32) - .whitespace_nowrap() - .child(gpui::StyledText::new(text).with_default_highlights(&style, highlights)), - ) - .into_any_element() -} diff --git a/crates/ui/src/components/dropdown_menu.rs b/crates/ui/src/components/dropdown_menu.rs index eaf59ef..26f5aea 100644 --- a/crates/ui/src/components/dropdown_menu.rs +++ b/crates/ui/src/components/dropdown_menu.rs @@ -242,124 +242,6 @@ impl RenderOnce for DropdownMenu { let trigger_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None)); let chevron_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None)); - let main = h_flex() - .id(self.id.clone()) - .debug_selector({ - let id = self.id.clone(); - move || id.to_string() - }) - .justify_center() - .h_full() - .when(icon_only, |zone| zone.w_full()) - .gap_2() - .line_height(relative(1.0)) - .control_text(self.size) - .text_color(foreground) - .role(Role::Button) - .when_some(a11y_label, |zone, label| zone.aria_label(label)) - .aria_expanded(self.open) - .when(!icon_only, |zone| zone.control_padding_x(self.size)) - .when(split, |zone| zone.rounded_l(radius)) - .when(!split, |zone| { - zone.rounded(radius) - .when(self.open, |zone| zone.bg(pressed)) - }) - .when(!icon_only && !split, |zone| { - zone.child( - icon(IconRole::ChevronDown) - .size(self.size.dense_icon_rems()) - .color(foreground), - ) - }) - .child( - h_flex() - .gap_2() - .when(self.loading, |content| content.invisible()) - .when_some(self.icon, |content, icon| { - content.child(icon.size(self.size.icon_rems()).color(foreground)) - }) - .when_some(self.label, |content, label| content.child(label)), - ) - .when(self.loading, |zone| { - zone.child( - h_flex().absolute().inset_0().justify_center().child( - Spinner::new((self.id.clone(), "spinner")) - .with_size(self.size) - .color(foreground), - ), - ) - }); - - let main = if inert { - main - } else { - main.track_focus(&focus) - .cursor_pointer() - .hover(move |style| style.bg(hover)) - .active(move |style| style.bg(pressed)) - .on_click({ - let on_click = self.on_click; - let on_open = on_open.clone(); - let keyboard_open = keyboard_open.clone(); - let open = self.open; - move |event, window, cx| match (on_click.as_ref(), event) { - (Some(on_click), _) => on_click(event, window, cx), - (None, ClickEvent::Keyboard(_)) => { - keyboard_open.update(cx, |keyboard_open, _| *keyboard_open = true); - on_open(!open, window, cx); - } - (None, _) => {} - } - }) - .on_key_down({ - let on_open = on_open.clone(); - let keyboard_open = keyboard_open.clone(); - move |event: &KeyDownEvent, window, cx| { - if event.keystroke.key == "down" { - keyboard_open.update(cx, |keyboard_open, _| *keyboard_open = true); - on_open(true, window, cx); - cx.stop_propagation(); - } - } - }) - }; - - let chevron_zone = h_flex() - .id((self.id.clone(), "chevron")) - .debug_selector({ - let id = self.id.clone(); - move || format!("{id}-chevron") - }) - .relative() - .h_full() - .control_dense_padding_x(self.size) - .rounded_r(radius) - .rounded_l_none() - .border_l_1() - .border_color(border) - .when(self.open, |zone| zone.bg(pressed)) - .when(!inert, |zone| { - zone.cursor_pointer() - .hover(move |style| style.bg(hover)) - .active(move |style| style.bg(pressed)) - }) - .child( - icon(IconRole::ChevronDown) - .size(self.size.dense_icon_rems()) - .color(foreground), - ) - .child( - canvas( - { - let cell = chevron_bounds.clone(); - move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) - }, - |_, _, _, _| {}, - ) - .absolute() - .inset_0(), - ); - let trigger = h_flex() .debug_selector({ let id = self.id.clone(); @@ -377,13 +259,129 @@ impl RenderOnce for DropdownMenu { .track_focus(&focus) .focus_visible(move |style| style.shadow(focus_ring(ring))) }) - .child(main); - - let trigger = if split { - trigger.child(chevron_zone) - } else { - trigger - }; + .child( + h_flex() + .id(self.id.clone()) + .debug_selector({ + let id = self.id.clone(); + move || id.to_string() + }) + .justify_center() + .h_full() + .when(icon_only, |zone| zone.w_full()) + .gap_2() + .line_height(relative(1.0)) + .control_text(self.size) + .text_color(foreground) + .role(Role::Button) + .when_some(a11y_label, |zone, label| zone.aria_label(label)) + .aria_expanded(self.open) + .when(!icon_only, |zone| zone.control_padding_x(self.size)) + .when(split, |zone| zone.rounded_l(radius)) + .when(!split, |zone| { + zone.rounded(radius) + .when(self.open, |zone| zone.bg(pressed)) + }) + .when(!icon_only && !split, |zone| { + zone.child( + icon(IconRole::ChevronDown) + .size(self.size.dense_icon_rems()) + .color(foreground), + ) + }) + .child( + h_flex() + .gap_2() + .when(self.loading, |content| content.invisible()) + .when_some(self.icon, |content, icon| { + content.child(icon.size(self.size.icon_rems()).color(foreground)) + }) + .when_some(self.label, |content, label| content.child(label)), + ) + .when(self.loading, |zone| { + zone.child( + h_flex().absolute().inset_0().justify_center().child( + Spinner::new((self.id.clone(), "spinner")) + .with_size(self.size) + .color(foreground), + ), + ) + }) + .when(!inert, |main| { + main.track_focus(&focus) + .cursor_pointer() + .hover(move |style| style.bg(hover)) + .active(move |style| style.bg(pressed)) + .on_click({ + let on_click = self.on_click; + let on_open = on_open.clone(); + let keyboard_open = keyboard_open.clone(); + let open = self.open; + move |event, window, cx| match (on_click.as_ref(), event) { + (Some(on_click), _) => on_click(event, window, cx), + (None, ClickEvent::Keyboard(_)) => { + keyboard_open.update(cx, |keyboard_open, _| { + *keyboard_open = true; + }); + on_open(!open, window, cx); + } + (None, _) => {} + } + }) + .on_key_down({ + let on_open = on_open.clone(); + let keyboard_open = keyboard_open.clone(); + move |event: &KeyDownEvent, window, cx| { + if event.keystroke.key == "down" { + keyboard_open.update(cx, |keyboard_open, _| { + *keyboard_open = true; + }); + on_open(true, window, cx); + cx.stop_propagation(); + } + } + }) + }), + ) + .when(split, |trigger| { + trigger.child( + h_flex() + .id((self.id.clone(), "chevron")) + .debug_selector({ + let id = self.id.clone(); + move || format!("{id}-chevron") + }) + .relative() + .h_full() + .control_dense_padding_x(self.size) + .rounded_r(radius) + .rounded_l_none() + .border_l_1() + .border_color(border) + .when(self.open, |zone| zone.bg(pressed)) + .when(!inert, |zone| { + zone.cursor_pointer() + .hover(move |style| style.bg(hover)) + .active(move |style| style.bg(pressed)) + }) + .child( + icon(IconRole::ChevronDown) + .size(self.size.dense_icon_rems()) + .color(foreground), + ) + .child( + canvas( + { + let cell = chevron_bounds.clone(); + move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) + }, + |_, _, _, _| {}, + ) + .absolute() + .inset_0(), + ), + ) + }); let items = if self.open { self.items diff --git a/crates/ui/src/components/empty_state.rs b/crates/ui/src/components/empty_state.rs index 2bccb08..323cd29 100644 --- a/crates/ui/src/components/empty_state.rs +++ b/crates/ui/src/components/empty_state.rs @@ -11,8 +11,8 @@ use gpui::prelude::FluentBuilder as _; use gpui::{ - App, IntoElement, ParentElement as _, RenderOnce, SharedString, StyleRefinement, Styled as _, - Window, div, rems, + AnyElement, App, IntoElement, ParentElement as _, RenderOnce, SharedString, StyleRefinement, + Styled as _, Window, div, rems, }; use crate::components::common::{StyledExt, v_flex}; @@ -45,6 +45,19 @@ impl EmptyState { } } + /// The empty state centered in the full available space. + pub fn centered(message: L) -> AnyElement + where + L: Into, + { + v_flex() + .size_full() + .items_center() + .justify_center() + .child(Self::new(message)) + .into_any_element() + } + /// Sets a large muted icon above the headline. pub fn icon(mut self, icon: I) -> Self where diff --git a/crates/ui/src/components/grain.rs b/crates/ui/src/components/grain.rs index 36c0643..7e047a7 100644 --- a/crates/ui/src/components/grain.rs +++ b/crates/ui/src/components/grain.rs @@ -29,11 +29,6 @@ const TILE_PX: u32 = 256; #[must_use] pub struct Grain; -/// Creates a grain overlay. -pub fn grain() -> Grain { - Grain -} - impl RenderOnce for Grain { fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { let texture = texture(); @@ -74,6 +69,11 @@ impl RenderOnce for Grain { } } +/// Creates a grain overlay. +pub fn grain() -> Grain { + Grain +} + /// Returns the shared noise tile so every tile reuses one atlas entry. fn texture() -> Arc { static TEXTURE: OnceLock> = OnceLock::new(); diff --git a/crates/ui/src/components/highlight.rs b/crates/ui/src/components/highlight.rs index 6dcd45d..3d293f3 100644 --- a/crates/ui/src/components/highlight.rs +++ b/crates/ui/src/components/highlight.rs @@ -28,14 +28,6 @@ thread_local! { RefCell::new(HashMap::new()); } -/// A grammar's parser and compiled highlight query. -#[cfg(not(target_arch = "wasm32"))] -struct Highlighter { - parser: tree_sitter::Parser, - query: tree_sitter::Query, - roles: Vec>, -} - /// A language source can highlight as. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Language { @@ -64,6 +56,14 @@ pub enum Role { Escape, } +/// A grammar's parser and compiled highlight query. +#[cfg(not(target_arch = "wasm32"))] +struct Highlighter { + parser: tree_sitter::Parser, + query: tree_sitter::Query, + roles: Vec>, +} + /// A run of text sharing one role. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct Span { diff --git a/crates/ui/src/components/input.rs b/crates/ui/src/components/input.rs index b5a9f40..07daf1e 100644 --- a/crates/ui/src/components/input.rs +++ b/crates/ui/src/components/input.rs @@ -12,7 +12,7 @@ //! use ui::input::{Input, InputState, bind_input_keys}; //! //! # let mut cx: gpui::App = unimplemented!(); -//! bind_input_keys(&mut cx, None); +//! bind_input_keys(&mut cx); //! //! let state = InputState::builder() //! .text("Ada Lovelace") @@ -131,10 +131,9 @@ actions!( /// The keybindings [`bind_input_keys`] registers on the application. /// /// A `None` field leaves its action unbound. Start from [`InputBindings::default`] -/// to rebind one action and keep the platform defaults, or from -/// [`InputBindings::empty`] to bind only what you set. +/// to rebind one action and keep the platform defaults. #[derive(Clone, Debug)] -pub struct InputBindings { +pub(crate) struct InputBindings { pub escape: Option, pub submit: Option, pub secondary_submit: Option, @@ -260,43 +259,6 @@ impl Default for InputBindings { } impl InputBindings { - /// A table with every key unbound, for building custom bindings. - pub fn empty() -> Self { - Self { - escape: None, - submit: None, - secondary_submit: None, - insert_newline: None, - backspace: None, - delete: None, - delete_word_left: None, - delete_word_right: None, - delete_to_beginning_of_line: None, - left: None, - right: None, - up: None, - down: None, - select_left: None, - select_right: None, - select_up: None, - select_down: None, - word_left: None, - word_right: None, - select_word_left: None, - select_word_right: None, - home: None, - end: None, - select_home: None, - select_end: None, - select_all: None, - copy: None, - cut: None, - paste: None, - undo: None, - redo: None, - } - } - /// Collects the table into keybindings. pub(crate) fn into_bindings(self) -> Vec { let mut bindings: Vec = [ @@ -508,55 +470,6 @@ impl HistoryEntry { } } -/// The application-owned state of a text field that [`Input`] renders. -pub struct InputState { - text: String, - /// The caret's byte offset. - cursor: usize, - /// The byte offset the selection extends from. - anchor: usize, - /// The byte range of in-progress IME composition, if any. - marked_range: Option>, - /// Whether the field had focus at the last paint, for focus transitions. - focused: bool, - focus_handle: gpui::FocusHandle, - /// The key-down handler, bound to this entity with `cx.listener`. - key_down_handler: KeyDownHandler, - /// The mouse-down handler, bound to this entity with `cx.listener`. - mouse_down_handler: MouseDownHandler, - /// Whether a drag-select is in progress. - dragging: bool, - /// Patch history. `redo_stack` holds undone entries awaiting redo. - undo_stack: Vec, - redo_stack: Vec, - /// Consecutive edits within this interval merge into one undo entry. - group_interval: Duration, - /// When set, user edits are refused; focus, movement, selection, and copy still work. - read_only: bool, - /// When set, the field is a password field. - password: bool, - /// Whether a password field currently shows its content. - revealed: bool, - /// Whether the field holds multiple lines of text. - multiline: bool, - /// Which keystroke submits a multiline field. - submit_on: SubmitOn, - /// The x the caret keeps across vertical movement, reset on any other move. - goal_x: Option, - /// Content scroll inside the field: x for single-line, y for multiline, clamped at paint. - scroll_offset: gpui::Point, - /// Set by every caret-affecting change. - scroll_to_caret_pending: bool, - /// Bumped on every edit. - caret_epoch: usize, - /// When the current caret epoch started. - caret_epoch_started: Instant, - /// The shaped line and element bounds, recorded during each paint. - layout: Option, - /// The last shaped buffer, reused while no shaping input changed. - shaped_cache: std::cell::RefCell>, -} - /// Everything `shape_text` consumes, for cache reuse between frames. #[derive(Clone, PartialEq)] struct ShapeCacheKey { @@ -567,8 +480,6 @@ struct ShapeCacheKey { color: gpui::Hsla, } -impl EventEmitter for InputState {} - /// Builder for [`InputState`] settings that are fixed at creation. #[derive(Default)] pub struct InputStateBuilder { @@ -628,6 +539,57 @@ impl InputStateBuilder { } } +/// The application-owned state of a text field that [`Input`] renders. +pub struct InputState { + text: String, + /// The caret's byte offset. + cursor: usize, + /// The byte offset the selection extends from. + anchor: usize, + /// The byte range of in-progress IME composition, if any. + marked_range: Option>, + /// Whether the field had focus at the last paint, for focus transitions. + focused: bool, + focus_handle: gpui::FocusHandle, + /// The key-down handler, bound to this entity with `cx.listener`. + key_down_handler: KeyDownHandler, + /// The mouse-down handler, bound to this entity with `cx.listener`. + mouse_down_handler: MouseDownHandler, + /// Whether a drag-select is in progress. + dragging: bool, + /// Patch history. `redo_stack` holds undone entries awaiting redo. + undo_stack: Vec, + redo_stack: Vec, + /// Consecutive edits within this interval merge into one undo entry. + group_interval: Duration, + /// When set, user edits are refused; focus, movement, selection, and copy still work. + read_only: bool, + /// When set, the field is a password field. + password: bool, + /// Whether a password field currently shows its content. + revealed: bool, + /// Whether the field holds multiple lines of text. + multiline: bool, + /// Which keystroke submits a multiline field. + submit_on: SubmitOn, + /// The x the caret keeps across vertical movement, reset on any other move. + goal_x: Option, + /// Content scroll inside the field: x for single-line, y for multiline, clamped at paint. + scroll_offset: gpui::Point, + /// Set by every caret-affecting change. + scroll_to_caret_pending: bool, + /// Bumped on every edit. + caret_epoch: usize, + /// When the current caret epoch started. + caret_epoch_started: Instant, + /// The shaped line and element bounds, recorded during each paint. + layout: Option, + /// The last shaped buffer, reused while no shaping input changed. + shaped_cache: std::cell::RefCell>, +} + +impl EventEmitter for InputState {} + impl InputState { fn new_inner(cx: &mut Context) -> Self { Self { @@ -2517,14 +2479,8 @@ impl RenderOnce for Input { } /// Registers the input keybindings on the application, once at startup. -/// -/// Pass `None` for the platform defaults or an [`InputBindings`] table for -/// custom ones. -pub fn bind_input_keys(cx: &mut App, bindings: B) -where - B: Into>, -{ - cx.bind_keys(bindings.into().unwrap_or_default().into_bindings()); +pub fn bind_input_keys(cx: &mut App) { + cx.bind_keys(InputBindings::default().into_bindings()); } /// The row holding `display`. diff --git a/crates/ui/src/components/kbd.rs b/crates/ui/src/components/kbd.rs index a56cdf2..b9529fa 100644 --- a/crates/ui/src/components/kbd.rs +++ b/crates/ui/src/components/kbd.rs @@ -3,23 +3,19 @@ //! # Examples //! //! ```no_run -//! use gpui::{Keystroke, ParentElement as _}; -//! use ui::kbd::{Kbd, KbdGroup}; +//! use gpui::Keystroke; +//! use ui::kbd::Kbd; //! //! let save = Kbd::new(Keystroke::parse("cmd-s").unwrap()); -//! let combo = KbdGroup::new() -//! .child(Kbd::new(Keystroke::parse("ctrl-b").unwrap())) -//! .child(Kbd::new(Keystroke::parse("ctrl-k").unwrap())); //! ``` -use gpui::prelude::FluentBuilder as _; use gpui::{ - Action, AnyElement, App, FocusHandle, InteractiveElement as _, IntoElement, KeyBinding, - KeyContext, Keystroke, OperatingSystem, ParentElement as _, RenderOnce, SharedString, - StyleRefinement, Styled as _, Window, div, relative, + Action, App, InteractiveElement as _, IntoElement, KeyBinding, KeyContext, Keystroke, + OperatingSystem, ParentElement as _, RenderOnce, SharedString, StyleRefinement, Styled as _, + Window, div, relative, }; -use crate::components::common::{StyledExt as _, h_flex}; +use crate::components::common::StyledExt as _; use crate::theme::ActiveTheme as _; /// A key or shortcut shown as a small key cap, like `⌘S` or `Ctrl+S`. @@ -27,7 +23,6 @@ use crate::theme::ActiveTheme as _; #[must_use] pub struct Kbd { stroke: Keystroke, - appearance: bool, style: StyleRefinement, } @@ -42,7 +37,6 @@ impl Kbd { pub fn new(stroke: Keystroke) -> Self { Self { stroke, - appearance: true, style: StyleRefinement::default(), } } @@ -52,12 +46,6 @@ impl Kbd { &self.stroke } - /// When false, paints the formatted shortcut as plain text without the key cap. - pub fn appearance(mut self, appearance: bool) -> Self { - self.appearance = appearance; - self - } - /// Returns a key cap for the highest-precedence binding of `action`. pub fn binding_for_action( action: &dyn Action, @@ -73,23 +61,6 @@ impl Kbd { Self::from_binding(&binding) } - /// Returns a key cap for the binding of `action`. - pub fn binding_for_action_in( - action: &dyn Action, - focus_handle: &FocusHandle, - window: &Window, - ) -> Option { - let binding = window.highest_precedence_binding_for_action_in(action, focus_handle)?; - Self::from_binding(&binding) - } - - /// Returns a key cap for the binding of `action` registered without a key context. - pub fn global_binding_for_action(action: &dyn Action, window: &Window) -> Option { - let binding = window - .highest_precedence_binding_for_action_in_context(action, KeyContext::default())?; - Self::from_binding(&binding) - } - /// Shows the binding's keystroke as the keymap holds it. fn from_binding(binding: &KeyBinding) -> Option { binding.keystrokes().first().map(|stroke| { @@ -102,7 +73,7 @@ impl Kbd { } /// Formats `stroke` for `os`: modifier symbols on macOS, `Ctrl+` words elsewhere. - pub fn format(stroke: &Keystroke, os: OperatingSystem) -> String { + fn format(stroke: &Keystroke, os: OperatingSystem) -> String { let mac = os == OperatingSystem::Mac; let separator = if mac { "" } else { "+" }; let mut parts: Vec<&str> = Vec::new(); @@ -253,60 +224,18 @@ impl RenderOnce for Kbd { let label = SharedString::from(Self::format(&self.stroke, os)); div() - // Lets a test ask whether this shortcut hint was painted this frame. .debug_selector(move || selector) - .when(self.appearance, |key| { - key.flex_none() - .border_1() - .border_color(theme.colors.border) - .bg(theme.colors.muted) - .text_color(theme.colors.muted_foreground) - .py_0p5() - .px_1() - .min_w_5() - .rounded(theme.radius.sm) - .text_center() - .line_height(relative(1.)) - .text_xs() - }) + .flex_none() + .bg(theme.colors.muted) + .text_color(theme.colors.muted_foreground) + .py_0p5() + .px_1() + .min_w_5() + .rounded(theme.radius.sm) + .text_center() + .line_height(relative(1.)) + .text_xs() .refine_style(&self.style) .child(label) } } - -/// A row of key caps, grouping the keys of a multi-key hint. -#[derive(IntoElement, Default)] -#[must_use] -pub struct KbdGroup { - style: StyleRefinement, - children: Vec, -} - -impl KbdGroup { - /// Creates an empty group. - pub fn new() -> Self { - Self::default() - } -} - -impl gpui::ParentElement for KbdGroup { - fn extend(&mut self, elements: impl IntoIterator) { - self.children.extend(elements); - } -} - -impl gpui::Styled for KbdGroup { - fn style(&mut self) -> &mut StyleRefinement { - &mut self.style - } -} - -impl RenderOnce for KbdGroup { - fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { - h_flex() - .flex_none() - .gap_1() - .refine_style(&self.style) - .children(self.children) - } -} diff --git a/crates/ui/src/components/link.rs b/crates/ui/src/components/link.rs deleted file mode 100644 index 1442b3d..0000000 --- a/crates/ui/src/components/link.rs +++ /dev/null @@ -1,154 +0,0 @@ -//! Renders a link that opens a URL or fires a click handler. -//! -//! # Examples -//! -//! ```no_run -//! use ui::link::Link; -//! -//! let docs = Link::new("docs-link") -//! .label("Documentation") -//! .href("https://example.com/docs"); -//! -//! let settings = Link::new("settings-link") -//! .label("Open settings") -//! .on_click(|_event, _window, _cx| println!("open settings")); -//! ``` - -use gpui::prelude::FluentBuilder as _; -use gpui::{ - App, ClickEvent, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, - RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, - Window, -}; - -use crate::components::common::{ControlSizing, Sizable, StyledExt as _, focus_ring, h_flex}; -use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; - -/// The handler called with the [`gpui::ClickEvent`], replacing the default `href` opening. -type ClickHandler = Box; - -/// A hyperlink that opens a URL or fires a click handler. -#[derive(IntoElement)] -#[must_use] -pub struct Link { - id: ElementId, - label: Option, - href: Option, - size: Size, - disabled: bool, - a11y_label: Option, - on_click: Option, - style: StyleRefinement, -} - -impl Link { - /// Creates a link without a label or target. - pub fn new(id: I) -> Self - where - I: Into, - { - Self { - id: id.into(), - label: None, - href: None, - size: Size::default(), - disabled: false, - a11y_label: None, - on_click: None, - style: StyleRefinement::default(), - } - } - - /// Sets the visible label. - pub fn label(mut self, label: L) -> Self - where - L: Into, - { - self.label = Some(label.into()); - self - } - - /// Sets the URL the link opens through the platform. - pub fn href(mut self, href: U) -> Self - where - U: Into, - { - self.href = Some(href.into()); - self - } - - /// Renders the link inert, unfocusable, and dimmed; disabled always wins. - pub fn disabled(mut self, disabled: bool) -> Self { - self.disabled = disabled; - self - } - - /// Overrides the accessibility label, which defaults to the visible label. - pub fn accessibility_label(mut self, label: L) -> Self - where - L: Into, - { - self.a11y_label = Some(label.into()); - self - } - - /// Replaces the default `href` opening with this handler. - pub fn on_click(mut self, handler: F) -> Self - where - F: Fn(&ClickEvent, &mut Window, &mut App) + 'static, - { - self.on_click = Some(Box::new(handler)); - self - } -} - -impl gpui::Styled for Link { - fn style(&mut self) -> &mut StyleRefinement { - &mut self.style - } -} - -impl Sizable for Link { - fn apply_size(&mut self, size: Size) { - self.size = size; - } -} - -impl RenderOnce for Link { - fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { - let theme = cx.theme(); - let colors = theme.colors; - let ramps = theme.ramps; - let size = self.size; - - let on_click = self.on_click; - let href = self.href; - let a11y_label = self.a11y_label.or_else(|| self.label.clone()); - - h_flex() - .id(self.id) - .control_text(size) - .text_color(ramps.primary.base) - .underline() - .refine_style(&self.style) - .role(Role::Link) - .when_some(a11y_label, |link, label| link.aria_label(label)) - .when(self.disabled, |link| link.opacity(DISABLED_OPACITY)) - .when(!self.disabled, |link| { - link.cursor_pointer() - .focusable() - .tab_stop(true) - .hover(move |style| style.text_color(ramps.primary.hover)) - .focus_visible(|style| style.shadow(focus_ring(colors.ring))) - .on_click(move |event, window, cx| match on_click.as_ref() { - Some(on_click) => on_click(event, window, cx), - None => { - if let Some(href) = href.as_ref() { - cx.open_url(href); - } - } - }) - }) - .when_some(self.label, |link, label| link.child(label)) - } -} diff --git a/crates/ui/src/components/list.rs b/crates/ui/src/components/list.rs deleted file mode 100644 index 9523ec3..0000000 --- a/crates/ui/src/components/list.rs +++ /dev/null @@ -1,290 +0,0 @@ -//! Renders a single-selection list of [`ListItem`] rows with keyboard navigation. -//! -//! # Examples -//! -//! ```no_run -//! use ui::list::{List, ListItem}; -//! -//! let folders = List::new("folders") -//! .selected(Some(0)) -//! .items(|_, _| { -//! vec![ -//! ListItem::new("documents", "Documents").detail("24 files"), -//! ListItem::new("downloads", "Downloads"), -//! ] -//! }) -//! .on_change(|_selected, _window, _cx| println!("selection changed")); -//! ``` - -use std::rc::Rc; - -use gpui::prelude::FluentBuilder; -use gpui::{ - AnyElement, App, ElementId, FocusHandle, InteractiveElement as _, IntoElement, KeyDownEvent, - ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, - StyleRefinement, Styled as _, Window, div, rems, -}; - -use crate::common::focus_handle; -use crate::components::common::{ - StyledExt as _, nav_key, paint_selectable_row, selectable_label_color, v_flex, -}; -use crate::icons::Icon; -use crate::theme::ActiveTheme as _; - -/// The change reporter, fired with the next selection by pointer and keys. -type ChangeHandler = Rc, &mut Window, &mut App)>; -/// The row builder, run during render. -type ItemsFn = Box Vec>; - -/// One row of a [`List`]. -#[must_use] -pub struct ListItem { - key: ElementId, - label: SharedString, - icon: Option, - detail: Option, - disabled: bool, -} - -impl ListItem { - /// Creates a row shown as `label`, identified by `key`. - pub fn new(key: K, label: L) -> Self - where - K: Into, - L: Into, - { - Self { - key: key.into(), - label: label.into(), - icon: None, - detail: None, - disabled: false, - } - } - - /// Shows an icon leading the label, a role or any custom [`crate::icons::IconNamed`]. - pub fn icon(mut self, icon: I) -> Self - where - I: Into, - { - self.icon = Some(icon.into()); - self - } - - /// Shows muted trailing text. - pub fn detail(mut self, detail: D) -> Self - where - D: Into, - { - self.detail = Some(detail.into()); - self - } - - /// Renders the row dimmed; clicks and keyboard skip it. - pub fn disabled(mut self, disabled: bool) -> Self { - self.disabled = disabled; - self - } -} - -// ListItem is a data builder, not an element, adopt the combinators explicitly. -impl FluentBuilder for ListItem {} - -/// A single-selection list of [`ListItem`] rows. -#[derive(IntoElement)] -#[must_use] -pub struct List { - id: ElementId, - selected: Option, - a11y_label: Option, - on_change: Option, - items: Option, - style: StyleRefinement, -} - -impl List { - /// Creates a list with nothing selected. - pub fn new(id: I) -> Self - where - I: Into, - { - Self { - id: id.into(), - selected: None, - a11y_label: None, - on_change: None, - items: None, - style: StyleRefinement::default(), - } - } - - /// Sets the current selection. - pub fn selected(mut self, selected: Option) -> Self { - self.selected = selected; - self - } - - /// Reports the next selection, from clicks and keys alike. - pub fn on_change(mut self, handler: F) -> Self - where - F: Fn(Option, &mut Window, &mut App) + 'static, - { - self.on_change = Some(Rc::new(handler)); - self - } - - /// Sets the rows; the closure runs during render and must not mutate entities or notify. - pub fn items(mut self, items: F) -> Self - where - F: Fn(&mut Window, &mut App) -> Vec + 'static, - { - self.items = Some(Box::new(items)); - self - } - - /// Overrides the accessibility label, which defaults to the id. - pub fn accessibility_label(mut self, label: L) -> Self - where - L: Into, - { - self.a11y_label = Some(label.into()); - self - } -} - -impl gpui::Styled for List { - fn style(&mut self) -> &mut StyleRefinement { - &mut self.style - } -} - -impl RenderOnce for List { - fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { - let items = match self.items { - Some(build) => build(window, cx), - None => Vec::new(), - }; - - let selectable: Vec = items - .iter() - .enumerate() - .filter(|(_, item)| !item.disabled) - .map(|(index, _)| index) - .collect(); - - let focus = focus_handle(&self.id, window, cx); - - let label = self - .a11y_label - .clone() - .unwrap_or_else(|| SharedString::from(self.id.to_string())); - - let rows: Vec = items - .iter() - .enumerate() - .map(|(index, item)| { - item.render_row( - cx, - index, - items.len(), - self.selected == Some(index), - &self.on_change, - &focus, - ) - }) - .collect(); - - v_flex() - .id(self.id) - .gap_0p5() - .text_sm() - .refine_style(&self.style) - .track_focus(&focus) - .focusable() - .tab_stop(true) - .role(Role::List) - .aria_label(label) - .on_key_down({ - let selected = self.selected; - let on_change = self.on_change.clone(); - - move |event: &KeyDownEvent, window, cx| { - if nav_key(&selectable, selected, &event.keystroke.key, |next| { - if let Some(on_change) = &on_change { - on_change(next, window, cx); - } - }) { - cx.stop_propagation(); - } - } - }) - .children(rows) - } -} - -impl ListItem { - fn render_row( - &self, - cx: &App, - index: usize, - count: usize, - selected: bool, - on_change: &Option, - focus: &FocusHandle, - ) -> AnyElement { - let theme = cx.theme(); - let label_color = selectable_label_color(cx, selected, self.disabled); - let disabled = self.disabled; - - div() - .id((self.key.clone(), "list-item")) - .flex() - .items_center() - .gap_2() - .px_2() - .py_1() - .min_h_8() - .rounded(theme.radius.sm) - .role(Role::ListItem) - .aria_selected(selected) - .aria_position_in_set(index + 1) - .aria_size_of_set(count) - .map(|row| paint_selectable_row(cx, row, selected, disabled)) - .when(!disabled, |row| { - row.cursor_pointer().on_click({ - let on_change = on_change.clone(); - let focus = focus.clone(); - move |_, window, cx| { - window.focus(&focus, cx); - if let Some(on_change) = &on_change { - on_change(Some(index), window, cx); - } - } - }) - }) - .when_some(self.icon.clone(), |row, icon| { - row.child(icon.size(rems(1.0)).color(label_color)) - }) - .child( - div() - .flex_1() - .text_color(label_color) - .child(self.label.clone()), - ) - .when_some(self.detail.clone(), |row, detail| { - row.child( - div() - .flex_none() - .text_sm() - .text_color(if selected { - theme.colors.primary_foreground - } else { - theme.colors.muted_foreground - }) - .child(detail), - ) - }) - .into_any_element() - } -} diff --git a/crates/ui/src/components/markdown.rs b/crates/ui/src/components/markdown.rs index 068b502..60a2479 100644 --- a/crates/ui/src/components/markdown.rs +++ b/crates/ui/src/components/markdown.rs @@ -19,8 +19,6 @@ //! fn notes(cx: &mut App) -> TextView { //! let state = cx.new(|_| MarkdownViewState::new("notes", "# Notes\n- [x] shipped")); //! TextView::new(&state) -//! .on_link_click(|destination, _window, _cx| println!("{destination}")) -//! .on_task_toggle(|index, checked, _window, _cx| println!("{index}: {checked}")) //! } //! ``` @@ -29,7 +27,6 @@ use std::collections::HashMap; use std::hash::{DefaultHasher, Hash, Hasher}; use std::ops::Range; use std::rc::Rc; -use std::sync::Arc; use gpui::prelude::FluentBuilder as _; use gpui::{ @@ -56,11 +53,6 @@ const BODY_LINE_HEIGHT: f32 = 1.6; /// The key context the text view declares while it holds focus. pub const TEXT_VIEW_CONTEXT: &str = "TextView"; -/// The callback a view invokes when the user clicks a markdown link. -pub type LinkClickHandler = Arc; -/// The callback a view invokes when the user toggles a task checkbox. -pub type TaskToggleHandler = Arc; - actions!(text_view, [Copy]); /// A heading level, 1 to 6. @@ -191,6 +183,94 @@ impl MarkdownBlock { self.hash(&mut hasher); hasher.finish() } + + /// The block's selectable text units, in render order. + fn block_text_units(&self) -> Vec { + match self { + MarkdownBlock::Heading { spans, .. } => vec![spans_text_of(spans)], + MarkdownBlock::Paragraph { items, .. } | MarkdownBlock::ListItem { items, .. } => { + let mut units: Vec = Vec::new(); + for item in items { + match item { + InlineItem::Text(span) => match units.last_mut() { + // Consecutive text items share the unit between images. + Some(unit) => unit.push_str(&span.text), + None => units.push(span.text.as_ref().to_string()), + }, + // An image starts the next unit; the render emits no + // element for it. + InlineItem::Image { .. } => units.push(String::new()), + } + } + units + } + MarkdownBlock::Code { lines, .. } => { + lines.lines.iter().map(|line| line.text()).collect() + } + MarkdownBlock::Table { table, .. } => table + .rows + .iter() + .flat_map(|row| row.cells.iter()) + .map(|cell| spans_text_of(&cell.spans)) + .collect(), + MarkdownBlock::Image { .. } | MarkdownBlock::ThematicBreak { .. } => Vec::new(), + } + } + + /// Renders one parsed block as a list row. + fn render_block(&self, block_index: usize, ctx: &BlockContext, cx: &App) -> AnyElement { + let gap = rems(0.75); + + match self { + MarkdownBlock::Heading { + level, + spans, + indent, + quote, + } => heading_row( + *level, + spans, + *indent, + *quote, + if block_index == 0 { + Rems::ZERO + } else { + rems(0.375) + }, + ctx, + cx, + ), + MarkdownBlock::Paragraph { + items, + indent, + quote, + } => text_row(items, *indent, *quote, gap, None, ctx, cx), + MarkdownBlock::ListItem { + marker, + items, + indent, + quote, + } => text_row(items, *indent, *quote, rems(0.2), Some(*marker), ctx, cx), + MarkdownBlock::Image { + source, + alt, + indent, + quote, + } => image_row(source, alt, *indent, *quote, ctx, cx), + MarkdownBlock::Code { + language, + lines, + indent, + quote, + } => code_row(lines, language.as_ref(), *indent, *quote, ctx, cx), + MarkdownBlock::ThematicBreak { indent, quote } => rule_row(*indent, *quote, ctx, cx), + MarkdownBlock::Table { + table, + indent, + quote, + } => table_row(table, *indent, *quote, ctx, cx), + } + } } /// One run of inline text sharing a style. @@ -235,8 +315,6 @@ pub struct MarkdownViewState { /// Drives the vertical scroll of the virtualized block list. handle: ListState, a11y_label: Option, - link_handler: Option, - task_toggle_handler: Option, /// `(anchor, head)` in the order they were set, over the rendered text. selection: Option<(usize, usize)>, /// Whether a drag is still extending the selection. @@ -265,8 +343,6 @@ impl MarkdownViewState { highlight_code: true, handle: ListState::new(count, ListAlignment::Top, CODE_OVERSCROLL_MAX), a11y_label: None, - link_handler: None, - task_toggle_handler: None, selection: None, selecting: false, focus_handle: None, @@ -360,34 +436,6 @@ impl MarkdownViewState { self } - /// Invokes `handler` when the user clicks a link, instead of opening it. - pub fn on_link_click(mut self, handler: F) -> Self - where - F: Fn(&SharedString, &mut Window, &mut App) + 'static, - { - self.link_handler = Some(Arc::new(handler)); - self - } - - /// Replaces the link click handler. - pub fn set_link_handler(&mut self, handler: LinkClickHandler) { - self.link_handler = Some(handler); - } - - /// Invokes `handler(block, checked)` when the user toggles a task checkbox. - pub fn on_task_toggle(mut self, handler: F) -> Self - where - F: Fn(usize, bool, &mut Window, &mut App) + 'static, - { - self.task_toggle_handler = Some(Arc::new(handler)); - self - } - - /// Replaces the task toggle handler. - pub fn set_task_toggle_handler(&mut self, handler: TaskToggleHandler) { - self.task_toggle_handler = Some(handler); - } - /// Selects a range over the rendered text, endpoints in byte offsets. pub fn select_range(&mut self, start: usize, end: usize, cx: &mut Context) { self.selection = Some((start, end)); @@ -430,8 +478,6 @@ impl Render for MarkdownViewState { let focus_handle = self.focus_handle(cx); let frame = std::rc::Rc::new(ViewFrame { state: state.clone(), - link_handler: self.link_handler.clone(), - task_toggle: self.task_toggle_handler.clone(), selection: self.selection(), focus_handle, pressed_on_piece: std::rc::Rc::new(std::cell::Cell::new(false)), @@ -455,7 +501,7 @@ impl Render for MarkdownViewState { block_index, block_id, }; - render_block(block, block_index, &ctx, cx) + block.render_block(block_index, &ctx, cx) } None => div().into_any_element(), } @@ -481,8 +527,6 @@ impl Render for MarkdownViewState { /// The per-frame context the view's renderers wire themselves from. struct ViewFrame { state: Entity, - link_handler: Option, - task_toggle: Option, /// The selection over the rendered text, endpoints in document order. selection: Option<(usize, usize)>, focus_handle: gpui::FocusHandle, @@ -525,7 +569,6 @@ impl BlockContext<'_> { Some(PieceContext { state: self.frame.state.clone(), - link_handler: self.frame.link_handler.clone(), doc_range: piece.range.clone(), selected, pressed_on_piece: self.frame.pressed_on_piece.clone(), @@ -536,7 +579,6 @@ impl BlockContext<'_> { /// What one selectable text element wires itself from. struct PieceContext { state: Entity, - link_handler: Option, /// The piece's byte range in the rendered text. doc_range: Range, /// The selection overlap, in piece-local bytes. @@ -579,7 +621,7 @@ impl TextDocument { .iter() .position(|piece| piece.block_index != block_index) .map_or(self.pieces.len(), |offset| piece_ix + offset); - let units = block_text_units(block); + let units = block.block_text_units(); for piece in &self.pieces[piece_ix..block_end] { let Some(unit) = units.get(piece.sub_index).filter(|unit| !unit.is_empty()) else { @@ -602,8 +644,6 @@ pub struct TextView { id: ElementId, source: Option, state: Option>, - link_handler: Option, - task_toggle_handler: Option, style: StyleRefinement, } @@ -618,8 +658,6 @@ impl TextView { id: id.into(), source: Some(source.into()), state: None, - link_handler: None, - task_toggle_handler: None, style: StyleRefinement::default(), } } @@ -630,29 +668,9 @@ impl TextView { id: ElementId::from(SharedString::from(format!("{}", state.entity_id()))), source: None, state: Some(state.clone()), - link_handler: None, - task_toggle_handler: None, style: StyleRefinement::default(), } } - - /// Invokes `handler` when the user clicks a link, instead of opening it. - pub fn on_link_click(mut self, handler: F) -> Self - where - F: Fn(&SharedString, &mut Window, &mut App) + 'static, - { - self.link_handler = Some(Arc::new(handler)); - self - } - - /// Invokes `handler(block, checked)` when the user toggles a task checkbox. - pub fn on_task_toggle(mut self, handler: F) -> Self - where - F: Fn(usize, bool, &mut Window, &mut App) + 'static, - { - self.task_toggle_handler = Some(Arc::new(handler)); - self - } } impl Styled for TextView { @@ -693,8 +711,6 @@ impl Element for TextView { }; let source = self.source.clone(); - let link_handler = self.link_handler.clone(); - let task_toggle = self.task_toggle_handler.clone(); let (selection, focus_handle) = state.update(cx, |view, cx| (view.selection(), view.focus_handle(cx))); @@ -703,19 +719,11 @@ impl Element for TextView { if let Some(source) = source { view.set_source(source, cx); } - if let Some(link_handler) = link_handler { - view.set_link_handler(link_handler); - } - if let Some(task_toggle) = task_toggle { - view.set_task_toggle_handler(task_toggle); - } }); let view = state.read(cx); let frame = ViewFrame { state: state.clone(), - link_handler: view.link_handler.clone(), - task_toggle: view.task_toggle_handler.clone(), selection, focus_handle, pressed_on_piece: std::rc::Rc::new(std::cell::Cell::new(false)), @@ -908,7 +916,7 @@ fn render_blocks( block_index, block_id, }; - render_block(block, block_index, &ctx, cx) + block.render_block(block_index, &ctx, cx) }, )) } @@ -917,37 +925,6 @@ fn spans_text_of(spans: &[InlineSpan]) -> String { spans.iter().map(|span| span.text.as_ref()).collect() } -/// The selectable text units of a block. -fn block_text_units(block: &MarkdownBlock) -> Vec { - match block { - MarkdownBlock::Heading { spans, .. } => vec![spans_text_of(spans)], - MarkdownBlock::Paragraph { items, .. } | MarkdownBlock::ListItem { items, .. } => { - let mut units: Vec = Vec::new(); - for item in items { - match item { - InlineItem::Text(span) => match units.last_mut() { - // Consecutive text items share the unit between images. - Some(unit) => unit.push_str(&span.text), - None => units.push(span.text.as_ref().to_string()), - }, - // An image starts the next unit; the render emits no - // element for it. - InlineItem::Image { .. } => units.push(String::new()), - } - } - units - } - MarkdownBlock::Code { lines, .. } => lines.lines.iter().map(|line| line.text()).collect(), - MarkdownBlock::Table { table, .. } => table - .rows - .iter() - .flat_map(|row| row.cells.iter()) - .map(|cell| spans_text_of(&cell.spans)) - .collect(), - MarkdownBlock::Image { .. } | MarkdownBlock::ThematicBreak { .. } => Vec::new(), - } -} - /// Enumerates the selectable text pieces of `blocks`, in render order. fn text_document(blocks: &[MarkdownBlock]) -> TextDocument { let mut pieces = Vec::new(); @@ -960,7 +937,7 @@ fn text_document(blocks: &[MarkdownBlock]) -> TextDocument { MarkdownBlock::Paragraph { .. } | MarkdownBlock::ListItem { .. } ); - for (sub_index, unit) in block_text_units(block).into_iter().enumerate() { + for (sub_index, unit) in block.block_text_units().into_iter().enumerate() { if unit.is_empty() && skip_empty { continue; } @@ -1405,66 +1382,6 @@ fn flush_item_inline( }); } -/// Renders one parsed block as a list row. -fn render_block( - block: &MarkdownBlock, - block_index: usize, - ctx: &BlockContext, - cx: &App, -) -> AnyElement { - let gap = rems(0.75); - - match block { - MarkdownBlock::Heading { - level, - spans, - indent, - quote, - } => heading_row( - *level, - spans, - *indent, - *quote, - if block_index == 0 { - Rems::ZERO - } else { - rems(0.375) - }, - ctx, - cx, - ), - MarkdownBlock::Paragraph { - items, - indent, - quote, - } => text_row(items, *indent, *quote, gap, None, ctx, cx), - MarkdownBlock::ListItem { - marker, - items, - indent, - quote, - } => text_row(items, *indent, *quote, rems(0.2), Some(*marker), ctx, cx), - MarkdownBlock::Image { - source, - alt, - indent, - quote, - } => image_row(source, alt, *indent, *quote, ctx, cx), - MarkdownBlock::Code { - language, - lines, - indent, - quote, - } => code_row(lines, language.as_ref(), *indent, *quote, ctx, cx), - MarkdownBlock::ThematicBreak { indent, quote } => rule_row(*indent, *quote, ctx, cx), - MarkdownBlock::Table { - table, - indent, - quote, - } => table_row(table, *indent, *quote, ctx, cx), - } -} - /// The shared block frame: ambient text style, spacing, quote bar. fn block_frame(quote: bool, top: Rems, bottom: Rems, id: &ElementId, cx: &App) -> Div { let theme = cx.theme(); @@ -1509,19 +1426,18 @@ fn heading_row( ctx: &BlockContext, cx: &App, ) -> AnyElement { - let frame = block_frame(quote, top, rems(0.75), ctx.block_id, cx); - let frame = match level { - MarkdownHeading::H1 => frame.text_xl().font_semibold(), - MarkdownHeading::H2 => frame.text_lg().font_semibold(), - MarkdownHeading::H3 => frame.text_base().font_semibold(), - MarkdownHeading::H4 | MarkdownHeading::H5 | MarkdownHeading::H6 => { - frame.text_sm().font_semibold() - } - }; - indented_frame( indent, - frame.child(text_child(spans, ctx.block_id, ctx.piece_context(0), cx)), + block_frame(quote, top, rems(0.75), ctx.block_id, cx) + .map(|frame| match level { + MarkdownHeading::H1 => frame.text_xl().font_semibold(), + MarkdownHeading::H2 => frame.text_lg().font_semibold(), + MarkdownHeading::H3 => frame.text_base().font_semibold(), + MarkdownHeading::H4 | MarkdownHeading::H5 | MarkdownHeading::H6 => { + frame.text_sm().font_semibold() + } + }) + .child(text_child(spans, ctx.block_id, ctx.piece_context(0), cx)), ) .into_any_element() } @@ -1542,35 +1458,42 @@ fn text_row( block_frame(quote, Rems::ZERO, bottom, ctx.block_id, cx).map(|frame| match marker { Some(marker) => { let line_height = rems(1.2); - let marker_cell = div() - .flex_none() - .w(rems(1.75)) - .h(line_height) - .flex() - .items_center() - .justify_end() - .pr_1() - .child(match marker { - ListMarker::Bullet => div() - .size_1() - .rounded(theme.radius.full) - .bg(theme.colors.muted_foreground) - .into_any_element(), - ListMarker::Ordered(number) => div() - .text_color(theme.colors.muted_foreground) - .whitespace_nowrap() - .child(format!("{number}.")) - .into_any_element(), - ListMarker::Task(checked) => task_toggle(checked, item_text(items), ctx), - }); frame.child( - div().flex().items_start().child(marker_cell).child( - div() - .flex_1() - .min_w_0() - .child(paragraph_child(items, ctx, cx)), - ), + div() + .flex() + .items_start() + .child( + div() + .flex_none() + .w(rems(1.75)) + .h(line_height) + .flex() + .items_center() + .justify_end() + .pr_1() + .child(match marker { + ListMarker::Bullet => div() + .size_1() + .rounded(theme.radius.full) + .bg(theme.colors.muted_foreground) + .into_any_element(), + ListMarker::Ordered(number) => div() + .text_color(theme.colors.muted_foreground) + .whitespace_nowrap() + .child(format!("{number}.")) + .into_any_element(), + ListMarker::Task(checked) => { + task_toggle(checked, item_text(items), ctx) + } + }), + ) + .child( + div() + .flex_1() + .min_w_0() + .child(paragraph_child(items, ctx, cx)), + ), ) } None => frame.child(paragraph_child(items, ctx, cx)), @@ -1579,22 +1502,17 @@ fn text_row( .into_any_element() } -/// The task marker: a checkbox that reports toggles when a handler is set. +/// The task marker: a checkbox that renders the state without toggling. fn task_toggle(checked: bool, label: SharedString, ctx: &BlockContext) -> AnyElement { let block_index = ctx.block_index; let selector = SharedString::from(format!("task-toggle-{block_index}")); - let checkbox = Checkbox::new((ctx.block_id.clone(), "task")) + Checkbox::new((ctx.block_id.clone(), "task")) .debug_selector(move || selector.to_string()) .checked(checked) .with_size(Size::Small) - .accessibility_label(label); - - match ctx.frame.task_toggle.clone() { - Some(handler) => checkbox - .on_change(move |next, window, cx| handler(block_index, next, window, cx)) - .into_any_element(), - None => checkbox.disabled(true).into_any_element(), - } + .accessibility_label(label) + .disabled(true) + .into_any_element() } /// The item's plain text, for the checkbox's accessibility label. @@ -1710,54 +1628,54 @@ fn code_row( .collect::>() .join("\n"); - let actions_row = h_flex() - .justify_between() - .pb_1() - .when_some(language.cloned(), |row, language| { - row.child( - div() - .text_xs() - .text_color(theme.colors.muted_foreground) - .child(language), - ) - }) - .child( - Button::new((ctx.block_id.clone(), "copy-code")) - .label("Copy") - .variant(ButtonVariant::Ghost) - .debug_selector(|| "copy-code".to_string()) - .on_click(move |_, _, cx| { - cx.write_to_clipboard(ClipboardItem::new_string(plain.clone())); - }), - ); - - let plate = v_flex() - .w_full() - .rounded(theme.radius.control) - .bg(theme.colors.muted) - .p_2() - .font_family(theme.mono_font) - .text_xs() - .line_height(relative(CODE_LINE_HEIGHT)) - .overflow_hidden() - .child(actions_row) - .children(lines.lines.iter().enumerate().map(|(line_ix, line)| { - let styled = code_line(line, theme.colors, theme.ramps); - let layout = styled.layout().clone(); - with_selection_handlers( - div() - .h(line_height) - .whitespace_nowrap() - .overflow_hidden() - .child(styled), - ctx.piece_context(line_ix), - layout, - ) - })); - indented_frame( indent, - block_frame(quote, Rems::ZERO, rems(0.75), ctx.block_id, cx).child(plate), + block_frame(quote, Rems::ZERO, rems(0.75), ctx.block_id, cx).child( + v_flex() + .w_full() + .rounded(theme.radius.control) + .bg(theme.colors.muted) + .p_2() + .font_family(theme.mono_font) + .text_xs() + .line_height(relative(CODE_LINE_HEIGHT)) + .overflow_hidden() + .child( + h_flex() + .justify_between() + .pb_1() + .when_some(language.cloned(), |row, language| { + row.child( + div() + .text_xs() + .text_color(theme.colors.muted_foreground) + .child(language), + ) + }) + .child( + Button::new((ctx.block_id.clone(), "copy-code")) + .label("Copy") + .variant(ButtonVariant::Ghost) + .debug_selector(|| "copy-code".to_string()) + .on_click(move |_, _, cx| { + cx.write_to_clipboard(ClipboardItem::new_string(plain.clone())); + }), + ), + ) + .children(lines.lines.iter().enumerate().map(|(line_ix, line)| { + let styled = code_line(line, theme.colors, theme.ramps); + let layout = styled.layout().clone(); + with_selection_handlers( + div() + .h(line_height) + .whitespace_nowrap() + .overflow_hidden() + .child(styled), + ctx.piece_context(line_ix), + layout, + ) + })), + ), ) .into_any_element() } @@ -1790,50 +1708,52 @@ fn table_row( let row_count = table.rows.len(); let mut cell_ix = 0usize; - let grid = v_flex() - .w_full() - .border_1() - .border_color(colors.border) - .rounded(theme.radius.control) - .overflow_hidden() - .children(table.rows.iter().enumerate().map(|(row_index, row)| { - div() - .w_full() - .flex() - .when(row_index + 1 < row_count, |row_element| { - row_element.border_b_1().border_color(colors.border) - }) - .when(row.header, |row_element| row_element.bg(colors.muted)) - .children( - row.cells - .iter() - .enumerate() - .map(|(column_index, cell)| { - let cell_id = ElementId::from(SharedString::from(format!( - "{}-cell-{row_index}-{column_index}", - ctx.block_id - ))); - let piece = ctx.piece_context(cell_ix); - cell_ix += 1; - div() - .flex_1() - .min_w_0() - .px_2() - .py_1() - .when(row.header, |cell_element| cell_element.font_semibold()) - .child(text_child(&cell.spans, &cell_id, piece, cx)) - }) - // Ragged tables pad missing cells so rows align. - .chain( - (row.cells.len()..width) - .map(|_| div().flex_1().min_w_0().px_2().py_1()), - ), - ) - })); - indented_frame( indent, - block_frame(quote, Rems::ZERO, rems(0.75), ctx.block_id, cx).child(grid), + block_frame(quote, Rems::ZERO, rems(0.75), ctx.block_id, cx).child( + v_flex() + .w_full() + .border_1() + .border_color(colors.border) + .rounded(theme.radius.control) + .overflow_hidden() + .children(table.rows.iter().enumerate().map(|(row_index, row)| { + div() + .w_full() + .flex() + .when(row_index + 1 < row_count, |row_element| { + row_element.border_b_1().border_color(colors.border) + }) + .when(row.header, |row_element| row_element.bg(colors.muted)) + .children( + row.cells + .iter() + .enumerate() + .map(|(column_index, cell)| { + let cell_id = ElementId::from(SharedString::from(format!( + "{}-cell-{row_index}-{column_index}", + ctx.block_id + ))); + let piece = ctx.piece_context(cell_ix); + cell_ix += 1; + div() + .flex_1() + .min_w_0() + .px_2() + .py_1() + .when(row.header, |cell_element| { + cell_element.font_semibold() + }) + .child(text_child(&cell.spans, &cell_id, piece, cx)) + }) + // Ragged tables pad missing cells so rows align. + .chain( + (row.cells.len()..width) + .map(|_| div().flex_1().min_w_0().px_2().py_1()), + ), + ) + })), + ), ) .into_any_element() } @@ -2016,16 +1936,12 @@ where let inner = if destinations.is_empty() { styled.into_any_element() } else { - let link_handler = piece.as_ref().and_then(|piece| piece.link_handler.clone()); InteractiveText::new(id.clone(), styled) - .on_click(link_ranges, move |range_ix, window, cx| { + .on_click(link_ranges, move |range_ix, _window, cx| { let Some(destination) = destinations.get(range_ix) else { return; }; - match link_handler.as_ref() { - Some(handler) => handler(destination, window, cx), - None => cx.open_url(destination.as_ref()), - } + cx.open_url(destination.as_ref()); }) .into_any_element() }; diff --git a/crates/ui/src/components/menu.rs b/crates/ui/src/components/menu.rs index ba78c63..cb80f8b 100644 --- a/crates/ui/src/components/menu.rs +++ b/crates/ui/src/components/menu.rs @@ -54,6 +54,14 @@ type TriggerFn = Box AnyElement>; /// The menu's rows, rebuilt on each render while open. type ItemsFn = Box Vec>; +/// One row of a [`Menu`]: an action, a checkable action, a submenu, or a separator. +#[derive(Clone)] +enum MenuItemKind { + Action, + Separator, + Submenu(Rc<[MenuItem]>), +} + /// One row of a [`Menu`]: an action, a checkable action, a submenu, or a separator. #[derive(Clone)] #[must_use] @@ -62,20 +70,12 @@ pub struct MenuItem { kind: MenuItemKind, label: SharedString, icon: Option, - shortcut: Option, handler: Option, disabled: bool, destructive: bool, checked: bool, } -#[derive(Clone)] -enum MenuItemKind { - Action, - Separator, - Submenu(Rc<[MenuItem]>), -} - impl MenuItem { /// Creates an action row with this label. pub fn new(label: L) -> Self @@ -87,7 +87,6 @@ impl MenuItem { kind: MenuItemKind::Action, label: label.into(), icon: None, - shortcut: None, handler: None, disabled: false, destructive: false, @@ -102,7 +101,6 @@ impl MenuItem { kind: MenuItemKind::Separator, label: SharedString::default(), icon: None, - shortcut: None, handler: None, disabled: false, destructive: false, @@ -137,15 +135,6 @@ impl MenuItem { self } - /// Shows a shortcut hint after the label. - pub fn shortcut(mut self, shortcut: S) -> Self - where - S: Into, - { - self.shortcut = Some(shortcut.into()); - self - } - /// Marks the item non-selectable and non-activatable. pub fn disabled(mut self, disabled: bool) -> Self { self.disabled = disabled; @@ -185,6 +174,226 @@ impl MenuItem { fn selectable(&self) -> bool { matches!(self.kind, MenuItemKind::Action | MenuItemKind::Submenu(_)) && !self.disabled } + + /// Renders one menu row. + fn render_item( + &self, + window: &mut Window, + cx: &mut App, + index: usize, + selected: bool, + env: &RowEnv, + ) -> AnyElement { + match &self.kind { + MenuItemKind::Separator => div() + .h_px() + .debug_selector(move || format!("{}-separator-{index}", env.debug_prefix)) + .mx_2() + .my_1() + .bg(env.chrome.border) + .into_any_element(), + MenuItemKind::Action => { + let label_color = self.row_color(selected, false, env.chrome); + let disabled = self.disabled; + let checked = self.checked; + let icon = self.icon.clone(); + + self.row_shell(cx, index, selected, env) + .on_click({ + let handler = self.handler.clone(); + let on_activate = env.on_activate.clone(); + move |_, window, cx| { + if disabled { + return; + } + + if let Some(on_activate) = &on_activate { + on_activate(false, window, cx); + } + + if let Some(handler) = &handler { + handler(window, cx); + } + } + }) + .when_some(icon, |row, icon| { + row.child(icon.size(rems(1.0)).color(label_color)) + }) + .child( + div() + .flex_1() + .text_color(label_color) + .child(self.label.clone()), + ) + .when(checked, |row| { + row.child( + icon_glyph(IconRole::Check) + .size(rems(0.75)) + .color(label_color), + ) + }) + .into_any_element() + } + MenuItemKind::Submenu(items) => { + let chrome = env.chrome; + let flyout = env.flyout; + let disabled = self.disabled; + let open = *flyout.open.read(cx) == Some(index); + let label_color = self.row_color(selected, open, chrome); + let row_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None)); + + self.row_shell(cx, index, selected, env) + .on_click({ + let set_flyout = flyout.set_flyout.clone(); + move |_, _window, cx| { + if disabled { + return; + } + // Hover already opens the flyout; a click never closes it. + set_flyout(Some(index), false, cx); + } + }) + .child( + div() + .flex_1() + .text_color(label_color) + .child(self.label.clone()), + ) + .child( + icon_glyph(IconRole::ChevronRight) + .size(rems(0.75)) + .color(label_color), + ) + .aria_expanded(open) + .when(open, |row| { + row.child( + canvas( + { + let cell = row_bounds.clone(); + move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) + }, + |_, _, _, _| {}, + ) + .absolute() + .inset_0(), + ) + .child( + deferred(div().absolute().left_full().top_0().child(menu_panel( + window, + cx, + flyout.state, + MenuPanelParams { + id: &flyout.id, + items: items.clone(), + initial_selection: None, + preselect: *flyout.preselect.read(cx), + min_width: flyout.min_width, + label: self.label.clone(), + dismiss_bounds: &row_bounds, + bounds_sink: Some(flyout.bounds), + outer_stack: Some(flyout.stack), + on_dismiss: Some(flyout.dismiss.clone()), + on_activate: flyout.on_activate.clone(), + is_flyout: true, + chrome, + enter_duration: flyout.enter_duration, + debug_prefix: "submenu", + }, + ))) + .with_priority(OVERLAY_LAYER), + ) + }) + .into_any_element() + } + } + } + + /// The shared row shell: dimensions, highlight, and hover-selection. + fn row_shell( + &self, + cx: &App, + index: usize, + selected: bool, + env: &RowEnv, + ) -> gpui::Stateful { + let chrome = env.chrome; + let selectable = self.selectable(); + let opens_submenu = self.submenu_items().is_some(); + let flyout_open = *env.flyout.open.read(cx) == Some(index); + let row_id = self + .id + .clone() + .unwrap_or_else(|| ("menu-item", index).into()); + + div() + .id(row_id) + .role(Role::MenuItem) + .debug_selector(move || format!("{}-item-{index}", env.debug_prefix)) + .flex() + .items_center() + .gap_2() + .min_h_8() + .px_4() + .text_sm() + .line_height(relative(1.0)) + .rounded(chrome.radius_full) + .map(|row| { + if self.disabled { + row + } else if selected && flyout_open { + row.bg(chrome.muted_hover) + } else if selected { + let highlight = if self.destructive { + chrome.destructive + } else { + chrome.primary + }; + row.bg(highlight) + } else { + row.hover(|row| row.bg(chrome.muted_hover)) + } + }) + .on_mouse_move({ + let selection = env.selection.clone(); + let flyout_open = env.flyout.open.clone(); + let set_flyout = env.flyout.set_flyout.clone(); + let dismiss = env.flyout.dismiss.clone(); + move |_, window, cx| { + if !selectable { + return; + } + + if *selection.read(cx) != Some(index) { + selection.update(cx, |selection, _| *selection = Some(index)); + } + + if opens_submenu { + set_flyout(Some(index), false, cx); + } else if flyout_open.read(cx).is_some() { + dismiss(false, window, cx); + } + } + }) + } + + /// The row's label/icon color. + fn row_color(&self, selected: bool, flyout_open: bool, chrome: &MenuChrome) -> gpui::Hsla { + if self.disabled { + return chrome.muted_foreground; + } + if self.destructive { + return if selected && !flyout_open { + chrome.destructive_foreground + } else { + chrome.destructive + }; + } + if selected && !flyout_open { + chrome.primary_foreground + } else { + chrome.foreground + } + } } // MenuItem is a data builder, not an element, adopt the combinators explicitly. @@ -378,49 +587,12 @@ impl RenderOnce for Menu { div() .relative() .refine_style(&self.style) - .child( - canvas( - { - let cell = trigger_bounds.clone(); - move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) - }, - { - let on_change = on_change; - let open = self.open; - let trigger_button = self.trigger_button; - let cell = trigger_bounds.clone(); - - move |_, _, window, _cx| { - let trigger_bounds = cell; - - window.on_mouse_event({ - let on_change = on_change.clone(); - move |event: &MouseDownEvent, phase, window, cx| { - if phase != DispatchPhase::Bubble - || event.button != trigger_button - { - return; - } - - let on_trigger = trigger_bounds - .borrow() - .is_some_and(|bounds| bounds.contains(&event.position)); - if !on_trigger { - return; - } - - if let Some(on_change) = &on_change { - on_change(!open, window, cx); - } - cx.stop_propagation(); - } - }); - } - }, - ) - .absolute() - .inset_0(), - ) + .child(trigger_toggle( + &trigger_bounds, + self.open, + on_change.clone(), + self.trigger_button, + )) .when_some(self.trigger, |wrapper, trigger| { wrapper.child(trigger(window, cx)) }) @@ -455,15 +627,6 @@ struct MenuPanelState { selection: Entity>, } -fn create_menu_panel_state(id: &ElementId, window: &mut Window, cx: &mut App) -> MenuPanelState { - MenuPanelState { - focus: focus_handle(&(id.clone(), "panel").into(), window, cx), - was_open: window.use_keyed_state((id.clone(), "menu-was-open"), cx, |_, _| false), - scroll: window.use_keyed_state((id.clone(), "menu-scroll"), cx, |_, _| ScrollHandle::new()), - selection: window.use_keyed_state((id.clone(), "menu-selection"), cx, |_, _| None), - } -} - struct MenuPanelParams<'a> { id: &'a ElementId, items: Rc<[MenuItem]>, @@ -513,6 +676,100 @@ struct RowEnv<'a> { debug_prefix: &'static str, } +/// Everything key navigation needs from the panel. +struct MenuKeyEnv<'a> { + items: &'a [MenuItem], + selection: &'a Entity>, + set_flyout: &'a FlyoutSetter, + on_dismiss: &'a Option, + on_activate: &'a Option, + left_dismisses: bool, +} + +/// Canvas that records the trigger's painted bounds and toggles `open` on click. +pub(crate) fn trigger_toggle( + bounds: &TriggerBoundsCell, + open: bool, + on_change: Option, + button: MouseButton, +) -> AnyElement { + let painted = bounds.clone(); + + canvas( + { + let cell = bounds.clone(); + move |painted, _window, _cx| *cell.borrow_mut() = Some(painted) + }, + move |_, _, window, _cx| { + let cell = painted.clone(); + window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| { + if phase != DispatchPhase::Bubble || event.button != button { + return; + } + + let on_trigger = cell + .borrow() + .is_some_and(|bounds| bounds.contains(&event.position)); + if !on_trigger { + return; + } + + if let Some(on_change) = &on_change { + on_change(!open, window, cx); + } + cx.stop_propagation(); + }); + }, + ) + .absolute() + .inset_0() + .into_any_element() +} + +/// Deferred anchored overlay on OVERLAY_LAYER, optionally fading in. +pub(crate) fn anchored_overlay( + position: Option>, + panel: AnyElement, + fade: Option<(&'static str, std::time::Duration)>, +) -> AnyElement { + deferred( + anchored() + .when_some(position, |anchored, position| anchored.position(position)) + .offset(point(px(0.), px(4.))) + // AnyElement lacks `Styled`, so the opacity animation rides a wrapper. + .child(panel.when_some(fade, |panel, (id, duration)| { + div() + .child(panel) + .with_animation( + id, + Animation::new(duration).with_easing(ease_out_quint()), + |panel, delta| panel.opacity(delta), + ) + .into_any_element() + })), + ) + .with_priority(OVERLAY_LAYER) + .into_any_element() +} + +/// Canvas that grabs focus when `should_grab` holds. +pub(crate) fn focus_capture( + focus: FocusHandle, + should_grab: impl Fn(&mut Window, &mut App) -> bool + 'static, +) -> AnyElement { + canvas( + |_, _, _| {}, + move |_, _, window, cx| { + if should_grab(window, cx) { + window.focus(&focus, cx); + } + }, + ) + .absolute() + .inset_0() + .into_any_element() +} + /// Assembles the floating menu panel anchored to its trigger. pub(crate) fn anchored_menu_panel( window: &mut Window, @@ -524,8 +781,6 @@ pub(crate) fn anchored_menu_panel( ) -> Option { let was_open = window.use_keyed_state((id.clone(), "menu-was-open"), cx, |_, _| false); - // Render-phase residue: trigger-toggle and owner-driven closes bypass every - // dismissal handler, so this closed frame is the only universal close hook. if !spec.open { was_open.update(cx, |was_open, _| *was_open = false); // A closed menu drops any open flyout; fresh state on the next open. @@ -562,17 +817,7 @@ pub(crate) fn anchored_menu_panel( }, ); - let anchored = match spec.position { - Some(position) => anchored().position(position), - None => anchored(), - } - .offset(point(px(0.), px(4.))); - - Some( - deferred(anchored.child(panel)) - .with_priority(OVERLAY_LAYER) - .into_any_element(), - ) + Some(anchored_overlay(spec.position, panel, None)) } /// Builds one menu panel: chrome, rows, focus, navigation, and dismissals. @@ -668,10 +913,9 @@ fn menu_panel( .iter() .enumerate() .map(|(index, item)| { - render_item( + item.render_item( window, cx, - item, index, selected == Some(index), &RowEnv { @@ -791,254 +1035,6 @@ fn menu_panel( .into_any_element() } -/// Renders one menu row. -fn render_item( - window: &mut Window, - cx: &mut App, - item: &MenuItem, - index: usize, - selected: bool, - env: &RowEnv, -) -> AnyElement { - match &item.kind { - MenuItemKind::Separator => div() - .h_px() - .debug_selector(move || format!("{}-separator-{index}", env.debug_prefix)) - .mx_2() - .my_1() - .bg(env.chrome.border) - .into_any_element(), - MenuItemKind::Action => { - let label_color = row_color(item, selected, false, env.chrome); - let disabled = item.disabled; - let destructive = item.destructive; - let checked = item.checked; - let shortcut = item.shortcut.clone(); - let icon = item.icon.clone(); - - row_shell(cx, item, index, selected, env) - .on_click({ - let handler = item.handler.clone(); - let on_activate = env.on_activate.clone(); - move |_, window, cx| { - if disabled { - return; - } - - if let Some(on_activate) = &on_activate { - on_activate(false, window, cx); - } - - if let Some(handler) = &handler { - handler(window, cx); - } - } - }) - .when_some(icon, |row, icon| { - row.child(icon.size(rems(1.0)).color(label_color)) - }) - .child( - div() - .flex_1() - .text_color(label_color) - .child(item.label.clone()), - ) - .when_some(shortcut, |row, shortcut| { - row.child( - div() - .text_color(if selected && !destructive && !disabled { - env.chrome.primary_foreground - } else { - env.chrome.muted_foreground - }) - .child(shortcut), - ) - }) - .when(checked, |row| { - row.child( - icon_glyph(IconRole::Check) - .size(rems(0.75)) - .color(label_color), - ) - }) - .into_any_element() - } - MenuItemKind::Submenu(items) => { - let chrome = env.chrome; - let flyout = env.flyout; - let disabled = item.disabled; - let open = *flyout.open.read(cx) == Some(index); - let label_color = row_color(item, selected, open, chrome); - let row_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None)); - - row_shell(cx, item, index, selected, env) - .on_click({ - let set_flyout = flyout.set_flyout.clone(); - move |_, _window, cx| { - if disabled { - return; - } - // Hover already opens the flyout; a click never closes it. - set_flyout(Some(index), false, cx); - } - }) - .child( - div() - .flex_1() - .text_color(label_color) - .child(item.label.clone()), - ) - .child( - icon_glyph(IconRole::ChevronRight) - .size(rems(0.75)) - .color(label_color), - ) - .aria_expanded(open) - .when(open, |row| { - row.child( - canvas( - { - let cell = row_bounds.clone(); - move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) - }, - |_, _, _, _| {}, - ) - .absolute() - .inset_0(), - ) - .child( - deferred(div().absolute().left_full().top_0().child(menu_panel( - window, - cx, - flyout.state, - MenuPanelParams { - id: &flyout.id, - items: items.clone(), - initial_selection: None, - preselect: *flyout.preselect.read(cx), - min_width: flyout.min_width, - label: item.label.clone(), - dismiss_bounds: &row_bounds, - bounds_sink: Some(flyout.bounds), - outer_stack: Some(flyout.stack), - on_dismiss: Some(flyout.dismiss.clone()), - on_activate: flyout.on_activate.clone(), - is_flyout: true, - chrome, - enter_duration: flyout.enter_duration, - debug_prefix: "submenu", - }, - ))) - .with_priority(OVERLAY_LAYER), - ) - }) - .into_any_element() - } - } -} - -/// The shared row shell: dimensions, highlight, and hover-selection. -fn row_shell( - cx: &App, - item: &MenuItem, - index: usize, - selected: bool, - env: &RowEnv, -) -> gpui::Stateful { - let chrome = env.chrome; - let selectable = item.selectable(); - let opens_submenu = item.submenu_items().is_some(); - let flyout_open = *env.flyout.open.read(cx) == Some(index); - let row_id = item - .id - .clone() - .unwrap_or_else(|| ("menu-item", index).into()); - - div() - .id(row_id) - .role(Role::MenuItem) - .debug_selector(move || format!("{}-item-{index}", env.debug_prefix)) - .flex() - .items_center() - .gap_2() - .min_h_8() - .px_4() - .text_sm() - .line_height(relative(1.0)) - .rounded(chrome.radius_full) - .map(|row| { - if item.disabled { - row - } else if selected && flyout_open { - row.bg(chrome.muted_hover) - } else if selected { - let highlight = if item.destructive { - chrome.destructive - } else { - chrome.primary - }; - row.bg(highlight) - } else { - row.hover(|row| row.bg(chrome.muted_hover)) - } - }) - .on_mouse_move({ - let selection = env.selection.clone(); - let flyout_open = env.flyout.open.clone(); - let set_flyout = env.flyout.set_flyout.clone(); - let dismiss = env.flyout.dismiss.clone(); - move |_, window, cx| { - if !selectable { - return; - } - - if *selection.read(cx) != Some(index) { - selection.update(cx, |selection, _| *selection = Some(index)); - } - - if opens_submenu { - set_flyout(Some(index), false, cx); - } else if flyout_open.read(cx).is_some() { - dismiss(false, window, cx); - } - } - }) -} - -/// The row's label/icon color. -fn row_color( - item: &MenuItem, - selected: bool, - flyout_open: bool, - chrome: &MenuChrome, -) -> gpui::Hsla { - if item.disabled { - return chrome.muted_foreground; - } - if item.destructive { - return if selected && !flyout_open { - chrome.destructive_foreground - } else { - chrome.destructive - }; - } - if selected && !flyout_open { - chrome.primary_foreground - } else { - chrome.foreground - } -} - -/// Everything key navigation needs from the panel. -struct MenuKeyEnv<'a> { - items: &'a [MenuItem], - selection: &'a Entity>, - set_flyout: &'a FlyoutSetter, - on_dismiss: &'a Option, - on_activate: &'a Option, - left_dismisses: bool, -} - /// Handles the panel's navigation keys. fn handle_menu_key(event: &KeyDownEvent, env: MenuKeyEnv, window: &mut Window, cx: &mut App) { let selectable: Vec = env @@ -1111,3 +1107,13 @@ fn handle_menu_key(event: &KeyDownEvent, env: MenuKeyEnv, window: &mut Window, c cx.stop_propagation(); } + +/// Creates one panel's keyed state: focus, open tracking, scroll, and selection. +fn create_menu_panel_state(id: &ElementId, window: &mut Window, cx: &mut App) -> MenuPanelState { + MenuPanelState { + focus: focus_handle(&(id.clone(), "panel").into(), window, cx), + was_open: window.use_keyed_state((id.clone(), "menu-was-open"), cx, |_, _| false), + scroll: window.use_keyed_state((id.clone(), "menu-scroll"), cx, |_, _| ScrollHandle::new()), + selection: window.use_keyed_state((id.clone(), "menu-selection"), cx, |_, _| None), + } +} diff --git a/crates/ui/src/components/mod.rs b/crates/ui/src/components/mod.rs index 4dbaaa7..c213d56 100644 --- a/crates/ui/src/components/mod.rs +++ b/crates/ui/src/components/mod.rs @@ -10,9 +10,7 @@ pub mod code; pub mod combobox; pub mod command_palette; pub mod common; -pub mod context_menu; pub mod dialog; -pub mod diff; pub mod dropdown_menu; pub mod empty_state; pub mod field; @@ -20,21 +18,15 @@ pub mod grain; pub mod highlight; pub mod input; pub mod kbd; -pub mod link; -pub mod list; pub mod markdown; pub mod menu; pub mod popover; -pub mod progress; -pub mod radio; pub mod scroll_area; pub mod scrollbar; pub mod segmented; pub mod select; pub mod separator; pub mod sidebar; -pub mod slider; -pub mod speech; pub mod spinner; pub mod status_dot; pub mod switch; diff --git a/crates/ui/src/components/popover.rs b/crates/ui/src/components/popover.rs index 29bd36c..5bfdcb1 100644 --- a/crates/ui/src/components/popover.rs +++ b/crates/ui/src/components/popover.rs @@ -24,24 +24,21 @@ use std::rc::Rc; use gpui::prelude::FluentBuilder as _; use gpui::{ - Animation, AnimationExt as _, AnyElement, App, Bounds, DispatchPhase, ElementId, - InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, MouseDownEvent, - ParentElement as _, Pixels, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, - StyleRefinement, Styled as _, Window, anchored, canvas, deferred, div, ease_out_quint, point, - px, + AnyElement, App, ElementId, InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, + ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, + StyleRefinement, Styled as _, Window, div, }; -use crate::components::common::{OVERLAY_LAYER, StyledExt as _, floating_panel, v_flex}; +use crate::components::common::{StyledExt as _, floating_panel, v_flex}; +use crate::components::menu::{ + ChangeHandler, TriggerBoundsCell, anchored_overlay, focus_capture, trigger_toggle, +}; use crate::theme::{ActiveTheme as _, POPOVER_MIN_WIDTH}; -/// Reports the next open state of a [`Popover`]: `true` to open, `false` to close. -type ChangeHandler = Rc; /// The element the panel anchors below, built during render. type TriggerFn = Box AnyElement>; /// The panel's contents, built when it opens. type ContentFn = Box AnyElement>; -/// Bounds captured during the last paint, shared with the dismissal listener. -type BoundsCell = Rc>>>; /// A floating panel anchored below its trigger. #[derive(IntoElement)] @@ -134,7 +131,7 @@ impl RenderOnce for Popover { ) }; - let trigger_bounds: BoundsCell = Rc::new(RefCell::new(None)); + let trigger_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None)); let fallback_label = self .a11y_label @@ -144,49 +141,12 @@ impl RenderOnce for Popover { div() .relative() .refine_style(&self.style) - .child( - canvas( - { - let cell = trigger_bounds.clone(); - move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) - }, - { - let on_change = self.on_change.clone(); - let open = self.open; - let cell = trigger_bounds.clone(); - - move |_, _, window, _cx| { - window.on_mouse_event({ - let on_change = on_change.clone(); - let trigger_bounds = cell; - move |event: &MouseDownEvent, phase, window, cx| { - if phase != DispatchPhase::Bubble - || event.button != MouseButton::Left - { - return; - } - - let on_trigger = trigger_bounds - .borrow() - .is_some_and(|bounds| bounds.contains(&event.position)); - - if !on_trigger { - return; - } - - if let Some(on_change) = &on_change { - on_change(!open, window, cx); - } - - cx.stop_propagation(); - } - }); - } - }, - ) - .absolute() - .inset_0(), - ) + .child(trigger_toggle( + &trigger_bounds, + self.open, + self.on_change.clone(), + MouseButton::Left, + )) .when_some(self.trigger, |wrapper, trigger| { wrapper.child(trigger(window, cx)) }) @@ -196,71 +156,56 @@ impl RenderOnce for Popover { let focus = crate::components::common::focus_handle(&self.id, window, cx); let content = self.content.map(|content| content(window, cx)); - let panel = floating_panel( - cx, - radius.overlay, - v_flex() - .id("popover-panel") - .debug_selector(|| "popover-panel".to_string()) - .occlude() - .track_focus(&focus) - .role(Role::Dialog) - .aria_label(label) - .min_w(POPOVER_MIN_WIDTH) - .text_color(colors.surface_foreground), - shadows, - ) - .overflow_hidden() - .on_mouse_down_out({ - let on_change = on_change.clone(); - let trigger_bounds = trigger_bounds.clone(); - move |event, window, cx| { - if trigger_bounds - .borrow() - .is_some_and(|bounds| bounds.contains(&event.position)) - { - return; - } - if let Some(on_change) = &on_change { - on_change(false, window, cx); - } - } - }) - .on_key_down({ - let on_change = on_change.clone(); - move |event: &KeyDownEvent, window, cx| { - if event.keystroke.key == "escape" { + wrapper.child(anchored_overlay( + None, + floating_panel( + cx, + radius.overlay, + v_flex() + .id("popover-panel") + .debug_selector(|| "popover-panel".to_string()) + .occlude() + .track_focus(&focus) + .role(Role::Dialog) + .aria_label(label) + .min_w(POPOVER_MIN_WIDTH) + .text_color(colors.surface_foreground), + shadows, + ) + .overflow_hidden() + .on_mouse_down_out({ + let on_change = on_change.clone(); + let trigger_bounds = trigger_bounds.clone(); + move |event, window, cx| { + if trigger_bounds + .borrow() + .is_some_and(|bounds| bounds.contains(&event.position)) + { + return; + } if let Some(on_change) = &on_change { on_change(false, window, cx); } - cx.stop_propagation(); } - } - }) - .when_some(content, |panel, content| panel.child(content)) - .child( - canvas(|_, _, _| {}, { - let focus = focus; - move |_, _, window, cx| { - if !focus.contains_focused(window, cx) { - window.focus(&focus, cx); + }) + .on_key_down({ + let on_change = on_change.clone(); + move |event: &KeyDownEvent, window, cx| { + if event.keystroke.key == "escape" { + if let Some(on_change) = &on_change { + on_change(false, window, cx); + } + cx.stop_propagation(); } } }) - .absolute() - .inset_0(), - ); - - wrapper.child( - deferred(anchored().offset(point(Pixels::ZERO, px(4.))).child( - panel.with_animation( - "popover-enter", - Animation::new(enter_duration).with_easing(ease_out_quint()), - |panel, delta| panel.opacity(delta), - ), - )) - .with_priority(OVERLAY_LAYER), - ) + .when_some(content, |panel, content| panel.child(content)) + .child(focus_capture(focus.clone(), move |window, cx| { + !focus.contains_focused(window, cx) + })) + .into_any_element(), + Some(("popover-enter", enter_duration)), + )) }) } } diff --git a/crates/ui/src/components/progress.rs b/crates/ui/src/components/progress.rs deleted file mode 100644 index 040cd47..0000000 --- a/crates/ui/src/components/progress.rs +++ /dev/null @@ -1,132 +0,0 @@ -//! Renders a progress bar with a determinate fill or an indeterminate sweep. -//! -//! # Examples -//! -//! ```no_run -//! use ui::progress::Progress; -//! -//! let upload = Progress::new("upload", 0.4); -//! let loading = Progress::new("loading", 0.0).indeterminate(true); -//! ``` - -use gpui::prelude::FluentBuilder as _; -use gpui::{ - Animation, AnimationExt as _, App, ElementId, InteractiveElement as _, IntoElement, - ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, - StyleRefinement, Styled as _, Window, div, relative, -}; - -use crate::components::common::{Sizable, StyledExt as _}; -use crate::theme::{ActiveTheme as _, PROGRESS_ANIMATION_PERIOD, Size}; - -/// A bar that paints a determinate fill from its `value`, or an indeterminate sweep. -#[derive(IntoElement)] -#[must_use] -pub struct Progress { - id: ElementId, - value: f32, - indeterminate: bool, - size: Size, - a11y_label: Option, - style: StyleRefinement, -} - -impl Progress { - /// Creates a determinate progress bar at `value` (`0..=1`). - pub fn new(id: I, value: f32) -> Self - where - I: Into, - { - Self { - id: id.into(), - value, - indeterminate: false, - size: Size::default(), - a11y_label: None, - style: StyleRefinement::default(), - } - } - - /// Sweeps instead of painting a fill, for work of unknown length. - pub fn indeterminate(mut self, indeterminate: bool) -> Self { - self.indeterminate = indeterminate; - self - } - - /// Sets the accessibility label. - pub fn accessibility_label(mut self, label: L) -> Self - where - L: Into, - { - self.a11y_label = Some(label.into()); - self - } -} - -impl gpui::Styled for Progress { - fn style(&mut self) -> &mut StyleRefinement { - &mut self.style - } -} - -impl Sizable for Progress { - fn apply_size(&mut self, size: Size) { - self.size = size; - } -} - -impl RenderOnce for Progress { - fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { - let theme = cx.theme(); - let colors = theme.colors; - let ramps = theme.ramps; - let radius = theme.radius; - let size = self.size; - - let value = self.value.clamp(0.0, 1.0); - - let track = div().w_full().rounded(radius.full).bg(colors.border); - let track = match size { - Size::XSmall => track.h_0p5(), - Size::Small | Size::Medium => track.h_1(), - Size::Large => track.h_1p5(), - }; - - div() - .id(self.id) - .w_full() - .refine_style(&self.style) - .role(Role::ProgressIndicator) - .when_some(self.a11y_label, |progress, label| { - progress.aria_label(label) - }) - .when(!self.indeterminate, |progress| { - progress - .aria_numeric_value(f64::from(value)) - .aria_min_numeric_value(0.0) - .aria_max_numeric_value(1.0) - }) - .child(track.child(if self.indeterminate { - div() - .h_full() - .w(relative(0.3)) - .rounded(radius.full) - .bg(ramps.primary.base) - .with_animation( - "indeterminate", - Animation::new(PROGRESS_ANIMATION_PERIOD) - .repeat() - .with_max_fps(30.), - |pill, delta| pill.ml(relative(delta * 0.7)), - ) - .into_any_element() - } else { - div() - .h_full() - .w(relative(value)) - .rounded(radius.full) - .bg(ramps.primary.base) - .into_any_element() - })) - } -} diff --git a/crates/ui/src/components/radio.rs b/crates/ui/src/components/radio.rs deleted file mode 100644 index fd92a94..0000000 --- a/crates/ui/src/components/radio.rs +++ /dev/null @@ -1,259 +0,0 @@ -//! Renders a group of radio buttons that reports the clicked choice. -//! -//! # Examples -//! -//! ```no_run -//! use ui::radio::{Radio, RadioGroup}; -//! -//! let plan = RadioGroup::new("plan") -//! .selected(Some("monthly")) -//! .child(Radio::new("monthly", "monthly").label("Monthly")) -//! .child(Radio::new("yearly", "yearly").label("Yearly")) -//! .on_change(|value, _window, _cx| println!("selected: {value}")); -//! ``` - -use gpui::prelude::FluentBuilder; -use gpui::{ - App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role, - SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Toggled, Window, - div, -}; - -use crate::components::common::{ - ControlSizing, Sizable, StyledExt as _, focus_ring, h_flex, v_flex, -}; -use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; - -/// The group's change reporter, fired with the clicked radio's value. -type ChangeHandler = std::rc::Rc; - -/// A single choice in a [`RadioGroup`]. -/// -/// Each radio is its own tab stop; the full ARIA radiogroup pattern (single -/// stop plus arrow-key roving focus) needs a group owner that does not exist yet. -#[must_use] -pub struct Radio { - id: ElementId, - value: V, - label: Option, - disabled: bool, - a11y_label: Option, -} - -impl Radio -where - V: Clone + PartialEq + 'static, -{ - /// Creates a radio representing `value`. - pub fn new(id: I, value: V) -> Self - where - I: Into, - { - Self { - id: id.into(), - value, - label: None, - disabled: false, - a11y_label: None, - } - } - - /// Sets the visible label; clicking it selects the radio too. - pub fn label(mut self, label: L) -> Self - where - L: Into, - { - self.label = Some(label.into()); - self - } - - /// Renders the radio inert, unfocusable, and dimmed. - pub fn disabled(mut self, disabled: bool) -> Self { - self.disabled = disabled; - self - } - - /// Overrides the accessibility label, which defaults to the visible label. - pub fn accessibility_label(mut self, label: L) -> Self - where - L: Into, - { - self.a11y_label = Some(label.into()); - self - } -} - -// Radio is a data builder, not an element, adopt the combinators explicitly. -impl FluentBuilder for Radio {} - -/// A set of [`Radio`] choices that reports clicks through [`RadioGroup::on_change`]. -#[derive(IntoElement)] -#[must_use] -pub struct RadioGroup -where - V: Clone + PartialEq + 'static, -{ - id: ElementId, - selected: Option, - children: Vec>, - size: Size, - a11y_label: Option, - on_change: Option>, - style: StyleRefinement, -} - -impl RadioGroup -where - V: Clone + PartialEq + 'static, -{ - /// Creates an empty group with nothing selected. - pub fn new(id: I) -> Self - where - I: Into, - { - Self { - id: id.into(), - selected: None, - children: Vec::new(), - size: Size::default(), - a11y_label: None, - on_change: None, - style: StyleRefinement::default(), - } - } - - /// Sets the currently selected value. - pub fn selected(mut self, selected: Option) -> Self { - self.selected = selected; - self - } - - /// Adds a radio to the group. - pub fn child(mut self, radio: Radio) -> Self { - self.children.push(radio); - self - } - - /// Sets the group's accessibility label. - pub fn accessibility_label(mut self, label: L) -> Self - where - L: Into, - { - self.a11y_label = Some(label.into()); - self - } - - /// Sets the handler fired with the clicked radio's value. - pub fn on_change(mut self, handler: F) -> Self - where - F: Fn(V, &mut Window, &mut App) + 'static, - { - self.on_change = Some(std::rc::Rc::new(handler)); - self - } -} - -impl Sizable for RadioGroup -where - V: Clone + PartialEq + 'static, -{ - fn apply_size(&mut self, size: Size) { - self.size = size; - } -} - -impl gpui::Styled for RadioGroup -where - V: Clone + PartialEq + 'static, -{ - fn style(&mut self) -> &mut StyleRefinement { - &mut self.style - } -} - -impl RenderOnce for RadioGroup -where - V: Clone + PartialEq + 'static, -{ - fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { - let theme = cx.theme(); - let colors = theme.colors; - let ramps = theme.ramps; - let radius = theme.radius; - let size = self.size; - let selected = self.selected; - let on_change = self.on_change; - let group_label = self.a11y_label; - - v_flex() - .id(self.id) - .gap_2() - .control_text(size) - .refine_style(&self.style) - .role(Role::RadioGroup) - .when_some(group_label.clone(), |group, label| group.aria_label(label)) - .children(self.children.into_iter().map(move |radio| { - let is_selected = selected.as_ref() == Some(&radio.value); - let disabled = radio.disabled; - let row_on_change = on_change.clone(); - - let a11y_label = radio - .a11y_label - .or(radio.label.clone()) - .or_else(|| group_label.clone()); - - h_flex() - .id(radio.id) - .gap_2() - .role(Role::RadioButton) - .when_some(a11y_label, |row, label| row.aria_label(label)) - .aria_toggled(Toggled::from(is_selected)) - .when(disabled, |row| row.opacity(DISABLED_OPACITY)) - .when(!disabled, move |row| { - let value = radio.value.clone(); - row.cursor_pointer() - .focusable() - .tab_stop(true) - .focus_visible(|style| style.shadow(focus_ring(colors.ring))) - .when_some(row_on_change, |row, on_change| { - row.on_click(move |_, window, cx| { - on_change(value.clone(), window, cx) - }) - }) - }) - .child( - h_flex() - .justify_center() - .flex_none() - .control_indicator(size) - .rounded(radius.full) - .border_1() - .when(is_selected, |indicator| { - indicator - .bg(ramps.primary.base) - .border_color(ramps.primary.base) - .hover(|style| { - style - .bg(ramps.primary.hover) - .border_color(ramps.primary.hover) - }) - .child({ - let dot = match size { - Size::XSmall => div().size_1p5(), - Size::Small | Size::Medium => div().size_2(), - Size::Large => div().size_2p5(), - }; - dot.rounded(radius.full).bg(colors.primary_foreground) - }) - }) - .when(!is_selected, |indicator| { - indicator - .bg(colors.input) - .border_color(colors.border) - .hover(|style| style.border_color(colors.muted_foreground)) - }), - ) - .when_some(radio.label, |row, label| row.child(label)) - })) - } -} diff --git a/crates/ui/src/components/scroll_area.rs b/crates/ui/src/components/scroll_area.rs index f470b1b..80d53f1 100644 --- a/crates/ui/src/components/scroll_area.rs +++ b/crates/ui/src/components/scroll_area.rs @@ -108,31 +108,31 @@ impl RenderOnce for ScrollArea { let mut pane_style = self.style.clone(); pane_style.padding = Default::default(); - let pane = div() - .id(self.id.clone()) - .h_full() - .overflow_hidden() - .when(self.axes != ScrollAxes::Horizontal, |area| { - area.overflow_y_scroll() - }) - .when(self.axes != ScrollAxes::Vertical, |area| { - area.overflow_x_scroll() - }) - .when_some(self.handle.clone(), |area, handle| { - area.track_scroll(&handle) - }) - .when_some(self.a11y_label, |area, label| area.aria_label(label)) - .on_scroll(|_, _, cx| { - // Keep wheel events from scrolling an outer scroll area too. - cx.stop_propagation(); - }) - .refine_style(&pane_style) - .children(self.children); - div() .relative() .refine_style(&self.style) - .child(pane.into_any_element()) + .child( + div() + .id(self.id.clone()) + .h_full() + .overflow_hidden() + .when(self.axes != ScrollAxes::Horizontal, |area| { + area.overflow_y_scroll() + }) + .when(self.axes != ScrollAxes::Vertical, |area| { + area.overflow_x_scroll() + }) + .when_some(self.handle.clone(), |area, handle| { + area.track_scroll(&handle) + }) + .when_some(self.a11y_label, |area, label| area.aria_label(label)) + .on_scroll(|_, _, cx| { + // Keep wheel events from scrolling an outer scroll area too. + cx.stop_propagation(); + }) + .refine_style(&pane_style) + .children(self.children), + ) .when_some(self.handle, |wrapper, handle| { let id = self.id.clone(); diff --git a/crates/ui/src/components/scrollbar.rs b/crates/ui/src/components/scrollbar.rs index 7636566..58a0d7e 100644 --- a/crates/ui/src/components/scrollbar.rs +++ b/crates/ui/src/components/scrollbar.rs @@ -42,6 +42,39 @@ pub enum ScrollbarVisibility { /// How often the autohide fade repaints while it runs. const FADE_STEP: Duration = Duration::from_millis(50); +/// The drag state shared between the scrollbar's mouse handlers. +type Drag = Option<(Pixels, Pixels)>; + +/// Which direction the scrollbar lies along. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Axis { + Vertical, + Horizontal, +} + +impl Axis { + fn along(self, position: Point) -> Pixels { + match self { + Axis::Vertical => position.y, + Axis::Horizontal => position.x, + } + } + + fn with_along(self, position: Point, along: Pixels) -> Point { + match self { + Axis::Vertical => point(position.x, along), + Axis::Horizontal => point(along, position.y), + } + } + + fn viewport_along(self, viewport: &Bounds) -> Pixels { + match self { + Axis::Vertical => viewport.size.height, + Axis::Horizontal => viewport.size.width, + } + } +} + /// The shared autohide timeline for an overlay scrollbar. #[derive(Clone)] struct Autohide { @@ -199,36 +232,6 @@ impl ScrollbarHandle for ListState { } } -/// Which direction the scrollbar lies along. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Axis { - Vertical, - Horizontal, -} - -impl Axis { - fn along(self, position: Point) -> Pixels { - match self { - Axis::Vertical => position.y, - Axis::Horizontal => position.x, - } - } - - fn with_along(self, position: Point, along: Pixels) -> Point { - match self { - Axis::Vertical => point(position.x, along), - Axis::Horizontal => point(along, position.y), - } - } - - fn viewport_along(self, viewport: &Bounds) -> Pixels { - match self { - Axis::Vertical => viewport.size.height, - Axis::Horizontal => viewport.size.width, - } - } -} - /// An overlay scrollbar, rendered over the scrolled surface. #[derive(IntoElement)] #[must_use] @@ -239,6 +242,20 @@ pub struct Scrollbar { id: ElementId, } +impl RenderOnce for Scrollbar { + fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + canvas(|_, _, _| {}, { + let handle = self.handle; + let axis = self.axis; + let visibility = self.visibility; + let id = self.id; + move |_, _, window, cx| Self::paint(&handle, axis, visibility, &id, window, cx) + }) + .absolute() + .inset_0() + } +} + impl Scrollbar { /// Creates a vertical scrollbar named by `id`, driven by `handle`. pub fn vertical(id: I, handle: H) -> Self @@ -304,26 +321,7 @@ impl Scrollbar { ..color }) } -} -impl RenderOnce for Scrollbar { - fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { - canvas(|_, _, _| {}, { - let handle = self.handle; - let axis = self.axis; - let visibility = self.visibility; - let id = self.id; - move |_, _, window, cx| Self::paint(&handle, axis, visibility, &id, window, cx) - }) - .absolute() - .inset_0() - } -} - -/// The drag state shared between the scrollbar's mouse handlers. -type Drag = Option<(Pixels, Pixels)>; - -impl Scrollbar { fn paint( handle: &Rc, axis: Axis, diff --git a/crates/ui/src/components/select.rs b/crates/ui/src/components/select.rs index 264583b..23d3b31 100644 --- a/crates/ui/src/components/select.rs +++ b/crates/ui/src/components/select.rs @@ -29,7 +29,7 @@ use crate::icons::{Icon, IconRole, icon}; use crate::theme::{ActiveTheme as _, Size}; /// Reports the value the user chose. `None` means the select holds no value. -pub type SelectHandler = Rc, &mut Window, &mut App)>; +type SelectHandler = Rc, &mut Window, &mut App)>; /// Select option for a [`Select`] control. #[derive(Clone)] @@ -340,7 +340,7 @@ where .collect() }; - let menu = Menu::new(self.id) + Menu::new(self.id) .open(is_open) .on_change({ let open = open.clone(); @@ -353,8 +353,7 @@ where } }) .trigger(trigger) - .items(items); - - menu.when_some(selected_index, |menu, index| menu.initial_selection(index)) + .items(items) + .when_some(selected_index, |menu, index| menu.initial_selection(index)) } } diff --git a/crates/ui/src/components/sidebar.rs b/crates/ui/src/components/sidebar.rs index 2750bee..ae53030 100644 --- a/crates/ui/src/components/sidebar.rs +++ b/crates/ui/src/components/sidebar.rs @@ -143,269 +143,7 @@ impl SidebarEntry { } self } -} -// SidebarEntry is a data builder, not an element, adopt the combinators explicitly. -impl FluentBuilder for SidebarEntry {} - -/// A sidebar of [`SidebarEntry`] rows grouped under section headers. -#[derive(IntoElement)] -#[must_use] -pub struct Sidebar { - id: ElementId, - selected: Option, - transparent: bool, - grain: bool, - border_right: bool, - padded: bool, - width: Pixels, - a11y_label: Option, - on_change: Option, - entries: Option, - style: StyleRefinement, -} - -impl Sidebar { - /// Creates a sidebar with nothing selected. - pub fn new(id: I) -> Self - where - I: Into, - { - Self { - id: id.into(), - selected: None, - transparent: false, - grain: false, - border_right: true, - padded: true, - width: SIDEBAR_DEFAULT_WIDTH, - a11y_label: None, - on_change: None, - entries: None, - style: StyleRefinement::default(), - } - } - - /// Sets the current selection. - pub fn selected(mut self, selected: Option) -> Self { - self.selected = selected; - self - } - - /// Paints translucent material fills so the window's native backdrop shows through. - pub fn transparent(mut self, transparent: bool) -> Self { - self.transparent = transparent; - self - } - - /// Whether translucent material fills are painted. - pub fn is_transparent(&self) -> bool { - self.transparent - } - - /// Textures the sidebar with a film-grain overlay. - pub fn grain(mut self, grain: bool) -> Self { - self.grain = grain; - self - } - - /// Paints a hairline border on the sidebar's right edge. - pub fn border_right(mut self, border_right: bool) -> Self { - self.border_right = border_right; - self - } - - /// Whether the right-edge border is painted. - pub fn has_border_right(&self) -> bool { - self.border_right - } - - /// Insets the entry list from the sidebar's edges; the scrollbar stays on the edge. - pub fn padded(mut self, padded: bool) -> Self { - self.padded = padded; - self - } - - /// Whether the entry list is inset from the sidebar's edges. - pub fn is_padded(&self) -> bool { - self.padded - } - - /// Sets the sidebar's width, overriding the default. - pub fn width(mut self, width: W) -> Self - where - W: Into, - { - self.width = width.into(); - self - } - - /// Reports the next selected row, from clicks and keys alike. - pub fn on_change(mut self, handler: F) -> Self - where - F: Fn(Option, &mut Window, &mut App) + 'static, - { - self.on_change = Some(Rc::new(handler)); - self - } - - /// Sets the entries; the closure runs during render and must not mutate entities or notify. - pub fn entries(mut self, entries: F) -> Self - where - F: Fn(&mut Window, &mut App) -> Vec + 'static, - { - self.entries = Some(Box::new(entries)); - self - } - - /// Overrides the accessibility label, which defaults to the id. - pub fn accessibility_label(mut self, label: L) -> Self - where - L: Into, - { - self.a11y_label = Some(label.into()); - self - } -} - -impl gpui::Styled for Sidebar { - fn style(&mut self) -> &mut StyleRefinement { - &mut self.style - } -} - -impl RenderOnce for Sidebar { - fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { - let Self { - id, - selected, - transparent: material, - grain, - border_right, - padded, - width, - a11y_label, - on_change, - entries, - style, - } = self; - - let label = a11y_label.unwrap_or_else(|| SharedString::from(id.to_string())); - let debug_id = id.clone(); - - let entries = match entries { - Some(build) => build(window, cx), - None => Vec::new(), - }; - - // Headers and custom entries are never selectable, only enabled rows are. - let selectable: Vec = entries - .iter() - .enumerate() - .filter(|(_, entry)| match entry { - SidebarEntry::Row { disabled, .. } => !disabled, - SidebarEntry::Header { .. } | SidebarEntry::Custom(_) => false, - }) - .map(|(index, _)| index) - .collect(); - - let focus = crate::components::common::focus_handle(&id, window, cx); - let scroll = window.with_element_namespace(id.clone(), |window| { - window - .use_keyed_state("scroll", cx, |_, _| gpui::ScrollHandle::new()) - .clone() - }); - let scroll_area_id = (id.clone(), "entries"); - - let row_count = entries - .iter() - .filter(|entry| matches!(entry, SidebarEntry::Row { .. })) - .count(); - let mut row_position = 0usize; - - let children: Vec = entries - .into_iter() - .enumerate() - .map(|(index, entry)| { - let is_row = matches!(entry, SidebarEntry::Row { .. }); - - if is_row { - row_position += 1; - } - - let (position_in_set, size_of_set) = if is_row { - (row_position, row_count) - } else { - (0, 0) - }; - - entry.render_entry( - cx, - index, - position_in_set, - size_of_set, - selected == Some(index), - material, - &on_change, - &focus, - ) - }) - .collect(); - - let body = div() - .id((id.clone(), "list")) - .flex_1() - .min_h_0() - .track_focus(&focus) - .focusable() - .tab_stop(true) - .role(Role::List) - .aria_label(label) - .on_key_down({ - let on_change = on_change.clone(); - move |event: &KeyDownEvent, window, cx| { - if nav_key(&selectable, selected, &event.keystroke.key, |next| { - if let Some(on_change) = &on_change { - on_change(next, window, cx); - } - }) { - cx.stop_propagation(); - } - } - }) - .child( - ScrollArea::new(scroll_area_id) - .handle(scroll.read(cx).clone()) - .h_full() - .child( - v_flex() - .gap_0p5() - .when(padded, |content| content.p_2()) - .children(children), - ), - ) - .into_any_element(); - - let theme = cx.theme(); - - v_flex() - .id(id.clone()) - .refine_style(&style) - .debug_selector(move || format!("sidebar-{debug_id}")) - .h_full() - .w(width) - .text_sm() - .when(border_right, |sidebar| { - sidebar - .border_r(BORDER_WIDTH) - .border_color(theme.colors.border) - }) - .child(body) - .when(material && grain, |sidebar| sidebar.child(grain_overlay())) - } -} - -impl SidebarEntry { #[allow(clippy::too_many_arguments)] fn render_entry( self, @@ -529,3 +267,227 @@ impl SidebarEntry { } } } + +// SidebarEntry is a data builder, not an element, adopt the combinators explicitly. +impl FluentBuilder for SidebarEntry {} + +/// A sidebar of [`SidebarEntry`] rows grouped under section headers. +#[derive(IntoElement)] +#[must_use] +pub struct Sidebar { + id: ElementId, + selected: Option, + transparent: bool, + grain: bool, + border_right: bool, + padded: bool, + width: Pixels, + a11y_label: Option, + on_change: Option, + entries: Option, + style: StyleRefinement, +} + +impl Sidebar { + /// Creates a sidebar with nothing selected. + pub fn new(id: I) -> Self + where + I: Into, + { + Self { + id: id.into(), + selected: None, + transparent: false, + grain: false, + border_right: true, + padded: true, + width: SIDEBAR_DEFAULT_WIDTH, + a11y_label: None, + on_change: None, + entries: None, + style: StyleRefinement::default(), + } + } + + /// Sets the current selection. + pub fn selected(mut self, selected: Option) -> Self { + self.selected = selected; + self + } + + /// Paints translucent material fills so the window's native backdrop shows through. + pub fn transparent(mut self, transparent: bool) -> Self { + self.transparent = transparent; + self + } + + /// Paints a hairline border on the sidebar's right edge. + pub fn border_right(mut self, border_right: bool) -> Self { + self.border_right = border_right; + self + } + + /// Reports the next selected row, from clicks and keys alike. + pub fn on_change(mut self, handler: F) -> Self + where + F: Fn(Option, &mut Window, &mut App) + 'static, + { + self.on_change = Some(Rc::new(handler)); + self + } + + /// Sets the entries; the closure runs during render and must not mutate entities or notify. + pub fn entries(mut self, entries: F) -> Self + where + F: Fn(&mut Window, &mut App) -> Vec + 'static, + { + self.entries = Some(Box::new(entries)); + self + } + + /// Overrides the accessibility label, which defaults to the id. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } +} + +impl gpui::Styled for Sidebar { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for Sidebar { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let Self { + id, + selected, + transparent: material, + grain, + border_right, + padded, + width, + a11y_label, + on_change, + entries, + style, + } = self; + + let label = a11y_label.unwrap_or_else(|| SharedString::from(id.to_string())); + let debug_id = id.clone(); + + let entries = match entries { + Some(build) => build(window, cx), + None => Vec::new(), + }; + + // Headers and custom entries are never selectable, only enabled rows are. + let selectable: Vec = entries + .iter() + .enumerate() + .filter(|(_, entry)| match entry { + SidebarEntry::Row { disabled, .. } => !disabled, + SidebarEntry::Header { .. } | SidebarEntry::Custom(_) => false, + }) + .map(|(index, _)| index) + .collect(); + + let focus = crate::components::common::focus_handle(&id, window, cx); + let scroll = window.with_element_namespace(id.clone(), |window| { + window + .use_keyed_state("scroll", cx, |_, _| gpui::ScrollHandle::new()) + .clone() + }); + let scroll_area_id = (id.clone(), "entries"); + + let row_count = entries + .iter() + .filter(|entry| matches!(entry, SidebarEntry::Row { .. })) + .count(); + let mut row_position = 0usize; + + let children: Vec = entries + .into_iter() + .enumerate() + .map(|(index, entry)| { + let is_row = matches!(entry, SidebarEntry::Row { .. }); + + if is_row { + row_position += 1; + } + + let (position_in_set, size_of_set) = if is_row { + (row_position, row_count) + } else { + (0, 0) + }; + + entry.render_entry( + cx, + index, + position_in_set, + size_of_set, + selected == Some(index), + material, + &on_change, + &focus, + ) + }) + .collect(); + + let theme = cx.theme(); + + v_flex() + .id(id.clone()) + .refine_style(&style) + .debug_selector(move || format!("sidebar-{debug_id}")) + .h_full() + .w(width) + .text_sm() + .when(border_right, |sidebar| { + sidebar + .border_r(BORDER_WIDTH) + .border_color(theme.colors.border) + }) + .child( + div() + .id((id.clone(), "list")) + .flex_1() + .min_h_0() + .track_focus(&focus) + .focusable() + .tab_stop(true) + .role(Role::List) + .aria_label(label) + .on_key_down({ + let on_change = on_change.clone(); + move |event: &KeyDownEvent, window, cx| { + if nav_key(&selectable, selected, &event.keystroke.key, |next| { + if let Some(on_change) = &on_change { + on_change(next, window, cx); + } + }) { + cx.stop_propagation(); + } + } + }) + .child( + ScrollArea::new(scroll_area_id) + .handle(scroll.read(cx).clone()) + .h_full() + .child( + v_flex() + .gap_0p5() + .when(padded, |content| content.p_2()) + .children(children), + ), + ) + .into_any_element(), + ) + .when(material && grain, |sidebar| sidebar.child(grain_overlay())) + } +} diff --git a/crates/ui/src/components/slider.rs b/crates/ui/src/components/slider.rs deleted file mode 100644 index b461549..0000000 --- a/crates/ui/src/components/slider.rs +++ /dev/null @@ -1,341 +0,0 @@ -//! Renders a controlled slider that reports its next value on click, drag, and arrow keys. -//! -//! # Examples -//! -//! ```no_run -//! use ui::slider::Slider; -//! -//! let opacity = Slider::new("opacity", 1.0) -//! .step(0.25) -//! .on_change(|value, _window, _cx| println!("opacity: {value}")); -//! ``` - -use std::cell::Cell; -use std::rc::Rc; - -use gpui::prelude::FluentBuilder as _; -use gpui::{ - App, Bounds, DispatchPhase, ElementId, InteractiveElement as _, IntoElement, KeyDownEvent, - MouseButton, MouseMoveEvent, MouseUpEvent, ParentElement as _, Pixels, RenderOnce, Role, - SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, canvas, - div, relative, -}; - -use crate::components::common::{Sizable, StyledExt as _, focus_ring, h_flex}; -use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; - -/// The change reporter, fired with the next value by click, drag, and arrows. -type ChangeHandler = Rc; - -/// The pointer→value setter shared by the click and drag listeners. -type ValueSetter = Rc; - -/// The arrow-key stride as a share of the range when the slider is continuous. -const FALLBACK_STEP_FRACTION: f32 = 0.05; - -impl Slider { - /// Clamps `value` into `[min, max]` and snaps it to `step` when stepped. - fn constrain(min: f32, max: f32, step: f32, value: f32) -> f32 { - let clamped = value.clamp(min, max); - if step > 0.0 { - (min + ((clamped - min) / step).round() * step).clamp(min, max) - } else { - clamped - } - } -} - -/// A controlled slider over `[min, max]`. -#[derive(IntoElement)] -#[must_use] -pub struct Slider { - id: ElementId, - min: f32, - max: f32, - step: f32, - value: f32, - size: Size, - disabled: bool, - a11y_label: Option, - on_change: Option, - style: StyleRefinement, -} - -impl Slider { - /// Creates a slider over `0..=1` with no stepping, at `value`. - pub fn new(id: I, value: f32) -> Self - where - I: Into, - { - Self { - id: id.into(), - min: 0.0, - max: 1.0, - step: 0.0, - value, - size: Size::default(), - disabled: false, - a11y_label: None, - on_change: None, - style: StyleRefinement::default(), - } - } - - /// Sets the range's lower bound. - pub fn min(mut self, min: f32) -> Self { - self.min = min; - self - } - - /// Sets the range's upper bound. - pub fn max(mut self, max: f32) -> Self { - self.max = max; - self - } - - /// Sets the step; values snap to `min + n * step`. `0` is continuous. - pub fn step(mut self, step: f32) -> Self { - self.step = step; - self - } - - /// Renders the slider inert, unfocusable, and dimmed; disabled always wins. - pub fn disabled(mut self, disabled: bool) -> Self { - self.disabled = disabled; - self - } - - /// Sets the accessibility label, required for an unlabeled slider. - pub fn accessibility_label(mut self, label: L) -> Self - where - L: Into, - { - self.a11y_label = Some(label.into()); - self - } - - /// Sets the change handler, fired with the next value by click, drag, and arrows. - pub fn on_change(mut self, handler: F) -> Self - where - F: Fn(f32, &mut Window, &mut App) + 'static, - { - self.on_change = Some(Rc::new(handler)); - self - } -} - -impl gpui::Styled for Slider { - fn style(&mut self) -> &mut StyleRefinement { - &mut self.style - } -} - -impl Sizable for Slider { - fn apply_size(&mut self, size: Size) { - self.size = size; - } -} - -impl RenderOnce for Slider { - fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { - let theme = cx.theme(); - let colors = theme.colors; - let ramps = theme.ramps; - let radius = theme.radius; - - let rem = window.rem_size(); - let row_height = self.size.slider_row_rems() * rem; - let track_height = self.size.slider_track_rems() * rem; - let knob = self.size.indicator_rems() * rem; - - let value = self.value.clamp(self.min, self.max); - let fraction = if self.max > self.min { - (value - self.min) / (self.max - self.min) - } else { - 0.0 - }; - - let bounds_cell = Rc::new(Cell::new(None::>)); - let focus_handle = crate::components::common::focus_handle(&self.id, window, cx); - - let dragging = - window.use_keyed_state((self.id.clone(), "slider-dragging"), cx, |_, _| false); - - let set_value: ValueSetter = { - let bounds_cell = bounds_cell.clone(); - let on_change = self.on_change.clone(); - let (min, max, step) = (self.min, self.max, self.step); - - Rc::new(move |x: Pixels, window: &mut Window, cx: &mut App| { - if let (Some(bounds), Some(on_change)) = (bounds_cell.get(), on_change.as_ref()) - && bounds.size.width > Pixels::ZERO - { - let fraction = ((x - bounds.origin.x) / bounds.size.width).clamp(0.0, 1.0); - on_change( - Self::constrain(min, max, step, min + fraction * (max - min)), - window, - cx, - ); - } - }) - }; - - let down_dragging = dragging.clone(); - let down_set_value = set_value.clone(); - let disabled = self.disabled; - - h_flex() - .id(self.id) - .relative() - .w_full() - .map(|slider| match self.size { - Size::XSmall => slider.h_6(), - Size::Small => slider.h_9(), - Size::Medium => slider.h_10(), - Size::Large => slider.h_12(), - }) - .refine_style(&self.style) - .role(Role::Slider) - .when_some(self.a11y_label.clone(), |slider, label| { - slider.aria_label(label) - }) - .aria_numeric_value(f64::from(value)) - .aria_min_numeric_value(f64::from(self.min)) - .aria_max_numeric_value(f64::from(self.max)) - .when(self.disabled, |slider| slider.opacity(DISABLED_OPACITY)) - .when(!self.disabled, |slider| { - slider - .track_focus(&focus_handle) - .tab_stop(true) - .focus_visible(|style| style.shadow(focus_ring(colors.ring))) - .on_mouse_down(MouseButton::Left, move |event, window, cx| { - down_dragging.update(cx, |dragging, _| *dragging = true); - down_set_value(event.position.x, window, cx); - }) - .on_key_down(move |event: &KeyDownEvent, window, cx| { - if !focus_handle.contains_focused(window, cx) { - return; - } - - let single_step = if self.step > 0.0 { - self.step - } else { - (self.max - self.min) * FALLBACK_STEP_FRACTION - }; - - let next = match event.keystroke.key.as_str() { - "left" | "down" => Some(value - single_step), - "right" | "up" => Some(value + single_step), - "home" => Some(self.min), - "end" => Some(self.max), - _ => None, - }; - - if let Some(next) = next - && let Some(on_change) = self.on_change.as_ref() - { - on_change( - Self::constrain(self.min, self.max, self.step, next), - window, - cx, - ); - cx.stop_propagation(); - } - }) - }) - .child( - canvas( - { - let bounds_cell = bounds_cell.clone(); - move |bounds, _, _| bounds_cell.set(Some(bounds)) - }, - { - let dragging = dragging.clone(); - let set_value = set_value.clone(); - move |_, _, window, _cx| { - if disabled { - return; - } - window.on_mouse_event({ - let dragging = dragging.clone(); - let set_value = set_value.clone(); - move |event: &MouseMoveEvent, phase, window, cx| { - if phase == DispatchPhase::Bubble - && *dragging.read(cx) - && event.pressed_button == Some(MouseButton::Left) - { - set_value(event.position.x, window, cx); - } - } - }); - window.on_mouse_event({ - let dragging = dragging.clone(); - move |event: &MouseUpEvent, phase, _window, cx| { - if phase == DispatchPhase::Bubble - && event.button == MouseButton::Left - { - dragging.update(cx, |dragging, _| *dragging = false); - } - } - }); - } - }, - ) - .absolute() - .inset_0(), - ) - .child( - div() - .absolute() - .left_0() - .top((row_height - track_height) / 2.0) - .map(|track| match self.size { - Size::XSmall => track.h_0p5(), - Size::Small | Size::Medium => track.h_1(), - Size::Large => track.h_1p5(), - }) - .w_full() - .rounded(radius.full) - .bg(colors.border), - ) - .child( - div() - .absolute() - .left_0() - .top((row_height - track_height) / 2.0) - .map(|track| match self.size { - Size::XSmall => track.h_0p5(), - Size::Small | Size::Medium => track.h_1(), - Size::Large => track.h_1p5(), - }) - .w(relative(fraction)) - .rounded(radius.full) - .bg(ramps.primary.base), - ) - .child( - h_flex() - .absolute() - .left_0() - .top_0() - .h_full() - .w(relative(fraction)) - .justify_end() - .items_center() - .child( - div() - .map(|dot| match self.size { - Size::XSmall => dot.size_2p5(), - Size::Small => dot.size_3p5(), - Size::Medium => dot.size_4(), - Size::Large => dot.size_5(), - }) - .flex_none() - .rounded(radius.full) - .bg(colors.primary_foreground) - .border_1() - .border_color(colors.border) - .mr(-knob / 2.0), - ), - ) - } -} diff --git a/crates/ui/src/components/speech.rs b/crates/ui/src/components/speech.rs deleted file mode 100644 index d603382..0000000 --- a/crates/ui/src/components/speech.rs +++ /dev/null @@ -1,1126 +0,0 @@ -//! Dictation: a state that turns speech into text, a button that drives the -//! session, and a waveform that shows what the microphone hears. -//! -//! The application owns where the text goes: subscribe to [`SpeechEvent`] and -//! insert the final transcript where it belongs. Recognition and capture are -//! both replaceable seams; without further setup the state uses [`Microphone`] -//! and has no recognizer, so [`SpeechButton`] renders nothing until the -//! application provides one. -//! -//! # Examples -//! -//! ```no_run -//! use ui::speech::{SpeechButton, SpeechRecognizer, SpeechState}; -//! -//! # use gpui::{App, AppContext as _}; -//! # fn bind(cx: &mut App, recognizer: R) -//! # where -//! # R: SpeechRecognizer + 'static, -//! # { -//! // Create the state once and hold its entity in the owning view. -//! let speech = cx.new(|cx| SpeechState::new(cx).recognizer(recognizer)); -//! -//! let dictation = SpeechButton::new(&speech); -//! # } -//! ``` - -#[cfg(not(target_arch = "wasm32"))] -use std::sync::{Arc, Mutex}; -use std::time::Duration; - -use gpui::prelude::FluentBuilder as _; -use gpui::{ - App, Context, Div, ElementId, Entity, EventEmitter, Hsla, InteractiveElement as _, IntoElement, - ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, - StyleRefinement, Styled, Subscription, Task, WeakEntity, Window, div, relative, rems, -}; - -use crate::components::common::{ControlSizing, Sizable, StyledExt as _, focus_ring, h_flex}; -use crate::components::spinner::Spinner; -use crate::components::tooltip::Tooltip; -use crate::icons::{IconRole, icon}; -use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, SPEECH_WAVEFORM_WIDTH, Size}; - -/// One input-level entry per this much of captured audio. -const LEVEL_BUCKET: Duration = Duration::from_millis(80); -/// The level history a waveform draws, one entry per [`LEVEL_BUCKET`]. -const MAX_LEVELS: usize = 128; -/// Amplitude below which background noise reads as silence. -const NOISE_GATE: f32 = 0.03; -/// How much of a full-scale peak maps to a full bar. -const LEVEL_SCALE: f32 = 0.5; -/// How fast a peak falls back before the next bucket's level. -const LEVEL_FALL: f32 = 0.72; -/// How long a session waits for the recognizer's final result once stopped. -const DEFAULT_STOP_TIMEOUT: Duration = Duration::from_secs(3); -/// The bars [`SpeechButton`] shows while capturing. -const BUTTON_BARS: usize = 4; -/// The share of the bar height a silent bar keeps, so silence reads as a dot. -const DOT_HEIGHT: f32 = 0.14; -/// The bar height reduced motion holds at. -const STILL_HEIGHT: f32 = 0.35; - -/// The PCM layout a recognizer consumes: interleaved 16-bit samples. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct AudioFormat { - sample_rate: u32, - channels: u8, -} - -impl AudioFormat { - /// Creates a format at the given sample rate and channel count. - pub fn new(sample_rate: u32, channels: u8) -> Self { - Self { - sample_rate, - channels: channels.max(1), - } - } - - /// Samples per second per channel. - pub fn sample_rate(&self) -> u32 { - self.sample_rate - } - - /// The number of interleaved channels. - pub fn channels(&self) -> u8 { - self.channels - } -} - -impl Default for AudioFormat { - /// 16 kHz mono, what most recognizers consume. - fn default() -> Self { - Self::new(16_000, 1) - } -} - -/// Why a dictation session failed. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct SpeechError { - message: SharedString, -} - -impl SpeechError { - /// A recognizer failed to start or to report a result. - pub fn recognizer(error: E) -> Self - where - E: std::fmt::Display, - { - Self::new(format!("Speech recognizer error: {error}")) - } - - /// Audio capture failed to start or to deliver samples. - pub fn input(error: E) -> Self - where - E: std::fmt::Display, - { - Self::new(format!("Audio input error: {error}")) - } - - fn new(message: String) -> Self { - Self { - message: message.into(), - } - } -} - -impl std::fmt::Display for SpeechError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(&self.message) - } -} - -impl std::error::Error for SpeechError {} - -/// Turns captured audio into text. -pub trait SpeechRecognizer { - /// The PCM layout [`RecognitionSession::push_audio`] delivers. - fn audio_format(&self) -> AudioFormat { - AudioFormat::default() - } - - /// Whether the recognizer can run right now. - fn is_available(&self, _cx: &App) -> bool { - true - } - - /// Opens a session. - /// - /// # Errors - /// - /// Errors when the recognizer cannot open a session. - fn start( - &self, - sink: SpeechSink, - cx: &mut App, - ) -> Result, SpeechError>; -} - -/// A recognition session opened by [`SpeechRecognizer::start`]. -pub trait RecognitionSession { - /// Delivers interleaved 16-bit PCM in the recognizer's [`SpeechRecognizer::audio_format`]. - fn push_audio(&mut self, samples: &[i16], cx: &mut App); - - /// The user stopped talking. - fn finish(&mut self, cx: &mut App); -} - -/// Reports recognition results for the active session. -#[derive(Clone)] -pub struct SpeechSink { - state: WeakEntity, - generation: u64, -} - -impl SpeechSink { - /// The recognizer accepts audio; the status moves to `Recording`. - pub fn ready(&self, cx: &mut App) { - self.defer(cx, |state, cx| state.mark_ready(cx)); - } - - /// Replaces the hypothesis of the phrase being spoken. - pub fn hypothesis(&self, text: T, cx: &mut App) - where - T: Into + 'static, - { - self.defer(cx, move |state, cx| { - state.report_hypothesis(text.into(), cx) - }); - } - - /// Commits a recognized phrase to the transcript. - pub fn phrase(&self, text: T, cx: &mut App) - where - T: Into + 'static, - { - self.defer(cx, move |state, cx| state.report_phrase(text.into(), cx)); - } - - /// Ends the session normally with what has been recognized so far. - pub fn finish(&self, cx: &mut App) { - self.defer(cx, |state, cx| state.report_finish(cx)); - } - - /// Ends the session with a failure. - pub fn error(&self, error: SpeechError, cx: &mut App) { - self.defer(cx, move |state, cx| state.report_error(error, cx)); - } - - fn defer(&self, cx: &mut App, apply: F) - where - F: FnOnce(&mut SpeechState, &mut Context) + 'static, - { - let state = self.state.clone(); - let generation = self.generation; - cx.defer(move |cx| { - // A report arriving after the state dropped is a normal lifecycle outcome. - if let Some(state) = state.upgrade() { - state.update(cx, |state, cx| state.apply(generation, cx, apply)); - } - }); - } -} - -/// Captures audio for a session. -pub trait AudioInput { - /// Starts capture in `format`, pushing samples to `sink`; dropping the - /// returned `Subscription` stops capture. - /// - /// # Errors - /// - /// Errors when capture cannot start; no samples are delivered. - fn start( - &self, - format: AudioFormat, - sink: AudioSink, - cx: &mut App, - ) -> Result; -} - -/// Delivers captured audio to the active session. -#[derive(Clone)] -pub struct AudioSink { - state: WeakEntity, - generation: u64, -} - -impl AudioSink { - /// Pushes interleaved 16-bit PCM in the recognizer's format. - pub fn push(&self, samples: S, cx: &mut App) - where - S: Into> + 'static, - { - let state = self.state.clone(); - let generation = self.generation; - cx.defer(move |cx| { - // Audio arriving after the state dropped is a normal lifecycle outcome. - if let Some(state) = state.upgrade() { - state.update(cx, |state, cx| { - state.receive_audio(generation, samples.into(), cx) - }); - } - }); - } -} - -/// Where a dictation session is in its life. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum SpeechStatus { - /// No session is running. - #[default] - Idle, - /// Audio is captured while the recognizer connects. - Connecting, - /// Audio is captured and recognized. - Recording, - /// Capture stopped; waiting for the final result. - Stopping, -} - -impl SpeechStatus { - /// True for every status but `Idle`. - pub fn is_active(self) -> bool { - self != Self::Idle - } - - /// True while audio is captured. - pub fn is_capturing(self) -> bool { - matches!(self, Self::Connecting | Self::Recording) - } -} - -/// What a session reports. -#[derive(Clone, Debug, PartialEq)] -pub enum SpeechEvent { - /// A session started and audio is being captured. - Started, - /// The transcript changed while the user speaks. - Partial(SharedString), - /// The session ended normally. The text may be empty. - Final(SharedString), - /// The session was cancelled and its transcript discarded. - Cancelled, - /// The session failed and ended. - Error(SpeechError), -} - -/// Owns a dictation session. -pub struct SpeechState { - recognizer: Option>, - input: Option>, - stop_timeout: Duration, - format: AudioFormat, - status: SpeechStatus, - phrases: Vec, - hypothesis: Option, - levels: Vec, - bucket: Vec, - session: Option>, - capture: Option, - generation: u64, - stop_task: Option>, -} - -impl EventEmitter for SpeechState {} - -impl SpeechState { - /// Creates an idle state without a recognizer or input. - pub fn new(_cx: &mut Context) -> Self { - Self { - recognizer: None, - input: None, - stop_timeout: DEFAULT_STOP_TIMEOUT, - format: AudioFormat::default(), - status: SpeechStatus::Idle, - phrases: Vec::new(), - hypothesis: None, - levels: Vec::new(), - bucket: Vec::new(), - session: None, - capture: None, - generation: 0, - stop_task: None, - } - } - - /// Sets the recognizer every session runs with. - pub fn recognizer(mut self, recognizer: R) -> Self - where - R: SpeechRecognizer + 'static, - { - self.recognizer = Some(Box::new(recognizer)); - self - } - - /// Sets the audio source every session captures with. - pub fn input(mut self, input: I) -> Self - where - I: AudioInput + 'static, - { - self.input = Some(Box::new(input)); - self - } - - /// How long `stop` waits for the recognizer's final result. - pub fn stop_timeout(mut self, timeout: Duration) -> Self { - self.stop_timeout = timeout; - self - } - - /// Where the session is. - pub fn status(&self) -> SpeechStatus { - self.status - } - - /// Whether a session can run on this platform. - pub fn has_recognizer(&self) -> bool { - self.recognizer.is_some() && (self.input.is_some() || Self::has_default_input()) - } - - /// Whether the recognizer reports itself ready to run. - pub fn is_available(&self, cx: &App) -> bool { - self.recognizer - .as_ref() - .is_some_and(|recognizer| recognizer.is_available(cx)) - } - - /// The whole transcript so far. - pub fn transcript(&self) -> SharedString { - let mut transcript = String::new(); - - for phrase in &self.phrases { - transcript.push_str(phrase); - } - - if let Some(hypothesis) = &self.hypothesis { - transcript.push_str(hypothesis); - } - - transcript.into() - } - - /// The recent input levels in `0.0..=1.0`, oldest first, one per 80 ms of audio. - pub fn levels(&self) -> &[f32] { - &self.levels - } - - /// Starts a session. Does nothing while one is running. - pub fn start(&mut self, cx: &mut Context) { - if self.status.is_active() { - return; - } - - self.generation = self.generation.wrapping_add(1); - let generation = self.generation; - - let Some(recognizer) = self.recognizer.as_ref() else { - self.fail("No speech recognizer is set up on this platform.", cx); - return; - }; - - if !recognizer.is_available(cx) { - self.fail("The speech recognizer is not available right now.", cx); - return; - } - - self.format = recognizer.audio_format(); - let sink = SpeechSink { - state: cx.entity().downgrade(), - generation, - }; - - let session = match recognizer.start(sink, cx) { - Ok(session) => session, - Err(error) => { - self.fail(error, cx); - return; - } - }; - - let audio_sink = AudioSink { - state: cx.entity().downgrade(), - generation, - }; - - let capture = match self.capture_input(self.format, audio_sink, cx) { - Ok(capture) => capture, - Err(error) => { - self.fail(error, cx); - return; - } - }; - - self.session = Some(session); - self.capture = Some(capture); - self.phrases.clear(); - self.hypothesis = None; - self.levels.clear(); - self.bucket.clear(); - self.status = SpeechStatus::Connecting; - cx.emit(SpeechEvent::Started); - cx.notify(); - } - - /// Ends the session and emits `Final` once the result is in, at the latest after the stop timeout. - pub fn stop(&mut self, cx: &mut Context) { - if !self.status.is_capturing() { - return; - } - self.capture = None; - self.status = SpeechStatus::Stopping; - cx.notify(); - - let generation = self.generation; - let stop_timeout = self.stop_timeout; - - if let Some(mut session) = self.session.take() { - session.finish(cx); - } - - self.stop_task = Some(cx.spawn(async move |this, cx| { - cx.background_executor().timer(stop_timeout).await; - // The state may drop while the timeout is still pending. - this.update(cx, |state, cx| state.apply_stop_timeout(generation, cx)) - .ok(); - })); - } - - /// Cancels the session at once and discards its transcript. - pub fn cancel(&mut self, cx: &mut Context) { - if !self.status.is_active() { - return; - } - self.capture = None; - self.session = None; - self.stop_task = None; - self.reset(); - cx.emit(SpeechEvent::Cancelled); - cx.notify(); - } - - /// `start` when idle, otherwise `stop`. - pub fn toggle(&mut self, cx: &mut Context) { - if self.status == SpeechStatus::Idle { - self.start(cx); - } else { - self.stop(cx); - } - } - - fn has_default_input() -> bool { - cfg!(not(target_arch = "wasm32")) - } - - #[cfg(not(target_arch = "wasm32"))] - fn default_input() -> Option> { - Some(Box::new(Microphone)) - } - - #[cfg(target_arch = "wasm32")] - fn default_input() -> Option> { - None - } - - fn capture_input( - &self, - format: AudioFormat, - sink: AudioSink, - cx: &mut App, - ) -> Result { - if let Some(input) = &self.input { - return input.start(format, sink, cx); - } - match Self::default_input() { - Some(input) => input.start(format, sink, cx), - None => Err(SpeechError::input( - "No audio input is available on this platform; provide one with `SpeechState::input`.", - )), - } - } - - fn reset(&mut self) { - self.generation = self.generation.wrapping_add(1); - self.status = SpeechStatus::Idle; - self.phrases.clear(); - self.hypothesis = None; - self.levels.clear(); - self.bucket.clear(); - } - - /// Ends a failed start without ever emitting `Started`. - fn fail(&mut self, message: M, cx: &mut Context) - where - M: std::fmt::Display, - { - self.capture = None; - self.session = None; - self.reset(); - cx.emit(SpeechEvent::Error(SpeechError::new(message.to_string()))); - cx.notify(); - } - - /// Ends the session normally, emitting `Final` with the transcript so far. - fn finalize(&mut self, cx: &mut Context) { - self.capture = None; - self.session = None; - self.stop_task = None; - let transcript = self.transcript(); - self.reset(); - cx.emit(SpeechEvent::Final(transcript)); - cx.notify(); - } - - fn apply(&mut self, generation: u64, cx: &mut Context, apply: F) - where - F: FnOnce(&mut Self, &mut Context), - { - if self.generation != generation { - return; - } - apply(self, cx); - } - - fn mark_ready(&mut self, cx: &mut Context) { - if self.status == SpeechStatus::Connecting { - self.status = SpeechStatus::Recording; - cx.notify(); - } - } - - fn report_hypothesis(&mut self, text: SharedString, cx: &mut Context) { - if !self.status.is_active() { - return; - } - self.hypothesis = Some(text); - cx.emit(SpeechEvent::Partial(self.transcript())); - cx.notify(); - } - - fn report_phrase(&mut self, text: SharedString, cx: &mut Context) { - if !self.status.is_active() { - return; - } - self.phrases.push(text); - self.hypothesis = None; - cx.emit(SpeechEvent::Partial(self.transcript())); - cx.notify(); - } - - fn report_finish(&mut self, cx: &mut Context) { - if self.status.is_active() { - self.finalize(cx); - } - } - - fn report_error(&mut self, error: SpeechError, cx: &mut Context) { - if !self.status.is_active() { - return; - } - self.capture = None; - self.session = None; - self.stop_task = None; - self.reset(); - cx.emit(SpeechEvent::Error(error)); - cx.notify(); - } - - fn apply_stop_timeout(&mut self, generation: u64, cx: &mut Context) { - if self.generation == generation && self.status == SpeechStatus::Stopping { - self.finalize(cx); - } - } - - fn receive_audio(&mut self, generation: u64, samples: Vec, cx: &mut Context) { - if self.generation != generation || !self.status.is_capturing() { - return; - } - if let Some(session) = self.session.as_mut() { - session.push_audio(&samples, cx); - } - if self.update_levels(&samples) { - cx.notify(); - } - } - - /// Fills one level per bucket; returns whether any level was recorded. - fn update_levels(&mut self, samples: &[i16]) -> bool { - let channels = self.format.channels() as usize; - let bucket_len = ((self.format.sample_rate() as f32 * LEVEL_BUCKET.as_secs_f32()) as usize - * channels) - .max(channels); - self.bucket.extend_from_slice(samples); - - let mut recorded = false; - while self.bucket.len() >= bucket_len { - let peak = self - .bucket - .drain(..bucket_len) - .map(|sample| sample.unsigned_abs() as f32 / i16::MAX as f32) - .fold(0.0f32, f32::max); - let previous = self.levels.last().copied().unwrap_or(0.0); - let level = ((peak - NOISE_GATE).max(0.0) / LEVEL_SCALE) - .min(1.0) - .max(previous * LEVEL_FALL); - self.levels.push(level); - if self.levels.len() > MAX_LEVELS { - self.levels.remove(0); - } - recorded = true; - } - recorded - } -} - -/// Starts and stops a dictation session. -#[derive(IntoElement)] -#[must_use] -pub struct SpeechButton { - speech: Entity, - size: Size, - disabled: bool, - show_when_unsupported: bool, - style: StyleRefinement, -} - -impl SpeechButton { - /// Creates the button driving the given state. - pub fn new(speech: &Entity) -> Self { - Self { - speech: speech.clone(), - size: Size::default(), - disabled: false, - show_when_unsupported: false, - style: StyleRefinement::default(), - } - } - - /// Shows the button even when dictation is unsupported, rendered disabled. - pub fn show_when_unsupported(mut self, show: bool) -> Self { - self.show_when_unsupported = show; - self - } - - /// Disables the button for application reasons, such as a readonly field. - pub fn disabled(mut self, disabled: bool) -> Self { - self.disabled = disabled; - self - } -} - -impl gpui::Styled for SpeechButton { - fn style(&mut self) -> &mut StyleRefinement { - &mut self.style - } -} - -impl Sizable for SpeechButton { - fn apply_size(&mut self, size: Size) { - self.size = size; - } -} - -/// The waveform bar elements for a dictation control's level history. -fn waveform_bars<'a>( - levels: &'a [f32], - size: Size, - cx: &'a App, - bar_color: impl Fn(f32) -> Hsla + 'a, -) -> impl IntoIterator + 'a { - let theme = cx.theme(); - let bar_height = move |level: f32| { - if theme.accessibility.reduce_motion { - STILL_HEIGHT - } else { - DOT_HEIGHT + (1.0 - DOT_HEIGHT) * level - } - }; - - levels.iter().map(move |level| { - div() - .flex_none() - .w(rems(size.dense_icon_rems().0 / 4.0)) - .h(relative(bar_height(*level))) - .rounded(theme.radius.full) - .bg(bar_color(*level)) - }) -} - -impl RenderOnce for SpeechButton { - fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { - let unsupported = !self.speech.read(cx).has_recognizer(); - if unsupported && !self.show_when_unsupported { - return div().into_any_element(); - } - - let (status, unavailable, capturing, bars) = { - let state = self.speech.read(cx); - let status = state.status(); - let levels = state.levels(); - let tail_start = levels.len().saturating_sub(BUTTON_BARS); - ( - status, - unsupported || !state.is_available(cx), - status.is_capturing(), - levels[tail_start..].to_vec(), - ) - }; - - let stopping = status == SpeechStatus::Stopping; - let disabled = self.disabled || unavailable || stopping; - - let theme = cx.theme(); - let colors = theme.colors; - let size = self.size; - let id: ElementId = ("speech-button", self.speech.entity_id()).into(); - - let group = SharedString::from(format!( - "speech-button-{}", - self.speech.entity_id().as_u64() - )); - - let label: SharedString = if unavailable { - "Dictation is unavailable".into() - } else if capturing { - "Stop dictation".into() - } else { - "Start dictation".into() - }; - - let foreground = colors.foreground; - let bar_color = |_| theme.ramps.primary.base; - - h_flex() - .id(id.clone()) - .group(group.clone()) - .role(Role::Button) - .justify_center() - .control_height(size) - .control_dense_padding_x(size) - .gap_0p5() - .rounded(theme.radius.control) - .text_color(foreground) - .when(capturing, |button| button.bg(colors.muted)) - .refine_style(&self.style) - .when(disabled, |button| button.opacity(DISABLED_OPACITY)) - .aria_label(label.clone()) - .tooltip(Tooltip::text(label)) - .child(if stopping { - Spinner::new(("speech-spinner", self.speech.entity_id())) - .with_size(self.size) - .color(foreground) - .into_any_element() - } else if capturing { - h_flex() - .id(("speech-bars", self.speech.entity_id())) - .h(size.icon_rems()) - .items_end() - .gap_0p5() - .children(waveform_bars(&bars, size, cx, bar_color)) - .group_hover(group.clone(), |style| style.invisible()) - .into_any_element() - } else { - icon(IconRole::Microphone) - .size(size.icon_rems()) - .color(foreground) - .into_any_element() - }) - .when(capturing, |button| { - button.child( - div() - .invisible() - .group_hover(group, |style| style.visible()) - .child( - icon(IconRole::Stop) - .size(size.icon_rems()) - .color(foreground), - ), - ) - }) - .when(!disabled, |button| { - let speech = self.speech.clone(); - button - .cursor_pointer() - .focusable() - .tab_stop(true) - .hover(move |style| style.bg(colors.muted_hover)) - .active(move |style| style.bg(theme.ramps.secondary.pressed)) - .focus_visible(move |style| style.shadow(focus_ring(colors.ring))) - .on_click(move |_, _, cx| speech.update(cx, |state, cx| state.toggle(cx))) - }) - .into_any_element() - } -} - -/// A live waveform of what a dictation session hears. -#[derive(IntoElement)] -#[must_use] -pub struct SpeechWaveform { - speech: Entity, - size: Size, - style: gpui::StyleRefinement, -} - -impl SpeechWaveform { - /// Creates the waveform drawn from the given state. - pub fn new(speech: &Entity) -> Self { - Self { - speech: speech.clone(), - size: Size::default(), - style: gpui::StyleRefinement::default(), - } - } -} - -impl Sizable for SpeechWaveform { - fn apply_size(&mut self, size: Size) { - self.size = size; - } -} - -impl Styled for SpeechWaveform { - fn style(&mut self) -> &mut gpui::StyleRefinement { - &mut self.style - } -} - -impl RenderOnce for SpeechWaveform { - fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { - if !self.speech.read(cx).status().is_capturing() { - return div().into_any_element(); - } - let levels = { - let state = self.speech.read(cx); - state.levels().to_vec() - }; - - let theme = cx.theme(); - let colors = theme.colors; - let size = self.size; - let bar_color = |level: f32| { - if level <= 0.0 { - colors.muted_foreground - } else { - theme.ramps.primary.base - } - }; - - h_flex() - .id(("speech-waveform", self.speech.entity_id())) - .items_end() - .justify_end() - .gap_0p5() - .h(size.icon_rems()) - .w(SPEECH_WAVEFORM_WIDTH) - .overflow_hidden() - .children(waveform_bars(&levels, size, cx, bar_color)) - .refine_style(&self.style) - .into_any_element() - } -} - -#[cfg(not(target_arch = "wasm32"))] -/// The built-in input. -pub struct Microphone; - -#[cfg(not(target_arch = "wasm32"))] -impl AudioInput for Microphone { - fn start( - &self, - format: AudioFormat, - sink: AudioSink, - cx: &mut App, - ) -> Result { - use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; - - let host = cpal::default_host(); - let device = host - .default_input_device() - .ok_or_else(|| SpeechError::input("No microphone is connected."))?; - - let config = device.default_input_config().map_err(SpeechError::input)?; - let stream_config = cpal::StreamConfig { - channels: config.channels(), - sample_rate: config.sample_rate(), - buffer_size: cpal::BufferSize::Default, - }; - let device_channels = stream_config.channels.max(1) as usize; - - let (sender, receiver) = flume::unbounded::, String>>(); - let converter = Arc::new(Mutex::new(Resampler::new( - config.sample_rate() as f32 / format.sample_rate().max(1) as f32, - ))); - let error_handler = { - let sender = sender.clone(); - move |error: cpal::Error| { - log::warn!("microphone stream error: {error}"); - if sender.send(Err(error.to_string())).is_err() { - log::debug!("speech session closed before its stream error arrived"); - } - } - }; - - let stream = match config.sample_format() { - cpal::SampleFormat::F32 => device.build_input_stream( - stream_config, - Microphone::callback( - |sample: f32| sample, - device_channels, - format, - converter.clone(), - sender.clone(), - ), - error_handler, - None, - ), - cpal::SampleFormat::I16 => device.build_input_stream( - stream_config, - Microphone::callback( - |sample: i16| sample as f32 / i16::MAX as f32, - device_channels, - format, - converter.clone(), - sender.clone(), - ), - error_handler, - None, - ), - cpal::SampleFormat::U16 => device.build_input_stream( - stream_config, - Microphone::callback( - |sample: u16| (sample as f32 - u16::MAX as f32 / 2.0) / (u16::MAX as f32 / 2.0), - device_channels, - format, - converter.clone(), - sender.clone(), - ), - error_handler, - None, - ), - sample_format => { - return Err(SpeechError::input(format!( - "Unsupported microphone sample format: {sample_format}" - ))); - } - } - .map_err(SpeechError::input)?; - - stream.play().map_err(SpeechError::input)?; - - let task = cx.spawn(async move |cx| { - while let Ok(message) = receiver.recv_async().await { - match message { - Ok(samples) => cx.update(|cx| sink.push(samples, cx)), - Err(message) => { - let error = SpeechError::input(message); - let state = sink.state.clone(); - let generation = sink.generation; - cx.update(move |cx| { - if let Some(state) = state.upgrade() { - state.update(cx, |state, cx| { - state.apply(generation, cx, |state, cx| { - state.report_error(error, cx) - }) - }); - } - }); - } - } - } - }); - - Ok(Subscription::new(move || { - drop(stream); - drop(task); - })) - } -} - -#[cfg(not(target_arch = "wasm32"))] -impl Microphone { - fn callback( - to_sample: fn(T) -> f32, - device_channels: usize, - format: AudioFormat, - converter: Arc>, - sender: flume::Sender, String>>, - ) -> impl FnMut(&[T], &cpal::InputCallbackInfo) + Send + 'static - where - T: Copy + 'static, - { - move |data: &[T], _: &cpal::InputCallbackInfo| { - // A panic while resampling poisons the lock; the phase is - // approximate anyway, so recover and keep the stream alive. - let mut converter = match converter.lock() { - Ok(converter) => converter, - Err(poisoned) => { - log::warn!("microphone resampler lock was poisoned; recovering"); - poisoned.into_inner() - } - }; - - let mut mono = Vec::with_capacity(data.len() / device_channels + 1); - for frame in data.chunks(device_channels) { - let total: f32 = frame.iter().map(|sample| to_sample(*sample)).sum(); - mono.push(total / frame.len() as f32); - } - - let mut resampled = Vec::with_capacity(mono.len()); - converter.resample(&mono, &mut resampled); - - let channels = format.channels() as usize; - let mut samples = Vec::with_capacity(resampled.len() * channels); - - for value in resampled { - let sample = (value * i16::MAX as f32) - .round() - .clamp(i16::MIN as f32, i16::MAX as f32) as i16; - for _ in 0..channels { - samples.push(sample); - } - } - - if sender.send(Ok(samples)).is_err() { - log::debug!("speech session closed before its audio arrived"); - } - } - } -} - -#[cfg(not(target_arch = "wasm32"))] -/// A minimal linear resampler that carries its phase across callbacks. -struct Resampler { - step: f32, - phase: f32, - last: Option, -} - -#[cfg(not(target_arch = "wasm32"))] -impl Resampler { - fn new(step: f32) -> Self { - Self { - step, - phase: 0.0, - last: None, - } - } - - fn resample(&mut self, input: &[f32], output: &mut Vec) { - if input.is_empty() { - return; - } - let mut phase = self.phase; - while phase < input.len() as f32 { - let index = (phase as usize).min(input.len() - 1); - let fraction = phase - index as f32; - let previous = if index == 0 { - self.last.unwrap_or(input[0]) - } else { - input[index - 1] - }; - output.push(previous + (input[index] - previous) * fraction); - phase += self.step; - } - self.phase = phase - input.len() as f32; - self.last = Some(input[input.len() - 1]); - } -} diff --git a/crates/ui/src/components/spinner.rs b/crates/ui/src/components/spinner.rs index 4e3fbb5..a85b0bb 100644 --- a/crates/ui/src/components/spinner.rs +++ b/crates/ui/src/components/spinner.rs @@ -10,11 +10,12 @@ use gpui::prelude::FluentBuilder as _; use gpui::{ - App, ElementId, Hsla, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, - Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, div, + AnyElement, App, ElementId, Hsla, InteractiveElement as _, IntoElement, ParentElement as _, + RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, + Window, div, }; -use crate::components::common::{Sizable, StyledExt as _}; +use crate::components::common::{Sizable, StyledExt as _, v_flex}; use crate::icons::{IconRole, icon}; use crate::theme::{ActiveTheme as _, SPINNER_PERIOD, Size}; @@ -44,6 +45,19 @@ impl Spinner { } } + /// The spinner centered in the full available space. + pub fn centered(id: I) -> AnyElement + where + I: Into, + { + v_flex() + .size_full() + .items_center() + .justify_center() + .child(Self::new(id)) + .into_any_element() + } + /// Overrides the icon color, for accent-filled surfaces. pub fn color(mut self, color: Hsla) -> Self { self.color = Some(color); diff --git a/crates/ui/src/components/status_dot.rs b/crates/ui/src/components/status_dot.rs index a545794..8c9cdbe 100644 --- a/crates/ui/src/components/status_dot.rs +++ b/crates/ui/src/components/status_dot.rs @@ -107,21 +107,20 @@ impl RenderOnce for StatusDot { let size = self.size; let color = self.variant.color(theme); - let dot = div() + div() .id(self.id.clone()) .debug_selector(move || self.id.to_string()) .flex_none() .rounded(theme.radius.full) - .bg(color); - let dot = match size { - Size::XSmall => dot.size_1p5(), - Size::Small | Size::Medium => dot.size_2(), - Size::Large => dot.size_2p5(), - }; - - dot.when_some(self.label, |dot, label| { - dot.role(Role::Status).aria_label(label) - }) - .refine_style(&self.style) + .bg(color) + .map(|dot| match size { + Size::XSmall => dot.size_1p5(), + Size::Small | Size::Medium => dot.size_2(), + Size::Large => dot.size_2p5(), + }) + .refine_style(&self.style) + .when_some(self.label, |dot, label| { + dot.role(Role::Status).aria_label(label) + }) } } diff --git a/crates/ui/src/components/tabs.rs b/crates/ui/src/components/tabs.rs index d8d3092..06d3c9d 100644 --- a/crates/ui/src/components/tabs.rs +++ b/crates/ui/src/components/tabs.rs @@ -388,6 +388,292 @@ impl Tab { self.wrap = Some(Box::new(wrap)); self } + + fn render_tab(mut self, ctx: &StripCtx, cx: &App, index: usize) -> AnyElement { + let selected = index == ctx.selected; + // A pinned tab always wears the active treatment, selected or not. + let active = selected || self.pinned; + + let theme = cx.theme(); + let label_color = tab_label_color(ctx.variant, active, self.disabled, cx); + + let titlebar = ctx.variant == TabsVariant::Titlebar; + let group = SharedString::from(format!("{}-tab-{}", ctx.id, self.key)); + let close = (self.closeable && ctx.on_close.is_some() && !self.disabled) + .then(|| self.render_tab_close(&ctx.id, index, &ctx.on_close)); + + let label = div() + .flex_grow(1.0) + .when(titlebar, |label| { + let fade = if active { + theme.colors.background + } else { + theme.colors.muted + }; + + let hover_fade = if active { + theme.colors.background + } else { + theme.colors.muted_hover + }; + + let fade_width = rems(0.75); + let hover_fade_width = rems(1.5); + + label + .min_w_0() + .relative() + .overflow_hidden() + .child( + div() + .w_full() + .whitespace_nowrap() + .text_overflow(TextOverflow::Truncate(SharedString::default())) + .child(self.label.clone()), + ) + .child( + div() + .absolute() + .top_0() + .right_0() + .bottom_0() + .w(fade_width) + .bg(linear_gradient( + 90., + linear_color_stop(fade.opacity(0.), 0.), + linear_color_stop(fade, 1.), + )), + ) + .child( + div() + .absolute() + .top_0() + .right_0() + .bottom_0() + .w(hover_fade_width) + .bg(linear_gradient( + 90., + linear_color_stop(hover_fade.opacity(0.), 0.), + linear_color_stop(hover_fade, 1.), + )) + .invisible() + .group_hover(group.clone(), |style| style.visible()), + ) + }) + .when(!titlebar, |label| label.child(self.label.clone())); + + let strip_tab = div() + .id((self.key.clone(), "tab")) + .debug_selector({ + let tabs_id = ctx.id.clone(); + let label = self.label.clone(); + move || format!("{tabs_id}-tab-{}", label) + }) + .flex() + .items_center() + .gap_2() + .role(Role::Tab) + .aria_selected(selected) + .text_color(label_color) + .when(titlebar, |strip_tab| strip_tab.group(group.clone())) + .when(!self.disabled && !active, |strip_tab| { + strip_tab.hover(|strip_tab| { + strip_tab.bg(match ctx.variant { + TabsVariant::Titlebar => theme.colors.muted_hover, + _ => theme.colors.muted, + }) + }) + }) + .map(|strip_tab| { + apply_tab_chrome(strip_tab, ctx.variant, active, cx).when(titlebar, |strip_tab| { + strip_tab.min_w(TAB_MIN_WIDTH).max_w(TAB_MAX_WIDTH) + }) + }) + .when_some(self.lead.take(), |strip_tab, lead| strip_tab.child(lead)) + .child(label) + .when(ctx.variant == TabsVariant::Pill, |strip_tab| { + strip_tab.child(div().flex_none().w_4()) + }) + .when(self.busy && !self.disabled, |strip_tab| { + strip_tab.child( + Spinner::new((self.key.clone(), "tab-busy")) + .small() + .accessibility_label("Loading"), + ) + }) + .when_some(close, |strip_tab, close| { + if titlebar { + strip_tab.child( + div() + .flex_none() + .invisible() + .group_hover(group, |style| style.visible()) + .child(close), + ) + } else { + strip_tab.child(close) + } + }) + .when( + { + let drop = ctx.drop_at.read(cx); + drop.onto == Some(index) && !drop.canceled() + }, + |strip_tab| { + strip_tab.child( + div() + .absolute() + .left_0() + .top_0p5() + .bottom_0p5() + .w_0p5() + .rounded(theme.radius.sm) + .bg(theme.ramps.primary.base), + ) + }, + ) + .when_some(ctx.measure.clone(), |strip_tab, measure| { + let key = measure.key.clone(); + let root_bounds = measure.root_bounds.clone(); + let tab_key = self.key.to_string(); + strip_tab.child( + canvas( + move |bounds, _, cx| { + let root = root_bounds.borrow(); + if let Some(root) = root.as_ref() { + cx.default_global::().record_tab( + &key, + tab_key, + TabMeasure { + left: bounds.origin.x - root.origin.x, + width: bounds.size.width, + }, + ); + } + }, + |_, _, _, _| {}, + ) + .absolute() + .inset_0(), + ) + }) + .when(!self.disabled, |strip_tab| { + strip_tab.cursor_pointer().on_click({ + let selected = ctx.selected; + let on_change = ctx.on_change.clone(); + let focus = ctx.focus.clone(); + move |_, window, cx| { + window.focus(&focus, cx); + if index != selected + && let Some(on_change) = &on_change + { + on_change(index, window, cx); + } + } + }) + }) + .when(ctx.draggable && !self.disabled, |strip_tab| { + strip_tab + .on_mouse_down(MouseButton::Left, { + let drop_at = ctx.drop_at.clone(); + move |event, _, cx| { + cx.stop_propagation(); + drop_at.update(cx, |drop, cx| { + let fresh = TabDrop { + origin: Some(event.position), + ..TabDrop::default() + }; + if *drop != fresh { + *drop = fresh; + cx.notify(); + } + }); + } + }) + .on_drag(TabDrag { index }, { + let label = self.label.clone(); + move |_, _, _, cx| { + cx.new(|_| TabDragPreview { + label: label.clone(), + }) + } + }) + .drag_over::({ + let drop_at = ctx.drop_at.clone(); + move |style, drag, _, cx| { + let drop = *drop_at.read(cx); + let hovered = drag.index != index && !drop.canceled(); + drop_at.update(cx, |drop, cx| match (hovered, drop.onto) { + (true, current) if current != Some(index) => { + drop.onto = Some(index); + cx.notify(); + } + (false, Some(_)) => { + drop.onto = None; + cx.notify(); + } + _ => {} + }); + style + } + }) + .on_drop::({ + let on_reorder = ctx.on_reorder.clone(); + let drop_at = ctx.drop_at.clone(); + move |drag, window, cx| { + let canceled = drop_at.read(cx).canceled(); + drop_at.update(cx, |drop, cx| { + if drop.onto.is_some() { + drop.onto = None; + cx.notify(); + } + }); + let target = (!canceled) + .then(|| reorder_target(drag.index, index)) + .flatten(); + if let (Some(to), Some(on_reorder)) = (target, on_reorder.as_ref()) { + on_reorder(drag.index, to, window, cx); + } + } + }) + }); + + match self.wrap { + Some(wrap) => wrap(strip_tab), + None => strip_tab.into_any_element(), + } + } + + fn render_tab_close( + &self, + tabs_id: &ElementId, + index: usize, + on_close: &Option, + ) -> AnyElement { + Button::new((self.key.clone(), "tab-close")) + .icon(IconRole::Close) + .variant(ButtonVariant::Ghost) + .xsmall() + .fully_rounded(true) + .tab_stop(false) + .debug_selector({ + let tabs_id = tabs_id.clone(); + let label = self.label.clone(); + move || format!("{tabs_id}-close-{}", label) + }) + .tooltip(Tooltip::text("Close")) + .accessibility_label(SharedString::from(format!("Close {}", self.label))) + .on_click({ + let on_close = on_close.clone(); + move |_, window, cx| { + cx.stop_propagation(); + if let Some(on_close) = &on_close { + on_close(index, window, cx); + } + } + }) + .into_any_element() + } } // Tab is a data builder, not an element, adopt the combinators explicitly. @@ -988,33 +1274,6 @@ impl RenderOnce for Tabs { return root.children(strip); }; - let container_canvas = canvas( - { - let key = measure_key.clone(); - move |bounds, _, cx| { - cx.default_global::() - .record_container(&key, bounds.size.width); - *root_bounds.borrow_mut() = Some(bounds); - } - }, - |_, _, _, _| {}, - ) - .absolute() - .inset(shadow_bleed); - - let trigger_canvas = canvas( - { - let key = measure_key; - move |bounds, _, cx| { - cx.default_global::() - .record_trigger(&key, bounds.size.width); - } - }, - |_, _, _, _| {}, - ) - .absolute() - .inset_0(); - let control = match popover { Some(popover) => div().flex_none().relative().child(popover), None => div().flex_none().relative().child( @@ -1030,7 +1289,21 @@ impl RenderOnce for Tabs { .overflow_hidden() .p(shadow_bleed) .m(-shadow_bleed) - .child(container_canvas) + .child( + canvas( + { + let key = measure_key.clone(); + move |bounds, _, cx| { + cx.default_global::() + .record_container(&key, bounds.size.width); + *root_bounds.borrow_mut() = Some(bounds); + } + }, + |_, _, _, _| {}, + ) + .absolute() + .inset(shadow_bleed), + ) .child( div() .flex_none() @@ -1039,7 +1312,22 @@ impl RenderOnce for Tabs { .when(self.variant.is_capsule(), |row| row.items_center()) .children(strip), ) - .child(control.child(trigger_canvas)) + .child( + control.child( + canvas( + { + let key = measure_key; + move |bounds, _, cx| { + cx.default_global::() + .record_trigger(&key, bounds.size.width); + } + }, + |_, _, _, _| {}, + ) + .absolute() + .inset_0(), + ), + ) } else if self.overflow_scroll { root.min_w_0() .overflow_x_scroll() @@ -1059,291 +1347,3 @@ impl RenderOnce for Tabs { }) } } - -impl Tab { - fn render_tab(mut self, ctx: &StripCtx, cx: &App, index: usize) -> AnyElement { - let selected = index == ctx.selected; - // A pinned tab always wears the active treatment, selected or not. - let active = selected || self.pinned; - - let theme = cx.theme(); - let label_color = tab_label_color(ctx.variant, active, self.disabled, cx); - - let titlebar = ctx.variant == TabsVariant::Titlebar; - let group = SharedString::from(format!("{}-tab-{}", ctx.id, self.key)); - let close = (self.closeable && ctx.on_close.is_some() && !self.disabled) - .then(|| self.render_tab_close(&ctx.id, index, &ctx.on_close)); - - let label = div() - .flex_grow(1.0) - .when(titlebar, |label| { - let fade = if active { - theme.colors.background - } else { - theme.colors.muted - }; - - let hover_fade = if active { - theme.colors.background - } else { - theme.colors.muted_hover - }; - - let fade_width = rems(0.75); - let hover_fade_width = rems(1.5); - - label - .min_w_0() - .relative() - .overflow_hidden() - .child( - div() - .w_full() - .whitespace_nowrap() - .text_overflow(TextOverflow::Truncate(SharedString::default())) - .child(self.label.clone()), - ) - .child( - div() - .absolute() - .top_0() - .right_0() - .bottom_0() - .w(fade_width) - .bg(linear_gradient( - 90., - linear_color_stop(fade.opacity(0.), 0.), - linear_color_stop(fade, 1.), - )), - ) - .child( - div() - .absolute() - .top_0() - .right_0() - .bottom_0() - .w(hover_fade_width) - .bg(linear_gradient( - 90., - linear_color_stop(hover_fade.opacity(0.), 0.), - linear_color_stop(hover_fade, 1.), - )) - .invisible() - .group_hover(group.clone(), |style| style.visible()), - ) - }) - .when(!titlebar, |label| label.child(self.label.clone())); - - let strip_tab = div() - .id((self.key.clone(), "tab")) - .debug_selector({ - let tabs_id = ctx.id.clone(); - let label = self.label.clone(); - move || format!("{tabs_id}-tab-{}", label) - }) - .flex() - .items_center() - .gap_2() - .role(Role::Tab) - .aria_selected(selected) - .text_color(label_color) - .when(titlebar, |strip_tab| strip_tab.group(group.clone())) - .when(!self.disabled && !active, |strip_tab| { - strip_tab.hover(|strip_tab| { - strip_tab.bg(match ctx.variant { - TabsVariant::Titlebar => theme.colors.muted_hover, - _ => theme.colors.muted, - }) - }) - }) - .map(|strip_tab| { - apply_tab_chrome(strip_tab, ctx.variant, active, cx).when(titlebar, |strip_tab| { - strip_tab.min_w(TAB_MIN_WIDTH).max_w(TAB_MAX_WIDTH) - }) - }) - .when_some(self.lead.take(), |strip_tab, lead| strip_tab.child(lead)) - .child(label) - .when(ctx.variant == TabsVariant::Pill, |strip_tab| { - strip_tab.child(div().flex_none().w_4()) - }) - .when(self.busy && !self.disabled, |strip_tab| { - strip_tab.child( - Spinner::new((self.key.clone(), "tab-busy")) - .small() - .accessibility_label("Loading"), - ) - }) - .when_some(close, |strip_tab, close| { - if titlebar { - strip_tab.child( - div() - .flex_none() - .invisible() - .group_hover(group, |style| style.visible()) - .child(close), - ) - } else { - strip_tab.child(close) - } - }) - .when( - { - let drop = ctx.drop_at.read(cx); - drop.onto == Some(index) && !drop.canceled() - }, - |strip_tab| { - strip_tab.child( - div() - .absolute() - .left_0() - .top_0p5() - .bottom_0p5() - .w_0p5() - .rounded(theme.radius.sm) - .bg(theme.ramps.primary.base), - ) - }, - ) - .when_some(ctx.measure.clone(), |strip_tab, measure| { - let key = measure.key.clone(); - let root_bounds = measure.root_bounds.clone(); - let tab_key = self.key.to_string(); - strip_tab.child( - canvas( - move |bounds, _, cx| { - let root = root_bounds.borrow(); - if let Some(root) = root.as_ref() { - cx.default_global::().record_tab( - &key, - tab_key, - TabMeasure { - left: bounds.origin.x - root.origin.x, - width: bounds.size.width, - }, - ); - } - }, - |_, _, _, _| {}, - ) - .absolute() - .inset_0(), - ) - }) - .when(!self.disabled, |strip_tab| { - strip_tab.cursor_pointer().on_click({ - let selected = ctx.selected; - let on_change = ctx.on_change.clone(); - let focus = ctx.focus.clone(); - move |_, window, cx| { - window.focus(&focus, cx); - if index != selected - && let Some(on_change) = &on_change - { - on_change(index, window, cx); - } - } - }) - }) - .when(ctx.draggable && !self.disabled, |strip_tab| { - strip_tab - .on_mouse_down(MouseButton::Left, { - let drop_at = ctx.drop_at.clone(); - move |event, _, cx| { - cx.stop_propagation(); - drop_at.update(cx, |drop, cx| { - let fresh = TabDrop { - origin: Some(event.position), - ..TabDrop::default() - }; - if *drop != fresh { - *drop = fresh; - cx.notify(); - } - }); - } - }) - .on_drag(TabDrag { index }, { - let label = self.label.clone(); - move |_, _, _, cx| { - cx.new(|_| TabDragPreview { - label: label.clone(), - }) - } - }) - .drag_over::({ - let drop_at = ctx.drop_at.clone(); - move |style, drag, _, cx| { - let drop = *drop_at.read(cx); - let hovered = drag.index != index && !drop.canceled(); - drop_at.update(cx, |drop, cx| match (hovered, drop.onto) { - (true, current) if current != Some(index) => { - drop.onto = Some(index); - cx.notify(); - } - (false, Some(_)) => { - drop.onto = None; - cx.notify(); - } - _ => {} - }); - style - } - }) - .on_drop::({ - let on_reorder = ctx.on_reorder.clone(); - let drop_at = ctx.drop_at.clone(); - move |drag, window, cx| { - let canceled = drop_at.read(cx).canceled(); - drop_at.update(cx, |drop, cx| { - if drop.onto.is_some() { - drop.onto = None; - cx.notify(); - } - }); - let target = (!canceled) - .then(|| reorder_target(drag.index, index)) - .flatten(); - if let (Some(to), Some(on_reorder)) = (target, on_reorder.as_ref()) { - on_reorder(drag.index, to, window, cx); - } - } - }) - }); - - match self.wrap { - Some(wrap) => wrap(strip_tab), - None => strip_tab.into_any_element(), - } - } - - fn render_tab_close( - &self, - tabs_id: &ElementId, - index: usize, - on_close: &Option, - ) -> AnyElement { - Button::new((self.key.clone(), "tab-close")) - .icon(IconRole::Close) - .variant(ButtonVariant::Ghost) - .xsmall() - .fully_rounded(true) - .tab_stop(false) - .debug_selector({ - let tabs_id = tabs_id.clone(); - let label = self.label.clone(); - move || format!("{tabs_id}-close-{}", label) - }) - .tooltip(Tooltip::text("Close")) - .accessibility_label(SharedString::from(format!("Close {}", self.label))) - .on_click({ - let on_close = on_close.clone(); - move |_, window, cx| { - cx.stop_propagation(); - if let Some(on_close) = &on_close { - on_close(index, window, cx); - } - } - }) - .into_any_element() - } -} diff --git a/crates/ui/src/components/toast.rs b/crates/ui/src/components/toast.rs index 0405678..ca45215 100644 --- a/crates/ui/src/components/toast.rs +++ b/crates/ui/src/components/toast.rs @@ -2,17 +2,7 @@ //! //! A [`Toasts`] entity holds the raised toast, and a [`ToastsView`] renders //! it; mount the view at the window root. -//! -//! # Examples -//! -//! ```no_run -//! use ui::toast::{Toast, ToastAction}; -//! -//! let toast = Toast::new("Copied to clipboard") -//! .action(ToastAction::new("Undo", |_cx| println!("undo"))); -//! ``` -use std::rc::Rc; use std::time::Duration; use gpui::prelude::FluentBuilder; @@ -25,45 +15,18 @@ use gpui::{ use crate::components::button::{Button, ButtonVariant}; use crate::components::common::{ - DismissHandler, ResultLogErr as _, Sizable as _, StyledExt as _, TOAST_LAYER, floating_panel, - v_flex, + ResultLogErr as _, Sizable as _, StyledExt as _, TOAST_LAYER, floating_panel, v_flex, }; use crate::icons::{Icon, IconRole}; use crate::theme::{ActiveTheme as _, TOAST_MAX_WIDTH}; -/// The action handler of a [`Toast`]. -pub type ActionHandler = Rc; - -/// One user action offered by a toast. -#[derive(Clone)] -pub struct ToastAction { - label: SharedString, - handler: ActionHandler, -} - -impl ToastAction { - /// Creates an action with this label. - pub fn new(label: L, handler: F) -> Self - where - L: Into, - F: Fn(&mut App) + 'static, - { - Self { - label: label.into(), - handler: Rc::new(handler), - } - } -} - /// A toast notification. #[derive(Clone)] #[must_use] pub struct Toast { message: SharedString, icon: Option, - action: Option, duration: Option, - on_dismiss: Option, style: StyleRefinement, } @@ -79,9 +42,7 @@ impl Toast { Self { message: message.into(), icon: None, - action: None, duration: Some(Self::DURATION), - on_dismiss: None, style: StyleRefinement::default(), } } @@ -94,27 +55,6 @@ impl Toast { self.icon = Some(icon.into()); self } - - /// Offers the user this action. - pub fn action(mut self, action: ToastAction) -> Self { - self.action = Some(action); - self - } - - /// Sets the time before the toast dismisses itself. - pub fn duration(mut self, duration: Duration) -> Self { - self.duration = Some(duration); - self - } - - /// Runs when the toast is dismissed by any means, once it is fully gone. - pub fn on_dismiss(mut self, handler: F) -> Self - where - F: Fn(&mut App) + 'static, - { - self.on_dismiss = Some(Rc::new(handler)); - self - } } // Toast is a data builder, not an element, adopt the combinators explicitly. @@ -127,6 +67,68 @@ pub struct ToastEntry { pub toast: Toast, } +impl ToastEntry { + /// The rendered pill for this toast. + fn pill(&self, toasts: &Entity, cx: &App) -> gpui::Stateful { + let theme = cx.theme(); + let foreground = theme.colors.foreground; + let radius = theme.radius.full; + let toast = &self.toast; + let toasts = toasts.clone(); + let id = self.id; + + floating_panel( + cx, + radius, + div() + .id(("toast", id)) + .debug_selector(|| "toast-pill".to_string()) + .role(Role::Alert) + .aria_label(toast.message.clone()) + .max_w(TOAST_MAX_WIDTH) + .flex() + .items_center() + .gap_2() + .py_1p5() + .px_3(), + theme.elevations.popover.shadows(), + ) + .refine_style(&toast.style) + .when_some(toast.icon.clone(), |pill, icon| { + pill.child( + div() + .flex_none() + .flex() + .items_center() + .child(icon.size(rems(1.0)).color(foreground)), + ) + }) + .child( + div() + .flex_1() + .min_w(px(0.)) + .truncate() + .text_sm() + .text_color(foreground) + .child(toast.message.clone()), + ) + .child( + div().flex_none().child( + Button::new(("toast-close", id)) + .icon(IconRole::Close) + .variant(ButtonVariant::Ghost) + .small() + .accessibility_label("Dismiss") + .on_click(move |_, _window, cx| { + toasts.update(cx, |toasts, cx| { + toasts.dismiss(id, cx); + }); + }), + ), + ) + } +} + /// The store of raised toasts. #[derive(Default)] pub struct Toasts { @@ -177,33 +179,13 @@ impl Toasts { } } - /// Dismisses the toast on screen. - pub fn clear(&mut self, cx: &mut Context) { - if let Some(entry) = self.current.take() { - self.start_exit(entry, cx); - } else { - self.finish_exit(cx); - } - } - /// The toast now showing, if any. pub fn current(&self) -> Option<&ToastEntry> { self.current.as_ref() } - /// How many toasts are on screen, including one fading out. - pub fn count(&self) -> usize { - usize::from(self.current.is_some()) + usize::from(self.exiting.is_some()) - } - /// Moves a toast into the fade-out phase. fn start_exit(&mut self, entry: ToastEntry, cx: &mut Context) { - if let Some(previous) = self.exiting.take() - && let Some(on_dismiss) = &previous.toast.on_dismiss - { - on_dismiss(cx); - } - self.exiting = Some(entry); cx.notify(); @@ -217,11 +199,8 @@ impl Toasts { } fn finish_exit(&mut self, cx: &mut Context) { - if let Some(entry) = self.exiting.take() { + if self.exiting.take().is_some() { cx.notify(); - if let Some(on_dismiss) = &entry.toast.on_dismiss { - on_dismiss(cx); - } } } } @@ -282,82 +261,3 @@ impl RenderOnce for ToastsView { .with_priority(TOAST_LAYER) } } - -impl ToastEntry { - /// The rendered pill for this toast. - fn pill(&self, toasts: &Entity, cx: &App) -> gpui::Stateful { - let theme = cx.theme(); - let foreground = theme.colors.foreground; - let radius = theme.radius.full; - let toast = &self.toast; - let toasts = toasts.clone(); - let id = self.id; - - floating_panel( - cx, - radius, - div() - .id(("toast", id)) - .debug_selector(|| "toast-pill".to_string()) - .role(Role::Alert) - .aria_label(toast.message.clone()) - .max_w(TOAST_MAX_WIDTH) - .flex() - .items_center() - .gap_2() - .py_1p5() - .px_3(), - theme.elevations.popover.shadows(), - ) - .refine_style(&toast.style) - .when_some(toast.icon.clone(), |pill, icon| { - pill.child( - div() - .flex_none() - .flex() - .items_center() - .child(icon.size(rems(1.0)).color(foreground)), - ) - }) - .child( - div() - .flex_1() - .min_w(px(0.)) - .truncate() - .text_sm() - .text_color(foreground) - .child(toast.message.clone()), - ) - .when_some(toast.action.clone(), |pill, action| { - let toasts = toasts.clone(); - pill.child( - div().flex_none().child( - Button::new(("toast-action", id)) - .label(action.label.clone()) - .variant(ButtonVariant::Primary) - .small() - .on_click(move |_, _window, cx| { - (action.handler)(cx); - toasts.update(cx, |toasts, cx| { - toasts.dismiss(id, cx); - }); - }), - ), - ) - }) - .child( - div().flex_none().child( - Button::new(("toast-close", id)) - .icon(IconRole::Close) - .variant(ButtonVariant::Ghost) - .small() - .accessibility_label("Dismiss") - .on_click(move |_, _window, cx| { - toasts.update(cx, |toasts, cx| { - toasts.dismiss(id, cx); - }); - }), - ), - ) - } -} diff --git a/crates/ui/src/components/tree.rs b/crates/ui/src/components/tree.rs index 6b5cfe3..2299b6f 100644 --- a/crates/ui/src/components/tree.rs +++ b/crates/ui/src/components/tree.rs @@ -15,6 +15,8 @@ //! .on_change(|_selected, _window, _cx| println!("selection changed")); //! ``` +use std::collections::{HashMap, HashSet}; +use std::path::PathBuf; use std::rc::Rc; use gpui::prelude::FluentBuilder; @@ -71,6 +73,16 @@ impl TreeItem { } } + /// The row's key: the path-like id its builder passed. + pub fn key(&self) -> &ElementId { + &self.key + } + + /// Whether the row has children and paints a chevron. + pub fn is_expandable(&self) -> bool { + self.expandable + } + /// Shows a custom icon leading the label. pub fn icon(mut self, icon: I) -> Self where @@ -103,11 +115,299 @@ impl TreeItem { self.disabled = disabled; self } + + #[allow(clippy::too_many_arguments)] + fn render_row( + &self, + cx: &App, + index: usize, + position_in_set: usize, + size_of_set: usize, + selected: bool, + on_change: &Option, + on_disclosure: &Option, + focus: &FocusHandle, + ) -> AnyElement { + let theme = cx.theme(); + let label_color = selectable_label_color(cx, selected, self.disabled); + let disabled = self.disabled; + + let depth = self.depth.min(TREE_MAX_DEPTH) as f32; + let indent = rems(0.75 * if self.depth == 0 { 0.5 } else { depth + 1.0 }); + + div() + .id((self.key.clone(), "tree-item")) + .relative() + .flex() + .items_center() + .gap_2() + .pl(indent) + .pr_2() + .py_1() + .min_h_8() + .rounded(theme.radius.sm) + .role(Role::TreeItem) + .aria_selected(selected) + .aria_level(self.depth + 1) + .aria_position_in_set(position_in_set) + .aria_size_of_set(size_of_set) + .when(self.expandable, |row| row.aria_expanded(self.expanded)) + .map(|row| paint_selectable_row(cx, row, selected, disabled)) + .when(!disabled, |row| { + row.cursor_pointer().on_click({ + let on_change = on_change.clone(); + let on_disclosure = on_disclosure.clone(); + let expandable = self.expandable; + let focus = focus.clone(); + + move |_, window, cx| { + window.focus(&focus, cx); + if let Some(on_change) = &on_change { + on_change(Some(index), window, cx); + } + // A folder row toggles with its own click, not just its chevron. + if expandable && let Some(on_disclosure) = &on_disclosure { + on_disclosure(index, window, cx); + } + } + }) + }) + .children((0..self.depth.min(TREE_MAX_DEPTH)).map(|level| { + let step = level as f32; + div() + .absolute() + .left(rems(0.75 * (step + 0.5))) + .top_0() + .bottom_0() + .border_l_1() + .border_color(theme.colors.border) + })) + .child(self.render_disclosure(cx, selected)) + .when_some( + self.icon + .clone() + .or_else(|| (!self.expandable).then(|| icon(IconRole::File))), + |row, icon| row.child(icon.size(rems(1.0)).color(label_color)), + ) + .child( + div() + .flex_1() + .text_color(label_color) + .child(self.label.clone()), + ) + .into_any_element() + } + + fn render_disclosure(&self, cx: &App, selected: bool) -> AnyElement { + let theme = cx.theme(); + let glyph_color = if self.disabled || !selected { + theme.colors.muted_foreground + } else { + theme.colors.primary_foreground + }; + + // Only expandable rows draw a chevron; the empty cell keeps labels aligned with folders. + div() + .flex_none() + .size_4() + .flex() + .items_center() + .justify_center() + .when(self.expandable, |cell| { + cell.child( + icon(if self.expanded { + IconRole::ChevronDown + } else { + IconRole::ChevronRight + }) + .size(rems(0.75)) + .color(glyph_color), + ) + }) + .into_any_element() + } } // TreeItem is a data builder, not an element, adopt the combinators explicitly. impl FluentBuilder for TreeItem {} +/// A nested path node; `flatten_all` turns a forest of these into rows. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TreeItemSeed { + /// Path of the node, relative to the worktree root. + pub id: String, + pub label: String, + pub children: Vec, +} + +impl TreeItemSeed { + /// Flattens the seeds into the rows a flat tree renders, honoring `expanded`. + /// + /// Expandable rows carry the folder icon; leaves fall back to the file icon + /// the tree paints by default. + pub fn flatten_all(seeds: &[TreeItemSeed], expanded: &HashSet) -> Vec { + fn push( + seed: &TreeItemSeed, + depth: usize, + expanded: &HashSet, + rows: &mut Vec, + ) { + let is_expanded = expanded.contains(&seed.id); + let mut item = TreeItem::new(seed.id.clone(), seed.label.clone()) + .depth(depth) + .expandable(!seed.children.is_empty()) + .expanded(is_expanded); + if !seed.children.is_empty() { + item = item.icon(Icon::named(IconRole::Folder)); + } + rows.push(item); + + if is_expanded { + for child in &seed.children { + push(child, depth + 1, expanded, rows); + } + } + } + + let mut rows = Vec::new(); + for seed in seeds { + push(seed, 0, expanded, &mut rows); + } + rows + } + + /// Every folder id, for starting with the tree fully expanded. + pub fn collect_expanded(seeds: &[TreeItemSeed]) -> HashSet { + fn push(seed: &TreeItemSeed, expanded: &mut HashSet) { + if !seed.children.is_empty() { + expanded.insert(seed.id.clone()); + for child in &seed.children { + push(child, expanded); + } + } + } + + let mut expanded = HashSet::new(); + for seed in seeds { + push(seed, &mut expanded); + } + expanded + } + + /// Builds nested tree items from a flat entry list sorted dirs-first. + pub fn from_paths(paths: &[PathBuf]) -> Vec { + // Node indices by full path, so parents resolve in constant time while inserting. + let mut index: HashMap = HashMap::new(); + let mut nodes: Vec<(String, String, Vec)> = Vec::new(); + let mut roots: Vec = Vec::new(); + + for entry in paths { + let mut parent: Option = None; + let mut path = String::new(); + for part in entry.components() { + let label = part.as_os_str().to_string_lossy().into_owned(); + path = if path.is_empty() { + label.clone() + } else { + format!("{path}/{label}") + }; + let ix = *index.entry(path.clone()).or_insert_with(|| { + let ix = nodes.len(); + nodes.push((path.clone(), label.clone(), Vec::new())); + match parent { + Some(parent) => nodes[parent].2.push(ix), + None => roots.push(ix), + } + ix + }); + parent = Some(ix); + } + } + + fn assemble(ix: usize, nodes: &[(String, String, Vec)]) -> TreeItemSeed { + let (id, label, children) = &nodes[ix]; + TreeItemSeed { + id: id.clone(), + label: label.clone(), + children: children + .iter() + .map(|child| assemble(*child, nodes)) + .collect(), + } + } + + roots.iter().map(|root| assemble(*root, &nodes)).collect() + } +} + +#[cfg(test)] +mod seed_tests { + use super::*; + + fn ids(rows: &[TreeItem]) -> Vec<(String, usize)> { + rows.iter() + .map(|row| (row.key().to_string(), row.depth)) + .collect() + } + + #[test] + fn collapsed_folders_hide_children() { + let seeds = TreeItemSeed::from_paths(&[ + PathBuf::from("src"), + PathBuf::from("src/lib.rs"), + PathBuf::from("README.md"), + ]); + + let rows = TreeItemSeed::flatten_all(&seeds, &HashSet::new()); + + assert_eq!( + ids(&rows), + vec![("src".to_owned(), 0), ("README.md".to_owned(), 0)] + ); + assert!(rows[0].expandable); + assert!(!rows[0].expanded); + } + + #[test] + fn expanding_a_folder_shows_children_in_order() { + let seeds = TreeItemSeed::from_paths(&[ + PathBuf::from("src"), + PathBuf::from("src/lib.rs"), + PathBuf::from("src/views/mod.rs"), + PathBuf::from("README.md"), + ]); + let expanded = HashSet::from(["src".to_owned(), "src/views".to_owned()]); + + let rows = TreeItemSeed::flatten_all(&seeds, &expanded); + + assert_eq!( + ids(&rows), + vec![ + ("src".to_owned(), 0), + ("src/lib.rs".to_owned(), 1), + ("src/views".to_owned(), 1), + ("src/views/mod.rs".to_owned(), 2), + ("README.md".to_owned(), 0), + ] + ); + } + + #[test] + fn indices_map_to_row_ids() { + let seeds = TreeItemSeed::from_paths(&[ + PathBuf::from("docs"), + PathBuf::from("docs/guide.md"), + PathBuf::from("README.md"), + ]); + let expanded = HashSet::from(["docs".to_owned()]); + let rows = TreeItemSeed::flatten_all(&seeds, &expanded); + + assert_eq!(rows[0].key().to_string(), "docs"); + assert_eq!(rows[1].key().to_string(), "docs/guide.md"); + assert_eq!(rows[2].key().to_string(), "README.md"); + } +} + /// A tree of [`TreeItem`] rows with single selection and disclosure handling. #[derive(IntoElement)] #[must_use] @@ -345,116 +645,3 @@ impl RenderOnce for Tree { .children(rows) } } - -impl TreeItem { - #[allow(clippy::too_many_arguments)] - fn render_row( - &self, - cx: &App, - index: usize, - position_in_set: usize, - size_of_set: usize, - selected: bool, - on_change: &Option, - on_disclosure: &Option, - focus: &FocusHandle, - ) -> AnyElement { - let theme = cx.theme(); - let label_color = selectable_label_color(cx, selected, self.disabled); - let disabled = self.disabled; - - let depth = self.depth.min(TREE_MAX_DEPTH) as f32; - let indent = rems(0.75 * if self.depth == 0 { 0.5 } else { depth + 1.0 }); - - div() - .id((self.key.clone(), "tree-item")) - .relative() - .flex() - .items_center() - .gap_2() - .pl(indent) - .pr_2() - .py_1() - .min_h_8() - .rounded(theme.radius.sm) - .role(Role::TreeItem) - .aria_selected(selected) - .aria_level(self.depth + 1) - .aria_position_in_set(position_in_set) - .aria_size_of_set(size_of_set) - .when(self.expandable, |row| row.aria_expanded(self.expanded)) - .map(|row| paint_selectable_row(cx, row, selected, disabled)) - .when(!disabled, |row| { - row.cursor_pointer().on_click({ - let on_change = on_change.clone(); - let on_disclosure = on_disclosure.clone(); - let expandable = self.expandable; - let focus = focus.clone(); - - move |_, window, cx| { - window.focus(&focus, cx); - if let Some(on_change) = &on_change { - on_change(Some(index), window, cx); - } - // A folder row toggles with its own click, not just its chevron. - if expandable && let Some(on_disclosure) = &on_disclosure { - on_disclosure(index, window, cx); - } - } - }) - }) - .children((0..self.depth.min(TREE_MAX_DEPTH)).map(|level| { - let step = level as f32; - div() - .absolute() - .left(rems(0.75 * (step + 0.5))) - .top_0() - .bottom_0() - .border_l_1() - .border_color(theme.colors.border) - })) - .child(self.render_disclosure(cx, selected)) - .when_some( - self.icon - .clone() - .or_else(|| (!self.expandable).then(|| icon(IconRole::File))), - |row, icon| row.child(icon.size(rems(1.0)).color(label_color)), - ) - .child( - div() - .flex_1() - .text_color(label_color) - .child(self.label.clone()), - ) - .into_any_element() - } - - fn render_disclosure(&self, cx: &App, selected: bool) -> AnyElement { - let theme = cx.theme(); - let glyph_color = if self.disabled || !selected { - theme.colors.muted_foreground - } else { - theme.colors.primary_foreground - }; - - // Only expandable rows draw a chevron; the empty cell keeps labels aligned with folders. - div() - .flex_none() - .size_4() - .flex() - .items_center() - .justify_center() - .when(self.expandable, |cell| { - cell.child( - icon(if self.expanded { - IconRole::ChevronDown - } else { - IconRole::ChevronRight - }) - .size(rems(0.75)) - .color(glyph_color), - ) - }) - .into_any_element() - } -} diff --git a/crates/ui/src/components/utils.rs b/crates/ui/src/components/utils.rs index 366c63a..4026915 100644 --- a/crates/ui/src/components/utils.rs +++ b/crates/ui/src/components/utils.rs @@ -1,5 +1,5 @@ //! Shared helpers for the editor's views: gutter cells, role colors and run -//! styles, code line text, language mapping and change washes. +//! styles, code line text and language mapping. use std::ops::Range; @@ -8,10 +8,7 @@ use gpui::{ }; use crate::components::highlight::{Language, Line, Role}; -use crate::theme::{ - ActiveTheme as _, CODE_GUTTER_WIDTH, ColorTokens, Ramps, WASH_ALPHA, WASH_ALPHA_GUTTER, - WASH_ALPHA_STRONG, -}; +use crate::theme::{ActiveTheme as _, CODE_GUTTER_WIDTH, ColorTokens, Ramps}; impl Role { /// Maps the role to the theme's semantic palette. @@ -78,30 +75,6 @@ where .child(content) } -/// A change wash: the ramp color at the alpha rows tint with. -pub(crate) fn wash(color: Hsla) -> Hsla { - Hsla { - a: color.a * WASH_ALPHA, - ..color - } -} - -/// The stronger wash under number gutters and intra-line word changes. -pub(crate) fn wash_strong(color: Hsla) -> Hsla { - Hsla { - a: color.a * WASH_ALPHA_STRONG, - ..color - } -} - -/// The subtle wash that sets the number gutter off from the code. -pub(crate) fn wash_gutter(colors: &ColorTokens) -> Hsla { - Hsla { - a: colors.muted.a * WASH_ALPHA_GUTTER, - ..colors.muted - } -} - /// One highlighted code line as styled text, roles resolved from the theme. pub(crate) fn code_line(line: &Line, colors: ColorTokens, ramps: Ramps) -> StyledText { let mut highlights: Vec<(Range, HighlightStyle)> = Vec::new(); diff --git a/crates/ui/src/icons/assets/maximize.svg b/crates/ui/src/icons/assets/maximize.svg new file mode 100644 index 0000000..4e7be8a --- /dev/null +++ b/crates/ui/src/icons/assets/maximize.svg @@ -0,0 +1,3 @@ + + + diff --git a/crates/ui/src/icons/assets/minimize.svg b/crates/ui/src/icons/assets/minimize.svg new file mode 100644 index 0000000..57fa22b --- /dev/null +++ b/crates/ui/src/icons/assets/minimize.svg @@ -0,0 +1,3 @@ + + + diff --git a/crates/ui/src/icons/mod.rs b/crates/ui/src/icons/mod.rs index 76c60d6..1dfc866 100644 --- a/crates/ui/src/icons/mod.rs +++ b/crates/ui/src/icons/mod.rs @@ -62,6 +62,8 @@ pub enum IconRole { PanelLeft, UnfoldVertical, Download, + Maximize, + Minimize, } impl IconRole { @@ -112,6 +114,8 @@ impl IconRole { Self::PanelLeft => "panel-left", Self::UnfoldVertical => "unfold-vertical", Self::Download => "download", + Self::Maximize => "maximize", + Self::Minimize => "minimize", } } @@ -150,17 +154,6 @@ pub struct Icon { rotation_period: Option, } -/// Creates an icon for the role at the default size. -pub fn icon(role: IconRole) -> Icon { - Icon { - glyph: Glyph::Role(role), - size: AbsoluteLength::Rems(DEFAULT_ICON_SIZE), - color: None, - transformation: None, - rotation_period: None, - } -} - impl Icon { /// Creates an icon from an application-defined icon set. pub fn named(named: I) -> Self @@ -306,3 +299,14 @@ impl AssetSource for Assets { .collect()) } } + +/// Creates an icon for the role at the default size. +pub fn icon(role: IconRole) -> Icon { + Icon { + glyph: Glyph::Role(role), + size: AbsoluteLength::Rems(DEFAULT_ICON_SIZE), + color: None, + transformation: None, + rotation_period: None, + } +} diff --git a/crates/ui/src/layout/mod.rs b/crates/ui/src/layout/mod.rs index d66a3c5..e471ced 100644 --- a/crates/ui/src/layout/mod.rs +++ b/crates/ui/src/layout/mod.rs @@ -1,4 +1,4 @@ -//! Application window layout: a titlebar over a panel row. +//! Application window layout: a titlebar over a panel stack. //! //! The shared flex and focus helpers live in [`crate::components::common`]; //! they are re-exported here for the `ui::layout::…` paths. @@ -8,7 +8,7 @@ pub use crate::components::common::{StyledExt, focus_handle, focus_ring, h_flex, pub mod panel; pub mod resizable; pub mod resize_handle; -pub mod shell; +pub mod root; pub mod titlebar; pub mod window_controls; diff --git a/crates/ui/src/layout/panel.rs b/crates/ui/src/layout/panel.rs index 0efe632..27c4712 100644 --- a/crates/ui/src/layout/panel.rs +++ b/crates/ui/src/layout/panel.rs @@ -1,22 +1,31 @@ -//! The panel row: the window's main content, island-style over the app -//! background. It can split once into two panels with a drag divider -//! between them; the divider opens at half the row or at a set width -//! ([`PanelRow::split_at`]), and dragging it can be disabled -//! ([`PanelRow::resizable`]). A double-click restores the half split. +//! The panel stack: the window's main content, island-style over the app +//! background. It owns every panel it shows: a main stack, tabbed in the +//! titlebar through [`PanelStack::main_tabs`], and a split stack that opens a +//! second pane beside the main panel while it holds a panel, at half the +//! width or at a set width on either side of it +//! ([`PanelStack::insert_split_at`]), with a drag divider between the panes; a +//! double-click restores half. While no main panel is open the stack shows the +//! empty state its owner set ([`PanelStack::set_empty`]). +//! A panel can ask for a zoom and close toolbar over its pane's top right +//! corner ([`Panel::toolbar`]); zooming shows that panel alone until toggled back. use std::sync::Arc; +use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyElement, AnyView, App, Axis, Div, ElementId, Entity, IntoElement, ParentElement as _, - Pixels, Render, RenderOnce, SharedString, StyleRefinement, Styled as _, Window, div, + AnyElement, AnyView, App, Axis, Context, Div, ElementId, Entity, IntoElement, + ParentElement as _, Pixels, Render, SharedString, StyleRefinement, Styled as _, Window, div, }; -use crate::components::tabs::Tab; -use crate::layout::StyledExt as _; +use crate::components::button::{Button, ButtonVariant}; +use crate::components::common::{ResultLogErr as _, Sizable as _, h_flex, v_flex}; +use crate::components::tabs::{Tab, Tabs, TabsVariant}; +use crate::components::tooltip::Tooltip; +use crate::icons::{Icon, IconRole}; use crate::layout::resizable::{Resizable, ResizableState}; use crate::theme::{ActiveTheme as _, PANE_MIN_SIZE, RESIZE_HANDLE_WIDTH}; -/// A user-defined panel the row can show. +/// A user-defined panel the stack can show. #[allow(unused_variables)] pub trait Panel: Render + 'static { /// The kind the panel belongs to; same-kind panels group in the tab bar. @@ -36,6 +45,11 @@ pub trait Panel: Render + 'static { fn loading(&self, cx: &App) -> bool { false } + + /// Whether the panel shows the zoom and close toolbar while a split is on screen. + fn toolbar(&self, cx: &App) -> bool { + false + } } /// An object-safe handle to a panel, so apps can hold panels by kind. @@ -62,6 +76,11 @@ pub trait PanelView: 'static { false } + /// Whether the panel shows the zoom and close toolbar. + fn toolbar(&self, cx: &App) -> bool { + false + } + /// Builds the panel's tab from its title, prefix, and loading state. fn tab(&self, key: ElementId, cx: &App) -> Tab { let mut tab = Tab::new(key, self.title(cx)).busy(self.loading(cx)); @@ -92,6 +111,10 @@ impl PanelView for Entity { fn loading(&self, cx: &App) -> bool { self.read(cx).loading(cx) } + + fn toolbar(&self, cx: &App) -> bool { + self.read(cx).toolbar(cx) + } } impl PanelView for Arc

{ @@ -114,6 +137,128 @@ impl PanelView for Arc

{ fn loading(&self, cx: &App) -> bool { (**self).loading(cx) } + + fn toolbar(&self, cx: &App) -> bool { + (**self).toolbar(cx) + } +} + +/// Which stack, main or split, a panel opens into. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PanelSlot { + /// The stack tabbed in the titlebar. + Main, + /// The stack in the pane beside the main panel. + Split, +} + +/// The side of the main panel a split pane opens on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SplitSide { + /// Before the main panel. + Leading, + /// After the main panel. + Trailing, +} + +/// An ordered stack of panels with one of them shown. +#[derive(Default)] +struct Stack { + /// The open panels in tab order. + panels: Vec<(SharedString, Arc)>, + /// The shown panel; `None` once the stack is empty. + active: Option, +} + +impl Stack { + fn len(&self) -> usize { + self.panels.len() + } + + fn is_empty(&self) -> bool { + self.panels.is_empty() + } + + fn position(&self, id: &SharedString) -> Option { + self.panels.iter().position(|(open, _)| open == id) + } + + /// The tab index of the shown panel. + fn selected(&self) -> Option { + self.active.as_ref().and_then(|id| self.position(id)) + } + + fn active(&self) -> Option> { + let id = self.active.as_ref()?; + self.panels + .iter() + .find(|(open, _)| open == id) + .map(|(_, view)| view.clone()) + } + + /// Shows `view` under `id`, opening it at the end of the stack when new. + fn insert(&mut self, id: SharedString, view: Arc) { + match self.position(&id) { + Some(index) => { + if let Some((_, open)) = self.panels.get_mut(index) { + *open = view; + } + } + None => self.panels.push((id.clone(), view)), + } + self.active = Some(id); + } + + fn activate(&mut self, id: &SharedString) { + self.active = Some(id.clone()); + } + + /// Closes the panel at `index`; its neighbor is shown when it was shown. + fn remove(&mut self, index: usize) -> bool { + if index >= self.panels.len() { + return false; + } + let (id, _) = self.panels.remove(index); + if self.active.as_ref() == Some(&id) { + self.active = self + .panels + .get(index) + .or_else(|| index.checked_sub(1).and_then(|prev| self.panels.get(prev))) + .map(|(open, _)| open.clone()); + } + true + } + + fn clear(&mut self) { + self.panels.clear(); + self.active = None; + } +} + +/// What the stack shows while no main panel is open. +struct EmptyContent { + main: AnyView, + /// The view beside `main`, which then opens at this width. + split: Option<(AnyView, Pixels)>, +} + +/// The panel stack drawn under the titlebar: the main stack, and the split stack beside it. +pub struct PanelStack { + id: ElementId, + main: Stack, + split: Stack, + empty: Option, + resizable: bool, + /// The width the on-screen split pane opened at; `None` splits the row in half. + split_width: Option, + /// The side of the main panel the on-screen split pane opened on. + split_side: SplitSide, + /// The main pane width the divider was last seeded at, to tell a drag from a window resize. + opened_at: Option, + /// The panel shown alone while it is zoomed. + zoomed: Option, + /// The divider position, kept only while a split is on screen. + sizes: Entity, } /// The layout the cached panel content lays out with. @@ -135,137 +280,504 @@ fn island(panel: Div, cx: &App) -> Div { .overflow_hidden() } -/// The panel row drawn under the titlebar. -#[derive(IntoElement)] -#[must_use] -pub struct PanelRow { - id: ElementId, - main: Option, - split: Option, - /// The main pane's width when split; `None` splits the row in half. - split_width: Option, - resizable: bool, - style: StyleRefinement, -} - -impl PanelRow { - /// Creates the panel row. - pub fn new(id: I) -> Self +impl PanelStack { + /// Creates the panel stack with the main and split stacks empty. + pub fn new(id: I, cx: &mut Context) -> Self where I: Into, { Self { id: id.into(), - main: None, - split: None, - split_width: None, + main: Stack::default(), + split: Stack::default(), + empty: None, resizable: true, - style: StyleRefinement::default(), + split_width: None, + split_side: SplitSide::Trailing, + opened_at: None, + zoomed: None, + sizes: ResizableState::new(cx), } } - /// Sets the main panel's content. - pub fn main

(mut self, main: P) -> Self - where - P: PanelView, - { - self.main = Some(main.view().cached(content_style()).into_any_element()); - self + /// Sets what the stack shows while no main panel is open: `main`, beside `split`, `main` at that width. + pub fn set_empty( + &mut self, + main: impl Into, + split: Option<(AnyView, Pixels)>, + cx: &mut Context, + ) { + self.empty = Some(EmptyContent { + main: main.into(), + split, + }); + self.forget_divider(cx); + cx.notify(); } - /// Splits the row into two half-width panels. - pub fn split

(mut self, panel: P) -> Self - where - P: PanelView, - { - self.split = Some(panel.view().cached(content_style()).into_any_element()); - self - } - - /// Splits the row with the main pane at `width`, the split pane beside it. - pub fn split_at

(mut self, panel: P, width: Pixels) -> Self - where - P: PanelView, - { - self.split_width = Some(width); - self.split = Some(panel.view().cached(content_style()).into_any_element()); - self - } - - /// Whether the divider can be dragged to resize the panels. Defaults to true. - pub fn resizable(mut self, resizable: bool) -> Self { + /// Sets whether the divider can be dragged; a fixed split keeps its opening width. + pub fn set_resizable(&mut self, resizable: bool, cx: &mut Context) { self.resizable = resizable; - self + cx.notify(); } -} -impl gpui::Styled for PanelRow { - fn style(&mut self) -> &mut StyleRefinement { - &mut self.style + /// Shows `view` in `slot` under `id`, opening it at the end of the stack when new. + pub fn insert( + &mut self, + slot: PanelSlot, + id: impl Into, + view: Arc, + cx: &mut Context, + ) { + let id = id.into(); + self.switch_main(slot, &id); + self.stack_mut(slot).insert(id, view); + self.forget_divider(cx); + cx.notify(); } -} -impl RenderOnce for PanelRow { - fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { - let id = self.id.clone(); - let gutter = RESIZE_HANDLE_WIDTH; + /// Shows the panel under `id`, building it only when it is not open yet. + pub fn open( + &mut self, + slot: PanelSlot, + id: impl Into, + build: F, + window: &mut Window, + cx: &mut Context, + ) where + P: Panel + 'static, + F: Fn(&mut Window, &mut App) -> Entity

+ 'static, + { + let id = id.into(); + if self.activate(slot, &id, cx) { + return; + } + let view: Arc = Arc::new(build(window, cx)); + self.insert(slot, id, view, cx); + } - let main = island( - div() - .size_full() - .child(self.main.unwrap_or_else(|| div().into_any_element())), - cx, - ); + /// Whether the panel under `id` is open in `slot`. + pub fn is_open(&self, slot: PanelSlot, id: &SharedString) -> bool { + self.stack(slot).position(id).is_some() + } - let row = match self.split { - Some(split) => { - let split = island(div().size_full().child(split), cx); - let extent = window.viewport_size().width - gutter * 2.0; + /// Whether the panel under `id` is the one shown in `slot`. + pub fn is_active(&self, slot: PanelSlot, id: &SharedString) -> bool { + self.stack(slot).active.as_ref() == Some(id) + } - let main_width = self - .split_width - .unwrap_or((extent - gutter) / 2.0) - .max(PANE_MIN_SIZE); + /// Shows `view` in the split stack under `id`; a split pane not on screen yet opens at `width` on `side`. + pub fn insert_split_at( + &mut self, + id: T, + width: Pixels, + side: SplitSide, + view: Arc, + cx: &mut Context, + ) where + T: Into, + { + if !self.is_split_shown() { + self.split_width = Some(width); + self.split_side = side; + } + self.insert(PanelSlot::Split, id, view, cx); + } - if !self.resizable { - div() - .w_full() - .h_full() - .flex() - .flex_row() - .child(div().flex_none().w(main_width).h_full().child(main)) - .child(div().flex_none().w(gutter)) - .child(div().flex_1().min_w_0().h_full().child(split)) - } else { - let sizes = window.with_element_namespace(id.clone(), |window| { - window - .use_keyed_state("panel-sizes", cx, |_, _| ResizableState::default()) - .clone() - }); + /// Closes the panel under `id`. + pub fn close(&mut self, slot: PanelSlot, id: &SharedString, cx: &mut Context) { + if let Some(index) = self.stack(slot).position(id) { + self.close_at(slot, index, cx); + } + } - if sizes.read(cx).sizes().is_empty() { - sizes.update(cx, |state, cx| state.set_pane_width(0, main_width, cx)); - } + /// Closes every panel in both stacks. + pub fn clear(&mut self, cx: &mut Context) { + self.main.clear(); + self.split.clear(); + self.forget_divider(cx); + cx.notify(); + } - div().w_full().h_full().child( - Resizable::new((id.clone(), "split"), sizes) - .axis(Axis::Horizontal) - .pane(main) - .pane(split) - .h_full(), - ) - } + /// The main stack's tab strip for the titlebar; `None` while the stack is empty. + pub fn main_tabs(stack: Entity, cx: &App) -> Option { + let (id, panels, selected) = { + let this = stack.read(cx); + if this.main.is_empty() { + return None; } - None => div().w_full().h_full().child(main), + ( + this.id.clone(), + this.main.panels.clone(), + this.main.selected().unwrap_or(usize::MAX), + ) + }; + let change = stack.downgrade(); + let close = change.clone(); + + Some( + Tabs::new((id, "main-tabs")) + .variant(TabsVariant::Titlebar) + .overflow_scroll(true) + .selected(selected) + .tabs(move |_, cx| { + panels + .iter() + .map(|(id, panel)| panel.tab(id.clone().into(), cx).closeable(true)) + .collect() + }) + .on_change(move |index, _, cx| { + change + .update(cx, |stack, cx| { + stack.activate_at(PanelSlot::Main, index, cx) + }) + .log_err(); + }) + .on_close(move |index, _, cx| { + close + .update(cx, |stack, cx| stack.close_at(PanelSlot::Main, index, cx)) + .log_err(); + }), + ) + } + + /// Shows the panel under `id`; `false` when it is not open. + fn activate(&mut self, slot: PanelSlot, id: &SharedString, cx: &mut Context) -> bool { + if self.stack(slot).position(id).is_none() { + return false; + } + self.switch_main(slot, id); + self.stack_mut(slot).activate(id); + self.forget_divider(cx); + cx.notify(); + true + } + + /// Shows the panel at `index`. + fn activate_at(&mut self, slot: PanelSlot, index: usize, cx: &mut Context) { + let id = self.stack(slot).panels.get(index).map(|(id, _)| id.clone()); + if let Some(id) = id { + self.activate(slot, &id, cx); + } + } + + /// Shows the slot's shown panel alone, or the split again when it already is. + fn toggle_zoom(&mut self, slot: PanelSlot, cx: &mut Context) { + let active = self.stack(slot).active.clone(); + self.zoomed = if self.is_split_shown() && self.zoomed != active { + active + } else { + None + }; + cx.notify(); + } + + fn close_active(&mut self, slot: PanelSlot, cx: &mut Context) { + if let Some(index) = self.stack(slot).selected() { + self.close_at(slot, index, cx); + } + } + + fn close_at(&mut self, slot: PanelSlot, index: usize, cx: &mut Context) { + let was_shown = self.stack(slot).selected() == Some(index); + if !self.stack_mut(slot).remove(index) { + return; + } + if slot == PanelSlot::Main && was_shown { + self.split.clear(); + } + self.forget_divider(cx); + cx.notify(); + } + + /// Closes every split panel when `id` is another main panel than the shown one. + fn switch_main(&mut self, slot: PanelSlot, id: &SharedString) { + if slot == PanelSlot::Main && self.main.active.as_ref() != Some(id) { + self.split.clear(); + } + } + + fn stack(&self, slot: PanelSlot) -> &Stack { + match slot { + PanelSlot::Main => &self.main, + PanelSlot::Split => &self.split, + } + } + + fn stack_mut(&mut self, slot: PanelSlot) -> &mut Stack { + match slot { + PanelSlot::Main => &mut self.main, + PanelSlot::Split => &mut self.split, + } + } + + /// Whether a split is on screen: the split stack beside a main panel, or the empty state's. + fn is_split_shown(&self) -> bool { + if self.main.active.is_some() { + return !self.split.is_empty(); + } + self.empty + .as_ref() + .is_some_and(|empty| empty.split.is_some()) + } + + /// Drops the divider position, width, side, and zoom while no split is on screen, so the next split opens at its start width. + fn forget_divider(&mut self, cx: &mut Context) { + if self.is_split_shown() { + return; + } + + self.split_width = None; + self.split_side = SplitSide::Trailing; + self.opened_at = None; + self.zoomed = None; + + if !self.sizes.read(cx).sizes().is_empty() { + self.sizes.update(cx, |state, cx| state.set_sizes([], cx)); + } + } + + /// The split pane's content: the split stack's tabs over its shown panel. + fn split_pane(&self, cx: &mut Context) -> AnyElement { + let panels: Vec<(SharedString, Arc)> = self.split.panels.clone(); + let selected = self.split.selected().unwrap_or(usize::MAX); + let change = cx.weak_entity(); + let close = change.clone(); + + v_flex() + .size_full() + .gap_2() + .when(self.split.len() > 1, |pane| { + pane.child( + Tabs::new((self.id.clone(), "split-tabs")) + .variant(TabsVariant::Pill) + .overflow_scroll(true) + .selected(selected) + .tabs(move |_, cx| { + panels + .iter() + .map(|(id, panel)| panel.tab(id.clone().into(), cx).closeable(true)) + .collect() + }) + .on_change(move |index, _, cx| { + change + .update(cx, |stack, cx| { + stack.activate_at(PanelSlot::Split, index, cx) + }) + .log_err(); + }) + .on_close(move |index, _, cx| { + close + .update(cx, |stack, cx| stack.close_at(PanelSlot::Split, index, cx)) + .log_err(); + }), + ) + }) + .child( + div() + .flex_1() + .min_h_0() + .w_full() + .children(self.split.active().map(|panel| panel.view())), + ) + .into_any_element() + } + + /// The zoom and close buttons over a pane's top right corner, when its shown panel asks for them. + fn toolbar(&self, slot: PanelSlot, cx: &Context) -> Option { + if !self.stack(slot).active()?.toolbar(cx) { + return None; + } + + let zoomed = self.stack(slot).active == self.zoomed; + let enabled = self.is_split_shown(); + + let (zoom_id, close_id, pane) = match slot { + PanelSlot::Main => ("zoom-main", "close-main", "main"), + PanelSlot::Split => ("zoom-split", "close-split", "split"), }; - div() - .flex_1() - .min_w_0() - .h_full() - .p_2() - .pt_1() - .refine_style(&self.style) - .child(row) + let change = cx.weak_entity(); + let close = change.clone(); + let zoom_prefix = self.id.clone(); + let close_prefix = zoom_prefix.clone(); + + Some( + h_flex() + .absolute() + .top_2() + .right_2() + .gap_1() + .child( + Button::new((self.id.clone(), zoom_id)) + .icon(Icon::named(if zoomed { + IconRole::Minimize + } else { + IconRole::Maximize + })) + .variant(ButtonVariant::Ghost) + .xsmall() + .fully_rounded(true) + .tab_stop(false) + .disabled(!enabled) + .tooltip(Tooltip::text(if zoomed { + "Unzoom panel" + } else { + "Zoom panel" + })) + .debug_selector(move || format!("{zoom_prefix}-zoom-{pane}")) + .on_click(move |_, _, cx| { + change + .update(cx, |stack, cx| stack.toggle_zoom(slot, cx)) + .log_err(); + }), + ) + .child( + Button::new((self.id.clone(), close_id)) + .icon(IconRole::Close) + .variant(ButtonVariant::Ghost) + .xsmall() + .fully_rounded(true) + .tab_stop(false) + .disabled(!enabled) + .tooltip(Tooltip::text("Close panel")) + .debug_selector(move || format!("{close_prefix}-close-{pane}")) + .on_click(move |_, _, cx| { + close + .update(cx, |stack, cx| stack.close_active(slot, cx)) + .log_err(); + }), + ) + .into_any_element(), + ) + } + + /// The island around a pane's content, with its toolbar over the top right corner. + fn pane(&self, content: AnyElement, toolbar: Option, cx: &App) -> Div { + island( + div() + .size_full() + .relative() + .child(content) + .children(toolbar), + cx, + ) + } +} + +impl Render for PanelStack { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + let gutter = RESIZE_HANDLE_WIDTH; + let extent = window.viewport_size().width - gutter * 2.0; + let cached = |view: AnyView| view.cached(content_style()).into_any_element(); + + // The main pane's content, the split pane's when one is on screen, and how the first pane opens. + let (main, split, width, leading) = match self.main.active() { + Some(panel) => { + let leading = self.split_side == SplitSide::Leading; + // The pane opened at a width is the sized one; the other fills what is left. + let width = if leading { + self.split_width + } else { + self.split_width + .map(|split_width| extent - gutter - split_width) + }; + ( + cached(panel.view()), + (!self.split.is_empty()).then(|| self.split_pane(cx)), + width, + leading, + ) + } + None => match &self.empty { + Some(empty) => { + let (split, width) = match &empty.split { + Some((view, width)) => (Some(cached(view.clone())), Some(*width)), + None => (None, None), + }; + (cached(empty.main.clone()), split, width, false) + } + None => (div().into_any_element(), None, None, false), + }, + }; + + // The pane shown alone while its panel is zoomed. + let zoomed = self.zoomed.as_ref().and_then(|zoomed| { + [PanelSlot::Main, PanelSlot::Split] + .into_iter() + .find(|slot| split.is_some() && self.stack(*slot).active.as_ref() == Some(zoomed)) + }); + + div().flex_1().min_w_0().h_full().p_2().pt_1().map(|this| { + match split { + Some(split) => match zoomed { + // A zoomed panel fills the row; its toolbar is the way back. + Some(slot) => { + let content = match slot { + PanelSlot::Main => main, + PanelSlot::Split => split, + }; + this.child(div().w_full().h_full().child(self.pane( + content, + self.toolbar(slot, cx), + cx, + ))) + } + None => { + let main = self.pane(main, self.toolbar(PanelSlot::Main, cx), cx); + let split = self.pane(split, self.toolbar(PanelSlot::Split, cx), cx); + let (first, last) = if leading { + (split, main) + } else { + (main, split) + }; + let first_width = + width.unwrap_or((extent - gutter) / 2.0).max(PANE_MIN_SIZE); + + if !self.resizable { + this.child( + div() + .w_full() + .h_full() + .flex() + .flex_row() + .child(div().flex_none().w(first_width).h_full().child(first)) + .child(div().flex_none().w(gutter)) + .child(div().flex_1().min_w_0().h_full().child(last)), + ) + } else { + // A split opened at a width keeps it across window resizes until the divider is dragged. + let current = self.sizes.read(cx).sizes().first().copied(); + let keeps_width = + self.split_width.is_some() && current == self.opened_at; + + if current.is_none() + || (keeps_width && self.opened_at != Some(first_width)) + { + self.sizes.update(cx, |state, cx| { + state.set_pane_width(0, first_width, cx); + }); + self.opened_at = Some(first_width); + } + + this.child( + div().w_full().h_full().child( + Resizable::new((self.id.clone(), "split"), self.sizes.clone()) + .axis(Axis::Horizontal) + .pane(first) + .pane(last) + .h_full(), + ), + ) + } + } + }, + None => this.child(div().w_full().h_full().child(self.pane( + main, + self.toolbar(PanelSlot::Main, cx), + cx, + ))), + } + }) } } diff --git a/crates/ui/src/layout/resizable.rs b/crates/ui/src/layout/resizable.rs index 6dbd402..4120c20 100644 --- a/crates/ui/src/layout/resizable.rs +++ b/crates/ui/src/layout/resizable.rs @@ -111,9 +111,11 @@ impl ResizableState { pub fn set_pane_width(&mut self, ix: usize, width: Pixels, cx: &mut Context) { // Persisted layouts can carry negative sizes. let width = width.max(PANE_MIN_SIZE); + while self.sizes.len() <= ix { self.sizes.push(width); } + if self.sizes[ix] != width { self.sizes[ix] = width; cx.notify(); @@ -249,26 +251,6 @@ impl RenderOnce for Resizable { .refine_style(&self.style) .children(self.panes.into_iter().enumerate().flat_map(|(ix, pane)| { let remainder = ix + 1 == pane_count; - let pane_element = div() - .overflow_hidden() - .when(remainder, |pane_element| { - pane_element - .flex_1() - .when(axis == Axis::Vertical, |p| p.min_h(pane.min)) - .when(axis == Axis::Horizontal, |p| p.min_w(pane.min)) - }) - .when(!remainder, |pane_element| { - pane_element - .flex_none() - .when(axis == Axis::Vertical, |p| p.h(sizes[ix]).w_full()) - .when(axis == Axis::Horizontal, |p| p.w(sizes[ix]).h_full()) - }) - .when_some(debug_selector.clone(), |pane_element, selector| { - let prefix = selector(); - pane_element.debug_selector(move || format!("{prefix}-{ix}")) - }) - .child(pane.content) - .into_any_element(); let divider = (!remainder).then(|| { // The positional index is a stable id: panes are append-only, never reordered. @@ -291,7 +273,29 @@ impl RenderOnce for Resizable { .into_any_element() }); - std::iter::once(pane_element).chain(divider) + std::iter::once( + div() + .overflow_hidden() + .when(remainder, |pane_element| { + pane_element + .flex_1() + .when(axis == Axis::Vertical, |p| p.min_h(pane.min)) + .when(axis == Axis::Horizontal, |p| p.min_w(pane.min)) + }) + .when(!remainder, |pane_element| { + pane_element + .flex_none() + .when(axis == Axis::Vertical, |p| p.h(sizes[ix]).w_full()) + .when(axis == Axis::Horizontal, |p| p.w(sizes[ix]).h_full()) + }) + .when_some(debug_selector.clone(), |pane_element, selector| { + let prefix = selector(); + pane_element.debug_selector(move || format!("{prefix}-{ix}")) + }) + .child(pane.content) + .into_any_element(), + ) + .chain(divider) })) .when(pane_count > 0, |group| { group.child( @@ -303,7 +307,9 @@ impl RenderOnce for Resizable { Axis::Vertical => bounds.size.height, Axis::Horizontal => bounds.size.width, }; - state.update(cx, |state, cx| state.set_measured(extent, cx)); + state.update(cx, |state, cx| { + state.set_measured(extent, cx); + }); } }, |_, _, _, _| {}, @@ -314,30 +320,3 @@ impl RenderOnce for Resizable { }) } } - -#[cfg(test)] -mod tests { - use super::*; - use gpui::TestAppContext; - - #[gpui::test] - fn resize_never_stores_sub_floor_size(cx: &mut TestAppContext) { - let state = cx.new(|_| ResizableState::default()); - state.update(cx, |state, cx| { - // The measured extent is smaller than the other pane's floor. - state.set_measured(px(100.), cx); - state.resize(0, px(500.), &[px(48.), px(150.)], cx); - assert_eq!(state.sizes[0], px(48.)); - }); - } - - #[gpui::test] - fn set_pane_width_clamps_negative_values(cx: &mut TestAppContext) { - let state = cx.new(|_| ResizableState::default()); - state.update(cx, |state, cx| { - // Persisted layouts can carry negative sizes. - state.set_pane_width(0, px(-20.), cx); - assert_eq!(state.pane_size(0, 1), PANE_MIN_SIZE); - }); - } -} diff --git a/crates/ui/src/layout/root.rs b/crates/ui/src/layout/root.rs new file mode 100644 index 0000000..d5d2c5e --- /dev/null +++ b/crates/ui/src/layout/root.rs @@ -0,0 +1,194 @@ +//! The window root: application content in the client-side frame, with the +//! toast, alert, and dialog overlays the root itself owns mounted above it. +//! +//! Applications mount [`Root`] as the window's root view and set their content +//! entity; the root owns the frame, the background, the floating surfaces, and +//! their layering. Code anywhere presents dialogs or pushes toasts through the +//! static helpers, which reach the mounted root via its global. + +use gpui::prelude::FluentBuilder as _; +use gpui::{ + AnyView, App, AppContext as _, Context, Entity, Global, IntoElement, ParentElement as _, + Render, StyleRefinement, Styled, WeakEntity, Window, div, +}; + +use crate::components::alert::{Alerts, AlertsView}; +use crate::components::grain::grain as grain_overlay; +use crate::components::toast::{Toasts, ToastsView}; +use crate::layout::window_frame::frame; +use crate::layout::{StyledExt as _, v_flex}; +use crate::theme::ActiveTheme as _; +use crate::toast::Toast; + +/// The mounted root's handle, for access from anywhere. +struct RootGlobal { + root: WeakEntity, +} + +impl Global for RootGlobal {} + +/// Root presentation helpers on gpui contexts. +pub trait RootContext { + /// Pushes a toast on the mounted root's store. + fn toast(&mut self, toast: Toast); + + /// Mounts the command palette view on the root. + /// + /// Mounted once at startup; the palette renders only while open. + fn open_palette(&mut self, view: impl Into); + + /// Presents a dialog view above the mounted root's content. + fn open_dialog(&mut self, view: impl Into); +} + +impl RootContext for App { + fn toast(&mut self, toast: Toast) { + if let Some(root) = Root::global(self) { + let toasts = root.read(self).toasts(); + toasts.update(self, |toasts, cx| { + toasts.push(toast, cx); + }); + } + } + + fn open_palette(&mut self, view: impl Into) { + if let Some(root) = Root::global(self) { + root.update(self, |root, cx| root.mount_palette(view, cx)); + } + } + + fn open_dialog(&mut self, view: impl Into) { + if let Some(root) = Root::global(self) { + root.update(self, |root, cx| { + root.mount_dialog(view, cx); + }); + } + } +} + +/// The window's content and floating-surface host. +pub struct Root { + content: Option, + palette: Option, + dialogs: Vec, + toasts: Entity, + alerts: Entity, + transparent: bool, + grain: bool, + style: StyleRefinement, +} + +impl Root { + /// Creates the root and its toast and alert stores. + pub fn new(_window: &mut Window, cx: &mut Context) -> Self { + let toasts = cx.new(|_| Toasts::default()); + let alerts = cx.new(|_| Alerts::default()); + let weak = cx.weak_entity(); + cx.set_global(RootGlobal { root: weak }); + + Self { + content: None, + palette: None, + dialogs: Vec::new(), + toasts, + alerts, + transparent: false, + grain: false, + style: StyleRefinement::default(), + } + } + + /// The mounted root, if the window has opened one. + pub fn global(cx: &App) -> Option> { + cx.try_global::() + .and_then(|global| global.root.upgrade()) + } + + /// Sets the application content view. + pub fn set_content(&mut self, content: impl Into, cx: &mut Context) { + self.content = Some(content.into()); + cx.notify(); + } + + /// The root's toast store. + pub fn toasts(&self) -> Entity { + self.toasts.clone() + } + + /// The root's alert store. + pub fn alerts(&self) -> Entity { + self.alerts.clone() + } + + /// Mounts the command palette view above the content. + fn mount_palette(&mut self, view: impl Into, cx: &mut Context) { + self.palette = Some(view.into()); + cx.notify(); + } + + /// Mounts a dialog view above the content. + fn mount_dialog(&mut self, view: impl Into, cx: &mut Context) { + self.dialogs.push(view.into()); + cx.notify(); + } + + /// Paints the app background with the translucent material fill. + pub fn transparent(mut self, transparent: bool) -> Self { + self.transparent = transparent; + self + } + + /// Textures the app background with a film-grain overlay. + pub fn grain(mut self, grain: bool) -> Self { + self.grain = grain; + self + } +} + +impl Styled for Root { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl Render for Root { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + let theme = cx.theme(); + let background = if self.transparent { + theme.material.background + } else { + theme.colors.muted + }; + + div() + .relative() + .size_full() + .font_family(theme.ui_font()) + .text_color(theme.colors.foreground) + .child(frame( + v_flex() + .w_full() + .h_full() + .overflow_hidden() + .bg(background) + .refine_style(&self.style) + .when(self.transparent && self.grain, |layout| { + layout.child(grain_overlay()) + }) + .child( + self.content + .clone() + .map(AnyView::into_any_element) + .unwrap_or_else(|| div().into_any_element()), + ), + window, + cx, + )) + .when_some(self.palette.clone(), |layout, palette| { + layout.child(palette) + }) + .children(self.dialogs.clone()) + .child(ToastsView::new("root-toasts", self.toasts.clone())) + .child(AlertsView::new("root-alerts", self.alerts.clone())) + } +} diff --git a/crates/ui/src/layout/shell.rs b/crates/ui/src/layout/shell.rs deleted file mode 100644 index eaf1430..0000000 --- a/crates/ui/src/layout/shell.rs +++ /dev/null @@ -1,132 +0,0 @@ -//! The application shell: the titlebar above the panel row, wrapped in the -//! client-side window frame, with the toast and alert overlays mounted at -//! the window root. - -use gpui::prelude::FluentBuilder as _; -use gpui::{ - AnyElement, App, ElementId, Entity, IntoElement, ParentElement as _, RenderOnce, - StyleRefinement, Styled as _, Window, div, -}; - -use crate::components::alert::{Alerts, AlertsView}; -use crate::components::grain::grain as grain_overlay; -use crate::components::toast::{Toasts, ToastsView}; -use crate::layout::titlebar::Titlebar; -use crate::layout::window_frame::frame; -use crate::layout::{StyledExt as _, v_flex}; -use crate::theme::ActiveTheme as _; - -/// The application shell. -#[derive(IntoElement)] -#[must_use] -pub struct Shell { - id: ElementId, - titlebar: Option, - panel: Option, - transparent: bool, - grain: bool, - toasts: Option>, - alerts: Option>, - style: StyleRefinement, -} - -impl Shell { - /// Creates the shell. - pub fn new(id: I) -> Self - where - I: Into, - { - Self { - id: id.into(), - titlebar: None, - panel: None, - transparent: false, - grain: false, - toasts: None, - alerts: None, - style: StyleRefinement::default(), - } - } - - /// Sets the titlebar drawn above the panel row. - pub fn titlebar(mut self, titlebar: Titlebar) -> Self { - self.titlebar = Some(titlebar); - self - } - - /// Sets the panel row filling the rest of the window. - pub fn panel(mut self, panel: E) -> Self - where - E: IntoElement, - { - self.panel = Some(panel.into_any_element()); - self - } - - /// Paints the app background with the translucent material fill. - pub fn transparent(mut self, transparent: bool) -> Self { - self.transparent = transparent; - self - } - - /// Textures the app background with a film-grain overlay. - pub fn grain(mut self, grain: bool) -> Self { - self.grain = grain; - self - } - - /// Hosts the toast overlay raised on `toasts`. - pub fn toasts(mut self, toasts: Entity) -> Self { - self.toasts = Some(toasts); - self - } - - /// Hosts the alert overlay stacked on `alerts`. - pub fn alerts(mut self, alerts: Entity) -> Self { - self.alerts = Some(alerts); - self - } -} - -impl gpui::Styled for Shell { - fn style(&mut self) -> &mut StyleRefinement { - &mut self.style - } -} - -impl RenderOnce for Shell { - fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { - let id = self.id.clone(); - let theme = cx.theme(); - - let background = if self.transparent { - theme.material.background - } else { - theme.colors.muted - }; - - frame( - v_flex() - .w_full() - .h_full() - .overflow_hidden() - .bg(background) - .refine_style(&self.style) - .when(self.transparent && self.grain, |layout| { - layout.child(grain_overlay()) - }) - .when_some(self.titlebar, |layout, titlebar| { - layout.child(titlebar.transparent(self.transparent)) - }) - .child(self.panel.unwrap_or_else(|| div().into_any_element())), - window, - cx, - ) - .when_some(self.toasts, |frame, toasts| { - frame.child(ToastsView::new((id.clone(), "toasts"), toasts)) - }) - .when_some(self.alerts, |frame, alerts| { - frame.child(AlertsView::new((id, "alerts"), alerts)) - }) - } -} diff --git a/crates/ui/src/layout/titlebar.rs b/crates/ui/src/layout/titlebar.rs index 85c8d1d..1087ac2 100644 --- a/crates/ui/src/layout/titlebar.rs +++ b/crates/ui/src/layout/titlebar.rs @@ -1,4 +1,4 @@ -//! The window titlebar: the full-width strip drawn above the panel row — +//! The window titlebar: the full-width strip drawn above the panel stack — //! the prefix, tab bar, and suffix in the middle, the platform's window //! controls at macOS's leading edge and every other platform's trailing //! edge. The bar itself moves the window, tab bar included; the prefix and @@ -22,7 +22,6 @@ pub struct Titlebar { prefix: Vec, tab_bar: Option, suffix: Vec, - transparent: bool, style: StyleRefinement, } @@ -37,7 +36,6 @@ impl Titlebar { prefix: Vec::new(), tab_bar: None, suffix: Vec::new(), - transparent: false, style: StyleRefinement::default(), } } @@ -68,12 +66,6 @@ impl Titlebar { self.suffix = vec![suffix.into_any_element()]; self } - - /// Leaves the strip unpainted so the shell's material backdrop shows through. - pub(crate) fn transparent(mut self, transparent: bool) -> Self { - self.transparent = transparent; - self - } } impl gpui::Styled for Titlebar { @@ -99,7 +91,7 @@ impl RenderOnce for Titlebar { .w_full() .h(height) .gap_2() - .when(!self.transparent, |bar| bar.bg(theme.colors.muted)) + .bg(theme.colors.muted) .px_3() .refine_style(&self.style) .when(cfg!(target_os = "macos"), |bar| bar.pl(TRAFFIC_LIGHT_PAD)) diff --git a/crates/ui/src/lib.rs b/crates/ui/src/lib.rs index 9f4f727..5d12738 100644 --- a/crates/ui/src/lib.rs +++ b/crates/ui/src/lib.rs @@ -12,7 +12,7 @@ pub use icons::{Assets, Icon, IconRole}; /// Initializes the theme and every key binding the UI layer owns. pub fn init(cx: &mut App) { theme::Theme::init(cx); - components::input::bind_input_keys(cx, None); + components::input::bind_input_keys(cx); components::combobox::bind_combobox_keys(cx); components::command_palette::bind_command_palette_keys(cx); components::code::bind_code_view_keys(cx); diff --git a/crates/ui/src/theme/colors.rs b/crates/ui/src/theme/colors.rs index 3961590..03664a5 100644 --- a/crates/ui/src/theme/colors.rs +++ b/crates/ui/src/theme/colors.rs @@ -7,14 +7,12 @@ use crate::theme::{ DEFAULT_TRANSPARENCY, MIN_MATERIAL_FILL_DARK, MIN_MATERIAL_FILL_LIGHT, ThemeVariant, }; -fn hex(hex: u32) -> Hsla { - rgb(hex).into() -} - -/// The dim scrim behind modal layers; always a translucent black. -pub(crate) fn scrim(alpha: f32) -> Hsla { - hsla(0., 0., 0., alpha) -} +/// Windows paints its caption close-button hover red in every theme. +pub const WINDOWS_CLOSE_HOVER: Hsla = hsla(0.986043, 0.863406, 0.488235, 1.0); +/// The close-button hover dimmed while pressed. +pub const WINDOWS_CLOSE_PRESSED: Hsla = hsla(0.986043, 0.863406, 0.488235, 0.8); +/// The close glyph's color over the red hover. +pub const WINDOWS_CLOSE_FOREGROUND: Hsla = gpui::white(); /// The semantic color roles components paint from. #[derive(Clone, Copy, Debug, PartialEq)] @@ -165,9 +163,11 @@ impl MaterialTokens { } } -/// Windows paints its caption close-button hover red in every theme. -pub const WINDOWS_CLOSE_HOVER: Hsla = hsla(0.986043, 0.863406, 0.488235, 1.0); -/// The close-button hover dimmed while pressed. -pub const WINDOWS_CLOSE_PRESSED: Hsla = hsla(0.986043, 0.863406, 0.488235, 0.8); -/// The close glyph's color over the red hover. -pub const WINDOWS_CLOSE_FOREGROUND: Hsla = gpui::white(); +fn hex(hex: u32) -> Hsla { + rgb(hex).into() +} + +/// The dim scrim behind modal layers; always a translucent black. +pub(crate) fn scrim(alpha: f32) -> Hsla { + hsla(0., 0., 0., alpha) +} diff --git a/crates/ui/src/theme/mod.rs b/crates/ui/src/theme/mod.rs index 9296620..c58cc8a 100644 --- a/crates/ui/src/theme/mod.rs +++ b/crates/ui/src/theme/mod.rs @@ -113,12 +113,6 @@ pub const PROGRESS_ANIMATION_PERIOD: Duration = Duration::from_millis(1500); pub const SCROLLBAR_AUTOHIDE_DELAY: Duration = Duration::from_millis(700); /// How long the autohide scrollbar's fade runs. pub const SCROLLBAR_FADE_DURATION: Duration = Duration::from_millis(250); -/// How much a change wash tints the rows it covers. -pub const WASH_ALPHA: f32 = 0.14; -/// The stronger wash under number gutters and intra-line word changes. -pub const WASH_ALPHA_STRONG: f32 = 0.34; -/// The subtle wash that sets the number gutter off from the code. -pub const WASH_ALPHA_GUTTER: f32 = 0.18; /// The soft wash that marks the active code row. pub const WASH_ALPHA_SOFT: f32 = 0.45; /// How far a scrolling list renders past its viewport. diff --git a/crates/ui/src/theme/ramps.rs b/crates/ui/src/theme/ramps.rs index 3db2938..a795120 100644 --- a/crates/ui/src/theme/ramps.rs +++ b/crates/ui/src/theme/ramps.rs @@ -40,6 +40,16 @@ impl Oklch { } } +/// The state shades components paint from for one accent color. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct AccentShades { + pub base: Hsla, + pub hover: Hsla, + pub pressed: Hsla, + pub subtle: Hsla, + pub foreground: Hsla, +} + /// Mixes `a` toward `b` by `t` in OKLCH, taking the shortest arc between hues. /// /// `t = 0` returns `a`, `t = 1` returns `b`. @@ -152,16 +162,6 @@ pub fn contrast_foreground(background: Hsla) -> Hsla { } } -/// The state shades components paint from for one accent color. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct AccentShades { - pub base: Hsla, - pub hover: Hsla, - pub pressed: Hsla, - pub subtle: Hsla, - pub foreground: Hsla, -} - /// Derives hover/pressed/subtle shades for an accent against its background. /// /// Where a platform states ramps (WinUI, KDE) those are used instead, diff --git a/crates/ui/src/theme/source/linux.rs b/crates/ui/src/theme/source/linux.rs index 8ef447e..2675d8c 100644 --- a/crates/ui/src/theme/source/linux.rs +++ b/crates/ui/src/theme/source/linux.rs @@ -31,33 +31,6 @@ enum Backend { Fallback, } -fn home_dir() -> Option { - std::env::var_os("HOME").map(PathBuf::from) -} - -/// Whether the session runs on Wayland, where compositors state blur protocols. -fn wayland_session() -> bool { - std::env::var_os("WAYLAND_DISPLAY").is_some() - || std::env::var("XDG_SESSION_TYPE").is_ok_and(|session| session == "wayland") -} - -fn detect(home: &Path, portal_reachable: bool, gsettings_reachable: bool) -> Backend { - let omarchy_marker = home - .join(".local/state/omarchy/current/theme.name") - .exists() - || home.join(".local/state/omarchy/current/theme").is_dir() - || home.join(".config/omarchy").is_dir(); - if omarchy_marker { - Backend::Omarchy - } else if home.join(".config/kdeglobals").exists() { - Backend::Kde - } else if portal_reachable || gsettings_reachable { - Backend::Portal - } else { - Backend::Fallback - } -} - /// What `gsettings` states for GNOME sessions. #[derive(Clone, Copy, Debug, Default, PartialEq)] struct GSettingsSnapshot { @@ -65,68 +38,6 @@ struct GSettingsSnapshot { accent: Option, } -fn gsettings_value(args: &[&str]) -> Option { - let output = std::process::Command::new("gsettings") - .args(args) - .output() - .ok()?; - if !output.status.success() { - return None; - } - String::from_utf8(output.stdout).ok() -} - -/// The named accent colors GNOME ships (libadwaita's background variants). -fn accent_rgb(name: &str) -> Option { - let hex = match name { - "blue" => 0x3584e4, - "teal" => 0x2190a4, - "green" => 0x3a944a, - "yellow" => 0xc88800, - "orange" => 0xed5b00, - "red" => 0xe62d42, - "pink" => 0xd56199, - "purple" => 0x9141ac, - "slate" => 0x6f8396, - _ => return None, - }; - Some(Hsla::from(gpui::rgb(hex))) -} - -fn read_gsettings() -> Option { - let variant = gsettings_value(&["get", "org.gnome.desktop.interface", "color-scheme"]) - .and_then(|value| match value.trim().trim_matches('\'') { - "prefer-dark" => Some(ThemeVariant::Dark), - "prefer-light" => Some(ThemeVariant::Light), - _ => None, - }); - - let accent = gsettings_value(&["get", "org.gnome.desktop.interface", "accent-color"]) - .and_then(|value| accent_rgb(value.trim().trim_matches('\''))); - - if variant.is_none() && accent.is_none() { - return None; - } - Some(GSettingsSnapshot { variant, accent }) -} - -pub(crate) fn platform_source() -> Box { - let portal = portal::io::PortalClient::connect(); - let gsettings = read_gsettings(); - - let backend = home_dir() - .map(|home| detect(&home, portal.is_some(), gsettings.is_some())) - .unwrap_or(Backend::Fallback); - - Box::new(LinuxSource { - backend, - portal, - gsettings, - file_watcher: None, - _signal: None, - }) -} - impl LinuxSource { fn gnome_snapshot( &self, @@ -280,3 +191,92 @@ impl ThemeSource for LinuxSource { } } } + +fn home_dir() -> Option { + std::env::var_os("HOME").map(PathBuf::from) +} + +/// Whether the session runs on Wayland, where compositors state blur protocols. +fn wayland_session() -> bool { + std::env::var_os("WAYLAND_DISPLAY").is_some() + || std::env::var("XDG_SESSION_TYPE").is_ok_and(|session| session == "wayland") +} + +fn detect(home: &Path, portal_reachable: bool, gsettings_reachable: bool) -> Backend { + let omarchy_marker = home + .join(".local/state/omarchy/current/theme.name") + .exists() + || home.join(".local/state/omarchy/current/theme").is_dir() + || home.join(".config/omarchy").is_dir(); + if omarchy_marker { + Backend::Omarchy + } else if home.join(".config/kdeglobals").exists() { + Backend::Kde + } else if portal_reachable || gsettings_reachable { + Backend::Portal + } else { + Backend::Fallback + } +} + +fn gsettings_value(args: &[&str]) -> Option { + let output = std::process::Command::new("gsettings") + .args(args) + .output() + .ok()?; + if !output.status.success() { + return None; + } + String::from_utf8(output.stdout).ok() +} + +/// The named accent colors GNOME ships (libadwaita's background variants). +fn accent_rgb(name: &str) -> Option { + let hex = match name { + "blue" => 0x3584e4, + "teal" => 0x2190a4, + "green" => 0x3a944a, + "yellow" => 0xc88800, + "orange" => 0xed5b00, + "red" => 0xe62d42, + "pink" => 0xd56199, + "purple" => 0x9141ac, + "slate" => 0x6f8396, + _ => return None, + }; + Some(Hsla::from(gpui::rgb(hex))) +} + +fn read_gsettings() -> Option { + let variant = gsettings_value(&["get", "org.gnome.desktop.interface", "color-scheme"]) + .and_then(|value| match value.trim().trim_matches('\'') { + "prefer-dark" => Some(ThemeVariant::Dark), + "prefer-light" => Some(ThemeVariant::Light), + _ => None, + }); + + let accent = gsettings_value(&["get", "org.gnome.desktop.interface", "accent-color"]) + .and_then(|value| accent_rgb(value.trim().trim_matches('\''))); + + if variant.is_none() && accent.is_none() { + return None; + } + Some(GSettingsSnapshot { variant, accent }) +} + +pub(crate) fn platform_source() -> Box { + let portal = portal::io::PortalClient::connect(); + let gsettings = read_gsettings(); + + let backend = home_dir() + .map(|home| detect(&home, portal.is_some(), gsettings.is_some())) + .unwrap_or(Backend::Fallback); + + Box::new(LinuxSource { + backend, + portal, + gsettings, + file_watcher: None, + _signal: None, + }) +} diff --git a/crates/ui/src/theme/source/macos.rs b/crates/ui/src/theme/source/macos.rs index 3ca7e2f..2925dc2 100644 --- a/crates/ui/src/theme/source/macos.rs +++ b/crates/ui/src/theme/source/macos.rs @@ -44,15 +44,6 @@ define_class!( } ); -impl ThemeObserver { - fn new(reapply: async_channel::Sender<()>) -> Retained { - let this = Self::alloc().set_ivars(reapply); - // SAFETY: `this` is freshly allocated with ivars set and not yet - // initialized, which is exactly the receiver `init` requires. - unsafe { msg_send![super(this), init] } - } -} - /// One watcher registration, kept so [`Drop`] can undo it. enum Watcher { /// A distributed notification, registered by name. @@ -82,6 +73,15 @@ pub(crate) struct MacosSource { _signal: Option, } +impl ThemeObserver { + fn new(reapply: async_channel::Sender<()>) -> Retained { + let this = Self::alloc().set_ivars(reapply); + // SAFETY: `this` is freshly allocated with ivars set and not yet initialized, + // which is exactly the receiver `init` requires. + unsafe { msg_send![super(this), init] } + } +} + impl MacosSource { fn color_to_hsla(color: &NSColor) -> Option { let srgb = NSColorSpace::sRGBColorSpace(); diff --git a/crates/ui/src/theme/source/windows.rs b/crates/ui/src/theme/source/windows.rs index 87a6f9b..af47619 100644 --- a/crates/ui/src/theme/source/windows.rs +++ b/crates/ui/src/theme/source/windows.rs @@ -55,25 +55,6 @@ pub(crate) struct WindowsSource { _signal: Option, } -pub(crate) fn platform_source() -> Box { - // SAFETY: WinRT activation requires COM on this thread; the STA matches - // the UI thread's message pump, and RPC_E_CHANGED_MODE means COM is - // already initialized in another apartment. - let initialized = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) }; - - if initialized.is_err() && initialized != RPC_E_CHANGED_MODE { - log::error!("theme: COM initialization failed: {initialized:?}"); - } - - match WindowsSource::new() { - Some(source) => Box::new(source), - None => { - log::warn!("theme: Windows system theme unavailable; using fallback"); - Box::new(super::fallback::FallbackSource) - } - } -} - impl WindowsSource { fn new() -> Option { let ui_settings = match UISettings::new() { @@ -206,3 +187,22 @@ impl ThemeSource for WindowsSource { SourceKind::Windows.label() } } + +pub(crate) fn platform_source() -> Box { + // SAFETY: WinRT activation requires COM on this thread, + // the STA matches the UI thread's message pump, + // and RPC_E_CHANGED_MODE means COM is already initialized in another apartment. + let initialized = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) }; + + if initialized.is_err() && initialized != RPC_E_CHANGED_MODE { + log::error!("theme: COM initialization failed: {initialized:?}"); + } + + match WindowsSource::new() { + Some(source) => Box::new(source), + None => { + log::warn!("theme: Windows system theme unavailable; using fallback"); + Box::new(super::fallback::FallbackSource) + } + } +} diff --git a/crates/ui/tests/panel.rs b/crates/ui/tests/panel.rs index 6e76938..97156c3 100644 --- a/crates/ui/tests/panel.rs +++ b/crates/ui/tests/panel.rs @@ -1,14 +1,16 @@ -//! The panel row: the main island fills the window; splitting makes two +//! The panel stack: the main island fills the window; splitting makes two //! half-width islands with a drag divider that resizes them. +use std::sync::Arc; + use gpui::{ AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement as _, - Pixels, Render, SharedString, Styled as _, TestAppContext, VisualTestContext, Window, div, - point, px, size, + Render, SharedString, Styled as _, TestAppContext, VisualTestContext, Window, div, point, px, + size, }; use ui::common::v_flex; -use ui::layout::panel::{Panel, PanelRow, PanelView}; +use ui::layout::panel::{Panel, PanelSlot, PanelStack, PanelView, SplitSide}; use ui::tabs::Tabs; use ui::theme::Theme; @@ -18,12 +20,22 @@ const WINDOW_HEIGHT: f32 = 768.0; /// A full-size marker the tests measure through its debug selector. struct TagView { selector: SharedString, + /// Whether the marker asks for the zoom and close toolbar. + toolbar: bool, } impl TagView { fn new(selector: &'static str) -> Self { Self { selector: SharedString::from(selector), + toolbar: false, + } + } + + fn with_toolbar(selector: &'static str) -> Self { + Self { + toolbar: true, + ..Self::new(selector) } } } @@ -41,64 +53,86 @@ impl Panel for TagView { fn title(&self, _cx: &App) -> SharedString { self.selector.clone() } + + fn toolbar(&self, _cx: &App) -> bool { + self.toolbar + } } struct PanelHarness { - split: bool, - split_width: Option, - resizable: bool, - main: Entity, - split_view: Entity, + stack: Entity, } impl Render for PanelHarness { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { - let panel = PanelRow::new("panel-harness") - .main(self.main.clone()) - .resizable(self.resizable); - let panel = match self.split_width { - Some(width) => panel.split_at(self.split_view.clone(), width), - None if self.split => panel.split(self.split_view.clone()), - None => panel, - }; - div().size_full().child(panel) + div().size_full().child(self.stack.clone()) } } -fn panel_window(cx: &mut TestAppContext, split: bool) -> VisualTestContext { - split_window(cx, split, None, true) +/// A marker view. +fn tag(cx: &mut App, selector: &'static str) -> Entity { + cx.new(|_| TagView::new(selector)) } -fn split_window( - cx: &mut TestAppContext, - split: bool, - split_width: Option, - resizable: bool, -) -> VisualTestContext { - let (main, split_view) = cx.update(|cx| { - Theme::init(cx); - let main = cx.new(|_| TagView::new("panel-test-main")); - let split = cx.new(|_| TagView::new("panel-test-split")); - (main, split) - }); +/// A marker view that shows the zoom and close toolbar. +fn toolbar_tag(cx: &mut App, selector: &'static str) -> Entity { + cx.new(|_| TagView::with_toolbar(selector)) +} +/// Opens the test window over a stack seeded by `seed`. +fn stack_window( + cx: &mut TestAppContext, + seed: impl FnOnce(&mut PanelStack, &mut Context), +) -> (VisualTestContext, Entity) { + let stack = cx.update(|cx| { + Theme::init(cx); + let stack = cx.new(|cx| PanelStack::new("panel-harness", cx)); + stack.update(cx, seed); + stack + }); let window = cx.open_window(size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), |_, _| { PanelHarness { - split, - split_width, - resizable, - main, - split_view, + stack: stack.clone(), } }); let cx = VisualTestContext::from_window(window.into(), cx); cx.run_until_parked(); - cx + (cx, stack) +} + +/// Seeds the main stack with one panel. +fn main_only(stack: &mut PanelStack, cx: &mut Context) { + stack.insert( + PanelSlot::Main, + "main", + Arc::new(tag(cx, "panel-test-main")), + cx, + ); +} + +/// Seeds the main stack and the split stack with one panel each. +fn main_and_split(stack: &mut PanelStack, cx: &mut Context) { + main_only(stack, cx); + stack.insert( + PanelSlot::Split, + "split", + Arc::new(tag(cx, "panel-test-split")), + cx, + ); +} + +/// Seeds the empty state: a 300px pane with another beside it. +fn empty_state(stack: &mut PanelStack, cx: &mut Context) { + stack.set_empty( + tag(cx, "panel-test-main"), + Some((tag(cx, "panel-test-split").into(), px(300.))), + cx, + ); } #[gpui::test] fn main_fills_the_row_without_a_split(cx: &mut TestAppContext) { - let mut cx = panel_window(cx, false); + let (mut cx, _stack) = stack_window(cx, main_only); let main = cx .debug_bounds("panel-test-main") @@ -112,7 +146,7 @@ fn main_fills_the_row_without_a_split(cx: &mut TestAppContext) { #[gpui::test] fn split_makes_two_half_width_panels(cx: &mut TestAppContext) { - let mut cx = panel_window(cx, true); + let (mut cx, _stack) = stack_window(cx, main_and_split); let main = cx .debug_bounds("panel-test-main") @@ -135,10 +169,10 @@ fn split_makes_two_half_width_panels(cx: &mut TestAppContext) { assert!(main.size.height >= px(WINDOW_HEIGHT - 40.0)); } -/// A split opened at a width lays the main pane out at exactly that width. +/// An empty state's split opens its main pane at the given width. #[gpui::test] -fn split_at_opens_the_main_pane_at_the_width(cx: &mut TestAppContext) { - let mut cx = split_window(cx, true, Some(px(300.0)), true); +fn an_empty_state_split_opens_its_main_pane_at_the_width(cx: &mut TestAppContext) { + let (mut cx, _stack) = stack_window(cx, empty_state); let main = cx .debug_bounds("panel-test-main") @@ -147,9 +181,8 @@ fn split_at_opens_the_main_pane_at_the_width(cx: &mut TestAppContext) { .debug_bounds("panel-test-split") .expect("split panel laid out"); - // The marker fills the island's content box, which extends under the - // overlay border to the full pane width. - assert_eq!(main.size.width, px(300.0)); + // The marker fills the island's content box, inside its 1px border. + assert!((main.size.width - px(300.0)).abs() <= px(2.0)); assert!(main.right() <= split.left()); assert!(split.size.width > px(300.0)); assert!(split.right() <= px(WINDOW_WIDTH)); @@ -158,12 +191,15 @@ fn split_at_opens_the_main_pane_at_the_width(cx: &mut TestAppContext) { /// With resizing disabled there is no divider and drags over the seam do nothing. #[gpui::test] fn a_static_split_ignores_drags(cx: &mut TestAppContext) { - let mut cx = split_window(cx, true, Some(px(300.0)), false); + let (mut cx, _stack) = stack_window(cx, |stack, cx| { + empty_state(stack, cx); + stack.set_resizable(false, cx); + }); let before = cx .debug_bounds("panel-test-main") .expect("main panel laid out"); - assert_eq!(before.size.width, px(300.0)); + assert!((before.size.width - px(300.0)).abs() <= px(2.0)); assert!( cx.debug_bounds("resize-handle").is_none(), "a static split has no divider" @@ -197,7 +233,7 @@ fn a_static_split_ignores_drags(cx: &mut TestAppContext) { #[gpui::test] fn dragging_the_divider_resizes_the_panels(cx: &mut TestAppContext) { - let mut cx = panel_window(cx, true); + let (mut cx, _stack) = stack_window(cx, main_and_split); let before = cx .debug_bounds("panel-test-main") @@ -333,3 +369,623 @@ fn panel_tab_uses_title_prefix_and_loading(cx: &mut TestAppContext) { "loading adds the spinner to the tab" ); } + +/// The split pane exists only while the split stack holds a panel. +#[gpui::test] +fn the_split_pane_follows_the_split_stack(cx: &mut TestAppContext) { + let (mut cx, stack) = stack_window(cx, main_only); + assert!( + cx.debug_bounds("panel-test-split").is_none(), + "no split pane without a split panel" + ); + + cx.update(|_, cx| { + stack.update(cx, |stack, cx| { + stack.insert( + PanelSlot::Split, + "split", + Arc::new(tag(cx, "panel-test-split")), + cx, + ) + }) + }); + cx.run_until_parked(); + assert!( + cx.debug_bounds("panel-test-split").is_some(), + "a split panel opens the split pane" + ); + + cx.update(|_, cx| { + stack.update(cx, |stack, cx| { + stack.close(PanelSlot::Split, &SharedString::from("split"), cx) + }) + }); + cx.run_until_parked(); + assert!( + cx.debug_bounds("panel-test-split").is_none(), + "closing the last split panel closes the pane" + ); +} + +/// A main panel replaces the empty state. +#[gpui::test] +fn a_main_panel_replaces_the_empty_state(cx: &mut TestAppContext) { + let (mut cx, stack) = stack_window(cx, |stack, cx| { + stack.set_empty( + tag(cx, "panel-test-empty"), + Some((tag(cx, "panel-test-side").into(), px(300.))), + cx, + ); + }); + assert!(cx.debug_bounds("panel-test-empty").is_some()); + assert!(cx.debug_bounds("panel-test-side").is_some()); + + cx.update(|_, cx| { + stack.update(cx, |stack, cx| { + stack.insert( + PanelSlot::Main, + "main", + Arc::new(tag(cx, "panel-test-main")), + cx, + ) + }) + }); + cx.run_until_parked(); + + assert!( + cx.debug_bounds("panel-test-empty").is_none(), + "the empty state leaves when a main panel opens" + ); + assert!( + cx.debug_bounds("panel-test-side").is_none(), + "its split pane leaves with it" + ); + assert!(cx.debug_bounds("panel-test-main").is_some()); +} + +/// A split that leaves the screen and comes back starts at half again. +#[gpui::test] +fn a_reopened_split_starts_at_half_again(cx: &mut TestAppContext) { + let (mut cx, stack) = stack_window(cx, main_and_split); + let start = cx + .debug_bounds("panel-test-main") + .expect("main panel laid out") + .size + .width; + + let handle = cx.debug_bounds("resize-handle").expect("divider laid out"); + let seam = point(handle.center().x, px(400.0)); + cx.simulate_event(MouseDownEvent { + position: seam, + button: MouseButton::Left, + modifiers: Modifiers::default(), + click_count: 1, + first_mouse: false, + }); + cx.simulate_event(MouseMoveEvent { + position: point(seam.x + px(100.0), seam.y), + pressed_button: Some(MouseButton::Left), + modifiers: Modifiers::default(), + }); + cx.simulate_event(MouseUpEvent { + position: point(seam.x + px(100.0), seam.y), + button: MouseButton::Left, + modifiers: Modifiers::default(), + click_count: 1, + }); + cx.run_until_parked(); + let dragged = cx + .debug_bounds("panel-test-main") + .expect("main panel laid out after the drag") + .size + .width; + assert_eq!(dragged, start + px(100.0)); + + let split = SharedString::from("split"); + cx.update(|_, cx| stack.update(cx, |stack, cx| stack.close(PanelSlot::Split, &split, cx))); + cx.run_until_parked(); + cx.update(|_, cx| { + stack.update(cx, |stack, cx| { + stack.insert( + PanelSlot::Split, + split.clone(), + Arc::new(tag(cx, "panel-test-split")), + cx, + ) + }) + }); + cx.run_until_parked(); + + let reopened = cx + .debug_bounds("panel-test-main") + .expect("main panel laid out after reopening") + .size + .width; + assert_eq!( + reopened, start, + "the divider position is forgotten while no split is on screen" + ); +} + +/// The titlebar strip above the stack. +struct TabsHarness { + stack: Entity, +} + +impl Render for TabsHarness { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + v_flex() + .size_full() + .children(PanelStack::main_tabs(self.stack.clone(), cx)) + .child(self.stack.clone()) + } +} + +/// The titlebar strip lists the main stack; its tabs switch and close panels. +#[gpui::test] +fn main_tabs_switch_and_close_the_main_stack(cx: &mut TestAppContext) { + let stack = cx.update(|cx| { + Theme::init(cx); + cx.new(|cx| PanelStack::new("panel-harness", cx)) + }); + let window = cx.open_window(size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), |_, _| { + TabsHarness { + stack: stack.clone(), + } + }); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.run_until_parked(); + assert!( + cx.debug_bounds("panel-harness-main-tabs-tab-panel-test-first") + .is_none(), + "no strip while the main stack is empty" + ); + + cx.update(|_, cx| { + stack.update(cx, |stack, cx| { + stack.insert( + PanelSlot::Main, + "first", + Arc::new(tag(cx, "panel-test-first")), + cx, + ); + stack.insert( + PanelSlot::Main, + "second", + Arc::new(tag(cx, "panel-test-second")), + cx, + ); + }) + }); + cx.run_until_parked(); + assert!( + cx.debug_bounds("panel-test-second").is_some(), + "the newest panel opens shown" + ); + + let first = cx + .debug_bounds("panel-harness-main-tabs-tab-panel-test-first") + .expect("the strip lists the first panel"); + cx.simulate_click(first.center(), Modifiers::none()); + cx.run_until_parked(); + assert!( + cx.debug_bounds("panel-test-first").is_some(), + "clicking a tab shows its panel" + ); + assert!(cx.debug_bounds("panel-test-second").is_none()); + // The close control is laid out only while its tab is hovered. + let second = cx + .debug_bounds("panel-harness-main-tabs-tab-panel-test-second") + .expect("the strip lists the second panel"); + cx.simulate_event(MouseMoveEvent { + position: second.center(), + pressed_button: None, + modifiers: Modifiers::default(), + }); + cx.run_until_parked(); + + let close = cx + .debug_bounds("panel-harness-main-tabs-close-panel-test-second") + .expect("tabs close"); + cx.simulate_click(close.center(), Modifiers::none()); + cx.run_until_parked(); + assert!( + cx.debug_bounds("panel-harness-main-tabs-tab-panel-test-second") + .is_none(), + "closing a tab closes its panel" + ); + assert!( + cx.debug_bounds("panel-test-first").is_some(), + "the shown panel stays" + ); +} + +/// A split inserted at a width opens with it. +#[gpui::test] +fn a_split_inserted_at_a_width_opens_there(cx: &mut TestAppContext) { + let (mut cx, stack) = stack_window(cx, main_only); + cx.update(|_, cx| { + stack.update(cx, |stack, cx| { + stack.insert_split_at( + "side", + px(300.), + SplitSide::Trailing, + Arc::new(tag(cx, "panel-test-split")), + cx, + ) + }) + }); + cx.run_until_parked(); + + let split = cx + .debug_bounds("panel-test-split") + .expect("split panel laid out"); + assert!((split.size.width - px(300.0)).abs() <= px(2.0)); + cx.update(|_, cx| { + let stack = stack.read(cx); + let side = SharedString::from("side"); + assert!(stack.is_open(PanelSlot::Split, &side)); + assert!(stack.is_active(PanelSlot::Split, &side)); + }); +} + +/// A split already on screen keeps its divider and side when another opens at a width. +#[gpui::test] +fn a_width_and_side_apply_to_a_split_new_to_the_screen_only(cx: &mut TestAppContext) { + let (mut cx, stack) = stack_window(cx, main_and_split); + let before = cx + .debug_bounds("panel-test-main") + .expect("main panel laid out"); + + cx.update(|_, cx| { + stack.update(cx, |stack, cx| { + stack.insert_split_at( + "side", + px(300.), + SplitSide::Leading, + Arc::new(tag(cx, "panel-test-side")), + cx, + ) + }) + }); + cx.run_until_parked(); + + let after = cx + .debug_bounds("panel-test-main") + .expect("main panel laid out"); + assert_eq!(after, before); + cx.update(|_, cx| { + let stack = stack.read(cx); + let split = SharedString::from("split"); + assert!(stack.is_open(PanelSlot::Split, &split)); + assert!(!stack.is_active(PanelSlot::Split, &split)); + }); + let side = cx + .debug_bounds("panel-test-side") + .expect("the new split panel laid out"); + assert!( + side.left() >= after.right(), + "it still opens after the main panel" + ); +} + +/// A split opened at a width keeps it across window resizes until the divider is dragged. +#[gpui::test] +fn a_width_split_follows_resizes_until_dragged(cx: &mut TestAppContext) { + let (mut cx, _stack) = stack_window(cx, |stack, cx| { + main_only(stack, cx); + stack.insert_split_at( + "side", + px(300.), + SplitSide::Trailing, + Arc::new(tag(cx, "panel-test-split")), + cx, + ); + }); + + cx.simulate_resize(size(px(WINDOW_WIDTH + 400.0), px(WINDOW_HEIGHT))); + cx.run_until_parked(); + let split = cx + .debug_bounds("panel-test-split") + .expect("split panel laid out after the resize"); + assert!( + (split.size.width - px(300.0)).abs() <= px(2.0), + "the split keeps its width: {:?}", + split.size.width + ); + + let handle = cx.debug_bounds("resize-handle").expect("divider laid out"); + let seam = point(handle.center().x, px(400.0)); + cx.simulate_event(MouseDownEvent { + position: seam, + button: MouseButton::Left, + modifiers: Modifiers::default(), + click_count: 1, + first_mouse: false, + }); + cx.simulate_event(MouseMoveEvent { + position: point(seam.x + px(100.0), seam.y), + pressed_button: Some(MouseButton::Left), + modifiers: Modifiers::default(), + }); + cx.simulate_event(MouseUpEvent { + position: point(seam.x + px(100.0), seam.y), + button: MouseButton::Left, + modifiers: Modifiers::default(), + click_count: 1, + }); + cx.run_until_parked(); + let dragged = cx + .debug_bounds("panel-test-main") + .expect("main panel laid out after the drag") + .size + .width; + + cx.simulate_resize(size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT))); + cx.run_until_parked(); + let resized = cx + .debug_bounds("panel-test-main") + .expect("main panel laid out after the resize") + .size + .width; + assert_eq!(resized, dragged, "a dragged divider keeps its pane's width"); +} + +/// A leading split opens before the main panel and keeps its width, dragged or not, across window resizes. +#[gpui::test] +fn a_leading_split_opens_before_the_main_panel_at_its_width(cx: &mut TestAppContext) { + let (mut cx, _stack) = stack_window(cx, |stack, cx| { + main_only(stack, cx); + stack.insert_split_at( + "side", + px(300.), + SplitSide::Leading, + Arc::new(tag(cx, "panel-test-split")), + cx, + ); + }); + + let split = cx + .debug_bounds("panel-test-split") + .expect("split panel laid out"); + let main = cx + .debug_bounds("panel-test-main") + .expect("main panel laid out"); + assert!(split.right() <= main.left(), "the split comes first"); + assert!((split.size.width - px(300.0)).abs() <= px(2.0)); + + cx.simulate_resize(size(px(WINDOW_WIDTH + 400.0), px(WINDOW_HEIGHT))); + cx.run_until_parked(); + let split = cx + .debug_bounds("panel-test-split") + .expect("split panel laid out after the resize"); + assert!( + (split.size.width - px(300.0)).abs() <= px(2.0), + "the split keeps its width: {:?}", + split.size.width + ); + + // Drag the divider 100px right, then put the window back: the split keeps the dragged width. + let handle = cx.debug_bounds("resize-handle").expect("divider laid out"); + let seam = point(handle.center().x, px(400.0)); + cx.simulate_event(MouseDownEvent { + position: seam, + button: MouseButton::Left, + modifiers: Modifiers::default(), + click_count: 1, + first_mouse: false, + }); + cx.simulate_event(MouseMoveEvent { + position: point(seam.x + px(100.0), seam.y), + pressed_button: Some(MouseButton::Left), + modifiers: Modifiers::default(), + }); + cx.simulate_event(MouseUpEvent { + position: point(seam.x + px(100.0), seam.y), + button: MouseButton::Left, + modifiers: Modifiers::default(), + click_count: 1, + }); + cx.run_until_parked(); + + cx.simulate_resize(size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT))); + cx.run_until_parked(); + let split = cx + .debug_bounds("panel-test-split") + .expect("split panel laid out after the resize"); + assert!( + (split.size.width - px(400.0)).abs() <= px(2.0), + "the split keeps its dragged width: {:?}", + split.size.width + ); +} + +/// Once no split is on screen, the next one opens after the main panel again. +#[gpui::test] +fn a_split_after_a_leading_one_opens_after_the_main_panel(cx: &mut TestAppContext) { + let (mut cx, stack) = stack_window(cx, |stack, cx| { + main_only(stack, cx); + stack.insert_split_at( + "side", + px(300.), + SplitSide::Leading, + Arc::new(tag(cx, "panel-test-side")), + cx, + ); + }); + + let side = SharedString::from("side"); + cx.update(|_, cx| { + stack.update(cx, |stack, cx| { + stack.close(PanelSlot::Split, &side, cx); + stack.insert( + PanelSlot::Split, + "split", + Arc::new(tag(cx, "panel-test-split")), + cx, + ); + }) + }); + cx.run_until_parked(); + + let main = cx + .debug_bounds("panel-test-main") + .expect("main panel laid out"); + let split = cx + .debug_bounds("panel-test-split") + .expect("split panel laid out"); + assert!( + main.right() <= split.left(), + "the split opens after the main panel again" + ); +} + +/// A panel's toolbar zooms it to fill the row and back, and closes it. +#[gpui::test] +fn the_toolbar_zooms_its_panel_and_closes_it(cx: &mut TestAppContext) { + let (mut cx, _stack) = stack_window(cx, |stack, cx| { + main_only(stack, cx); + stack.insert( + PanelSlot::Split, + "split", + Arc::new(toolbar_tag(cx, "panel-test-split")), + cx, + ); + }); + + let pane = cx + .debug_bounds("panel-test-split") + .expect("split panel laid out"); + let zoom = cx + .debug_bounds("panel-harness-zoom-split") + .expect("the split pane shows a zoom button"); + assert!( + zoom.right() <= pane.right() && zoom.top() >= pane.top(), + "the toolbar sits over the pane's top right: {:?}", + zoom + ); + assert!( + cx.debug_bounds("panel-harness-zoom-main").is_none(), + "a panel without the toolbar shows none" + ); + + cx.simulate_click(zoom.center(), Modifiers::none()); + cx.run_until_parked(); + let zoomed = cx + .debug_bounds("panel-test-split") + .expect("split panel laid out zoomed"); + assert!( + cx.debug_bounds("panel-test-main").is_none(), + "zooming hides the main pane" + ); + assert!( + cx.debug_bounds("resize-handle").is_none(), + "and the divider" + ); + assert!(zoomed.size.width >= px(WINDOW_WIDTH - 40.0)); + + cx.simulate_click(zoom.center(), Modifiers::none()); + cx.run_until_parked(); + let restored = cx + .debug_bounds("panel-test-split") + .expect("split panel laid out restored"); + assert!( + cx.debug_bounds("panel-test-main").is_some(), + "unzooming brings the main pane back" + ); + assert!(restored.size.width < px(WINDOW_WIDTH / 2.0)); + + let close = cx + .debug_bounds("panel-harness-close-split") + .expect("the split pane shows a close button"); + cx.simulate_click(close.center(), Modifiers::none()); + cx.run_until_parked(); + assert!( + cx.debug_bounds("panel-test-split").is_none(), + "close closes the panel" + ); + assert!( + cx.debug_bounds("panel-harness-zoom-split").is_none(), + "and its toolbar leaves with it" + ); +} + +/// Without a split on screen, the toolbar's buttons do nothing. +#[gpui::test] +fn toolbar_buttons_do_nothing_without_a_split(cx: &mut TestAppContext) { + let (mut cx, stack) = stack_window(cx, |stack, cx| { + stack.insert( + PanelSlot::Main, + "main", + Arc::new(toolbar_tag(cx, "panel-test-main")), + cx, + ); + }); + let before = cx + .debug_bounds("panel-test-main") + .expect("main panel laid out"); + let zoom = cx + .debug_bounds("panel-harness-zoom-main") + .expect("the main pane shows a zoom button"); + let close = cx + .debug_bounds("panel-harness-close-main") + .expect("the main pane shows a close button"); + + cx.simulate_click(zoom.center(), Modifiers::none()); + cx.simulate_click(close.center(), Modifiers::none()); + cx.run_until_parked(); + + assert_eq!( + cx.debug_bounds("panel-test-main") + .expect("main panel laid out"), + before, + "the buttons are disabled without a split" + ); + cx.update(|_, cx| { + assert!( + stack + .read(cx) + .is_active(PanelSlot::Main, &SharedString::from("main")) + ); + }); +} + +/// Zooming belongs to the panel: showing another split panel ends it. +#[gpui::test] +fn zoom_ends_when_another_split_panel_is_shown(cx: &mut TestAppContext) { + let (mut cx, _stack) = stack_window(cx, |stack, cx| { + main_only(stack, cx); + stack.insert( + PanelSlot::Split, + "second", + Arc::new(tag(cx, "panel-test-second")), + cx, + ); + stack.insert( + PanelSlot::Split, + "first", + Arc::new(toolbar_tag(cx, "panel-test-first")), + cx, + ); + }); + let zoom = cx + .debug_bounds("panel-harness-zoom-split") + .expect("zoom button"); + cx.simulate_click(zoom.center(), Modifiers::none()); + cx.run_until_parked(); + assert!( + cx.debug_bounds("panel-test-main").is_none(), + "the first panel is zoomed" + ); + + let second = cx + .debug_bounds("panel-harness-split-tabs-tab-panel-test-second") + .expect("the second panel's pill tab"); + cx.simulate_click(second.center(), Modifiers::none()); + cx.run_until_parked(); + assert!(cx.debug_bounds("panel-test-second").is_some()); + assert!( + cx.debug_bounds("panel-test-main").is_some(), + "the split is back once another panel is shown" + ); +} diff --git a/desktop/src/main.rs b/desktop/src/main.rs index 5141d38..d8bd5cf 100644 --- a/desktop/src/main.rs +++ b/desktop/src/main.rs @@ -46,30 +46,36 @@ fn main() { KeyBinding::new("cmd-q", Quit, None), KeyBinding::new("ctrl-q", Quit, None), ]); + cx.on_action(|_: &Quit, cx| cx.quit()); + cx.set_app_identity("info.reya.signed", "Signed"); let store = cx.new(|cx| SettingsStore::new(paths::settings_file(), cx)); SettingsStore::set_global(store.clone(), cx); + let settings = store.read(cx).settings().clone(); - signed_app::apply_appearance(&settings, cx); + signed_app::apply_appearance_mode(settings.appearance, cx); if let Err(error) = std::fs::create_dir_all(paths::nostr_dir()) { tracing::warn!("failed to create nostr dir: {error}"); } + if let Err(error) = std::fs::create_dir_all(paths::repos_dir()) { tracing::warn!("failed to create repos dir: {error}"); } + signed_state::init( paths::nostr_dir(), paths::repos_dir().clone(), settings.local_repos.scan_paths.clone(), cx, ); + metadata::init(cx); - cx.set_app_identity("info.reya.signed", "Signed"); let theme = cx.theme(); let bounds = Bounds::centered(None, size(px(1120.0), px(750.0)), cx); + let options = WindowOptions { window_bounds: Some(WindowBounds::Windowed(bounds)), window_min_size: Some(size(px(960.0), px(640.0))), diff --git a/docs/gpui-native-kit-gaps.md b/docs/gpui-native-kit-gaps.md index e21ee37..1ac38fa 100644 --- a/docs/gpui-native-kit-gaps.md +++ b/docs/gpui-native-kit-gaps.md @@ -2,5 +2,10 @@ Vendored `crates/ui` shortcomings recorded here instead of patched in place. -- `PanelRow` (`src/layout/panel.rs`) seeds its split panes from `window.viewport_size()` during the first render frame. On some launches that size is not yet the window's final bounds, so the divider freezes at a wrong position (observed ~24% instead of the intended 50%) until a drag or a double-click reset. Seeding from the canvas-measured extent, or re-seeding while no user resize has happened, would fix it. +- `PanelStack` (`src/layout/panel.rs`) seeds its split panes from `window.viewport_size()` during the first render frame. On some launches that size is not yet the window's final bounds, so the divider freezes at a wrong position (observed ~24% instead of the intended 50%) until a drag or a double-click reset. A split opened at a width is not affected: `insert_split_at` sizes a leading one directly and re-seeds a trailing one while untouched. Seeding from the canvas-measured extent, or re-seeding while no user resize has happened, would fix the half splits. - `island()` (`src/layout/panel.rs`) rounds and paints `overflow_hidden`, but gpui's `ContentMask` is rectangular only: children are never clipped to the rounded corners. Full-bleed panel content (photos, backgrounds) paints square over the island chrome and must apply the matching `theme.radius.overlay` itself — see the signed-out banner in `signed_app`. +- The popup primitives extracted into `menu.rs` (`trigger_toggle`, `anchored_overlay`, `focus_capture`) cover the trigger-button, anchored-panel, and focus-grab surfaces. They do not cover lists: `ComboboxState` and `CommandPaletteState` keep their own entity-backed virtualized rows outside the `MenuItem` engine because menu rows are built per frame from a `Vec`, while both hold stateful selections the `uniform_list` drives. Any future row engine should absorb those two. +- `toast.rs` and `alert.rs` each re-implement the same scaffolding: a store entity with push/dismiss ids, an entry wrapper, a floating stack view with fade-out. Unification was declined for now; if either gains behavior the other lacks, extract the shared store/stack shell first. +- The toggle family (`checkbox.rs`, `switch.rs`, `toggle.rs`) restates the same control scaffolding three times: sizing, disabled handling, a `when(checked)` style fork, and an on-change handler with optimistic paint. A shared toggle base would shrink the trio. +- `StatusDot` and `Badge` both map a `*Variant` enum onto the same theme tokens (primary/success/warning/destructive ramps plus muted foreground). The tables are duplicated rather than shared. +- `ControlSizing` (`common.rs`) and the `Size::*_rems` methods (`theme`) are parallel lookup tables: one maps `Size` to control metrics, the other to glyph metrics. Adding a size means touching both.