From 0b8b6193429ae6aa20abdbbbadfb772171a3b3cc Mon Sep 17 00:00:00 2001 From: Ren Amamiya Date: Wed, 28 Oct 2026 17:02:02 +0700 Subject: [PATCH] add button --- AGENTS.md | 2 +- Cargo.lock | 283 ++++++++++++++++++++++++++++++--- crates/core/Cargo.toml | 5 + crates/core/src/button.rs | 181 +++++++++++++++++++++ crates/core/src/common.rs | 13 ++ crates/core/src/lib.rs | 12 +- crates/core/tests/button.rs | 89 +++++++++++ crates/theme/src/definition.rs | 1 + crates/theme/src/lib.rs | 27 +++- crates/theme/src/resolve.rs | 22 ++- docs/PLAN.md | 54 ++++--- examples/gallery/Cargo.toml | 1 + examples/gallery/src/main.rs | 72 ++++++++- 13 files changed, 708 insertions(+), 54 deletions(-) create mode 100644 crates/core/src/button.rs create mode 100644 crates/core/src/common.rs create mode 100644 crates/core/tests/button.rs diff --git a/AGENTS.md b/AGENTS.md index f310f2d..f26ad96 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -5,7 +5,7 @@ - Keep doc comments and comments simple, one line, straightforward, and unbloated. - Prefer implementing functionality in existing files unless it is a new logical component. Avoid creating many small files. - Prefer `impl` blocks over standalone functions: place functionality as methods or associated functions on the relevant type, extending the type's existing `impl` block instead of creating a duplicate one in another file. -- Prefer generic parameters with a `where` clause over argument-position `impl Trait` in function signatures (`fn extend(&mut self, elements: I) where I: IntoIterator`); return-position `impl Trait` stays. +- Always use generic parameters with a `where` clause instead of argument-position `impl Trait` in function signatures (`fn extend(&mut self, elements: I) where I: IntoIterator`); return-position `impl Trait` stays. - Do not wrap dependency APIs in project structs or pass-through helper functions; call their methods directly where needed. Extract a helper only when it holds real logic that is used in more than one place. - Bind a global store handle to a local before using it (`let theme = Theme::global(cx);` then `theme.…`) instead of chaining `::global(cx)` inline. - Avoid using functions that panic like `unwrap()`; instead use mechanisms like `?` to propagate errors. diff --git a/Cargo.lock b/Cargo.lock index 19cfc48..24cb3e6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -73,7 +73,7 @@ checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" dependencies = [ "cfg-if", "cipher", - "cpufeatures", + "cpufeatures 0.2.17", "zeroize", ] @@ -338,6 +338,12 @@ dependencies = [ "syn 3.0.9", ] +[[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" @@ -365,7 +371,7 @@ dependencies = [ "num-traits", "pastey 0.1.1", "rayon", - "thiserror", + "thiserror 2.0.21", "v_frame", "y4m", ] @@ -428,6 +434,10 @@ name = "bit-vec" version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5727b15fa97d4f4fee0a3b7c3d550ed0269f54329207b86388de918604e31269" +dependencies = [ + "borsh", + "serde", +] [[package]] name = "bit_field" @@ -505,6 +515,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.9", +] + [[package]] name = "built" version = "0.8.1" @@ -618,6 +652,17 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + [[package]] name = "chrono" version = "0.4.45" @@ -698,6 +743,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" @@ -750,6 +804,12 @@ dependencies = [ "libc", ] +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + [[package]] name = "core_maths" version = "0.1.1" @@ -792,6 +852,15 @@ dependencies = [ "libc", ] +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + [[package]] name = "crc32fast" version = "1.5.3" @@ -820,6 +889,15 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-utils" version = "0.8.23" @@ -879,7 +957,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", @@ -1169,6 +1247,12 @@ version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +[[package]] +name = "fixedbitset" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" + [[package]] name = "flate2" version = "1.1.10" @@ -1209,6 +1293,12 @@ dependencies = [ "spin 0.9.9", ] +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + [[package]] name = "foldhash" version = "0.2.0" @@ -1328,6 +1418,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" @@ -1409,6 +1512,7 @@ name = "gallery" version = "0.1.0" dependencies = [ "gpui", + "gpui-native-core", "gpui-native-icons", "gpui-native-theme", "gpui_platform", @@ -1458,6 +1562,7 @@ dependencies = [ "cfg-if", "libc", "r-efi 6.0.0", + "rand_core 0.10.1", ] [[package]] @@ -1518,7 +1623,7 @@ dependencies = [ "hashbrown 0.16.1", "log", "presser", - "thiserror", + "thiserror 2.0.21", "windows 0.62.2", ] @@ -1540,6 +1645,7 @@ dependencies = [ "embed-resource", "etagere", "futures", + "futures-concurrency", "getrandom 0.3.4", "gpui_macros", "gpui_shared_string", @@ -1558,8 +1664,10 @@ dependencies = [ "parking", "parking_lot", "pin-project", - "pollster", + "pollster 0.4.0", + "postage", "profiling", + "proptest", "rand 0.9.5", "raw-window-handle", "refineable", @@ -1576,12 +1684,13 @@ dependencies = [ "strum", "sum_tree", "taffy", - "thiserror", + "thiserror 2.0.21", "ttf-parser", "url", "usvg", "uuid", "waker-fn", + "web-time", "windows 0.62.2", "zed-scap", ] @@ -1591,6 +1700,8 @@ name = "gpui-native-core" version = "0.1.0" dependencies = [ "gpui", + "gpui-native-icons", + "gpui-native-theme", ] [[package]] @@ -1659,7 +1770,7 @@ dependencies = [ "parking_lot", "pathfinder_geometry", "smallvec", - "thiserror", + "thiserror 2.0.21", "zed-font-kit", ] @@ -2181,7 +2292,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" dependencies = [ "byteorder-lite", - "quick-error", + "quick-error 2.0.1", ] [[package]] @@ -2630,7 +2741,7 @@ dependencies = [ "once_cell", "rustc-hash 1.1.0", "spirv", - "thiserror", + "thiserror 2.0.21", "unicode-ident", ] @@ -2642,7 +2753,7 @@ dependencies = [ "hashbrown 0.17.1", "indexmap", "rustc-hash 1.1.0", - "thiserror", + "thiserror 2.0.21", ] [[package]] @@ -3338,6 +3449,12 @@ dependencies = [ "windows-sys", ] +[[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" @@ -3368,6 +3485,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" @@ -3435,6 +3567,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", + "core_detect", + "num-traits", + "proptest-macro", + "rand 0.10.3", + "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.9", +] + [[package]] name = "pulp" version = "0.22.3" @@ -3473,6 +3638,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" @@ -3530,6 +3701,16 @@ dependencies = [ "rand_core 0.9.5", ] +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "getrandom 0.4.3", + "rand_core 0.10.1", +] + [[package]] name = "rand_chacha" version = "0.3.1" @@ -3568,6 +3749,21 @@ dependencies = [ "getrandom 0.3.4", ] +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[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" @@ -3610,7 +3806,7 @@ dependencies = [ "rand 0.9.5", "rand_chacha 0.9.0", "simd_helpers", - "thiserror", + "thiserror 2.0.21", "v_frame", "wasm-bindgen", ] @@ -3624,7 +3820,7 @@ dependencies = [ "avif-serialize", "imgref", "loop9", - "quick-error", + "quick-error 2.0.1", "rav1e", "rayon", "rgb", @@ -3721,7 +3917,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" dependencies = [ "libredox", - "thiserror", + "thiserror 2.0.21", ] [[package]] @@ -3874,6 +4070,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" @@ -4097,7 +4305,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", - "cpufeatures", + "cpufeatures 0.2.17", "digest", ] @@ -4400,7 +4608,7 @@ version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f37a6c354fd28fc9e322ed9bd47e3959576dad28c9d58ea1cf888cce1c7ccb36" dependencies = [ - "thiserror", + "thiserror 2.0.21", "windows 0.62.2", "windows-version", ] @@ -4427,13 +4635,33 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + [[package]] name = "thiserror" version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ - "thiserror-impl", + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] @@ -4456,7 +4684,7 @@ dependencies = [ "fax", "flate2", "half", - "quick-error", + "quick-error 2.0.1", "weezl", "zune-jpeg", ] @@ -4681,6 +4909,12 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + [[package]] name = "unicode-bidi" version = "0.3.18" @@ -4836,6 +5070,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" @@ -5023,7 +5266,7 @@ dependencies = [ "rustc-hash 1.1.0", "scopeguard", "smallvec", - "thiserror", + "thiserror 2.0.21", "wgpu-core-deps-apple", "wgpu-core-deps-emscripten", "wgpu-core-deps-linux-android-bsd", @@ -5115,7 +5358,7 @@ dependencies = [ "renderdoc-sys", "smallvec", "static_assertions", - "thiserror", + "thiserror 2.0.21", "wasm-bindgen", "wayland-sys", "web-sys", @@ -5248,7 +5491,7 @@ checksum = "3a4df73e95feddb9ec1a7e9c2ca6323b8c97d5eeeff78d28f1eccdf19c882b24" dependencies = [ "parking_lot", "rayon", - "thiserror", + "thiserror 2.0.21", "windows 0.61.3", "windows-future 0.2.1", ] diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 26fbe5d..36b9b22 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -6,6 +6,11 @@ description = "The GPUI components every application needs, one cargo feature ea [dependencies] gpui = { workspace = true } +gpui-native-icons = { workspace = true } +gpui-native-theme = { workspace = true } + +[dev-dependencies] +gpui = { workspace = true, features = ["test-support"] } [features] default = ["full"] diff --git a/crates/core/src/button.rs b/crates/core/src/button.rs new file mode 100644 index 0000000..61b4c8c --- /dev/null +++ b/crates/core/src/button.rs @@ -0,0 +1,181 @@ +//! The push button: the API template for every control that follows. + +use gpui::prelude::FluentBuilder as _; +use gpui::{ + App, BoxShadow, ClickEvent, ElementId, InteractiveElement as _, IntoElement, + ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, + Styled as _, Window, px, +}; +use gpui_native_icons::{IconRole, icon}; +use gpui_native_theme::ActiveTheme as _; + +use crate::common::h_flex; + +/// The single activation handler, shared by pointer, Enter, and Space. +type ClickHandler = Box; + +/// Which visual treatment a button uses. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ButtonVariant { + /// Accent-filled; the platform's default action. + #[default] + Primary, + /// Neutral and bordered; the everyday companion to `Primary`. + Secondary, + /// Unpainted until hovered, for toolbars and dense UI. + Ghost, + /// The destructive action. + Destructive, +} + +/// A push button: pointer, Enter, and Space all fire the single `on_click`. +#[derive(IntoElement)] +pub struct Button { + id: ElementId, + label: Option, + icon: Option, + variant: ButtonVariant, + disabled: bool, + a11y_label: Option, + on_click: Option, +} + +impl Button { + /// Creates a primary button. + pub fn new(id: I) -> Self + where + I: Into, + { + Self { + id: id.into(), + label: None, + icon: None, + variant: ButtonVariant::default(), + disabled: false, + a11y_label: None, + on_click: None, + } + } + + /// Sets the visible label. + pub fn label(mut self, label: L) -> Self + where + L: Into, + { + self.label = Some(label.into()); + self + } + + /// Shows an icon beside the label. + pub fn icon(mut self, role: IconRole) -> Self { + self.icon = Some(role); + self + } + + /// Sets the visual treatment. + pub fn variant(mut self, variant: ButtonVariant) -> Self { + self.variant = variant; + self + } + + /// Renders the button inert, unfocusable, and dimmed; disabled always wins. + pub fn disabled(mut self, disabled: bool) -> Self { + self.disabled = disabled; + self + } + + /// Overrides the accessibility label, which defaults to the visible label. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } + + /// The single activation handler, fired by pointer, Enter, and Space. + pub fn on_click(mut self, handler: F) -> Self + where + F: Fn(&ClickEvent, &mut Window, &mut App) + 'static, + { + self.on_click = Some(Box::new(handler)); + self + } +} + +impl 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 on_click = self.on_click; + let a11y_label = self.a11y_label.or_else(|| self.label.clone()); + + 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.secondary), + colors.secondary_foreground, + ramps.secondary.hover, + ramps.secondary.pressed, + ), + ButtonVariant::Ghost => ( + None, + colors.foreground, + colors.muted, + ramps.secondary.pressed, + ), + ButtonVariant::Destructive => ( + Some(ramps.destructive.base), + colors.destructive_foreground, + ramps.destructive.hover, + ramps.destructive.pressed, + ), + }; + + h_flex() + .id(self.id) + .role(Role::Button) + .justify_center() + .h_7() + .px_4() + .gap_1p5() + .rounded(theme.radius.control) + .text_sm() + .when(self.variant == ButtonVariant::Secondary, |button| { + button.border_1().border_color(colors.border) + }) + .when_some(background, |button, background| button.bg(background)) + .text_color(foreground) + .when_some(a11y_label, |button, label| button.aria_label(label)) + .when_some(self.icon, |button, role| { + button.child(icon(role).color(foreground)) + }) + .when_some(self.label, |button, label| button.child(label)) + .when(self.disabled, |button| button.opacity(0.5)) + .when(!self.disabled, |button| { + button + .cursor_pointer() + .focusable() + .tab_stop(true) + .hover(move |style| style.bg(hover)) + .active(move |style| style.bg(pressed)) + .focus_visible(|style| { + // Paint-only keyboard ring; the width joins the native + // metrics table when that lands. + style.shadow(vec![ + BoxShadow::new(px(0.), px(0.), colors.ring).spread_radius(px(3.)), + ]) + }) + .when_some(on_click, |button, on_click| { + button.on_click(move |event, window, cx| on_click(event, window, cx)) + }) + }) + } +} diff --git a/crates/core/src/common.rs b/crates/core/src/common.rs new file mode 100644 index 0000000..cb5ab1f --- /dev/null +++ b/crates/core/src/common.rs @@ -0,0 +1,13 @@ +//! Shared element constructors and small style helpers. + +use gpui::{Div, Styled as _, div}; + +/// A row whose children center on the cross axis. +pub fn h_flex() -> Div { + div().flex().flex_row().items_center() +} + +/// A column whose children stretch across the cross axis. +pub fn v_flex() -> Div { + div().flex().flex_col() +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index d60a914..67ac608 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -1,8 +1,6 @@ //! The components every application needs, one cargo feature each. -//! -//! Components land one per feature: `button`, `checkbox`, `input`, … -//! `default-features = false` plus the features you want for a lean build; -//! `full` (the default) for everything. Features gate whole modules and are -//! additive only; each component adds its `#[cfg(feature = "…")] pub mod` -//! declaration together with its file. Shared helpers promoted per the -//! third-use rule live in the ungated `common` module once one exists. + +pub mod common; + +#[cfg(feature = "button")] +pub mod button; diff --git a/crates/core/tests/button.rs b/crates/core/tests/button.rs new file mode 100644 index 0000000..df3c820 --- /dev/null +++ b/crates/core/tests/button.rs @@ -0,0 +1,89 @@ +use std::{cell::RefCell, rc::Rc}; + +use gpui::{ + AnyWindowHandle, AppContext as _, Context, IntoElement, KeyDownEvent, KeyUpEvent, Keystroke, + Modifiers, ParentElement as _, Render, Styled as _, TestAppContext, VisualTestContext, Window, + div, point, px, +}; +use gpui_native_core::button::Button; +use gpui_native_theme::Theme; + +struct Harness { + clicks: Rc>, + disabled: bool, +} + +impl Render for Harness { + fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { + let clicks = self.clicks.clone(); + div().size_full().flex().flex_col().child( + Button::new("test-button") + .label("Save") + .disabled(self.disabled) + .on_click(move |_, _, _| *clicks.borrow_mut() += 1), + ) + } +} + +/// A maximized window whose button stretches across the top 28px, so +/// `point(px(60.), px(14.))` always lands on it. +fn button_window(disabled: bool) -> (VisualTestContext, AnyWindowHandle, Rc>) { + let mut cx = TestAppContext::single(); + cx.update(Theme::init); + let clicks = Rc::new(RefCell::new(0)); + let harness_clicks = clicks.clone(); + let window = cx.add_window(move |_, _| Harness { + clicks: harness_clicks, + disabled, + }); + let window = window.into(); + cx.update_window(window, |_, window, cx| { + window.draw(cx).clear(cx); + }) + .unwrap(); + (VisualTestContext::from_window(window, &cx), window, clicks) +} + +fn draw(cx: &mut VisualTestContext, window: AnyWindowHandle) { + cx.update_window(window, |_, window, cx| { + window.draw(cx).clear(cx); + }) + .unwrap(); +} + +#[test] +fn pointer_click_fires_on_click() { + let (mut cx, _window, clicks) = button_window(false); + cx.simulate_click(point(px(60.), px(14.)), Modifiers::default()); + assert_eq!(*clicks.borrow(), 1); +} + +#[test] +fn disabled_button_ignores_clicks() { + let (mut cx, _window, clicks) = button_window(true); + cx.simulate_click(point(px(60.), px(14.)), Modifiers::default()); + assert_eq!(*clicks.borrow(), 0); +} + +#[test] +fn enter_and_space_fire_on_click_while_focused() { + let (mut cx, window, clicks) = button_window(false); + cx.simulate_click(point(px(60.), px(14.)), Modifiers::default()); + assert_eq!(*clicks.borrow(), 1, "the pointer click itself activates"); + + // Repaint with the button focused so its Enter/Space handlers register. + draw(&mut cx, window); + + for key in ["enter", "space"] { + cx.simulate_event(KeyDownEvent { + keystroke: Keystroke::parse(key).unwrap(), + is_held: false, + prefer_character_input: false, + }); + cx.simulate_event(KeyUpEvent { + keystroke: Keystroke::parse(key).unwrap(), + }); + } + + assert_eq!(*clicks.borrow(), 3, "Enter and Space each fire on_click"); +} diff --git a/crates/theme/src/definition.rs b/crates/theme/src/definition.rs index 06bbde4..583d515 100644 --- a/crates/theme/src/definition.rs +++ b/crates/theme/src/definition.rs @@ -10,6 +10,7 @@ use crate::ThemeVariant; #[derive(Clone, Debug, Default, PartialEq, Deserialize)] pub struct ThemeDefinition { pub mode: Option, + pub control_radius: Option, pub accent: Option, pub accent_foreground: Option, pub background: Option, diff --git a/crates/theme/src/lib.rs b/crates/theme/src/lib.rs index c618d9c..bdaf4ba 100644 --- a/crates/theme/src/lib.rs +++ b/crates/theme/src/lib.rs @@ -20,7 +20,7 @@ pub use ramps::{AccentShades, Oklch}; pub use resolve::{Ramps, ResolvedTheme}; pub use system::{AccessibilityPreferences, PartialPalette, SourceKind, SystemTheme}; -use gpui::{App, Global, WindowAppearance}; +use gpui::{App, Global, Pixels, WindowAppearance, px}; /// Light or dark, resolved from the system appearance. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Deserialize)] @@ -46,11 +46,35 @@ pub struct Theme { pub variant: ThemeVariant, pub colors: ColorTokens, pub ramps: Ramps, + pub radius: Radius, pub accessibility: AccessibilityPreferences, } impl Global for Theme {} +/// Corner radii components paint from; grows one class at a time. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Radius { + pub control: Pixels, +} + +impl Default for Radius { + fn default() -> Self { + Self { control: px(6.) } + } +} + +/// Reads the resolved theme global from any app context. +pub trait ActiveTheme { + fn theme(&self) -> &Theme; +} + +impl ActiveTheme for App { + fn theme(&self) -> &Theme { + Theme::global(self) + } +} + impl Theme { /// Reads the theme global. Panics before `init`. pub fn global(cx: &App) -> &Self { @@ -62,6 +86,7 @@ impl Theme { variant: resolved.variant, colors: resolved.colors, ramps: resolved.ramps, + radius: resolved.radius, accessibility: resolved.accessibility, } } diff --git a/crates/theme/src/resolve.rs b/crates/theme/src/resolve.rs index 95e5ae7..8fa6fdc 100644 --- a/crates/theme/src/resolve.rs +++ b/crates/theme/src/resolve.rs @@ -6,12 +6,14 @@ use crate::definition::ThemeDefinition; use crate::ramps::{AccentShades, Oklch, contrast_foreground, derive_shades, mix}; use crate::system::SystemTheme; -use crate::{ColorTokens, ThemeVariant}; +use crate::{ColorTokens, Radius, ThemeVariant}; +use gpui::px; /// Derived state shades for the colors that get pressed and hovered. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Ramps { pub primary: AccentShades, + pub secondary: AccentShades, pub destructive: AccentShades, } @@ -21,6 +23,7 @@ pub struct ResolvedTheme { pub variant: ThemeVariant, pub colors: ColorTokens, pub ramps: Ramps, + pub radius: Radius, pub accessibility: crate::system::AccessibilityPreferences, } @@ -134,10 +137,20 @@ pub(crate) fn resolve( .to_hsla(); } + let mut radius = Radius::default(); + if let Some(control) = preset.and_then(|def| def.control_radius) { + radius.control = px(control); + } + ResolvedTheme { variant, ramps: Ramps { primary: derive_shades(primary, colors.background, variant == ThemeVariant::Dark), + secondary: derive_shades( + colors.secondary, + colors.background, + variant == ThemeVariant::Dark, + ), destructive: derive_shades( destructive, colors.background, @@ -145,6 +158,7 @@ pub(crate) fn resolve( ), }, colors, + radius, accessibility, } } @@ -188,6 +202,8 @@ mod tests { assert_eq!(resolved.colors.background, base.background); assert_eq!(resolved.colors.accent, base.accent); assert_eq!(resolved.ramps.primary.base, base.primary); + assert_eq!(resolved.ramps.secondary.base, base.secondary); + assert_eq!(resolved.radius.control, px(6.)); } } @@ -240,7 +256,7 @@ mod tests { #[test] fn preset_beats_system_and_the_mode_override_beats_everything() { let def = ThemeDefinition::parse_toml( - "mode = \"dark\"\nbackground = \"#1a1b26\"\naccent = \"#7aa2f7\"\n", + "mode = \"dark\"\nbackground = \"#1a1b26\"\naccent = \"#7aa2f7\"\ncontrol_radius = 12.0\n", ) .unwrap(); let palette = PartialPalette { @@ -259,6 +275,8 @@ mod tests { assert!((bg.b - 0x26 as f32 / 255.0).abs() < 0.001); let accent = Rgba::from(resolved.colors.accent); assert!((accent.r - 0x7a as f32 / 255.0).abs() < 0.001); + // And the metric override beats the radius default. + assert_eq!(resolved.radius.control, px(12.)); let forced = resolve( &system(ThemeVariant::Light, palette, None), diff --git a/docs/PLAN.md b/docs/PLAN.md index 12aac8b..bbbb2b9 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -1,6 +1,6 @@ # gpui-native-kit — Project Plan -Rev 5 (2026-10-28). Changes from rev 4: the workspace is split into focused crates — `theme`, `icons`, `core`, and sibling crates for advanced elements (`editor`, `data`, …) — with per-component cargo features so applications enable only what they use. System icons are now in scope: semantic roles resolved to SF Symbols / Segoe Fluent Icons / freedesktop icons per platform, with a bundled Lucide fallback. Everything else (empty-project reset, own lean implementations, theme engine as the product) stands. +Rev 6 (2026-10-28). Changes from rev 5: components are built **one element at a time behind a review gate** — each unit is designed, implemented, tested, shown in the gallery, and reviewed before the next starts (batch waves are gone). [gpui-kit `base`](https://github.com/longbridge/gpui-kit/tree/main/crates/base) is re-admitted as the **API-design reference**: its unstyled-control conventions (controlled state, one activation path for pointer + Enter + Space, semantic states, a11y labels) shape our component APIs, and small utilities may be adapted where they help. Everything else (empty-project reset, theme engine as the product, crate split, per-component features) stands. ## 1. Vision @@ -12,12 +12,12 @@ Consumption is flexible: small focused crates, per-component cargo features, and | Crate | What it is | Verdict | What we take | | --- | --- | --- | --- | -| gpui-kit (longbridge) | Unstyled `base` behavior layer + styled component library | Dropped: over-engineered base; review-gated porting too slow; upstream pins `gpui-pre` snapshots | Nothing; previous ports reverted | +| gpui-kit (longbridge) | Unstyled `base` behavior layer (controlled state, one activation path, semantic states, a11y roles, focus utilities) + styled component library | Not a wholesale foundation: the full base is larger than we need and pins `gpui-pre` snapshots. **But `base` is the API-design reference for our components** (D20), and its small utilities are adapted where they help | API shapes: `Button::new("save")` unstyled + `.on_click` as the single path for pointer/Enter/Space; controlled `checked` + `on_change(next)`; `disabled`/`selected` semantic states resolved after the builder chain, disabled last; `accessibility_label`; composable parts (`CheckboxIndicator`, `SwitchTrack`/`SwitchThumb`) where a component needs them. Utilities worth adapting: `h_flex`/`v_flex`, `StyledExt`, `StateStyle`, focus-ring helper | | gpuikit (iamnbutler) | Web/SwiftUI-style toolkit (editor, input, keymap, markdown, selection, a11y modules) on `gpui-unofficial` | Not a foundation: builds on the `gpui-unofficial` crates.io distribution (conflicts with D3); generic theme system with no per-OS native look | Component API ergonomics; showcase/gallery pattern | | bezel (crabtalk) | SwiftUI-lean library; style flows through the environment — `Theme::of(cx)` + catalog traits, zero style parameters, `Brand`/`Tint` hue re-theming; own gpui fork (`bezel-gpui`) | Not a foundation: gpui fork (conflicts with D3); one visual language (macOS-leaning HIG), not per-OS native | Environment-first styling: components read the theme global at paint time and take no color/size parameters; `Brand`-style hue overrides inform custom themes | | zeron (zeronsh) | Production gpui app (coding-agent control plane; crates: ui, theme, text, syntax, term, …) | Not a foundation — an application, not a library | Existence proof that gpui scales; app-level patterns for data-heavy screens | -Decision D15: we depend on no UI toolkit and port nothing. These crates (plus native-theme, D1) are read for API and design ideas only — and always simplified, never mirrored 1:1. When in doubt, ship the smaller API. +Decision D15: we depend on no UI toolkit and port no wholesale subsystems. These crates (plus native-theme, D1) are read for API and design ideas — and always simplified, never mirrored 1:1. When in doubt, ship the smaller API. ## 3. Background facts (verified) @@ -78,11 +78,17 @@ One-way, no cycles. Nothing depends on `gpui-component`, `gpui-kit`, `gpuikit`, ### 4.3 Component design -- **Controlled components:** the owner passes the current value, callbacks report intent, the owner updates state and calls `cx.notify()`. No second source of truth. +- **One element at a time, review-gated (D20).** Each component is one unit: API sketch → implementation → tests → gallery page → review. The next unit starts only after the previous one is approved. No batch waves. +- **API shape follows gpui-kit `base` conventions** (adapted, simplified where we can): + - Controlled components: the owner passes the current value, the callback reports the **next** value, the owner updates state and calls `cx.notify()`. `Checkbox::new(id).checked(v).on_change(move |next, window, cx| …)`. + - One activation path: pointer, Enter, and Space all fire the same `on_click` (gpui synthesizes keyboard clicks for tracked focus elements). + - Semantic states as builders — `disabled(bool)`, `selected(bool)`, `checked(bool)`, `pressed(bool)` — resolved **after** the builder chain and painted from theme state colors; disabled resolves last and always wins. + - `accessibility_label(...)` on every control; correct accesskit role per control (`Button`, `CheckBox`, `Switch`, `RadioButton`, `Link`, …). + - Composable parts (`CheckboxIndicator`, `SwitchTrack`/`Thumb`) only where a component genuinely needs independently painted pieces — we paint from tokens, so most parts collapse into the component itself; decide per review. - **Value-like controls** are `#[derive(IntoElement)]` + `RenderOnce`; stateful ones are `Entity` the application owns. - **No style parameters** (bezel's model): a component reads the theme global at paint time and takes zero color/size arguments. Overrides are gpui style modifiers chained by the caller. - **Behavior is inline.** Activation, focus, keyboard, dragging, and a11y are written per component with gpui primitives (`Interactivity`, `FocusHandle` + `tab_stop(true)`, `actions!`, a11y builders). A helper is promoted to shared `common` only when a third component needs it — no pre-built behavior layer. -- **APIs are our own**, shaped by what our components need; inspiration from other crates is distilled, never copied 1:1. +- **Deliberate divergence from base:** our `Link` opens `href` through the platform by default (`cx.open_url`) — native feel is the product — with `on_click` as an override for apps that route internally. Base never opens URLs; we do unless told otherwise. - Each component has a named native reference per platform (NSButton / WinUI Button / Adwaita / Breeze) recorded on its gallery page; "native feel" is reviewed against those references. - Naming seams per AGENTS.md: `is_`/`has_` readers, `with_` builders, `set_` mutation, `on_` callbacks, `State`/`Delegate` suffixes, stable domain-derived `ElementId`s. @@ -178,16 +184,26 @@ Native feel is half geometry. Per-platform tables for: control heights and paddi Real semantic colors per platform (`NSColor` / `UISettings` / portal) instead of hardcoded approximations; OKLCH accent-ramp derivation; native metrics as a first-class deliverable; Omarchy as a first-class target; a designed neutral fallback; custom themes with overlay merge priority and live reload; a role-minimal token set instead of a 139-field toolkit mapping. -## 6. Component roadmap (written from scratch) +## 6. Component roadmap (review units, in order) -| Wave | Crate | Components | -| --- | --- | --- | -| 1 — controls | core | Button, Checkbox, Switch, Radio + RadioGroup, Toggle, Link, Slider, Progress, Avatar; plus the `IconRole` catalog + Lucide fallback | -| 2 — input | core | Input (single-line first, then multiline), NumberInput. String buffer + `unicode-segmentation` word movement; the field owns its own selection. Multiline editing may seed `crates/editor`. | -| 3 — overlays | core | Popover, Tooltip, Menu, Dialog, AlertDialog, Sheet, Toast | -| 4 — data & navigation | data (new) | List, Table, Tree, Tabs, Sidebar | -| 5 — pickers | pickers or data (decide at wave time) | Calendar/DatePicker, TimeField, ColorPicker | -| editor | editor (new) | Text/code editor, syntax highlighting (D12) | +Each row is one review unit: build it, show it in the gallery, review, then move on. + +| Unit | Crate | Component | Notes | +| --- | --- | --- | --- | +| 1 | core | Button | Variants (primary/secondary/ghost/destructive) painted from token ramps; single activation path; disabled + a11y role. The API template for everything after. | +| 2 | core | Checkbox | Controlled `checked` + `on_change(next)`; Check icon from the icons crate. | +| 3 | core | Switch | Controlled pill + thumb; thumb slides once motion exists. | +| 4 | core | Radio + RadioGroup | Group owns the selected value; radios never self-uncheck. | +| 5 | core | Toggle | Controlled `pressed` (aria-pressed). | +| 6 | core | Link | `href` opens via platform by default; `on_click` overrides. | +| 7 | core | Slider | Click-to-set + in-track drag; controlled value. | +| 8 | core | Progress | Determinate + indeterminate. | +| 9 | core | Avatar | Initials; image slot later. | +| 10 | core | Input (single-line) then multiline, NumberInput | String buffer + `unicode-segmentation` word movement; the field owns its own selection. May seed `crates/editor`. | +| 11+ | core | Popover, Tooltip, Menu, Dialog, AlertDialog, Sheet, Toast | One unit each, same gate. | +| then | data (new) | List, Table, Tree, Tabs, Sidebar | Created on demand, same gate. | +| then | pickers or data | Calendar/DatePicker, TimeField, ColorPicker | Decide at unit time. | +| editor | editor (new) | Text/code editor, syntax highlighting (D12) | Same gate. | Deferred until a real need: Markdown/TextView, Dock, VirtualList, window-wide text selection, a motion system (use gpui's built-in animations first), charts. @@ -197,7 +213,7 @@ Deferred until a real need: Markdown/TextView, Dock, VirtualList, window-wide te | --- | --- | --- | | A — scaffold (next) | Workspace per §4.1: theme stub, icons crate (`IconRole` + Lucide fallback), core crate with feature scaffolding (zero components), facade, gallery shell, CI incl. feature checks | `gallery` opens a window reading the theme global; `core` builds at default / no-default / all / each-feature-alone | | B — theme engine core | Token model + resolve + presets (neutral fallback, tokyo-night) + macOS source + `ThemeWatcher`; gallery theme inspector. Done: `resolve` overlay chain (base → system → preset → mode override → high-contrast) is pure and tested; OKLCH accent-ramp engine; `NSColor`/`NSWorkspace` adapter; distributed-notification watchers; inspector with live mode/preset switching. (The "Button + Checkbox painted from live tokens" proof moves to Phase C — those components land there; the gallery inspector proves the live pipeline meanwhile.) | -| C — controls | Wave 1 in `core`, one feature each; macOS SF Symbols resolver behind the icon seam | Each control: tests + gallery page + native-reference screenshots; icon browser shows per-role resolution | +| C — controls | One review unit at a time (§6, units 1–9), each: API per §4.3 + tests + gallery page → review gate. macOS SF Symbols resolver behind the icon seam lands with the first unit that shows it matters | Per unit: activation, controlled round-trip, and disabled inertness tested; gallery page shows the live control against the theme; your approval closes the unit | | D — input | Wave 2 | Single-line input with cursor, selection, clipboard; NumberInput | | E — overlays | Wave 3 | Focus trapping and escape/dismiss semantics per overlay | | F — platforms + data | `crates/data` + Windows/GNOME/KDE/Omarchy theme sources + Segoe Fluent/freedesktop icon resolvers | Side-by-side gallery screenshots per platform | @@ -213,6 +229,7 @@ Pure tests for resolve/overlay chain, payload parsing (fixtures), icon resolutio - All code in this repo is original: Apache-2.0 (D6). - gpui: Apache-2.0 dependency, nothing copied. +- gpui-kit `base`: API-design reference (D20); where a small utility is adapted rather than reinvented, keep Apache-2.0 compliance — note the origin in a file-header comment or NOTICE. - Lucide icons: ISC — bundled subset with attribution in NOTICE. - SF Symbols and Segoe Fluent Icons: used through the operating system at runtime only; never extracted or redistributed. - native-theme, gpui-omarchy, gpuikit, bezel: inspiration only; no code copied. If that ever changes, respect their licenses. @@ -244,16 +261,17 @@ Pure tests for resolve/overlay chain, payload parsing (fixtures), icon resolutio | D12 | Editor deferred; `crates/editor` is created when wave 2's multiline editing or highlighting demands it | | D13 | Accent shades hybrid: stated platform ramps where available (WinUI, KDE), OKLCH derivation elsewhere | | D14 | Custom-theme live reload via `notify` | -| D15 | No porting, no UI-toolkit dependencies; inspiration only, always simplified — never mirrored 1:1 | +| D15 | No wholesale porting, no UI-toolkit dependencies. Component APIs follow gpui-kit `base` conventions where they fit (D20), always simplified — never mirrored 1:1; small utilities may be adapted with attribution | | D16 | No separate behavior crate; behavior lives in each component; shared helpers promoted at the third use | | D17 | `UPSTREAM.md` removed; provenance = §3 pins + git history | | D18 | Crate split for consumption: `core` (every-app components) → `editor`, `data`, … (advanced) → thin `gpui-native-kit` facade; one cargo feature per component, additive, module-gated | | D19 | System icons via semantic `IconRole`s with per-platform resolvers (SF Symbols / Segoe Fluent Icons / freedesktop) and a bundled Lucide fallback; platform glyph sets are used at runtime only, never bundled | +| D20 | Components land one element at a time behind a review gate: API sketch → implementation → tests → gallery page → review → next. gpui-kit `base` is the API-design reference for these units; its conventions (controlled state, one activation path, semantic states, a11y labels) and selected utilities are adopted, simplified | -Dropped from rev 3: D2, D5, D9 (port-era decisions). D10 (no icon bundling) is superseded by D19. +Dropped from rev 3: D2, D5, D9 (port-era decisions); the review gate returns in a lighter form as D20. D10 (no icon bundling) is superseded by D19. ## 12. Immediate next steps 1. ~~Phase A scaffold~~ ✅ — workspace, toolchain pin, CI, theme seed, icons crate, core feature scaffolding, facade, gallery shell. 2. ~~Phase B theme engine core~~ ✅ — resolve pipeline, OKLCH ramps, presets, macOS source + watchers, gallery theme inspector. -3. Then wave 1 controls (Phase C). +3. **Unit 1: Button** (next) — API per §4.3 modeled on gpui-kit `base`'s Button (single activation path, `disabled`, a11y role + label), painted from theme ramps; tests for activation / disabled inertness / keyboard activation; gallery page. → your review, then unit 2 (Checkbox). diff --git a/examples/gallery/Cargo.toml b/examples/gallery/Cargo.toml index d545b02..fd4a5e8 100644 --- a/examples/gallery/Cargo.toml +++ b/examples/gallery/Cargo.toml @@ -7,6 +7,7 @@ description = "Live preview of every component against the resolved system theme [dependencies] gpui = { workspace = true } gpui_platform = { workspace = true } +gpui-native-core = { workspace = true } gpui-native-icons = { workspace = true } gpui-native-theme = { workspace = true } diff --git a/examples/gallery/src/main.rs b/examples/gallery/src/main.rs index a359c20..a9dc855 100644 --- a/examples/gallery/src/main.rs +++ b/examples/gallery/src/main.rs @@ -4,20 +4,25 @@ use gpui::{ ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled as _, Window, WindowBounds, WindowOptions, div, px, size, }; +use gpui_native_core::button::{Button, ButtonVariant}; +use gpui_native_core::common::{h_flex, v_flex}; use gpui_native_icons::{IconAssets, IconRole, icon}; -use gpui_native_theme::Theme; +use gpui_native_theme::{ActiveTheme as _, Theme}; use gpui_platform::application; -struct Gallery; +struct Gallery { + button_clicks: usize, +} impl Render for Gallery { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { - let theme = Theme::global(cx); + let theme = cx.theme(); let colors = theme.colors; let variant = theme.variant; let source = gpui_native_theme::detected_source(cx); let mode_override = gpui_native_theme::mode_override(cx); let active_preset = gpui_native_theme::active_preset(cx); + let gallery = cx.entity(); let swatches: [(&str, gpui::Hsla); 18] = [ ("background", colors.background), @@ -68,6 +73,13 @@ impl Render for Gallery { ), ]; + let button_variants = [ + ("primary", ButtonVariant::Primary), + ("secondary", ButtonVariant::Secondary), + ("ghost", ButtonVariant::Ghost), + ("destructive", ButtonVariant::Destructive), + ]; + div() .size_full() .font_family(".SystemUIFont") @@ -93,7 +105,7 @@ impl Render for Gallery { .text_sm() .text_color(colors.muted_foreground) .child(format!( - "phase B — theme engine · source: {source} · variant: {variant:?}" + "phase C — button · source: {source} · variant: {variant:?}" )), ), ) @@ -141,6 +153,47 @@ impl Render for Gallery { })), ), ) + .child( + v_flex() + .gap_2() + .child(section_label( + "button · native refs — NSButton, WinUI Button, Adwaita, Breeze", + colors, + )) + .child( + h_flex() + .flex_wrap() + .gap_2() + .children(button_variants.map(|(name, variant)| { + let gallery = gallery.clone(); + Button::new(SharedString::from(format!("gallery-button-{name}"))) + .label(button_label(variant)) + .variant(variant) + .on_click(move |_, _, cx| { + gallery.update(cx, |gallery, cx| { + gallery.button_clicks += 1; + cx.notify(); + }); + }) + })) + .child( + Button::new("gallery-button-disabled") + .label("Disabled") + .disabled(true), + ) + .child( + Button::new("gallery-button-icon") + .label("Open") + .icon(IconRole::Folder), + ), + ) + .child( + div() + .text_xs() + .text_color(colors.muted_foreground) + .child(format!("clicked {} times", self.button_clicks)), + ), + ) .child( div() .flex() @@ -217,6 +270,15 @@ impl Render for Gallery { } } +fn button_label(variant: ButtonVariant) -> &'static str { + match variant { + ButtonVariant::Primary => "Primary", + ButtonVariant::Secondary => "Secondary", + ButtonVariant::Ghost => "Ghost", + ButtonVariant::Destructive => "Delete", + } +} + fn section_label(text: &str, colors: gpui_native_theme::ColorTokens) -> impl IntoElement + use<> { div() .text_sm() @@ -280,7 +342,7 @@ fn main() { cx.refresh_windows(); }) .detach(); - cx.new(|_| Gallery) + cx.new(|_| Gallery { button_clicks: 0 }) }, ) { eprintln!("failed to open gallery window: {err}");