Vendor the native UI kit as crates/ui

- crates/ui holds the theme, icons, components, data widgets, editor surfaces, layout, and utilities; cargo feature gates are gone.
- One merged icon set of 154 SVGs where the app file wins every duplicate name, served by a single rust-embed Assets source.
- IconRole grows the 25 app glyphs, so assets::CustomIconName and crates/assets are deleted.
- ui::init owns the theme and key bindings that desktop used to bind in three calls.
- docs/gpui-native-kit-gaps.md becomes docs/ui-gaps.md; the icon gap is closed.
This commit is contained in:
2026-11-17 09:36:20 +07:00
parent ad6e00b4b9
commit d795dc6e32
287 changed files with 28142 additions and 590 deletions
Generated
+427 -137
View File
@@ -114,6 +114,15 @@ dependencies = [
"equator",
]
[[package]]
name = "alloca"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5a7d05ea6aea7e9e64d25b9156ba2fee3fdd659e34e41063cd2fc7cd020d7f4"
dependencies = [
"cc",
]
[[package]]
name = "allocator-api2"
version = "0.2.21"
@@ -151,6 +160,18 @@ dependencies = [
"libc",
]
[[package]]
name = "anes"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299"
[[package]]
name = "anstyle"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
[[package]]
name = "anyhow"
version = "1.0.104"
@@ -226,16 +247,6 @@ dependencies = [
"zbus 5.19.0",
]
[[package]]
name = "assets"
version = "0.2.0"
dependencies = [
"gpui",
"gpui-native-kit",
"rust-embed",
"serde_json",
]
[[package]]
name = "async-broadcast"
version = "0.7.2"
@@ -420,6 +431,12 @@ dependencies = [
"web-sys",
]
[[package]]
name = "atomic"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c59bdb34bc650a32731b31bd8f0829cc15d24a708ee31559e0bb34f2bc320cba"
[[package]]
name = "atomic-waker"
version = "1.1.2"
@@ -531,6 +548,17 @@ version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "efbd3e1070bbdf4cd88a75264e18e8a26f7cb5c6949eadf0ceb85fb159cf08f8"
[[package]]
name = "bench_metrics"
version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#d39178f6c9e6adeb68e7a0df0b2a5b7d7bd35877"
dependencies = [
"anyhow",
"criterion",
"libc",
"perf-event2",
]
[[package]]
name = "bip39"
version = "2.2.2"
@@ -556,6 +584,10 @@ name = "bit-vec"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72503af1e72be411d74ca45cd6b309878fcb35354e252fc2a3a8bda3a97082a0"
dependencies = [
"borsh",
"serde",
]
[[package]]
name = "bit_field"
@@ -699,6 +731,30 @@ dependencies = [
"piper",
]
[[package]]
name = "borsh"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a"
dependencies = [
"borsh-derive",
"bytes",
"cfg_aliases",
]
[[package]]
name = "borsh-derive"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56"
dependencies = [
"once_cell",
"proc-macro-crate",
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "bstr"
version = "1.13.1"
@@ -760,6 +816,12 @@ version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
[[package]]
name = "c-enum"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd17eb909a8c6a894926bfcc3400a4bb0e732f5a57d37b1f14e8b29e329bace8"
[[package]]
name = "calloop"
version = "0.14.5"
@@ -772,6 +834,12 @@ dependencies = [
"tracing",
]
[[package]]
name = "cast"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
[[package]]
name = "cbc"
version = "0.1.2"
@@ -872,6 +940,33 @@ dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "ciborium"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e"
dependencies = [
"ciborium-io",
"ciborium-ll",
"serde",
]
[[package]]
name = "ciborium-io"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757"
[[package]]
name = "ciborium-ll"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9"
dependencies = [
"ciborium-io",
"half",
]
[[package]]
name = "cipher"
version = "0.4.4"
@@ -894,6 +989,31 @@ dependencies = [
"inout 0.2.6",
]
[[package]]
name = "clap"
version = "4.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac230478587d0269d8d6998b82ae69ea51509d55df66d9e92edd1f986904cd4a"
dependencies = [
"clap_builder",
]
[[package]]
name = "clap_builder"
version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
dependencies = [
"anstyle",
"clap_lex",
]
[[package]]
name = "clap_lex"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79"
[[package]]
name = "clru"
version = "0.6.3"
@@ -989,6 +1109,15 @@ dependencies = [
"unicode-segmentation",
]
[[package]]
name = "convert_case"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "affbf0190ed2caf063e3def54ff444b449371d55c58e513a95ab98eca50adb49"
dependencies = [
"unicode-segmentation",
]
[[package]]
name = "core-foundation"
version = "0.10.1"
@@ -1151,6 +1280,41 @@ dependencies = [
"cfg-if",
]
[[package]]
name = "criterion"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "950046b2aa2492f9a536f5f4f9a3de7b9e2476e575e05bd6c333371add4d98f3"
dependencies = [
"alloca",
"anes",
"cast",
"ciborium",
"clap",
"criterion-plot",
"itertools 0.13.0",
"num-traits",
"oorandom",
"page_size",
"plotters",
"rayon",
"regex",
"serde",
"serde_json",
"tinytemplate",
"walkdir",
]
[[package]]
name = "criterion-plot"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8d80a2f4f5b554395e47b5d8305bc3d27813bacb73493eb1001e8f76dae29ea"
dependencies = [
"cast",
"itertools 0.13.0",
]
[[package]]
name = "crossbeam-channel"
version = "0.5.17"
@@ -1331,7 +1495,7 @@ version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"
dependencies = [
"convert_case",
"convert_case 0.10.0",
"proc-macro2",
"quote",
"rustc_version",
@@ -1689,6 +1853,12 @@ version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
[[package]]
name = "fixedbitset"
version = "0.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5905ec755cc8386d7928353e4d356d2be3e89e81e5ca01fe630a1ca4d08dc175"
[[package]]
name = "flatbuffers"
version = "25.12.19"
@@ -1876,6 +2046,19 @@ dependencies = [
"futures-sink",
]
[[package]]
name = "futures-concurrency"
version = "7.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "175cd8cca9e1d45b87f18ffa75088f2099e3c4fe5e2f83e42de112560bea8ea6"
dependencies = [
"fixedbitset",
"futures-core",
"futures-lite",
"pin-project",
"smallvec",
]
[[package]]
name = "futures-core"
version = "0.3.34"
@@ -2995,6 +3178,7 @@ dependencies = [
"async-channel",
"async-task",
"backtrace",
"bench_metrics",
"bitflags 2.13.2",
"chrono",
"collections",
@@ -3002,6 +3186,7 @@ dependencies = [
"embed-resource",
"etagere",
"futures",
"futures-concurrency",
"getrandom 0.3.4",
"gpui_macros",
"gpui_shared_string",
@@ -3011,7 +3196,7 @@ dependencies = [
"icu_segmenter",
"image",
"inventory",
"itertools",
"itertools 0.14.0",
"libc",
"log",
"lyon_path",
@@ -3021,8 +3206,10 @@ dependencies = [
"parking",
"parking_lot",
"pin-project",
"pollster",
"pollster 0.4.0",
"postage",
"profiling",
"proptest",
"rand 0.9.5",
"raw-window-handle",
"refineable",
@@ -3047,123 +3234,11 @@ dependencies = [
"usvg",
"uuid",
"waker-fn",
"web-time",
"windows 0.62.2",
"zed-scap",
]
[[package]]
name = "gpui-native-core"
version = "0.1.0"
source = "git+https://git.reya.info/reya/gpui-native-kit#aed3601c890e49a8aba354df06416ce95ecbe169"
dependencies = [
"cpal",
"flume 0.12.0",
"gpui",
"gpui-native-icons",
"gpui-native-theme",
"gpui-native-utils",
"image",
"log",
"unicode-segmentation",
]
[[package]]
name = "gpui-native-data"
version = "0.1.0"
source = "git+https://git.reya.info/reya/gpui-native-kit#aed3601c890e49a8aba354df06416ce95ecbe169"
dependencies = [
"gpui",
"gpui-native-core",
"gpui-native-icons",
"gpui-native-theme",
"gpui-native-utils",
]
[[package]]
name = "gpui-native-editor"
version = "0.1.0"
source = "git+https://git.reya.info/reya/gpui-native-kit#aed3601c890e49a8aba354df06416ce95ecbe169"
dependencies = [
"gpui",
"gpui-native-core",
"gpui-native-theme",
"gpui-native-utils",
"log",
"pulldown-cmark",
"similar",
"tree-sitter",
"tree-sitter-javascript",
"tree-sitter-python",
"tree-sitter-rust",
"tree-sitter-typescript",
]
[[package]]
name = "gpui-native-icons"
version = "0.1.0"
source = "git+https://git.reya.info/reya/gpui-native-kit#aed3601c890e49a8aba354df06416ce95ecbe169"
dependencies = [
"anyhow",
"gpui",
]
[[package]]
name = "gpui-native-kit"
version = "0.1.0"
source = "git+https://git.reya.info/reya/gpui-native-kit#aed3601c890e49a8aba354df06416ce95ecbe169"
dependencies = [
"gpui",
"gpui-native-core",
"gpui-native-data",
"gpui-native-editor",
"gpui-native-icons",
"gpui-native-layout",
"gpui-native-theme",
]
[[package]]
name = "gpui-native-layout"
version = "0.1.0"
source = "git+https://git.reya.info/reya/gpui-native-kit#aed3601c890e49a8aba354df06416ce95ecbe169"
dependencies = [
"gpui",
"gpui-native-core",
"gpui-native-icons",
"gpui-native-theme",
"gpui-native-utils",
]
[[package]]
name = "gpui-native-theme"
version = "0.1.0"
source = "git+https://git.reya.info/reya/gpui-native-kit#aed3601c890e49a8aba354df06416ce95ecbe169"
dependencies = [
"anyhow",
"async-channel",
"block2 0.6.2",
"gpui",
"log",
"notify",
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
"serde",
"toml 0.8.23",
"windows 0.62.2",
"windows-registry 0.6.1",
"zbus 5.19.0",
]
[[package]]
name = "gpui-native-utils"
version = "0.1.0"
source = "git+https://git.reya.info/reya/gpui-native-kit#aed3601c890e49a8aba354df06416ce95ecbe169"
dependencies = [
"gpui",
"gpui-native-theme",
"log",
]
[[package]]
name = "gpui_apple"
version = "0.1.0"
@@ -3272,7 +3347,7 @@ dependencies = [
"gpui_apple",
"gpui_util",
"image",
"itertools",
"itertools 0.14.0",
"log",
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
@@ -3379,7 +3454,7 @@ dependencies = [
"etagere",
"gpui",
"gpui_util",
"itertools",
"itertools 0.14.0",
"js-sys",
"log",
"parking_lot",
@@ -3408,7 +3483,7 @@ dependencies = [
"gpui",
"gpui_util",
"image",
"itertools",
"itertools 0.14.0",
"log",
"parking_lot",
"rand 0.9.5",
@@ -3669,6 +3744,7 @@ dependencies = [
"futures",
"http",
"http-body",
"log",
"parking_lot",
"serde",
"serde_json",
@@ -3983,7 +4059,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"
dependencies = [
"byteorder-lite",
"quick-error",
"quick-error 2.0.1",
]
[[package]]
@@ -4085,6 +4161,15 @@ version = "2.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
[[package]]
name = "itertools"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
dependencies = [
"either",
]
[[package]]
name = "itertools"
version = "0.14.0"
@@ -5408,6 +5493,12 @@ dependencies = [
"zvariant",
]
[[package]]
name = "oorandom"
version = "11.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
[[package]]
name = "opaque-debug"
version = "0.3.1"
@@ -5560,6 +5651,41 @@ version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "perf-event-data"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "575828d9d7d205188048eb1508560607a03d21eafdbba47b8cade1736c1c28e1"
dependencies = [
"bitflags 2.13.2",
"c-enum",
"perf-event-open-sys2",
]
[[package]]
name = "perf-event-open-sys2"
version = "5.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9c25955321465255e437600b54296983fab1feac2cd0c38958adeb26dbae49e"
dependencies = [
"libc",
"memoffset",
]
[[package]]
name = "perf-event2"
version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0939b8fad77dfaeb29ebbd35faaeaadbf833167f30975f1b8993bbba09ea0a0f"
dependencies = [
"bitflags 2.13.2",
"c-enum",
"libc",
"memmap2",
"perf-event-data",
"perf-event-open-sys2",
]
[[package]]
name = "phf"
version = "0.11.3"
@@ -5651,6 +5777,34 @@ version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
[[package]]
name = "plotters"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5aeb6f403d7a4911efb1e33402027fc44f29b5bf6def3effcc22d7bb75f2b747"
dependencies = [
"num-traits",
"plotters-backend",
"plotters-svg",
"wasm-bindgen",
"web-sys",
]
[[package]]
name = "plotters-backend"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df42e13c12958a16b3f7f4386b9ab1f3e7933914ecea48da7139435263a4172a"
[[package]]
name = "plotters-svg"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51bae2ac328883f7acdfea3d66a7c35751187f870bc81f94563733a154d7a670"
dependencies = [
"plotters-backend",
]
[[package]]
name = "png"
version = "0.17.16"
@@ -5691,6 +5845,12 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "pollster"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5da3b0203fd7ee5720aa0b5e790b591aa5d3f41c3ed2c34a3a393382198af2f7"
[[package]]
name = "pollster"
version = "0.4.0"
@@ -5732,6 +5892,21 @@ dependencies = [
"portable-atomic",
]
[[package]]
name = "postage"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af3fb618632874fb76937c2361a7f22afd393c982a2165595407edc75b06d3c1"
dependencies = [
"atomic",
"crossbeam-queue",
"parking_lot",
"pin-project",
"pollster 0.2.5",
"static_assertions",
"thiserror 1.0.69",
]
[[package]]
name = "potential_utf"
version = "0.1.6"
@@ -5810,6 +5985,39 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "proptest"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0"
dependencies = [
"bit-set",
"bit-vec",
"bitflags 2.13.2",
"chacha20 0.10.2",
"core_detect",
"num-traits",
"proptest-macro",
"rand 0.10.4",
"rand_xorshift",
"regex-syntax",
"rusty-fork",
"tempfile",
"unarray",
]
[[package]]
name = "proptest-macro"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e99782ea31698c2206c6887c1220d2f594b291c26cb9ec5b6d7cf175320bc212"
dependencies = [
"convert_case 0.11.0",
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "pulldown-cmark"
version = "0.13.6"
@@ -5836,6 +6044,12 @@ dependencies = [
"bytemuck",
]
[[package]]
name = "quick-error"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
[[package]]
name = "quick-error"
version = "2.0.1"
@@ -6014,6 +6228,15 @@ dependencies = [
"rand_core 0.10.1",
]
[[package]]
name = "rand_xorshift"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf"
dependencies = [
"rand_core 0.10.1",
]
[[package]]
name = "range-alloc"
version = "0.1.5"
@@ -6042,7 +6265,7 @@ dependencies = [
"built",
"cfg-if",
"interpolate_name",
"itertools",
"itertools 0.14.0",
"libc",
"libfuzzer-sys",
"log",
@@ -6070,7 +6293,7 @@ dependencies = [
"avif-serialize",
"imgref",
"loop9",
"quick-error",
"quick-error 2.0.1",
"rav1e",
"rayon",
"rgb",
@@ -6498,6 +6721,18 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "rusty-fork"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2"
dependencies = [
"fnv",
"quick-error 1.2.3",
"tempfile",
"wait-timeout",
]
[[package]]
name = "rustybuzz"
version = "0.20.1"
@@ -6868,9 +7103,7 @@ dependencies = [
name = "signed"
version = "0.2.0"
dependencies = [
"assets",
"gpui",
"gpui-native-kit",
"gpui_platform",
"metadata",
"paths",
@@ -6880,6 +7113,7 @@ dependencies = [
"signed_state",
"tracing",
"tracing-subscriber",
"ui",
]
[[package]]
@@ -6887,10 +7121,8 @@ name = "signed_app"
version = "0.2.0"
dependencies = [
"anyhow",
"assets",
"futures",
"gpui",
"gpui-native-kit",
"log",
"metadata",
"nostr",
@@ -6900,6 +7132,7 @@ dependencies = [
"signed_git",
"signed_nostr",
"signed_state",
"ui",
"utils",
]
@@ -7417,7 +7650,7 @@ dependencies = [
"fax",
"flate2",
"half",
"quick-error",
"quick-error 2.0.1",
"weezl",
"zune-jpeg",
]
@@ -7478,6 +7711,16 @@ dependencies = [
"zerovec",
]
[[package]]
name = "tinytemplate"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc"
dependencies = [
"serde",
"serde_json",
]
[[package]]
name = "tinyvec"
version = "1.13.3"
@@ -7889,6 +8132,44 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "ui"
version = "0.2.0"
dependencies = [
"anyhow",
"async-channel",
"block2 0.6.2",
"cpal",
"flume 0.11.1",
"gpui",
"image",
"log",
"notify",
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
"pulldown-cmark",
"rust-embed",
"serde",
"similar",
"toml 0.8.23",
"tree-sitter",
"tree-sitter-javascript",
"tree-sitter-python",
"tree-sitter-rust",
"tree-sitter-typescript",
"unicode-segmentation",
"windows 0.62.2",
"windows-registry 0.6.1",
"zbus 5.19.0",
]
[[package]]
name = "unarray"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"
[[package]]
name = "unicase"
version = "2.10.0"
@@ -8116,6 +8397,15 @@ dependencies = [
"libc",
]
[[package]]
name = "wait-timeout"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"
dependencies = [
"libc",
]
[[package]]
name = "waker-fn"
version = "1.2.0"
-2
View File
@@ -13,8 +13,6 @@ gpui = { git = "https://github.com/zed-industries/zed" }
gpui_platform = { git = "https://github.com/zed-industries/zed", features = ["font-kit"] }
reqwest_client = { git = "https://github.com/zed-industries/zed" }
gpui-native-kit = { git = "https://git.reya.info/reya/gpui-native-kit", features = ["layout", "editor"] }
settings = { path = "crates/settings" }
signed_app = { path = "crates/signed_app" }
-13
View File
@@ -1,13 +0,0 @@
[package]
name = "assets"
version.workspace = true
edition.workspace = true
publish.workspace = true
[dependencies]
gpui.workspace = true
gpui-native-kit.workspace = true
rust-embed.workspace = true
[dev-dependencies]
serde_json.workspace = true
View File
-98
View File
@@ -1,98 +0,0 @@
use gpui::{AssetSource, Result, SharedString};
use gpui_native_kit::icons::IconNamed;
use rust_embed::RustEmbed;
#[derive(RustEmbed)]
#[folder = "assets"]
#[include = "icons/**/*.svg"]
#[exclude = "*.DS_Store"]
pub struct Assets;
impl AssetSource for Assets {
fn load(&self, path: &str) -> Result<Option<std::borrow::Cow<'static, [u8]>>> {
if let Some(file) = Self::get(path) {
return Ok(Some(file.data));
}
gpui_native_kit::icons::IconAssets.load(path)
}
fn list(&self, path: &str) -> Result<Vec<SharedString>> {
let mut paths: Vec<SharedString> = Self::iter()
.filter(|p| p.starts_with(path))
.map(Into::into)
.collect();
paths.extend(gpui_native_kit::icons::IconAssets.list(path)?);
Ok(paths)
}
}
pub enum CustomIconName {
CirclePlus,
Unlock,
Filter,
GlobalOn,
GlobalOff,
GitFile,
GitCommit,
GitIssueDone,
GitIssueOpen,
GitIssueClosed,
GitIssueOngoing,
GitPullRequest,
GitPullRequestClosed,
GitPullRequestDraft,
GitPullRequestMerged,
GitClone,
GitBranch,
Tag,
Markdown,
Share,
Trending,
Recent,
Refresh,
Grid,
Init,
EllipsisVertical,
ArrowUp,
Trash,
Globe,
Inbox,
}
impl IconNamed for CustomIconName {
fn path(self) -> gpui::SharedString {
match self {
CustomIconName::CirclePlus => "icons/circle-plus.svg",
CustomIconName::Unlock => "icons/unlock.svg",
CustomIconName::Filter => "icons/filter.svg",
CustomIconName::GlobalOn => "icons/global-on.svg",
CustomIconName::GlobalOff => "icons/global-off.svg",
CustomIconName::GitCommit => "icons/git-commit.svg",
CustomIconName::GitFile => "icons/git-file.svg",
CustomIconName::GitIssueDone => "icons/git-issue-done.svg",
CustomIconName::GitIssueOpen => "icons/git-issue-open.svg",
CustomIconName::GitIssueClosed => "icons/git-issue-close.svg",
CustomIconName::GitIssueOngoing => "icons/git-issue-ongoing.svg",
CustomIconName::GitPullRequest => "icons/git-pull-request.svg",
CustomIconName::GitPullRequestClosed => "icons/git-pull-request-closed.svg",
CustomIconName::GitPullRequestDraft => "icons/git-pull-request-draft.svg",
CustomIconName::GitPullRequestMerged => "icons/git-pull-request-merged.svg",
CustomIconName::GitClone => "icons/git-clone.svg",
CustomIconName::GitBranch => "icons/git-branch.svg",
CustomIconName::Tag => "icons/tag.svg",
CustomIconName::Markdown => "icons/markdown.svg",
CustomIconName::Share => "icons/share.svg",
CustomIconName::Trending => "icons/trending.svg",
CustomIconName::Refresh => "icons/refresh.svg",
CustomIconName::Recent => "icons/recent.svg",
CustomIconName::Grid => "icons/grid.svg",
CustomIconName::Init => "icons/init.svg",
CustomIconName::EllipsisVertical => "icons/ellipsis-vertical.svg",
CustomIconName::ArrowUp => "icons/arrow-up.svg",
CustomIconName::Trash => "icons/trash.svg",
CustomIconName::Globe => "icons/globe.svg",
CustomIconName::Inbox => "icons/inbox.svg",
}
.into()
}
}
+1 -2
View File
@@ -5,7 +5,6 @@ edition.workspace = true
publish.workspace = true
[dependencies]
assets = { path = "../assets" }
metadata = { path = "../metadata" }
paths = { path = "../paths" }
settings = { path = "../settings" }
@@ -16,7 +15,7 @@ signed_state = { path = "../signed_state" }
utils = { path = "../utils" }
gpui.workspace = true
gpui-native-kit.workspace = true
ui = { path = "../ui" }
nostr.workspace = true
anyhow.workspace = true
futures.workspace = true
+1 -1
View File
@@ -1,6 +1,6 @@
use gpui::App;
use gpui_native_kit::theme::{ThemeVariant, follow_system, set_mode_override};
use settings::{AppearanceMode, Settings};
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) {
+6 -6
View File
@@ -6,15 +6,15 @@ use gpui::{
AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _,
Subscription, Window, div,
};
use gpui_native_kit::icons::IconRole;
use gpui_native_kit::layout::panel::PanelRow;
use gpui_native_kit::layout::shell::Shell;
use gpui_native_kit::layout::titlebar::Titlebar;
use gpui_native_kit::theme::ActiveTheme as _;
use gpui_native_kit::toast::{Toast, Toasts};
use helpers::apply_appearance;
use settings::SettingsStore;
use signed_state::{Backend, BackendEvent};
use ui::icons::IconRole;
use ui::layout::panel::PanelRow;
use ui::layout::shell::Shell;
use ui::layout::titlebar::Titlebar;
use ui::theme::ActiveTheme as _;
use ui::toast::{Toast, Toasts};
use crate::app::placeholder::PlaceholderView;
use crate::app::sign_in::SignedOutView;
+2 -2
View File
@@ -1,8 +1,8 @@
use gpui::{
Context, IntoElement, ParentElement as _, Render, SharedString, Styled as _, Window, div,
};
use gpui_native_kit::empty_state::EmptyState;
use gpui_native_kit::layout::panel::Panel;
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 {
+3 -3
View File
@@ -1,9 +1,9 @@
use gpui::{
Context, FontWeight, IntoElement, ParentElement as _, Render, Styled as _, Window, div,
};
use gpui_native_kit::button::{Button, ButtonVariant};
use gpui_native_kit::common::v_flex;
use gpui_native_kit::layout::panel::Panel;
use ui::button::{Button, ButtonVariant};
use ui::common::v_flex;
use ui::layout::panel::Panel;
use crate::identity;
+5 -6
View File
@@ -1,16 +1,15 @@
use assets::CustomIconName;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, Entity, InteractiveElement as _, IntoElement, ParentElement as _, SharedString,
StatefulInteractiveElement as _, Styled as _, WeakEntity, div, px,
};
use gpui_native_kit::avatar::Avatar;
use gpui_native_kit::common::{Sizable as _, h_flex, v_flex};
use gpui_native_kit::icons::Icon;
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use metadata::ProfileDirectory;
use signed_core::Announcement;
use signed_state::{RepoListStore, Timestamp};
use ui::avatar::Avatar;
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use utils::relative_time;
use crate::repo::actions::open_repo_panel;
@@ -134,7 +133,7 @@ pub(super) fn render_card(
.text_color(cx.theme().colors.muted_foreground)
.whitespace_nowrap()
.child(
Icon::named(CustomIconName::GitBranch)
Icon::named(IconRole::GitBranch)
.size(px(12.))
.color(cx.theme().colors.muted_foreground),
)
+9 -10
View File
@@ -1,24 +1,23 @@
mod helpers;
use assets::CustomIconName;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render,
SharedString, Styled as _, Subscription, UniformListScrollHandle, WeakEntity, Window, div, px,
uniform_list,
};
use gpui_native_kit::common::{h_flex, v_flex};
use gpui_native_kit::empty_state::EmptyState;
use gpui_native_kit::icons::{Icon, IconRole};
use gpui_native_kit::input::{Input, InputState, InputStateEvent};
use gpui_native_kit::layout::panel::Panel;
use gpui_native_kit::scrollbar::Scrollbar;
use gpui_native_kit::segmented::{Segmented, SegmentedOption};
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use helpers::{RepoFilter, render_card};
use metadata::ProfileDirectory;
use nostr::prelude::PublicKey;
use signed_state::RepoListStore;
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::scrollbar::Scrollbar;
use ui::segmented::{Segmented, SegmentedOption};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use crate::workspace::Workspace;
@@ -131,7 +130,7 @@ impl ExploreView {
SegmentedOption::new(RepoFilter::All, "All")
.icon(Icon::named(IconRole::Grid).small().color(muted)),
SegmentedOption::new(RepoFilter::Popular, "Popular")
.icon(Icon::named(CustomIconName::Trending).small().color(muted)),
.icon(Icon::named(IconRole::Trending).small().color(muted)),
SegmentedOption::new(RepoFilter::Recent, "Recent")
.icon(Icon::named(IconRole::Clock).small().color(muted)),
])
+4 -4
View File
@@ -1,11 +1,11 @@
use gpui::{
AnyElement, Context, IntoElement, ParentElement as _, Render, Styled as _, Window, div,
};
use gpui_native_kit::button::{Button, ButtonVariant};
use gpui_native_kit::common::v_flex;
use gpui_native_kit::dialog::Dialog;
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use signed_state::Backend;
use ui::button::{Button, ButtonVariant};
use ui::common::v_flex;
use ui::dialog::Dialog;
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use crate::shared::dialogs::close_global;
+6 -6
View File
@@ -3,13 +3,13 @@ use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
Styled as _, Subscription, Task, Window, div, px,
};
use gpui_native_kit::button::Button;
use gpui_native_kit::common::v_flex;
use gpui_native_kit::dialog::Dialog;
use gpui_native_kit::field::Field;
use gpui_native_kit::input::{Input, InputState, InputStateEvent};
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use signed_state::Backend;
use ui::button::Button;
use ui::common::v_flex;
use ui::dialog::Dialog;
use ui::field::Field;
use ui::input::{Input, InputState, InputStateEvent};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use crate::shared::dialogs::close_global;
use crate::shared::progress::{DialogProgress, error_row};
+6 -6
View File
@@ -3,13 +3,13 @@ use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
Styled as _, Window, div, px,
};
use gpui_native_kit::button::Button;
use gpui_native_kit::common::v_flex;
use gpui_native_kit::dialog::Dialog;
use gpui_native_kit::field::Field;
use gpui_native_kit::input::{Input, InputState};
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use signed_state::Backend;
use ui::button::Button;
use ui::common::v_flex;
use ui::dialog::Dialog;
use ui::field::Field;
use ui::input::{Input, InputState};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use crate::shared::dialogs::close_global;
use crate::shared::progress::{DialogProgress, error_row};
+6 -6
View File
@@ -3,13 +3,13 @@ use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
Styled as _, Subscription, Window, px,
};
use gpui_native_kit::button::Button;
use gpui_native_kit::common::v_flex;
use gpui_native_kit::dialog::Dialog;
use gpui_native_kit::field::Field;
use gpui_native_kit::icons::{Icon, IconRole};
use gpui_native_kit::input::{Input, InputState, InputStateEvent};
use signed_state::Backend;
use ui::button::Button;
use ui::common::v_flex;
use ui::dialog::Dialog;
use ui::field::Field;
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState, InputStateEvent};
use crate::shared::dialogs::close_global;
use crate::shared::progress::{DialogProgress, error_row, push_steps_row};
+7 -8
View File
@@ -1,16 +1,15 @@
use assets::CustomIconName;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, Div, Entity, InteractiveElement as _, IntoElement, ParentElement as _,
SharedString, Stateful, Styled as _, div, px,
};
use gpui_native_kit::avatar::Avatar;
use gpui_native_kit::badge::Badge;
use gpui_native_kit::common::{Sizable as _, h_flex, v_flex};
use gpui_native_kit::icons::Icon;
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use metadata::ProfileDirectory;
use nostr::prelude::{Event, Kind, PublicKey};
use ui::avatar::Avatar;
use ui::badge::Badge;
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use utils::relative_time;
pub fn repo_header(id: SharedString, name: SharedString, unread: usize, cx: &App) -> AnyElement {
@@ -87,7 +86,7 @@ pub fn thread(
.items_center()
.justify_center()
.child(
Icon::named(CustomIconName::Inbox)
Icon::named(IconRole::Inbox)
.small()
.color(cx.theme().colors.muted_foreground),
),
@@ -179,7 +178,7 @@ pub fn empty_state(message: &'static str, cx: &App) -> AnyElement {
.gap_2()
.py_8()
.child(
Icon::named(CustomIconName::Inbox)
Icon::named(IconRole::Inbox)
.size(px(24.))
.color(cx.theme().colors.muted_foreground),
)
+6 -6
View File
@@ -7,16 +7,16 @@ use gpui::{
SharedString, StatefulInteractiveElement as _, Styled as _, Subscription, Task, WeakEntity,
Window, div,
};
use gpui_native_kit::button::Button;
use gpui_native_kit::common::{h_flex, v_flex};
use gpui_native_kit::icons::{Icon, IconRole};
use gpui_native_kit::layout::panel::Panel;
use gpui_native_kit::scroll_area::ScrollArea;
use gpui_native_kit::theme::{TextRole, Typeset as _};
use metadata::ProfileDirectory;
use nostr::prelude::{Event, EventId, Kind, PublicKey, Timestamp};
use signed_core::{InboxItem, InboxReadState, RepoAddr};
use signed_state::{Backend, BackendEvent, Inbox, RefreshGate, RefreshRequest, RepoListStore};
use ui::button::Button;
use ui::common::{h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::layout::panel::Panel;
use ui::scroll_area::ScrollArea;
use ui::theme::{TextRole, Typeset as _};
mod helpers;
+7 -7
View File
@@ -2,17 +2,17 @@ use gpui::{
Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render,
ScrollHandle, SharedString, Styled as _, Subscription, Window, div,
};
use gpui_native_kit::avatar::Avatar;
use gpui_native_kit::common::{Sizable as _, h_flex, v_flex};
use gpui_native_kit::empty_state::EmptyState;
use gpui_native_kit::input::InputState;
use gpui_native_kit::layout::panel::Panel;
use gpui_native_kit::scroll_area::ScrollArea;
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use metadata::ProfileDirectory;
use nostr::prelude::{EventId, PublicKey};
use signed_core::GitEvent;
use signed_state::RepoStore;
use ui::avatar::Avatar;
use ui::common::{Sizable 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::theme::{ActiveTheme as _, TextRole, Typeset as _};
use utils::relative_time;
use crate::issues::helpers::{comment_form, comments_section, issue_roots, sidebar_section};
+9 -10
View File
@@ -1,20 +1,19 @@
use assets::CustomIconName;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, Entity, IntoElement, ParentElement as _, SharedString, Styled as _, div, px,
};
use gpui_native_kit::avatar::Avatar;
use gpui_native_kit::badge::{Badge, BadgeVariant};
use gpui_native_kit::button::Button;
use gpui_native_kit::common::{Sizable as _, h_flex, v_flex};
use gpui_native_kit::icons::Icon;
use gpui_native_kit::input::{Input, InputState};
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use gpui_native_kit::tooltip::Tooltip;
use metadata::ProfileDirectory;
use nostr::prelude::{Event, EventId, PublicKey};
use signed_core::RepoStatus;
use signed_state::RepoStore;
use ui::avatar::Avatar;
use ui::badge::{Badge, BadgeVariant};
use ui::button::Button;
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use ui::tooltip::Tooltip;
use utils::relative_time;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -245,7 +244,7 @@ pub(crate) fn comment_form(
.typeset(TextRole::Caption, cx)
.text_color(cx.theme().colors.muted_foreground)
.child(
Icon::named(CustomIconName::Markdown)
Icon::named(IconRole::Markdown)
.size(px(12.))
.color(cx.theme().colors.muted_foreground),
)
+13 -14
View File
@@ -1,24 +1,23 @@
use assets::CustomIconName;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement,
ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled as _,
Subscription, UniformListScrollHandle, WeakEntity, Window, div, px, uniform_list,
};
use gpui_native_kit::avatar::Avatar;
use gpui_native_kit::button::Button;
use gpui_native_kit::common::{Sizable as _, h_flex, v_flex};
use gpui_native_kit::empty_state::EmptyState;
use gpui_native_kit::icons::Icon;
use gpui_native_kit::layout::panel::Panel;
use gpui_native_kit::scrollbar::Scrollbar;
use gpui_native_kit::segmented::{Segmented, SegmentedOption};
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use helpers::{IssueFilter, StatusCounts, filter_by_status};
use metadata::ProfileDirectory;
use nostr::prelude::PublicKey;
use signed_core::GitEvent;
use signed_state::RepoStore;
use ui::avatar::Avatar;
use ui::button::Button;
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::empty_state::EmptyState;
use ui::icons::{Icon, IconRole};
use ui::layout::panel::Panel;
use ui::scrollbar::Scrollbar;
use ui::segmented::{Segmented, SegmentedOption};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use utils::relative_time;
use self::detail::IssueDetailView;
@@ -136,14 +135,14 @@ impl IssuesView {
Segmented::new("issue-filter", self.filter)
.options(vec![
SegmentedOption::new(IssueFilter::All, format!("All ({})", counts.total))
.icon(Icon::named(CustomIconName::GitIssueDone).color(muted)),
.icon(Icon::named(IconRole::GitIssueDone).color(muted)),
SegmentedOption::new(IssueFilter::Open, format!("Open ({})", counts.open))
.icon(Icon::named(CustomIconName::GitIssueOpen).color(muted)),
.icon(Icon::named(IconRole::GitIssueOpen).color(muted)),
SegmentedOption::new(
IssueFilter::Closed,
format!("Closed ({})", counts.closed),
)
.icon(Icon::named(CustomIconName::GitIssueClosed).color(muted)),
.icon(Icon::named(IconRole::GitIssueClosed).color(muted)),
])
.on_change(move |filter, _, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
@@ -158,7 +157,7 @@ impl IssuesView {
.child(
Button::new("new-issue")
.label("New issue")
.icon(Icon::named(CustomIconName::CirclePlus))
.icon(Icon::named(IconRole::CirclePlus))
.on_click(cx.listener(|this, _, _, cx| {
new_issue::open(this.store.clone(), cx);
})),
+6 -6
View File
@@ -2,13 +2,13 @@ use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
Styled as _, Window, div,
};
use gpui_native_kit::button::Button;
use gpui_native_kit::common::v_flex;
use gpui_native_kit::dialog::Dialog;
use gpui_native_kit::field::Field;
use gpui_native_kit::input::{Input, InputState};
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use signed_state::RepoStore;
use ui::button::Button;
use ui::common::v_flex;
use ui::dialog::Dialog;
use ui::field::Field;
use ui::input::{Input, InputState};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use crate::shared::dialogs::{close_global, open_global};
+13 -14
View File
@@ -1,29 +1,28 @@
use std::path::PathBuf;
use assets::CustomIconName;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement,
ParentElement as _, Render, SharedString, Styled as _, Subscription, UniformListScrollHandle,
WeakEntity, Window, div, uniform_list,
};
use gpui_native_kit::avatar::Avatar;
use gpui_native_kit::button::Button;
use gpui_native_kit::clipboard::ClipboardButton;
use gpui_native_kit::common::{Sizable as _, h_flex, v_flex};
use gpui_native_kit::data::tabs::{Tab, Tabs};
use gpui_native_kit::icons::Icon;
use gpui_native_kit::input::InputState;
use gpui_native_kit::layout::panel::Panel;
use gpui_native_kit::scroll_area::ScrollArea;
use gpui_native_kit::scrollbar::Scrollbar;
use gpui_native_kit::spinner::Spinner;
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use metadata::ProfileDirectory;
use nostr::prelude::{EventId, Kind, PublicKey, Url};
use signed_core::{GitEvent, PullRequest, RepoAddr};
use signed_git::{FileCommit, PatchParser};
use signed_state::{Backend, Mirrors, RepoStore};
use ui::avatar::Avatar;
use ui::button::Button;
use ui::clipboard::ClipboardButton;
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::data::tabs::{Tab, Tabs};
use ui::icons::{Icon, IconRole};
use ui::input::InputState;
use ui::layout::panel::Panel;
use ui::scroll_area::ScrollArea;
use ui::scrollbar::Scrollbar;
use ui::spinner::Spinner;
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use utils::relative_time;
use super::dialogs;
@@ -540,7 +539,7 @@ impl PullRequestDetailView {
this.child(
Button::new("branch")
.label(branch)
.icon(Icon::named(CustomIconName::GitBranch))
.icon(Icon::named(IconRole::GitBranch))
.small(),
)
})
@@ -2,14 +2,14 @@ use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
Styled as _, Window, div,
};
use gpui_native_kit::button::Button;
use gpui_native_kit::common::v_flex;
use gpui_native_kit::dialog::Dialog;
use gpui_native_kit::field::Field;
use gpui_native_kit::input::{Input, InputState};
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use nostr::prelude::Event;
use signed_state::RepoStore;
use ui::button::Button;
use ui::common::v_flex;
use ui::dialog::Dialog;
use ui::field::Field;
use ui::input::{Input, InputState};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use crate::shared::dialogs::{close_global, open_global};
@@ -1,9 +1,9 @@
use std::path::PathBuf;
use gpui::{SharedString, WeakEntity};
use gpui_native_kit::menu::MenuItem;
use nostr::prelude::PublicKey;
use signed_core::{Announcement, RepoAddr, RepoStatus};
use ui::menu::MenuItem;
use utils::middle_truncate;
use super::NewPullRequestView;
+16 -17
View File
@@ -1,24 +1,23 @@
use assets::CustomIconName;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement,
ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled as _,
Subscription, UniformListScrollHandle, WeakEntity, Window, div, px, uniform_list,
};
use gpui_native_kit::alert::{Alert, AlertSeverity};
use gpui_native_kit::avatar::Avatar;
use gpui_native_kit::common::{Sizable as _, h_flex, v_flex};
use gpui_native_kit::dropdown_menu::DropdownMenu;
use gpui_native_kit::icons::Icon;
use gpui_native_kit::layout::panel::Panel;
use gpui_native_kit::menu::MenuItem;
use gpui_native_kit::scrollbar::Scrollbar;
use gpui_native_kit::segmented::{Segmented, SegmentedOption};
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use metadata::ProfileDirectory;
use nostr::prelude::{Kind, PublicKey};
use signed_core::GitEvent;
use signed_state::RepoStore;
use ui::alert::{Alert, AlertSeverity};
use ui::avatar::Avatar;
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::dropdown_menu::DropdownMenu;
use ui::icons::{Icon, IconRole};
use ui::layout::panel::Panel;
use ui::menu::MenuItem;
use ui::scrollbar::Scrollbar;
use ui::segmented::{Segmented, SegmentedOption};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use utils::relative_time;
mod detail;
@@ -215,27 +214,27 @@ impl PullRequestsView {
PullRequestFilter::All,
format!("All ({})", counts.total),
)
.icon(Icon::named(CustomIconName::GitPullRequest).color(muted)),
.icon(Icon::named(IconRole::GitPullRequest).color(muted)),
SegmentedOption::new(
PullRequestFilter::Open,
format!("Open ({})", counts.open),
)
.icon(Icon::named(CustomIconName::GitPullRequest).color(muted)),
.icon(Icon::named(IconRole::GitPullRequest).color(muted)),
SegmentedOption::new(
PullRequestFilter::Closed,
format!("Closed ({})", counts.closed),
)
.icon(Icon::named(CustomIconName::GitPullRequestClosed).color(muted)),
.icon(Icon::named(IconRole::GitPullRequestClosed).color(muted)),
SegmentedOption::new(
PullRequestFilter::Draft,
format!("Draft ({})", counts.draft),
)
.icon(Icon::named(CustomIconName::GitPullRequestDraft).color(muted)),
.icon(Icon::named(IconRole::GitPullRequestDraft).color(muted)),
SegmentedOption::new(
PullRequestFilter::Merged,
format!("Merged ({})", counts.applied),
)
.icon(Icon::named(CustomIconName::GitPullRequestMerged).color(muted)),
.icon(Icon::named(IconRole::GitPullRequestMerged).color(muted)),
])
.on_change(move |filter, _, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
@@ -250,7 +249,7 @@ impl PullRequestsView {
.child(
DropdownMenu::new("new-pr-actions")
.label("New")
.icon(Icon::named(CustomIconName::GitPullRequest))
.icon(Icon::named(IconRole::GitPullRequest))
.open(self.new_pr_menu_open)
.on_click(move |_, window, cx| {
if let Err(error) =
+14 -15
View File
@@ -1,24 +1,23 @@
use std::path::PathBuf;
use assets::CustomIconName;
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, uniform_list,
};
use gpui_native_kit::button::Button;
use gpui_native_kit::combobox::{Combobox, ComboboxState};
use gpui_native_kit::common::{h_flex, v_flex};
use gpui_native_kit::data::tabs::{Tab, Tabs};
use gpui_native_kit::icons::{Icon, IconRole};
use gpui_native_kit::input::{Input, InputState};
use gpui_native_kit::layout::panel::Panel;
use gpui_native_kit::menu::Menu;
use gpui_native_kit::scrollbar::Scrollbar;
use gpui_native_kit::spinner::Spinner;
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use signed_state::{CheckoutsStore, RepoStore};
use ui::button::Button;
use ui::combobox::{Combobox, ComboboxState};
use ui::common::{h_flex, v_flex};
use ui::data::tabs::{Tab, Tabs};
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
use ui::layout::panel::Panel;
use ui::menu::Menu;
use ui::scrollbar::Scrollbar;
use ui::spinner::Spinner;
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use super::helpers::{ForkCompare, fork_display_name, truncate_label};
use crate::repo::commit_diff::{CommitDiffView, DiffPane};
@@ -307,7 +306,7 @@ impl NewPullRequestView {
.trigger(move |_, _| {
Button::new("compare-source")
.label(source_label.clone())
.variant(gpui_native_kit::button::ButtonVariant::Secondary)
.variant(ui::button::ButtonVariant::Secondary)
.into_any_element()
})
.items(move |_, _| {
@@ -357,9 +356,9 @@ impl NewPullRequestView {
.tabs(move |_, _| {
vec![
Tab::new("files", format!("Files ({files})"))
.lead(Icon::named(CustomIconName::GitFile)),
.lead(Icon::named(IconRole::GitFile)),
Tab::new("commits", format!("Commits ({commits})"))
.lead(Icon::named(CustomIconName::GitCommit)),
.lead(Icon::named(IconRole::GitCommit)),
]
})
.on_change(move |index, _, cx| {
@@ -1,16 +1,15 @@
use assets::CustomIconName;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render,
SharedString, Styled as _, WeakEntity, Window, div,
};
use gpui_native_kit::button::Button;
use gpui_native_kit::common::{h_flex, v_flex};
use gpui_native_kit::icons::Icon;
use gpui_native_kit::input::{Input, InputState};
use gpui_native_kit::layout::panel::Panel;
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use signed_state::RepoStore;
use ui::button::Button;
use ui::common::{h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
use ui::layout::panel::Panel;
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use crate::workspace::Workspace;
@@ -110,7 +109,7 @@ impl SendPatchView {
.child(
Button::new("send-patch")
.label("Send patch")
.icon(Icon::named(CustomIconName::ArrowUp))
.icon(Icon::named(IconRole::ArrowUp))
.loading(self.submitting)
.disabled(!can_submit)
.on_click(move |_, _, cx| {
+10 -10
View File
@@ -7,17 +7,17 @@ use gpui::{
Render, ScrollStrategy, SharedString, Styled as _, Task, UniformListScrollHandle, Window, div,
px, uniform_list,
};
use gpui_native_kit::badge::{Badge, BadgeVariant};
use gpui_native_kit::clipboard::ClipboardButton;
use gpui_native_kit::common::{h_flex, v_flex};
use gpui_native_kit::data::tree::{Tree, TreeItem};
use gpui_native_kit::icons::{Icon, IconRole};
use gpui_native_kit::layout::panel::Panel;
use gpui_native_kit::layout::resizable::{Resizable, ResizableState};
use gpui_native_kit::scrollbar::Scrollbar;
use gpui_native_kit::spinner::Spinner;
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use signed_git::{CommitDiff, DiffStatus, FileCommit, FileDiff, Repo};
use ui::badge::{Badge, BadgeVariant};
use ui::clipboard::ClipboardButton;
use ui::common::{h_flex, v_flex};
use ui::data::tree::{Tree, TreeItem};
use ui::icons::{Icon, IconRole};
use ui::layout::panel::Panel;
use ui::layout::resizable::{Resizable, ResizableState};
use ui::scrollbar::Scrollbar;
use ui::spinner::Spinner;
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use utils::relative_time_secs;
use super::helpers::{DiffRow, diff_rows, render_diff_row};
+5 -5
View File
@@ -2,14 +2,14 @@ use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
SharedString, Styled as _, Window, div, px,
};
use gpui_native_kit::avatar::Avatar;
use gpui_native_kit::clipboard::ClipboardButton;
use gpui_native_kit::common::{Sizable as _, h_flex, v_flex};
use gpui_native_kit::dialog::Dialog;
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use metadata::ProfileDirectory;
use nostr::prelude::PublicKey;
use signed_core::Announcement;
use ui::avatar::Avatar;
use ui::clipboard::ClipboardButton;
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::dialog::Dialog;
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use utils::middle_truncate;
use crate::shared::dialogs::{close_global, open_global};
+8 -8
View File
@@ -5,16 +5,16 @@ use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _,
PathPromptOptions, Render, Styled as _, WeakEntity, Window, div, px,
};
use gpui_native_kit::button::{Button, ButtonVariant};
use gpui_native_kit::common::{h_flex, v_flex};
use gpui_native_kit::dialog::Dialog;
use gpui_native_kit::field::Field;
use gpui_native_kit::icons::{Icon, IconRole};
use gpui_native_kit::input::{Input, InputState};
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use gpui_native_kit::tooltip::Tooltip;
use settings::SettingsStore;
use signed_state::{Backend, CheckoutsStore};
use ui::button::{Button, ButtonVariant};
use ui::common::{h_flex, v_flex};
use ui::dialog::Dialog;
use ui::field::Field;
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use ui::tooltip::Tooltip;
use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers};
use crate::repo::actions::open_repo_panel;
@@ -3,16 +3,16 @@ use gpui::{
AnyElement, App, AppContext as _, Entity, IntoElement, ParentElement as _, SharedString,
Styled as _, Window, div,
};
use gpui_native_kit::button::{Button, ButtonVariant};
use gpui_native_kit::common::{h_flex, v_flex};
use gpui_native_kit::icons::{Icon, IconRole};
use gpui_native_kit::input::{Input, InputState};
use gpui_native_kit::switch::Switch;
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use gpui_native_kit::tooltip::Tooltip;
use nostr::prelude::RelayUrl;
use settings::{DEFAULT_GRASP_SERVERS, GraspServersSettings};
use signed_state::Backend;
use ui::button::{Button, ButtonVariant};
use ui::common::{h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
use ui::switch::Switch;
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use ui::tooltip::Tooltip;
/// State of the grasp-server section of a publish dialog, so async results can be rendered.
#[derive(Default)]
+8 -8
View File
@@ -5,18 +5,18 @@ use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
SharedString, Styled as _, WeakEntity, Window, div, px,
};
use gpui_native_kit::button::Button;
use gpui_native_kit::common::v_flex;
use gpui_native_kit::dialog::Dialog;
use gpui_native_kit::field::Field;
use gpui_native_kit::icons::{Icon, IconRole};
use gpui_native_kit::input::{Input, InputState};
use gpui_native_kit::select::{Select, SelectOption};
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use settings::SettingsStore;
use signed_core::RepoAddr;
use signed_git::Repo;
use signed_state::Backend;
use ui::button::Button;
use ui::common::v_flex;
use ui::dialog::Dialog;
use ui::field::Field;
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
use ui::select::{Select, SelectOption};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers};
use crate::repo::RepoDetailView;
+4 -4
View File
@@ -2,11 +2,11 @@ use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
Styled as _, Window, div, px,
};
use gpui_native_kit::button::{Button, ButtonVariant};
use gpui_native_kit::common::v_flex;
use gpui_native_kit::dialog::Dialog;
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use signed_state::RepoStore;
use ui::button::{Button, ButtonVariant};
use ui::common::v_flex;
use ui::dialog::Dialog;
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use crate::shared::dialogs::{close_global, open_global};
+6 -6
View File
@@ -7,13 +7,13 @@ use gpui::{
AnyElement, App, AppContext as _, Context, Entity, EventEmitter, IntoElement,
ParentElement as _, SharedString, Styled as _, Task, WeakEntity, Window, div, px,
};
use gpui_native_kit::common::{h_flex, v_flex};
use gpui_native_kit::data::tree::{Tree, TreeItem};
use gpui_native_kit::editor::code::CodeViewState;
use gpui_native_kit::editor::markdown::MarkdownViewState;
use gpui_native_kit::icons::{Icon, IconRole};
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use signed_git::{FileCommit, Repo, WorktreeSnapshot};
use ui::common::{h_flex, v_flex};
use ui::data::tree::{Tree, TreeItem};
use ui::editor::code::CodeViewState;
use ui::editor::markdown::MarkdownViewState;
use ui::icons::{Icon, IconRole};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use super::helpers::{code_language, is_markdown_path, preview_spinner, source_hash};
use crate::shared::tree::{TreeItemSeed, TreeRow, collect_expanded, flatten};
+16 -20
View File
@@ -1,23 +1,22 @@
use std::collections::HashSet;
use assets::CustomIconName;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, InteractiveElement as _, IntoElement,
ParentElement as _, SharedString, StatefulInteractiveElement as _, Styled as _, Window, div,
px,
};
use gpui_native_kit::avatar::Avatar;
use gpui_native_kit::button::{Button, ButtonVariant};
use gpui_native_kit::clipboard::ClipboardButton;
use gpui_native_kit::common::{Sizable, h_flex, v_flex};
use gpui_native_kit::dropdown_menu::DropdownMenu;
use gpui_native_kit::icons::{Icon, IconRole};
use gpui_native_kit::menu::MenuItem;
use gpui_native_kit::popover::Popover;
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use gpui_native_kit::tooltip::Tooltip;
use signed_state::{Backend, CheckoutStatus, CheckoutSyncStatus, CheckoutsStore, Nip34Kind};
use ui::avatar::Avatar;
use ui::button::{Button, ButtonVariant};
use ui::clipboard::ClipboardButton;
use ui::common::{Sizable, 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 _, TextRole, Typeset 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};
@@ -197,7 +196,7 @@ impl RepoDetailView {
.trigger(move |_, _| {
Button::new("code")
.label("Code")
.icon(Icon::named(CustomIconName::GitClone))
.icon(Icon::named(IconRole::GitClone))
.tooltip(Tooltip::text("Clone repository"))
.loading(cloning)
.disabled(cloning)
@@ -250,7 +249,7 @@ impl RepoDetailView {
.child(
h_flex().justify_end().child(
Button::new("download")
.icon(Icon::named(CustomIconName::GitClone))
.icon(Icon::named(IconRole::GitClone))
.label("Download")
.on_click({
let weak = weak_download.clone();
@@ -271,7 +270,7 @@ impl RepoDetailView {
)
.child(
DropdownMenu::new("repo-menu")
.icon(CustomIconName::EllipsisVertical)
.icon(IconRole::EllipsisVertical)
.variant(ButtonVariant::Ghost)
.disabled(pushing)
.open(self.repo_menu_open)
@@ -374,7 +373,7 @@ impl RepoDetailView {
Some(binding) => this.child(bound_repo_label(binding, &self.directory, cx)),
None => this.child(
Button::new("init")
.icon(Icon::named(CustomIconName::ArrowUp))
.icon(Icon::named(IconRole::ArrowUp))
.label("Initialize on Nostr")
.tooltip(Tooltip::text("Publish this repository to Nostr"))
.on_click(cx.listener(|this, _, window, cx| {
@@ -438,7 +437,7 @@ impl RepoDetailView {
};
let path = status.path.clone();
(
Icon::named(CustomIconName::ArrowUp),
Icon::named(IconRole::ArrowUp),
SharedString::from(format!("{commits} ready to push")),
format!("Push {}", status.branch),
path,
@@ -533,10 +532,7 @@ impl RepoDetailView {
history.open_commit_diff(&commit_id, window, cx);
});
})
.child(
Icon::named(CustomIconName::GitCommit)
.color(cx.theme().colors.muted_foreground),
)
.child(Icon::named(IconRole::GitCommit).color(cx.theme().colors.muted_foreground))
.child(
div()
.font_family(cx.theme().mono_font)
+10 -13
View File
@@ -1,23 +1,22 @@
use std::path::{Path, PathBuf};
use anyhow::Error;
use assets::CustomIconName;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _,
SharedString, StatefulInteractiveElement as _, Styled as _, Window, div, px,
};
use gpui_native_kit::avatar::Avatar;
use gpui_native_kit::clipboard::ClipboardButton;
use gpui_native_kit::combobox::ComboboxState;
use gpui_native_kit::common::{Sizable as _, h_flex, v_flex};
use gpui_native_kit::icons::Icon;
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use metadata::ProfileDirectory;
use nostr::prelude::{RelayUrl, ToBech32};
use signed_core::Announcement;
use signed_git::{DiffHunk, DiffLine, DiffLineKind, FileCommit, FileDiff, Repo};
use signed_state::{Nip34Binding, RepoListStore, RepoStore};
use ui::avatar::Avatar;
use ui::clipboard::ClipboardButton;
use ui::combobox::ComboboxState;
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use utils::relative_time_secs;
use super::RepoDetailView;
@@ -117,7 +116,7 @@ pub(super) fn fork_row(
.min_w_0()
.typeset(TextRole::Body, cx)
.text_color(cx.theme().colors.muted_foreground)
.child(Icon::named(CustomIconName::GitBranch).small())
.child(Icon::named(IconRole::GitBranch).small())
.child(div().whitespace_nowrap().text_ellipsis().child(label));
Some(if clickable {
@@ -230,15 +229,13 @@ pub(super) fn preview_spinner() -> AnyElement {
.size_full()
.items_center()
.justify_center()
.child(gpui_native_kit::spinner::Spinner::new(
"repo-preview-spinner",
))
.child(ui::spinner::Spinner::new("repo-preview-spinner"))
.into_any_element()
}
/// The kit grammar for a path; only four languages are supported.
pub(super) fn code_language(path: &str) -> gpui_native_kit::editor::highlight::Language {
use gpui_native_kit::editor::highlight::Language;
pub(super) fn code_language(path: &str) -> ui::editor::highlight::Language {
use ui::editor::highlight::Language;
match Path::new(path)
.extension()
.and_then(|ext| ext.to_str())
+4 -4
View File
@@ -6,12 +6,12 @@ use gpui::{
AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, SharedString,
Styled as _, Task, UniformListScrollHandle, WeakEntity, Window, div, uniform_list,
};
use gpui_native_kit::common::v_flex;
use gpui_native_kit::scrollbar::Scrollbar;
use gpui_native_kit::spinner::Spinner;
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use signed_git::{CommitList, Repo};
use signed_state::RepoStore;
use ui::common::v_flex;
use ui::scrollbar::Scrollbar;
use ui::spinner::Spinner;
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use super::commit_diff::CommitDiffView;
use super::helpers::commit_row;
+10 -11
View File
@@ -2,20 +2,12 @@ use std::collections::HashSet;
use std::path::PathBuf;
use anyhow::Error;
use assets::CustomIconName;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement,
ParentElement as _, PathPromptOptions, Render, SharedString, Styled as _, Subscription, Task,
WeakEntity, Window, div,
};
use gpui_native_kit::alert::{Alert, AlertSeverity};
use gpui_native_kit::common::{h_flex, v_flex};
use gpui_native_kit::data::sidebar::{Sidebar, SidebarEntry};
use gpui_native_kit::icons::Icon;
use gpui_native_kit::layout::panel::Panel;
use gpui_native_kit::spinner::Spinner;
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use metadata::ProfileDirectory;
use nostr::prelude::{PublicKey, Url};
use signed_core::{Announcement, RepoAddr};
@@ -23,6 +15,13 @@ use signed_git::{FileCommit, GitCache, Repo};
use signed_state::{
Backend, CheckoutsStore, LocalReposStore, Mirrors, Nip34Binding, RepoStore, SyncStatusDirectory,
};
use ui::alert::{Alert, AlertSeverity};
use ui::common::{h_flex, v_flex};
use ui::data::sidebar::{Sidebar, SidebarEntry};
use ui::icons::{Icon, IconRole};
use ui::layout::panel::Panel;
use ui::spinner::Spinner;
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
pub mod actions;
pub mod commit_diff;
@@ -885,19 +884,19 @@ impl RepoDetailView {
.entries(move |_, cx| {
let mut entries = vec![
SidebarEntry::row("repo-nav-commits", "Commits")
.prefix(Icon::named(CustomIconName::GitCommit))
.prefix(Icon::named(IconRole::GitCommit))
.when_some(commit_count, |entry, count| entry.suffix(count.to_string())),
];
if include_issues {
entries.push(
SidebarEntry::row("repo-nav-issues", "Issues")
.prefix(Icon::named(CustomIconName::GitIssueDone))
.prefix(Icon::named(IconRole::GitIssueDone))
.when_some(issue_count, |entry, count| entry.suffix(count.to_string())),
);
entries.push(
SidebarEntry::row("repo-nav-pulls", "Pull requests")
.prefix(Icon::named(CustomIconName::GitPullRequest))
.prefix(Icon::named(IconRole::GitPullRequest))
.when_some(pull_count, |entry, count| entry.suffix(count.to_string())),
);
}
+1 -1
View File
@@ -1,5 +1,5 @@
use gpui::{App, AppContext as _, Entity, SharedString, WeakEntity, Window};
use gpui_native_kit::combobox::{Combobox, ComboboxState};
use ui::combobox::{Combobox, ComboboxState};
use super::RepoDetailView;
use super::helpers::sync_selector;
+11 -11
View File
@@ -4,14 +4,14 @@ use gpui::{
AnyElement, App, AppContext as _, Entity, IntoElement, ParentElement as _, PathPromptOptions,
SharedString, Styled as _, Window, div, px,
};
use gpui_native_kit::button::Button;
use gpui_native_kit::common::{h_flex, v_flex};
use gpui_native_kit::icons::{Icon, IconRole};
use gpui_native_kit::input::{Input, InputState};
use gpui_native_kit::select::{Select, SelectOption};
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use gpui_native_kit::tooltip::Tooltip;
use settings::{AppearanceMode, EventFetchingStrategy, SettingsStore};
use ui::button::Button;
use ui::common::{h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
use ui::select::{Select, SelectOption};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use ui::tooltip::Tooltip;
use crate::repo::dialogs::grasp_servers::{normalize_server, server_host};
@@ -134,7 +134,7 @@ pub fn grasp_servers_editor(input: &Entity<InputState>, cx: &App) -> AnyElement
.child(
Button::new(format!("settings-remove-server:{ix}"))
.icon(Icon::named(IconRole::Close))
.variant(gpui_native_kit::button::ButtonVariant::Ghost)
.variant(ui::button::ButtonVariant::Ghost)
.tooltip(Tooltip::text("Remove"))
.on_click({
let store = store.clone();
@@ -163,7 +163,7 @@ pub fn grasp_servers_editor(input: &Entity<InputState>, cx: &App) -> AnyElement
.child(
Button::new("settings-add-server")
.icon(Icon::named(IconRole::Plus))
.variant(gpui_native_kit::button::ButtonVariant::Ghost)
.variant(ui::button::ButtonVariant::Ghost)
.tooltip(Tooltip::text("Add grasp server"))
.on_click({
let input = input.clone();
@@ -234,7 +234,7 @@ pub fn scan_paths_editor(cx: &App) -> AnyElement {
.child(
Button::new(format!("settings-remove-path:{ix}"))
.icon(Icon::named(IconRole::Close))
.variant(gpui_native_kit::button::ButtonVariant::Ghost)
.variant(ui::button::ButtonVariant::Ghost)
.tooltip(Tooltip::text("Remove"))
.on_click(move |_, _, cx| {
store.update(cx, |store, cx| {
@@ -307,7 +307,7 @@ pub fn default_folder_selector(default_folder: &Entity<InputState>) -> AnyElemen
.child(
Button::new("settings-choose-folder")
.icon(Icon::named(IconRole::Folder))
.variant(gpui_native_kit::button::ButtonVariant::Ghost)
.variant(ui::button::ButtonVariant::Ghost)
.tooltip(Tooltip::text("Choose folder"))
.on_click(move |_, window, cx| {
choose_default_folder(&folder, window, cx);
+4 -4
View File
@@ -4,15 +4,15 @@ use gpui::{
App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _,
Window, px,
};
use gpui_native_kit::common::v_flex;
use gpui_native_kit::dialog::Dialog;
use gpui_native_kit::input::InputState;
use gpui_native_kit::separator::Separator;
use helpers::{
appearance_select, default_folder_selector, event_fetching_select, grasp_servers_editor,
scan_paths_editor, setting_block, setting_row,
};
use settings::SettingsStore;
use ui::common::v_flex;
use ui::dialog::Dialog;
use ui::input::InputState;
use ui::separator::Separator;
use crate::shared::dialogs::open_global;
+1 -1
View File
@@ -1,7 +1,7 @@
use std::sync::Arc;
use gpui::{App, Entity, SharedString, WeakEntity, Window};
use gpui_native_kit::layout::panel::{Panel, PanelView};
use ui::layout::panel::{Panel, PanelView};
use crate::workspace::Workspace;
+4 -4
View File
@@ -2,12 +2,12 @@ use gpui::{
AnyElement, App, Context, IntoElement as _, ParentElement as _, SharedString, Styled as _,
Subscription, div,
};
use gpui_native_kit::common::{h_flex, v_flex};
use gpui_native_kit::icons::{Icon, IconRole};
use gpui_native_kit::spinner::Spinner;
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use signed_core::RepoAddr;
use signed_state::{Backend, BackendEvent, PushStepStatus};
use ui::common::{h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::spinner::Spinner;
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
/// Progress of an async dialog action: a busy flag that disables the form and an error shown below it.
#[derive(Debug, Default)]
+10 -23
View File
@@ -1,31 +1,18 @@
use assets::CustomIconName;
use gpui::{AnyElement, App, IntoElement, ParentElement as _, SharedString, Styled as _, div};
use gpui_native_kit::badge::{Badge, BadgeVariant};
use gpui_native_kit::empty_state::EmptyState;
use gpui_native_kit::icons::Icon;
use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _};
use gpui_native_kit::tooltip::Tooltip;
use signed_core::RepoStatus;
use ui::badge::{Badge, BadgeVariant};
use ui::empty_state::EmptyState;
use ui::icons::{Icon, IconRole};
use ui::theme::{ActiveTheme as _, TextRole, Typeset as _};
use ui::tooltip::Tooltip;
/// The status pill shown on issue and pull-request rows.
pub fn status_badge(status: RepoStatus) -> Badge {
let (label, variant, icon) = match status {
RepoStatus::Open => ("Open", BadgeVariant::Neutral, CustomIconName::GitIssueOpen),
RepoStatus::Closed => (
"Closed",
BadgeVariant::Danger,
CustomIconName::GitIssueClosed,
),
RepoStatus::Draft => (
"Draft",
BadgeVariant::Warning,
CustomIconName::GitIssueOngoing,
),
RepoStatus::Applied => (
"Applied",
BadgeVariant::Success,
CustomIconName::GitIssueDone,
),
RepoStatus::Open => ("Open", BadgeVariant::Neutral, IconRole::GitIssueOpen),
RepoStatus::Closed => ("Closed", BadgeVariant::Danger, IconRole::GitIssueClosed),
RepoStatus::Draft => ("Draft", BadgeVariant::Warning, IconRole::GitIssueOngoing),
RepoStatus::Applied => ("Applied", BadgeVariant::Success, IconRole::GitIssueDone),
};
Badge::new(format!("status-{label}"), label)
@@ -37,7 +24,7 @@ pub fn status_badge(status: RepoStatus) -> Badge {
/// A centered empty-state message filling the available space.
pub fn empty_state(message: impl Into<SharedString>) -> AnyElement {
let message = message.into();
gpui_native_kit::common::v_flex()
ui::common::v_flex()
.size_full()
.items_center()
.justify_center()
+2 -2
View File
@@ -1,7 +1,7 @@
use gpui::{AnyElement, App, IntoElement};
use gpui_native_kit::avatar::Avatar;
use gpui_native_kit::common::Sizable as _;
use signed_state::ResolvedLocalRepo;
use ui::avatar::Avatar;
use ui::common::Sizable as _;
/// The bound owner's avatar, falling back to the path's pixel avatar when unowned.
pub(super) fn local_avatar(
+9 -9
View File
@@ -4,20 +4,20 @@ use gpui::{
AnyElement, App, AppContext as _, Context, IntoElement, ParentElement as _, SharedString,
Styled as _, Subscription, WeakEntity, Window, px,
};
use gpui_native_kit::avatar::Avatar;
use gpui_native_kit::button::{Button, ButtonVariant};
use gpui_native_kit::command_palette::{Command, CommandPalette, CommandPaletteState};
use gpui_native_kit::common::{Sizable as _, h_flex};
use gpui_native_kit::data::tabs::{Tab, Tabs, TabsVariant};
use gpui_native_kit::icons::{Icon, IconRole};
use gpui_native_kit::menu::{Menu, MenuItem};
use gpui_native_kit::theme::ActiveTheme as _;
use gpui_native_kit::tooltip::Tooltip;
use helpers::local_avatar;
use metadata::{Profile, ProfileDirectory};
use nostr::prelude::PublicKey;
use signed_core::Announcement;
use signed_state::{Backend, BackendEvent, LocalReposStore, RepoListStore, ResolvedLocalRepo};
use ui::avatar::Avatar;
use ui::button::{Button, ButtonVariant};
use ui::command_palette::{Command, CommandPalette, CommandPaletteState};
use ui::common::{Sizable as _, h_flex};
use ui::data::tabs::{Tab, Tabs, TabsVariant};
use ui::icons::{Icon, IconRole};
use ui::menu::{Menu, MenuItem};
use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip;
use crate::repo::{RepoDetailView, actions, dialogs};
use crate::shared::{log_dropped, panels};
+3 -3
View File
@@ -4,9 +4,9 @@ use std::sync::Arc;
use gpui::{
Context, IntoElement, ParentElement as _, Render, SharedString, Styled as _, Window, div,
};
use gpui_native_kit::common::v_flex;
use gpui_native_kit::data::tabs::{Tab, Tabs, TabsVariant};
use gpui_native_kit::layout::panel::{Panel, PanelView};
use ui::common::v_flex;
use ui::data::tabs::{Tab, Tabs, TabsVariant};
use ui::layout::panel::{Panel, PanelView};
use crate::shared::log_dropped;
+71
View File
@@ -0,0 +1,71 @@
[package]
name = "ui"
description = "Signed's native GPUI theme, icons, and components."
version.workspace = true
edition.workspace = true
publish.workspace = true
[dependencies]
gpui.workspace = true
anyhow.workspace = true
log.workspace = true
serde.workspace = true
rust-embed.workspace = true
flume.workspace = true
unicode-segmentation = "1.12"
image = { version = "0.25.1", default-features = false }
similar = "2"
pulldown-cmark = { version = "0.13", default-features = false }
tree-sitter-rust = "0.24"
tree-sitter-typescript = "0.23"
tree-sitter-javascript = "0.23"
tree-sitter-python = "0.23"
toml = "0.8"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
cpal = "0.18"
tree-sitter = "0.25"
[target.'cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))'.dependencies]
async-channel = "2"
[target.'cfg(target_os = "linux")'.dependencies]
notify = "8"
zbus = "5"
[target.'cfg(target_os = "windows")'.dependencies]
windows = { version = "0.62", features = [
"Foundation",
"UI",
"UI_ViewManagement",
"Win32_Foundation",
"Win32_System_Com",
] }
windows-registry = "0.6"
[target.'cfg(target_os = "macos")'.dependencies]
block2 = "0.6"
objc2 = "0.6"
objc2-app-kit = { version = "0.3.2", default-features = false, features = [
"NSAccessibility",
"NSAppearance",
"NSColor",
"NSColorSpace",
"NSWorkspace",
"block2",
"objc2-core-foundation",
] }
objc2-foundation = { version = "=0.3.2", default-features = false, features = [
"NSDictionary",
"NSDistributedNotificationCenter",
"NSNotification",
"NSKeyValueObserving",
"NSOperation",
"NSUserDefaults",
"NSString",
"block2",
"std",
] }
[dev-dependencies]
gpui = { workspace = true, features = ["test-support"] }
+407
View File
@@ -0,0 +1,407 @@
use std::rc::Rc;
use crate::icons::{Icon, IconRole};
use crate::theme::{
ALERT_EDGE_WIDTH, ALERT_STACK_WIDTH, ActiveTheme as _, ENTER_SLIDE_DISTANCE, Size, TextRole,
Typeset as _,
};
use crate::utils::ResultLogErr as _;
use gpui::prelude::FluentBuilder as _;
use gpui::{
Animation, AnimationExt as _, App, Context, ElementId, Entity, InteractiveElement as _,
IntoElement, ParentElement as _, RenderOnce, Role, SharedString,
StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, deferred, div,
ease_out_quint,
};
use crate::components::button::{Button, ButtonVariant};
use crate::components::common::DismissHandler;
use crate::components::common::Sizable as _;
use crate::components::common::StyledExt as _;
use crate::components::common::TOAST_LAYER;
use crate::components::common::v_flex;
/// How alarming an [`Alert`] is; picks the accent color.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum AlertSeverity {
/// The default; uses the info role.
#[default]
Info,
/// Uses the success role.
Success,
/// Uses the warning role.
Warning,
/// Uses the destructive role.
Danger,
}
/// How an [`Alert`] presents.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum AlertStyle {
/// A floating banner styled like a popover; the default.
#[default]
Overlay,
/// A tinted callout embedded in the page.
Inline,
}
/// A static callout banner.
#[derive(Clone, IntoElement)]
#[must_use]
pub struct Alert {
id: ElementId,
title: Option<SharedString>,
message: Option<SharedString>,
severity: AlertSeverity,
presentation: AlertStyle,
icon: Option<Icon>,
on_dismiss: Option<DismissHandler>,
style: StyleRefinement,
}
impl Alert {
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
title: None,
message: None,
severity: AlertSeverity::Info,
presentation: AlertStyle::default(),
icon: None,
on_dismiss: None,
style: StyleRefinement::default(),
}
}
/// Sets the primary line.
pub fn title<L>(mut self, title: L) -> Self
where
L: Into<SharedString>,
{
self.title = Some(title.into());
self
}
/// Sets a secondary line under the title.
pub fn message<L>(mut self, message: L) -> Self
where
L: Into<SharedString>,
{
self.message = Some(message.into());
self
}
/// Sets how alarming the alert is.
pub fn severity(mut self, severity: AlertSeverity) -> Self {
self.severity = severity;
self
}
/// Sets how the alert presents.
pub fn style(mut self, style: AlertStyle) -> Self {
self.presentation = style;
self
}
/// Shows an icon before the text.
pub fn icon<I>(mut self, icon: I) -> Self
where
I: Into<Icon>,
{
self.icon = Some(icon.into());
self
}
/// Runs when the user dismisses the alert.
pub fn on_dismiss<F>(mut self, handler: F) -> Self
where
F: Fn(&mut App) + 'static,
{
self.on_dismiss = Some(Rc::new(handler));
self
}
fn rekey(mut self, id: usize) -> Self {
self.id = ElementId::from(id);
self
}
}
impl gpui::Styled for Alert {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for Alert {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let ramp = match self.severity {
AlertSeverity::Info => theme.ramps.info,
AlertSeverity::Success => theme.ramps.success,
AlertSeverity::Warning => theme.ramps.warning,
AlertSeverity::Danger => theme.ramps.destructive,
};
let foreground = theme.colors.foreground;
let muted_foreground = theme.colors.muted_foreground;
let metrics = theme.sizes.resolve(Size::Medium);
let icon_size = metrics.icon_size;
let dense_icon_size = metrics.dense_icon_size;
let content = v_flex()
.flex_1()
.gap_0p5()
.when_some(self.title.clone(), |alert, title| {
alert.child(
div()
.typeset(TextRole::Headline, cx)
.text_color(foreground)
.child(title),
)
})
.when_some(self.message.clone(), |alert, message| {
let color = if self.title.is_some() {
muted_foreground
} else {
foreground
};
alert.child(
div()
.text_size(metrics.text_size)
.text_color(color)
.child(message),
)
});
let dismiss = self.on_dismiss.clone().map(|on_dismiss| {
Button::new((self.id.clone(), "alert-close"))
.icon(IconRole::Close)
.variant(ButtonVariant::Ghost)
.xsmall()
.accessibility_label("Dismiss")
.on_click(move |_, _window, cx| on_dismiss(cx))
});
match self.presentation {
AlertStyle::Overlay => {
let surface = theme.colors.surface;
let border = theme.colors.border;
div()
.id(self.id.clone())
.role(Role::Alert)
.w_full()
.flex()
.items_start()
.gap_2()
.px_3()
.py_2()
.rounded(theme.radius.overlay)
.bg(surface)
.border_1()
.border_color(border)
.shadow(theme.elevations.popover.shadows())
.refine_style(&self.style)
.when_some(self.icon.clone(), |alert, icon_glyph| {
alert.child(
div()
.flex_none()
.flex()
.items_center()
.h(window.line_height())
.child(icon_glyph.size(icon_size).color(ramp.base)),
)
})
.child(content)
.when_some(dismiss, |alert, dismiss| alert.child(dismiss))
}
AlertStyle::Inline => div()
.id(self.id.clone())
.role(Role::Alert)
.w_full()
.flex()
.overflow_hidden()
.bg(ramp.subtle)
.refine_style(&self.style)
.child(
div()
.flex_none()
.w(ALERT_EDGE_WIDTH)
.self_stretch()
.bg(ramp.base),
)
.child(
div()
.flex_1()
.flex()
.items_start()
.gap_3()
.px_3()
.py_2()
.when_some(self.icon.clone(), |alert, icon_glyph| {
alert.child(
div()
.flex_none()
.flex()
.items_center()
.justify_center()
.size(theme.sizes.small.avatar_size)
.rounded(theme.radius.full)
.bg(ramp.base)
.child(icon_glyph.size(dense_icon_size).color(ramp.foreground)),
)
})
.child(content),
)
.when_some(dismiss, |alert, dismiss| {
alert.child(div().flex_none().self_center().pr_3().child(dismiss))
}),
}
}
}
/// One pushed alert, with its identity in the stack.
#[derive(Clone)]
pub struct AlertEntry {
pub id: usize,
pub alert: Alert,
on_dismiss: Option<DismissHandler>,
}
/// The stack of pushed alerts.
#[derive(Default)]
pub struct Alerts {
entries: Vec<AlertEntry>,
next_id: usize,
}
impl Alerts {
/// Pushes an alert onto the stack.
pub fn push(&mut self, mut alert: Alert, cx: &mut Context<Self>) -> usize {
let id = self.next_id;
self.next_id += 1;
let on_dismiss = alert.on_dismiss.take();
let stack = cx.entity().downgrade();
alert.on_dismiss = Some(Rc::new(move |cx: &mut App| {
stack
.update(cx, |alerts, cx| alerts.dismiss(id, cx))
.log_err();
}));
self.entries.push(AlertEntry {
id,
alert: alert.rekey(id),
on_dismiss,
});
cx.notify();
id
}
/// Dismisses one alert by id, running its dismiss handler.
pub fn dismiss(&mut self, id: usize, cx: &mut Context<Self>) {
if let Some(position) = self.entries.iter().position(|entry| entry.id == id) {
let entry = self.entries.remove(position);
cx.notify();
if let Some(on_dismiss) = &entry.on_dismiss {
(on_dismiss.clone())(cx);
}
}
}
/// Dismisses every alert, running each entry's `on_dismiss` handler.
pub fn clear(&mut self, cx: &mut Context<Self>) {
if self.entries.is_empty() {
return;
}
let entries = std::mem::take(&mut self.entries);
cx.notify();
for entry in entries {
if let Some(on_dismiss) = entry.on_dismiss {
on_dismiss(cx);
}
}
}
/// The stacked alerts, oldest first.
pub 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.
#[derive(IntoElement)]
#[must_use]
pub struct AlertsView {
alerts: Entity<Alerts>,
id: ElementId,
}
impl AlertsView {
/// Binds the view to an alert stack.
pub fn new<I>(id: I, alerts: Entity<Alerts>) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
alerts,
}
}
}
impl RenderOnce for AlertsView {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let enter_duration = theme.motion.overlay;
let entries = self.alerts.read(cx).entries();
deferred(
div()
.id(self.id)
.absolute()
.top_4()
.right_4()
.w(ALERT_STACK_WIDTH)
.flex()
.flex_col()
.items_end()
.gap_2()
.children(entries.iter().rev().map(|entry| {
let id = entry.id;
let ease_slide = ease_out_quint();
div()
.relative()
.w_full()
.debug_selector(|| "alert-entry".to_string())
.child(entry.alert.clone())
.with_animation(
("alert-enter", id),
Animation::new(enter_duration),
move |layer, delta| {
layer.left(ENTER_SLIDE_DISTANCE * (1. - ease_slide(delta)))
},
)
})),
)
.with_priority(TOAST_LAYER)
}
}
+331
View File
@@ -0,0 +1,331 @@
use std::fmt::Display;
use crate::theme::{
ActiveTheme as _, Oklch, PIXEL_AVATAR_DARK_FACTOR, PIXEL_AVATAR_DARK_FLOOR,
PIXEL_AVATAR_LIGHT_CAP, PIXEL_AVATAR_LIGHT_LIFT, PIXEL_AVATAR_TINT_ALPHA, Size, ThemeVariant,
};
use gpui::{
App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role,
SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, div,
};
use crate::components::common::{Sizable, StyledExt, h_flex};
/// Number of rows and columns in the pixel grid.
const GRID_SIZE: usize = 8;
/// Empty cells kept between the pattern and the avatar edge.
const MARGIN: usize = 1;
/// Probability that a cell in the left half of the pattern area is filled.
const FILL_PROBABILITY: f32 = 0.42;
/// Probability that a filled cell uses the shade instead of the main color.
const SHADE_PROBABILITY: f32 = 0.25;
/// Minimum number of filled left-half cells.
const MIN_FILLED: usize = 5;
/// An avatar for a user or other entity.
#[derive(IntoElement)]
#[must_use]
pub struct Avatar {
id: SharedString,
name: Option<SharedString>,
picture: Option<SharedString>,
size: Size,
fully_rounded: bool,
style: StyleRefinement,
}
impl Avatar {
/// Create an avatar for `id`, a public key or any other stable string.
///
/// The id seeds the pixel fallback shown when no picture is set.
pub fn new<T>(id: T) -> Self
where
T: Display,
{
Self {
id: id.to_string().into(),
name: None,
picture: None,
size: Size::default(),
fully_rounded: false,
style: StyleRefinement::default(),
}
}
/// The display name of the avatar's subject, if known.
pub fn name<N>(mut self, name: N) -> Self
where
N: Into<SharedString>,
{
self.name = Some(name.into());
self
}
/// The user's picture URL.
pub fn picture<P>(mut self, picture: Option<P>) -> Self
where
P: Into<SharedString>,
{
self.picture = picture.map(Into::into);
self
}
/// Renders the avatar circular instead of the control radius.
pub fn fully_rounded(mut self, fully_rounded: bool) -> Self {
self.fully_rounded = fully_rounded;
self
}
}
impl Sizable for Avatar {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl gpui::Styled for Avatar {
fn style(&mut self) -> &mut gpui::StyleRefinement {
&mut self.style
}
}
impl RenderOnce for Avatar {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
// Avatars sit one class below the shared control scale.
let size = match self.size {
Size::XSmall | Size::Small => Size::XSmall,
Size::Medium => Size::Small,
Size::Large => Size::Medium,
};
let side = theme.sizes.resolve(size).avatar_size;
let radius = if self.fully_rounded {
theme.radius.full
} else {
theme.radius.sm
};
let base = h_flex()
.id(ElementId::from(self.id.clone()))
.flex_none()
.justify_center()
.overflow_hidden()
.size(side)
.bg(theme.colors.secondary)
.rounded(radius)
.role(Role::Image)
.aria_label(self.name.clone().unwrap_or_else(|| self.id.clone()))
.refine_style(&self.style);
match self.picture {
Some(url) => base.child(gpui::img(url).size_full().rounded(radius)),
None => base.child(PixelAvatar {
seed: fnv1a(self.id.as_bytes()),
side,
radius,
fully_rounded: self.fully_rounded,
}),
}
.into_any_element()
}
}
/// A deterministic, offline pixel-art avatar.
#[derive(IntoElement)]
struct PixelAvatar {
seed: u64,
side: gpui::Pixels,
radius: gpui::Pixels,
fully_rounded: bool,
}
impl RenderOnce for PixelAvatar {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let pattern = pattern(self.seed);
let mut cells = Vec::new();
let hue = (self.seed as f32 / u64::MAX as f32) * 360.0;
let accent = Oklch::from_hsla(theme.colors.accent);
let main = Oklch { h: hue, ..accent }.to_hsla();
let shade = if theme.variant == ThemeVariant::Dark {
Oklch {
l: (accent.l * PIXEL_AVATAR_LIGHT_LIFT).min(PIXEL_AVATAR_LIGHT_CAP),
..Oklch::from_hsla(main)
}
.to_hsla()
} else {
Oklch {
l: (accent.l * PIXEL_AVATAR_DARK_FACTOR).max(PIXEL_AVATAR_DARK_FLOOR),
..Oklch::from_hsla(main)
}
.to_hsla()
};
let inset = if self.fully_rounded {
self.side / GRID_SIZE as f32
} else {
gpui::Pixels::ZERO
};
for row in 0..GRID_SIZE {
for col in 0..GRID_SIZE {
let value = pattern[row * GRID_SIZE + col];
if value != 0 {
let color = if value == 2 { shade } else { main };
cells.push(
div()
.row_start(row as i16 + 1)
.row_end(row as i16 + 2)
.col_start(col as i16 + 1)
.col_end(col as i16 + 2)
.bg(color),
);
}
}
}
div()
.grid()
.grid_cols(GRID_SIZE as u16)
.grid_rows(GRID_SIZE as u16)
.size(self.side)
.flex_none()
.p(inset)
.rounded(self.radius)
.bg(gpui::Hsla {
a: PIXEL_AVATAR_TINT_ALPHA,
..main
})
.children(cells)
}
}
fn pattern(seed: u64) -> [u8; GRID_SIZE * GRID_SIZE] {
let mut rng = PixelRng::new(seed);
let mut pattern = [0u8; GRID_SIZE * GRID_SIZE];
let mut filled = 0usize;
let art_rows = GRID_SIZE - 2 * MARGIN;
let art_columns = GRID_SIZE / 2 - MARGIN;
for row in MARGIN..GRID_SIZE - MARGIN {
for col in MARGIN..GRID_SIZE / 2 {
if rng.chance(FILL_PROBABILITY) {
let shade = rng.chance(SHADE_PROBABILITY);
set_cell(&mut pattern, row, col, if shade { 2 } else { 1 });
filled += 1;
}
}
}
if filled < MIN_FILLED {
let total = art_rows * art_columns;
let start = (rng.next() % total as u64) as usize;
for offset in 0..total {
if filled >= MIN_FILLED {
break;
}
let flat_index = (start + offset) % total;
let row = MARGIN + flat_index / art_columns;
let col = MARGIN + flat_index % art_columns;
if pattern[row * GRID_SIZE + col] == 0 {
set_cell(&mut pattern, row, col, 1);
filled += 1;
}
}
}
pattern
}
/// Fill `cell (row, col)` and its horizontal mirror.
fn set_cell(pattern: &mut [u8; GRID_SIZE * GRID_SIZE], row: usize, col: usize, value: u8) {
pattern[row * GRID_SIZE + col] = value;
pattern[row * GRID_SIZE + (GRID_SIZE - 1 - col)] = value;
}
/// FNV-1a 64-bit hash, stable across platforms and runs.
fn fnv1a(bytes: &[u8]) -> u64 {
let mut hash = 0xcbf2_9ce4_8422_2325u64;
for &byte in bytes {
hash ^= byte as u64;
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
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
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_pattern_is_mirror_symmetric() {
for seed in [0u64, 1, 42, u64::MAX] {
let pattern = pattern(seed);
for row in 0..GRID_SIZE {
for col in 0..GRID_SIZE / 2 {
assert_eq!(
pattern[row * GRID_SIZE + col],
pattern[row * GRID_SIZE + (GRID_SIZE - 1 - col)],
"seed {seed} row {row} col {col}"
);
}
}
}
}
#[test]
fn the_pattern_keeps_the_outer_ring_empty() {
for seed in [0u64, 1, 42, u64::MAX] {
let pattern = pattern(seed);
for col in 0..GRID_SIZE {
assert_eq!(pattern[col], 0, "top row, seed {seed}");
assert_eq!(pattern[(GRID_SIZE - 1) * GRID_SIZE + col], 0, "bottom row");
}
for row in 0..GRID_SIZE {
assert_eq!(pattern[row * GRID_SIZE], 0, "left column, seed {seed}");
assert_eq!(pattern[row * GRID_SIZE + GRID_SIZE - 1], 0, "right column");
}
}
}
#[test]
fn the_pattern_is_deterministic_and_fills_the_minimum() {
for seed in [0u64, 7, 42, u64::MAX] {
let first = pattern(seed);
assert_eq!(first, pattern(seed), "seed {seed} must be stable");
// Mirrored cells count twice, so both halves carry the minimum.
let filled = first.iter().filter(|cell| **cell != 0).count();
assert!(filled >= MIN_FILLED * 2, "seed {seed} filled {filled}");
}
}
}
+161
View File
@@ -0,0 +1,161 @@
use std::rc::Rc;
use crate::icons::Icon;
use crate::theme::{ActiveTheme as _, Size, Theme};
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyView, App, ElementId, Hsla, InteractiveElement as _, IntoElement, ParentElement as _,
RenderOnce, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _,
Window, transparent_black,
};
use crate::components::common::{StyledExt, h_flex};
/// The tooltip view builder gpui's `.tooltip(...)` expects.
type TooltipBuilder = Rc<dyn Fn(&mut Window, &mut App) -> AnyView>;
/// How loud a badge is.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BadgeVariant {
/// The default; quiet muted fill for counts.
#[default]
Neutral,
/// The accent ramp; something active or newly added.
Accent,
/// The success ramp.
Success,
/// The warning ramp.
Warning,
/// The destructive ramp.
Danger,
/// No fill, just a border; the quietest badge.
Outline,
}
impl BadgeVariant {
fn tokens(self, theme: &Theme) -> (Hsla, Hsla, Hsla) {
match self {
Self::Neutral => (
theme.colors.muted,
theme.colors.muted_foreground,
transparent_black(),
),
Self::Accent => (
theme.ramps.primary.base,
theme.colors.primary_foreground,
transparent_black(),
),
Self::Success => (
theme.ramps.success.base,
theme.colors.success_foreground,
transparent_black(),
),
Self::Warning => (
theme.ramps.warning.base,
theme.colors.warning_foreground,
transparent_black(),
),
Self::Danger => (
theme.ramps.destructive.base,
theme.colors.destructive_foreground,
transparent_black(),
),
Self::Outline => (
transparent_black(),
theme.colors.foreground,
theme.colors.border,
),
}
}
}
/// A small pill for a count or a state.
#[derive(IntoElement)]
#[must_use]
pub struct Badge {
id: ElementId,
label: SharedString,
icon: Option<Icon>,
variant: BadgeVariant,
tooltip: Option<TooltipBuilder>,
style: StyleRefinement,
}
impl Badge {
/// Creates a badge showing `label` — a count or state word the caller formats.
pub fn new<I, L>(id: I, label: L) -> Self
where
I: Into<ElementId>,
L: Into<SharedString>,
{
Self {
id: id.into(),
label: label.into(),
icon: None,
variant: BadgeVariant::default(),
tooltip: None,
style: StyleRefinement::default(),
}
}
/// Sets how loud the badge is.
pub fn variant(mut self, variant: BadgeVariant) -> Self {
self.variant = variant;
self
}
/// Shows an icon before the label.
pub fn icon<I>(mut self, icon: I) -> Self
where
I: Into<Icon>,
{
self.icon = Some(icon.into());
self
}
/// Shows a tooltip view next to the badge after it is hovered.
pub fn tooltip<F>(mut self, tooltip: F) -> Self
where
F: Fn(&mut Window, &mut App) -> AnyView + 'static,
{
self.tooltip = Some(Rc::new(tooltip));
self
}
}
impl gpui::Styled for Badge {
fn style(&mut self) -> &mut gpui::StyleRefinement {
&mut self.style
}
}
impl RenderOnce for Badge {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let metrics = theme.sizes.resolve(Size::Small);
let label_size = metrics.caption_size;
let (background, foreground, border) = self.variant.tokens(theme);
h_flex()
.id(self.id.clone())
.flex_none()
.justify_center()
.gap_1()
.rounded(theme.radius.full)
.border_1()
.border_color(border)
.bg(background)
.text_color(foreground)
.text_size(label_size)
.px(metrics.dense_padding_x)
.py_0p5()
.when_some(self.icon, |badge, icon| {
badge.child(icon.size(metrics.dense_icon_size).color(foreground))
})
.child(self.label)
.refine_style(&self.style)
.when_some(self.tooltip, |badge, tooltip| {
badge.tooltip(move |window, cx| tooltip(window, cx))
})
}
}
+342
View File
@@ -0,0 +1,342 @@
//! The push button: the API template for every control that follows.
use crate::icons::Icon;
use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size};
use crate::utils::{focus_ring, record_anchor_bounds};
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, AnyView, App, ClickEvent, ElementId, InteractiveElement as _, IntoElement,
ParentElement, RenderOnce, Role, SharedString, StatefulInteractiveElement as _,
StyleRefinement, Styled as _, Window, canvas, relative, transparent_black,
};
use std::rc::Rc;
use crate::components::common::{Sizable, StyledExt as _, h_flex};
use crate::components::spinner::Spinner;
/// The single activation handler, shared by pointer, Enter, and Space.
type ClickHandler = Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>;
/// The tooltip view builder gpui's `.tooltip(...)` expects.
type TooltipBuilder = Rc<dyn Fn(&mut Window, &mut App) -> AnyView>;
/// Which visual treatment a button uses.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ButtonVariant {
/// The platform's default action.
#[default]
Primary,
/// The everyday companion to `Primary`.
Secondary,
/// Unpainted until hovered, for toolbars and dense UI.
Ghost,
/// The destructive action.
Destructive,
}
/// Which edge the button's content aligns to.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ButtonSide {
/// Centered content.
#[default]
Center,
/// Content on the left edge, icon leading the label.
Left,
/// Content on the right edge, icon trailing the label.
Right,
}
/// A push button: pointer, Enter, and Space all fire the single `on_click`.
#[derive(IntoElement)]
#[must_use]
pub struct Button {
id: ElementId,
label: Option<SharedString>,
icon: Option<Icon>,
children: Vec<AnyElement>,
variant: ButtonVariant,
size: Size,
disabled: bool,
loading: bool,
padded: bool,
side: ButtonSide,
tab_stop: bool,
debug_selector: Option<Rc<dyn Fn() -> String>>,
a11y_label: Option<SharedString>,
tooltip: Option<TooltipBuilder>,
on_click: Option<ClickHandler>,
style: StyleRefinement,
}
impl Button {
/// Creates a primary button.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
label: None,
icon: None,
children: Vec::new(),
variant: ButtonVariant::default(),
size: Size::default(),
disabled: false,
loading: false,
padded: true,
side: ButtonSide::default(),
tab_stop: true,
debug_selector: None,
a11y_label: None,
tooltip: None,
on_click: None,
style: StyleRefinement::default(),
}
}
/// Sets the visible label.
pub fn label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.label = Some(label.into());
self
}
/// Shows an icon beside the label; without a label the button renders square.
pub fn icon<I>(mut self, icon: I) -> Self
where
I: Into<Icon>,
{
self.icon = Some(icon.into());
self
}
/// Shows a tooltip view next to the button after it is hovered.
pub fn tooltip<F>(mut self, tooltip: F) -> Self
where
F: Fn(&mut Window, &mut App) -> AnyView + 'static,
{
self.tooltip = Some(Rc::new(tooltip));
self
}
/// Sets the button's visual language.
pub fn variant(mut self, variant: ButtonVariant) -> Self {
self.variant = variant;
self
}
/// Whether the button is a keyboard tab stop, dense toolbars turn it off.
pub fn tab_stop(mut self, tab_stop: bool) -> Self {
self.tab_stop = tab_stop;
self
}
/// Sets the debug-bounds selector, for headless tests.
pub fn debug_selector<F>(mut self, selector: F) -> Self
where
F: Fn() -> String + 'static,
{
self.debug_selector = Some(Rc::new(selector));
self
}
/// Renders the button inert, unfocusable, and dimmed.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
/// Shows the spinner in place of the content and suppresses activation.
pub fn loading(mut self, loading: bool) -> Self {
self.loading = loading;
self
}
/// Whether the button pads its content. false removes all padding.
pub fn padded(mut self, padded: bool) -> Self {
self.padded = padded;
self
}
/// Sets the edge the content aligns to, `Right` renders the icon after the label.
pub fn side(mut self, side: ButtonSide) -> Self {
self.side = side;
self
}
/// Overrides the accessibility label, which defaults to the visible label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// The single activation handler, fired by pointer, Enter, and Space.
pub fn on_click<F>(mut self, handler: F) -> Self
where
F: Fn(&ClickEvent, &mut Window, &mut App) + 'static,
{
self.on_click = Some(Box::new(handler));
self
}
}
impl ParentElement for Button {
fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
self.children.extend(elements);
}
}
impl gpui::Styled for Button {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl Sizable for Button {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl RenderOnce for Button {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
let metrics = theme.sizes.resolve(self.size);
let on_click = self.on_click;
let a11y_label = self.a11y_label.or_else(|| self.label.clone());
let is_icon_only = self.icon.is_some() && self.label.is_none() && self.children.is_empty();
let icon_trailing = self.side == ButtonSide::Right;
let (background, foreground, hover, pressed) = match self.variant {
ButtonVariant::Primary => (
Some(ramps.primary.base),
colors.primary_foreground,
ramps.primary.hover,
ramps.primary.pressed,
),
ButtonVariant::Secondary => (
Some(colors.surface),
colors.foreground,
colors.muted,
colors.muted_hover,
),
ButtonVariant::Ghost => (
None,
colors.foreground,
colors.muted_hover,
ramps.secondary.pressed,
),
ButtonVariant::Destructive => (
Some(ramps.destructive.base),
colors.destructive_foreground,
ramps.destructive.hover,
ramps.destructive.pressed,
),
};
let (border, hover_border, pressed_border) = match self.variant {
ButtonVariant::Primary => (
ramps.primary.base,
ramps.primary.hover,
ramps.primary.pressed,
),
ButtonVariant::Secondary => (colors.border, colors.border, colors.border),
ButtonVariant::Ghost => (
transparent_black(),
transparent_black(),
transparent_black(),
),
ButtonVariant::Destructive => (
ramps.destructive.base,
ramps.destructive.hover,
ramps.destructive.pressed,
),
};
h_flex()
.id(self.id.clone())
.when_some(self.debug_selector, |button, selector| {
button.debug_selector(move || selector())
})
.role(Role::Button)
.map(|button| match self.side {
ButtonSide::Center => button.justify_center(),
ButtonSide::Left => button.justify_start(),
ButtonSide::Right => button.justify_end(),
})
.h(metrics.control_height)
.when(is_icon_only, |button| button.w(metrics.control_height))
.when(!is_icon_only && self.padded, |button| {
button.px(metrics.padding_x)
})
.line_height(relative(1.0))
.rounded(theme.radius.control)
.text_size(metrics.text_size)
.border_1()
.border_color(border)
.when_some(background, |button, background| button.bg(background))
.text_color(foreground)
.refine_style(&self.style)
.when_some(a11y_label, |button, label| button.aria_label(label))
.child(
h_flex()
.gap_2()
.when(self.loading, |content| content.invisible())
.map(|content| {
if icon_trailing {
content
.when_some(self.label, |content, label| content.child(label))
.children(self.children)
.when_some(self.icon, |content, icon| {
content.child(icon.size(metrics.icon_size))
})
} else {
content
.when_some(self.icon, |content, icon| {
content.child(icon.size(metrics.icon_size))
})
.when_some(self.label, |content, label| content.child(label))
.children(self.children)
}
}),
)
.when(self.loading, |button| {
button.child(
h_flex().absolute().inset_0().justify_center().child(
Spinner::new((self.id.clone(), "spinner"))
.with_size(self.size)
.variant(crate::components::spinner::SpinnerVariant::Icon)
.color(foreground),
),
)
})
.child(
canvas(record_anchor_bounds(self.id.clone()), |_, _, _, _| {})
.absolute()
.inset_0(),
)
.when(self.disabled, |button| button.opacity(DISABLED_OPACITY))
.when_some(self.tooltip, |button, tooltip| {
button.tooltip(move |window, cx| tooltip(window, cx))
})
.when(!self.disabled && !self.loading, |button| {
button
.cursor_pointer()
.focusable()
.tab_stop(self.tab_stop)
.hover(move |style| style.bg(hover).border_color(hover_border))
.active(move |style| style.bg(pressed).border_color(pressed_border))
.focus_visible(|style| style.shadow(focus_ring(colors.ring)))
.when_some(on_click, |button, on_click| {
button.on_click(move |event, window, cx| on_click(event, window, cx))
})
})
}
}
+177
View File
@@ -0,0 +1,177 @@
//! The checkbox: a controlled on/off value with an optional label.
use std::rc::Rc;
use crate::icons::{IconRole, icon};
use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size};
use crate::utils::focus_ring;
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role,
SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Toggled, Window,
};
use crate::components::common::{Sizable, StyledExt as _, h_flex};
/// The change reporter, fired with the next value by pointer, Enter, and Space.
type ChangeHandler = Box<dyn Fn(bool, &mut Window, &mut App)>;
/// A controlled checkbox component.
#[derive(IntoElement)]
#[must_use]
pub struct Checkbox {
id: ElementId,
label: Option<SharedString>,
checked: bool,
size: Size,
disabled: bool,
debug_selector: Option<Rc<dyn Fn() -> String>>,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler>,
style: StyleRefinement,
}
impl Checkbox {
/// Creates an unchecked checkbox.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
label: None,
checked: false,
size: Size::default(),
disabled: false,
debug_selector: None,
a11y_label: None,
on_change: None,
style: StyleRefinement::default(),
}
}
/// Sets the visible label; clicking it toggles too.
pub fn label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.label = Some(label.into());
self
}
/// Sets the current value; the checkbox never owns it.
pub fn checked(mut self, checked: bool) -> Self {
self.checked = checked;
self
}
/// Renders the checkbox inert, unfocusable, and dimmed; disabled always wins.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
/// Sets the debug-bounds selector, for headless tests.
pub fn debug_selector<F>(mut self, selector: F) -> Self
where
F: Fn() -> String + 'static,
{
self.debug_selector = Some(Rc::new(selector));
self
}
/// Overrides the accessibility label, which defaults to the visible label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// The change handler, fired with the next value by pointer, Enter, and Space.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(bool, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Box::new(handler));
self
}
}
impl gpui::Styled for Checkbox {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl Sizable for Checkbox {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl RenderOnce for Checkbox {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
let metrics = theme.sizes.resolve(self.size);
let on_change = self.on_change;
let next = !self.checked;
let a11y_label = self.a11y_label.or_else(|| self.label.clone());
h_flex()
.id(self.id)
.gap_2()
.text_size(metrics.text_size)
.refine_style(&self.style)
.when_some(self.debug_selector, |checkbox, selector| {
checkbox.debug_selector(move || selector())
})
.role(Role::CheckBox)
.when_some(a11y_label, |checkbox, label| checkbox.aria_label(label))
.aria_toggled(Toggled::from(self.checked))
.when(self.disabled, |checkbox| checkbox.opacity(DISABLED_OPACITY))
.when(!self.disabled, |checkbox| {
checkbox
.cursor_pointer()
.focusable()
.tab_stop(true)
.focus_visible(|style| style.shadow(focus_ring(colors.ring)))
.when_some(on_change, |checkbox, on_change| {
checkbox.on_click(move |_, window, cx| on_change(next, window, cx))
})
})
.child(
h_flex()
.justify_center()
.flex_none()
.size(metrics.indicator_size)
.rounded(theme.radius.sm)
.border_1()
.when(self.checked, |indicator| {
indicator
.bg(ramps.primary.base)
.border_color(ramps.primary.base)
.hover(|style| {
style
.bg(ramps.primary.hover)
.border_color(ramps.primary.hover)
})
.child(
icon(IconRole::Check)
.size(metrics.dense_icon_size)
.color(colors.primary_foreground),
)
})
.when(!self.checked, |indicator| {
indicator
.bg(colors.input)
.border_color(colors.border)
.hover(|style| style.border_color(colors.muted_foreground))
}),
)
.when_some(self.label, |checkbox, label| checkbox.child(label))
}
}
+177
View File
@@ -0,0 +1,177 @@
//! The clipboard button: copies a value and confirms with a brief check mark.
use std::rc::Rc;
use std::time::Duration;
use crate::icons::IconRole;
use crate::theme::Size;
use crate::utils::ResultLogErr as _;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyView, App, ClipboardItem, ElementId, Entity, IntoElement, RenderOnce, SharedString,
StyleRefinement, Task, Window,
};
use crate::components::button::{Button, ButtonVariant};
use crate::components::common::{Sizable, StyledExt as _};
/// How long the check mark shows before reverting to the copy icon.
pub const COPIED_DURATION: Duration = Duration::from_secs(1);
/// The tooltip view builder gpui's `.tooltip(...)` expects.
type TooltipBuilder = Rc<dyn Fn(&mut Window, &mut App) -> AnyView>;
/// Runs after the value lands on the clipboard.
type CopiedHandler = Box<dyn Fn(&mut App)>;
/// A quiet icon button that copies a value to the system clipboard.
#[derive(IntoElement)]
#[must_use]
pub struct ClipboardButton {
id: ElementId,
value: SharedString,
size: Size,
disabled: bool,
a11y_label: Option<SharedString>,
tooltip: Option<TooltipBuilder>,
on_copied: Option<CopiedHandler>,
style: StyleRefinement,
}
impl ClipboardButton {
/// Creates a copy button for this value.
pub fn new<I, V>(id: I, value: V) -> Self
where
I: Into<ElementId>,
V: Into<SharedString>,
{
Self {
id: id.into(),
value: value.into(),
size: Size::default(),
disabled: false,
a11y_label: None,
tooltip: None,
on_copied: None,
style: StyleRefinement::default(),
}
}
/// Shows a tooltip view next to the button after it is hovered.
pub fn tooltip<F>(mut self, tooltip: F) -> Self
where
F: Fn(&mut Window, &mut App) -> AnyView + 'static,
{
self.tooltip = Some(Rc::new(tooltip));
self
}
/// Renders the button inert and dimmed.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
/// Overrides the accessibility label, which defaults to `Copy`.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// Runs after the value lands on the clipboard.
pub fn on_copied<F>(mut self, handler: F) -> Self
where
F: Fn(&mut App) + 'static,
{
self.on_copied = Some(Box::new(handler));
self
}
}
impl Sizable for ClipboardButton {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
/// The transient copied marker keyed per button.
struct CopiedState {
generation: u64,
tasks: Vec<Task<()>>,
}
impl RenderOnce for ClipboardButton {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let copied: Entity<CopiedState> =
window.use_keyed_state((self.id.clone(), "clipboard-copied"), cx, |_, _| {
CopiedState {
generation: 0,
tasks: Vec::new(),
}
});
let is_copied = copied.read(cx).generation != 0;
let selector = if is_copied {
"clipboard-copied"
} else {
"clipboard"
};
Button::new((self.id.clone(), "clipboard-button"))
.icon(if is_copied {
IconRole::Check
} else {
IconRole::Copy
})
.variant(ButtonVariant::Ghost)
.with_size(self.size)
.disabled(self.disabled)
.refine_style(&self.style)
.debug_selector(move || selector.to_string())
.accessibility_label(self.a11y_label.unwrap_or_else(|| "Copy".into()))
.when_some(self.tooltip, |button, tooltip| {
button.tooltip(move |window, cx| tooltip(window, cx))
})
.on_click({
let value = self.value;
let copied = copied.clone();
let on_copied = self.on_copied;
move |_, window, cx| {
cx.write_to_clipboard(ClipboardItem::new_string(value.to_string()));
let generation = copied.update(cx, |state, cx| {
state.generation += 1;
cx.notify();
state.generation
});
let weak = copied.downgrade();
let task = window.spawn(cx, async move |cx| {
cx.background_executor().timer(COPIED_DURATION).await;
cx.update(|_, cx| {
weak.update(cx, |state, cx| {
if state.generation == generation {
state.generation = 0;
cx.notify();
}
})
.log_err();
})
.log_err();
});
copied.update(cx, |state, _| {
state.tasks.push(task);
});
// Invoke the callback after copying
if let Some(on_copied) = &on_copied {
on_copied(cx);
}
}
})
}
}
+752
View File
@@ -0,0 +1,752 @@
//! The combobox: an editable field that filters its options while typing.
//!
//! The state is the view: it 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 [`UnmatchedText`] — revert by default.
use std::cell::RefCell;
use std::rc::Rc;
use crate::icons::{IconRole, icon};
use crate::theme::ActiveTheme as _;
use crate::theme::{COMBOBOX_MIN_WIDTH, COMBOBOX_WIDTH, POPUP_MAX_HEIGHT, Size};
use crate::utils::ResultLogErr as _;
use gpui::prelude::FluentBuilder;
use gpui::{
App, Bounds, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding,
MouseButton, MouseDownEvent, ParentElement as _, Pixels, Render, Role, ScrollHandle,
SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Subscription, Task,
Window, actions, anchored, canvas, deferred, div, point, px,
};
use crate::components::common::{OVERLAY_LAYER, Sizable, StyledExt as _, h_flex, v_flex};
use crate::components::input::{Input, InputState, InputStateEvent};
use crate::components::scroll_area::ScrollArea;
actions!(
combobox,
[HighlightNext, HighlightPrevious, Choose, Dismiss]
);
/// 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> = (T, SharedString);
/// Reports the value whenever it changes;
pub type ComboboxHandler<T> = Rc<dyn Fn(Option<T>, &mut Window, &mut App)>;
/// Receives unmatched text when the field loses focus in create mode.
pub type ComboboxCreateHandler = Rc<dyn Fn(SharedString, &mut Window, &mut App)>;
/// Decides which options survive a query: the query, the value, the label.
pub type ComboboxFilter<T> = Rc<dyn Fn(&str, &T, &SharedString) -> bool>;
/// Builder for a combobox. Pass it to [`ComboboxState::new`].
#[must_use]
pub struct Combobox<T>
where
T: Clone + PartialEq + 'static,
{
id: ElementId,
name: SharedString,
options: Vec<ComboboxOption<T>>,
selected: Option<T>,
placeholder: SharedString,
on_change: Option<ComboboxHandler<T>>,
on_create: Option<ComboboxCreateHandler>,
filter: Option<ComboboxFilter<T>>,
unmatched: UnmatchedText,
size: Size,
style: StyleRefinement,
}
impl<T> Combobox<T>
where
T: Clone + PartialEq + 'static,
{
pub fn new<I, N>(id: I, name: N, options: Vec<ComboboxOption<T>>) -> Self
where
I: Into<ElementId>,
N: Into<SharedString>,
{
Self {
id: id.into(),
name: name.into(),
options,
selected: None,
placeholder: SharedString::from("Select..."),
on_change: None,
on_create: None,
filter: None,
unmatched: UnmatchedText::default(),
size: Size::default(),
style: StyleRefinement::default(),
}
}
/// Sets the initially selected value; its label seeds the field.
pub fn selected<S>(mut self, selected: S) -> Self
where
S: Into<Option<T>>,
{
self.selected = selected.into();
self
}
/// Sets the text shown while the field is empty.
pub fn placeholder<L>(mut self, placeholder: L) -> Self
where
L: Into<SharedString>,
{
self.placeholder = placeholder.into();
self
}
/// Reports the value whenever it changes.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(Option<T>, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Rc::new(handler));
self
}
/// Hands unmatched text to `handler` when the field loses focus.
pub fn on_create<F>(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<F>(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<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.name = label.into();
self
}
}
/// Style refinements set the combobox's width.
impl<T> Styled for Combobox<T>
where
T: Clone + PartialEq + 'static,
{
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
// Combobox is a data builder, not an element, adopt the combinators explicitly.
impl<T> FluentBuilder for Combobox<T> where T: Clone + PartialEq + 'static {}
/// The stateful combobox.
pub struct ComboboxState<T>
where
T: Clone + PartialEq + 'static,
{
id: ElementId,
name: SharedString,
placeholder: SharedString,
options: Vec<ComboboxOption<T>>,
/// The chosen value. `None` while the text names nothing.
selected: Option<T>,
query: Entity<InputState>,
/// Indices into `options` that survived the filter, in popup row order.
visible: Vec<usize>,
/// The highlighted popup *row*, when the popup is open.
highlight: Option<usize>,
on_change: Option<ComboboxHandler<T>>,
on_create: Option<ComboboxCreateHandler>,
filter: ComboboxFilter<T>,
unmatched: UnmatchedText,
size: Size,
/// Width refinements from the builder, applied to the wrapper each render.
style: StyleRefinement,
/// Handler reports in flight; held so they die with the state.
tasks: Vec<Task<()>>,
/// Keeps the query-event subscription tied to the state's lifetime.
_subscription: Subscription,
}
impl<T> Sizable for ComboboxState<T>
where
T: Clone + PartialEq + 'static,
{
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl<T> ComboboxState<T>
where
T: Clone + PartialEq + 'static,
{
/// Builds the state, its query field, and the subscription tying them.
pub fn new(combobox: Combobox<T>, window: &mut Window, cx: &mut Context<Self>) -> Self {
let query = InputState::new(cx);
// The field starts showing the label of whatever was chosen,
// so text and value agree from the first frame.
if let Some(selected) = &combobox.selected
&& let Some((_, label)) = combobox.options.iter().find(|(value, _)| value == selected)
{
let label = label.to_string();
query.update(cx, |query, cx| query.set_value_silent(label, window, cx));
}
let subscription =
cx.subscribe_in(&query, window, |state, _, event, window, cx| match event {
InputStateEvent::Focused => state.query_focused(window, cx),
InputStateEvent::TextChanged => state.text_changed(window, cx),
InputStateEvent::Blurred => state.blurred(window, cx),
_ => {}
});
let visible = (0..combobox.options.len()).collect();
Self {
id: combobox.id,
name: combobox.name,
placeholder: combobox.placeholder,
options: combobox.options,
selected: combobox.selected,
query,
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,
tasks: Vec::new(),
_subscription: subscription,
}
}
/// 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()
}
/// Replaces the value; reports it when it actually changed.
pub fn set_selected(&mut self, value: Option<T>, window: &mut Window, cx: &mut Context<Self>) {
self.set_value(value, window, cx);
}
/// Replaces the choice list and re-runs the current filter.
pub fn set_options(&mut self, options: Vec<ComboboxOption<T>>, cx: &mut Context<Self>) {
self.options = options;
let query = self.query.read(cx).value().to_string();
self.refilter(&query);
cx.notify();
}
/// A copy of the current choice list.
pub fn options_snapshot(&self) -> Vec<ComboboxOption<T>> {
self.options.clone()
}
/// The label of the chosen option, if there is one.
fn selected_label(&self) -> Option<SharedString> {
let selected = self.selected.as_ref()?;
self.options
.iter()
.find(|(value, _)| value == selected)
.map(|(_, label)| label.clone())
}
/// Recomputes `visible` for `query` and clamps the highlight onto it.
fn refilter(&mut self, query: &str) {
let filter = self.filter.clone();
self.visible = self
.options
.iter()
.enumerate()
.filter(|(_, (value, label))| filter(query, value, label))
.map(|(index, _)| index)
.collect();
self.highlight = self.highlight.filter(|row| *row < self.visible.len());
}
fn query_text(&self, cx: &Context<Self>) -> String {
self.query.read(cx).value().trim().to_string()
}
/// Sets the value and reports it, including when it is `None`.
fn set_value(&mut self, value: Option<T>, window: &mut Window, cx: &mut Context<Self>) {
if self.selected == value {
return;
}
self.selected = value.clone();
if let Some(on_change) = self.on_change.clone() {
let value = value.clone();
let task = window.spawn(cx, async move |cx| {
cx.update(|window, cx| on_change(value, window, cx))
.log_err();
});
self.tasks.push(task);
}
cx.notify();
}
/// Commits the option at popup *row*.
fn choose_row(&mut self, row: usize, window: &mut Window, cx: &mut Context<Self>) {
let Some(option_index) = self.visible.get(row).copied() else {
return;
};
let Some((value, label)) = self.options.get(option_index).cloned() else {
return;
};
self.query.update(cx, |query, cx| {
query.set_value_silent(label.to_string(), window, cx)
});
self.highlight = None;
self.refilter("");
self.set_value(Some(value), window, cx);
}
/// Typing: re-filter, open, reset the highlight, and clear the value.
fn text_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let query = self.query_text(cx);
self.refilter(&query);
self.highlight = Some(0);
self.set_value(None, window, cx);
cx.notify();
}
/// Gaining focus.
fn query_focused(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
if self.selected.is_some() {
return;
}
self.refilter("");
self.highlight = Some(0);
cx.notify();
}
/// Losing focus. [`UnmatchedText`] decides what the text becomes.
fn blurred(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.highlight = None;
let text = self.query_text(cx);
if self.selected_label().as_deref() == Some(text.as_str()) {
cx.notify();
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.tasks.push(task);
}
}
}
cx.notify();
}
/// Down and Up over the visible rows.
fn move_highlight(&mut self, delta: i32, cx: &mut Context<Self>) {
if self.visible.is_empty() {
return;
}
let count = self.visible.len();
let current = self.highlight.filter(|row| *row < count);
let next = match current {
Some(row) => match row.checked_add_signed(isize::try_from(delta).unwrap_or(0)) {
Some(next) if next < count => next,
Some(_) => 0,
None => count - 1,
},
None => {
if delta > 0 {
0
} else {
count - 1
}
}
};
self.highlight = Some(next);
cx.notify();
}
/// Enter. Commits the highlighted row.
fn choose(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(row) = self.highlight else {
cx.propagate();
return;
};
self.choose_row(row, window, cx);
}
/// Escape. Closes the picker.
fn dismiss(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
if self.highlight.is_none() {
cx.propagate();
return;
}
self.highlight = None;
cx.notify();
}
}
impl<T> Render for ComboboxState<T>
where
T: Clone + PartialEq + 'static,
{
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let (metrics, colors, radius, panel_border, spacing_unit, shadows) = {
let theme = cx.theme();
let metrics = theme.sizes.resolve(self.size);
(
metrics,
theme.colors,
theme.radius,
theme.colors.border,
theme.spacing.unit,
theme.elevations.popover.shadows(),
)
};
let icon_size = metrics.dense_icon_size;
let id = self.id.clone();
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(icon_size)
.color(colors.muted_foreground),
);
let wrapper_bounds: Rc<RefCell<Option<Bounds<Pixels>>>> = Rc::new(RefCell::new(None));
div()
.id(id.clone())
.key_context(COMBOBOX_CONTEXT)
.relative()
.w(COMBOBOX_WIDTH)
.min_w(COMBOBOX_MIN_WIDTH)
.refine_style(&self.style)
.role(Role::ComboBox)
.aria_expanded(open)
.aria_label(self.name.clone())
.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(
canvas(
{
let cell = wrapper_bounds.clone();
move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds)
},
|_, _, _window, _cx| {},
)
.absolute()
.inset_0(),
)
.child(
Input::new((id.clone(), "query"), self.query.clone())
.placeholder(self.placeholder.clone())
.placeholder_when_focused(true)
.with_size(self.size),
)
.child(
h_flex()
.absolute()
.right(metrics.dense_padding_x)
.top((metrics.input_height - icon_size) / 2.)
.child(chevron),
)
.when(open, |wrapper| {
let rows: Vec<gpui::AnyElement> = self
.visible
.iter()
.enumerate()
.map(|(row, option_index)| {
let Some((value, label)) = self.options.get(*option_index) else {
return div().into_any_element();
};
let highlighted = self.highlight == Some(row);
let checked = self.selected.as_ref() == Some(value);
let state = state.clone();
let row_index = row;
div()
.id(("option", *option_index))
.debug_selector({
let id = id.clone();
move || format!("{id}-option-{row}")
})
.role(Role::ListBoxOption)
.aria_label(label.clone())
.flex()
.items_center()
.gap_2()
.px_2()
.py_1()
.min_h(metrics.control_height)
.rounded(radius.sm)
.when(highlighted, |row| row.bg(colors.muted))
.when(!highlighted, |row| row.hover(|row| row.bg(colors.muted)))
.on_mouse_move({
let state = state.clone();
move |_, _window, cx| {
if state.read(cx).highlight != Some(row_index) {
state.update(cx, |state, cx| {
state.highlight = Some(row_index);
cx.notify();
});
}
}
})
.on_click({
let state = state.clone();
move |_, window, cx| {
state.update(cx, |state, cx| {
state.choose_row(row_index, window, cx)
});
}
})
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.child(label.clone()),
)
.when(checked, |row| {
row.child(
icon(IconRole::Check)
.size(icon_size)
.color(colors.foreground),
)
})
.into_any_element()
})
.collect();
let rows: gpui::AnyElement = if rows.is_empty() {
div()
.px_2()
.py_1()
.text_size(metrics.caption_size)
.text_color(colors.muted_foreground)
.child("No matches")
.into_any_element()
} else {
let scroll = window.use_keyed_state((id.clone(), "rows-scroll"), cx, |_, _| {
ScrollHandle::new()
});
ScrollArea::new((id.clone(), "rows"))
.handle(scroll.read(cx).clone())
.axes(crate::components::scroll_area::ScrollAxes::Vertical)
.max_h(POPUP_MAX_HEIGHT)
.children(rows)
.into_any_element()
};
let panel_bounds: Rc<RefCell<Option<Bounds<Pixels>>>> = Rc::new(RefCell::new(None));
let popup_width = wrapper_bounds
.borrow()
.map(|bounds| bounds.size.width)
.unwrap_or(COMBOBOX_WIDTH);
let panel = v_flex()
.id((id.clone(), "panel"))
.debug_selector({
let id = id.clone();
move || format!("{id}-panel")
})
.w(popup_width)
.p_1()
.bg(colors.surface)
.text_color(colors.foreground)
.rounded(radius.overlay)
.border_1()
.border_color(panel_border)
.shadow(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();
});
}
});
}
},
)
.absolute()
.inset_0(),
);
wrapper.child(
deferred(anchored().offset(point(px(0.), spacing_unit)).child(panel))
.with_priority(OVERLAY_LAYER),
)
})
}
}
+529
View File
@@ -0,0 +1,529 @@
//! The command palette: a modal query field over the application's actions.
use std::rc::Rc;
use crate::icons::Icon;
use crate::theme::{ActiveTheme as _, POPUP_MAX_HEIGHT, Size};
use gpui::prelude::FluentBuilder;
use gpui::{
AnyElement, App, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding,
MouseButton, ParentElement as _, Render, Role, ScrollHandle, SharedString,
StatefulInteractiveElement as _, StyleRefinement, Styled as _, Subscription, Window, actions,
canvas, deferred, div, relative,
};
use crate::components::common::{DIALOG_LAYER, StyledExt as _, h_flex, v_flex};
use crate::components::input::{Input, InputState, InputStateEvent};
use crate::components::scroll_area::{ScrollArea, ScrollAxes};
actions!(
command_palette,
[HighlightNext, HighlightPrevious, Choose, Dismiss]
);
/// 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)),
]);
}
/// A command the palette can run: a stable id and the label the matcher sees.
#[derive(Clone)]
#[must_use]
pub struct Command {
/// The stable domain id handed to `on_execute`.
pub id: SharedString,
/// What the matcher matches and the row shows.
pub label: SharedString,
/// Gray text on the row's right edge, e.g. the keybinding.
pub hint: Option<SharedString>,
/// Leading glyph shown before the label.
pub icon: Option<Icon>,
}
impl Command {
/// Creates a command without a hint or icon.
pub fn new<I, L>(id: I, label: L) -> Self
where
I: Into<SharedString>,
L: Into<SharedString>,
{
Self {
id: id.into(),
label: label.into(),
hint: None,
icon: None,
}
}
/// Shows an icon before the label.
pub fn icon<I>(mut self, icon: I) -> Self
where
I: Into<Icon>,
{
self.icon = Some(icon.into());
self
}
/// Sets the row's right-edge hint.
pub fn hint<H>(mut self, hint: H) -> Self
where
H: Into<SharedString>,
{
self.hint = Some(hint.into());
self
}
}
// 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<dyn Fn(&str, &[Command]) -> Vec<Command>>;
/// Runs the chosen command.
pub type CommandHandler = Rc<dyn Fn(&Command, &mut Window, &mut App)>;
/// Builder for a command palette. Pass it to [`CommandPaletteState::new`].
#[must_use]
pub struct CommandPalette {
id: ElementId,
name: SharedString,
placeholder: SharedString,
commands: Vec<Command>,
matcher: CommandMatcher,
on_execute: Option<CommandHandler>,
style: StyleRefinement,
}
impl CommandPalette {
/// Creates the builder, the caller-owned matcher decides what matches.
pub fn new<I, M>(id: I, commands: Vec<Command>, matcher: M) -> Self
where
I: Into<ElementId>,
M: Fn(&str, &[Command]) -> Vec<Command> + 'static,
{
Self {
id: id.into(),
name: SharedString::from("Command palette"),
placeholder: SharedString::from("Type a command..."),
commands,
matcher: Rc::new(matcher),
on_execute: None,
style: StyleRefinement::default(),
}
}
/// Sets the text shown while the query is empty.
pub fn placeholder<L>(mut self, placeholder: L) -> Self
where
L: Into<SharedString>,
{
self.placeholder = placeholder.into();
self
}
/// Runs `handler` with the chosen command, then closes the palette.
pub fn on_execute<F>(mut self, handler: F) -> Self
where
F: Fn(&Command, &mut Window, &mut App) + 'static,
{
self.on_execute = Some(Rc::new(handler));
self
}
/// Overrides the accessibility label of the panel.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.name = label.into();
self
}
}
// CommandPalette is a data builder, not an element, adopt the combinators explicitly.
impl FluentBuilder for CommandPalette {}
/// The stateful palette.
pub struct CommandPaletteState {
id: ElementId,
name: SharedString,
placeholder: SharedString,
commands: Vec<Command>,
matcher: CommandMatcher,
on_execute: Option<CommandHandler>,
style: StyleRefinement,
query: Entity<InputState>,
/// The commands the matcher returned for the query, in display order.
matches: Vec<Command>,
/// The highlighted row, when the palette is open.
highlight: Option<usize>,
open: bool,
/// Keeps the query-event subscription tied to the state's lifetime.
_subscription: Subscription,
}
impl CommandPaletteState {
/// Builds the state, its query field, and the subscription tying them.
pub fn new(palette: CommandPalette, window: &mut Window, cx: &mut Context<Self>) -> Self {
let query = InputState::new(cx);
let subscription = cx.subscribe_in(&query, window, |state, _, event, window, cx| {
if event == &InputStateEvent::TextChanged {
state.text_changed(window, cx);
}
});
let matches = (palette.matcher)("", &palette.commands);
Self {
id: palette.id,
name: palette.name,
placeholder: palette.placeholder,
commands: palette.commands,
matcher: palette.matcher,
on_execute: palette.on_execute,
style: palette.style,
query,
matches,
highlight: None,
open: false,
_subscription: subscription,
}
}
/// Opens the palette: fresh query, fresh matches, focus in the field.
pub fn open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.open {
self.focus(window, cx);
return;
}
self.open = true;
self.query.update(cx, |query, cx| {
query.set_value_silent("", window, cx);
});
self.refilter("");
self.highlight = (!self.matches.is_empty()).then_some(0);
self.focus(window, cx);
cx.notify();
}
/// Closes the palette.
pub fn close(&mut self, cx: &mut Context<Self>) {
if !self.open {
return;
}
self.open = false;
self.highlight = None;
cx.notify();
}
/// Opens the palette when closed, closes it when open.
pub fn toggle(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.open {
self.close(cx);
} else {
self.open(window, cx);
}
}
/// Whether the palette is showing.
pub fn is_open(&self) -> bool {
self.open
}
/// Replaces the command list and re-runs the current query's matches.
pub fn set_commands(&mut self, commands: Vec<Command>, cx: &mut Context<Self>) {
self.commands = commands;
let query = self.query.read(cx).value().to_string();
self.refilter(&query);
cx.notify();
}
/// Focuses the query field.
pub fn focus(&self, window: &mut Window, cx: &mut App) {
window.focus(&self.query.read(cx).focus_handle(), cx);
}
/// Asks the caller's matcher who matches, and clamps the highlight.
fn refilter(&mut self, query: &str) {
self.matches = (self.matcher)(query, &self.commands);
if let Some(highlight) = self.highlight {
self.highlight = (highlight < self.matches.len()).then_some(highlight);
}
}
/// Typing: fresh matches, highlight the first row.
fn text_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
let query = self.query.read(cx).value().to_string();
self.refilter(&query);
self.highlight = (!self.matches.is_empty()).then_some(0);
cx.notify();
}
/// Down and Up over the matched rows, wrapping at the ends.
fn move_highlight(&mut self, delta: i32, cx: &mut Context<Self>) {
if self.matches.is_empty() {
return;
}
let count = self.matches.len();
let next = match self.highlight {
Some(row) => match row.checked_add_signed(isize::try_from(delta).unwrap_or(0)) {
Some(next) if next < count => next,
Some(_) => 0,
None => count - 1,
},
None if delta > 0 => 0,
None => count - 1,
};
self.highlight = Some(next);
cx.notify();
}
/// Enter. Runs the highlighted command and closes.
fn choose(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(row) = self.highlight else {
cx.propagate();
return;
};
self.choose_row(row, window, cx);
}
/// Runs the command at a row and closes.
fn choose_row(&mut self, row: usize, window: &mut Window, cx: &mut Context<Self>) {
let Some(command) = self.matches.get(row) else {
return;
};
let command = command.clone();
if let Some(on_execute) = self.on_execute.clone() {
on_execute(&command, window, cx);
}
self.close(cx);
}
/// Escape. Closes the palette.
fn dismiss(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
if !self.open {
cx.propagate();
return;
}
self.close(cx);
}
}
impl Render for CommandPaletteState {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
if !self.open {
return div().into_any_element();
}
let (colors, radius, metrics, panel_border, shadows, titlebar_height) = {
let theme = cx.theme();
(
theme.colors,
theme.radius,
theme.sizes.resolve(Size::default()),
theme.colors.border,
theme.elevations.dialog.shadows(),
theme.titlebar_height,
)
};
let id = self.id.clone();
let state = cx.entity();
let query_focus = self.query.read(cx).focus_handle();
let rows: Vec<AnyElement> = self
.matches
.iter()
.enumerate()
.map(|(row, command)| {
let highlighted = self.highlight == Some(row);
let state = state.clone();
let row_index = row;
h_flex()
.id((ElementId::from(command.id.clone()), "command"))
.debug_selector({
let id = id.clone();
move || format!("{id}-command-{row}")
})
.role(Role::ListBoxOption)
.aria_label(command.label.clone())
.gap_2()
.px_2()
.py_1()
.min_h(metrics.control_height)
.text_size(metrics.text_size)
.line_height(relative(1.0))
.rounded(radius.sm)
.when(highlighted, |row| row.bg(colors.muted))
.when(!highlighted, |row| row.hover(|row| row.bg(colors.muted)))
.on_mouse_move({
let state = state.clone();
move |_, _window, cx| {
if state.read(cx).highlight != Some(row_index) {
state.update(cx, |state, cx| {
state.highlight = Some(row_index);
cx.notify();
});
}
}
})
.on_click({
let state = state.clone();
move |_, window, cx| {
state.update(cx, |state, cx| state.choose_row(row_index, window, cx));
}
})
.when_some(command.icon.clone(), |row, icon| {
row.child(icon.size(metrics.icon_size).color(colors.foreground))
})
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.child(command.label.clone()),
)
.when_some(command.hint.clone(), |row, hint| {
row.child(
div()
.flex_shrink_0()
.text_size(metrics.caption_size)
.text_color(colors.muted_foreground)
.child(hint),
)
})
.into_any_element()
})
.collect();
let rows: AnyElement = if rows.is_empty() {
div()
.px_2()
.py_1()
.text_size(metrics.caption_size)
.text_color(colors.muted_foreground)
.child("No matches")
.into_any_element()
} else {
let scroll =
window.use_keyed_state((id.clone(), "rows-scroll"), cx, |_, _| ScrollHandle::new());
ScrollArea::new((id.clone(), "rows"))
.handle(scroll.read(cx).clone())
.axes(ScrollAxes::Vertical)
.max_h(POPUP_MAX_HEIGHT)
.children(rows)
.into_any_element()
};
let panel = 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()
.bg(colors.surface)
.text_color(colors.foreground)
.rounded(radius.overlay)
.border_1()
.border_color(panel_border)
.shadow(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()
.inset_0()
.flex()
.justify_center()
.items_start()
.pt(titlebar_height)
.child(scrim)
.child(panel),
)
.with_priority(DIALOG_LAYER)
.into_any_element()
}
}
+50
View File
@@ -0,0 +1,50 @@
//! Shared element constructors and small style helpers.
pub use crate::theme::Size;
pub use crate::utils::{StyledExt, h_flex, v_flex};
/// A handler told to clean up after a dismissed surface.
pub type DismissHandler = std::rc::Rc<dyn Fn(&mut gpui::App)>;
/// 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.
fn with_size(mut self, size: Size) -> Self {
self.apply_size(size);
self
}
/// Applies the size to the component's fields.
fn apply_size(&mut self, size: Size);
/// Sets `Size::XSmall`.
fn xsmall(self) -> Self
where
Self: Sized,
{
self.with_size(Size::XSmall)
}
/// Sets `Size::Small`.
fn small(self) -> Self
where
Self: Sized,
{
self.with_size(Size::Small)
}
/// Sets `Size::Large`.
fn large(self) -> Self
where
Self: Sized,
{
self.with_size(Size::Large)
}
}
+127
View File
@@ -0,0 +1,127 @@
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<dyn Fn(&mut Window, &mut App) -> gpui::AnyElement>;
/// Builds the menu's items fresh each render.
type ItemsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<MenuItem>>;
/// 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<TargetFn>,
items: Option<ItemsFn>,
a11y_label: Option<SharedString>,
style: StyleRefinement,
}
impl ContextMenu {
/// Creates a context menu over a target set with [`ContextMenu::target`].
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
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<F>(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<F>(mut self, items: F) -> Self
where
F: Fn(&mut Window, &mut App) -> Vec<MenuItem> + 'static,
{
self.items = Some(Box::new(items));
self
}
/// Overrides the menu's accessibility label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
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)
})
}
}
+331
View File
@@ -0,0 +1,331 @@
use gpui::prelude::FluentBuilder as _;
use std::rc::Rc;
use crate::icons::IconRole;
use crate::theme::{ActiveTheme as _, DIALOG_MIN_WIDTH, TextRole, Typeset as _};
use gpui::{
Animation, AnimationExt as _, AnyElement, App, DefiniteLength, ElementId,
InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, ParentElement as _,
RenderOnce, Role, ScrollHandle, SharedString, StatefulInteractiveElement as _, StyleRefinement,
Styled as _, Window, canvas, deferred, div, ease_out_quint, relative,
};
use crate::components::button::{Button, ButtonVariant};
use crate::components::common::{DIALOG_LAYER, Sizable, StyledExt as _, v_flex};
use crate::components::grain::grain;
use crate::components::scroll_area::ScrollArea;
/// Requests the dialog's close: `false` closes.
pub type ChangeHandler = Rc<dyn Fn(bool, &mut Window, &mut App)>;
type ContentFn = Box<dyn Fn(&mut Window, &mut App) -> AnyElement>;
type ActionsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<AnyElement>>;
/// A centred panel over a dim scrim: the platform's modal.
#[derive(IntoElement)]
#[must_use]
pub struct Dialog {
id: ElementId,
open: bool,
alert: bool,
grain: bool,
title: Option<SharedString>,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler>,
content: Option<ContentFn>,
actions: Option<ActionsFn>,
min_width: Option<DefiniteLength>,
height: Option<DefiniteLength>,
style: StyleRefinement,
}
impl Dialog {
/// Creates a closed dialog.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
open: false,
alert: false,
grain: false,
title: None,
a11y_label: None,
on_change: None,
content: None,
actions: None,
min_width: None,
height: None,
style: StyleRefinement::default(),
}
}
/// Sets the current open state.
pub fn open(mut self, open: bool) -> Self {
self.open = open;
self
}
/// Sets the alert mode.
pub fn alert(mut self, alert: bool) -> Self {
self.alert = alert;
self
}
/// Textures the scrim with a film-grain overlay.
pub fn grain(mut self, grain: bool) -> Self {
self.grain = grain;
self
}
/// Requests close through `on_change` on escape, scrim clicks, and the close button.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(bool, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Rc::new(handler));
self
}
/// Sets the dialog's title.
pub fn title<L>(mut self, title: L) -> Self
where
L: Into<SharedString>,
{
self.title = Some(title.into());
self
}
/// Sets the body content between the title and the actions.
pub fn content<F>(mut self, content: F) -> Self
where
F: Fn(&mut Window, &mut App) -> AnyElement + 'static,
{
self.content = Some(Box::new(content));
self
}
/// Sets the footer actions, laid out right-aligned in the given order.
pub fn actions<F>(mut self, actions: F) -> Self
where
F: Fn(&mut Window, &mut App) -> Vec<AnyElement> + 'static,
{
self.actions = Some(Box::new(actions));
self
}
/// Overrides the accessibility label of the panel.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// Sets the panel's minimum width, defaults to the standard dialog width.
pub fn min_width<W>(mut self, width: W) -> Self
where
W: Into<DefiniteLength>,
{
self.min_width = Some(width.into());
self
}
/// Sets the panel's height, body content taller than the panel scrolls.
pub fn height<H>(mut self, height: H) -> Self
where
H: Into<DefiniteLength>,
{
self.height = Some(height.into());
self
}
}
impl gpui::Styled for Dialog {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for Dialog {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let root = div().absolute().inset_0();
if !self.open {
return root.into_any_element();
}
let (scrim_color, border, foreground, surface, radius, shadows, enter_duration) = {
let theme = cx.theme();
(
theme.colors.overlay,
theme.colors.border,
theme.colors.foreground,
theme.colors.surface,
theme.radius.overlay,
theme.elevations.dialog.shadows(),
theme.motion.overlay,
)
};
let role = if self.alert {
Role::AlertDialog
} else {
Role::Dialog
};
let label = self
.a11y_label
.clone()
.or_else(|| self.title.clone())
.unwrap_or_else(|| SharedString::from(self.id.to_string()));
let on_change = self.on_change.clone();
let alert = self.alert;
let show_close = !alert && on_change.is_some();
// Keyboard focus rides the panel across frames.
let focus = crate::utils::focus_handle(&self.id, window, cx);
let content = self.content.map(|build| build(window, cx));
let actions = self.actions.map(|build| build(window, cx));
let height = self.height;
let scroll = window
.use_keyed_state("dialog-content-scroll", cx, |_, _| ScrollHandle::new())
.read(cx)
.clone();
let panel = v_flex()
.id("dialog-panel")
.track_focus(&focus)
.role(role)
.aria_label(label)
.when_some(self.min_width, |panel, width| panel.min_w(width))
.when(self.min_width.is_none(), |panel| {
panel.min_w(DIALOG_MIN_WIDTH)
})
.max_w(relative(0.9))
.when_some(height, |panel, height| panel.h(height))
.p_4()
.gap_4()
.bg(surface)
.text_color(foreground)
.rounded(radius)
.border_1()
.border_color(border)
.shadow(shadows)
.overflow_hidden()
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_key_down({
let on_change = on_change.clone();
move |event: &KeyDownEvent, window, cx| {
if event.keystroke.key == "escape"
&& !alert
&& let Some(on_change) = &on_change
{
on_change(false, window, cx);
}
cx.stop_propagation();
}
})
.when(self.title.is_some() || show_close, |panel| {
panel.child(
div()
.flex()
.items_center()
.justify_end()
.gap_2()
.when_some(self.title.clone(), |row, title| {
row.child(div().flex_1().typeset(TextRole::Title3, cx).child(title))
})
.when(show_close, |row| {
row.child(
Button::new("dialog-close")
.icon(IconRole::Close)
.variant(ButtonVariant::Ghost)
.xsmall()
.debug_selector(|| "dialog-close".to_string())
.accessibility_label("Close")
.on_click({
let on_change = on_change.clone();
move |_, window, cx| {
if let Some(on_change) = &on_change {
on_change(false, window, cx);
}
}
}),
)
}),
)
})
.when_some(content, |panel, content| {
panel.map(|this| {
if height.is_some() {
this.child(
ScrollArea::new("dialog-content")
.handle(scroll)
.flex_1()
.min_h_0()
.child(content),
)
} else {
this.child(content)
}
})
})
.when_some(actions, |panel, actions| {
panel.child(div().flex().justify_end().gap_3().children(actions))
})
.child(
canvas(|_, _, _| {}, {
move |_, _, window, cx| {
if !focus.contains_focused(window, cx) {
window.focus(&focus, cx);
}
}
})
.absolute()
.inset_0(),
);
let scrim = div()
.absolute()
.inset_0()
.bg(scrim_color)
.occlude()
.when(self.grain, |scrim| scrim.child(grain()))
.when(!alert, |scrim| {
scrim.on_mouse_down(MouseButton::Left, {
let on_change = on_change.clone();
move |_, _window, cx| {
if let Some(on_change) = &on_change {
on_change(false, _window, cx);
}
cx.stop_propagation();
}
})
});
deferred(
root.flex()
.items_center()
.justify_center()
.p_4()
.refine_style(&self.style)
.child(scrim.with_animation(
"dialog-scrim-enter",
Animation::new(enter_duration).with_easing(ease_out_quint()),
|scrim, delta| scrim.opacity(delta),
))
.child(panel.with_animation(
"dialog-enter",
Animation::new(enter_duration).with_easing(ease_out_quint()),
|panel, delta| panel.opacity(delta),
)),
)
.with_priority(DIALOG_LAYER)
.into_any_element()
}
}
+491
View File
@@ -0,0 +1,491 @@
//! The dropdown menu: a push button with an attached menu of actions.
use std::cell::RefCell;
use std::rc::Rc;
use crate::icons::{Icon, IconRole, icon};
use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size};
use crate::utils::{focus_handle, focus_ring};
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, ClickEvent, DefiniteLength, DispatchPhase, ElementId, InteractiveElement as _,
IntoElement, KeyDownEvent, MouseButton, MouseDownEvent, ParentElement as _, RenderOnce, Role,
SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, canvas,
div, relative,
};
use crate::components::button::ButtonVariant;
use crate::components::common::{Sizable, StyledExt as _, h_flex};
use crate::components::menu::{
ChangeHandler, MenuChrome, MenuItem, MenuPanelSpec, TriggerBoundsCell, anchored_menu_panel,
};
use crate::components::spinner::Spinner;
/// The main zone's activation handler, shared by pointer, Enter, and Space.
type ClickHandler = Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>;
type ItemsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<MenuItem>>;
/// A push button with an attached dropdown menu.
#[derive(IntoElement)]
#[must_use]
pub struct DropdownMenu {
id: ElementId,
label: Option<SharedString>,
icon: Option<Icon>,
variant: ButtonVariant,
size: Size,
disabled: bool,
loading: bool,
tab_stop: bool,
open: bool,
a11y_label: Option<SharedString>,
on_click: Option<ClickHandler>,
on_open_change: Option<ChangeHandler>,
items: Option<ItemsFn>,
min_width: Option<DefiniteLength>,
style: StyleRefinement,
}
impl DropdownMenu {
/// Creates a closed dropdown menu rendered as a primary button.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
label: None,
icon: None,
variant: ButtonVariant::default(),
size: Size::default(),
disabled: false,
loading: false,
tab_stop: true,
open: false,
a11y_label: None,
on_click: None,
on_open_change: None,
items: None,
min_width: None,
style: StyleRefinement::default(),
}
}
/// Sets the visible label.
pub fn label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.label = Some(label.into());
self
}
/// Shows an icon. Omitting the label renders an icon-only trigger.
pub fn icon<I>(mut self, icon: I) -> Self
where
I: Into<Icon>,
{
self.icon = Some(icon.into());
self
}
/// Sets the button's visual language.
pub fn variant(mut self, variant: ButtonVariant) -> Self {
self.variant = variant;
self
}
/// Whether the trigger is a keyboard tab stop, dense toolbars turn it off.
pub fn tab_stop(mut self, tab_stop: bool) -> Self {
self.tab_stop = tab_stop;
self
}
/// Renders the trigger inert, unfocusable, and dimmed.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
/// Shows the spinner in place of the content and suppresses activation.
pub fn loading(mut self, loading: bool) -> Self {
self.loading = loading;
self
}
/// Sets the current open state.
pub fn open(mut self, open: bool) -> Self {
self.open = open;
self
}
/// Overrides the accessibility label, which defaults to the visible label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// The main zone's action. Without one, activating the button opens the menu.
pub fn on_click<F>(mut self, handler: F) -> Self
where
F: Fn(&ClickEvent, &mut Window, &mut App) + 'static,
{
self.on_click = Some(Box::new(handler));
self
}
/// Reports the menu's next open state.
pub fn on_open_change<F>(mut self, handler: F) -> Self
where
F: Fn(bool, &mut Window, &mut App) + 'static,
{
self.on_open_change = Some(Rc::new(handler));
self
}
/// Sets the menu's items, built fresh each render.
pub fn items<F>(mut self, items: F) -> Self
where
F: Fn(&mut Window, &mut App) -> Vec<MenuItem> + 'static,
{
self.items = Some(Box::new(items));
self
}
/// Sets the panel's minimum width, defaults to the standard menu width.
pub fn min_width<W>(mut self, width: W) -> Self
where
W: Into<DefiniteLength>,
{
self.min_width = Some(width.into());
self
}
}
impl Sizable for DropdownMenu {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl gpui::Styled for DropdownMenu {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for DropdownMenu {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
let metrics = theme.sizes.resolve(self.size);
let radius = theme.radius.control;
let ring = colors.ring;
let (panel_chrome, enter_duration) = MenuChrome::read(cx);
let (background, foreground, hover, pressed) = match self.variant {
ButtonVariant::Primary => (
Some(ramps.primary.base),
colors.primary_foreground,
ramps.primary.hover,
ramps.primary.pressed,
),
ButtonVariant::Secondary => (
Some(colors.surface),
colors.foreground,
colors.muted,
colors.muted_hover,
),
ButtonVariant::Ghost => (
None,
colors.foreground,
colors.muted_hover,
ramps.secondary.pressed,
),
ButtonVariant::Destructive => (
Some(ramps.destructive.base),
colors.destructive_foreground,
ramps.destructive.hover,
ramps.destructive.pressed,
),
};
let border = match self.variant {
ButtonVariant::Primary => ramps.primary.base,
ButtonVariant::Secondary => colors.border,
ButtonVariant::Ghost => gpui::transparent_black(),
ButtonVariant::Destructive => ramps.destructive.base,
};
let split = self.on_click.is_some();
let icon_only = self.icon.is_some() && self.label.is_none() && !split;
let inert = self.disabled || self.loading;
let label = self
.a11y_label
.clone()
.unwrap_or_else(|| SharedString::from(self.id.to_string()));
let a11y_label = self.a11y_label.or_else(|| self.label.clone());
let focus = focus_handle(&self.id, window, cx).tab_stop(self.tab_stop);
// How the menu was last opened, read by the frame that mounts the panel.
let keyboard_open =
window.use_keyed_state((self.id.clone(), "dropdown-open-origin"), cx, |_, _| false);
let on_open: ChangeHandler = {
let focus = focus.clone();
let on_open_change = self.on_open_change.clone();
let keyboard_open = keyboard_open.clone();
Rc::new(move |next, window, cx| {
if !next {
window.focus(&focus, cx);
keyboard_open.update(cx, |keyboard_open, _| *keyboard_open = false);
}
if let Some(on_open_change) = &on_open_change {
on_open_change(next, window, cx);
}
})
};
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))
.text_size(metrics.text_size)
.text_color(foreground)
.role(Role::Button)
.when_some(a11y_label, |zone, label| zone.aria_label(label))
.aria_expanded(self.open)
.px(if icon_only {
gpui::Pixels::ZERO
} else {
metrics.padding_x
})
.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(metrics.dense_icon_size)
.color(foreground),
)
})
.child(
h_flex()
.gap_2()
.when(self.loading, |content| content.invisible())
.when_some(self.icon, |content, icon| {
content.child(icon.size(metrics.icon_size).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)
.variant(crate::components::spinner::SpinnerVariant::Icon)
.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()
.px(metrics.dense_padding_x)
.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(metrics.dense_icon_size)
.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();
move || format!("{id}-trigger")
})
.h(metrics.control_height)
.when(icon_only, |trigger| trigger.w(metrics.control_height))
.rounded(radius)
.border_1()
.border_color(border)
.when_some(background, |trigger, background| trigger.bg(background))
.when(self.disabled, |trigger| trigger.opacity(DISABLED_OPACITY))
.when(!inert, |trigger| {
trigger
.track_focus(&focus)
.focus_visible(move |style| style.shadow(focus_ring(ring)))
})
.child(main);
let trigger = if split {
trigger.child(chevron_zone)
} else {
trigger
};
let items = if self.open {
self.items
.map(|build| Rc::from(build(window, cx)))
.unwrap_or_else(|| Rc::from([]))
} else {
Rc::from([])
};
let on_close = Some(on_open.clone());
let spec = MenuPanelSpec {
open: self.open,
items,
initial_selection: None,
preselect: *keyboard_open.read(cx),
min_width: self.min_width,
label,
position: None,
trigger_bounds: trigger_bounds.clone(),
on_dismiss: on_close.clone(),
on_activate: on_close,
};
div()
.relative()
.refine_style(&self.style)
.child(
canvas(
{
let cell = trigger_bounds.clone();
move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds)
},
{
let on_open = on_open.clone();
let trigger_bounds = trigger_bounds.clone();
let chevron_bounds = chevron_bounds.clone();
let keyboard_open = keyboard_open.clone();
let open = self.open;
move |_, _, window, _cx| {
window.on_mouse_event({
let on_open = on_open.clone();
let keyboard_open = keyboard_open.clone();
move |event: &MouseDownEvent, phase, window, cx| {
if phase != DispatchPhase::Bubble
|| event.button != MouseButton::Left
|| inert
{
return;
}
let in_trigger = trigger_bounds
.borrow()
.is_some_and(|bounds| bounds.contains(&event.position));
if !in_trigger {
return;
}
let in_chevron = chevron_bounds
.borrow()
.is_some_and(|bounds| bounds.contains(&event.position));
if !open && split && !in_chevron {
return;
}
keyboard_open
.update(cx, |keyboard_open, _| *keyboard_open = false);
on_open(!open, window, cx);
cx.stop_propagation();
}
});
}
},
)
.absolute()
.inset_0(),
)
.child(trigger)
.when_some(
anchored_menu_panel(window, cx, &self.id, spec, &panel_chrome, enter_duration),
|wrapper, panel| wrapper.child(panel),
)
}
}
+111
View File
@@ -0,0 +1,111 @@
use crate::icons::Icon;
use crate::theme::{ActiveTheme as _, Size, TextRole, Typeset as _};
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, IntoElement, ParentElement as _, RenderOnce, SharedString, StyleRefinement, Styled as _,
Window, div,
};
use crate::components::common::{StyledExt, v_flex};
/// The centered "nothing here yet" panel for lists, tables, and searches.
#[derive(IntoElement)]
#[must_use]
pub struct EmptyState {
icon: Option<Icon>,
headline: SharedString,
hint: Option<SharedString>,
action: Option<gpui::AnyElement>,
style: StyleRefinement,
}
impl EmptyState {
/// Creates an empty state whose headline is the primary statement.
pub fn new<L>(headline: L) -> Self
where
L: Into<SharedString>,
{
Self {
icon: None,
headline: headline.into(),
hint: None,
action: None,
style: StyleRefinement::default(),
}
}
/// Sets a large muted icon above the headline.
pub fn icon<I>(mut self, icon: I) -> Self
where
I: Into<Icon>,
{
self.icon = Some(icon.into());
self
}
/// Sets a secondary line under the headline.
pub fn hint<L>(mut self, hint: L) -> Self
where
L: Into<SharedString>,
{
self.hint = Some(hint.into());
self
}
/// Sets an action element — usually a button — under the hint.
pub fn action<E>(mut self, action: E) -> Self
where
E: IntoElement,
{
self.action = Some(action.into_any_element());
self
}
}
impl gpui::Styled for EmptyState {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for EmptyState {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let metrics = theme.sizes.resolve(Size::Medium);
let muted_foreground = theme.colors.muted_foreground;
let foreground = theme.colors.foreground;
let illustration = metrics.icon_size * 2.0;
v_flex()
.w_full()
.items_center()
.justify_center()
.text_center()
.p_4()
.when_some(self.icon, |state, icon| {
state.child(
div()
.mb_2()
.child(icon.size(illustration).color(muted_foreground)),
)
})
.child(
div()
.typeset(TextRole::Title3, cx)
.text_color(foreground)
.child(self.headline),
)
.when_some(self.hint, |state, hint| {
state.child(
div()
.typeset(TextRole::Subheadline, cx)
.text_color(muted_foreground)
.child(hint),
)
})
.when_some(self.action, |state, action| {
state.child(div().mt_3().child(action))
})
.refine_style(&self.style)
}
}
+181
View File
@@ -0,0 +1,181 @@
//! The field: a label, description, and error wrapped around a control.
use crate::theme::{ActiveTheme as _, TextRole, Typeset as _};
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, ElementId, InteractiveElement as _, IntoElement, ParentElement, RenderOnce,
Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Window, div,
};
use crate::components::common::{StyledExt, h_flex, v_flex};
/// The arrangement of a [`Field`]'s label and control.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FieldVariant {
/// The label block sits above the control, full width.
#[default]
Block,
/// The label block leads and the control trails — the settings row.
Row,
}
/// A labeled control: the label, description, and error around any element.
#[derive(IntoElement)]
#[must_use]
pub struct Field {
id: ElementId,
label: SharedString,
description: Option<SharedString>,
error: Option<SharedString>,
variant: FieldVariant,
control: Vec<AnyElement>,
style: StyleRefinement,
}
impl Field {
/// Creates a field naming its control.
pub fn new<I, L>(id: I, label: L) -> Self
where
I: Into<ElementId>,
L: Into<SharedString>,
{
Self {
id: id.into(),
label: label.into(),
description: None,
error: None,
variant: FieldVariant::default(),
control: Vec::new(),
style: StyleRefinement::default(),
}
}
/// The helper text under the label.
pub fn description<D>(mut self, description: D) -> Self
where
D: Into<SharedString>,
{
self.description = Some(description.into());
self
}
/// The error under the control; `None` clears it.
pub fn error<E>(mut self, error: Option<E>) -> Self
where
E: Into<SharedString>,
{
self.error = error.map(Into::into);
self
}
/// Sets the field's arrangement.
pub fn variant(mut self, variant: FieldVariant) -> Self {
self.variant = variant;
self
}
}
impl ParentElement for Field {
fn extend(&mut self, children: impl IntoIterator<Item = AnyElement>) {
self.control.extend(children);
}
}
impl Styled for Field {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for Field {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let metrics = theme.sizes.medium;
let error_color = theme.ramps.destructive.base;
let id = self.id.clone();
let title = div()
.debug_selector({
let id = id.clone();
move || format!("{id}-label")
})
.when(self.description.is_some(), |title| {
title.typeset(TextRole::Headline, cx)
})
.when(self.description.is_none(), |title| {
title.typeset(TextRole::Callout, cx)
})
.child(self.label.clone());
let control = h_flex()
.items_center()
.gap_2()
.debug_selector({
let id = id.clone();
move || format!("{id}-control")
})
.children(self.control);
let error = self.error.map(|error| {
div()
.debug_selector({
let id = id.clone();
move || format!("{id}-error")
})
.text_size(metrics.caption_size)
.text_color(error_color)
.child(error)
});
let description_text = |cx: &App| {
div()
.text_size(metrics.caption_size)
.text_color(cx.theme().colors.muted_foreground)
};
let content = if self.variant == FieldVariant::Row {
div()
.flex()
.flex_col()
.gap_1()
.child(
h_flex()
.items_center()
.justify_between()
.gap_4()
.child(title.flex_1().min_w_0())
.child(control.flex_none()),
)
.when_some(self.description.clone(), |field, description| {
field.child(description_text(cx).child(description))
})
.when_some(error, |field, error| field.child(error))
} else {
div()
.flex()
.flex_col()
.gap_2()
.child(
v_flex()
.gap_0p5()
.child(title)
.when_some(self.description.clone(), |slot, description| {
slot.child(description_text(cx).child(description))
}),
)
.child(control)
.when_some(error, |field, error| field.child(error))
};
div()
.id(self.id)
.w_full()
.role(Role::Group)
.aria_label(self.label.clone())
.when_some(self.description, |field, description| {
field.aria_description(description)
})
.refine_style(&self.style)
.child(content)
}
}
+90
View File
@@ -0,0 +1,90 @@
//! The grain: a film-noise overlay for material surfaces.
use std::sync::{Arc, OnceLock};
use crate::theme::GRAIN_ALPHA;
use crate::utils::ResultLogErr as _;
use gpui::{
App, Bounds, Corners, IntoElement, RenderImage, RenderOnce, Styled as _, Window, canvas, point,
px, size,
};
use image::{Frame, ImageBuffer, Rgba};
/// The side of one noise tile, in device pixels.
const TILE_PX: u32 = 256;
/// A film-grain overlay: tiled monochrome noise at [`GRAIN_ALPHA`] strength.
#[derive(IntoElement)]
#[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();
canvas(
|_, _, _| (),
move |bounds, (), window, _| {
let tile = px(TILE_PX as f32);
let columns = (bounds.size.width / tile).ceil() as u32;
let rows = (bounds.size.height / tile).ceil() as u32;
for row in 0..rows {
for column in 0..columns {
let x = bounds.origin.x + column as f32 * tile;
let y = bounds.origin.y + row as f32 * tile;
let tile_bounds = Bounds {
origin: point(x, y),
size: size(
tile.min(bounds.origin.x + bounds.size.width - x),
tile.min(bounds.origin.y + bounds.size.height - y),
),
};
window
.paint_image(
tile_bounds,
tile_bounds,
Corners::default(),
texture.clone(),
0,
false,
)
.log_err();
}
}
},
)
.absolute()
.inset_0()
}
}
/// The shared noise tile, every tile reuses its one atlas entry.
fn texture() -> Arc<RenderImage> {
static TEXTURE: OnceLock<Arc<RenderImage>> = OnceLock::new();
TEXTURE
.get_or_init(|| {
// An LCG keeps the grain deterministic across launches.
let mut state = 0x9E37_79B9_u32;
let mut noise = move || {
state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
(state >> 24) as u8
};
// The grays are noise samples, not palette colors.
let alpha = (GRAIN_ALPHA * 255.0) as u8;
Arc::new(RenderImage::new([Frame::new(ImageBuffer::from_fn(
TILE_PX,
TILE_PX,
|_, _| {
let gray = noise();
Rgba([gray, gray, gray, alpha])
},
))]))
})
.clone()
}
File diff suppressed because it is too large Load Diff
+139
View File
@@ -0,0 +1,139 @@
use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size};
use crate::utils::focus_ring;
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::{Sizable, StyledExt as _, h_flex};
/// The click handler. When set it replaces the default `href` opening.
type ClickHandler = Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>;
/// Link component.
#[derive(IntoElement)]
#[must_use]
pub struct Link {
id: ElementId,
label: Option<SharedString>,
href: Option<SharedString>,
size: Size,
disabled: bool,
a11y_label: Option<SharedString>,
on_click: Option<ClickHandler>,
style: StyleRefinement,
}
impl Link {
/// Creates a link without a label or target.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
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<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.label = Some(label.into());
self
}
/// Sets the URL the link opens through the platform.
pub fn href<U>(mut self, href: U) -> Self
where
U: Into<SharedString>,
{
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<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// Replaces the default `href` opening with this handler.
pub fn on_click<F>(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 metrics = theme.sizes.resolve(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)
.text_size(metrics.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))
}
}
File diff suppressed because it is too large Load Diff
+36
View File
@@ -0,0 +1,36 @@
//! The components every application needs.
pub mod alert;
pub mod avatar;
pub mod badge;
pub mod button;
pub mod checkbox;
pub mod clipboard;
pub mod combobox;
pub mod command_palette;
pub mod common;
pub mod context_menu;
pub mod dialog;
pub mod dropdown_menu;
pub mod empty_state;
pub mod field;
pub mod grain;
pub mod input;
pub mod link;
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 slider;
pub mod speech;
pub mod spinner;
pub mod status_dot;
pub mod switch;
pub mod toast;
pub mod toggle;
pub mod tooltip;
+244
View File
@@ -0,0 +1,244 @@
use std::cell::RefCell;
use std::rc::Rc;
use crate::theme::{ActiveTheme as _, POPOVER_MIN_WIDTH};
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,
};
use crate::components::common::{OVERLAY_LAYER, StyledExt as _, v_flex};
/// Reports the next open state of a [`Popover`]: `true` to open, `false` to close.
type ChangeHandler = Rc<dyn Fn(bool, &mut Window, &mut App)>;
type TriggerFn = Box<dyn FnOnce(&mut Window, &mut App) -> AnyElement>;
type ContentFn = Box<dyn FnOnce(&mut Window, &mut App) -> AnyElement>;
/// Bounds captured during the last paint, shared with the dismissal listener.
type BoundsCell = Rc<RefCell<Option<Bounds<Pixels>>>>;
/// A floating panel anchored below its trigger.
#[derive(IntoElement)]
#[must_use]
pub struct Popover {
id: ElementId,
open: bool,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler>,
trigger: Option<TriggerFn>,
content: Option<ContentFn>,
style: StyleRefinement,
}
impl Popover {
/// Creates a closed popover.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
open: false,
a11y_label: None,
on_change: None,
trigger: None,
content: None,
style: StyleRefinement::default(),
}
}
/// Sets the current open state.
pub fn open(mut self, open: bool) -> Self {
self.open = open;
self
}
/// Reports the next open state, from dismissals and app changes alike.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(bool, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Rc::new(handler));
self
}
/// Sets the element the panel anchors below, rendered in place.
pub fn trigger<F>(mut self, trigger: F) -> Self
where
F: FnOnce(&mut Window, &mut App) -> AnyElement + 'static,
{
self.trigger = Some(Box::new(trigger));
self
}
/// Sets the panel's contents.
pub fn content<F>(mut self, content: F) -> Self
where
F: FnOnce(&mut Window, &mut App) -> AnyElement + 'static,
{
self.content = Some(Box::new(content));
self
}
/// Overrides the accessibility label of the panel.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
impl gpui::Styled for Popover {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for Popover {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let (colors, radius, shadows, enter_duration, panel_border, anchor_gap) = {
let theme = cx.theme();
(
theme.colors,
theme.radius,
theme.elevations.popover.shadows(),
theme.motion.overlay,
theme.colors.border,
theme.spacing.unit,
)
};
let trigger_bounds: BoundsCell = Rc::new(RefCell::new(None));
let fallback_label = self
.a11y_label
.clone()
.unwrap_or_else(|| SharedString::from(self.id.to_string()));
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(),
)
.when_some(self.trigger, |wrapper, trigger| {
wrapper.child(trigger(window, cx))
})
.when(self.open, |wrapper| {
let on_change = self.on_change;
let label = fallback_label.clone();
let focus = crate::utils::focus_handle(&self.id, window, cx);
let content = self.content.map(|content| content(window, cx));
let panel = 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)
.bg(colors.surface)
.text_color(colors.surface_foreground)
.rounded(radius.overlay)
.border_1()
.border_color(panel_border)
.shadow(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" {
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);
}
}
})
.absolute()
.inset_0(),
);
wrapper.child(
deferred(anchored().offset(point(Pixels::ZERO, anchor_gap)).child(
panel.with_animation(
"popover-enter",
Animation::new(enter_duration).with_easing(ease_out_quint()),
|panel, delta| panel.opacity(delta),
),
))
.with_priority(OVERLAY_LAYER),
)
})
}
}
+124
View File
@@ -0,0 +1,124 @@
//! The progress bar: determinate fill or an indeterminate sweep.
use crate::theme::{ActiveTheme as _, PROGRESS_ANIMATION_PERIOD, Size};
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 _};
/// A progress bar. With a `value` in `0..=1` it paints a determinate fill.
#[derive(IntoElement)]
#[must_use]
pub struct Progress {
id: ElementId,
value: f32,
indeterminate: bool,
size: Size,
a11y_label: Option<SharedString>,
style: StyleRefinement,
}
impl Progress {
/// Creates a determinate progress bar at `value` (`0..=1`).
pub fn new<I>(id: I, value: f32) -> Self
where
I: Into<ElementId>,
{
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<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
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 metrics = theme.sizes.resolve(self.size);
let track_height = metrics.icon_size / 4.0;
let value = self.value.clamp(0.0, 1.0);
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(
div()
.w_full()
.h(track_height)
.rounded(radius.full)
.bg(colors.border)
.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()
}),
)
}
}
+242
View File
@@ -0,0 +1,242 @@
use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size};
use crate::utils::focus_ring;
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::{Sizable, StyledExt as _, h_flex, v_flex};
/// The group's change reporter, fired with the clicked radio's value.
type ChangeHandler<V> = std::rc::Rc<dyn Fn(V, &mut Window, &mut App)>;
/// Radio button.
///
/// 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<V> {
id: ElementId,
value: V,
label: Option<SharedString>,
disabled: bool,
a11y_label: Option<SharedString>,
}
impl<V> Radio<V>
where
V: Clone + PartialEq + 'static,
{
/// Creates a radio representing `value`.
pub fn new<I>(id: I, value: V) -> Self
where
I: Into<ElementId>,
{
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<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
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<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
// Radio is a data builder, not an element, adopt the combinators explicitly.
impl<V> FluentBuilder for Radio<V> {}
/// Group of radio buttons.
#[derive(IntoElement)]
#[must_use]
pub struct RadioGroup<V>
where
V: Clone + PartialEq + 'static,
{
id: ElementId,
selected: Option<V>,
children: Vec<Radio<V>>,
size: Size,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler<V>>,
style: StyleRefinement,
}
impl<V> RadioGroup<V>
where
V: Clone + PartialEq + 'static,
{
/// Creates an empty group with nothing selected.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
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<V>) -> Self {
self.selected = selected;
self
}
/// Adds a radio to the group.
pub fn child(mut self, radio: Radio<V>) -> Self {
self.children.push(radio);
self
}
/// Sets the group's accessibility label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// Sets the change handler.
pub fn on_change<F>(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<V> Sizable for RadioGroup<V>
where
V: Clone + PartialEq + 'static,
{
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl<V> gpui::Styled for RadioGroup<V>
where
V: Clone + PartialEq + 'static,
{
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl<V> RenderOnce for RadioGroup<V>
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 metrics = theme.sizes.resolve(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()
.text_size(metrics.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()
.size(metrics.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(
div()
.size(metrics.indicator_size / 2.0)
.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))
}))
}
}
+143
View File
@@ -0,0 +1,143 @@
//! A scrollable container with an overlay scrollbar.
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, ElementId, InteractiveElement as _, IntoElement, ParentElement, RenderOnce, ScrollHandle,
SharedString, StatefulInteractiveElement as _, Styled, Window, div,
};
use crate::components::common::StyledExt;
use crate::components::scrollbar::{Scrollbar, ScrollbarVisibility};
/// Which directions the content scrolls in.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum ScrollAxes {
/// Vertical only; the default.
#[default]
Vertical,
/// Horizontal only.
Horizontal,
/// Both directions.
Both,
}
/// A scrollable container with an overlay scrollbar.
#[derive(IntoElement)]
#[must_use]
pub struct ScrollArea {
id: ElementId,
handle: Option<ScrollHandle>,
axes: ScrollAxes,
visibility: ScrollbarVisibility,
a11y_label: Option<SharedString>,
style: gpui::StyleRefinement,
children: Vec<gpui::AnyElement>,
}
impl ParentElement for ScrollArea {
fn extend(&mut self, children: impl IntoIterator<Item = gpui::AnyElement>) {
self.children.extend(children);
}
}
impl Styled for ScrollArea {
fn style(&mut self) -> &mut gpui::StyleRefinement {
&mut self.style
}
}
impl ScrollArea {
/// Creates a vertically scrolling area.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
handle: None,
axes: ScrollAxes::Vertical,
visibility: ScrollbarVisibility::default(),
a11y_label: None,
style: gpui::StyleRefinement::default(),
children: Vec::new(),
}
}
/// Sets which directions the content scrolls in.
pub fn axes(mut self, axes: ScrollAxes) -> Self {
self.axes = axes;
self
}
/// Overrides when the scrollbar shows, instead of the platform default.
pub fn visibility(mut self, visibility: ScrollbarVisibility) -> Self {
self.visibility = visibility;
self
}
/// Scrolls with a handle held on the owning view.
pub fn handle(mut self, handle: ScrollHandle) -> Self {
self.handle = Some(handle);
self
}
/// Overrides the accessibility label of the container.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
impl RenderOnce for ScrollArea {
fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
let mut pane_style = self.style.clone();
pane_style.padding = Default::default();
let pane = div()
.id(self.id.clone())
.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())
.when_some(self.handle, |wrapper, handle| {
let id = self.id.clone();
wrapper
.when(self.axes != ScrollAxes::Horizontal, |wrapper| {
wrapper.child(
Scrollbar::vertical((id.clone(), "v-scrollbar"), handle.clone())
.visibility(self.visibility)
.into_any_element(),
)
})
.when(self.axes != ScrollAxes::Vertical, |wrapper| {
wrapper.child(
Scrollbar::horizontal((id, "h-scrollbar"), handle)
.visibility(self.visibility)
.into_any_element(),
)
})
})
}
}
+520
View File
@@ -0,0 +1,520 @@
//! Overlay scrollbars for scroll surfaces.
use std::rc::Rc;
use std::sync::Arc;
use std::time::{Duration, Instant};
use crate::theme::{ActiveTheme as _, SCROLLBAR_AUTOHIDE_DELAY, SCROLLBAR_FADE_DURATION};
use crate::utils::ResultLogErr as _;
use gpui::{
App, Bounds, DispatchPhase, ElementId, Entity, EntityId, IntoElement, ListState, MouseButton,
MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point, RenderOnce, ScrollEvent,
ScrollHandle, SharedString, Styled as _, Task, UniformListScrollHandle, Window, canvas, fill,
point,
};
/// When an overlay scrollbar shows.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ScrollbarVisibility {
/// The running platform's behavior, from the theme.
#[default]
Platform,
Always,
Autohide,
}
/// How often the autohide fade repaints while it runs.
const FADE_STEP: Duration = Duration::from_millis(50);
/// The shared autohide timeline for an overlay scrollbar.
#[derive(Clone)]
struct Autohide {
view: EntityId,
state: Entity<AutohideState>,
}
struct AutohideState {
last_activity: Option<Instant>,
hide_task: Option<Task<()>>,
}
impl Autohide {
fn new(key: ElementId, window: &mut Window, cx: &mut App) -> Self {
let view = window.current_view();
let state = window.use_keyed_state(key, cx, |_, _| AutohideState {
last_activity: None,
hide_task: None,
});
Self { view, state }
}
/// Marks interaction.
fn touch(&self, window: &mut Window, cx: &mut App) {
let view = self.view;
let reduce_motion = cx.theme().accessibility.reduce_motion;
let task = window.spawn(cx, async move |cx| {
if reduce_motion {
cx.background_executor()
.timer(SCROLLBAR_AUTOHIDE_DELAY + SCROLLBAR_FADE_DURATION)
.await;
cx.update(|_, cx| cx.notify(view)).log_err();
return;
}
let steps = (SCROLLBAR_FADE_DURATION.as_millis() / FADE_STEP.as_millis()).max(1);
cx.background_executor()
.timer(SCROLLBAR_AUTOHIDE_DELAY)
.await;
for _ in 0..steps {
cx.update(|_, cx| cx.notify(view)).log_err();
cx.background_executor().timer(FADE_STEP).await;
}
cx.update(|_, cx| cx.notify(view)).log_err();
});
self.state.update(cx, |state, _| {
state.last_activity = Some(Instant::now());
state.hide_task = Some(task);
});
}
/// The thumb's opacity.
fn alpha(&self, cx: &App, dragging: bool) -> f32 {
if dragging {
return 1.0;
}
let Some(activity) = self.state.read(cx).last_activity else {
return 0.0;
};
let idle = activity.elapsed();
if idle <= SCROLLBAR_AUTOHIDE_DELAY {
return 1.0;
}
let fade = idle.saturating_sub(SCROLLBAR_AUTOHIDE_DELAY);
if fade >= SCROLLBAR_FADE_DURATION {
return 0.0;
}
1.0 - fade.as_secs_f32() / SCROLLBAR_FADE_DURATION.as_secs_f32()
}
}
/// The scroll state a scrollbar drives, implemented for gpui's scroll handles.
pub trait ScrollbarHandle: 'static {
/// How far the content can scroll, positive along each axis.
fn max_offset(&self) -> Point<Pixels>;
/// The current offset, non-positive along each axis.
fn offset(&self) -> Point<Pixels>;
/// Applies the offset along one axis, keeping the other.
fn set_offset(&self, offset: Point<Pixels>);
/// The bounds of the scrolled surface.
fn viewport(&self) -> Bounds<Pixels>;
/// A thumb drag began.
fn drag_started(&self) {}
/// A thumb drag ended.
fn drag_ended(&self) {}
}
impl ScrollbarHandle for ScrollHandle {
fn max_offset(&self) -> Point<Pixels> {
ScrollHandle::max_offset(self)
}
fn offset(&self) -> Point<Pixels> {
ScrollHandle::offset(self)
}
fn set_offset(&self, offset: Point<Pixels>) {
ScrollHandle::set_offset(self, offset);
}
fn viewport(&self) -> Bounds<Pixels> {
self.bounds()
}
}
impl ScrollbarHandle for UniformListScrollHandle {
fn max_offset(&self) -> Point<Pixels> {
self.0.borrow().base_handle.max_offset()
}
fn offset(&self) -> Point<Pixels> {
self.0.borrow().base_handle.offset()
}
fn set_offset(&self, offset: Point<Pixels>) {
self.0.borrow().base_handle.set_offset(offset);
}
fn viewport(&self) -> Bounds<Pixels> {
self.0.borrow().base_handle.bounds()
}
}
impl ScrollbarHandle for ListState {
fn max_offset(&self) -> Point<Pixels> {
ListState::max_offset_for_scrollbar(self)
}
fn offset(&self) -> Point<Pixels> {
ListState::scroll_px_offset_for_scrollbar(self)
}
fn set_offset(&self, offset: Point<Pixels>) {
ListState::set_offset_from_scrollbar(self, offset);
}
fn viewport(&self) -> Bounds<Pixels> {
self.viewport_bounds()
}
fn drag_started(&self) {
ListState::scrollbar_drag_started(self);
}
fn drag_ended(&self) {
ListState::scrollbar_drag_ended(self);
}
}
/// Which direction the scrollbar lies along.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Axis {
Vertical,
Horizontal,
}
impl Axis {
fn along(self, position: Point<Pixels>) -> Pixels {
match self {
Axis::Vertical => position.y,
Axis::Horizontal => position.x,
}
}
fn with_along(self, position: Point<Pixels>, along: Pixels) -> Point<Pixels> {
match self {
Axis::Vertical => point(position.x, along),
Axis::Horizontal => point(along, position.y),
}
}
fn viewport_along(self, viewport: &Bounds<Pixels>) -> 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]
pub struct Scrollbar {
axis: Axis,
handle: Rc<dyn ScrollbarHandle>,
visibility: ScrollbarVisibility,
id: ElementId,
}
impl Scrollbar {
/// A vertical scrollbar named by `id`, driven by `handle`.
pub fn vertical<I, H>(id: I, handle: H) -> Self
where
I: Into<ElementId>,
H: ScrollbarHandle,
{
Self {
axis: Axis::Vertical,
handle: Rc::new(handle),
visibility: ScrollbarVisibility::default(),
id: id.into(),
}
}
/// A horizontal scrollbar named by `id`, driven by `handle`.
pub fn horizontal<I, H>(id: I, handle: H) -> Self
where
I: Into<ElementId>,
H: ScrollbarHandle,
{
Self {
axis: Axis::Horizontal,
handle: Rc::new(handle),
visibility: ScrollbarVisibility::default(),
id: id.into(),
}
}
/// Overrides when the scrollbar shows, instead of the platform default.
pub fn visibility(mut self, visibility: ScrollbarVisibility) -> Self {
self.visibility = visibility;
self
}
fn state_key(name: &'static str, id: &ElementId) -> ElementId {
ElementId::NamedChild(Arc::new(id.clone()), SharedString::from(name))
}
/// Pure thumb geometry for an overlay scrollbar.
fn thumb_geometry(
viewport: Pixels,
content: Pixels,
offset: Pixels,
track: Pixels,
min_thumb: Pixels,
) -> (Pixels, Pixels) {
if content <= viewport || content <= Pixels::ZERO {
return (track, Pixels::ZERO);
}
let length = (viewport / content * track).max(min_thumb).min(track);
let overflow = content - viewport;
let progress = (-offset / overflow).clamp(0., 1.);
let travel = track - length;
(length, travel * progress)
}
/// An overlay scrollbar thumb's style for one paint: `None` hides it.
fn thumb_style(color: gpui::Hsla, alpha: f32) -> Option<gpui::Hsla> {
(alpha > 0.0).then_some(gpui::Hsla {
a: color.a * alpha,
..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<dyn ScrollbarHandle>,
axis: Axis,
visibility: ScrollbarVisibility,
id: &ElementId,
window: &mut Window,
cx: &mut App,
) {
let view = window.current_view();
let theme = cx.theme();
let color = theme.colors.scrollbar_thumb;
let width = theme.scrollbar.width;
let inset = theme.scrollbar.inset;
let min_thumb = theme.scrollbar.min_thumb;
let viewport = handle.viewport();
let viewport_along = axis.viewport_along(&viewport);
let max_offset = axis.along(handle.max_offset());
if max_offset <= Pixels::ZERO || viewport_along <= Pixels::ZERO {
return;
}
let autohide = match visibility {
ScrollbarVisibility::Platform => theme.scrollbar.autohide,
ScrollbarVisibility::Always => false,
ScrollbarVisibility::Autohide => true,
};
let autohide_state =
autohide.then(|| Autohide::new(Self::state_key("autohide", id), window, cx));
let track_length = viewport_along - inset * 2.0;
let (thumb_length, thumb_travel) = Self::thumb_geometry(
viewport_along,
viewport_along + max_offset,
axis.along(handle.offset()),
track_length,
min_thumb,
);
// The track strip is the thumb's rail plus the padding the thumb rides inside.
let (thumb_bounds, track_bounds) = match axis {
Axis::Vertical => {
let thumb_x = viewport.right() - width - inset;
(
Bounds::from_corners(
point(thumb_x, viewport.top() + inset + thumb_travel),
point(
thumb_x + width,
viewport.top() + inset + thumb_travel + thumb_length,
),
),
Bounds::from_corners(
point(viewport.right() - width, viewport.top() + inset),
point(viewport.right(), viewport.top() + inset + track_length),
),
)
}
Axis::Horizontal => {
let thumb_y = viewport.bottom() - width - inset;
(
Bounds::from_corners(
point(viewport.left() + inset + thumb_travel, thumb_y),
point(
viewport.left() + inset + thumb_travel + thumb_length,
thumb_y + width,
),
),
Bounds::from_corners(
point(viewport.left() + inset, viewport.bottom() - width),
point(viewport.left() + inset + track_length, viewport.bottom()),
),
)
}
};
let drag = window.use_keyed_state(Self::state_key("thumb-drag", id), cx, |_, _| Drag::None);
let dragging = drag.read(cx).is_some();
let alpha = match &autohide_state {
Some(state) => state.alpha(cx, dragging),
None => 1.0,
};
if let Some(color) = Self::thumb_style(color, alpha) {
window.paint_quad(fill(thumb_bounds, color).corner_radii(width / 2.0));
}
if let Some(state) = &autohide_state {
window.on_mouse_event({
let state = state.clone();
move |event: &ScrollEvent, phase, window, cx| {
if phase != DispatchPhase::Bubble || !viewport.contains(&event.position) {
return;
}
state.touch(window, cx);
}
});
}
window.on_mouse_event({
let handle = handle.clone();
let drag = drag.clone();
let autohide_state = autohide_state.clone();
move |event: &MouseDownEvent, phase, window, cx| {
if phase != DispatchPhase::Bubble || event.button != MouseButton::Left {
return;
}
let in_thumb = thumb_bounds.contains(&event.position);
let in_track = !in_thumb && track_bounds.contains(&event.position);
if !in_thumb && !in_track {
return;
}
let start_offset = if in_thumb {
axis.along(handle.offset())
} else if track_length > thumb_length {
let thumb_start = ((axis.along(event.position)
- axis.along(track_bounds.origin))
- thumb_length / 2.0)
.clamp(Pixels::ZERO, track_length - thumb_length);
let offset = -(thumb_start / (track_length - thumb_length)) * max_offset;
handle.set_offset(axis.with_along(handle.offset(), offset));
cx.notify(view);
offset
} else {
return;
};
drag.update(cx, |drag, _| {
*drag = Some((axis.along(event.position), start_offset));
});
handle.drag_started();
if let Some(state) = &autohide_state {
state.touch(window, cx);
}
cx.stop_propagation();
}
});
window.on_mouse_event({
let handle = handle.clone();
let drag = drag.clone();
let autohide_state = autohide_state.clone();
move |event: &MouseMoveEvent, phase, window, cx| {
if phase != DispatchPhase::Bubble {
return;
}
if let Some(state) = &autohide_state
&& track_bounds.contains(&event.position)
&& drag.read(cx).is_none()
{
state.touch(window, cx);
}
if event.pressed_button != Some(MouseButton::Left) {
return;
}
let Some((start_position, start_offset)) = *drag.read(cx) else {
return;
};
if track_length <= thumb_length {
return;
}
let scale = max_offset / (track_length - thumb_length);
let offset = (start_offset - (axis.along(event.position) - start_position) * scale)
.clamp(-max_offset, Pixels::ZERO);
handle.set_offset(axis.with_along(handle.offset(), offset));
cx.notify(view);
}
});
window.on_mouse_event({
let handle = handle.clone();
let drag = drag.clone();
let autohide_state = autohide_state.clone();
move |event: &MouseUpEvent, phase, window, cx| {
if phase != DispatchPhase::Bubble || event.button != MouseButton::Left {
return;
}
if drag.read(cx).is_none() {
return;
}
drag.update(cx, |drag, _| {
*drag = None;
});
handle.drag_ended();
// Unfreezing a ListState's height can change the thumb's geometry.
cx.notify(view);
if let Some(state) = &autohide_state {
state.touch(window, cx);
}
}
});
}
}
+358
View File
@@ -0,0 +1,358 @@
use std::rc::Rc;
use crate::icons::Icon;
use crate::theme::{ActiveTheme as _, CONTROL_SPRING, Size};
use crate::utils::{focus_handle, focus_ring};
use gpui::prelude::FluentBuilder;
use gpui::{
AnimationExt as _, App, Bounds, ElementId, Entity, InteractiveElement as _, IntoElement,
KeyDownEvent, ParentElement as _, Point, RenderOnce, Role, SharedString, SpringAnimation,
StatefulInteractiveElement as _, StyleRefinement, Styled as _, Toggled, Window, canvas, div,
};
use crate::components::common::{Sizable, StyledExt, h_flex};
/// Reports the segment the user chose.
type ChangeHandler<T> = Rc<dyn Fn(T, &mut Window, &mut App)>;
/// Segment option for a segmented control.
#[derive(Clone)]
#[must_use]
pub struct SegmentedOption<T> {
value: T,
label: SharedString,
icon: Option<Icon>,
}
impl<T> SegmentedOption<T> {
/// Creates a choice showing `label`; picking it reports `value`.
pub fn new<L>(value: T, label: L) -> Self
where
L: Into<SharedString>,
{
Self {
value,
label: label.into(),
icon: None,
}
}
/// Sets a leading icon for the segment.
pub fn icon<I>(mut self, icon: I) -> Self
where
I: Into<Icon>,
{
self.icon = Some(icon.into());
self
}
}
impl<T, L> From<(T, L)> for SegmentedOption<T>
where
L: Into<SharedString>,
{
fn from((value, label): (T, L)) -> Self {
Self {
value,
label: label.into(),
icon: None,
}
}
}
// SegmentedOption is a data builder, not an element, adopt the combinators explicitly.
impl<T> FluentBuilder for SegmentedOption<T> {}
/// A pill strip of mutually exclusive choices.
#[derive(IntoElement)]
#[must_use]
pub struct Segmented<T>
where
T: Clone + PartialEq + 'static,
{
id: ElementId,
/// Shared with the per-segment and key handlers, so captures are bumps.
options: Rc<[SegmentedOption<T>]>,
selected: T,
a11y_label: Option<SharedString>,
size: Size,
style: StyleRefinement,
on_change: Option<ChangeHandler<T>>,
}
impl<T> Segmented<T>
where
T: Clone + PartialEq + 'static,
{
pub fn new<I>(id: I, selected: T) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
options: Rc::from([]),
selected,
a11y_label: None,
size: Size::Small,
style: StyleRefinement::default(),
on_change: None,
}
}
/// Sets the choices.
pub fn options<I>(mut self, options: I) -> Self
where
I: IntoIterator,
I::Item: Into<SegmentedOption<T>>,
{
self.options = options.into_iter().map(Into::into).collect();
self
}
/// Reports the segment chosen, by pointer or by arrow.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(T, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Rc::new(handler));
self
}
/// Overrides the strip's accessibility label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
impl<T> Sizable for Segmented<T>
where
T: Clone + PartialEq + 'static,
{
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl<T> gpui::Styled for Segmented<T>
where
T: Clone + PartialEq + 'static,
{
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl<T> RenderOnce for Segmented<T>
where
T: Clone + PartialEq + 'static,
{
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let metrics = theme.sizes.resolve(self.size);
let muted = theme.colors.muted;
let surface = theme.colors.surface;
let foreground = theme.colors.foreground;
let muted_foreground = theme.colors.muted_foreground;
let ring = theme.colors.ring;
let radius = theme.radius.full;
let plate_shadow = theme.elevations.control.shadows();
let track_height = metrics.strip_height;
let track_inset = metrics.plate_inset;
let horizontal_padding = metrics.dense_padding_x;
let text_size = metrics.text_size;
let icon_size = metrics.icon_size;
let selected_index = self
.options
.iter()
.position(|segment| segment.value == self.selected);
let option_count = self.options.len();
let on_change = self.on_change.clone();
let key_on_change = on_change.clone();
let key_options = self.options.clone();
let options = self.options.clone();
let label = self
.a11y_label
.clone()
.unwrap_or_else(|| SharedString::from(self.id.to_string()));
window.with_element_namespace(self.id.clone(), |window| {
let geometry: Entity<Vec<Option<Bounds<gpui::Pixels>>>> =
window.use_keyed_state("segmented-geometry", cx, |_, _| Vec::new());
let track_origin: Entity<Option<Point<gpui::Pixels>>> =
window.use_keyed_state("segmented-track-origin", cx, |_, _| None);
let focus = focus_handle(&self.id, window, cx);
let track_point = *track_origin.read(cx);
let plate_target = geometry
.read(cx)
.get(selected_index.unwrap_or(usize::MAX))
.copied()
.flatten()
.zip(track_point)
.map(|(bounds, track)| (bounds.origin.x - track.x, bounds.size.width));
let segments = self
.options
.iter()
.enumerate()
.map(move |(index, segment)| {
let is_selected = Some(index) == selected_index;
let on_change = on_change.clone();
let options = options.clone();
let content_color = if is_selected {
foreground
} else {
muted_foreground
};
h_flex()
.id((ElementId::from("segment"), segment.label.clone()))
.gap_2()
.justify_center()
.cursor_pointer()
.h_full()
.px(horizontal_padding)
.rounded(radius)
.text_size(text_size)
.text_color(content_color)
.when(!is_selected, |segment| {
segment.hover(|style| style.bg(surface))
})
.role(Role::RadioButton)
.aria_label(segment.label.clone())
.aria_toggled(Toggled::from(is_selected))
.when_some(segment.icon.clone(), |segment, icon| {
segment.child(icon.size(icon_size).color(content_color))
})
.child(segment.label.clone())
.child(
canvas(
{
let geometry = geometry.clone();
move |bounds, _, cx| {
geometry.update(cx, |geometry, _| {
if geometry.len() <= index {
geometry.resize(index + 1, None);
}
geometry[index] = Some(bounds);
});
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0(),
)
.on_click({
move |_, window, cx| {
if Some(index) != selected_index
&& let Some(on_change) = &on_change
&& let Some(option) = options.get(index)
{
on_change(option.value.clone(), window, cx);
}
}
})
});
div().child(
div()
.id(self.id.clone())
.track_focus(&focus)
.focusable()
.tab_stop(true)
.focus_visible(|style| style.shadow(focus_ring(ring)))
.role(Role::RadioGroup)
.aria_label(label)
.flex()
.items_center()
.gap_1()
.relative()
.flex_none()
.h(track_height)
.p(track_inset)
.rounded(radius)
.bg(muted)
.text_size(metrics.text_size)
.child(
canvas(
{
let track_origin = track_origin.clone();
move |bounds, _, cx| {
track_origin
.update(cx, |origin, _| *origin = Some(bounds.origin));
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0(),
)
.when_some(plate_target, |track, (x, width)| {
track.child(
div()
.id("segmented-plate")
.debug_selector(|| "segmented-plate".to_string())
.absolute()
.top(track_inset)
.bottom(track_inset)
.rounded(radius)
.bg(surface)
.shadow(plate_shadow.clone())
.with_spring(
"segmented-plate-x",
SpringAnimation::new(CONTROL_SPRING).to(x),
|plate, x| plate.left(x),
)
.with_spring(
"segmented-plate-w",
SpringAnimation::new(CONTROL_SPRING).to(width),
|spring_plate, width| {
spring_plate.map_element(move |plate| plate.w(width))
},
),
)
})
.on_key_down({
move |event: &KeyDownEvent, window, cx| {
let target = match event.keystroke.key.as_str() {
"right" => match selected_index {
Some(index) => {
index.checked_add(1).filter(|next| *next < option_count)
}
None => (option_count > 0).then_some(0),
},
"left" => selected_index.and_then(|index| index.checked_sub(1)),
"home" => (option_count > 0).then_some(0),
"end" => option_count.checked_sub(1),
_ => return,
};
if let Some(next) = target
&& Some(next) != selected_index
&& let Some(on_change) = &key_on_change
&& let Some(option) = key_options.get(next)
{
on_change(option.value.clone(), window, cx);
}
cx.stop_propagation();
}
})
.children(segments)
.refine_style(&self.style),
)
})
}
}
+348
View File
@@ -0,0 +1,348 @@
use std::rc::Rc;
use crate::icons::{Icon, IconRole, icon};
use crate::theme::{ActiveTheme as _, Size};
use crate::utils::focus_handle;
use gpui::prelude::FluentBuilder;
use gpui::{
App, ElementId, InteractiveElement as _, IntoElement, KeyDownEvent, ParentElement as _,
RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _,
Window, canvas,
};
use crate::components::common::{Sizable, StyledExt, h_flex};
use crate::components::menu::{Menu, MenuItem};
/// Reports the value the user chose. `None` means the select holds no value.
pub type SelectHandler<T> = Rc<dyn Fn(Option<T>, &mut Window, &mut App)>;
/// Select option for a [`Select`] control.
#[derive(Clone)]
#[must_use]
pub struct SelectOption<T> {
value: T,
label: SharedString,
icon: Option<Icon>,
}
impl<T> SelectOption<T> {
/// Creates a choice showing `label`; picking it reports `value`.
pub fn new<L>(value: T, label: L) -> Self
where
L: Into<SharedString>,
{
Self {
value,
label: label.into(),
icon: None,
}
}
/// Sets a leading icon for the option's row.
pub fn icon<I>(mut self, icon: I) -> Self
where
I: Into<Icon>,
{
self.icon = Some(icon.into());
self
}
}
impl<T, L> From<(T, L)> for SelectOption<T>
where
L: Into<SharedString>,
{
fn from((value, label): (T, L)) -> Self {
Self {
value,
label: label.into(),
icon: None,
}
}
}
// SelectOption is a data builder, not an element, adopt the combinators explicitly.
impl<T> FluentBuilder for SelectOption<T> {}
/// A control that shows the chosen value and opens a menu of the choices.
#[derive(IntoElement)]
#[must_use]
pub struct Select<T>
where
T: Clone + PartialEq + 'static,
{
id: ElementId,
options: Vec<SelectOption<T>>,
selected: Option<T>,
placeholder: SharedString,
a11y_label: Option<SharedString>,
size: Size,
style: StyleRefinement,
on_change: Option<SelectHandler<T>>,
}
impl<T> Select<T>
where
T: Clone + PartialEq + 'static,
{
/// Creates a closed select holding no value.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
options: Vec::new(),
selected: None,
placeholder: SharedString::from("Select..."),
a11y_label: None,
size: Size::default(),
style: StyleRefinement::default(),
on_change: None,
}
}
/// Sets the choice.
pub fn options<I>(mut self, options: I) -> Self
where
I: IntoIterator,
I::Item: Into<SelectOption<T>>,
{
self.options = options.into_iter().map(Into::into).collect();
self
}
/// Sets the current value. `None` shows the placeholder.
pub fn selected<S>(mut self, selected: S) -> Self
where
S: Into<Option<T>>,
{
self.selected = selected.into();
self
}
/// Sets the text shown while no value is chosen.
pub fn placeholder<L>(mut self, placeholder: L) -> Self
where
L: Into<SharedString>,
{
self.placeholder = placeholder.into();
self
}
/// Reports the chosen value, when the user activates an option.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(Option<T>, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Rc::new(handler));
self
}
/// Overrides the trigger's accessibility label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
impl<T> Sizable for Select<T>
where
T: Clone + PartialEq + 'static,
{
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl<T> gpui::Styled for Select<T>
where
T: Clone + PartialEq + 'static,
{
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl<T> RenderOnce for Select<T>
where
T: Clone + PartialEq + 'static,
{
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let metrics = theme.sizes.resolve(self.size);
let border = theme.colors.border;
let ring = theme.colors.ring;
let input = theme.colors.input;
let muted = theme.colors.muted;
let foreground = theme.colors.foreground;
let muted_foreground = theme.colors.muted_foreground;
let radius = theme.radius.control;
let icon_size = metrics.dense_icon_size;
let label = self
.a11y_label
.clone()
.unwrap_or_else(|| self.placeholder.clone());
let open = window.with_element_namespace(self.id.clone(), |window| {
window
.use_keyed_state("select-open", cx, |_, _| false)
.clone()
});
let focus = focus_handle(&self.id, window, cx);
// Set when the popup closes without an activation; the trigger claims
// focus at paint, leaving keyboard activations to drop focus in place.
let refocus_pending = window.with_element_namespace(self.id.clone(), |window| {
window
.use_keyed_state("select-refocus", cx, |_, _| false)
.clone()
});
let is_open = *open.read(cx);
let open_for_items = open.clone();
let rest_border = if is_open { ring } else { border };
let hover_border = rest_border;
let selected_index = self.selected.as_ref().and_then(|value| {
self.options
.iter()
.position(|option| &option.value == value)
});
// The trigger's text is fixed at render time; only it moves into the closure.
let trigger_text = selected_index
.and_then(|index| self.options.get(index))
.map(|option| option.label.clone())
.unwrap_or_else(|| self.placeholder.clone());
let trigger_has_value = self.selected.is_some();
let trigger_id = self.id.clone();
let trigger_label = label.clone();
let trigger_style = self.style;
let trigger = {
let open = open.clone();
let focus = focus.clone();
let refocus_for_trigger = refocus_pending.clone();
move |_window: &mut Window, _cx: &mut App| {
h_flex()
.id((trigger_id.clone(), "select-trigger"))
.debug_selector(|| "select-trigger".to_string())
.role(Role::ComboBox)
.aria_label(trigger_label.clone())
.aria_expanded(is_open)
.track_focus(&focus)
.tab_stop(true)
.focus_visible(move |style| style.border_color(ring))
.on_key_down({
let open = open.clone();
move |event: &KeyDownEvent, _window, cx| {
if !matches!(event.keystroke.key.as_str(), "enter" | "space") {
return;
}
open.update(cx, |open, _| *open = !*open);
cx.stop_propagation();
}
})
.cursor_pointer()
.justify_between()
.gap_3()
.w_full()
.h(metrics.input_height)
.pl(metrics.dense_padding_x)
.pr(metrics.plate_inset * 2.0)
.rounded(radius)
.border_1()
.border_color(rest_border)
.bg(input)
.text_size(metrics.text_size)
.text_color(if trigger_has_value {
foreground
} else {
muted_foreground
})
.hover(|style| style.bg(muted).border_color(hover_border))
.child(trigger_text.clone())
.child(
icon(IconRole::ChevronDown)
.size(icon_size)
.color(muted_foreground),
)
.child(
canvas(|_, _, _| {}, {
let focus = focus.clone();
let refocus_pending = refocus_for_trigger.clone();
move |_, _, window, cx| {
if *refocus_pending.read(cx) {
refocus_pending.update(cx, |pending, _| *pending = false);
window.focus(&focus, cx);
}
}
})
.absolute()
.inset_0(),
)
.refine_style(&trigger_style)
.into_any_element()
}
};
let select_id = self.id.clone();
let refocus_for_items = refocus_pending.clone();
let items = move |_window: &mut Window, _cx: &mut App| {
self.options
.iter()
.enumerate()
.map(|(index, option)| {
let is_selected = self.selected.as_ref() == Some(&option.value);
let handler = {
let open = open_for_items.clone();
let refocus_pending = refocus_for_items.clone();
let value = option.value.clone();
let on_change = self.on_change.clone();
move |window: &mut Window, cx: &mut App| {
open.update(cx, |open, _| *open = false);
// Activations own the close, so no focus returns to the trigger.
refocus_pending.update(cx, |pending, _| *pending = false);
if let Some(on_change) = &on_change {
on_change(Some(value.clone()), window, cx);
}
}
};
MenuItem::new(option.label.clone())
.id((select_id.clone(), format!("option-{index}")))
.when_some(option.icon.clone(), |row, icon| row.icon(icon))
.checked(is_selected)
.handler(handler)
})
.collect()
};
let menu = Menu::new(self.id)
.open(is_open)
.on_change({
let open = open.clone();
let refocus_pending = refocus_pending.clone();
move |next, _window, cx| {
if !next {
refocus_pending.update(cx, |pending, _| *pending = true);
}
open.update(cx, |open, _| *open = next);
}
})
.trigger(trigger)
.items(items);
menu.when_some(selected_index, |menu, index| menu.initial_selection(index))
}
}
+91
View File
@@ -0,0 +1,91 @@
//! The separator: a hairline rule between sibling content.
use std::rc::Rc;
use crate::theme::{ActiveTheme as _, BORDER_WIDTH};
use crate::utils::StyledExt as _;
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, InteractiveElement as _, IntoElement, RenderOnce, StyleRefinement, Styled as _, Window,
div,
};
/// Which axis the rule runs along.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SeparatorOrientation {
/// A horizontal rule between stacked content.
#[default]
Horizontal,
/// A vertical rule between side-by-side content.
Vertical,
}
type DebugSelector = Rc<dyn Fn() -> String>;
/// A hairline rule that divides sibling content.
#[derive(IntoElement)]
#[must_use]
pub struct Separator {
orientation: SeparatorOrientation,
debug_selector: Option<DebugSelector>,
style: StyleRefinement,
}
impl Separator {
/// Creates a horizontal rule.
pub fn horizontal() -> Self {
Self {
orientation: SeparatorOrientation::Horizontal,
debug_selector: None,
style: StyleRefinement::default(),
}
}
/// Creates a vertical rule.
pub fn vertical() -> Self {
Self {
orientation: SeparatorOrientation::Vertical,
debug_selector: None,
style: StyleRefinement::default(),
}
}
/// Sets which axis the rule runs along.
pub fn orientation(mut self, orientation: SeparatorOrientation) -> Self {
self.orientation = orientation;
self
}
/// Sets the debug-bounds selector, for headless tests.
pub fn debug_selector<F>(mut self, selector: F) -> Self
where
F: Fn() -> String + 'static,
{
self.debug_selector = Some(Rc::new(selector));
self
}
}
impl gpui::Styled for Separator {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for Separator {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let border = cx.theme().colors.border;
div()
.flex_none()
.bg(border)
.when_some(self.debug_selector, |rule, selector| {
rule.debug_selector(move || selector())
})
.map(|rule| match self.orientation {
SeparatorOrientation::Horizontal => rule.w_full().h(BORDER_WIDTH),
SeparatorOrientation::Vertical => rule.self_stretch().w(BORDER_WIDTH),
})
.refine_style(&self.style)
}
}
+312
View File
@@ -0,0 +1,312 @@
use std::cell::Cell;
use std::rc::Rc;
use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size};
use crate::utils::focus_ring;
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 _, h_flex};
/// The change reporter, fired with the next value by click, drag, and arrows.
type ChangeHandler = Rc<dyn Fn(f32, &mut Window, &mut App)>;
/// The pointer→value setter shared by the click and drag listeners.
type ValueSetter = Rc<dyn Fn(Pixels, &mut Window, &mut App)>;
/// 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<SharedString>,
on_change: Option<ChangeHandler>,
style: StyleRefinement,
}
impl Slider {
/// Creates a slider over `0..=1` with no stepping, at `value`.
pub fn new<I>(id: I, value: f32) -> Self
where
I: Into<ElementId>,
{
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<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// The change handler, fired with the next value by click, drag, and arrows.
pub fn on_change<F>(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 metrics = theme.sizes.resolve(self.size);
let row_height = metrics.icon_size * 2.5;
let track_height = metrics.icon_size / 4.0;
let knob = metrics.indicator_size;
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::<Bounds<Pixels>>));
let focus_handle = crate::utils::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()
.h(row_height)
.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)
.h(track_height)
.w_full()
.rounded(radius.full)
.bg(colors.border),
)
.child(
div()
.absolute()
.left_0()
.top((row_height - track_height) / 2.0)
.h(track_height)
.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()
.size(knob)
.flex_none()
.rounded(radius.full)
.bg(colors.primary_foreground)
.border_1()
.border_color(colors.border)
.mr(-knob / 2.0),
),
)
}
}
File diff suppressed because it is too large Load Diff
+299
View File
@@ -0,0 +1,299 @@
//! The loading ring: spins for unknown work, or holds a determinate arc.
use std::cell::Cell;
use std::f32::consts::{PI, TAU};
use std::rc::Rc;
use crate::icons::{Icon, IconRole, icon};
use crate::theme::{ActiveTheme as _, SPINNER_PERIOD, Size};
use gpui::prelude::FluentBuilder as _;
use gpui::{
Animation, AnimationElement, AnimationExt as _, App, Canvas, ElementId, Hsla,
InteractiveElement as _, IntoElement, ParentElement as _, Path, PathBuilder, Pixels, Point,
RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _,
Window, canvas, div, point, px,
};
use crate::components::common::{Sizable, StyledExt as _};
/// The share of the circle the spinning arc paints.
const SPIN_SWEEP: f32 = 0.75;
/// The ring stroke as a share of the side.
const RING_STROKE: f32 = 0.125;
/// The visual language of a [`Spinner`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SpinnerVariant {
/// The painted arc ring.
#[default]
Ring,
/// The platform loader glyph, rotated.
Icon,
}
/// A loading ring.
#[derive(IntoElement)]
#[must_use]
pub struct Spinner {
id: ElementId,
value: Option<f32>,
variant: SpinnerVariant,
size: Size,
color: Option<Hsla>,
a11y_label: Option<SharedString>,
style: StyleRefinement,
}
impl Spinner {
/// Creates a spinning ring.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
value: None,
variant: SpinnerVariant::default(),
size: Size::default(),
color: None,
a11y_label: None,
style: StyleRefinement::default(),
}
}
/// Overrides the arc color, for accent-filled surfaces.
pub fn color(mut self, color: Hsla) -> Self {
self.color = Some(color);
self
}
/// Sets the spinner's visual language.
pub fn variant(mut self, variant: SpinnerVariant) -> Self {
self.variant = variant;
self
}
/// Paints a determinate arc at `value` (`0..=1`) instead of spinning.
pub fn value(mut self, value: f32) -> Self {
self.value = Some(value);
self
}
/// Sets the accessibility label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
impl gpui::Styled for Spinner {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl Sizable for Spinner {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl RenderOnce for Spinner {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let side = theme.sizes.resolve(self.size).icon_size;
let stroke = side * RING_STROKE;
let track = theme.colors.border;
let accent = self.color.unwrap_or(theme.ramps.primary.base);
let value = self.value.map(|value| value.clamp(0.0, 1.0));
div()
.id(self.id)
.flex_none()
.size(side)
.refine_style(&self.style)
.role(Role::ProgressIndicator)
.when_some(self.a11y_label, |spinner, label| spinner.aria_label(label))
.when_some(value, |spinner, value| {
spinner
.aria_numeric_value(f64::from(value))
.aria_min_numeric_value(0.0)
.aria_max_numeric_value(1.0)
})
.child(match (self.variant, value) {
(SpinnerVariant::Ring, Some(value)) => {
determinate_ring(side, stroke, track, accent, value).into_any_element()
}
(SpinnerVariant::Ring, None) => {
spinning_ring(side, stroke, accent).into_any_element()
}
(SpinnerVariant::Icon, Some(_)) => icon(IconRole::Loader)
.size(side)
.color(accent)
.into_any_element(),
(SpinnerVariant::Icon, None) => spinning_icon(side, accent).into_any_element(),
})
}
}
fn determinate_ring(
side: Pixels,
stroke: Pixels,
track: Hsla,
accent: Hsla,
value: f32,
) -> Canvas<()> {
canvas(
|_, _, _| (),
move |bounds, (), window, _| {
let center = bounds.center();
let radius = bounds.size.width / 2.0 - stroke / 2.0;
paint_circle(center, radius, stroke, track, window);
if value >= 1.0 {
paint_circle(center, radius, stroke, accent, window);
} else if value > 0.0
&& let Some(path) = arc_path(center, radius, stroke, 0.0, value * TAU)
{
window.paint_path(path, accent);
}
},
)
.size(side)
}
fn spinning_ring(side: Pixels, stroke: Pixels, accent: Hsla) -> AnimationElement<Canvas<()>> {
let angle = Rc::new(Cell::new(0.0));
let spun = angle.clone();
canvas(
|_, _, _| (),
move |bounds, (), window, _| {
let radius = bounds.size.width / 2.0 - stroke / 2.0;
if let Some(path) = arc_path(
bounds.center(),
radius,
stroke,
spun.get(),
SPIN_SWEEP * TAU,
) {
window.paint_path(path, accent);
}
},
)
.size(side)
.with_animation(
"spin",
Animation::new(SPINNER_PERIOD).repeat().with_max_fps(60.),
move |ring, delta| {
angle.set(delta * TAU);
ring
},
)
}
fn spinning_icon(side: Pixels, accent: Hsla) -> Icon {
icon(IconRole::Loader)
.size(side)
.color(accent)
.with_rotation_animation(SPINNER_PERIOD)
}
fn paint_circle(
center: Point<Pixels>,
radius: Pixels,
stroke: Pixels,
color: Hsla,
window: &mut Window,
) {
if let Some(path) = circle_path(center, radius, stroke) {
window.paint_path(path, color);
}
}
/// A point on the ring at `angle`, clockwise from 12 o'clock.
fn ring_point(center: Point<Pixels>, radius: Pixels, angle: f32) -> Point<Pixels> {
point(
center.x + radius * angle.sin(),
center.y - radius * angle.cos(),
)
}
/// A stroked arc from `start`, sweeping clockwise by `sweep` radians.
fn arc_path(
center: Point<Pixels>,
radius: Pixels,
stroke: Pixels,
start: f32,
sweep: f32,
) -> Option<Path> {
let mut builder = PathBuilder::stroke(stroke);
builder.move_to(ring_point(center, radius, start));
builder.arc_to(
point(radius, radius),
px(0.),
sweep > PI,
true,
ring_point(center, radius, start + sweep),
);
builder.build().ok()
}
/// A stroked full circle; `None` on degenerate geometry.
fn circle_path(center: Point<Pixels>, radius: Pixels, stroke: Pixels) -> Option<Path> {
let mut builder = PathBuilder::stroke(stroke);
builder.move_to(ring_point(center, radius, 0.0));
builder.arc_to(
point(radius, radius),
px(0.),
false,
true,
ring_point(center, radius, PI),
);
builder.arc_to(
point(radius, radius),
px(0.),
false,
true,
ring_point(center, radius, TAU),
);
builder.build().ok()
}
#[cfg(test)]
mod tests {
use super::*;
use std::f32::consts::FRAC_PI_2;
#[test]
fn ring_points_run_clockwise_from_twelve() {
let center = point(px(10.0), px(20.0));
let radius = px(4.0);
assert_eq!(ring_point(center, radius, 0.0), point(px(10.0), px(16.0)));
assert_eq!(
ring_point(center, radius, FRAC_PI_2),
point(px(14.0), px(20.0))
);
assert_eq!(ring_point(center, radius, PI), point(px(10.0), px(24.0)));
assert_eq!(
ring_point(center, radius, -FRAC_PI_2),
point(px(6.0), px(20.0))
);
}
#[test]
fn arcs_tessellate_across_the_range() {
let center = point(px(0.0), px(0.0));
let radius = px(8.0);
let stroke = px(2.0);
// The large-arc flag flips past half a circle; both sides must build.
for fraction in [0.25, 0.5, 0.75] {
assert!(
arc_path(center, radius, stroke, 0.0, fraction * TAU).is_some(),
"fraction {fraction} failed to build"
);
}
assert!(circle_path(center, radius, stroke).is_some());
}
}
+108
View File
@@ -0,0 +1,108 @@
//! The status dot: a small colored bead for row state.
use crate::theme::{ActiveTheme as _, Size, Theme};
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, ElementId, Hsla, InteractiveElement as _, IntoElement, RenderOnce, Role, SharedString,
StatefulInteractiveElement as _, StyleRefinement, Styled, Window, div,
};
use crate::components::common::{Sizable, StyledExt};
/// How loud a dot is, the same vocabulary as [`crate::components::badge::BadgeVariant`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum StatusDotVariant {
#[default]
Neutral,
Accent,
Success,
Warning,
Danger,
}
impl StatusDotVariant {
fn color(self, theme: &Theme) -> Hsla {
match self {
Self::Neutral => theme.colors.muted_foreground,
Self::Accent => theme.ramps.primary.base,
Self::Success => theme.ramps.success.base,
Self::Warning => theme.ramps.warning.base,
Self::Danger => theme.ramps.destructive.base,
}
}
}
/// A small circular bead marking a row's state.
#[derive(IntoElement)]
#[must_use]
pub struct StatusDot {
id: ElementId,
variant: StatusDotVariant,
size: Size,
label: Option<SharedString>,
style: StyleRefinement,
}
impl StatusDot {
/// Creates an idle dot.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
variant: StatusDotVariant::default(),
size: Size::default(),
label: None,
style: StyleRefinement::default(),
}
}
/// Sets how loud the dot is.
pub fn variant(mut self, variant: StatusDotVariant) -> Self {
self.variant = variant;
self
}
/// The state the dot announces to screen readers.
pub fn label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.label = Some(label.into());
self
}
}
impl Sizable for StatusDot {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl Styled for StatusDot {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for StatusDot {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let metrics = theme.sizes.resolve(self.size);
let side = metrics.icon_size / 2.;
let color = self.variant.color(theme);
div()
.id(self.id.clone())
.debug_selector(move || self.id.to_string())
.flex_none()
.size(side)
.rounded(theme.radius.full)
.bg(color)
.when_some(self.label, |dot, label| {
dot.role(Role::Status).aria_label(label)
})
.refine_style(&self.style)
}
}
+180
View File
@@ -0,0 +1,180 @@
//! The switch: a controlled on/off pill with a thumb.
use crate::theme::{ActiveTheme as _, BORDER_WIDTH, CONTROL_SPRING, DISABLED_OPACITY, Size};
use crate::utils::focus_ring;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnimationExt as _, App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _,
RenderOnce, Role, SharedString, SpringAnimation, StatefulInteractiveElement as _,
StyleRefinement, Styled as _, Toggled, Window, div, px,
};
use crate::components::common::{Sizable, StyledExt as _, h_flex};
/// The change reporter, fired with the next value by pointer, Enter, and Space.
type ChangeHandler = Box<dyn Fn(bool, &mut Window, &mut App)>;
/// Switch component.
#[derive(IntoElement)]
#[must_use]
pub struct Switch {
id: ElementId,
label: Option<SharedString>,
checked: bool,
size: Size,
disabled: bool,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler>,
style: StyleRefinement,
}
impl Switch {
/// Creates an unchecked switch.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
label: None,
checked: false,
size: Size::default(),
disabled: false,
a11y_label: None,
on_change: None,
style: StyleRefinement::default(),
}
}
/// Sets the visible label; clicking it toggles too.
pub fn label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.label = Some(label.into());
self
}
/// Sets the current value; the switch never owns it.
pub fn checked(mut self, checked: bool) -> Self {
self.checked = checked;
self
}
/// Renders the switch 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<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// The change handler, fired with the next value by pointer, Enter, and Space.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(bool, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Box::new(handler));
self
}
}
impl gpui::Styled for Switch {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl Sizable for Switch {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl RenderOnce for Switch {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
let metrics = theme.sizes.resolve(self.size);
let track_height = metrics.switch_height;
let track_width = metrics.switch_width;
let knob = metrics.switch_knob;
// Absolute children sit inside the track's border, so remove it from the inset.
let inset = (track_height - knob) / 2. - BORDER_WIDTH;
let travel = track_width - BORDER_WIDTH * 2. - knob - inset * 2.;
let next = !self.checked;
let on_change = self.on_change;
let a11y_label = self.a11y_label.or_else(|| self.label.clone());
let id = self.id.clone();
let anim =
SpringAnimation::new(CONTROL_SPRING).to(if self.checked { travel } else { px(0.) });
h_flex()
.id(self.id)
.gap_2()
.text_size(metrics.text_size)
.refine_style(&self.style)
.role(Role::Switch)
.when_some(a11y_label, |switch, label| switch.aria_label(label))
.aria_toggled(Toggled::from(self.checked))
.when(self.disabled, |switch| switch.opacity(DISABLED_OPACITY))
.when(!self.disabled, |switch| {
switch
.cursor_pointer()
.focusable()
.tab_stop(true)
.focus_visible(|style| style.shadow(focus_ring(colors.ring)))
.when_some(on_change, |switch, on_change| {
switch.on_click(move |_, window, cx| on_change(next, window, cx))
})
})
.child(
div()
.flex_none()
.relative()
.debug_selector(move || format!("{id}-track"))
.w(track_width)
.h(track_height)
.rounded(theme.radius.full)
.border_1()
.when(self.checked, |track| {
track
.bg(ramps.primary.base)
.border_color(ramps.primary.base)
.hover(|style| {
style
.bg(ramps.primary.hover)
.border_color(ramps.primary.hover)
})
})
.when(!self.checked, |track| {
track.bg(colors.input).border_color(colors.border)
})
.child(
div()
.absolute()
.top(inset)
.left(inset)
.size(knob)
.rounded(theme.radius.full)
.bg(colors.primary_foreground)
.with_spring("switch-thumb", anim, move |thumb, offset| {
thumb.left(inset + offset)
}),
),
)
.when_some(self.label, |switch, label| switch.child(label))
}
}
+354
View File
@@ -0,0 +1,354 @@
//! Toasts: succinct, temporary messages at the bottom center of the window.
use std::rc::Rc;
use std::time::Duration;
use crate::icons::{Icon, IconRole};
use crate::theme::{ActiveTheme as _, TOAST_MAX_WIDTH};
use crate::utils::ResultLogErr as _;
use gpui::prelude::FluentBuilder;
use gpui::{
Animation, AnimationExt as _, App, Context, ElementId, Entity, InteractiveElement as _,
IntoElement, ParentElement as _, RenderOnce, Role, SharedString,
StatefulInteractiveElement as _, StyleRefinement, Styled as _, Task, Window, deferred, div,
ease_out_quint, px,
};
use crate::components::button::{Button, ButtonVariant};
use crate::components::common::{DismissHandler, Sizable as _, StyledExt as _, TOAST_LAYER};
/// The action handler of a [`Toast`].
pub type ActionHandler = Rc<dyn Fn(&mut App)>;
/// 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<L, F>(label: L, handler: F) -> Self
where
L: Into<SharedString>,
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<Icon>,
action: Option<ToastAction>,
duration: Option<Duration>,
on_dismiss: Option<DismissHandler>,
style: StyleRefinement,
}
impl Toast {
/// How long a toast stays up by default.
pub const DURATION: Duration = Duration::from_secs(5);
/// Creates a toast with this one-line content.
pub fn new<L>(message: L) -> Self
where
L: Into<SharedString>,
{
Self {
message: message.into(),
icon: None,
action: None,
duration: Some(Self::DURATION),
on_dismiss: None,
style: StyleRefinement::default(),
}
}
/// Shows this glyph before the content.
pub fn icon<I>(mut self, icon: I) -> Self
where
I: Into<Icon>,
{
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<F>(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.
impl FluentBuilder for Toast {}
/// One raised toast, with its identity in the store.
#[derive(Clone)]
pub struct ToastEntry {
pub id: usize,
pub toast: Toast,
}
/// The store of raised toasts.
#[derive(Default)]
pub struct Toasts {
current: Option<ToastEntry>,
exiting: Option<ToastEntry>,
next_id: usize,
/// Pending dismiss and fade timers; held so they die with the store.
tasks: Vec<Task<()>>,
}
impl Toasts {
/// Raises a toast, replacing the one on screen. Returns its id.
pub fn push(&mut self, toast: Toast, cx: &mut Context<Self>) -> usize {
let id = self.next_id;
self.next_id += 1;
let duration = toast.duration;
if let Some(previous) = self.current.take() {
self.start_exit(previous, cx);
}
self.current = Some(ToastEntry { id, toast });
cx.notify();
if let Some(duration) = duration.filter(|duration| !duration.is_zero()) {
let task = cx.spawn(async move |this, cx| {
cx.background_executor().timer(duration).await;
this.update(cx, |toasts, cx| toasts.dismiss(id, cx))
.log_err();
});
self.tasks.push(task);
}
id
}
/// Dismisses one toast by id.
pub fn dismiss(&mut self, id: usize, cx: &mut Context<Self>) {
if self.exiting.as_ref().is_some_and(|entry| entry.id == id) {
self.finish_exit(cx);
return;
}
if let Some(entry) = self.current.take_if(|entry| entry.id == id) {
self.start_exit(entry, cx);
}
}
/// Dismisses the toast on screen.
pub fn clear(&mut self, cx: &mut Context<Self>) {
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<Self>) {
if let Some(previous) = self.exiting.take()
&& let Some(on_dismiss) = &previous.toast.on_dismiss
{
on_dismiss(cx);
}
self.exiting = Some(entry);
cx.notify();
let fade = cx.theme().motion.overlay;
let task = cx.spawn(async move |this, cx| {
cx.background_executor().timer(fade).await;
this.update(cx, |toasts, cx| toasts.finish_exit(cx))
.log_err();
});
self.tasks.push(task);
}
fn finish_exit(&mut self, cx: &mut Context<Self>) {
if let Some(entry) = self.exiting.take() {
cx.notify();
if let Some(on_dismiss) = &entry.toast.on_dismiss {
on_dismiss(cx);
}
}
}
}
/// The floating stack of toasts, bottom center.
#[derive(IntoElement)]
#[must_use]
pub struct ToastsView {
toasts: Entity<Toasts>,
id: ElementId,
}
impl ToastsView {
/// Binds the view to a toast store.
pub fn new<I>(id: I, toasts: Entity<Toasts>) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
toasts,
}
}
}
impl RenderOnce for ToastsView {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let fade = cx.theme().motion.overlay;
let exiting = self.toasts.read(cx).exiting.clone();
let current = self.toasts.read(cx).current.clone();
deferred(
div()
.id(self.id)
.absolute()
.left_0()
.bottom_4()
.w_full()
.flex()
.flex_col()
.items_center()
.when_some(exiting, |column, entry| {
let id = entry.id;
column.child(entry.pill(&self.toasts, cx).with_animation(
("toast-exit", id),
Animation::new(fade),
|pill, delta| pill.opacity(1. - delta),
))
})
.when_some(current, |column, entry| {
let id = entry.id;
column.child(entry.pill(&self.toasts, cx).with_animation(
("toast-enter", id),
Animation::new(fade).with_easing(ease_out_quint()),
|pill, delta| pill.opacity(delta),
))
}),
)
.with_priority(TOAST_LAYER)
}
}
impl ToastEntry {
/// The rendered pill for this toast.
fn pill(&self, toasts: &Entity<Toasts>, cx: &App) -> gpui::Stateful<gpui::Div> {
let theme = cx.theme();
let surface = theme.colors.surface;
let border = theme.colors.border;
let foreground = theme.colors.foreground;
let radius = theme.radius.full;
let shadows = theme.elevations.popover.shadows();
let icon_size = theme.sizes.medium.icon_size;
let text_size = theme.sizes.medium.text_size;
let toast = &self.toast;
let toasts = toasts.clone();
let id = self.id;
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()
.bg(surface)
.border_1()
.border_color(border)
.rounded(radius)
.shadow(shadows.clone())
.refine_style(&toast.style)
.when_some(toast.icon.clone(), |pill, icon| {
pill.child(
div()
.flex_none()
.flex()
.items_center()
.child(icon.size(icon_size).color(foreground)),
)
})
.child(
div()
.flex_1()
.min_w(px(0.))
.truncate()
.text_size(text_size)
.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);
});
}),
),
)
}
}
+166
View File
@@ -0,0 +1,166 @@
use crate::icons::Icon;
use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size};
use crate::utils::focus_ring;
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role,
SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Toggled, Window,
};
use crate::components::common::{Sizable, StyledExt as _, h_flex};
/// The change handler, fired with the next pressed state.
type ChangeHandler = Box<dyn Fn(bool, &mut Window, &mut App)>;
/// A toggle component.
#[derive(IntoElement)]
#[must_use]
pub struct Toggle {
id: ElementId,
label: Option<SharedString>,
icon: Option<Icon>,
pressed: bool,
size: Size,
disabled: bool,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler>,
style: StyleRefinement,
}
impl Toggle {
/// Creates an unpressed toggle.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
label: None,
icon: None,
pressed: false,
size: Size::default(),
disabled: false,
a11y_label: None,
on_change: None,
style: StyleRefinement::default(),
}
}
/// Sets the visible label.
pub fn label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.label = Some(label.into());
self
}
/// Shows an icon. Omitting the label renders an icon-only toggle.
pub fn icon<I>(mut self, icon: I) -> Self
where
I: Into<Icon>,
{
self.icon = Some(icon.into());
self
}
/// Sets the current pressed state; the toggle never owns it.
pub fn pressed(mut self, pressed: bool) -> Self {
self.pressed = pressed;
self
}
/// Renders the toggle 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<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// Sets the change handler, fired with the next pressed state.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(bool, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Box::new(handler));
self
}
}
impl gpui::Styled for Toggle {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl Sizable for Toggle {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl RenderOnce for Toggle {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
let metrics = theme.sizes.resolve(self.size);
let on_change = self.on_change;
let next = !self.pressed;
let a11y_label = self.a11y_label.or_else(|| self.label.clone());
let icon_only = self.icon.is_some() && self.label.is_none();
h_flex()
.id(self.id)
.justify_center()
.h(metrics.control_height)
.when(icon_only, |toggle| {
toggle.w(metrics.control_height).px(gpui::Pixels::ZERO)
})
.when(!icon_only, |toggle| toggle.px(metrics.dense_padding_x))
.rounded(theme.radius.control)
.text_size(metrics.text_size)
.text_color(colors.foreground)
.role(Role::Button)
.when_some(a11y_label, |toggle, label| toggle.aria_label(label))
.aria_toggled(Toggled::from(self.pressed))
.when(self.pressed, |toggle| {
toggle
.bg(ramps.secondary.hover)
.hover(|style| style.bg(ramps.secondary.pressed))
})
.when(!self.pressed, |toggle| {
toggle
.hover(|style| style.bg(colors.muted))
.active(|style| style.bg(ramps.secondary.hover))
})
.refine_style(&self.style)
.when(self.disabled, |toggle| toggle.opacity(DISABLED_OPACITY))
.when(!self.disabled, |toggle| {
toggle
.cursor_pointer()
.focusable()
.tab_stop(true)
.focus_visible(|style| style.shadow(focus_ring(colors.ring)))
.when_some(on_change, |toggle, on_change| {
toggle.on_click(move |_, window, cx| on_change(next, window, cx))
})
})
.child(
h_flex()
.gap_2()
.when_some(self.icon, |content, icon| {
content.child(icon.size(metrics.icon_size))
})
.when_some(self.label, |content, label| content.child(label)),
)
}
}
+141
View File
@@ -0,0 +1,141 @@
use crate::theme::{ActiveTheme as _, BORDER_WIDTH, TOOLTIP_MAX_WIDTH, TOOLTIP_OFFSET};
use crate::utils::{anchor_bounds, record_anchor_bounds};
use gpui::AppContext as _;
use gpui::{
AnyView, App, Bounds, Context, ElementId, Entity, InteractiveElement as _, IntoElement,
ParentElement as _, Pixels, Render, Role, SharedString, StatefulInteractiveElement as _,
Styled as _, Window, canvas, div, point,
};
const PANEL_BOUNDS_ID: &str = "tooltip-panel-bounds";
/// A small text panel gpui shows next to a hovered element.
pub struct Tooltip {
text: SharedString,
anchor: Option<Bounds<Pixels>>,
}
impl Tooltip {
/// Creates the tooltip view.
pub fn new<L>(text: L, cx: &mut App) -> Entity<Self>
where
L: Into<SharedString>,
{
cx.new(|_| Self {
text: text.into(),
anchor: None,
})
}
/// Sets the anchor element ID for the tooltip.
///
/// The `.tooltip(...)` closure pinning the panel next to `anchor_id`.
pub fn anchored<L, I>(
text: L,
anchor_id: I,
) -> impl Fn(&mut Window, &mut App) -> AnyView + 'static
where
L: Into<SharedString>,
I: Into<ElementId>,
{
let text = text.into();
let anchor_id = anchor_id.into();
move |window, cx| {
let anchor = anchor_bounds(window.window_handle().window_id(), &anchor_id, cx);
cx.new(|_| Self {
text: text.clone(),
anchor,
})
.into()
}
}
/// The `.tooltip(...)` closure for a plain text tooltip.
pub fn text<L>(text: L) -> impl Fn(&mut Window, &mut App) -> AnyView + 'static
where
L: Into<SharedString>,
{
let text = text.into();
move |_, cx| Tooltip::new(text.clone(), cx).into()
}
}
impl Render for Tooltip {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
// Copied out: the mutable reads below need `cx` free of this borrow.
let theme = cx.theme();
let text_size = theme.sizes.medium.text_size;
let line_height = theme.typography.callout.line_height;
let spacing_unit = theme.spacing.unit;
let surface = theme.colors.surface;
let surface_foreground = theme.colors.surface_foreground;
let radius_sm = theme.radius.sm;
let shadows = theme.elevations.popover.shadows();
let border = theme.colors.border;
let build_panel = || {
div()
.id("tooltip-panel")
.role(Role::Tooltip)
.debug_selector(|| "tooltip-panel".to_string())
.px_2()
.py_1()
.max_w(TOOLTIP_MAX_WIDTH)
.bg(surface)
.border_1()
.border_color(border)
.rounded(radius_sm)
.shadow(shadows.clone())
.text_size(text_size)
.line_height(line_height)
.text_color(surface_foreground)
.child(self.text.clone())
};
let (wrapper, panel) = match self.anchor {
Some(parent) => {
let origin = window.mouse_position() + point(TOOLTIP_OFFSET, TOOLTIP_OFFSET);
let viewport_height = window.viewport_size().height;
let height = anchor_bounds(
window.window_handle().window_id(),
&ElementId::from(PANEL_BOUNDS_ID),
cx,
)
.map(|bounds| bounds.size.height)
.unwrap_or_else(|| line_height + spacing_unit * 2.0 + BORDER_WIDTH * 2.0);
let below = viewport_height - spacing_unit - parent.bottom();
let above = parent.top() - spacing_unit;
let hang_below = below >= height || below >= above;
let panel = build_panel()
.ml(parent.left() - origin.x)
.mt(if hang_below {
parent.bottom() + spacing_unit - origin.y
} else {
parent.top() - spacing_unit - height - origin.y
})
.child(
canvas(
record_anchor_bounds(ElementId::from(PANEL_BOUNDS_ID)),
|_, _, _, _| {},
)
.absolute()
.inset_0(),
);
(div().debug_selector(|| "tooltip-anchor".to_string()), panel)
}
None => {
let wrapper = div()
.debug_selector(|| "tooltip-anchor".to_string())
.pl(spacing_unit * 2.0)
.pt(spacing_unit * 2.0);
(wrapper, build_panel())
}
};
wrapper.child(panel)
}
}
+270
View File
@@ -0,0 +1,270 @@
use std::rc::Rc;
use crate::icons::Icon;
use crate::theme::{ActiveTheme as _, TextRole, Typeset as _};
use crate::utils::{StyledExt as _, nav_key, paint_selectable_row, selectable_label_color};
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,
};
/// The change reporter, fired with the next selection by pointer and keys.
type ChangeHandler = Rc<dyn Fn(Option<usize>, &mut Window, &mut App)>;
type ItemsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<ListItem>>;
/// One row of a [`List`].
#[must_use]
pub struct ListItem {
key: ElementId,
label: SharedString,
icon: Option<Icon>,
detail: Option<SharedString>,
disabled: bool,
}
impl ListItem {
/// Creates a row shown as `label`, identified by `key`.
pub fn new<K, L>(key: K, label: L) -> Self
where
K: Into<ElementId>,
L: Into<SharedString>,
{
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<I>(mut self, icon: I) -> Self
where
I: Into<Icon>,
{
self.icon = Some(icon.into());
self
}
/// Shows muted trailing text.
pub fn detail<D>(mut self, detail: D) -> Self
where
D: Into<SharedString>,
{
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.
#[derive(IntoElement)]
#[must_use]
pub struct List {
id: ElementId,
selected: Option<usize>,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler>,
items: Option<ItemsFn>,
style: StyleRefinement,
}
impl List {
/// Creates a list with nothing selected.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
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<usize>) -> Self {
self.selected = selected;
self
}
/// Reports the next selection, from clicks and keys alike.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(Option<usize>, &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<F>(mut self, items: F) -> Self
where
F: Fn(&mut Window, &mut App) -> Vec<ListItem> + 'static,
{
self.items = Some(Box::new(items));
self
}
/// Overrides the accessibility label, which defaults to the id.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
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<usize> = items
.iter()
.enumerate()
.filter(|(_, item)| !item.disabled)
.map(|(index, _)| index)
.collect();
let focus = crate::utils::focus_handle(&self.id, window, cx);
let theme = cx.theme();
let label = self
.a11y_label
.clone()
.unwrap_or_else(|| SharedString::from(self.id.to_string()));
let rows: Vec<AnyElement> = items
.iter()
.enumerate()
.map(|(index, item)| {
item.render_row(
cx,
index,
items.len(),
self.selected == Some(index),
&self.on_change,
&focus,
)
})
.collect();
div()
.id(self.id)
.flex()
.flex_col()
.gap_0p5()
.text_size(theme.sizes.medium.text_size)
.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<ChangeHandler>,
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(theme.sizes.medium.control_height)
.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(theme.sizes.medium.icon_size).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()
.typeset(TextRole::Subheadline, cx)
.text_color(if selected {
theme.colors.primary_foreground
} else {
theme.colors.muted_foreground
})
.child(detail),
)
})
.into_any_element()
}
}
+6
View File
@@ -0,0 +1,6 @@
//! Data-heavy components: lists, trees, tabs, sidebars.
pub mod list;
pub mod sidebar;
pub mod tabs;
pub mod tree;
+524
View File
@@ -0,0 +1,524 @@
//! The sidebar: a controlled list with section headers — the Finder
//! sidebar's model of rows grouped under non-selectable labels. Custom
//! entries slot user content between the rows.
use std::rc::Rc;
use crate::components::grain::grain as grain_overlay;
use crate::components::scroll_area::ScrollArea;
use crate::theme::{ActiveTheme as _, BORDER_WIDTH, SIDEBAR_DEFAULT_WIDTH, TextRole, Typeset as _};
use crate::utils::{StyledExt as _, nav_key, paint_selectable_row, selectable_label_color};
use gpui::prelude::FluentBuilder;
use gpui::{
AnyElement, App, ElementId, FocusHandle, InteractiveElement as _, IntoElement, KeyDownEvent,
ParentElement as _, Pixels, RenderOnce, Role, SharedString, StatefulInteractiveElement as _,
StyleRefinement, Styled as _, Window, div,
};
/// The change reporter, fired with the next selected row by pointer and keys.
type ChangeHandler = Rc<dyn Fn(Option<usize>, &mut Window, &mut App)>;
type EntriesFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<SidebarEntry>>;
/// One entry of a [`Sidebar`], a section header, a selectable row, or custom content.
#[must_use]
pub enum SidebarEntry {
/// A non-selectable section label.
Header {
label: SharedString,
prefix: Option<AnyElement>,
suffix: Option<AnyElement>,
},
/// A selectable row.
Row {
key: ElementId,
label: SharedString,
detail: Option<SharedString>,
prefix: Option<AnyElement>,
suffix: Option<AnyElement>,
disabled: bool,
},
/// Custom content occupying a slot in the list.
Custom(AnyElement),
}
impl SidebarEntry {
/// Creates a section header.
pub fn header<L>(label: L) -> Self
where
L: Into<SharedString>,
{
Self::Header {
label: label.into(),
prefix: None,
suffix: None,
}
}
/// Creates a selectable row shown as `label`, identified by `key`.
pub fn row<K, L>(key: K, label: L) -> Self
where
K: Into<ElementId>,
L: Into<SharedString>,
{
Self::Row {
key: key.into(),
label: label.into(),
detail: None,
prefix: None,
suffix: None,
disabled: false,
}
}
/// Wraps custom content occupying a slot in the list.
pub fn custom<E>(element: E) -> Self
where
E: IntoElement,
{
Self::Custom(element.into_any_element())
}
/// Shows muted trailing text.
pub fn detail<D>(mut self, detail: D) -> Self
where
D: Into<SharedString>,
{
if let Self::Row {
detail: row_detail, ..
} = &mut self
{
*row_detail = Some(detail.into());
}
self
}
/// Shows an element leading the entry.
pub fn prefix<E>(mut self, prefix: E) -> Self
where
E: IntoElement,
{
if let Self::Row { prefix: slot, .. } | Self::Header { prefix: slot, .. } = &mut self {
*slot = Some(prefix.into_any_element());
}
self
}
/// Shows an element trailing the entry.
pub fn suffix<E>(mut self, suffix: E) -> Self
where
E: IntoElement,
{
if let Self::Row { suffix: slot, .. } | Self::Header { suffix: slot, .. } = &mut self {
*slot = Some(suffix.into_any_element());
}
self
}
/// Renders the row dimmed; clicks and keyboard skip it.
pub fn disabled(mut self, disabled: bool) -> Self {
if let Self::Row {
disabled: row_disabled,
..
} = &mut self
{
*row_disabled = disabled;
}
self
}
}
// SidebarEntry is a data builder, not an element, adopt the combinators explicitly.
impl FluentBuilder for SidebarEntry {}
/// A sidebar.
#[derive(IntoElement)]
#[must_use]
pub struct Sidebar {
id: ElementId,
selected: Option<usize>,
transparent: bool,
grain: bool,
border_right: bool,
padded: bool,
width: Pixels,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler>,
entries: Option<EntriesFn>,
style: StyleRefinement,
}
impl Sidebar {
/// Creates a sidebar with nothing selected.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
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<usize>) -> 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 material with a film-grain overlay; it renders only while
/// the sidebar paints one.
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<W>(mut self, width: W) -> Self
where
W: Into<Pixels>,
{
self.width = width.into();
self
}
/// Reports the next selected row, from clicks and keys alike.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(Option<usize>, &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<F>(mut self, entries: F) -> Self
where
F: Fn(&mut Window, &mut App) -> Vec<SidebarEntry> + 'static,
{
self.entries = Some(Box::new(entries));
self
}
/// Overrides the accessibility label, which defaults to the id.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
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<usize> = entries
.iter()
.enumerate()
.filter(|(_, entry)| match entry {
SidebarEntry::Row { disabled, .. } => !disabled,
SidebarEntry::Header { .. } | SidebarEntry::Custom(_) => false,
})
.map(|(index, _)| index)
.collect();
let focus = crate::utils::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<AnyElement> = 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(
div()
.flex()
.flex_col()
.gap_0p5()
.when(padded, |content| content.p_2())
.children(children),
),
)
.into_any_element();
let theme = cx.theme();
div()
.id(id.clone())
.debug_selector(move || format!("sidebar-{debug_id}"))
.h_full()
.w(width)
.flex()
.flex_col()
.map(|sidebar| {
if material {
sidebar.bg(theme.material.background)
} else {
sidebar.bg(theme.colors.sidebar)
}
})
.text_size(theme.sizes.medium.text_size)
.refine_style(&style)
.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,
cx: &App,
index: usize,
position_in_set: usize,
size_of_set: usize,
selected: bool,
material: bool,
on_change: &Option<ChangeHandler>,
focus: &FocusHandle,
) -> AnyElement {
let theme = cx.theme();
match self {
SidebarEntry::Header {
label,
prefix,
suffix,
} => {
// The id is required for the role to surface in the a11y tree.
div()
.id(("sidebar-header".into(), label.clone()))
.flex()
.items_center()
.gap_2()
.px_2()
.pt_2()
.pb_1()
.typeset(TextRole::Headline, cx)
.text_color(theme.colors.muted_foreground)
.role(Role::Heading)
.when_some(prefix, |header, prefix| header.child(prefix))
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.child(label),
)
.when_some(suffix, |header, suffix| header.child(suffix))
.into_any_element()
}
SidebarEntry::Custom(element) => element,
SidebarEntry::Row {
key,
label,
detail,
prefix,
suffix,
disabled: row_disabled,
} => {
let label_color = selectable_label_color(cx, selected, row_disabled);
div()
.id((key.clone(), "sidebar-row"))
.flex()
.items_center()
.gap_2()
.px_2()
.py_1()
.min_h(theme.sizes.medium.control_height)
.rounded(theme.radius.sm)
.role(Role::ListItem)
.aria_selected(selected)
.aria_position_in_set(position_in_set)
.aria_size_of_set(size_of_set)
.map(|row| {
if material && !row_disabled {
if selected {
row.bg(theme.material.selection)
} else {
row.hover(|row| row.bg(theme.material.hover))
}
} else {
paint_selectable_row(cx, row, selected, row_disabled)
}
})
.when(!row_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(prefix, |row, prefix| row.child(prefix))
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.text_color(label_color)
.child(label),
)
.when_some(detail, |row, detail| {
row.child(
div()
.flex_none()
.typeset(TextRole::Subheadline, cx)
.text_color(if selected {
theme.colors.primary_foreground
} else {
theme.colors.muted_foreground
})
.child(detail),
)
})
.when_some(suffix, |row, suffix| row.child(suffix))
.into_any_element()
}
}
}
}
File diff suppressed because it is too large Load Diff
+476
View File
@@ -0,0 +1,476 @@
use std::rc::Rc;
use crate::icons::{Icon, IconRole, icon};
use crate::theme::ActiveTheme as _;
use crate::utils::{StyledExt as _, nav_key, paint_selectable_row, selectable_label_color};
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,
};
/// The change reporter, fired with the next selection by pointer and keys.
type ChangeHandler = Rc<dyn Fn(Option<usize>, &mut Window, &mut App)>;
/// The disclosure reporter, fired with the toggled row's index.
type DisclosureHandler = Rc<dyn Fn(usize, &mut Window, &mut App)>;
type ItemsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<TreeItem>>;
/// Tree item.
#[derive(Clone)]
#[must_use]
pub struct TreeItem {
key: ElementId,
label: SharedString,
icon: Option<Icon>,
depth: usize,
expandable: bool,
expanded: bool,
disabled: bool,
}
impl TreeItem {
/// Creates a leaf row shown as `label` at the root depth, identified by `key`.
pub fn new<K, L>(key: K, label: L) -> Self
where
K: Into<ElementId>,
L: Into<SharedString>,
{
Self {
key: key.into(),
label: label.into(),
icon: None,
depth: 0,
expandable: false,
expanded: false,
disabled: false,
}
}
/// Shows a custom icon leading the label.
pub fn icon<I>(mut self, icon: I) -> Self
where
I: Into<Icon>,
{
self.icon = Some(icon.into());
self
}
/// Nests the row one level per count.
pub fn depth(mut self, depth: usize) -> Self {
self.depth = depth;
self
}
/// Marks the row as having children.
pub fn expandable(mut self, expandable: bool) -> Self {
self.expandable = expandable;
self
}
/// Sets the row's disclosure state.
pub fn expanded(mut self, expanded: bool) -> Self {
self.expanded = expanded;
self
}
/// Renders the row dimmed; clicks and keyboard skip it.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
}
// TreeItem is a data builder, not an element, adopt the combinators explicitly.
impl FluentBuilder for TreeItem {}
/// A tree.
#[derive(IntoElement)]
#[must_use]
pub struct Tree {
id: ElementId,
selected: Option<usize>,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler>,
on_disclosure: Option<DisclosureHandler>,
items: Option<ItemsFn>,
style: StyleRefinement,
}
impl Tree {
/// Creates a tree with nothing selected.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
selected: None,
a11y_label: None,
on_change: None,
on_disclosure: None,
items: None,
style: StyleRefinement::default(),
}
}
/// Sets the current selection.
pub fn selected(mut self, selected: Option<usize>) -> Self {
self.selected = selected;
self
}
/// Reports the next selection, from clicks and keys alike.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(Option<usize>, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Rc::new(handler));
self
}
/// Reports the row whose disclosure the user toggled.
pub fn on_disclosure<F>(mut self, handler: F) -> Self
where
F: Fn(usize, &mut Window, &mut App) + 'static,
{
self.on_disclosure = Some(Rc::new(handler));
self
}
/// Sets the visible rows; the closure runs during render and must not mutate entities or notify.
pub fn items<F>(mut self, items: F) -> Self
where
F: Fn(&mut Window, &mut App) -> Vec<TreeItem> + 'static,
{
self.items = Some(Box::new(items));
self
}
/// Overrides the accessibility label, which defaults to the id.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// Maps each visible row to its 1-based position-in-set and set size among its siblings.
fn sibling_sets(items: &[TreeItem]) -> Vec<(usize, usize)> {
let mut sets = vec![(0usize, 0usize); items.len()];
// Open sibling runs along the ancestry path, deeper runs above shallower ones.
let mut runs: Vec<(usize, Vec<usize>)> = Vec::new();
for (index, item) in items.iter().enumerate() {
while runs
.last()
.is_some_and(|(run_depth, _)| *run_depth > item.depth)
{
if let Some((_, pending)) = runs.pop() {
Self::stamp_sibling_run(&mut sets, pending);
}
}
match runs.last_mut() {
// A row at the running depth extends the open sibling run.
Some((run_depth, pending)) if *run_depth == item.depth => pending.push(index),
_ => runs.push((item.depth, vec![index])),
}
}
for (_, pending) in runs {
Self::stamp_sibling_run(&mut sets, pending);
}
sets
}
fn stamp_sibling_run(sets: &mut [(usize, usize)], pending: Vec<usize>) {
let size_of_set = pending.len();
for (position, index) in pending.into_iter().enumerate() {
if let Some(set) = sets.get_mut(index) {
*set = (position + 1, size_of_set);
}
}
}
/// The nearest row above `index` with a smaller depth.
fn parent_of(items: &[TreeItem], index: usize) -> Option<usize> {
let depth = items.get(index)?.depth;
items[..index]
.iter()
.rposition(|candidate| candidate.depth < depth)
}
/// The first selectable row deeper than `index`, when its branch is open.
fn first_descendant(items: &[TreeItem], selectable: &[usize], index: usize) -> Option<usize> {
let depth = items.get(index)?.depth;
selectable.iter().copied().find(|candidate| {
*candidate > index && items.get(*candidate).is_some_and(|row| row.depth > depth)
})
}
}
impl gpui::Styled for Tree {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for Tree {
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<usize> = items
.iter()
.enumerate()
.filter(|(_, item)| !item.disabled)
.map(|(index, _)| index)
.collect();
let focus = crate::utils::focus_handle(&self.id, window, cx);
let theme = cx.theme();
let label = self
.a11y_label
.clone()
.unwrap_or_else(|| SharedString::from(self.id.to_string()));
let sibling_sets = Self::sibling_sets(&items);
let rows: Vec<AnyElement> = items
.iter()
.enumerate()
.map(|(index, item)| {
let (position_in_set, size_of_set) = sibling_sets[index];
item.render_row(
cx,
index,
position_in_set,
size_of_set,
self.selected == Some(index),
&self.on_change,
&self.on_disclosure,
&focus,
)
})
.collect();
div()
.id(self.id)
.flex()
.flex_col()
.gap_0p5()
.text_size(theme.sizes.medium.text_size)
.refine_style(&self.style)
.track_focus(&focus)
.focusable()
.tab_stop(true)
.role(Role::Tree)
.aria_label(label)
.on_key_down({
let selected = self.selected;
let on_change = self.on_change.clone();
let on_disclosure = self.on_disclosure.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();
return;
}
match event.keystroke.key.as_str() {
"left" | "right" => {
let expanding = event.keystroke.key == "right";
let mut disclose = None;
let mut target = None;
if let Some(index) = selected
&& let Some(item) = items.get(index)
&& !item.disabled
{
if item.expandable && item.expanded != expanding {
disclose = Some(index);
} else if expanding {
target = Self::first_descendant(&items, &selectable, index);
} else {
target = Self::parent_of(&items, index)
.filter(|parent| selectable.contains(parent));
}
}
if let Some(index) = disclose
&& let Some(on_disclosure) = &on_disclosure
{
on_disclosure(index, window, cx);
} else if let Some(next) = target
&& let Some(on_change) = &on_change
{
on_change(Some(next), window, cx);
}
}
_ => return,
}
cx.stop_propagation();
}
})
.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<ChangeHandler>,
on_disclosure: &Option<DisclosureHandler>,
focus: &FocusHandle,
) -> AnyElement {
let theme = cx.theme();
let label_color = selectable_label_color(cx, selected, self.disabled);
let disabled = self.disabled;
let depth = u32::try_from(self.depth).unwrap_or(u32::MAX) as f32;
let indent = theme.sizes.medium.padding_x * 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(theme.sizes.medium.control_height)
.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).map(|level| {
let step = u32::try_from(level).unwrap_or(u32::MAX) as f32;
div()
.absolute()
.left(theme.sizes.medium.padding_x * (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(theme.sizes.medium.icon_size).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(theme.sizes.medium.icon_size)
.flex()
.items_center()
.justify_center()
.when(self.expandable, |cell| {
cell.child(
icon(if self.expanded {
IconRole::ChevronDown
} else {
IconRole::ChevronRight
})
.size(theme.sizes.medium.dense_icon_size)
.color(glyph_color),
)
})
.into_any_element()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn item(depth: usize) -> TreeItem {
TreeItem::new("item", "Item").depth(depth)
}
#[test]
fn flat_rows_number_one_of_three() {
let sets = Tree::sibling_sets(&[item(0), item(0), item(0)]);
assert_eq!(sets, vec![(1, 3), (2, 3), (3, 3)]);
}
#[test]
fn nested_rows_number_per_level() {
let sets = Tree::sibling_sets(&[item(0), item(1), item(2), item(1), item(0)]);
assert_eq!(sets, vec![(1, 2), (1, 2), (1, 1), (2, 2), (2, 2)]);
}
#[test]
fn parent_skips_the_subtree_above() {
let rows = [item(0), item(1), item(2), item(1), item(0)];
assert_eq!(Tree::parent_of(&rows, 3), Some(0));
assert_eq!(Tree::parent_of(&rows, 2), Some(1));
assert_eq!(Tree::parent_of(&rows, 0), None);
}
#[test]
fn first_descendant_skips_disabled_rows() {
let rows = [item(0), item(1), item(1), item(0)];
let selectable = vec![0, 2, 3];
assert_eq!(Tree::first_descendant(&rows, &selectable, 0), Some(2));
assert_eq!(Tree::first_descendant(&rows, &selectable, 2), None);
}
}
+576
View File
@@ -0,0 +1,576 @@
//! The code view: a virtualized, read-only rendering of highlighted source.
//! Rows render only when visible, the line-number gutter is part of each
//! row, and the overlay scrollbar is the core one.
use crate::components::scrollbar::{Scrollbar, ScrollbarHandle, ScrollbarVisibility};
use crate::theme::{
ActiveTheme as _, CODE_GUTTER_WIDTH, CODE_LINE_HEIGHT, ColorTokens, MONO_ADVANCE_RATIO, Ramps,
WASH_ALPHA_SOFT,
};
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, Bounds, ClipboardItem, Context, ElementId, HighlightStyle, Hsla, InteractiveElement as _,
IntoElement, KeyBinding, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
ParentElement as _, Pixels, Point, Render, ScrollStrategy, SharedString,
StatefulInteractiveElement as _, Styled as _, TextStyle, UniformListScrollHandle, Window,
actions, canvas, div, uniform_list,
};
use crate::editor::highlight::{HighlightedCode, Language, Role, highlight};
use crate::editor::utils::gutter_cell;
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 = Some(CODE_VIEW_CONTEXT);
#[cfg(target_os = "macos")]
let copy = "cmd-c";
#[cfg(not(target_os = "macos"))]
let copy = "ctrl-c";
cx.bind_keys([KeyBinding::new(copy, Copy, context)]);
}
/// A point in the source, in lines and characters (not bytes).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SelectionPoint {
pub row: usize,
pub col: usize,
}
impl SelectionPoint {
/// The earlier of two points, in document order.
fn earlier_than(&self, other: &Self) -> bool {
(self.row, self.col) <= (other.row, other.col)
}
}
/// Retained state for a code view.
pub struct CodeViewState {
id: ElementId,
source: SharedString,
language: Language,
code: HighlightedCode,
handle: UniformListScrollHandle,
/// The hovered line, driving the active-line wash and number emphasis.
active_line: Option<usize>,
/// `(anchor, head)` in the order they were set.
selection: Option<(SelectionPoint, SelectionPoint)>,
/// Whether a drag that started on a row is still extending the selection.
selecting: bool,
focus_handle: gpui::FocusHandle,
a11y_label: Option<SharedString>,
}
impl CodeViewState {
/// Builds the state, highlighting `source` with `language`.
pub fn new<I, S>(id: I, source: S, language: Language, cx: &mut App) -> Self
where
I: Into<ElementId>,
S: Into<SharedString>,
{
let source = source.into();
let code = highlight(&source, language);
Self {
id: id.into(),
source,
language,
code,
handle: UniformListScrollHandle::new(),
active_line: None,
selection: None,
selecting: false,
focus_handle: cx.focus_handle().tab_stop(true),
a11y_label: None,
}
}
/// Replaces the source and re-highlights it.
pub fn set_source<S>(&mut self, source: S, language: Language, cx: &mut Context<Self>)
where
S: Into<SharedString>,
{
let source = source.into();
self.code = highlight(&source, language);
self.source = source;
self.language = language;
self.selection = None;
self.handle.scroll_to_item(0, ScrollStrategy::Top);
cx.notify();
}
/// Replaces one line's text and re-highlights the file.
pub fn update_line<T>(&mut self, line_ix: usize, text: T, cx: &mut Context<Self>)
where
T: AsRef<str>,
{
let trailing_newline = self.source.ends_with('\n');
let mut lines: Vec<String> = self.source.lines().map(str::to_string).collect();
let line_ix = line_ix.min(lines.len().saturating_sub(1));
let replacement: Vec<String> = if text.as_ref().is_empty() {
vec![String::new()]
} else {
text.as_ref().lines().map(str::to_string).collect()
};
lines.splice(line_ix..line_ix + 1, replacement);
self.source = (lines.join("\n") + if trailing_newline { "\n" } else { "" }).into();
self.code = highlight(&self.source, self.language);
self.selection = None;
cx.notify();
}
/// The highlighted source text.
pub fn source(&self) -> &str {
&self.source
}
/// The highlighted lines.
pub fn code(&self) -> &HighlightedCode {
&self.code
}
/// Scrolls `line` to the top of the view.
pub fn scroll_to_line(&self, line: usize) {
self.handle.scroll_to_item(
line.min(self.code.lines.len().saturating_sub(1)),
ScrollStrategy::Top,
);
}
/// The line the pointer last hovered, if any.
pub fn active_line(&self) -> Option<usize> {
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>,
) {
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)> {
self.selection.map(|(anchor, head)| {
if anchor.earlier_than(&head) {
(anchor, head)
} else {
(head, anchor)
}
})
}
/// The selected text, or `None` when nothing is selected.
pub fn selected_text(&self) -> Option<String> {
let (start, end) = self.selection()?;
let lines: Vec<&str> = self.source.split('\n').collect();
let mut selected = Vec::new();
for row in start.row..=end.row.min(lines.len().saturating_sub(1)) {
let line_chars: Vec<char> = lines.get(row)?.chars().collect();
let start_col = if row == start.row {
start.col.min(line_chars.len())
} else {
0
};
let end_col = if row == end.row {
end.col.min(line_chars.len())
} else {
line_chars.len()
};
selected.push(line_chars[start_col..end_col].iter().collect::<String>());
}
(!selected.is_empty()).then(|| selected.join("\n"))
}
// Overrides the accessibility label of the view.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// Maps a window position to a point in the source.
fn position_at(
&self,
bounds: Bounds<Pixels>,
position: Point<Pixels>,
scroll_y: Pixels,
line_height: Pixels,
char_width: Pixels,
text_x: Pixels,
) -> SelectionPoint {
// Saturating so an empty document cannot invert the clamp.
let last_row = self.code.lines.len().saturating_sub(1);
let row = (((position.y - bounds.origin.y - scroll_y) / line_height).floor() as isize)
.clamp(0, last_row as isize) as usize;
let chars = self.code.lines.get(row).map_or(0, |line| {
line.spans
.iter()
.map(|span| span.text.chars().count())
.sum::<usize>()
});
let col = (((position.x - text_x) / char_width).round() as isize).clamp(0, chars as isize)
as usize;
SelectionPoint { row, col }
}
}
impl gpui::Focusable for CodeViewState {
fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
self.focus_handle.clone()
}
}
impl Render for CodeViewState {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let mono_font = theme.mono_font;
let text_size = theme.sizes.small.text_size;
let line_height = text_size * CODE_LINE_HEIGHT;
let char_width = text_size * MONO_ADVANCE_RATIO;
let root_font_size = theme.root_font_size;
let id = self.id.clone();
let state = cx.entity();
let line_count = self.code.lines.len();
let selection = self.selection();
let gutter_width = CODE_GUTTER_WIDTH;
let bounds_cell: std::rc::Rc<std::cell::RefCell<Option<Bounds<Pixels>>>> =
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,
theme.sizes.small.text_size,
line_height,
cx,
)
})
.collect()
}
})
.track_scroll(&self.handle)
.h_full()
.w_full();
div()
.id((id.clone(), "view"))
.relative()
.size_full()
.text_size(text_size)
.font_family(mono_font)
.text_color(colors.foreground)
.key_context(CODE_VIEW_CONTEXT)
.track_focus(&self.focus_handle)
.on_mouse_down(MouseButton::Left, {
let state = state.clone();
let bounds_cell = bounds_cell.clone();
move |event: &MouseDownEvent, window: &mut Window, cx: &mut App| {
window.focus(&state.read(cx).focus_handle.clone(), cx);
let bounds = bounds_cell.borrow();
let Some(bounds) = bounds.as_ref() else {
return;
};
let text_x = bounds.origin.x + gutter_width + root_font_size;
let point = {
let code = state.read(cx);
code.position_at(
*bounds,
event.position,
ScrollbarHandle::offset(&code.handle).y,
line_height,
char_width,
text_x,
)
};
state.update(cx, |state, cx| {
if event.modifiers.shift {
if let Some((anchor, _)) = state.selection {
state.selection = Some((anchor, point));
} else {
state.selection = Some((point, point));
}
} else {
state.selection = Some((point, point));
}
state.selecting = true;
cx.notify();
});
}
})
.on_mouse_move({
let state = state.clone();
let bounds_cell = bounds_cell.clone();
move |event: &MouseMoveEvent, _window: &mut Window, cx: &mut App| {
let bounds = bounds_cell.borrow();
let Some(bounds) = bounds.as_ref() else {
return;
};
let text_x = bounds.origin.x + gutter_width + root_font_size;
let point = {
let code = state.read(cx);
code.position_at(
*bounds,
event.position,
ScrollbarHandle::offset(&code.handle).y,
line_height,
char_width,
text_x,
)
};
let selecting = state.read(cx).selecting;
if selecting {
let changed = state
.read(cx)
.selection
.map(|(_, head)| head != point)
.unwrap_or(true);
if changed {
state.update(cx, |state, cx| {
if let Some((anchor, _)) = state.selection {
state.selection = Some((anchor, point));
}
cx.notify();
});
}
return;
}
let changed = state.read(cx).active_line != Some(point.row);
if changed {
state.update(cx, |state, cx| {
state.active_line = Some(point.row);
cx.notify();
});
}
}
})
.on_mouse_up(MouseButton::Left, {
let state = state.clone();
move |_: &MouseUpEvent, _window: &mut Window, cx: &mut App| {
if state.read(cx).selecting {
state.update(cx, |state, cx| {
state.selecting = false;
cx.notify();
});
}
}
})
.on_action({
let state = state.clone();
move |_: &Copy, _window, cx| {
if let Some(text) = state.read(cx).selected_text() {
cx.write_to_clipboard(ClipboardItem::new_string(text));
}
}
})
.child(
canvas(
{
let bounds_cell = bounds_cell.clone();
move |bounds, _window, _cx| {
*bounds_cell.borrow_mut() = Some(bounds);
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0(),
)
.child(rows)
.child(
Scrollbar::vertical((self.id.clone(), "v-scrollbar"), self.handle.clone())
.visibility(ScrollbarVisibility::Platform),
)
.when_some(self.a11y_label.clone(), |view, label| {
view.aria_label(label)
})
}
}
#[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 line = code.code().lines.get(line_ix);
let mut text = String::new();
for span in line.map_or(&[][..], |line| line.spans.as_slice()) {
text.push_str(&span.text);
}
let char_count = text.chars().count();
let mut roles = vec![Role::Text; char_count];
let mut offset = 0usize;
for span in line.map_or(&[][..], |line| line.spans.as_slice()) {
let chars = span.text.chars().count();
for slot in &mut roles[offset..offset + chars] {
*slot = span.role;
}
offset += chars;
}
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<usize>, 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()
.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()
}
+691
View File
@@ -0,0 +1,691 @@
//! The diff view: a unified, syntax-highlighted rendering of two versions of
//! a file, in the style of the Pierre diff engine used by tangled.org: change
//! bars instead of markers, tinted number gutters, word-level intra-line
//! highlights and 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`].
use crate::components::scrollbar::{Scrollbar, ScrollbarHandle, ScrollbarVisibility};
use crate::theme::{ActiveTheme as _, BORDER_WIDTH, CODE_GUTTER_WIDTH, MONO_ADVANCE_RATIO};
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, uniform_list,
};
use similar::{Change, ChangeTag, TextDiff};
use std::ops::Range;
use crate::editor::highlight::{HighlightedCode, Language, Line, Role, highlight};
use crate::editor::utils::{gutter_cell, wash, wash_gutter, wash_strong};
/// 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<usize>,
/// 1-based line number in the new version, when the row exists there.
pub new_number: Option<usize>,
/// Byte ranges of intra-line word changes, tinted on changed rows.
pub changed_ranges: Vec<Range<usize>>,
/// 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 {
pub indicators: DiffIndicators,
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<Range<usize>>,
) -> 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.
pub struct DiffViewState {
id: ElementId,
rows: Vec<DiffRow>,
/// Cached per-row id and text length, parallel to `rows`.
row_layouts: Vec<RowLayout>,
/// The row whose width drives horizontal scroll extent, `rows`-derived.
widest_row: Option<usize>,
options: DiffViewOptions,
/// Drives both scroll axes of the virtualized row list.
handle: UniformListScrollHandle,
a11y_label: Option<SharedString>,
}
/// 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<I, O, N>(id: I, old: O, new: N, language: Language) -> Self
where
I: Into<ElementId>,
O: AsRef<str>,
N: AsRef<str>,
{
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<O, N>(&mut self, old: O, new: N, language: Language)
where
O: AsRef<str>,
N: AsRef<str>,
{
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`.
pub fn diff_rows(old: &str, new: &str, language: Language) -> Vec<DiffRow> {
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<O, N>(&mut self, old: O, new: N, language: Language, cx: &mut Context<Self>)
where
O: AsRef<str>,
N: AsRef<str>,
{
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<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
impl Render for DiffViewState {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let text_size = theme.sizes.small.text_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,
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_size(text_size)
.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,
cx: &App,
) -> gpui::AnyElement {
let theme = cx.theme();
let mono_font = theme.mono_font;
let colors = theme.colors;
let ramps = theme.ramps;
let text_size = theme.sizes.small.text_size;
let line_height = text_size * 1.5;
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_size(text_size)
.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(BORDER_WIDTH * 4.0)
.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<usize>, 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<usize> = 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<usize>, 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(BORDER_WIDTH * 4.0)
.border_color(change_color)
}),
)
})
.when(
options.indicators == DiffIndicators::Bars && !options.line_numbers,
|row_element| {
row_element.child(
div()
.h_full()
.flex_none()
.border_l(BORDER_WIDTH * 4.0)
.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()
}
+267
View File
@@ -0,0 +1,267 @@
//! Tree-sitter highlighting: source text in, role-styled lines out. Roles
//! are resolved to theme colors at render time, so a theme change re-colors
//! code without re-parsing it.
use crate::utils::ResultLogErr;
use gpui::SharedString;
use std::cell::RefCell;
use std::collections::HashMap;
#[cfg(not(target_arch = "wasm32"))]
use tree_sitter::StreamingIterator as _;
#[cfg(not(target_arch = "wasm32"))]
thread_local! {
static HIGHLIGHTERS: RefCell<HashMap<Language, Option<Highlighter>>> =
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<Option<Role>>,
}
/// A language source can highlight as.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Language {
Plain,
Rust,
JavaScript,
TypeScript,
Python,
}
/// The semantic role a span plays.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Role {
Text,
Keyword,
String,
Comment,
Function,
Type,
Number,
Constant,
Property,
Operator,
Punctuation,
Tag,
Escape,
}
/// A run of text sharing one role.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Span {
pub text: SharedString,
pub role: Role,
}
/// One rendered line of code.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct Line {
pub spans: Vec<Span>,
}
impl Line {
/// The line's flat text, in character order.
pub fn text(&self) -> String {
let mut text = String::new();
for span in &self.spans {
text.push_str(&span.text);
}
text
}
}
/// Source text split into role-styled lines.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct HighlightedCode {
pub lines: Vec<Line>,
}
/// Highlights `source` with `language`'s tree-sitter grammar.
#[cfg(not(target_arch = "wasm32"))]
pub fn highlight(source: &str, language: Language) -> HighlightedCode {
let Some((grammar, query_source)) = grammar_for(language) else {
return plain(source);
};
HIGHLIGHTERS.with(|cache| {
let mut cache = cache.borrow_mut();
let highlighter = cache
.entry(language)
.or_insert_with(|| {
let mut parser = tree_sitter::Parser::new();
parser.set_language(&grammar).log_err()?;
let query = tree_sitter::Query::new(&grammar, query_source).log_err()?;
let roles = query
.capture_names()
.iter()
.map(|name| role_for_capture(name))
.collect();
Some(Highlighter {
parser,
query,
roles,
})
})
.as_mut();
let Some(highlighter) = highlighter else {
return plain(source);
};
let Some(tree) = highlighter.parser.parse(source, None) else {
log::warn!("tree-sitter failed to parse {language:?}; rendering plain text");
return plain(source);
};
// One role per byte; matches arrive in query order
let mut role_at = vec![None; source.len()];
let mut cursor = tree_sitter::QueryCursor::new();
let mut matches = cursor.matches(&highlighter.query, tree.root_node(), source.as_bytes());
while let Some(matched) = matches.next() {
for capture in matched.captures {
let Some(role) = highlighter
.roles
.get(capture.index as usize)
.copied()
.flatten()
else {
continue;
};
for byte in capture.node.byte_range() {
if let Some(slot) = role_at.get_mut(byte) {
*slot = Some(role);
}
}
}
}
build_lines(source, &role_at)
})
}
/// The web target has no tree-sitter parsers.
#[cfg(target_arch = "wasm32")]
pub fn highlight(source: &str, _language: Language) -> HighlightedCode {
plain(source)
}
/// Source rendered without any grammar: plain text roles.
pub(crate) fn plain(source: &str) -> HighlightedCode {
build_lines(source, &[])
}
/// The grammar and its highlight query for a language, when compiled in.
#[cfg(not(target_arch = "wasm32"))]
fn grammar_for(language: Language) -> Option<(tree_sitter::Language, &'static str)> {
match language {
Language::Rust => rust_grammar(),
Language::TypeScript => typescript_grammar(),
Language::JavaScript => javascript_grammar(),
Language::Python => python_grammar(),
Language::Plain => None,
}
}
/// The Rust grammar.
#[cfg(not(target_arch = "wasm32"))]
fn rust_grammar() -> Option<(tree_sitter::Language, &'static str)> {
Some((
tree_sitter_rust::LANGUAGE.into(),
tree_sitter_rust::HIGHLIGHTS_QUERY,
))
}
/// The TypeScript grammar.
#[cfg(not(target_arch = "wasm32"))]
fn typescript_grammar() -> Option<(tree_sitter::Language, &'static str)> {
Some((
tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(),
tree_sitter_typescript::HIGHLIGHTS_QUERY,
))
}
/// The JavaScript grammar.
#[cfg(not(target_arch = "wasm32"))]
fn javascript_grammar() -> Option<(tree_sitter::Language, &'static str)> {
Some((
tree_sitter_javascript::LANGUAGE.into(),
tree_sitter_javascript::HIGHLIGHT_QUERY,
))
}
/// The Python grammar.
#[cfg(not(target_arch = "wasm32"))]
fn python_grammar() -> Option<(tree_sitter::Language, &'static str)> {
Some((
tree_sitter_python::LANGUAGE.into(),
tree_sitter_python::HIGHLIGHTS_QUERY,
))
}
/// Maps a query capture name to a role; unmapped captures render as text.
fn role_for_capture(name: &str) -> Option<Role> {
match name.split('.').next()? {
"keyword" => Some(Role::Keyword),
"string" => Some(Role::String),
"escape" => Some(Role::Escape),
"comment" => Some(Role::Comment),
"function" | "method" => Some(Role::Function),
"type" | "attribute" => Some(Role::Type),
"number" => Some(Role::Number),
"constant" => Some(Role::Constant),
"property" => Some(Role::Property),
"operator" => Some(Role::Operator),
"punctuation" => Some(Role::Punctuation),
"tag" => Some(Role::Tag),
_ => None,
}
}
/// Splits `source` into lines, grouping consecutive bytes that share a role into one span.
fn build_lines(source: &str, role_at: &[Option<Role>]) -> HighlightedCode {
let role_of =
|byte: usize| -> Role { role_at.get(byte).copied().flatten().unwrap_or(Role::Text) };
let mut lines = Vec::new();
let mut spans: Vec<Span> = Vec::new();
let mut text = String::new();
let mut role = Role::Text;
for (byte, character) in source.char_indices() {
let byte_role = role_of(byte);
if character == '\n' {
flush_run(&mut text, role, &mut spans);
lines.push(Line {
spans: std::mem::take(&mut spans),
});
continue;
}
if byte_role != role && !text.is_empty() {
flush_run(&mut text, role, &mut spans);
}
role = byte_role;
text.push(character);
}
flush_run(&mut text, role, &mut spans);
lines.push(Line {
spans: std::mem::take(&mut spans),
});
HighlightedCode { lines }
}
fn flush_run(text: &mut String, role: Role, spans: &mut Vec<Span>) {
if !text.is_empty() {
spans.push(Span {
text: SharedString::from(std::mem::take(text)),
role,
});
}
}
File diff suppressed because it is too large Load Diff
+8
View File
@@ -0,0 +1,8 @@
//! Read-only code surfaces: tree-sitter highlighted code views.
pub mod code;
pub mod diff;
pub mod highlight;
pub mod markdown;
mod utils;
+123
View File
@@ -0,0 +1,123 @@
//! Shared helpers for the editor's views: gutter cells, role colors and run
//! styles, code line text, language mapping and change washes.
use std::ops::Range;
use crate::editor::highlight::{Language, Line};
use crate::theme::{ActiveTheme as _, CODE_GUTTER_WIDTH, ColorTokens, Ramps};
use crate::theme::{WASH_ALPHA, WASH_ALPHA_GUTTER, WASH_ALPHA_STRONG};
use gpui::StyledText;
use gpui::{App, HighlightStyle, Hsla, IntoElement, ParentElement as _, Styled as _, div};
use crate::editor::highlight::Role;
impl Role {
/// Maps the role to the theme's semantic palette.
pub(crate) fn color(self, colors: ColorTokens, ramps: Ramps) -> Hsla {
match self {
Role::Text => colors.foreground,
Role::Keyword => ramps.primary.base,
Role::String | Role::Escape => ramps.success.base,
Role::Comment | Role::Punctuation => colors.muted_foreground,
Role::Function | Role::Property => ramps.info.base,
Role::Type => ramps.warning.base,
Role::Number | Role::Constant => ramps.secondary.base,
Role::Operator => colors.foreground,
Role::Tag => ramps.destructive.base,
}
}
/// Builds the highlight style for one run of a code view row.
pub(crate) fn run_style(
self,
selected: bool,
colors: ColorTokens,
ramps: Ramps,
) -> HighlightStyle {
HighlightStyle {
color: Some(self.color(colors, ramps)),
background_color: selected.then_some(colors.selection),
..Default::default()
}
}
}
impl Language {
/// Maps a fence info string to a language.
pub(crate) fn from_fence_info(info: &str) -> Option<Language> {
match info.to_ascii_lowercase().as_str() {
"plain" | "text" | "txt" => Some(Language::Plain),
"rust" | "rs" => Some(Language::Rust),
"typescript" | "ts" => Some(Language::TypeScript),
"javascript" | "js" => Some(Language::JavaScript),
"python" | "py" => Some(Language::Python),
_ => None,
}
}
}
/// A gutter cell sized to the whole row.
pub(crate) fn gutter_cell<E>(cx: &App, color: Hsla, content: E) -> gpui::Div
where
E: IntoElement,
{
let theme = cx.theme();
div()
.size(CODE_GUTTER_WIDTH)
.flex()
.items_center()
.justify_center()
.flex_none()
.font_family(theme.mono_font)
.text_size(theme.sizes.small.text_size)
.line_height(gpui::relative(1.0))
.text_color(color)
.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<usize>, HighlightStyle)> = Vec::new();
let mut offset = 0usize;
for span in &line.spans {
let end = offset + span.text.len();
if span.role != Role::Text {
highlights.push((
offset..end,
HighlightStyle {
color: Some(span.role.color(colors, ramps)),
..Default::default()
},
));
}
offset = end;
}
StyledText::new(line.text()).with_highlights(highlights)
}
+9
View File
@@ -0,0 +1,9 @@
# Licenses
## Bundled icons (`assets/*.svg`)
Lucide, ISC License, © Lucide Contributors. Fetched from https://github.com/lucide-icons/lucide (main) on 2026-10-28 and 2026-11-13. These are the offline fallback glyphs, see https://lucide.dev/license.
## Platform glyph sets (not bundled)
SF Symbols (macOS) and Segoe Fluent Icons (Windows) are resolved through the operating system at runtime and are never extracted, modified, or redistributed. Freedesktop icons are loaded from the user's installed icon themes.

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

Before

Width:  |  Height:  |  Size: 320 B

After

Width:  |  Height:  |  Size: 320 B

Before

Width:  |  Height:  |  Size: 319 B

After

Width:  |  Height:  |  Size: 319 B

Before

Width:  |  Height:  |  Size: 320 B

After

Width:  |  Height:  |  Size: 320 B

Some files were not shown because too many files have changed in this diff Show More