style: cargo fmt with the workspace tab policy (hard_tabs)

Whitespace only; the fork has no own rustfmt.toml so the Oak root
policy applies.
This commit is contained in:
2026-08-11 23:06:13 +08:00
parent 507d7e6e8d
commit af5482d774
318 changed files with 132564 additions and 132170 deletions
+222 -222
View File
@@ -15,265 +15,265 @@ use std::time::Duration;
use anyhow::Result;
use gpui::colors::Colors;
use gpui::{
Animation, AnimationExt as _, App, AssetSource, Bounds, Context, Hsla, SharedString,
Transformation, Window, WindowBounds, WindowOptions, bounce, div, ease_in_out, linear,
percentage, prelude::*, px, rgb, size as gpui_size, svg,
Animation, AnimationExt as _, App, AssetSource, Bounds, Context, Hsla, SharedString,
Transformation, Window, WindowBounds, WindowOptions, bounce, div, ease_in_out, linear,
percentage, prelude::*, px, rgb, size as gpui_size, svg,
};
struct Assets {}
impl AssetSource for Assets {
fn load(&self, path: &str) -> Result<Option<std::borrow::Cow<'static, [u8]>>> {
std::fs::read(path)
.map(Into::into)
.map_err(Into::into)
.map(Some)
}
fn load(&self, path: &str) -> Result<Option<std::borrow::Cow<'static, [u8]>>> {
std::fs::read(path)
.map(Into::into)
.map_err(Into::into)
.map(Some)
}
fn list(&self, path: &str) -> Result<Vec<SharedString>> {
Ok(std::fs::read_dir(path)?
.filter_map(|entry| {
Some(SharedString::from(
entry.ok()?.path().to_string_lossy().into_owned(),
))
})
.collect::<Vec<_>>())
}
fn list(&self, path: &str) -> Result<Vec<SharedString>> {
Ok(std::fs::read_dir(path)?
.filter_map(|entry| {
Some(SharedString::from(
entry.ok()?.path().to_string_lossy().into_owned(),
))
})
.collect::<Vec<_>>())
}
}
const ARROW_CIRCLE_SVG: &str = concat!(
env!("CARGO_MANIFEST_DIR"),
"/examples/legacy/image/arrow_circle.svg"
env!("CARGO_MANIFEST_DIR"),
"/examples/legacy/image/arrow_circle.svg"
);
struct AnimationExample;
impl Render for AnimationExample {
fn render(&mut self, window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
fn render(&mut self, window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
div()
.id("main")
.size_full()
.p_6()
.bg(colors.background)
.overflow_scroll()
.child(
div()
.flex()
.flex_col()
.gap_6()
.max_w(px(600.))
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(
div()
.text_xl()
.font_weight(gpui::FontWeight::BOLD)
.text_color(colors.text)
.child("Animation Patterns"),
)
.child(
div()
.text_sm()
.text_color(colors.disabled)
.child("Animations, easing, and transformations in GPUI"),
),
)
.child(section(
&colors,
"Rotation Animation",
rotation_example(&colors),
))
.child(section(&colors, "Bounce Easing", bounce_example(&colors)))
.child(section(&colors, "Scale Animation", scale_example(&colors)))
.child(section(
&colors,
"Combined Animations",
combined_example(&colors),
)),
)
}
div()
.id("main")
.size_full()
.p_6()
.bg(colors.background)
.overflow_scroll()
.child(
div()
.flex()
.flex_col()
.gap_6()
.max_w(px(600.))
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(
div()
.text_xl()
.font_weight(gpui::FontWeight::BOLD)
.text_color(colors.text)
.child("Animation Patterns"),
)
.child(
div()
.text_sm()
.text_color(colors.disabled)
.child("Animations, easing, and transformations in GPUI"),
),
)
.child(section(
&colors,
"Rotation Animation",
rotation_example(&colors),
))
.child(section(&colors, "Bounce Easing", bounce_example(&colors)))
.child(section(&colors, "Scale Animation", scale_example(&colors)))
.child(section(
&colors,
"Combined Animations",
combined_example(&colors),
)),
)
}
}
fn rotation_example(colors: &Colors) -> impl IntoElement {
let text_muted = colors.disabled;
let accent = colors.selected;
let text_muted = colors.disabled;
let accent = colors.selected;
div()
.flex()
.flex_col()
.gap_3()
.child(
div()
.text_xs()
.text_color(text_muted)
.child("Continuous rotation with ease_in_out easing"),
)
.child(
div().flex().items_center().justify_center().h_24().child(
svg()
.size_16()
.overflow_hidden()
.path(ARROW_CIRCLE_SVG)
.text_color(accent)
.with_animation(
"rotation",
Animation::new(Duration::from_secs(2))
.repeat()
.with_easing(ease_in_out),
|svg, delta| {
svg.with_transformation(Transformation::rotate(percentage(delta)))
},
),
),
)
div()
.flex()
.flex_col()
.gap_3()
.child(
div()
.text_xs()
.text_color(text_muted)
.child("Continuous rotation with ease_in_out easing"),
)
.child(
div().flex().items_center().justify_center().h_24().child(
svg()
.size_16()
.overflow_hidden()
.path(ARROW_CIRCLE_SVG)
.text_color(accent)
.with_animation(
"rotation",
Animation::new(Duration::from_secs(2))
.repeat()
.with_easing(ease_in_out),
|svg, delta| {
svg.with_transformation(Transformation::rotate(percentage(delta)))
},
),
),
)
}
fn bounce_example(colors: &Colors) -> impl IntoElement {
let text_muted = colors.disabled;
let success = rgb(0x388e3c);
let text_muted = colors.disabled;
let success = rgb(0x388e3c);
div()
.flex()
.flex_col()
.gap_3()
.child(
div()
.text_xs()
.text_color(text_muted)
.child("Bouncing rotation with bounce(ease_in_out)"),
)
.child(
div().flex().items_center().justify_center().h_24().child(
svg()
.size_16()
.overflow_hidden()
.path(ARROW_CIRCLE_SVG)
.text_color(success)
.with_animation(
"bounce_rotation",
Animation::new(Duration::from_secs(2))
.repeat()
.with_easing(bounce(ease_in_out)),
|svg, delta| {
svg.with_transformation(Transformation::rotate(percentage(delta)))
},
),
),
)
div()
.flex()
.flex_col()
.gap_3()
.child(
div()
.text_xs()
.text_color(text_muted)
.child("Bouncing rotation with bounce(ease_in_out)"),
)
.child(
div().flex().items_center().justify_center().h_24().child(
svg()
.size_16()
.overflow_hidden()
.path(ARROW_CIRCLE_SVG)
.text_color(success)
.with_animation(
"bounce_rotation",
Animation::new(Duration::from_secs(2))
.repeat()
.with_easing(bounce(ease_in_out)),
|svg, delta| {
svg.with_transformation(Transformation::rotate(percentage(delta)))
},
),
),
)
}
fn scale_example(colors: &Colors) -> impl IntoElement {
let text_muted = colors.disabled;
let warning = rgb(0xf9a825);
let text_muted = colors.disabled;
let warning = rgb(0xf9a825);
div()
.flex()
.flex_col()
.gap_3()
.child(
div()
.text_xs()
.text_color(text_muted)
.child("Scale pulsing with linear easing"),
)
.child(
div().flex().items_center().justify_center().h_24().child(
svg()
.size_16()
.overflow_hidden()
.path(ARROW_CIRCLE_SVG)
.text_color(warning)
.with_animation(
"scale",
Animation::new(Duration::from_millis(1500))
.repeat()
.with_easing(bounce(linear)),
|svg, delta| {
let scale = 0.8 + (delta * 0.4);
svg.with_transformation(Transformation::scale(gpui_size(scale, scale)))
},
),
),
)
div()
.flex()
.flex_col()
.gap_3()
.child(
div()
.text_xs()
.text_color(text_muted)
.child("Scale pulsing with linear easing"),
)
.child(
div().flex().items_center().justify_center().h_24().child(
svg()
.size_16()
.overflow_hidden()
.path(ARROW_CIRCLE_SVG)
.text_color(warning)
.with_animation(
"scale",
Animation::new(Duration::from_millis(1500))
.repeat()
.with_easing(bounce(linear)),
|svg, delta| {
let scale = 0.8 + (delta * 0.4);
svg.with_transformation(Transformation::scale(gpui_size(scale, scale)))
},
),
),
)
}
fn combined_example(colors: &Colors) -> impl IntoElement {
let text_muted = colors.disabled;
let error = rgb(0xd32f2f);
let text_muted = colors.disabled;
let error = rgb(0xd32f2f);
div()
.flex()
.flex_col()
.gap_3()
.child(
div()
.text_xs()
.text_color(text_muted)
.child("Rotation + scale combined"),
)
.child(
div().flex().items_center().justify_center().h_24().child(
svg()
.size_16()
.overflow_hidden()
.path(ARROW_CIRCLE_SVG)
.text_color(error)
.with_animation(
"combined",
Animation::new(Duration::from_secs(3))
.repeat()
.with_easing(ease_in_out),
|svg, delta| {
let scale = 0.7 + (delta * 0.6);
svg.with_transformation(
Transformation::rotate(percentage(delta))
.with_scaling(gpui_size(scale, scale)),
)
},
),
),
)
div()
.flex()
.flex_col()
.gap_3()
.child(
div()
.text_xs()
.text_color(text_muted)
.child("Rotation + scale combined"),
)
.child(
div().flex().items_center().justify_center().h_24().child(
svg()
.size_16()
.overflow_hidden()
.path(ARROW_CIRCLE_SVG)
.text_color(error)
.with_animation(
"combined",
Animation::new(Duration::from_secs(3))
.repeat()
.with_easing(ease_in_out),
|svg, delta| {
let scale = 0.7 + (delta * 0.6);
svg.with_transformation(
Transformation::rotate(percentage(delta))
.with_scaling(gpui_size(scale, scale)),
)
},
),
),
)
}
fn section(colors: &Colors, title: &'static str, content: impl IntoElement) -> impl IntoElement {
let surface: Hsla = colors.container.into();
let surface: Hsla = colors.container.into();
div()
.flex()
.flex_col()
.gap_2()
.p_4()
.bg(surface.opacity(0.5))
.rounded_lg()
.child(
div()
.text_sm()
.font_weight(gpui::FontWeight::SEMIBOLD)
.text_color(colors.text)
.child(title),
)
.child(content)
div()
.flex()
.flex_col()
.gap_2()
.p_4()
.bg(surface.opacity(0.5))
.rounded_lg()
.child(
div()
.text_sm()
.font_weight(gpui::FontWeight::SEMIBOLD)
.text_color(colors.text)
.child(title),
)
.child(content)
}
fn main() {
gpui_platform::application()
.with_assets(Assets {})
.run(|cx: &mut App| {
let bounds = Bounds::centered(None, gpui_size(px(500.), px(650.)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|_, cx| cx.new(|_| AnimationExample),
)
.expect("Failed to open window");
gpui_platform::application()
.with_assets(Assets {})
.run(|cx: &mut App| {
let bounds = Bounds::centered(None, gpui_size(px(500.), px(650.)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|_, cx| cx.new(|_| AnimationExample),
)
.expect("Failed to open window");
example_prelude::init_example(cx, "Animation");
});
example_prelude::init_example(cx, "Animation");
});
}
+442 -443
View File
@@ -14,8 +14,8 @@ use std::time::Duration;
use gpui::colors::Colors;
use gpui::{
App, Bounds, Context, Entity, Render, Task, Window, WindowBounds, WindowOptions, div,
prelude::*, px, rgb, size,
App, Bounds, Context, Entity, Render, Task, Window, WindowBounds, WindowOptions, div,
prelude::*, px, rgb, size,
};
// Example 1: Simple Foreground Task
@@ -24,38 +24,38 @@ use gpui::{
// Use it when you need to perform async work that updates UI.
struct ForegroundTaskDemo {
message: String,
is_loading: bool,
message: String,
is_loading: bool,
}
impl ForegroundTaskDemo {
fn new() -> Self {
Self {
message: "Click to start a foreground task".into(),
is_loading: false,
}
}
fn new() -> Self {
Self {
message: "Click to start a foreground task".into(),
is_loading: false,
}
}
fn start_task(&mut self, cx: &mut Context<Self>) {
self.is_loading = true;
self.message = "Loading...".into();
cx.notify();
fn start_task(&mut self, cx: &mut Context<Self>) {
self.is_loading = true;
self.message = "Loading...".into();
cx.notify();
cx.spawn(async move |this, cx| {
cx.background_spawn(async {
std::thread::sleep(Duration::from_secs(1));
})
.await;
cx.spawn(async move |this, cx| {
cx.background_spawn(async {
std::thread::sleep(Duration::from_secs(1));
})
.await;
this.update(cx, |this, cx| {
this.message = "Task completed!".into();
this.is_loading = false;
cx.notify();
})
.ok();
})
.detach();
}
this.update(cx, |this, cx| {
this.message = "Task completed!".into();
this.is_loading = false;
cx.notify();
})
.ok();
})
.detach();
}
}
// Example 2: Background Task with Progress
@@ -64,51 +64,51 @@ impl ForegroundTaskDemo {
// Use it for heavy computation that shouldn't block the UI.
struct BackgroundTaskDemo {
progress: u32,
result: Option<u64>,
is_computing: bool,
progress: u32,
result: Option<u64>,
is_computing: bool,
}
impl BackgroundTaskDemo {
fn new() -> Self {
Self {
progress: 0,
result: None,
is_computing: false,
}
}
fn new() -> Self {
Self {
progress: 0,
result: None,
is_computing: false,
}
}
fn start_computation(&mut self, cx: &mut Context<Self>) {
self.is_computing = true;
self.progress = 0;
self.result = None;
cx.notify();
fn start_computation(&mut self, cx: &mut Context<Self>) {
self.is_computing = true;
self.progress = 0;
self.result = None;
cx.notify();
cx.spawn(async move |this, cx| {
for i in 0..100 {
let computation = cx.background_spawn(async move {
std::thread::sleep(Duration::from_millis(10));
(i + 1) as u64
});
cx.spawn(async move |this, cx| {
for i in 0..100 {
let computation = cx.background_spawn(async move {
std::thread::sleep(Duration::from_millis(10));
(i + 1) as u64
});
let partial_result = computation.await;
let partial_result = computation.await;
this.update(cx, |this, cx| {
this.progress = i as u32 + 1;
this.result = Some(partial_result);
cx.notify();
})
.ok();
}
this.update(cx, |this, cx| {
this.progress = i as u32 + 1;
this.result = Some(partial_result);
cx.notify();
})
.ok();
}
this.update(cx, |this, cx| {
this.is_computing = false;
cx.notify();
})
.ok();
})
.detach();
}
this.update(cx, |this, cx| {
this.is_computing = false;
cx.notify();
})
.ok();
})
.detach();
}
}
// Example 3: Cancellable Task
@@ -117,50 +117,50 @@ impl BackgroundTaskDemo {
// Store a task in a field to keep it running.
struct CancellableTaskDemo {
counter: u32,
counting_task: Option<Task<()>>,
counter: u32,
counting_task: Option<Task<()>>,
}
impl CancellableTaskDemo {
fn new() -> Self {
Self {
counter: 0,
counting_task: None,
}
}
fn new() -> Self {
Self {
counter: 0,
counting_task: None,
}
}
fn is_running(&self) -> bool {
self.counting_task.is_some()
}
fn is_running(&self) -> bool {
self.counting_task.is_some()
}
fn toggle(&mut self, cx: &mut Context<Self>) {
if self.counting_task.is_some() {
self.counting_task = None;
cx.notify();
} else {
self.counting_task = Some(cx.spawn(async move |this, cx| {
loop {
cx.background_spawn(async {
std::thread::sleep(Duration::from_millis(100));
})
.await;
fn toggle(&mut self, cx: &mut Context<Self>) {
if self.counting_task.is_some() {
self.counting_task = None;
cx.notify();
} else {
self.counting_task = Some(cx.spawn(async move |this, cx| {
loop {
cx.background_spawn(async {
std::thread::sleep(Duration::from_millis(100));
})
.await;
let should_continue = this
.update(cx, |this, cx| {
this.counter += 1;
cx.notify();
true
})
.unwrap_or(false);
let should_continue = this
.update(cx, |this, cx| {
this.counter += 1;
cx.notify();
true
})
.unwrap_or(false);
if !should_continue {
break;
}
}
}));
cx.notify();
}
}
if !should_continue {
break;
}
}
}));
cx.notify();
}
}
}
// Example 4: Task with Return Value
@@ -168,395 +168,394 @@ impl CancellableTaskDemo {
// Tasks can return values that you can await.
struct ReturnValueDemo {
numbers: Vec<i32>,
sum: Option<i32>,
is_calculating: bool,
numbers: Vec<i32>,
sum: Option<i32>,
is_calculating: bool,
}
impl ReturnValueDemo {
fn new() -> Self {
Self {
numbers: vec![1, 2, 3, 4, 5],
sum: None,
is_calculating: false,
}
}
fn new() -> Self {
Self {
numbers: vec![1, 2, 3, 4, 5],
sum: None,
is_calculating: false,
}
}
fn calculate_sum(&mut self, cx: &mut Context<Self>) {
self.is_calculating = true;
cx.notify();
fn calculate_sum(&mut self, cx: &mut Context<Self>) {
self.is_calculating = true;
cx.notify();
let numbers = self.numbers.clone();
let numbers = self.numbers.clone();
cx.spawn(async move |this, cx| {
let result = cx
.background_spawn(async move {
std::thread::sleep(Duration::from_millis(500));
numbers.iter().sum::<i32>()
})
.await;
cx.spawn(async move |this, cx| {
let result = cx
.background_spawn(async move {
std::thread::sleep(Duration::from_millis(500));
numbers.iter().sum::<i32>()
})
.await;
this.update(cx, |this, cx| {
this.sum = Some(result);
this.is_calculating = false;
cx.notify();
})
.ok();
})
.detach();
}
this.update(cx, |this, cx| {
this.sum = Some(result);
this.is_calculating = false;
cx.notify();
})
.ok();
})
.detach();
}
fn randomize(&mut self, cx: &mut Context<Self>) {
use std::collections::hash_map::RandomState;
use std::hash::{BuildHasher, Hasher};
let hasher = RandomState::new().build_hasher().finish();
self.numbers = (0..5)
.map(|i| ((hasher >> (i * 8)) & 0xFF) as i32 % 100)
.collect();
self.sum = None;
cx.notify();
}
fn randomize(&mut self, cx: &mut Context<Self>) {
use std::collections::hash_map::RandomState;
use std::hash::{BuildHasher, Hasher};
let hasher = RandomState::new().build_hasher().finish();
self.numbers = (0..5)
.map(|i| ((hasher >> (i * 8)) & 0xFF) as i32 % 100)
.collect();
self.sum = None;
cx.notify();
}
}
// Main Application
struct AsyncTasksExample {
foreground_demo: Entity<ForegroundTaskDemo>,
background_demo: Entity<BackgroundTaskDemo>,
cancellable_demo: Entity<CancellableTaskDemo>,
return_demo: Entity<ReturnValueDemo>,
foreground_demo: Entity<ForegroundTaskDemo>,
background_demo: Entity<BackgroundTaskDemo>,
cancellable_demo: Entity<CancellableTaskDemo>,
return_demo: Entity<ReturnValueDemo>,
}
impl AsyncTasksExample {
fn new(cx: &mut Context<Self>) -> Self {
Self {
foreground_demo: cx.new(|_| ForegroundTaskDemo::new()),
background_demo: cx.new(|_| BackgroundTaskDemo::new()),
cancellable_demo: cx.new(|_| CancellableTaskDemo::new()),
return_demo: cx.new(|_| ReturnValueDemo::new()),
}
}
fn new(cx: &mut Context<Self>) -> Self {
Self {
foreground_demo: cx.new(|_| ForegroundTaskDemo::new()),
background_demo: cx.new(|_| BackgroundTaskDemo::new()),
cancellable_demo: cx.new(|_| CancellableTaskDemo::new()),
return_demo: cx.new(|_| ReturnValueDemo::new()),
}
}
}
impl Render for AsyncTasksExample {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
let foreground = self.foreground_demo.read(cx);
let background = self.background_demo.read(cx);
let cancellable = self.cancellable_demo.read(cx);
let return_demo = self.return_demo.read(cx);
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
let foreground = self.foreground_demo.read(cx);
let background = self.background_demo.read(cx);
let cancellable = self.cancellable_demo.read(cx);
let return_demo = self.return_demo.read(cx);
div()
.id("main")
.size_full()
.p_6()
.bg(colors.background)
.overflow_scroll()
.child(
div()
.flex()
.flex_col()
.gap_6()
.max_w(px(500.))
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(
div()
.text_xl()
.font_weight(gpui::FontWeight::BOLD)
.text_color(colors.text)
.child("Async Tasks"),
)
.child(
div()
.text_sm()
.text_color(colors.disabled)
.child("Spawning, background work, and task management"),
),
)
.child(demo_section(
&colors,
"1. Foreground Task (cx.spawn)",
"Runs async work on the UI thread. Good for sequential async operations.",
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_sm()
.text_color(colors.text)
.child(foreground.message.clone()),
)
.child(
button(&colors, "foreground-btn", "Start Task", foreground.is_loading)
.on_click(cx.listener(|this, _, _, cx| {
this.foreground_demo.update(cx, |demo, cx| {
demo.start_task(cx);
});
})),
),
))
.child(demo_section(
&colors,
"2. Background Task (cx.background_spawn)",
"Runs heavy computation off the UI thread with progress updates.",
div()
.flex()
.flex_col()
.gap_2()
.child(progress_bar(&colors, background.progress))
.child(
div()
.text_sm()
.text_color(colors.text)
.child(format!(
div()
.id("main")
.size_full()
.p_6()
.bg(colors.background)
.overflow_scroll()
.child(
div()
.flex()
.flex_col()
.gap_6()
.max_w(px(500.))
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(
div()
.text_xl()
.font_weight(gpui::FontWeight::BOLD)
.text_color(colors.text)
.child("Async Tasks"),
)
.child(
div()
.text_sm()
.text_color(colors.disabled)
.child("Spawning, background work, and task management"),
),
)
.child(demo_section(
&colors,
"1. Foreground Task (cx.spawn)",
"Runs async work on the UI thread. Good for sequential async operations.",
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_sm()
.text_color(colors.text)
.child(foreground.message.clone()),
)
.child(
button(
&colors,
"foreground-btn",
"Start Task",
foreground.is_loading,
)
.on_click(cx.listener(|this, _, _, cx| {
this.foreground_demo.update(cx, |demo, cx| {
demo.start_task(cx);
});
})),
),
))
.child(demo_section(
&colors,
"2. Background Task (cx.background_spawn)",
"Runs heavy computation off the UI thread with progress updates.",
div()
.flex()
.flex_col()
.gap_2()
.child(progress_bar(&colors, background.progress))
.child(div().text_sm().text_color(colors.text).child(format!(
"Progress: {}% | Result: {}",
background.progress,
background
.result
.map(|r| r.to_string())
.unwrap_or_else(|| "-".into())
)),
)
.child(
button(&colors, "background-btn", "Compute", background.is_computing)
.on_click(cx.listener(|this, _, _, cx| {
this.background_demo.update(cx, |demo, cx| {
demo.start_computation(cx);
});
})),
),
))
.child(demo_section(
&colors,
"3. Cancellable Task",
"Store Task in a field to keep it running. Drop to cancel.",
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_2xl()
.font_weight(gpui::FontWeight::BOLD)
.text_color(colors.text)
.child(format!("{}", cancellable.counter)),
)
.child({
let is_running = cancellable.is_running();
let (bg, bg_hover) = if is_running {
(rgb(0xd32f2f), rgb(0xe04545))
} else {
(rgb(0x388e3c), rgb(0x43a047))
};
div()
.id("cancel-btn")
.px_3()
.py_1p5()
.rounded_md()
.text_sm()
.text_color(colors.text)
.cursor_pointer()
.bg(bg)
.hover(move |style| style.bg(bg_hover))
.child(if is_running { "Stop" } else { "Start Counter" })
.on_click(cx.listener(|this, _, _, cx| {
this.cancellable_demo.update(cx, |demo, cx| {
demo.toggle(cx);
});
}))
}),
))
.child(demo_section(
&colors,
"4. Task with Return Value",
"Tasks can return values that can be awaited or used in chained operations.",
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_sm()
.text_color(colors.disabled)
.child(format!("Numbers: {:?}", return_demo.numbers)),
)
.child(
div()
.text_sm()
.text_color(colors.text)
.child(format!(
"Sum: {}",
if return_demo.is_calculating {
"Calculating...".into()
} else {
return_demo
.sum
.map(|s| s.to_string())
.unwrap_or_else(|| "Not calculated".into())
}
)),
)
.child(
div()
.flex()
.gap_2()
.child(
button(
&colors,
"sum-btn",
"Calculate Sum",
return_demo.is_calculating,
)
.on_click(cx.listener(|this, _, _, cx| {
this.return_demo.update(cx, |demo, cx| {
demo.calculate_sum(cx);
});
})),
)
.child(
secondary_button(&colors, "random-btn", "Randomize")
.on_click(cx.listener(|this, _, _, cx| {
this.return_demo.update(cx, |demo, cx| {
demo.randomize(cx);
});
})),
),
),
))
)
}
)))
.child(
button(
&colors,
"background-btn",
"Compute",
background.is_computing,
)
.on_click(cx.listener(|this, _, _, cx| {
this.background_demo.update(cx, |demo, cx| {
demo.start_computation(cx);
});
})),
),
))
.child(demo_section(
&colors,
"3. Cancellable Task",
"Store Task in a field to keep it running. Drop to cancel.",
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_2xl()
.font_weight(gpui::FontWeight::BOLD)
.text_color(colors.text)
.child(format!("{}", cancellable.counter)),
)
.child({
let is_running = cancellable.is_running();
let (bg, bg_hover) = if is_running {
(rgb(0xd32f2f), rgb(0xe04545))
} else {
(rgb(0x388e3c), rgb(0x43a047))
};
div()
.id("cancel-btn")
.px_3()
.py_1p5()
.rounded_md()
.text_sm()
.text_color(colors.text)
.cursor_pointer()
.bg(bg)
.hover(move |style| style.bg(bg_hover))
.child(if is_running { "Stop" } else { "Start Counter" })
.on_click(cx.listener(|this, _, _, cx| {
this.cancellable_demo.update(cx, |demo, cx| {
demo.toggle(cx);
});
}))
}),
))
.child(demo_section(
&colors,
"4. Task with Return Value",
"Tasks can return values that can be awaited or used in chained operations.",
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_sm()
.text_color(colors.disabled)
.child(format!("Numbers: {:?}", return_demo.numbers)),
)
.child(div().text_sm().text_color(colors.text).child(format!(
"Sum: {}",
if return_demo.is_calculating {
"Calculating...".into()
} else {
return_demo
.sum
.map(|s| s.to_string())
.unwrap_or_else(|| "Not calculated".into())
}
)))
.child(
div()
.flex()
.gap_2()
.child(
button(
&colors,
"sum-btn",
"Calculate Sum",
return_demo.is_calculating,
)
.on_click(cx.listener(|this, _, _, cx| {
this.return_demo.update(cx, |demo, cx| {
demo.calculate_sum(cx);
});
})),
)
.child(
secondary_button(&colors, "random-btn", "Randomize")
.on_click(cx.listener(|this, _, _, cx| {
this.return_demo.update(cx, |demo, cx| {
demo.randomize(cx);
});
})),
),
),
)),
)
}
}
// Helper Components
fn demo_section(
colors: &Colors,
title: &'static str,
description: &'static str,
content: impl IntoElement,
colors: &Colors,
title: &'static str,
description: &'static str,
content: impl IntoElement,
) -> impl IntoElement {
div()
.flex()
.flex_col()
.gap_3()
.p_4()
.rounded_lg()
.bg(colors.container)
.border_1()
.border_color(colors.border)
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(
div()
.text_sm()
.font_weight(gpui::FontWeight::SEMIBOLD)
.text_color(colors.text)
.child(title),
)
.child(
div()
.text_xs()
.text_color(colors.disabled)
.child(description),
),
)
.child(content)
div()
.flex()
.flex_col()
.gap_3()
.p_4()
.rounded_lg()
.bg(colors.container)
.border_1()
.border_color(colors.border)
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(
div()
.text_sm()
.font_weight(gpui::FontWeight::SEMIBOLD)
.text_color(colors.text)
.child(title),
)
.child(
div()
.text_xs()
.text_color(colors.disabled)
.child(description),
),
)
.child(content)
}
fn button(
colors: &Colors,
id: impl Into<gpui::ElementId>,
label: &'static str,
disabled: bool,
colors: &Colors,
id: impl Into<gpui::ElementId>,
label: &'static str,
disabled: bool,
) -> gpui::Stateful<gpui::Div> {
let disabled_bg = colors.selected;
let bg = colors.selected;
let bg_hover = colors.selected;
let bg_active = colors.selected;
let text = colors.selected_text;
let disabled_bg = colors.selected;
let bg = colors.selected;
let bg_hover = colors.selected;
let bg_active = colors.selected;
let text = colors.selected_text;
div()
.id(id)
.px_3()
.py_1p5()
.rounded_md()
.text_sm()
.text_color(text)
.when(disabled, |el| {
el.bg(disabled_bg).cursor_not_allowed().opacity(0.6)
})
.when(!disabled, |el| {
el.bg(bg)
.cursor_pointer()
.hover(move |style| style.bg(bg_hover))
.active(move |style| style.bg(bg_active))
})
.child(label)
div()
.id(id)
.px_3()
.py_1p5()
.rounded_md()
.text_sm()
.text_color(text)
.when(disabled, |el| {
el.bg(disabled_bg).cursor_not_allowed().opacity(0.6)
})
.when(!disabled, |el| {
el.bg(bg)
.cursor_pointer()
.hover(move |style| style.bg(bg_hover))
.active(move |style| style.bg(bg_active))
})
.child(label)
}
fn secondary_button(
colors: &Colors,
id: impl Into<gpui::ElementId>,
label: &'static str,
colors: &Colors,
id: impl Into<gpui::ElementId>,
label: &'static str,
) -> gpui::Stateful<gpui::Div> {
let bg = colors.selected;
let bg_hover = colors.border;
let text = colors.text;
let bg = colors.selected;
let bg_hover = colors.border;
let text = colors.text;
div()
.id(id)
.px_3()
.py_1p5()
.rounded_md()
.text_sm()
.text_color(text)
.bg(bg)
.cursor_pointer()
.hover(move |style| style.bg(bg_hover))
.child(label)
div()
.id(id)
.px_3()
.py_1p5()
.rounded_md()
.text_sm()
.text_color(text)
.bg(bg)
.cursor_pointer()
.hover(move |style| style.bg(bg_hover))
.child(label)
}
fn progress_bar(colors: &Colors, progress: u32) -> impl IntoElement {
let clamped = progress.min(100);
let bar_bg = colors.selected;
let bar_fill = rgb(0x388e3c);
let clamped = progress.min(100);
let bar_bg = colors.selected;
let bar_fill = rgb(0x388e3c);
div()
.h_2()
.w_full()
.rounded_full()
.bg(bar_bg)
.overflow_hidden()
.child(
div()
.h_full()
.rounded_full()
.bg(bar_fill)
.w(gpui::relative(clamped as f32 / 100.0)),
)
div()
.h_2()
.w_full()
.rounded_full()
.bg(bar_bg)
.overflow_hidden()
.child(
div()
.h_full()
.rounded_full()
.bg(bar_fill)
.w(gpui::relative(clamped as f32 / 100.0)),
)
}
fn main() {
gpui_platform::application().run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(550.), px(850.)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|_, cx| cx.new(|cx| AsyncTasksExample::new(cx)),
)
.expect("Failed to open window");
gpui_platform::application().run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(550.), px(850.)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|_, cx| cx.new(|cx| AsyncTasksExample::new(cx)),
)
.expect("Failed to open window");
example_prelude::init_example(cx, "Async Tasks");
});
example_prelude::init_example(cx, "Async Tasks");
});
}
+227 -227
View File
@@ -19,130 +19,130 @@
//! continuous and the seams are clean — the CSS "blur the wrapper" idiom).
use gpui::{
App, Bounds, Context, Render, Window, WindowBounds, WindowOptions, deferred, div, point,
prelude::*, px, rgb, rgba, size,
App, Bounds, Context, Render, Window, WindowBounds, WindowOptions, deferred, div, point,
prelude::*, px, rgb, rgba, size,
};
struct BlurExample;
/// A vivid, gap-free background so blur is obvious: a grid of saturated tiles filling the window.
fn busy_background() -> impl IntoElement {
let palette = [
0xef4444, 0xf97316, 0xeab308, 0x22c55e, 0x06b6d4, 0x3b82f6, 0x8b5cf6, 0xec4899,
];
let mut next = 0usize;
div()
.absolute()
.inset_0()
.flex()
.flex_col()
.children((0..9).map(|_| {
div().flex().flex_1().children(
(0..8)
.map(|_| {
let hex = palette[next % palette.len()];
next += 1;
div()
.flex_1()
.h_full()
.bg(rgb(hex))
.flex()
.items_center()
.justify_center()
.text_color(rgb(0xffffff))
.text_xl()
.child("◆")
})
.collect::<Vec<_>>(),
)
}))
let palette = [
0xef4444, 0xf97316, 0xeab308, 0x22c55e, 0x06b6d4, 0x3b82f6, 0x8b5cf6, 0xec4899,
];
let mut next = 0usize;
div()
.absolute()
.inset_0()
.flex()
.flex_col()
.children((0..9).map(|_| {
div().flex().flex_1().children(
(0..8)
.map(|_| {
let hex = palette[next % palette.len()];
next += 1;
div()
.flex_1()
.h_full()
.bg(rgb(hex))
.flex()
.items_center()
.justify_center()
.text_color(rgb(0xffffff))
.text_xl()
.child("◆")
})
.collect::<Vec<_>>(),
)
}))
}
/// A translucent rounded panel that frosts the content behind it.
fn frosted_panel() -> impl IntoElement {
div()
.absolute()
.left(px(60.))
.top(px(120.))
.w(px(360.))
.h(px(200.))
.rounded_xl()
.bg(rgba(0xffffff30))
.backdrop_blur(px(24.))
.border_1()
.border_color(rgba(0xffffff60))
.flex()
.items_center()
.justify_center()
.text_color(rgb(0x111111))
.text_2xl()
.child("backdrop_blur(24px)")
div()
.absolute()
.left(px(60.))
.top(px(120.))
.w(px(360.))
.h(px(200.))
.rounded_xl()
.bg(rgba(0xffffff30))
.backdrop_blur(px(24.))
.border_1()
.border_color(rgba(0xffffff60))
.flex()
.items_center()
.justify_center()
.text_color(rgb(0x111111))
.text_2xl()
.child("backdrop_blur(24px)")
}
/// A popover painted via `deferred()` so it sits above everything; its backdrop blur must
/// still pick up the panel and background beneath it.
fn deferred_popover() -> impl IntoElement {
deferred(
div()
.absolute()
.left(px(260.))
.top(px(260.))
.w(px(300.))
.h(px(150.))
.rounded_lg()
.bg(rgba(0x1e293b66))
.backdrop_blur(px(12.))
.border_1()
.border_color(rgba(0xffffffaa))
.flex()
.items_center()
.justify_center()
.text_color(rgb(0xffffff))
.text_xl()
.child("deferred + backdrop_blur"),
)
deferred(
div()
.absolute()
.left(px(260.))
.top(px(260.))
.w(px(300.))
.h(px(150.))
.rounded_lg()
.bg(rgba(0x1e293b66))
.backdrop_blur(px(12.))
.border_1()
.border_color(rgba(0xffffffaa))
.flex()
.items_center()
.justify_center()
.text_color(rgb(0xffffff))
.text_xl()
.child("deferred + backdrop_blur"),
)
}
/// A self-blurred element (CSS `filter: blur`) — its own content is blurred as a group.
fn content_blurred() -> impl IntoElement {
div()
.absolute()
.left(px(120.))
.top(px(420.))
.w(px(280.))
.h(px(120.))
.blur(px(5.))
.bg(rgb(0x0f172a))
.rounded_lg()
.flex()
.items_center()
.justify_center()
.text_color(rgb(0xfacc15))
.text_3xl()
.child("blur(5px) content")
div()
.absolute()
.left(px(120.))
.top(px(420.))
.w(px(280.))
.h(px(120.))
.blur(px(5.))
.bg(rgb(0x0f172a))
.rounded_lg()
.flex()
.items_center()
.justify_center()
.text_color(rgb(0xfacc15))
.text_3xl()
.child("blur(5px) content")
}
/// A content-blurred element with richer content (a row of colored chips), so the `filter: blur`
/// effect — the element and its children blurred as one group — is clearly visible.
fn content_blurred_rich() -> impl IntoElement {
div()
.absolute()
.left(px(120.))
.top(px(580.))
.w(px(280.))
.h(px(120.))
.blur(px(6.))
.bg(rgb(0x1e293b))
.rounded_lg()
.flex()
.items_center()
.justify_center()
.gap_3()
.children(
[0xef4444, 0x22c55e, 0x3b82f6]
.into_iter()
.map(|hex| div().w(px(48.)).h(px(48.)).rounded_md().bg(rgb(hex))),
)
div()
.absolute()
.left(px(120.))
.top(px(580.))
.w(px(280.))
.h(px(120.))
.blur(px(6.))
.bg(rgb(0x1e293b))
.rounded_lg()
.flex()
.items_center()
.justify_center()
.gap_3()
.children(
[0xef4444, 0x22c55e, 0x3b82f6]
.into_iter()
.map(|hex| div().w(px(48.)).h(px(48.)).rounded_md().bg(rgb(hex))),
)
}
/// Nested content blur: a `blur()` element inside another `blur()` element. The inner block is
@@ -150,37 +150,37 @@ fn content_blurred_rich() -> impl IntoElement {
/// per-nesting-level isolated group textures (up to `MAX_FILTER_DEPTH`). The inner content should
/// read as markedly softer than the outer block's own text.
fn nested_content_blurred() -> impl IntoElement {
div()
.absolute()
.left(px(740.))
.top(px(80.))
.w(px(290.))
.h(px(220.))
.blur(px(3.))
.bg(rgb(0x1e293b))
.rounded_xl()
.flex()
.flex_col()
.items_center()
.justify_center()
.gap_4()
.text_color(rgb(0xe2e8f0))
.text_xl()
.child("outer blur(3px)")
.child(
div()
.w(px(190.))
.h(px(100.))
.blur(px(8.))
.bg(rgb(0xf59e0b))
.rounded_lg()
.flex()
.items_center()
.justify_center()
.text_color(rgb(0x111111))
.text_2xl()
.child("inner blur(8px)"),
)
div()
.absolute()
.left(px(740.))
.top(px(80.))
.w(px(290.))
.h(px(220.))
.blur(px(3.))
.bg(rgb(0x1e293b))
.rounded_xl()
.flex()
.flex_col()
.items_center()
.justify_center()
.gap_4()
.text_color(rgb(0xe2e8f0))
.text_xl()
.child("outer blur(3px)")
.child(
div()
.w(px(190.))
.h(px(100.))
.blur(px(8.))
.bg(rgb(0xf59e0b))
.rounded_lg()
.flex()
.items_center()
.justify_center()
.text_color(rgb(0x111111))
.text_2xl()
.child("inner blur(8px)"),
)
}
const SEAM_COLORS: [u32; 4] = [0xef4444, 0x22c55e, 0x3b82f6, 0xeab308];
@@ -191,16 +191,16 @@ const SEAM_COLORS: [u32; 4] = [0xef4444, 0x22c55e, 0x3b82f6, 0xeab308];
/// parent would not clip the blurred children to its radius and the busy background would leak
/// through the corner triangles — a separate concern from the seam blending under test here.
fn seam_block(i: usize, hex: u32, blur_each: bool) -> impl IntoElement {
let block = div().flex_1().h_full();
let block = if blur_each { block.blur(px(5.)) } else { block };
block
.bg(rgb(hex))
.flex()
.items_center()
.justify_center()
.text_color(rgb(0xffffff))
.text_2xl()
.child(format!("{}", i + 1))
let block = div().flex_1().h_full();
let block = if blur_each { block.blur(px(5.)) } else { block };
block
.bg(rgb(hex))
.flex()
.items_center()
.justify_center()
.text_color(rgb(0xffffff))
.text_2xl()
.child(format!("{}", i + 1))
}
/// Adjacent blocks, each its OWN content-filter group (`blur` on every block), no gap, dark parent.
@@ -208,20 +208,20 @@ fn seam_block(i: usize, hex: u32, blur_each: bool) -> impl IntoElement {
/// composites independently, so the dark parent shows through each seam by roughly `α_left · α_right`
/// (peaking at ~25% right on the seam). This matches the web — the clean alternative is the next panel.
fn adjacent_per_block_blur() -> impl IntoElement {
div()
.absolute()
.left(px(740.))
.top(px(350.))
.w(px(290.))
.h(px(110.))
.bg(rgb(0x050505))
.flex()
.children(
SEAM_COLORS
.into_iter()
.enumerate()
.map(|(i, hex)| seam_block(i, hex, true)),
)
div()
.absolute()
.left(px(740.))
.top(px(350.))
.w(px(290.))
.h(px(110.))
.bg(rgb(0x050505))
.flex()
.children(
SEAM_COLORS
.into_iter()
.enumerate()
.map(|(i, hex)| seam_block(i, hex, true)),
)
}
/// The same adjacent blocks, but `blur` is on the PARENT — one content-filter group covering all
@@ -229,87 +229,87 @@ fn adjacent_per_block_blur() -> impl IntoElement {
/// is continuous across the seams and only the group's outer edge fades. This is the CSS "blur the
/// wrapper, not each child" idiom, and the seams come out clean.
fn adjacent_group_blur() -> impl IntoElement {
div()
.absolute()
.left(px(740.))
.top(px(510.))
.w(px(290.))
.h(px(110.))
.bg(rgb(0x050505))
.blur(px(5.))
.flex()
.children(
SEAM_COLORS
.into_iter()
.enumerate()
.map(|(i, hex)| seam_block(i, hex, false)),
)
div()
.absolute()
.left(px(740.))
.top(px(510.))
.w(px(290.))
.h(px(110.))
.bg(rgb(0x050505))
.blur(px(5.))
.flex()
.children(
SEAM_COLORS
.into_iter()
.enumerate()
.map(|(i, hex)| seam_block(i, hex, false)),
)
}
/// A small dark pill label so the two new test sections are identifiable over the busy background.
fn caption(text: &'static str, left: f32, top: f32) -> impl IntoElement {
div()
.absolute()
.left(px(left))
.top(px(top))
.px_2()
.py_1()
.rounded_md()
.bg(rgba(0x000000cc))
.text_color(rgb(0xffffff))
.text_sm()
.child(text)
div()
.absolute()
.left(px(left))
.top(px(top))
.px_2()
.py_1()
.rounded_md()
.bg(rgba(0x000000cc))
.text_color(rgb(0xffffff))
.text_sm()
.child(text)
}
impl Render for BlurExample {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div()
.relative()
.size_full()
.bg(rgb(0x000000))
.child(busy_background())
.child(frosted_panel())
.child(content_blurred())
.child(content_blurred_rich())
.child(nested_content_blurred())
.child(adjacent_per_block_blur())
.child(adjacent_group_blur())
.child(caption("nested content blur", 740., 50.))
.child(caption(
"adjacent — blur each block (seams, = CSS)",
740.,
322.,
))
.child(caption(
"adjacent — blur the parent (one group, clean)",
740.,
482.,
))
.child(deferred_popover())
}
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div()
.relative()
.size_full()
.bg(rgb(0x000000))
.child(busy_background())
.child(frosted_panel())
.child(content_blurred())
.child(content_blurred_rich())
.child(nested_content_blurred())
.child(adjacent_per_block_blur())
.child(adjacent_group_blur())
.child(caption("nested content blur", 740., 50.))
.child(caption(
"adjacent — blur each block (seams, = CSS)",
740.,
322.,
))
.child(caption(
"adjacent — blur the parent (one group, clean)",
740.,
482.,
))
.child(deferred_popover())
}
}
fn main() {
gpui_platform::application().run(|cx: &mut App| {
cx.activate(true);
cx.on_window_closed(|cx, _| {
if cx.windows().is_empty() {
cx.quit();
}
})
.detach();
gpui_platform::application().run(|cx: &mut App| {
cx.activate(true);
cx.on_window_closed(|cx, _| {
if cx.windows().is_empty() {
cx.quit();
}
})
.detach();
let bounds = Bounds {
origin: point(px(100.), px(100.)),
size: size(px(1060.), px(760.)),
};
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|_, cx| cx.new(|_| BlurExample),
)
.expect("failed to open window");
});
let bounds = Bounds {
origin: point(px(100.), px(100.)),
size: size(px(1060.), px(760.)),
};
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|_, cx| cx.new(|_| BlurExample),
)
.expect("failed to open window");
});
}
+313 -313
View File
@@ -13,8 +13,8 @@ mod example_prelude;
use example_prelude::init_example;
use gpui::colors::Colors;
use gpui::{
App, Bounds, Context, Entity, IntoElement, Render, RenderOnce, Window, WindowBounds,
WindowOptions, div, prelude::*, px, rgb, size,
App, Bounds, Context, Entity, IntoElement, Render, RenderOnce, Window, WindowBounds,
WindowOptions, div, prelude::*, px, rgb, size,
};
// ============================================================================
@@ -35,84 +35,84 @@ use gpui::{
// - State is tied to call site location
struct UseStateCounter {
count: i32,
count: i32,
}
fn use_state_counter(colors: &Colors, window: &mut Window, cx: &mut App) -> impl IntoElement {
let state: Entity<UseStateCounter> =
window.use_state(cx, |_window, _cx| UseStateCounter { count: 0 });
let state: Entity<UseStateCounter> =
window.use_state(cx, |_window, _cx| UseStateCounter { count: 0 });
let count = state.read(cx).count;
let count = state.read(cx).count;
let error = rgb(0xd32f2f);
let error_hover = rgb(0xe04545);
let success = rgb(0x388e3c);
let success_hover = rgb(0x43a047);
let error = rgb(0xd32f2f);
let error_hover = rgb(0xe04545);
let success = rgb(0x388e3c);
let success_hover = rgb(0x43a047);
div()
.id("use-state-counter")
.flex()
.flex_col()
.gap_2()
.p_4()
.rounded_lg()
.bg(colors.container)
.child(
div()
.text_sm()
.text_color(colors.disabled)
.child("use_state Counter"),
)
.child(
div()
.text_2xl()
.text_color(colors.text)
.child(format!("{}", count)),
)
.child(
div()
.flex()
.gap_2()
.child(
div()
.id("use-state-decrement")
.px_3()
.py_1()
.rounded_md()
.bg(error)
.text_color(colors.selected_text)
.cursor_pointer()
.hover(move |style| style.bg(error_hover))
.child("−")
.on_click({
let state = state.clone();
move |_, _, cx| {
state.update(cx, |state, cx| {
state.count -= 1;
cx.notify();
});
}
}),
)
.child(
div()
.id("use-state-increment")
.px_3()
.py_1()
.rounded_md()
.bg(success)
.text_color(colors.selected_text)
.cursor_pointer()
.hover(move |style| style.bg(success_hover))
.child("+")
.on_click(move |_, _, cx| {
state.update(cx, |state, cx| {
state.count += 1;
cx.notify();
});
}),
),
)
div()
.id("use-state-counter")
.flex()
.flex_col()
.gap_2()
.p_4()
.rounded_lg()
.bg(colors.container)
.child(
div()
.text_sm()
.text_color(colors.disabled)
.child("use_state Counter"),
)
.child(
div()
.text_2xl()
.text_color(colors.text)
.child(format!("{}", count)),
)
.child(
div()
.flex()
.gap_2()
.child(
div()
.id("use-state-decrement")
.px_3()
.py_1()
.rounded_md()
.bg(error)
.text_color(colors.selected_text)
.cursor_pointer()
.hover(move |style| style.bg(error_hover))
.child("−")
.on_click({
let state = state.clone();
move |_, _, cx| {
state.update(cx, |state, cx| {
state.count -= 1;
cx.notify();
});
}
}),
)
.child(
div()
.id("use-state-increment")
.px_3()
.py_1()
.rounded_md()
.bg(success)
.text_color(colors.selected_text)
.cursor_pointer()
.hover(move |style| style.bg(success_hover))
.child("+")
.on_click(move |_, _, cx| {
state.update(cx, |state, cx| {
state.count += 1;
cx.notify();
});
}),
),
)
}
// ============================================================================
@@ -135,97 +135,97 @@ fn use_state_counter(colors: &Colors, window: &mut Window, cx: &mut App) -> impl
#[derive(IntoElement)]
struct RenderOnceCounter {
colors: Colors,
count: i32,
on_increment: Option<Box<dyn Fn(&mut Window, &mut App) + 'static>>,
on_decrement: Option<Box<dyn Fn(&mut Window, &mut App) + 'static>>,
colors: Colors,
count: i32,
on_increment: Option<Box<dyn Fn(&mut Window, &mut App) + 'static>>,
on_decrement: Option<Box<dyn Fn(&mut Window, &mut App) + 'static>>,
}
impl RenderOnceCounter {
fn new(colors: Colors, count: i32) -> Self {
Self {
colors,
count,
on_increment: None,
on_decrement: None,
}
}
fn new(colors: Colors, count: i32) -> Self {
Self {
colors,
count,
on_increment: None,
on_decrement: None,
}
}
fn on_increment(mut self, callback: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_increment = Some(Box::new(callback));
self
}
fn on_increment(mut self, callback: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_increment = Some(Box::new(callback));
self
}
fn on_decrement(mut self, callback: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_decrement = Some(Box::new(callback));
self
}
fn on_decrement(mut self, callback: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_decrement = Some(Box::new(callback));
self
}
}
impl RenderOnce for RenderOnceCounter {
fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
let colors = self.colors;
let error = rgb(0xd32f2f);
let error_hover = rgb(0xe04545);
let success = rgb(0x388e3c);
let success_hover = rgb(0x43a047);
fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
let colors = self.colors;
let error = rgb(0xd32f2f);
let error_hover = rgb(0xe04545);
let success = rgb(0x388e3c);
let success_hover = rgb(0x43a047);
div()
.id("render-once-counter")
.flex()
.flex_col()
.gap_2()
.p_4()
.rounded_lg()
.bg(colors.container)
.child(
div()
.text_sm()
.text_color(colors.disabled)
.child("RenderOnce Counter"),
)
.child(
div()
.text_2xl()
.text_color(colors.text)
.child(format!("{}", self.count)),
)
.child(
div()
.flex()
.gap_2()
.child(
div()
.id("render-once-decrement")
.px_3()
.py_1()
.rounded_md()
.bg(error)
.text_color(colors.selected_text)
.cursor_pointer()
.hover(move |style| style.bg(error_hover))
.child("−")
.when_some(self.on_decrement, |element, callback| {
element.on_click(move |_, window, cx| callback(window, cx))
}),
)
.child(
div()
.id("render-once-increment")
.px_3()
.py_1()
.rounded_md()
.bg(success)
.text_color(colors.selected_text)
.cursor_pointer()
.hover(move |style| style.bg(success_hover))
.child("+")
.when_some(self.on_increment, |element, callback| {
element.on_click(move |_, window, cx| callback(window, cx))
}),
),
)
}
div()
.id("render-once-counter")
.flex()
.flex_col()
.gap_2()
.p_4()
.rounded_lg()
.bg(colors.container)
.child(
div()
.text_sm()
.text_color(colors.disabled)
.child("RenderOnce Counter"),
)
.child(
div()
.text_2xl()
.text_color(colors.text)
.child(format!("{}", self.count)),
)
.child(
div()
.flex()
.gap_2()
.child(
div()
.id("render-once-decrement")
.px_3()
.py_1()
.rounded_md()
.bg(error)
.text_color(colors.selected_text)
.cursor_pointer()
.hover(move |style| style.bg(error_hover))
.child("−")
.when_some(self.on_decrement, |element, callback| {
element.on_click(move |_, window, cx| callback(window, cx))
}),
)
.child(
div()
.id("render-once-increment")
.px_3()
.py_1()
.rounded_md()
.bg(success)
.text_color(colors.selected_text)
.cursor_pointer()
.hover(move |style| style.bg(success_hover))
.child("+")
.when_some(self.on_increment, |element, callback| {
element.on_click(move |_, window, cx| callback(window, cx))
}),
),
)
}
}
// ============================================================================
@@ -248,89 +248,89 @@ impl RenderOnce for RenderOnceCounter {
// - More complex lifecycle
struct RenderCounter {
count: i32,
count: i32,
}
impl RenderCounter {
fn new() -> Self {
Self { count: 0 }
}
fn new() -> Self {
Self { count: 0 }
}
fn increment(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
self.count += 1;
cx.notify();
}
fn increment(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
self.count += 1;
cx.notify();
}
fn decrement(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
self.count -= 1;
cx.notify();
}
fn decrement(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
self.count -= 1;
cx.notify();
}
}
impl Render for RenderCounter {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
let error = rgb(0xd32f2f);
let error_hover = rgb(0xe04545);
let success = rgb(0x388e3c);
let success_hover = rgb(0x43a047);
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
let error = rgb(0xd32f2f);
let error_hover = rgb(0xe04545);
let success = rgb(0x388e3c);
let success_hover = rgb(0x43a047);
div()
.id("render-counter")
.flex()
.flex_col()
.gap_2()
.p_4()
.rounded_lg()
.bg(colors.container)
.child(
div()
.text_sm()
.text_color(colors.disabled)
.child("Render Counter"),
)
.child(
div()
.text_2xl()
.text_color(colors.text)
.child(format!("{}", self.count)),
)
.child(
div()
.flex()
.gap_2()
.child(
div()
.id("render-decrement")
.px_3()
.py_1()
.rounded_md()
.bg(error)
.text_color(colors.selected_text)
.cursor_pointer()
.hover(move |style| style.bg(error_hover))
.child("−")
.on_click(cx.listener(|this, _, window, cx| {
this.decrement(window, cx);
})),
)
.child(
div()
.id("render-increment")
.px_3()
.py_1()
.rounded_md()
.bg(success)
.text_color(colors.selected_text)
.cursor_pointer()
.hover(move |style| style.bg(success_hover))
.child("+")
.on_click(cx.listener(|this, _, window, cx| {
this.increment(window, cx);
})),
),
)
}
div()
.id("render-counter")
.flex()
.flex_col()
.gap_2()
.p_4()
.rounded_lg()
.bg(colors.container)
.child(
div()
.text_sm()
.text_color(colors.disabled)
.child("Render Counter"),
)
.child(
div()
.text_2xl()
.text_color(colors.text)
.child(format!("{}", self.count)),
)
.child(
div()
.flex()
.gap_2()
.child(
div()
.id("render-decrement")
.px_3()
.py_1()
.rounded_md()
.bg(error)
.text_color(colors.selected_text)
.cursor_pointer()
.hover(move |style| style.bg(error_hover))
.child("−")
.on_click(cx.listener(|this, _, window, cx| {
this.decrement(window, cx);
})),
)
.child(
div()
.id("render-increment")
.px_3()
.py_1()
.rounded_md()
.bg(success)
.text_color(colors.selected_text)
.cursor_pointer()
.hover(move |style| style.bg(success_hover))
.child("+")
.on_click(cx.listener(|this, _, window, cx| {
this.increment(window, cx);
})),
),
)
}
}
// ============================================================================
@@ -338,98 +338,98 @@ impl Render for RenderCounter {
// ============================================================================
struct CreatingComponentsExample {
render_counter: Entity<RenderCounter>,
render_once_count: i32,
render_counter: Entity<RenderCounter>,
render_once_count: i32,
}
impl CreatingComponentsExample {
fn new(cx: &mut Context<Self>) -> Self {
Self {
render_counter: cx.new(|_| RenderCounter::new()),
render_once_count: 0,
}
}
fn new(cx: &mut Context<Self>) -> Self {
Self {
render_counter: cx.new(|_| RenderCounter::new()),
render_once_count: 0,
}
}
}
impl Render for CreatingComponentsExample {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
let render_once_count = self.render_once_count;
let handle = cx.entity().downgrade();
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
let render_once_count = self.render_once_count;
let handle = cx.entity().downgrade();
div()
.id("main")
.size_full()
.flex()
.flex_col()
.gap_6()
.p_8()
.bg(colors.background)
.overflow_scroll()
.child(
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_2xl()
.font_weight(gpui::FontWeight::BOLD)
.text_color(colors.text)
.child("Creating Components"),
)
.child(
div()
.text_sm()
.text_color(colors.disabled)
.child("Three approaches to stateful components in GPUI"),
),
)
.child(
div()
.flex()
.flex_row()
.gap_4()
.child(use_state_counter(&colors, window, cx))
.child(
RenderOnceCounter::new(colors.clone(), render_once_count)
.on_increment({
let handle = handle.clone();
move |_window, cx| {
handle
.update(cx, |this, cx| {
this.render_once_count += 1;
cx.notify();
})
.ok();
}
})
.on_decrement(move |_window, cx| {
handle
.update(cx, |this, cx| {
this.render_once_count -= 1;
cx.notify();
})
.ok();
}),
)
.child(self.render_counter.clone()),
)
}
div()
.id("main")
.size_full()
.flex()
.flex_col()
.gap_6()
.p_8()
.bg(colors.background)
.overflow_scroll()
.child(
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_2xl()
.font_weight(gpui::FontWeight::BOLD)
.text_color(colors.text)
.child("Creating Components"),
)
.child(
div()
.text_sm()
.text_color(colors.disabled)
.child("Three approaches to stateful components in GPUI"),
),
)
.child(
div()
.flex()
.flex_row()
.gap_4()
.child(use_state_counter(&colors, window, cx))
.child(
RenderOnceCounter::new(colors.clone(), render_once_count)
.on_increment({
let handle = handle.clone();
move |_window, cx| {
handle
.update(cx, |this, cx| {
this.render_once_count += 1;
cx.notify();
})
.ok();
}
})
.on_decrement(move |_window, cx| {
handle
.update(cx, |this, cx| {
this.render_once_count -= 1;
cx.notify();
})
.ok();
}),
)
.child(self.render_counter.clone()),
)
}
}
fn main() {
gpui_platform::application().run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(700.), px(400.)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|_, cx| cx.new(|cx| CreatingComponentsExample::new(cx)),
)
.expect("Failed to open window");
gpui_platform::application().run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(700.), px(400.)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|_, cx| cx.new(|cx| CreatingComponentsExample::new(cx)),
)
.expect("Failed to open window");
init_example(cx, "Creating Components");
});
init_example(cx, "Creating Components");
});
}
+376 -376
View File
@@ -9,9 +9,9 @@
use gpui::colors::Colors;
use gpui::{
App, Bounds, Context, Hsla, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Path,
PathBuilder, Pixels, Point, Render, Rgba, Window, WindowBounds, WindowOptions, canvas, div,
fill, point, prelude::*, px, rgb, size,
App, Bounds, Context, Hsla, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Path,
PathBuilder, Pixels, Point, Render, Rgba, Window, WindowBounds, WindowOptions, canvas, div,
fill, point, prelude::*, px, rgb, size,
};
#[path = "../shared/prelude.rs"]
@@ -24,42 +24,42 @@ mod example_prelude;
// - paint: Called during paint to actually draw
fn basic_shapes_canvas(colors: &Colors) -> impl IntoElement {
let error = rgb(0xd32f2f);
let success = rgb(0x388e3c);
let accent = colors.selected;
let error = rgb(0xd32f2f);
let success = rgb(0x388e3c);
let accent = colors.selected;
canvas(
move |_bounds, _window, _cx| {},
move |bounds, _prepaint_state, window, _cx| {
// Draw a filled rectangle
window.paint_quad(fill(
Bounds {
origin: point(bounds.origin.x + px(10.), bounds.origin.y + px(10.)),
size: size(px(60.), px(40.)),
},
error,
));
canvas(
move |_bounds, _window, _cx| {},
move |bounds, _prepaint_state, window, _cx| {
// Draw a filled rectangle
window.paint_quad(fill(
Bounds {
origin: point(bounds.origin.x + px(10.), bounds.origin.y + px(10.)),
size: size(px(60.), px(40.)),
},
error,
));
// Draw another rectangle
window.paint_quad(fill(
Bounds {
origin: point(bounds.origin.x + px(80.), bounds.origin.y + px(10.)),
size: size(px(60.), px(40.)),
},
success,
));
// Draw another rectangle
window.paint_quad(fill(
Bounds {
origin: point(bounds.origin.x + px(80.), bounds.origin.y + px(10.)),
size: size(px(60.), px(40.)),
},
success,
));
// Draw a third rectangle
window.paint_quad(fill(
Bounds {
origin: point(bounds.origin.x + px(150.), bounds.origin.y + px(10.)),
size: size(px(60.), px(40.)),
},
accent,
));
},
)
.size_full()
// Draw a third rectangle
window.paint_quad(fill(
Bounds {
origin: point(bounds.origin.x + px(150.), bounds.origin.y + px(10.)),
size: size(px(60.), px(40.)),
},
accent,
));
},
)
.size_full()
}
// Example 2: Custom Paths with PathBuilder
@@ -71,80 +71,80 @@ fn basic_shapes_canvas(colors: &Colors) -> impl IntoElement {
// - close: Close the current subpath
fn create_star(center: Point<Pixels>, outer_radius: f32, inner_radius: f32) -> Path<Pixels> {
let mut builder = PathBuilder::fill();
let points = 5;
let mut builder = PathBuilder::fill();
let points = 5;
for i in 0..points * 2 {
let angle =
std::f32::consts::PI / 2.0 - (i as f32) * std::f32::consts::PI / (points as f32);
let radius = if i % 2 == 0 {
outer_radius
} else {
inner_radius
};
for i in 0..points * 2 {
let angle =
std::f32::consts::PI / 2.0 - (i as f32) * std::f32::consts::PI / (points as f32);
let radius = if i % 2 == 0 {
outer_radius
} else {
inner_radius
};
let x = center.x + px(angle.cos() * radius);
let y = center.y - px(angle.sin() * radius);
let x = center.x + px(angle.cos() * radius);
let y = center.y - px(angle.sin() * radius);
if i == 0 {
builder.move_to(point(x, y));
} else {
builder.line_to(point(x, y));
}
}
if i == 0 {
builder.move_to(point(x, y));
} else {
builder.line_to(point(x, y));
}
}
builder.close();
builder.build().unwrap()
builder.close();
builder.build().unwrap()
}
fn create_triangle(p1: Point<Pixels>, p2: Point<Pixels>, p3: Point<Pixels>) -> Path<Pixels> {
let mut builder = PathBuilder::fill();
builder.move_to(p1);
builder.line_to(p2);
builder.line_to(p3);
builder.close();
builder.build().unwrap()
let mut builder = PathBuilder::fill();
builder.move_to(p1);
builder.line_to(p2);
builder.line_to(p3);
builder.close();
builder.build().unwrap()
}
fn custom_paths_canvas(colors: &Colors) -> impl IntoElement {
let warning = rgb(0xf9a825);
let accent = colors.selected;
let warning = rgb(0xf9a825);
let accent = colors.selected;
canvas(
move |_bounds, _window, _cx| {},
move |bounds, _, window, _cx| {
let center_y = bounds.origin.y + bounds.size.height / 2.0;
canvas(
move |_bounds, _window, _cx| {},
move |bounds, _, window, _cx| {
let center_y = bounds.origin.y + bounds.size.height / 2.0;
// Draw a star
let star_center = point(bounds.origin.x + px(50.), center_y);
let star = create_star(star_center, 30., 15.);
window.paint_path(star, warning);
// Draw a star
let star_center = point(bounds.origin.x + px(50.), center_y);
let star = create_star(star_center, 30., 15.);
window.paint_path(star, warning);
// Draw a triangle
let tri_base_x = bounds.origin.x + px(120.);
let triangle = create_triangle(
point(tri_base_x + px(30.), center_y - px(25.)),
point(tri_base_x, center_y + px(25.)),
point(tri_base_x + px(60.), center_y + px(25.)),
);
window.paint_path(triangle, rgb(0x8b5cf6)); // Purple
// Draw a triangle
let tri_base_x = bounds.origin.x + px(120.);
let triangle = create_triangle(
point(tri_base_x + px(30.), center_y - px(25.)),
point(tri_base_x, center_y + px(25.)),
point(tri_base_x + px(60.), center_y + px(25.)),
);
window.paint_path(triangle, rgb(0x8b5cf6)); // Purple
// Draw a custom shape (arrow)
let arrow_x = bounds.origin.x + px(200.);
let mut arrow_builder = PathBuilder::fill();
arrow_builder.move_to(point(arrow_x, center_y));
arrow_builder.line_to(point(arrow_x + px(20.), center_y - px(20.)));
arrow_builder.line_to(point(arrow_x + px(20.), center_y - px(10.)));
arrow_builder.line_to(point(arrow_x + px(50.), center_y - px(10.)));
arrow_builder.line_to(point(arrow_x + px(50.), center_y + px(10.)));
arrow_builder.line_to(point(arrow_x + px(20.), center_y + px(10.)));
arrow_builder.line_to(point(arrow_x + px(20.), center_y + px(20.)));
arrow_builder.close();
let arrow = arrow_builder.build().unwrap();
window.paint_path(arrow, accent);
},
)
.size_full()
// Draw a custom shape (arrow)
let arrow_x = bounds.origin.x + px(200.);
let mut arrow_builder = PathBuilder::fill();
arrow_builder.move_to(point(arrow_x, center_y));
arrow_builder.line_to(point(arrow_x + px(20.), center_y - px(20.)));
arrow_builder.line_to(point(arrow_x + px(20.), center_y - px(10.)));
arrow_builder.line_to(point(arrow_x + px(50.), center_y - px(10.)));
arrow_builder.line_to(point(arrow_x + px(50.), center_y + px(10.)));
arrow_builder.line_to(point(arrow_x + px(20.), center_y + px(10.)));
arrow_builder.line_to(point(arrow_x + px(20.), center_y + px(20.)));
arrow_builder.close();
let arrow = arrow_builder.build().unwrap();
window.paint_path(arrow, accent);
},
)
.size_full()
}
// Example 3: Interactive Drawing
@@ -152,329 +152,329 @@ fn custom_paths_canvas(colors: &Colors) -> impl IntoElement {
// Combine canvas with mouse events for interactive drawing
struct DrawingCanvas {
lines: Vec<Vec<Point<Pixels>>>,
current_line: Vec<Point<Pixels>>,
is_drawing: bool,
color_index: usize,
lines: Vec<Vec<Point<Pixels>>>,
current_line: Vec<Point<Pixels>>,
is_drawing: bool,
color_index: usize,
}
impl DrawingCanvas {
fn new() -> Self {
Self {
lines: Vec::new(),
current_line: Vec::new(),
is_drawing: false,
color_index: 0,
}
}
fn new() -> Self {
Self {
lines: Vec::new(),
current_line: Vec::new(),
is_drawing: false,
color_index: 0,
}
}
fn get_colors(colors: &Colors) -> Vec<Rgba> {
vec![
rgb(0xd32f2f),
rgb(0x388e3c),
colors.selected,
rgb(0xf9a825),
rgb(0x8b5cf6), // Purple
rgb(0x06b6d4), // Cyan
]
}
fn get_colors(colors: &Colors) -> Vec<Rgba> {
vec![
rgb(0xd32f2f),
rgb(0x388e3c),
colors.selected,
rgb(0xf9a825),
rgb(0x8b5cf6), // Purple
rgb(0x06b6d4), // Cyan
]
}
fn current_color(&self, colors: &Colors) -> Rgba {
let palette = Self::get_colors(colors);
palette[self.color_index % palette.len()]
}
fn current_color(&self, colors: &Colors) -> Rgba {
let palette = Self::get_colors(colors);
palette[self.color_index % palette.len()]
}
fn next_color(&mut self, colors: &Colors) {
let palette = Self::get_colors(colors);
self.color_index = (self.color_index + 1) % palette.len();
}
fn next_color(&mut self, colors: &Colors) {
let palette = Self::get_colors(colors);
self.color_index = (self.color_index + 1) % palette.len();
}
fn on_mouse_down(
&mut self,
event: &MouseDownEvent,
_window: &mut Window,
cx: &mut Context<Self>,
) {
if event.button == MouseButton::Left {
self.is_drawing = true;
self.current_line = vec![event.position];
cx.notify();
}
}
fn on_mouse_down(
&mut self,
event: &MouseDownEvent,
_window: &mut Window,
cx: &mut Context<Self>,
) {
if event.button == MouseButton::Left {
self.is_drawing = true;
self.current_line = vec![event.position];
cx.notify();
}
}
fn on_mouse_move(
&mut self,
event: &MouseMoveEvent,
_window: &mut Window,
cx: &mut Context<Self>,
) {
if self.is_drawing {
self.current_line.push(event.position);
cx.notify();
}
}
fn on_mouse_move(
&mut self,
event: &MouseMoveEvent,
_window: &mut Window,
cx: &mut Context<Self>,
) {
if self.is_drawing {
self.current_line.push(event.position);
cx.notify();
}
}
fn on_mouse_up(&mut self, _event: &MouseUpEvent, window: &mut Window, cx: &mut Context<Self>) {
if self.is_drawing && self.current_line.len() > 1 {
self.lines.push(std::mem::take(&mut self.current_line));
let colors = Colors::for_appearance(window);
self.next_color(&colors);
}
self.is_drawing = false;
self.current_line.clear();
cx.notify();
}
fn on_mouse_up(&mut self, _event: &MouseUpEvent, window: &mut Window, cx: &mut Context<Self>) {
if self.is_drawing && self.current_line.len() > 1 {
self.lines.push(std::mem::take(&mut self.current_line));
let colors = Colors::for_appearance(window);
self.next_color(&colors);
}
self.is_drawing = false;
self.current_line.clear();
cx.notify();
}
fn clear(&mut self, cx: &mut Context<Self>) {
self.lines.clear();
self.current_line.clear();
self.color_index = 0;
cx.notify();
}
fn clear(&mut self, cx: &mut Context<Self>) {
self.lines.clear();
self.current_line.clear();
self.color_index = 0;
cx.notify();
}
fn draw_line(window: &mut Window, points: &[Point<Pixels>], color: Rgba) {
if points.len() < 2 {
return;
}
fn draw_line(window: &mut Window, points: &[Point<Pixels>], color: Rgba) {
if points.len() < 2 {
return;
}
for pair in points.windows(2) {
let start = pair[0];
let end = pair[1];
for pair in points.windows(2) {
let start = pair[0];
let end = pair[1];
let dx = end.x - start.x;
let dy = end.y - start.y;
let dx = end.x - start.x;
let dy = end.y - start.y;
let dx_f = f32::from(dx);
let dy_f = f32::from(dy);
let len = (dx_f * dx_f + dy_f * dy_f).sqrt();
let dx_f = f32::from(dx);
let dy_f = f32::from(dy);
let len = (dx_f * dx_f + dy_f * dy_f).sqrt();
if len < 0.1 {
continue;
}
if len < 0.1 {
continue;
}
let thickness = 3.0_f32;
let px_offset = px(-dy_f / len * thickness / 2.0);
let py_offset = px(dx_f / len * thickness / 2.0);
let thickness = 3.0_f32;
let px_offset = px(-dy_f / len * thickness / 2.0);
let py_offset = px(dx_f / len * thickness / 2.0);
let mut builder = PathBuilder::fill();
builder.move_to(point(start.x + px_offset, start.y + py_offset));
builder.line_to(point(end.x + px_offset, end.y + py_offset));
builder.line_to(point(end.x - px_offset, end.y - py_offset));
builder.line_to(point(start.x - px_offset, start.y - py_offset));
builder.close();
let mut builder = PathBuilder::fill();
builder.move_to(point(start.x + px_offset, start.y + py_offset));
builder.line_to(point(end.x + px_offset, end.y + py_offset));
builder.line_to(point(end.x - px_offset, end.y - py_offset));
builder.line_to(point(start.x - px_offset, start.y - py_offset));
builder.close();
if let Ok(path) = builder.build() {
window.paint_path(path, color);
}
}
}
if let Ok(path) = builder.build() {
window.paint_path(path, color);
}
}
}
}
impl Render for DrawingCanvas {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
let lines = self.lines.clone();
let current_line = self.current_line.clone();
let current_color = self.current_color(&colors);
let palette = Self::get_colors(&colors);
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
let lines = self.lines.clone();
let current_line = self.current_line.clone();
let current_color = self.current_color(&colors);
let palette = Self::get_colors(&colors);
let surface = colors.container;
let border = colors.border;
let error = rgb(0xd32f2f);
let error_hover = rgb(0xe04545);
let text = colors.selected_text;
let text_muted = colors.disabled;
let surface = colors.container;
let border = colors.border;
let error = rgb(0xd32f2f);
let error_hover = rgb(0xe04545);
let text = colors.selected_text;
let text_muted = colors.disabled;
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.id("drawing-area")
.h_48()
.rounded_lg()
.bg(surface)
.border_1()
.border_color(border)
.cursor_crosshair()
.overflow_hidden()
.on_mouse_down(MouseButton::Left, cx.listener(Self::on_mouse_down))
.on_mouse_move(cx.listener(Self::on_mouse_move))
.on_mouse_up(MouseButton::Left, cx.listener(Self::on_mouse_up))
.child(
canvas(
move |_, _, _| {},
move |_bounds, _, window, _cx| {
for (i, line) in lines.iter().enumerate() {
let color = palette[i % palette.len()];
DrawingCanvas::draw_line(window, line, color);
}
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.id("drawing-area")
.h_48()
.rounded_lg()
.bg(surface)
.border_1()
.border_color(border)
.cursor_crosshair()
.overflow_hidden()
.on_mouse_down(MouseButton::Left, cx.listener(Self::on_mouse_down))
.on_mouse_move(cx.listener(Self::on_mouse_move))
.on_mouse_up(MouseButton::Left, cx.listener(Self::on_mouse_up))
.child(
canvas(
move |_, _, _| {},
move |_bounds, _, window, _cx| {
for (i, line) in lines.iter().enumerate() {
let color = palette[i % palette.len()];
DrawingCanvas::draw_line(window, line, color);
}
if !current_line.is_empty() {
DrawingCanvas::draw_line(window, &current_line, current_color);
}
},
)
.size_full(),
),
)
.child(
div()
.flex()
.gap_2()
.child(
div()
.id("clear-btn")
.px_3()
.py_1()
.rounded_md()
.bg(error)
.text_sm()
.text_color(text)
.cursor_pointer()
.hover(move |s| s.bg(error_hover))
.child("Clear")
.on_click(cx.listener(|this, _, _, cx| {
this.clear(cx);
})),
)
.child(
div()
.text_xs()
.text_color(text_muted)
.child("Click and drag to draw"),
),
)
}
if !current_line.is_empty() {
DrawingCanvas::draw_line(window, &current_line, current_color);
}
},
)
.size_full(),
),
)
.child(
div()
.flex()
.gap_2()
.child(
div()
.id("clear-btn")
.px_3()
.py_1()
.rounded_md()
.bg(error)
.text_sm()
.text_color(text)
.cursor_pointer()
.hover(move |s| s.bg(error_hover))
.child("Clear")
.on_click(cx.listener(|this, _, _, cx| {
this.clear(cx);
})),
)
.child(
div()
.text_xs()
.text_color(text_muted)
.child("Click and drag to draw"),
),
)
}
}
// Main Application View
struct CustomDrawingExample {
drawing_canvas: gpui::Entity<DrawingCanvas>,
drawing_canvas: gpui::Entity<DrawingCanvas>,
}
impl CustomDrawingExample {
fn new(cx: &mut Context<Self>) -> Self {
Self {
drawing_canvas: cx.new(|_| DrawingCanvas::new()),
}
}
fn new(cx: &mut Context<Self>) -> Self {
Self {
drawing_canvas: cx.new(|_| DrawingCanvas::new()),
}
}
}
impl Render for CustomDrawingExample {
fn render(&mut self, window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
fn render(&mut self, window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
div()
.id("main")
.size_full()
.p_6()
.bg(colors.background)
.overflow_scroll()
.child(
div()
.flex()
.flex_col()
.gap_6()
.max_w(px(500.))
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(
div()
.text_xl()
.font_weight(gpui::FontWeight::BOLD)
.text_color(colors.text)
.child("Custom Drawing"),
)
.child(
div()
.text_sm()
.text_color(colors.disabled)
.child("Canvas element, paths, and interactive painting"),
),
)
.child(section(
&colors,
"1. Basic Shapes (paint_quad)",
"Use window.paint_quad() to draw filled rectangles",
basic_shapes_canvas(&colors),
px(70.),
))
.child(section(
&colors,
"2. Custom Paths (PathBuilder)",
"Create complex shapes with PathBuilder and paint_path()",
custom_paths_canvas(&colors),
px(80.),
))
.child(section(
&colors,
"3. Interactive Drawing",
"Combine canvas with mouse events for drawing",
self.drawing_canvas.clone(),
px(240.),
)),
)
}
div()
.id("main")
.size_full()
.p_6()
.bg(colors.background)
.overflow_scroll()
.child(
div()
.flex()
.flex_col()
.gap_6()
.max_w(px(500.))
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(
div()
.text_xl()
.font_weight(gpui::FontWeight::BOLD)
.text_color(colors.text)
.child("Custom Drawing"),
)
.child(
div()
.text_sm()
.text_color(colors.disabled)
.child("Canvas element, paths, and interactive painting"),
),
)
.child(section(
&colors,
"1. Basic Shapes (paint_quad)",
"Use window.paint_quad() to draw filled rectangles",
basic_shapes_canvas(&colors),
px(70.),
))
.child(section(
&colors,
"2. Custom Paths (PathBuilder)",
"Create complex shapes with PathBuilder and paint_path()",
custom_paths_canvas(&colors),
px(80.),
))
.child(section(
&colors,
"3. Interactive Drawing",
"Combine canvas with mouse events for drawing",
self.drawing_canvas.clone(),
px(240.),
)),
)
}
}
fn section(
colors: &Colors,
title: &'static str,
description: &'static str,
content: impl IntoElement,
height: Pixels,
colors: &Colors,
title: &'static str,
description: &'static str,
content: impl IntoElement,
height: Pixels,
) -> impl IntoElement {
let surface: Hsla = colors.container.into();
let surface: Hsla = colors.container.into();
div()
.flex()
.flex_col()
.gap_3()
.p_4()
.rounded_lg()
.bg(surface.opacity(0.5))
.border_1()
.border_color(colors.border)
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(
div()
.text_sm()
.font_weight(gpui::FontWeight::SEMIBOLD)
.text_color(colors.text)
.child(title),
)
.child(
div()
.text_xs()
.text_color(colors.disabled)
.child(description),
),
)
.child(div().h(height).child(content))
div()
.flex()
.flex_col()
.gap_3()
.p_4()
.rounded_lg()
.bg(surface.opacity(0.5))
.border_1()
.border_color(colors.border)
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(
div()
.text_sm()
.font_weight(gpui::FontWeight::SEMIBOLD)
.text_color(colors.text)
.child(title),
)
.child(
div()
.text_xs()
.text_color(colors.disabled)
.child(description),
),
)
.child(div().h(height).child(content))
}
fn main() {
gpui_platform::application().run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(550.), px(800.)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|_, cx| cx.new(|cx| CustomDrawingExample::new(cx)),
)
.expect("Failed to open window");
gpui_platform::application().run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(550.), px(800.)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|_, cx| cx.new(|cx| CustomDrawingExample::new(cx)),
)
.expect("Failed to open window");
example_prelude::init_example(cx, "Custom Drawing");
});
example_prelude::init_example(cx, "Custom Drawing");
});
}
+91 -88
View File
@@ -17,12 +17,12 @@ mod example_prelude;
use example_prelude::init_example;
use gpui::dock::{
DockArea, DockEvent, DockLayoutState, DockPanel, PanelEvent, PanelHandle, PanelId,
PanelRegistry,
DockArea, DockEvent, DockLayoutState, DockPanel, PanelEvent, PanelHandle, PanelId,
PanelRegistry,
};
use gpui::{
AnyElement, App, Bounds, Context, Entity, EventEmitter, Render, SharedString, Window,
WindowBounds, WindowOptions, div, prelude::*, px, size,
AnyElement, App, Bounds, Context, Entity, EventEmitter, Render, SharedString, Window,
WindowBounds, WindowOptions, div, prelude::*, px, size,
};
use std::sync::Arc;
@@ -40,41 +40,41 @@ const TIMELINE_ID: PanelId = PanelId::new(4);
/// Shared shape of the demo placeholders: a labeled box.
struct PlaceholderPanel {
id: PanelId,
title: &'static str,
id: PanelId,
title: &'static str,
}
impl PlaceholderPanel {
fn new(id: PanelId, title: &'static str) -> Self {
Self { id, title }
}
fn new(id: PanelId, title: &'static str) -> Self {
Self { id, title }
}
}
impl Render for PlaceholderPanel {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div()
.size_full()
.flex()
.items_center()
.justify_center()
.child(format!("{} (placeholder)", self.title))
}
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div()
.size_full()
.flex()
.items_center()
.justify_center()
.child(format!("{} (placeholder)", self.title))
}
}
impl EventEmitter<PanelEvent> for PlaceholderPanel {}
impl DockPanel for PlaceholderPanel {
fn panel_id(&self) -> PanelId {
self.id
}
fn panel_id(&self) -> PanelId {
self.id
}
fn title(&self, _cx: &App) -> SharedString {
self.title.into()
}
fn title(&self, _cx: &App) -> SharedString {
self.title.into()
}
fn tab_content(&self, _cx: &App) -> AnyElement {
div().child(self.title).into_any_element()
}
fn tab_content(&self, _cx: &App) -> AnyElement {
div().child(self.title).into_any_element()
}
}
// ============================================================================
@@ -84,29 +84,29 @@ impl DockPanel for PlaceholderPanel {
struct DemoPanelRegistry;
impl PanelRegistry for DemoPanelRegistry {
fn panel_key(&self, id: PanelId) -> Option<String> {
match id {
PROJECT_BIN_ID => Some("project-bin".into()),
VIEWER_ID => Some("viewer".into()),
INSPECTOR_ID => Some("inspector".into()),
TIMELINE_ID => Some("timeline".into()),
_ => None,
}
}
fn panel_key(&self, id: PanelId) -> Option<String> {
match id {
PROJECT_BIN_ID => Some("project-bin".into()),
VIEWER_ID => Some("viewer".into()),
INSPECTOR_ID => Some("inspector".into()),
TIMELINE_ID => Some("timeline".into()),
_ => None,
}
}
fn build_panel(&self, key: &str, _window: &mut Window, cx: &mut App) -> Option<PanelHandle> {
let (id, title) = match key {
"project-bin" => (PROJECT_BIN_ID, "Project Bin"),
"viewer" => (VIEWER_ID, "Viewer"),
"inspector" => (INSPECTOR_ID, "Inspector"),
"timeline" => (TIMELINE_ID, "Timeline"),
_ => return None,
};
Some(PanelHandle::new(
cx.new(|_| PlaceholderPanel::new(id, title)),
cx,
))
}
fn build_panel(&self, key: &str, _window: &mut Window, cx: &mut App) -> Option<PanelHandle> {
let (id, title) = match key {
"project-bin" => (PROJECT_BIN_ID, "Project Bin"),
"viewer" => (VIEWER_ID, "Viewer"),
"inspector" => (INSPECTOR_ID, "Inspector"),
"timeline" => (TIMELINE_ID, "Timeline"),
_ => return None,
};
Some(PanelHandle::new(
cx.new(|_| PlaceholderPanel::new(id, title)),
cx,
))
}
}
// ============================================================================
@@ -114,57 +114,60 @@ impl PanelRegistry for DemoPanelRegistry {
// ============================================================================
struct DockLayoutExample {
dock: Entity<DockArea>,
dock: Entity<DockArea>,
}
impl DockLayoutExample {
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
let dock = cx.new(|cx| DockArea::new(cx).with_registry(Arc::new(DemoPanelRegistry)));
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
let dock = cx.new(|cx| DockArea::new(cx).with_registry(Arc::new(DemoPanelRegistry)));
// Seed a default workspace. Once the dock is implemented this will
// instead attempt `restore_state` from a persisted `DockLayoutState`
// first, falling back to this default when none exists.
let panels: Vec<PanelHandle> = ["project-bin", "viewer", "inspector", "timeline"]
.into_iter()
.filter_map(|key| DemoPanelRegistry.build_panel(key, window, cx))
.collect();
dock.update(cx, |dock, cx| {
for panel in panels {
dock.add_panel(panel, None, cx);
}
});
// Seed a default workspace. Once the dock is implemented this will
// instead attempt `restore_state` from a persisted `DockLayoutState`
// first, falling back to this default when none exists.
let panels: Vec<PanelHandle> = ["project-bin", "viewer", "inspector", "timeline"]
.into_iter()
.filter_map(|key| DemoPanelRegistry.build_panel(key, window, cx))
.collect();
dock.update(cx, |dock, cx| {
for panel in panels {
dock.add_panel(panel, None, cx);
}
});
// Autosave hook: persist on every layout change.
cx.subscribe(&dock, |_this, dock: Entity<DockArea>, event: &DockEvent, cx| {
if let DockEvent::LayoutChanged = event {
let _state: DockLayoutState = dock.read(cx).save_state();
todo!("serialize `_state` with serde_json and write it to the app data dir");
}
})
.detach();
// Autosave hook: persist on every layout change.
cx.subscribe(
&dock,
|_this, dock: Entity<DockArea>, event: &DockEvent, cx| {
if let DockEvent::LayoutChanged = event {
let _state: DockLayoutState = dock.read(cx).save_state();
todo!("serialize `_state` with serde_json and write it to the app data dir");
}
},
)
.detach();
Self { dock }
}
Self { dock }
}
}
impl Render for DockLayoutExample {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().size_full().child(self.dock.clone())
}
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().size_full().child(self.dock.clone())
}
}
fn main() {
gpui_platform::application().run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(1200.), px(800.)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|window, cx| cx.new(|cx| DockLayoutExample::new(window, cx)),
)
.expect("Failed to open window");
gpui_platform::application().run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(1200.), px(800.)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|window, cx| cx.new(|cx| DockLayoutExample::new(window, cx)),
)
.expect("Failed to open window");
init_example(cx, "Dock Layout");
});
init_example(cx, "Dock Layout");
});
}
+169 -169
View File
@@ -18,11 +18,11 @@ use std::sync::Arc;
use example_prelude::init_example;
use gpui::effect_stack::{
EffectCardKind, EffectData, EffectId, EffectStackDataSource, EffectStackEvent, EffectStackView,
EffectCardKind, EffectData, EffectId, EffectStackDataSource, EffectStackEvent, EffectStackView,
};
use gpui::{
App, Bounds, Context, Entity, Render, SharedString, Window, WindowBounds, WindowOptions, div,
prelude::*, px, size,
App, Bounds, Context, Entity, Render, SharedString, Window, WindowBounds, WindowOptions, div,
prelude::*, px, size,
};
// ---------------------------------------------------------------------------
@@ -30,117 +30,117 @@ use gpui::{
// ---------------------------------------------------------------------------
struct MockEffect {
id: EffectId,
kind: EffectCardKind,
title: String,
subtitle: Option<String>,
enabled: bool,
expanded: bool,
badge: Option<usize>,
id: EffectId,
kind: EffectCardKind,
title: String,
subtitle: Option<String>,
enabled: bool,
expanded: bool,
badge: Option<usize>,
}
impl EffectData for MockEffect {
fn id(&self) -> EffectId {
self.id
}
fn kind(&self) -> EffectCardKind {
self.kind
}
fn title(&self) -> SharedString {
self.title.clone().into()
}
fn subtitle(&self) -> Option<SharedString> {
self.subtitle.clone().map(Into::into)
}
fn is_enabled(&self) -> bool {
self.enabled
}
fn is_expanded(&self) -> bool {
self.expanded
}
fn badge_count(&self) -> Option<usize> {
self.badge
}
fn id(&self) -> EffectId {
self.id
}
fn kind(&self) -> EffectCardKind {
self.kind
}
fn title(&self) -> SharedString {
self.title.clone().into()
}
fn subtitle(&self) -> Option<SharedString> {
self.subtitle.clone().map(Into::into)
}
fn is_enabled(&self) -> bool {
self.enabled
}
fn is_expanded(&self) -> bool {
self.expanded
}
fn badge_count(&self) -> Option<usize> {
self.badge
}
}
/// The mock data source. In Oak this would be a view-model entity deriving
/// the ordered card list from the node-graph path of the selected clip.
struct MockStack {
clip_name: String,
effects: Vec<MockEffect>,
/// Reserved for allocating ids to effects added at runtime.
#[allow(dead_code)]
next_id: u64,
clip_name: String,
effects: Vec<MockEffect>,
/// Reserved for allocating ids to effects added at runtime.
#[allow(dead_code)]
next_id: u64,
}
impl MockStack {
fn demo() -> Self {
Self {
clip_name: "A001_C002_0103.mov".to_string(),
effects: vec![
MockEffect {
id: EffectId(0),
kind: EffectCardKind::Source,
title: "Media".into(),
subtitle: Some("A001_C002_0103.mov".into()),
enabled: true,
expanded: false,
badge: None,
},
MockEffect {
id: EffectId(1),
kind: EffectCardKind::Effect,
title: "Transform".into(),
subtitle: Some("scale 100%, rotate 0°".into()),
enabled: true,
expanded: true,
badge: Some(2),
},
MockEffect {
id: EffectId(2),
kind: EffectCardKind::Effect,
title: "OCIO LUT".into(),
subtitle: Some("filmic_to_display.cube".into()),
enabled: true,
expanded: false,
badge: None,
},
MockEffect {
id: EffectId(3),
kind: EffectCardKind::Output,
title: "Output".into(),
subtitle: None,
enabled: true,
expanded: false,
badge: None,
},
],
next_id: 4,
}
}
fn demo() -> Self {
Self {
clip_name: "A001_C002_0103.mov".to_string(),
effects: vec![
MockEffect {
id: EffectId(0),
kind: EffectCardKind::Source,
title: "Media".into(),
subtitle: Some("A001_C002_0103.mov".into()),
enabled: true,
expanded: false,
badge: None,
},
MockEffect {
id: EffectId(1),
kind: EffectCardKind::Effect,
title: "Transform".into(),
subtitle: Some("scale 100%, rotate 0°".into()),
enabled: true,
expanded: true,
badge: Some(2),
},
MockEffect {
id: EffectId(2),
kind: EffectCardKind::Effect,
title: "OCIO LUT".into(),
subtitle: Some("filmic_to_display.cube".into()),
enabled: true,
expanded: false,
badge: None,
},
MockEffect {
id: EffectId(3),
kind: EffectCardKind::Output,
title: "Output".into(),
subtitle: None,
enabled: true,
expanded: false,
badge: None,
},
],
next_id: 4,
}
}
}
impl EffectStackDataSource for MockStack {
fn effects(&self) -> Vec<Arc<dyn EffectData>> {
self.effects
.iter()
.map(|effect| {
Arc::new(MockEffect {
id: effect.id,
kind: effect.kind,
title: effect.title.clone(),
subtitle: effect.subtitle.clone(),
enabled: effect.enabled,
expanded: effect.expanded,
badge: effect.badge,
}) as Arc<dyn EffectData>
})
.collect()
}
fn effects(&self) -> Vec<Arc<dyn EffectData>> {
self.effects
.iter()
.map(|effect| {
Arc::new(MockEffect {
id: effect.id,
kind: effect.kind,
title: effect.title.clone(),
subtitle: effect.subtitle.clone(),
enabled: effect.enabled,
expanded: effect.expanded,
badge: effect.badge,
}) as Arc<dyn EffectData>
})
.collect()
}
fn target_label(&self) -> Option<SharedString> {
Some(self.clip_name.clone().into())
}
fn target_label(&self) -> Option<SharedString> {
Some(self.clip_name.clone().into())
}
}
// ---------------------------------------------------------------------------
@@ -150,93 +150,93 @@ impl EffectStackDataSource for MockStack {
/// Placeholder parameter view. A real app builds the effect's controls here
/// and calls [`EffectStackView::notify_parameter_changed`] after edits.
struct MockParams {
effect: EffectId,
effect: EffectId,
}
impl Render for MockParams {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().child(format!("parameters for {} (mock)", self.effect))
}
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().child(format!("parameters for {} (mock)", self.effect))
}
}
struct StackDemoRoot {
data: Entity<MockStack>,
stack: Entity<EffectStackView<MockStack>>,
data: Entity<MockStack>,
stack: Entity<EffectStackView<MockStack>>,
}
impl StackDemoRoot {
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
let data = cx.new(|_cx| MockStack::demo());
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
let data = cx.new(|_cx| MockStack::demo());
let stack = cx.new(|cx| {
EffectStackView::new(data.clone(), cx).params_renderer(|id, _window, cx| {
// Real apps build the effect's parameter controls here. The
// mock just shows a placeholder label.
cx.new(|_cx| MockParams { effect: *id }).into()
})
});
let stack = cx.new(|cx| {
EffectStackView::new(data.clone(), cx).params_renderer(|id, _window, cx| {
// Real apps build the effect's parameter controls here. The
// mock just shows a placeholder label.
cx.new(|_cx| MockParams { effect: *id }).into()
})
});
// The "edits are requests" loop: log each request, apply it to the
// model (Oak: engine command + undo), then notify.
cx.subscribe_in(&stack, window, {
let data = data.clone();
move |_root, _stack, event: &EffectStackEvent, _window, cx| {
println!("[effect_stack] request: {event:?}");
data.update(cx, |data, cx| {
match event {
EffectStackEvent::EnableToggled { effect, enabled } => {
if let Some(e) = data.effects.iter_mut().find(|e| e.id == *effect) {
e.enabled = *enabled;
}
}
EffectStackEvent::ExpansionToggled { effect, expanded } => {
if let Some(e) = data.effects.iter_mut().find(|e| e.id == *effect) {
e.expanded = *expanded;
}
}
EffectStackEvent::ReorderRequested { .. }
| EffectStackEvent::RemoveRequested(_)
| EffectStackEvent::AddRequested { .. }
| EffectStackEvent::ContextMenuRequested { .. }
| EffectStackEvent::ParameterChanged { .. } => {
todo!("apply {event:?} to the mock model (or engine, in a real app)")
}
}
cx.notify();
});
}
})
.detach();
// The "edits are requests" loop: log each request, apply it to the
// model (Oak: engine command + undo), then notify.
cx.subscribe_in(&stack, window, {
let data = data.clone();
move |_root, _stack, event: &EffectStackEvent, _window, cx| {
println!("[effect_stack] request: {event:?}");
data.update(cx, |data, cx| {
match event {
EffectStackEvent::EnableToggled { effect, enabled } => {
if let Some(e) = data.effects.iter_mut().find(|e| e.id == *effect) {
e.enabled = *enabled;
}
}
EffectStackEvent::ExpansionToggled { effect, expanded } => {
if let Some(e) = data.effects.iter_mut().find(|e| e.id == *effect) {
e.expanded = *expanded;
}
}
EffectStackEvent::ReorderRequested { .. }
| EffectStackEvent::RemoveRequested(_)
| EffectStackEvent::AddRequested { .. }
| EffectStackEvent::ContextMenuRequested { .. }
| EffectStackEvent::ParameterChanged { .. } => {
todo!("apply {event:?} to the mock model (or engine, in a real app)")
}
}
cx.notify();
});
}
})
.detach();
Self { data, stack }
}
Self { data, stack }
}
}
impl Render for StackDemoRoot {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let _ = &self.data;
let _ = cx;
div()
.size_full()
.flex()
.items_center()
.justify_center()
.child(self.stack.clone())
}
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let _ = &self.data;
let _ = cx;
div()
.size_full()
.flex()
.items_center()
.justify_center()
.child(self.stack.clone())
}
}
fn main() {
gpui_platform::application().run(|cx: &mut App| {
init_example(cx, "Effect Stack");
gpui_platform::application().run(|cx: &mut App| {
init_example(cx, "Effect Stack");
let bounds = Bounds::centered(None, size(px(420.0), px(640.0)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|window, cx| cx.new(|cx| StackDemoRoot::new(window, cx)),
)
.unwrap();
});
let bounds = Bounds::centered(None, size(px(420.0), px(640.0)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|window, cx| cx.new(|cx| StackDemoRoot::new(window, cx)),
)
.unwrap();
});
}
+281 -281
View File
@@ -14,10 +14,10 @@ mod example_prelude;
use example_prelude::init_example;
use gpui::{
App, Bounds, Context, DragMoveEvent, FontWeight, HapticFeedbackStyle, Hsla, InteractiveElement,
IntoElement, MouseButton, MouseDownEvent, ParentElement, Pixels, Render,
StatefulInteractiveElement, Styled, Window, WindowBounds, WindowOptions, colors::Colors, div,
prelude::*, px, relative, rgb, size,
App, Bounds, Context, DragMoveEvent, FontWeight, HapticFeedbackStyle, Hsla, InteractiveElement,
IntoElement, MouseButton, MouseDownEvent, ParentElement, Pixels, Render,
StatefulInteractiveElement, Styled, Window, WindowBounds, WindowOptions, colors::Colors, div,
prelude::*, px, relative, rgb, size,
};
const SLIDER_MIN: f32 = 0.0;
@@ -29,304 +29,304 @@ const SLIDER_STEP_COUNT: usize = ((SLIDER_MAX - SLIDER_MIN) / SLIDER_STEP) as us
struct SliderDrag;
impl Render for SliderDrag {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
gpui::Empty
}
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
gpui::Empty
}
}
struct HapticFeedbackExample {
supported: bool,
slider_value: f32,
slider_prev_step: i32,
slider_bounds: Option<Bounds<Pixels>>,
supported: bool,
slider_value: f32,
slider_prev_step: i32,
slider_bounds: Option<Bounds<Pixels>>,
}
impl HapticFeedbackExample {
fn new(cx: &mut App) -> Self {
Self {
supported: cx.supports_haptic_feedback(),
slider_value: 0.0,
slider_prev_step: 0,
slider_bounds: None,
}
}
fn new(cx: &mut App) -> Self {
Self {
supported: cx.supports_haptic_feedback(),
slider_value: 0.0,
slider_prev_step: 0,
slider_bounds: None,
}
}
fn haptic_button(
&self,
id: &'static str,
label: &'static str,
style: HapticFeedbackStyle,
color: Hsla,
colors: &Colors,
cx: &mut Context<Self>,
) -> impl IntoElement {
let _ = cx;
fn haptic_button(
&self,
id: &'static str,
label: &'static str,
style: HapticFeedbackStyle,
color: Hsla,
colors: &Colors,
cx: &mut Context<Self>,
) -> impl IntoElement {
let _ = cx;
div()
.id(id)
.flex()
.flex_col()
.w_48()
.items_center()
.justify_center()
.px_4()
.py_3()
.rounded_md()
.bg(color)
.cursor_pointer()
.hover(move |s| s.bg(color.opacity(0.8)))
.active(move |s| s.bg(color.opacity(0.6)))
.child(
div()
.text_base()
.font_weight(FontWeight::MEDIUM)
.text_color(Hsla::from(colors.selected_text))
.child(label),
)
.on_hover(move |hovered, _, cx| {
if *hovered {
cx.play_haptic_feedback(style);
}
})
}
div()
.id(id)
.flex()
.flex_col()
.w_48()
.items_center()
.justify_center()
.px_4()
.py_3()
.rounded_md()
.bg(color)
.cursor_pointer()
.hover(move |s| s.bg(color.opacity(0.8)))
.active(move |s| s.bg(color.opacity(0.6)))
.child(
div()
.text_base()
.font_weight(FontWeight::MEDIUM)
.text_color(Hsla::from(colors.selected_text))
.child(label),
)
.on_hover(move |hovered, _, cx| {
if *hovered {
cx.play_haptic_feedback(style);
}
})
}
fn value_to_step(value: f32) -> i32 {
((value - SLIDER_MIN) / SLIDER_STEP).round() as i32
}
fn value_to_step(value: f32) -> i32 {
((value - SLIDER_MIN) / SLIDER_STEP).round() as i32
}
fn snap_to_step(raw: f32) -> f32 {
let snapped = (raw / SLIDER_STEP).round() * SLIDER_STEP;
snapped.clamp(SLIDER_MIN, SLIDER_MAX)
}
fn snap_to_step(raw: f32) -> f32 {
let snapped = (raw / SLIDER_STEP).round() * SLIDER_STEP;
snapped.clamp(SLIDER_MIN, SLIDER_MAX)
}
fn value_to_percentage(value: f32) -> f32 {
((value - SLIDER_MIN) / (SLIDER_MAX - SLIDER_MIN)).clamp(0.0, 1.0)
}
fn value_to_percentage(value: f32) -> f32 {
((value - SLIDER_MIN) / (SLIDER_MAX - SLIDER_MIN)).clamp(0.0, 1.0)
}
fn update_slider_from_position(
&mut self,
position_x: Pixels,
bounds: Bounds<Pixels>,
cx: &mut Context<Self>,
) {
let inner_x = (position_x - bounds.left()).clamp(px(0.), bounds.size.width);
let percentage = inner_x / bounds.size.width;
let raw = SLIDER_MIN + (SLIDER_MAX - SLIDER_MIN) * percentage;
let new_value = Self::snap_to_step(raw);
let new_step = Self::value_to_step(new_value);
fn update_slider_from_position(
&mut self,
position_x: Pixels,
bounds: Bounds<Pixels>,
cx: &mut Context<Self>,
) {
let inner_x = (position_x - bounds.left()).clamp(px(0.), bounds.size.width);
let percentage = inner_x / bounds.size.width;
let raw = SLIDER_MIN + (SLIDER_MAX - SLIDER_MIN) * percentage;
let new_value = Self::snap_to_step(raw);
let new_step = Self::value_to_step(new_value);
self.slider_value = new_value;
self.slider_bounds = Some(bounds);
self.slider_value = new_value;
self.slider_bounds = Some(bounds);
if new_step != self.slider_prev_step {
cx.play_haptic_feedback(HapticFeedbackStyle::LevelChange);
self.slider_prev_step = new_step;
}
if new_step != self.slider_prev_step {
cx.play_haptic_feedback(HapticFeedbackStyle::LevelChange);
self.slider_prev_step = new_step;
}
cx.notify();
}
cx.notify();
}
}
impl Render for HapticFeedbackExample {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
let slider_percentage = Self::value_to_percentage(self.slider_value);
let slider_color = Hsla::from(rgb(0x3b82f6));
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
let slider_percentage = Self::value_to_percentage(self.slider_value);
let slider_color = Hsla::from(rgb(0x3b82f6));
div()
.flex()
.flex_col()
.size_full()
.bg(colors.background)
.p_8()
.gap_6()
.child(
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_2xl()
.font_weight(FontWeight::SEMIBOLD)
.text_color(colors.text)
.child("Haptic Feedback"),
)
.child(
div().text_sm().text_color(colors.disabled).child(
"macOS Force Touch trackpad haptics via NSHapticFeedbackManager",
),
),
)
.child(
div()
.flex()
.items_center()
.gap_2()
.px_4()
.py_2()
.rounded_md()
.bg(if self.supported {
Hsla::from(rgb(0x22c55e)).opacity(0.1)
} else {
Hsla::from(rgb(0xf59e0b)).opacity(0.1)
})
.child({
let dot = if self.supported {
rgb(0x22c55e)
} else {
rgb(0xf59e0b)
};
div().size_2().rounded_full().bg(dot)
})
.child(
div()
.text_sm()
.font_weight(FontWeight::MEDIUM)
.text_color(colors.text)
.when_else(
self.supported,
|this| this.child("Haptics is supported on this machine"),
|this| this.child("Haptics is not supported on this machine"),
),
),
)
.child(
div()
.child("Hover over each button to trigger haptic feedback")
.text_sm()
.text_color(colors.text),
)
.child(
div()
.flex()
.gap_3()
.child(self.haptic_button(
"btn-generic",
"Generic",
HapticFeedbackStyle::Generic,
Hsla::from(rgb(0x3b82f6)),
&colors,
cx,
))
.child(self.haptic_button(
"btn-alignment",
"Alignment",
HapticFeedbackStyle::Alignment,
Hsla::from(rgb(0x10b981)),
&colors,
cx,
))
.child(self.haptic_button(
"btn-levelchange",
"LevelChange",
HapticFeedbackStyle::LevelChange,
Hsla::from(rgb(0x8b5cf6)),
&colors,
cx,
)),
)
.child(
div()
.flex()
.flex_col()
.gap_3()
.child(
div()
.text_lg()
.font_weight(FontWeight::SEMIBOLD)
.text_color(colors.text)
.child("Slider with LevelChange haptic"),
)
.child(
div().flex().items_center().gap_2().child(
div()
.font_weight(FontWeight::MEDIUM)
.text_color(colors.selected_text)
.child(format!("Value: {:.0}", self.slider_value)),
),
)
.child(
div()
.id("slider-container")
.w_full()
.h_4()
.flex()
.items_center()
.px_2()
.cursor_pointer()
.on_drag(SliderDrag, |_, _, _, cx| cx.new(|_| SliderDrag))
.on_drag_move(cx.listener(
|this, e: &DragMoveEvent<SliderDrag>, _, cx| {
this.update_slider_from_position(
e.event.position.x,
e.bounds,
cx,
);
},
))
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, e: &MouseDownEvent, _, cx| {
if let Some(bounds) = this.slider_bounds {
this.update_slider_from_position(e.position.x, bounds, cx);
}
}),
)
.child(
div()
.w_full()
.h_1p5()
.rounded_full()
.bg(Hsla::from(colors.text).opacity(0.12))
.flex()
.items_center()
.justify_between()
.children((0..(SLIDER_STEP_COUNT + 1)).map(|_| {
div()
.size_1p5()
.rounded_full()
.bg(colors.disabled)
.into_any()
}))
.child(
div()
.absolute()
.h_full()
.left(px(0.))
.right(relative(1.0 - slider_percentage))
.bg(slider_color.opacity(0.7))
.rounded_full(),
)
.child(
div()
.absolute()
.top(px(-6.))
.left(relative(slider_percentage))
.ml(px(-8.))
.size_4()
.rounded_full()
.bg(slider_color)
.shadow_md(),
),
),
),
)
}
div()
.flex()
.flex_col()
.size_full()
.bg(colors.background)
.p_8()
.gap_6()
.child(
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_2xl()
.font_weight(FontWeight::SEMIBOLD)
.text_color(colors.text)
.child("Haptic Feedback"),
)
.child(
div().text_sm().text_color(colors.disabled).child(
"macOS Force Touch trackpad haptics via NSHapticFeedbackManager",
),
),
)
.child(
div()
.flex()
.items_center()
.gap_2()
.px_4()
.py_2()
.rounded_md()
.bg(if self.supported {
Hsla::from(rgb(0x22c55e)).opacity(0.1)
} else {
Hsla::from(rgb(0xf59e0b)).opacity(0.1)
})
.child({
let dot = if self.supported {
rgb(0x22c55e)
} else {
rgb(0xf59e0b)
};
div().size_2().rounded_full().bg(dot)
})
.child(
div()
.text_sm()
.font_weight(FontWeight::MEDIUM)
.text_color(colors.text)
.when_else(
self.supported,
|this| this.child("Haptics is supported on this machine"),
|this| this.child("Haptics is not supported on this machine"),
),
),
)
.child(
div()
.child("Hover over each button to trigger haptic feedback")
.text_sm()
.text_color(colors.text),
)
.child(
div()
.flex()
.gap_3()
.child(self.haptic_button(
"btn-generic",
"Generic",
HapticFeedbackStyle::Generic,
Hsla::from(rgb(0x3b82f6)),
&colors,
cx,
))
.child(self.haptic_button(
"btn-alignment",
"Alignment",
HapticFeedbackStyle::Alignment,
Hsla::from(rgb(0x10b981)),
&colors,
cx,
))
.child(self.haptic_button(
"btn-levelchange",
"LevelChange",
HapticFeedbackStyle::LevelChange,
Hsla::from(rgb(0x8b5cf6)),
&colors,
cx,
)),
)
.child(
div()
.flex()
.flex_col()
.gap_3()
.child(
div()
.text_lg()
.font_weight(FontWeight::SEMIBOLD)
.text_color(colors.text)
.child("Slider with LevelChange haptic"),
)
.child(
div().flex().items_center().gap_2().child(
div()
.font_weight(FontWeight::MEDIUM)
.text_color(colors.selected_text)
.child(format!("Value: {:.0}", self.slider_value)),
),
)
.child(
div()
.id("slider-container")
.w_full()
.h_4()
.flex()
.items_center()
.px_2()
.cursor_pointer()
.on_drag(SliderDrag, |_, _, _, cx| cx.new(|_| SliderDrag))
.on_drag_move(cx.listener(
|this, e: &DragMoveEvent<SliderDrag>, _, cx| {
this.update_slider_from_position(
e.event.position.x,
e.bounds,
cx,
);
},
))
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, e: &MouseDownEvent, _, cx| {
if let Some(bounds) = this.slider_bounds {
this.update_slider_from_position(e.position.x, bounds, cx);
}
}),
)
.child(
div()
.w_full()
.h_1p5()
.rounded_full()
.bg(Hsla::from(colors.text).opacity(0.12))
.flex()
.items_center()
.justify_between()
.children((0..(SLIDER_STEP_COUNT + 1)).map(|_| {
div()
.size_1p5()
.rounded_full()
.bg(colors.disabled)
.into_any()
}))
.child(
div()
.absolute()
.h_full()
.left(px(0.))
.right(relative(1.0 - slider_percentage))
.bg(slider_color.opacity(0.7))
.rounded_full(),
)
.child(
div()
.absolute()
.top(px(-6.))
.left(relative(slider_percentage))
.ml(px(-8.))
.size_4()
.rounded_full()
.bg(slider_color)
.shadow_md(),
),
),
),
)
}
}
fn main() {
gpui_platform::application().run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(520.), px(520.)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|_, cx| cx.new(|cx| HapticFeedbackExample::new(cx)),
)
.expect("Failed to open window");
gpui_platform::application().run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(520.), px(520.)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|_, cx| cx.new(|cx| HapticFeedbackExample::new(cx)),
)
.expect("Failed to open window");
init_example(cx, "Haptic Feedback");
});
init_example(cx, "Haptic Feedback");
});
}
+444 -444
View File
@@ -13,8 +13,8 @@ mod example_prelude;
use example_prelude::init_example;
use gpui::colors::Colors;
use gpui::{
App, Bounds, ClickEvent, Context, Entity, Half, Hsla, IntoElement, MouseButton, MouseMoveEvent,
Pixels, Point, Render, Window, WindowBounds, WindowOptions, div, prelude::*, px, rgb, size,
App, Bounds, ClickEvent, Context, Entity, Half, Hsla, IntoElement, MouseButton, MouseMoveEvent,
Pixels, Point, Render, Window, WindowBounds, WindowOptions, div, prelude::*, px, rgb, size,
};
// ============================================================================
@@ -27,88 +27,88 @@ use gpui::{
// - Click count tracking
struct ClickDemo {
click_count: usize,
last_click_type: String,
click_count: usize,
last_click_type: String,
}
impl ClickDemo {
fn new() -> Self {
Self {
click_count: 0,
last_click_type: "None".to_string(),
}
}
fn new() -> Self {
Self {
click_count: 0,
last_click_type: "None".to_string(),
}
}
}
impl Render for ClickDemo {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
div()
.flex()
.flex_col()
.gap_3()
.p_4()
.rounded_lg()
.bg(colors.container)
.child(
div()
.text_sm()
.font_weight(gpui::FontWeight::SEMIBOLD)
.text_color(colors.text)
.child("Click Events"),
)
.child(
div()
.text_xs()
.text_color(colors.disabled)
.child("Single click, double click, or triple click the button"),
)
.child(
div()
.id("click-target")
.px_4()
.py_2()
.rounded_md()
.bg(colors.selected)
.text_color(colors.selected_text)
.text_sm()
.cursor_pointer()
.hover(|style| style.bg(colors.selected))
.active(|style| style.bg(colors.selected))
.child("Click Me!")
// on_click receives a ClickEvent with click_count() method
.on_click(cx.listener(|this, event: &ClickEvent, _window, cx| {
this.click_count += 1;
this.last_click_type = match event.click_count() {
1 => "Single Click".to_string(),
2 => "Double Click".to_string(),
3 => "Triple Click".to_string(),
n => format!("{n}x Click"),
};
cx.notify();
})),
)
.child(
div()
.flex()
.flex_col()
.gap_1()
.mt_2()
.child(
div()
.text_xs()
.text_color(colors.disabled)
.child(format!("Total clicks: {}", self.click_count)),
)
.child(
div()
.text_xs()
.text_color(colors.disabled)
.child(format!("Last: {}", self.last_click_type)),
),
)
}
div()
.flex()
.flex_col()
.gap_3()
.p_4()
.rounded_lg()
.bg(colors.container)
.child(
div()
.text_sm()
.font_weight(gpui::FontWeight::SEMIBOLD)
.text_color(colors.text)
.child("Click Events"),
)
.child(
div()
.text_xs()
.text_color(colors.disabled)
.child("Single click, double click, or triple click the button"),
)
.child(
div()
.id("click-target")
.px_4()
.py_2()
.rounded_md()
.bg(colors.selected)
.text_color(colors.selected_text)
.text_sm()
.cursor_pointer()
.hover(|style| style.bg(colors.selected))
.active(|style| style.bg(colors.selected))
.child("Click Me!")
// on_click receives a ClickEvent with click_count() method
.on_click(cx.listener(|this, event: &ClickEvent, _window, cx| {
this.click_count += 1;
this.last_click_type = match event.click_count() {
1 => "Single Click".to_string(),
2 => "Double Click".to_string(),
3 => "Triple Click".to_string(),
n => format!("{n}x Click"),
};
cx.notify();
})),
)
.child(
div()
.flex()
.flex_col()
.gap_1()
.mt_2()
.child(
div()
.text_xs()
.text_color(colors.disabled)
.child(format!("Total clicks: {}", self.click_count)),
)
.child(
div()
.text_xs()
.text_color(colors.disabled)
.child(format!("Last: {}", self.last_click_type)),
),
)
}
}
// ============================================================================
@@ -120,90 +120,90 @@ impl Render for ClickDemo {
// - on_hover() callback for programmatic hover detection
struct HoverDemo {
is_hovered: bool,
hover_count: usize,
is_hovered: bool,
hover_count: usize,
}
impl HoverDemo {
fn new() -> Self {
Self {
is_hovered: false,
hover_count: 0,
}
}
fn new() -> Self {
Self {
is_hovered: false,
hover_count: 0,
}
}
}
impl Render for HoverDemo {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
let is_hovered = self.is_hovered;
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
let is_hovered = self.is_hovered;
div()
.flex()
.flex_col()
.gap_3()
.p_4()
.rounded_lg()
.bg(colors.container)
.child(
div()
.text_sm()
.font_weight(gpui::FontWeight::SEMIBOLD)
.text_color(colors.text)
.child("Hover Events"),
)
.child(
div()
.text_xs()
.text_color(colors.disabled)
.child("Move your mouse in and out of the target"),
)
.child(
div()
.id("hover-target")
.px_4()
.py_3()
.rounded_md()
.border_2()
.border_color(if is_hovered {
colors.selected
} else {
colors.border
})
.bg(if is_hovered {
colors.selected
} else {
colors.selected
})
.text_color(if is_hovered {
colors.selected_text
} else {
colors.text
})
.text_sm()
.cursor_pointer()
.child(if is_hovered {
"Mouse Inside!"
} else {
"Hover Over Me"
})
// on_hover callback receives a bool: true when mouse enters, false when it leaves
.on_hover(cx.listener(|this, &hovered, _window, cx| {
this.is_hovered = hovered;
if hovered {
this.hover_count += 1;
}
cx.notify();
})),
)
.child(
div()
.text_xs()
.text_color(colors.disabled)
.mt_2()
.child(format!("Times hovered: {}", self.hover_count)),
)
}
div()
.flex()
.flex_col()
.gap_3()
.p_4()
.rounded_lg()
.bg(colors.container)
.child(
div()
.text_sm()
.font_weight(gpui::FontWeight::SEMIBOLD)
.text_color(colors.text)
.child("Hover Events"),
)
.child(
div()
.text_xs()
.text_color(colors.disabled)
.child("Move your mouse in and out of the target"),
)
.child(
div()
.id("hover-target")
.px_4()
.py_3()
.rounded_md()
.border_2()
.border_color(if is_hovered {
colors.selected
} else {
colors.border
})
.bg(if is_hovered {
colors.selected
} else {
colors.selected
})
.text_color(if is_hovered {
colors.selected_text
} else {
colors.text
})
.text_sm()
.cursor_pointer()
.child(if is_hovered {
"Mouse Inside!"
} else {
"Hover Over Me"
})
// on_hover callback receives a bool: true when mouse enters, false when it leaves
.on_hover(cx.listener(|this, &hovered, _window, cx| {
this.is_hovered = hovered;
if hovered {
this.hover_count += 1;
}
cx.notify();
})),
)
.child(
div()
.text_xs()
.text_color(colors.disabled)
.mt_2()
.child(format!("Times hovered: {}", self.hover_count)),
)
}
}
// ============================================================================
@@ -216,115 +216,115 @@ impl Render for HoverDemo {
// - on_mouse_move - fires when mouse moves over element
struct MouseEventsDemo {
mouse_position: Option<Point<Pixels>>,
is_pressed: bool,
event_log: Vec<String>,
mouse_position: Option<Point<Pixels>>,
is_pressed: bool,
event_log: Vec<String>,
}
impl MouseEventsDemo {
fn new() -> Self {
Self {
mouse_position: None,
is_pressed: false,
event_log: Vec::new(),
}
}
fn new() -> Self {
Self {
mouse_position: None,
is_pressed: false,
event_log: Vec::new(),
}
}
fn log_event(&mut self, event: &str) {
self.event_log.push(event.to_string());
if self.event_log.len() > 5 {
self.event_log.remove(0);
}
}
fn log_event(&mut self, event: &str) {
self.event_log.push(event.to_string());
if self.event_log.len() > 5 {
self.event_log.remove(0);
}
}
}
impl Render for MouseEventsDemo {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
let is_pressed = self.is_pressed;
let position_text = self
.mouse_position
.map(|p| format!("({:.0}, {:.0})", f32::from(p.x), f32::from(p.y)))
.unwrap_or_else(|| "—".to_string());
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
let is_pressed = self.is_pressed;
let position_text = self
.mouse_position
.map(|p| format!("({:.0}, {:.0})", f32::from(p.x), f32::from(p.y)))
.unwrap_or_else(|| "—".to_string());
div()
.flex()
.flex_col()
.gap_3()
.p_4()
.rounded_lg()
.bg(colors.container)
.child(
div()
.text_sm()
.font_weight(gpui::FontWeight::SEMIBOLD)
.text_color(colors.text)
.child("Mouse Events"),
)
.child(
div()
.text_xs()
.text_color(colors.disabled)
.child("Move and click within the target area"),
)
.child(
div()
.id("mouse-events-target")
.h_20()
.rounded_md()
.border_2()
.border_color(if is_pressed {
colors.selected
} else {
colors.border
})
.bg(if is_pressed {
colors.selected
} else {
colors.selected
})
.flex()
.items_center()
.justify_center()
.text_sm()
.text_color(colors.text)
.child(format!("Position: {}", position_text))
.on_mouse_down(
MouseButton::Left,
cx.listener(|this, _event, _window, cx| {
this.is_pressed = true;
this.log_event("Mouse Down");
cx.notify();
}),
)
.on_mouse_up(
MouseButton::Left,
cx.listener(|this, _event, _window, cx| {
this.is_pressed = false;
this.log_event("Mouse Up");
cx.notify();
}),
)
.on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, _window, cx| {
this.mouse_position = Some(event.position);
cx.notify();
})),
)
.child(
div()
.flex()
.flex_col()
.gap_0p5()
.mt_2()
.text_xs()
.text_color(colors.disabled)
.children(
self.event_log
.iter()
.map(|e| div().child(format!("• {}", e))),
),
)
}
div()
.flex()
.flex_col()
.gap_3()
.p_4()
.rounded_lg()
.bg(colors.container)
.child(
div()
.text_sm()
.font_weight(gpui::FontWeight::SEMIBOLD)
.text_color(colors.text)
.child("Mouse Events"),
)
.child(
div()
.text_xs()
.text_color(colors.disabled)
.child("Move and click within the target area"),
)
.child(
div()
.id("mouse-events-target")
.h_20()
.rounded_md()
.border_2()
.border_color(if is_pressed {
colors.selected
} else {
colors.border
})
.bg(if is_pressed {
colors.selected
} else {
colors.selected
})
.flex()
.items_center()
.justify_center()
.text_sm()
.text_color(colors.text)
.child(format!("Position: {}", position_text))
.on_mouse_down(
MouseButton::Left,
cx.listener(|this, _event, _window, cx| {
this.is_pressed = true;
this.log_event("Mouse Down");
cx.notify();
}),
)
.on_mouse_up(
MouseButton::Left,
cx.listener(|this, _event, _window, cx| {
this.is_pressed = false;
this.log_event("Mouse Up");
cx.notify();
}),
)
.on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, _window, cx| {
this.mouse_position = Some(event.position);
cx.notify();
})),
)
.child(
div()
.flex()
.flex_col()
.gap_0p5()
.mt_2()
.text_xs()
.text_color(colors.disabled)
.children(
self.event_log
.iter()
.map(|e| div().child(format!("• {}", e))),
),
)
}
}
// ============================================================================
@@ -337,146 +337,146 @@ impl Render for MouseEventsDemo {
#[derive(Clone, Copy)]
struct DragData {
index: usize,
color: Hsla,
position: Point<Pixels>,
index: usize,
color: Hsla,
position: Point<Pixels>,
}
impl DragData {
fn new(index: usize, color: Hsla) -> Self {
Self {
index,
color,
position: Point::default(),
}
}
fn new(index: usize, color: Hsla) -> Self {
Self {
index,
color,
position: Point::default(),
}
}
fn with_position(mut self, position: Point<Pixels>) -> Self {
self.position = position;
self
}
fn with_position(mut self, position: Point<Pixels>) -> Self {
self.position = position;
self
}
}
// Render trait for DragData allows it to be rendered as drag feedback
impl Render for DragData {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let size = gpui::size(px(80.), px(40.));
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let size = gpui::size(px(80.), px(40.));
// Position the drag preview at the cursor
div()
.pl(self.position.x - size.width.half())
.pt(self.position.y - size.height.half())
.child(
div()
.flex()
.justify_center()
.items_center()
.w(size.width)
.h(size.height)
.bg(self.color.opacity(0.8))
.text_color(gpui::white())
.text_xs()
.rounded_md()
.shadow_lg()
.child(format!("Item {}", self.index + 1)),
)
}
// Position the drag preview at the cursor
div()
.pl(self.position.x - size.width.half())
.pt(self.position.y - size.height.half())
.child(
div()
.flex()
.justify_center()
.items_center()
.w(size.width)
.h(size.height)
.bg(self.color.opacity(0.8))
.text_color(gpui::white())
.text_xs()
.rounded_md()
.shadow_lg()
.child(format!("Item {}", self.index + 1)),
)
}
}
struct DragDropDemo {
dropped_item: Option<DragData>,
dropped_item: Option<DragData>,
}
impl DragDropDemo {
fn new() -> Self {
Self { dropped_item: None }
}
fn new() -> Self {
Self { dropped_item: None }
}
}
impl Render for DragDropDemo {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
let item_colors = [rgb(0xd32f2f), rgb(0x388e3c), rgb(0xf9a825)];
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
let item_colors = [rgb(0xd32f2f), rgb(0x388e3c), rgb(0xf9a825)];
div()
.flex()
.flex_col()
.gap_3()
.p_4()
.rounded_lg()
.bg(colors.container)
.child(
div()
.text_sm()
.font_weight(gpui::FontWeight::SEMIBOLD)
.text_color(colors.text)
.child("Drag and Drop"),
)
.child(
div()
.text_xs()
.text_color(colors.disabled)
.child("Drag items to the drop zone below"),
)
.child(
div()
.flex()
.gap_2()
.children(item_colors.into_iter().enumerate().map(|(index, color)| {
let drag_data = DragData::new(index, color.into());
div()
.flex()
.flex_col()
.gap_3()
.p_4()
.rounded_lg()
.bg(colors.container)
.child(
div()
.text_sm()
.font_weight(gpui::FontWeight::SEMIBOLD)
.text_color(colors.text)
.child("Drag and Drop"),
)
.child(
div()
.text_xs()
.text_color(colors.disabled)
.child("Drag items to the drop zone below"),
)
.child(
div()
.flex()
.gap_2()
.children(item_colors.into_iter().enumerate().map(|(index, color)| {
let drag_data = DragData::new(index, color.into());
div()
.id(("drag-item", index))
.px_3()
.py_2()
.rounded_md()
.border_2()
.border_color(color)
.text_color(color)
.text_xs()
.cursor_grab()
.hover(move |style| {
let c: Hsla = color.into();
style.bg(c.opacity(0.1))
})
.child(format!("Item {}", index + 1))
// on_drag takes: drag data, and a closure that creates the drag preview
.on_drag(drag_data, |data: &DragData, position, _, cx| {
cx.new(|_| data.with_position(position))
})
})),
)
.child(
div()
.id("drop-target")
.mt_2()
.h_16()
.rounded_md()
.border_2()
.border_dashed()
.border_color(
self.dropped_item
.map(|d| d.color)
.unwrap_or_else(|| colors.border.into()),
)
.when_some(self.dropped_item, |el, data| el.bg(data.color.opacity(0.2)))
.flex()
.items_center()
.justify_center()
.text_xs()
.text_color(colors.disabled)
// on_drop receives the drag data when an item is dropped
.on_drop(cx.listener(|this, data: &DragData, _window, cx| {
this.dropped_item = Some(*data);
cx.notify();
}))
.child(
self.dropped_item
.map(|d| format!("Dropped: Item {}", d.index + 1))
.unwrap_or_else(|| "Drop Zone".to_string()),
),
)
}
div()
.id(("drag-item", index))
.px_3()
.py_2()
.rounded_md()
.border_2()
.border_color(color)
.text_color(color)
.text_xs()
.cursor_grab()
.hover(move |style| {
let c: Hsla = color.into();
style.bg(c.opacity(0.1))
})
.child(format!("Item {}", index + 1))
// on_drag takes: drag data, and a closure that creates the drag preview
.on_drag(drag_data, |data: &DragData, position, _, cx| {
cx.new(|_| data.with_position(position))
})
})),
)
.child(
div()
.id("drop-target")
.mt_2()
.h_16()
.rounded_md()
.border_2()
.border_dashed()
.border_color(
self.dropped_item
.map(|d| d.color)
.unwrap_or_else(|| colors.border.into()),
)
.when_some(self.dropped_item, |el, data| el.bg(data.color.opacity(0.2)))
.flex()
.items_center()
.justify_center()
.text_xs()
.text_color(colors.disabled)
// on_drop receives the drag data when an item is dropped
.on_drop(cx.listener(|this, data: &DragData, _window, cx| {
this.dropped_item = Some(*data);
cx.notify();
}))
.child(
self.dropped_item
.map(|d| format!("Dropped: Item {}", d.index + 1))
.unwrap_or_else(|| "Drop Zone".to_string()),
),
)
}
}
// ============================================================================
@@ -484,84 +484,84 @@ impl Render for DragDropDemo {
// ============================================================================
struct InteractiveElementsExample {
click_demo: Entity<ClickDemo>,
hover_demo: Entity<HoverDemo>,
mouse_events_demo: Entity<MouseEventsDemo>,
drag_drop_demo: Entity<DragDropDemo>,
click_demo: Entity<ClickDemo>,
hover_demo: Entity<HoverDemo>,
mouse_events_demo: Entity<MouseEventsDemo>,
drag_drop_demo: Entity<DragDropDemo>,
}
impl InteractiveElementsExample {
fn new(cx: &mut Context<Self>) -> Self {
Self {
click_demo: cx.new(|_| ClickDemo::new()),
hover_demo: cx.new(|_| HoverDemo::new()),
mouse_events_demo: cx.new(|_| MouseEventsDemo::new()),
drag_drop_demo: cx.new(|_| DragDropDemo::new()),
}
}
fn new(cx: &mut Context<Self>) -> Self {
Self {
click_demo: cx.new(|_| ClickDemo::new()),
hover_demo: cx.new(|_| HoverDemo::new()),
mouse_events_demo: cx.new(|_| MouseEventsDemo::new()),
drag_drop_demo: cx.new(|_| DragDropDemo::new()),
}
}
}
impl Render for InteractiveElementsExample {
fn render(&mut self, window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
fn render(&mut self, window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
div()
.id("main")
.size_full()
.p_6()
.bg(colors.background)
.overflow_scroll()
.child(
div()
.flex()
.flex_col()
.gap_6()
.max_w(px(800.))
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(
div()
.text_xl()
.font_weight(gpui::FontWeight::BOLD)
.text_color(colors.text)
.child("Interactive Elements"),
)
.child(
div()
.text_sm()
.text_color(colors.disabled)
.child("Click, hover, mouse events, and drag-and-drop in GPUI"),
),
)
.child(
div()
.grid()
.grid_cols(2)
.gap_4()
.child(self.click_demo.clone())
.child(self.hover_demo.clone())
.child(self.mouse_events_demo.clone())
.child(self.drag_drop_demo.clone()),
),
)
}
div()
.id("main")
.size_full()
.p_6()
.bg(colors.background)
.overflow_scroll()
.child(
div()
.flex()
.flex_col()
.gap_6()
.max_w(px(800.))
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(
div()
.text_xl()
.font_weight(gpui::FontWeight::BOLD)
.text_color(colors.text)
.child("Interactive Elements"),
)
.child(
div()
.text_sm()
.text_color(colors.disabled)
.child("Click, hover, mouse events, and drag-and-drop in GPUI"),
),
)
.child(
div()
.grid()
.grid_cols(2)
.gap_4()
.child(self.click_demo.clone())
.child(self.hover_demo.clone())
.child(self.mouse_events_demo.clone())
.child(self.drag_drop_demo.clone()),
),
)
}
}
fn main() {
gpui_platform::application().run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(700.), px(650.)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|_, cx| cx.new(|cx| InteractiveElementsExample::new(cx)),
)
.expect("Failed to open window");
gpui_platform::application().run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(700.), px(650.)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|_, cx| cx.new(|cx| InteractiveElementsExample::new(cx)),
)
.expect("Failed to open window");
init_example(cx, "Interactive Elements");
});
init_example(cx, "Interactive Elements");
});
}
+131 -131
View File
@@ -15,7 +15,7 @@ mod example_prelude;
use gpui::colors::Colors;
use gpui::{
App, Bounds, Context, Render, Window, WindowBounds, WindowOptions, div, prelude::*, px, size,
App, Bounds, Context, Render, Window, WindowBounds, WindowOptions, div, prelude::*, px, size,
};
/// The URL the credentials are keyed by. The keyring label (Linux/FreeBSD) is a
@@ -23,154 +23,154 @@ use gpui::{
const CREDENTIAL_URL: &str = "https://example.com/keyring-demo";
struct KeyringExample {
status: String,
status: String,
}
impl KeyringExample {
fn new() -> Self {
Self {
status: "Use the buttons to store, load, and delete credentials.".into(),
}
}
fn new() -> Self {
Self {
status: "Use the buttons to store, load, and delete credentials.".into(),
}
}
fn set_status(&mut self, status: impl Into<String>, cx: &mut Context<Self>) {
self.status = status.into();
cx.notify();
}
fn set_status(&mut self, status: impl Into<String>, cx: &mut Context<Self>) {
self.status = status.into();
cx.notify();
}
fn save(&mut self, cx: &mut Context<Self>) {
self.set_status("Saving...", cx);
cx.spawn(async move |this, cx| {
let task =
cx.update(|cx| cx.write_credentials(CREDENTIAL_URL, "ada@example.com", b"hunter2"));
let result = task.await;
this.update(cx, |this, cx| match result {
Ok(()) => this.set_status("Saved credentials for ada@example.com.", cx),
Err(err) => this.set_status(format!("Failed to save: {err}"), cx),
})
})
.detach();
}
fn save(&mut self, cx: &mut Context<Self>) {
self.set_status("Saving...", cx);
cx.spawn(async move |this, cx| {
let task =
cx.update(|cx| cx.write_credentials(CREDENTIAL_URL, "ada@example.com", b"hunter2"));
let result = task.await;
this.update(cx, |this, cx| match result {
Ok(()) => this.set_status("Saved credentials for ada@example.com.", cx),
Err(err) => this.set_status(format!("Failed to save: {err}"), cx),
})
})
.detach();
}
fn load(&mut self, cx: &mut Context<Self>) {
self.set_status("Loading...", cx);
cx.spawn(async move |this, cx| {
let task = cx.update(|cx| cx.read_credentials(CREDENTIAL_URL));
let result = task.await;
this.update(cx, |this, cx| match result {
Ok(Some((username, password))) => this.set_status(
format!("Loaded {username} (password is {} bytes).", password.len()),
cx,
),
Ok(None) => this.set_status("No credentials stored yet.", cx),
Err(err) => this.set_status(format!("Failed to load: {err}"), cx),
})
})
.detach();
}
fn load(&mut self, cx: &mut Context<Self>) {
self.set_status("Loading...", cx);
cx.spawn(async move |this, cx| {
let task = cx.update(|cx| cx.read_credentials(CREDENTIAL_URL));
let result = task.await;
this.update(cx, |this, cx| match result {
Ok(Some((username, password))) => this.set_status(
format!("Loaded {username} (password is {} bytes).", password.len()),
cx,
),
Ok(None) => this.set_status("No credentials stored yet.", cx),
Err(err) => this.set_status(format!("Failed to load: {err}"), cx),
})
})
.detach();
}
fn delete(&mut self, cx: &mut Context<Self>) {
self.set_status("Deleting...", cx);
cx.spawn(async move |this, cx| {
let task = cx.update(|cx| cx.delete_credentials(CREDENTIAL_URL));
let result = task.await;
this.update(cx, |this, cx| match result {
Ok(()) => this.set_status("Deleted stored credentials.", cx),
Err(err) => this.set_status(format!("Failed to delete: {err}"), cx),
})
})
.detach();
}
fn delete(&mut self, cx: &mut Context<Self>) {
self.set_status("Deleting...", cx);
cx.spawn(async move |this, cx| {
let task = cx.update(|cx| cx.delete_credentials(CREDENTIAL_URL));
let result = task.await;
this.update(cx, |this, cx| match result {
Ok(()) => this.set_status("Deleted stored credentials.", cx),
Err(err) => this.set_status(format!("Failed to delete: {err}"), cx),
})
})
.detach();
}
}
impl Render for KeyringExample {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
div().size_full().p_6().bg(colors.background).child(
div()
.flex()
.flex_col()
.gap_4()
.max_w(px(460.))
.child(
div()
.text_xl()
.font_weight(gpui::FontWeight::BOLD)
.text_color(colors.text)
.child("Keyring Credentials"),
)
.child(
div()
.text_sm()
.text_color(colors.disabled)
.child(format!("Stored under: {CREDENTIAL_URL}")),
)
.child(
div()
.p_4()
.rounded_lg()
.bg(colors.container)
.border_1()
.border_color(colors.border)
.text_sm()
.text_color(colors.text)
.child(self.status.clone()),
)
.child(
div()
.flex()
.gap_2()
.child(
button(&colors, "save", "Save")
.on_click(cx.listener(|this, _, _, cx| this.save(cx))),
)
.child(
button(&colors, "load", "Load")
.on_click(cx.listener(|this, _, _, cx| this.load(cx))),
)
.child(
button(&colors, "delete", "Delete")
.on_click(cx.listener(|this, _, _, cx| this.delete(cx))),
),
),
)
}
div().size_full().p_6().bg(colors.background).child(
div()
.flex()
.flex_col()
.gap_4()
.max_w(px(460.))
.child(
div()
.text_xl()
.font_weight(gpui::FontWeight::BOLD)
.text_color(colors.text)
.child("Keyring Credentials"),
)
.child(
div()
.text_sm()
.text_color(colors.disabled)
.child(format!("Stored under: {CREDENTIAL_URL}")),
)
.child(
div()
.p_4()
.rounded_lg()
.bg(colors.container)
.border_1()
.border_color(colors.border)
.text_sm()
.text_color(colors.text)
.child(self.status.clone()),
)
.child(
div()
.flex()
.gap_2()
.child(
button(&colors, "save", "Save")
.on_click(cx.listener(|this, _, _, cx| this.save(cx))),
)
.child(
button(&colors, "load", "Load")
.on_click(cx.listener(|this, _, _, cx| this.load(cx))),
)
.child(
button(&colors, "delete", "Delete")
.on_click(cx.listener(|this, _, _, cx| this.delete(cx))),
),
),
)
}
}
fn button(
colors: &Colors,
id: impl Into<gpui::ElementId>,
label: &'static str,
colors: &Colors,
id: impl Into<gpui::ElementId>,
label: &'static str,
) -> gpui::Stateful<gpui::Div> {
let bg_hover = colors.border;
div()
.id(id)
.px_3()
.py_1p5()
.rounded_md()
.text_sm()
.text_color(colors.selected_text)
.bg(colors.selected)
.cursor_pointer()
.hover(move |style| style.bg(bg_hover))
.child(label)
let bg_hover = colors.border;
div()
.id(id)
.px_3()
.py_1p5()
.rounded_md()
.text_sm()
.text_color(colors.selected_text)
.bg(colors.selected)
.cursor_pointer()
.hover(move |style| style.bg(bg_hover))
.child(label)
}
fn main() {
gpui_platform::application().run(|cx: &mut App| {
cx.set_keyring_label("gpui-ce-keyring-example");
gpui_platform::application().run(|cx: &mut App| {
cx.set_keyring_label("gpui-ce-keyring-example");
let bounds = Bounds::centered(None, size(px(500.), px(360.)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|_, cx| cx.new(|_| KeyringExample::new()),
)
.expect("Failed to open window");
let bounds = Bounds::centered(None, size(px(500.), px(360.)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|_, cx| cx.new(|_| KeyringExample::new()),
)
.expect("Failed to open window");
example_prelude::init_example(cx, "Keyring");
});
example_prelude::init_example(cx, "Keyring");
});
}
+422 -422
View File
@@ -12,379 +12,379 @@ mod example_prelude;
use example_prelude::init_example;
use gpui::colors::Colors;
use gpui::{
Bounds, Context, Div, Hsla, Render, Rgba, Window, WindowBounds, WindowOptions, div, prelude::*,
px, size,
Bounds, Context, Div, Hsla, Render, Rgba, Window, WindowBounds, WindowOptions, div, prelude::*,
px, size,
};
// Helper: Colored block for visualization
fn block(label: &'static str, color: Hsla, text_color: Rgba) -> Div {
div()
.flex()
.items_center()
.justify_center()
.bg(color)
.border_1()
.border_color(gpui::white().opacity(0.3))
.rounded_md()
.text_xs()
.text_color(text_color)
.child(label)
div()
.flex()
.items_center()
.justify_center()
.bg(color)
.border_1()
.border_color(gpui::white().opacity(0.3))
.rounded_md()
.text_xs()
.text_color(text_color)
.child(label)
}
// Flexbox Examples
fn flexbox_row_example(colors: &Colors) -> impl IntoElement {
let text_muted = colors.disabled;
let text = colors.selected_text;
let text_muted = colors.disabled;
let text = colors.selected_text;
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_xs()
.text_color(text_muted)
.child("flex().flex_row().gap_2()"),
)
.child(
div()
.flex()
.flex_row()
.gap_2()
.child(block("A", gpui::red(), text).size_8())
.child(block("B", gpui::green(), text).size_8())
.child(block("C", gpui::blue(), text).size_8()),
)
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_xs()
.text_color(text_muted)
.child("flex().flex_row().gap_2()"),
)
.child(
div()
.flex()
.flex_row()
.gap_2()
.child(block("A", gpui::red(), text).size_8())
.child(block("B", gpui::green(), text).size_8())
.child(block("C", gpui::blue(), text).size_8()),
)
}
fn flexbox_column_example(colors: &Colors) -> impl IntoElement {
let text_muted = colors.disabled;
let text = colors.selected_text;
let text_muted = colors.disabled;
let text = colors.selected_text;
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_xs()
.text_color(text_muted)
.child("flex().flex_col().gap_2()"),
)
.child(
div()
.h_24()
.flex()
.flex_col()
.gap_2()
.child(block("A", gpui::red(), text).h_6())
.child(block("B", gpui::green(), text).h_6())
.child(block("C", gpui::blue(), text).h_6()),
)
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_xs()
.text_color(text_muted)
.child("flex().flex_col().gap_2()"),
)
.child(
div()
.h_24()
.flex()
.flex_col()
.gap_2()
.child(block("A", gpui::red(), text).h_6())
.child(block("B", gpui::green(), text).h_6())
.child(block("C", gpui::blue(), text).h_6()),
)
}
fn flexbox_justify_example(colors: &Colors) -> impl IntoElement {
let text_muted = colors.disabled;
let text = colors.selected_text;
let surface = colors.container;
let text_muted = colors.disabled;
let text = colors.selected_text;
let surface = colors.container;
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_xs()
.text_color(text_muted)
.child("justify_between / justify_center / justify_end"),
)
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(
div()
.flex()
.justify_between()
.p_1()
.bg(surface)
.rounded_sm()
.child(block("Start", gpui::red(), text).px_2().py_1())
.child(block("End", gpui::blue(), text).px_2().py_1()),
)
.child(
div()
.flex()
.justify_center()
.p_1()
.bg(surface)
.rounded_sm()
.child(block("Center", gpui::green(), text).px_2().py_1()),
)
.child(
div()
.flex()
.justify_end()
.p_1()
.bg(surface)
.rounded_sm()
.child(block("End", gpui::yellow(), text).px_2().py_1()),
),
)
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_xs()
.text_color(text_muted)
.child("justify_between / justify_center / justify_end"),
)
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(
div()
.flex()
.justify_between()
.p_1()
.bg(surface)
.rounded_sm()
.child(block("Start", gpui::red(), text).px_2().py_1())
.child(block("End", gpui::blue(), text).px_2().py_1()),
)
.child(
div()
.flex()
.justify_center()
.p_1()
.bg(surface)
.rounded_sm()
.child(block("Center", gpui::green(), text).px_2().py_1()),
)
.child(
div()
.flex()
.justify_end()
.p_1()
.bg(surface)
.rounded_sm()
.child(block("End", gpui::yellow(), text).px_2().py_1()),
),
)
}
fn flexbox_grow_example(colors: &Colors) -> impl IntoElement {
let text_muted = colors.disabled;
let text = colors.selected_text;
let text_muted = colors.disabled;
let text = colors.selected_text;
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_xs()
.text_color(text_muted)
.child("flex_1 (grow) vs flex_none (fixed)"),
)
.child(
div()
.flex()
.gap_2()
.child(block("fixed", gpui::red(), text).flex_none().w_16().h_8())
.child(block("flex_1 (grows)", gpui::green(), text).flex_1().h_8())
.child(block("fixed", gpui::blue(), text).flex_none().w_16().h_8()),
)
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_xs()
.text_color(text_muted)
.child("flex_1 (grow) vs flex_none (fixed)"),
)
.child(
div()
.flex()
.gap_2()
.child(block("fixed", gpui::red(), text).flex_none().w_16().h_8())
.child(block("flex_1 (grows)", gpui::green(), text).flex_1().h_8())
.child(block("fixed", gpui::blue(), text).flex_none().w_16().h_8()),
)
}
// Grid Examples
fn grid_basic_example(colors: &Colors) -> impl IntoElement {
let text_muted = colors.disabled;
let text = colors.selected_text;
let text_muted = colors.disabled;
let text = colors.selected_text;
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_xs()
.text_color(text_muted)
.child("grid().grid_cols(3).gap_1()"),
)
.child(
div()
.grid()
.grid_cols(3)
.gap_1()
.child(block("1", gpui::red(), text).h_8())
.child(block("2", gpui::green(), text).h_8())
.child(block("3", gpui::blue(), text).h_8())
.child(block("4", gpui::yellow(), text).h_8())
.child(block("5", gpui::red(), text).h_8())
.child(block("6", gpui::green(), text).h_8()),
)
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_xs()
.text_color(text_muted)
.child("grid().grid_cols(3).gap_1()"),
)
.child(
div()
.grid()
.grid_cols(3)
.gap_1()
.child(block("1", gpui::red(), text).h_8())
.child(block("2", gpui::green(), text).h_8())
.child(block("3", gpui::blue(), text).h_8())
.child(block("4", gpui::yellow(), text).h_8())
.child(block("5", gpui::red(), text).h_8())
.child(block("6", gpui::green(), text).h_8()),
)
}
fn grid_span_example(colors: &Colors) -> impl IntoElement {
let text_muted = colors.disabled;
let text = colors.selected_text;
let text_muted = colors.disabled;
let text = colors.selected_text;
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_xs()
.text_color(text_muted)
.child("col_span / row_span"),
)
.child(
div()
.grid()
.grid_cols(4)
.grid_rows(3)
.gap_1()
.child(
block("Header (col_span_full)", gpui::red(), text)
.col_span_full()
.h_6(),
)
.child(
block("Side", gpui::green(), text)
.col_span(1)
.row_span(2)
.h_full(),
)
.child(
block("Content (col_span 3)", gpui::blue(), text)
.col_span(3)
.row_span(2)
.h_full(),
),
)
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_xs()
.text_color(text_muted)
.child("col_span / row_span"),
)
.child(
div()
.grid()
.grid_cols(4)
.grid_rows(3)
.gap_1()
.child(
block("Header (col_span_full)", gpui::red(), text)
.col_span_full()
.h_6(),
)
.child(
block("Side", gpui::green(), text)
.col_span(1)
.row_span(2)
.h_full(),
)
.child(
block("Content (col_span 3)", gpui::blue(), text)
.col_span(3)
.row_span(2)
.h_full(),
),
)
}
// Common Layout Patterns
fn app_shell_pattern(colors: &Colors) -> impl IntoElement {
let text_muted = colors.disabled;
let text = colors.text;
let surface = colors.container;
let surface_hover = colors.selected;
let background = colors.background;
let border = colors.border;
let text_muted = colors.disabled;
let text = colors.text;
let surface = colors.container;
let surface_hover = colors.selected;
let background = colors.background;
let border = colors.border;
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_xs()
.text_color(text_muted)
.child("App Shell: Header + Sidebar + Content"),
)
.child(
div()
.h_32()
.flex()
.flex_col()
.border_1()
.border_color(border)
.rounded_md()
.overflow_hidden()
.child(
div()
.h_6()
.flex()
.items_center()
.px_2()
.bg(surface_hover)
.text_xs()
.text_color(text)
.child("Header"),
)
.child(
div()
.flex_1()
.flex()
.child(
div()
.w_16()
.bg(surface)
.flex()
.items_center()
.justify_center()
.text_xs()
.text_color(text_muted)
.child("Side"),
)
.child(
div()
.flex_1()
.bg(background)
.flex()
.items_center()
.justify_center()
.text_xs()
.text_color(text_muted)
.child("Content"),
),
),
)
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_xs()
.text_color(text_muted)
.child("App Shell: Header + Sidebar + Content"),
)
.child(
div()
.h_32()
.flex()
.flex_col()
.border_1()
.border_color(border)
.rounded_md()
.overflow_hidden()
.child(
div()
.h_6()
.flex()
.items_center()
.px_2()
.bg(surface_hover)
.text_xs()
.text_color(text)
.child("Header"),
)
.child(
div()
.flex_1()
.flex()
.child(
div()
.w_16()
.bg(surface)
.flex()
.items_center()
.justify_center()
.text_xs()
.text_color(text_muted)
.child("Side"),
)
.child(
div()
.flex_1()
.bg(background)
.flex()
.items_center()
.justify_center()
.text_xs()
.text_color(text_muted)
.child("Content"),
),
),
)
}
fn centered_pattern(colors: &Colors) -> impl IntoElement {
let text_muted = colors.disabled;
let text = colors.selected_text;
let surface = colors.container;
let accent = colors.selected;
let text_muted = colors.disabled;
let text = colors.selected_text;
let surface = colors.container;
let accent = colors.selected;
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_xs()
.text_color(text_muted)
.child("Centering: items_center + justify_center"),
)
.child(
div()
.h_20()
.flex()
.items_center()
.justify_center()
.bg(surface)
.rounded_md()
.child(
div()
.px_4()
.py_2()
.bg(accent)
.rounded_md()
.text_xs()
.text_color(text)
.child("Perfectly Centered"),
),
)
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_xs()
.text_color(text_muted)
.child("Centering: items_center + justify_center"),
)
.child(
div()
.h_20()
.flex()
.items_center()
.justify_center()
.bg(surface)
.rounded_md()
.child(
div()
.px_4()
.py_2()
.bg(accent)
.rounded_md()
.text_xs()
.text_color(text)
.child("Perfectly Centered"),
),
)
}
fn stack_pattern(colors: &Colors) -> impl IntoElement {
let text_muted = colors.disabled;
let surface = colors.container;
let text_muted = colors.disabled;
let surface = colors.container;
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_xs()
.text_color(text_muted)
.child("Stack: Overlapping with absolute positioning"),
)
.child(
div()
.h_20()
.relative()
.bg(surface)
.rounded_md()
.child(
div()
.absolute()
.top_2()
.left_2()
.size_10()
.bg(gpui::red().opacity(0.7))
.rounded_md(),
)
.child(
div()
.absolute()
.top_4()
.left_4()
.size_10()
.bg(gpui::green().opacity(0.7))
.rounded_md(),
)
.child(
div()
.absolute()
.top_6()
.left_6()
.size_10()
.bg(gpui::blue().opacity(0.7))
.rounded_md(),
),
)
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_xs()
.text_color(text_muted)
.child("Stack: Overlapping with absolute positioning"),
)
.child(
div()
.h_20()
.relative()
.bg(surface)
.rounded_md()
.child(
div()
.absolute()
.top_2()
.left_2()
.size_10()
.bg(gpui::red().opacity(0.7))
.rounded_md(),
)
.child(
div()
.absolute()
.top_4()
.left_4()
.size_10()
.bg(gpui::green().opacity(0.7))
.rounded_md(),
)
.child(
div()
.absolute()
.top_6()
.left_6()
.size_10()
.bg(gpui::blue().opacity(0.7))
.rounded_md(),
),
)
}
// Main Application View
@@ -392,109 +392,109 @@ fn stack_pattern(colors: &Colors) -> impl IntoElement {
struct LayoutExample;
impl Render for LayoutExample {
fn render(&mut self, window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
fn render(&mut self, window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
div()
.id("main")
.size_full()
.p_4()
.bg(colors.background)
.overflow_scroll()
.child(
div()
.flex()
.flex_col()
.gap_4()
.max_w(px(600.))
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(
div()
.text_xl()
.font_weight(gpui::FontWeight::BOLD)
.text_color(colors.text)
.child("Layout Patterns"),
)
.child(
div()
.text_sm()
.text_color(colors.disabled)
.child("Flexbox, Grid, and common layout patterns in GPUI"),
),
)
.child(section(
&colors,
"Flexbox: Row",
flexbox_row_example(&colors),
))
.child(section(
&colors,
"Flexbox: Column",
flexbox_column_example(&colors),
))
.child(section(
&colors,
"Flexbox: Justify Content",
flexbox_justify_example(&colors),
))
.child(section(
&colors,
"Flexbox: Grow/Shrink",
flexbox_grow_example(&colors),
))
.child(section(&colors, "Grid: Basic", grid_basic_example(&colors)))
.child(section(&colors, "Grid: Spans", grid_span_example(&colors)))
.child(section(
&colors,
"Pattern: App Shell",
app_shell_pattern(&colors),
))
.child(section(
&colors,
"Pattern: Centering",
centered_pattern(&colors),
))
.child(section(&colors, "Pattern: Stack", stack_pattern(&colors))),
)
}
div()
.id("main")
.size_full()
.p_4()
.bg(colors.background)
.overflow_scroll()
.child(
div()
.flex()
.flex_col()
.gap_4()
.max_w(px(600.))
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(
div()
.text_xl()
.font_weight(gpui::FontWeight::BOLD)
.text_color(colors.text)
.child("Layout Patterns"),
)
.child(
div()
.text_sm()
.text_color(colors.disabled)
.child("Flexbox, Grid, and common layout patterns in GPUI"),
),
)
.child(section(
&colors,
"Flexbox: Row",
flexbox_row_example(&colors),
))
.child(section(
&colors,
"Flexbox: Column",
flexbox_column_example(&colors),
))
.child(section(
&colors,
"Flexbox: Justify Content",
flexbox_justify_example(&colors),
))
.child(section(
&colors,
"Flexbox: Grow/Shrink",
flexbox_grow_example(&colors),
))
.child(section(&colors, "Grid: Basic", grid_basic_example(&colors)))
.child(section(&colors, "Grid: Spans", grid_span_example(&colors)))
.child(section(
&colors,
"Pattern: App Shell",
app_shell_pattern(&colors),
))
.child(section(
&colors,
"Pattern: Centering",
centered_pattern(&colors),
))
.child(section(&colors, "Pattern: Stack", stack_pattern(&colors))),
)
}
}
fn section(colors: &Colors, title: &'static str, content: impl IntoElement) -> impl IntoElement {
let surface: Hsla = colors.container.into();
let surface: Hsla = colors.container.into();
div()
.flex()
.flex_col()
.gap_2()
.p_3()
.bg(surface.opacity(0.5))
.rounded_lg()
.child(
div()
.text_sm()
.font_weight(gpui::FontWeight::SEMIBOLD)
.text_color(colors.text)
.child(title),
)
.child(content)
div()
.flex()
.flex_col()
.gap_2()
.p_3()
.bg(surface.opacity(0.5))
.rounded_lg()
.child(
div()
.text_sm()
.font_weight(gpui::FontWeight::SEMIBOLD)
.text_color(colors.text)
.child(title),
)
.child(content)
}
fn main() {
gpui_platform::application().run(|cx| {
let bounds = Bounds::centered(None, size(px(650.), px(700.)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|_, cx| cx.new(|_| LayoutExample),
)
.expect("Failed to open window");
gpui_platform::application().run(|cx| {
let bounds = Bounds::centered(None, size(px(650.), px(700.)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|_, cx| cx.new(|_| LayoutExample),
)
.expect("Failed to open window");
init_example(cx, "Layout");
});
init_example(cx, "Layout");
});
}
+198 -198
View File
@@ -13,13 +13,13 @@
// The modules under demo are skeletons whose bodies are `todo!()` by design.
#![allow(clippy::todo)]
use gpui::{
App, Bounds, Context, Entity, Hsla, Pixels, Point, Render, SharedString, Window, WindowBounds,
WindowOptions, div, point, prelude::*, px, size,
};
use gpui::node_graph::{
EdgeData, EdgeId, NodeData, NodeGraphDataSource, NodeGraphEvent, NodeGraphView, NodeId,
PortData, PortDataType, PortId, PortKind,
EdgeData, EdgeId, NodeData, NodeGraphDataSource, NodeGraphEvent, NodeGraphView, NodeId,
PortData, PortDataType, PortId, PortKind,
};
use gpui::{
App, Bounds, Context, Entity, Hsla, Pixels, Point, Render, SharedString, Window, WindowBounds,
WindowOptions, div, point, prelude::*, px, size,
};
// ---------------------------------------------------------------------------
@@ -28,198 +28,198 @@ use gpui::node_graph::{
#[derive(Clone)]
struct MockPort {
id: PortId,
kind: PortKind,
label: &'static str,
data_type: PortDataType,
connected: bool,
id: PortId,
kind: PortKind,
label: &'static str,
data_type: PortDataType,
connected: bool,
}
impl PortData for MockPort {
fn id(&self) -> PortId {
self.id
}
fn kind(&self) -> PortKind {
self.kind
}
fn label(&self) -> SharedString {
self.label.into()
}
fn data_type(&self) -> PortDataType {
self.data_type.clone()
}
fn is_connected(&self) -> bool {
self.connected
}
fn id(&self) -> PortId {
self.id
}
fn kind(&self) -> PortKind {
self.kind
}
fn label(&self) -> SharedString {
self.label.into()
}
fn data_type(&self) -> PortDataType {
self.data_type.clone()
}
fn is_connected(&self) -> bool {
self.connected
}
}
#[derive(Clone)]
struct MockNode {
id: NodeId,
title: &'static str,
position: Point<Pixels>,
inputs: Vec<MockPort>,
outputs: Vec<MockPort>,
header_color: Option<Hsla>,
id: NodeId,
title: &'static str,
position: Point<Pixels>,
inputs: Vec<MockPort>,
outputs: Vec<MockPort>,
header_color: Option<Hsla>,
}
impl NodeData for MockNode {
type Port = MockPort;
type Port = MockPort;
fn id(&self) -> NodeId {
self.id
}
fn title(&self) -> SharedString {
self.title.into()
}
fn position(&self) -> Point<Pixels> {
self.position
}
fn inputs(&self) -> Vec<MockPort> {
self.inputs.clone()
}
fn outputs(&self) -> Vec<MockPort> {
self.outputs.clone()
}
fn header_color(&self) -> Option<Hsla> {
self.header_color
}
fn is_collapsed(&self) -> bool {
false
}
fn is_enabled(&self) -> bool {
true
}
fn id(&self) -> NodeId {
self.id
}
fn title(&self) -> SharedString {
self.title.into()
}
fn position(&self) -> Point<Pixels> {
self.position
}
fn inputs(&self) -> Vec<MockPort> {
self.inputs.clone()
}
fn outputs(&self) -> Vec<MockPort> {
self.outputs.clone()
}
fn header_color(&self) -> Option<Hsla> {
self.header_color
}
fn is_collapsed(&self) -> bool {
false
}
fn is_enabled(&self) -> bool {
true
}
}
#[derive(Clone)]
struct MockEdge {
id: EdgeId,
from_node: NodeId,
from_port: PortId,
to_node: NodeId,
to_port: PortId,
id: EdgeId,
from_node: NodeId,
from_port: PortId,
to_node: NodeId,
to_port: PortId,
}
impl EdgeData for MockEdge {
fn id(&self) -> EdgeId {
self.id
}
fn from_node(&self) -> NodeId {
self.from_node
}
fn from_port(&self) -> PortId {
self.from_port
}
fn to_node(&self) -> NodeId {
self.to_node
}
fn to_port(&self) -> PortId {
self.to_port
}
fn id(&self) -> EdgeId {
self.id
}
fn from_node(&self) -> NodeId {
self.from_node
}
fn from_port(&self) -> PortId {
self.from_port
}
fn to_node(&self) -> NodeId {
self.to_node
}
fn to_port(&self) -> PortId {
self.to_port
}
}
/// The mock pipeline: media → transform → output.
struct MockGraph {
nodes: Vec<MockNode>,
edges: Vec<MockEdge>,
nodes: Vec<MockNode>,
edges: Vec<MockEdge>,
}
impl MockGraph {
fn new() -> Self {
let video = PortDataType::new("video", Hsla::blue());
// Port id packing: node id in the high bits, port index low. Inputs
// and outputs share one index space per node.
let port = |node: u64, index: u64| PortId((node << 32) | index);
fn new() -> Self {
let video = PortDataType::new("video", Hsla::blue());
// Port id packing: node id in the high bits, port index low. Inputs
// and outputs share one index space per node.
let port = |node: u64, index: u64| PortId((node << 32) | index);
let media = MockNode {
id: NodeId(1),
title: "Media",
position: point(px(40.), px(80.)),
inputs: vec![],
outputs: vec![MockPort {
id: port(1, 0),
kind: PortKind::Output,
label: "video",
data_type: video.clone(),
connected: true,
}],
header_color: Some(Hsla::green()),
};
let transform = MockNode {
id: NodeId(2),
title: "Transform",
position: point(px(320.), px(140.)),
inputs: vec![MockPort {
id: port(2, 0),
kind: PortKind::Input,
label: "in",
data_type: video.clone(),
connected: true,
}],
outputs: vec![MockPort {
id: port(2, 1),
kind: PortKind::Output,
label: "out",
data_type: video.clone(),
connected: true,
}],
header_color: None,
};
let output = MockNode {
id: NodeId(3),
title: "Output",
position: point(px(600.), px(200.)),
inputs: vec![MockPort {
id: port(3, 0),
kind: PortKind::Input,
label: "in",
data_type: video,
connected: true,
}],
outputs: vec![],
header_color: Some(Hsla::red()),
};
let media = MockNode {
id: NodeId(1),
title: "Media",
position: point(px(40.), px(80.)),
inputs: vec![],
outputs: vec![MockPort {
id: port(1, 0),
kind: PortKind::Output,
label: "video",
data_type: video.clone(),
connected: true,
}],
header_color: Some(Hsla::green()),
};
let transform = MockNode {
id: NodeId(2),
title: "Transform",
position: point(px(320.), px(140.)),
inputs: vec![MockPort {
id: port(2, 0),
kind: PortKind::Input,
label: "in",
data_type: video.clone(),
connected: true,
}],
outputs: vec![MockPort {
id: port(2, 1),
kind: PortKind::Output,
label: "out",
data_type: video.clone(),
connected: true,
}],
header_color: None,
};
let output = MockNode {
id: NodeId(3),
title: "Output",
position: point(px(600.), px(200.)),
inputs: vec![MockPort {
id: port(3, 0),
kind: PortKind::Input,
label: "in",
data_type: video,
connected: true,
}],
outputs: vec![],
header_color: Some(Hsla::red()),
};
let edges = vec![
MockEdge {
id: EdgeId(1),
from_node: NodeId(1),
from_port: port(1, 0),
to_node: NodeId(2),
to_port: port(2, 0),
},
MockEdge {
id: EdgeId(2),
from_node: NodeId(2),
from_port: port(2, 1),
to_node: NodeId(3),
to_port: port(3, 0),
},
];
let edges = vec![
MockEdge {
id: EdgeId(1),
from_node: NodeId(1),
from_port: port(1, 0),
to_node: NodeId(2),
to_port: port(2, 0),
},
MockEdge {
id: EdgeId(2),
from_node: NodeId(2),
from_port: port(2, 1),
to_node: NodeId(3),
to_port: port(3, 0),
},
];
Self {
nodes: vec![media, transform, output],
edges,
}
}
Self {
nodes: vec![media, transform, output],
edges,
}
}
}
impl NodeGraphDataSource for MockGraph {
type Node = MockNode;
type Edge = MockEdge;
type Node = MockNode;
type Edge = MockEdge;
fn nodes(&self) -> Vec<MockNode> {
self.nodes.clone()
}
fn edges(&self) -> Vec<MockEdge> {
self.edges.clone()
}
fn can_connect(&self, _from: PortId, _to: PortId) -> bool {
// A real app checks type compatibility, cycles and cardinality here.
// The mock allows everything between distinct ports.
true
}
fn nodes(&self) -> Vec<MockNode> {
self.nodes.clone()
}
fn edges(&self) -> Vec<MockEdge> {
self.edges.clone()
}
fn can_connect(&self, _from: PortId, _to: PortId) -> bool {
// A real app checks type compatibility, cycles and cardinality here.
// The mock allows everything between distinct ports.
true
}
}
// ---------------------------------------------------------------------------
@@ -227,47 +227,47 @@ impl NodeGraphDataSource for MockGraph {
// ---------------------------------------------------------------------------
struct NodeGraphExample {
graph: Entity<MockGraph>,
view: Entity<NodeGraphView<MockGraph>>,
graph: Entity<MockGraph>,
view: Entity<NodeGraphView<MockGraph>>,
}
impl NodeGraphExample {
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
let graph = cx.new(|_cx| MockGraph::new());
let view = cx.new(|cx| NodeGraphView::new(graph.clone(), window, cx));
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
let graph = cx.new(|_cx| MockGraph::new());
let view = cx.new(|cx| NodeGraphView::new(graph.clone(), window, cx));
// In Oak, each event becomes an engine operation wrapped in an undo
// command; here we just log the request.
cx.subscribe(&view, |_this, _view, event: &NodeGraphEvent, cx| {
println!("[node_graph] edit request: {event:?}");
// After applying a request to the model, notify so the view
// re-reads it, e.g.: `graph.update(cx, |_, cx| cx.notify())`.
let _ = cx;
})
.detach();
// In Oak, each event becomes an engine operation wrapped in an undo
// command; here we just log the request.
cx.subscribe(&view, |_this, _view, event: &NodeGraphEvent, cx| {
println!("[node_graph] edit request: {event:?}");
// After applying a request to the model, notify so the view
// re-reads it, e.g.: `graph.update(cx, |_, cx| cx.notify())`.
let _ = cx;
})
.detach();
Self { graph, view }
}
Self { graph, view }
}
}
impl Render for NodeGraphExample {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let _ = &self.graph;
div().size_full().child(self.view.clone())
}
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let _ = &self.graph;
div().size_full().child(self.view.clone())
}
}
fn main() {
gpui_platform::application().run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(900.), px(600.)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|window, cx| cx.new(|cx| NodeGraphExample::new(window, cx)),
)
.expect("failed to open window");
cx.activate(true);
});
gpui_platform::application().run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(900.), px(600.)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|window, cx| cx.new(|cx| NodeGraphExample::new(window, cx)),
)
.expect("failed to open window");
cx.activate(true);
});
}
+429 -429
View File
@@ -8,8 +8,8 @@
use gpui::colors::Colors;
use gpui::{
App, Bounds, Context, FocusHandle, Hsla, KeyBinding, Menu, MenuItem, Render, Rgba, Window,
WindowBounds, WindowOptions, actions, div, prelude::*, px, rgb, size,
App, Bounds, Context, FocusHandle, Hsla, KeyBinding, Menu, MenuItem, Render, Rgba, Window,
WindowBounds, WindowOptions, actions, div, prelude::*, px, rgb, size,
};
actions!(styling_example, [Quit, Tab, TabPrev]);
@@ -17,497 +17,497 @@ actions!(styling_example, [Quit, Tab, TabPrev]);
// Interactive States Example
fn interactive_button(
id: impl Into<gpui::ElementId>,
label: &'static str,
colors: &Colors,
id: impl Into<gpui::ElementId>,
label: &'static str,
colors: &Colors,
) -> impl IntoElement {
let accent = colors.selected;
let accent_hover = colors.selected;
let accent_active = colors.selected;
let text = colors.selected_text;
let accent = colors.selected;
let accent_hover = colors.selected;
let accent_active = colors.selected;
let text = colors.selected_text;
div()
.id(id)
.px_4()
.py_2()
.rounded_md()
.cursor_pointer()
.bg(accent)
.text_color(text)
.text_sm()
.hover(move |style| style.bg(accent_hover))
.active(move |style| style.bg(accent_active))
.child(label)
div()
.id(id)
.px_4()
.py_2()
.rounded_md()
.cursor_pointer()
.bg(accent)
.text_color(text)
.text_sm()
.hover(move |style| style.bg(accent_hover))
.active(move |style| style.bg(accent_active))
.child(label)
}
fn focus_button(
id: impl Into<gpui::ElementId>,
label: &'static str,
focus_handle: &FocusHandle,
colors: &Colors,
id: impl Into<gpui::ElementId>,
label: &'static str,
focus_handle: &FocusHandle,
colors: &Colors,
) -> impl IntoElement {
let surface = colors.container;
let surface_hover = colors.selected;
let text = colors.text;
let accent = colors.selected;
let focus_ring: Rgba = rgb(0x60a5fa);
let surface = colors.container;
let surface_hover = colors.selected;
let text = colors.text;
let accent = colors.selected;
let focus_ring: Rgba = rgb(0x60a5fa);
div()
.id(id)
.track_focus(focus_handle)
.px_4()
.py_2()
.rounded_md()
.cursor_pointer()
.bg(surface)
.text_color(text)
.text_sm()
.border_2()
.border_color(gpui::transparent_black())
.hover(move |style| style.bg(surface_hover))
.focus(move |style| style.border_color(accent))
.focus_visible(move |style| style.border_color(focus_ring).shadow_sm())
.child(label)
div()
.id(id)
.track_focus(focus_handle)
.px_4()
.py_2()
.rounded_md()
.cursor_pointer()
.bg(surface)
.text_color(text)
.text_sm()
.border_2()
.border_color(gpui::transparent_black())
.hover(move |style| style.bg(surface_hover))
.focus(move |style| style.border_color(accent))
.focus_visible(move |style| style.border_color(focus_ring).shadow_sm())
.child(label)
}
fn interactive_states_section(colors: &Colors) -> impl IntoElement {
div()
.flex()
.flex_col()
.gap_3()
.child(
div()
.text_xs()
.text_color(colors.disabled)
.child("hover() / active() - Mouse interaction states"),
)
.child(
div()
.flex()
.gap_2()
.child(interactive_button("btn-1", "Hover me", colors))
.child(interactive_button("btn-2", "Click me", colors)),
)
div()
.flex()
.flex_col()
.gap_3()
.child(
div()
.text_xs()
.text_color(colors.disabled)
.child("hover() / active() - Mouse interaction states"),
)
.child(
div()
.flex()
.gap_2()
.child(interactive_button("btn-1", "Hover me", colors))
.child(interactive_button("btn-2", "Click me", colors)),
)
}
// Conditional Styling Example
fn status_badge(status: &'static str, variant: StatusVariant, colors: &Colors) -> impl IntoElement {
let (bg, text): (Rgba, Rgba) = match variant {
StatusVariant::Success => (rgb(0x388e3c), colors.selected_text),
StatusVariant::Warning => (rgb(0xf9a825), rgb(0x000000)),
StatusVariant::Error => (rgb(0xd32f2f), colors.selected_text),
StatusVariant::Neutral => (colors.container, colors.text),
};
let (bg, text): (Rgba, Rgba) = match variant {
StatusVariant::Success => (rgb(0x388e3c), colors.selected_text),
StatusVariant::Warning => (rgb(0xf9a825), rgb(0x000000)),
StatusVariant::Error => (rgb(0xd32f2f), colors.selected_text),
StatusVariant::Neutral => (colors.container, colors.text),
};
div()
.px_2()
.py_0p5()
.rounded_full()
.text_xs()
.bg(bg)
.text_color(text)
.child(status)
div()
.px_2()
.py_0p5()
.rounded_full()
.text_xs()
.bg(bg)
.text_color(text)
.child(status)
}
#[derive(Clone, Copy)]
enum StatusVariant {
Success,
Warning,
Error,
Neutral,
Success,
Warning,
Error,
Neutral,
}
fn list_item(
id: impl Into<gpui::ElementId>,
label: &'static str,
is_selected: bool,
is_disabled: bool,
colors: &Colors,
id: impl Into<gpui::ElementId>,
label: &'static str,
is_selected: bool,
is_disabled: bool,
colors: &Colors,
) -> impl IntoElement {
let surface = colors.container;
let surface_hover = colors.selected;
let text = colors.text;
let text_muted = colors.disabled;
let accent = colors.selected;
let surface = colors.container;
let surface_hover = colors.selected;
let text = colors.text;
let text_muted = colors.disabled;
let accent = colors.selected;
div()
.id(id)
.px_3()
.py_2()
.rounded_md()
.text_sm()
.cursor_pointer()
.border_1()
.border_color(gpui::transparent_black())
.when(is_disabled, |el| {
el.opacity(0.5)
.cursor_not_allowed()
.bg(surface)
.text_color(text_muted)
})
.when(!is_disabled && is_selected, move |el| {
let accent_bg: Hsla = accent.into();
el.bg(accent_bg.opacity(0.2))
.border_color(accent)
.text_color(text)
})
.when(!is_disabled && !is_selected, move |el| {
el.bg(surface)
.text_color(text)
.hover(move |style| style.bg(surface_hover))
})
.child(label)
div()
.id(id)
.px_3()
.py_2()
.rounded_md()
.text_sm()
.cursor_pointer()
.border_1()
.border_color(gpui::transparent_black())
.when(is_disabled, |el| {
el.opacity(0.5)
.cursor_not_allowed()
.bg(surface)
.text_color(text_muted)
})
.when(!is_disabled && is_selected, move |el| {
let accent_bg: Hsla = accent.into();
el.bg(accent_bg.opacity(0.2))
.border_color(accent)
.text_color(text)
})
.when(!is_disabled && !is_selected, move |el| {
el.bg(surface)
.text_color(text)
.hover(move |style| style.bg(surface_hover))
})
.child(label)
}
fn conditional_section(colors: &Colors) -> impl IntoElement {
div()
.flex()
.flex_col()
.gap_3()
.child(
div()
.text_xs()
.text_color(colors.disabled)
.child("when() - Apply styles conditionally"),
)
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(list_item("item-1", "Normal item", false, false, colors))
.child(list_item("item-2", "Selected item", true, false, colors))
.child(list_item("item-3", "Disabled item", false, true, colors)),
)
.child(
div()
.text_xs()
.text_color(colors.disabled)
.mt_2()
.child("Status badges with variant-based styling"),
)
.child(
div()
.flex()
.gap_2()
.child(status_badge("Success", StatusVariant::Success, colors))
.child(status_badge("Warning", StatusVariant::Warning, colors))
.child(status_badge("Error", StatusVariant::Error, colors))
.child(status_badge("Neutral", StatusVariant::Neutral, colors)),
)
div()
.flex()
.flex_col()
.gap_3()
.child(
div()
.text_xs()
.text_color(colors.disabled)
.child("when() - Apply styles conditionally"),
)
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(list_item("item-1", "Normal item", false, false, colors))
.child(list_item("item-2", "Selected item", true, false, colors))
.child(list_item("item-3", "Disabled item", false, true, colors)),
)
.child(
div()
.text_xs()
.text_color(colors.disabled)
.mt_2()
.child("Status badges with variant-based styling"),
)
.child(
div()
.flex()
.gap_2()
.child(status_badge("Success", StatusVariant::Success, colors))
.child(status_badge("Warning", StatusVariant::Warning, colors))
.child(status_badge("Error", StatusVariant::Error, colors))
.child(status_badge("Neutral", StatusVariant::Neutral, colors)),
)
}
// Group Hover Example
fn card_with_group_hover(
id: impl Into<gpui::ElementId>,
title: &'static str,
description: &'static str,
colors: &Colors,
id: impl Into<gpui::ElementId>,
title: &'static str,
description: &'static str,
colors: &Colors,
) -> impl IntoElement {
let surface = colors.container;
let border = colors.border;
let accent = colors.selected;
let text = colors.text;
let text_muted = colors.disabled;
let surface = colors.container;
let border = colors.border;
let accent = colors.selected;
let text = colors.text;
let text_muted = colors.disabled;
div()
.id(id)
.group("card")
.p_4()
.rounded_lg()
.bg(surface)
.border_1()
.border_color(border)
.cursor_pointer()
.hover(move |style| style.border_color(accent))
.child(
div()
.flex()
.justify_between()
.items_center()
.child(
div()
.text_sm()
.font_weight(gpui::FontWeight::SEMIBOLD)
.text_color(text)
.child(title),
)
.child(
div()
.text_xs()
.text_color(text_muted)
.opacity(0.)
.group_hover("card", |style| style.opacity(1.))
.child("→"),
),
)
.child(
div()
.mt_1()
.text_xs()
.text_color(text_muted)
.child(description),
)
div()
.id(id)
.group("card")
.p_4()
.rounded_lg()
.bg(surface)
.border_1()
.border_color(border)
.cursor_pointer()
.hover(move |style| style.border_color(accent))
.child(
div()
.flex()
.justify_between()
.items_center()
.child(
div()
.text_sm()
.font_weight(gpui::FontWeight::SEMIBOLD)
.text_color(text)
.child(title),
)
.child(
div()
.text_xs()
.text_color(text_muted)
.opacity(0.)
.group_hover("card", |style| style.opacity(1.))
.child("→"),
),
)
.child(
div()
.mt_1()
.text_xs()
.text_color(text_muted)
.child(description),
)
}
fn group_hover_section(colors: &Colors) -> impl IntoElement {
div()
.flex()
.flex_col()
.gap_3()
.child(
div()
.text_xs()
.text_color(colors.disabled)
.child("group() / group_hover() - Parent hover affects children"),
)
.child(
div()
.flex()
.flex_col()
.gap_2()
.child(card_with_group_hover(
"card-1",
"Documents",
"View and manage your documents",
colors,
))
.child(card_with_group_hover(
"card-2",
"Settings",
"Configure application settings",
colors,
)),
)
div()
.flex()
.flex_col()
.gap_3()
.child(
div()
.text_xs()
.text_color(colors.disabled)
.child("group() / group_hover() - Parent hover affects children"),
)
.child(
div()
.flex()
.flex_col()
.gap_2()
.child(card_with_group_hover(
"card-1",
"Documents",
"View and manage your documents",
colors,
))
.child(card_with_group_hover(
"card-2",
"Settings",
"Configure application settings",
colors,
)),
)
}
// Main Application View
struct StylingExample {
focus_handle: FocusHandle,
buttons: Vec<FocusHandle>,
focus_handle: FocusHandle,
buttons: Vec<FocusHandle>,
}
impl StylingExample {
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
let focus_handle = cx.focus_handle();
window.focus(&focus_handle, cx);
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
let focus_handle = cx.focus_handle();
window.focus(&focus_handle, cx);
let buttons = vec![
cx.focus_handle().tab_index(1).tab_stop(true),
cx.focus_handle().tab_index(2).tab_stop(true),
cx.focus_handle().tab_index(3).tab_stop(true),
];
let buttons = vec![
cx.focus_handle().tab_index(1).tab_stop(true),
cx.focus_handle().tab_index(2).tab_stop(true),
cx.focus_handle().tab_index(3).tab_stop(true),
];
Self {
focus_handle,
buttons,
}
}
Self {
focus_handle,
buttons,
}
}
fn on_tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
window.focus_next(cx);
}
fn on_tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
window.focus_next(cx);
}
fn on_tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
window.focus_prev(cx);
}
fn on_tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
window.focus_prev(cx);
}
}
impl Render for StylingExample {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let colors = Colors::for_appearance(window);
div()
.id("app")
.track_focus(&self.focus_handle)
.on_action(cx.listener(Self::on_tab))
.on_action(cx.listener(Self::on_tab_prev))
.size_full()
.p_6()
.bg(colors.background)
.overflow_scroll()
.child(
div()
.flex()
.flex_col()
.gap_6()
.max_w(px(500.))
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(
div()
.text_xl()
.font_weight(gpui::FontWeight::BOLD)
.text_color(colors.text)
.child("Styling Patterns"),
)
.child(
div()
.text_sm()
.text_color(colors.disabled)
.child("Interactive states, conditional styling, and theming"),
),
)
.child(section(
&colors,
"Interactive States",
interactive_states_section(&colors),
))
.child(section(
&colors,
"Focus States (Tab to navigate)",
div()
.flex()
.flex_col()
.gap_3()
.child(
div()
.text_xs()
.text_color(colors.disabled)
.child("focus() / focus_visible() - Keyboard navigation"),
)
.child(
div()
.flex()
.gap_2()
.child(focus_button(
"focus-1",
"Button 1",
&self.buttons[0],
&colors,
))
.child(focus_button(
"focus-2",
"Button 2",
&self.buttons[1],
&colors,
))
.child(focus_button(
"focus-3",
"Button 3",
&self.buttons[2],
&colors,
)),
),
))
.child(section(
&colors,
"Conditional Styling",
conditional_section(&colors),
))
.child(section(
&colors,
"Group Hover",
group_hover_section(&colors),
))
.child(section(
&colors,
"Default Colors",
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_xs()
.text_color(colors.disabled)
.child("Using Colors::for_appearance() for consistent theming"),
)
.child(
div()
.flex()
.flex_wrap()
.gap_2()
.child(color_swatch(&colors, "background", colors.background))
.child(color_swatch(&colors, "container", colors.container))
.child(color_swatch(&colors, "selected", colors.selected))
.child(color_swatch(&colors, "success", rgb(0x388e3c)))
.child(color_swatch(&colors, "warning", rgb(0xf9a825)))
.child(color_swatch(&colors, "error", rgb(0xd32f2f)))
.child(color_swatch(&colors, "border", colors.border)),
),
)),
)
}
div()
.id("app")
.track_focus(&self.focus_handle)
.on_action(cx.listener(Self::on_tab))
.on_action(cx.listener(Self::on_tab_prev))
.size_full()
.p_6()
.bg(colors.background)
.overflow_scroll()
.child(
div()
.flex()
.flex_col()
.gap_6()
.max_w(px(500.))
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(
div()
.text_xl()
.font_weight(gpui::FontWeight::BOLD)
.text_color(colors.text)
.child("Styling Patterns"),
)
.child(
div()
.text_sm()
.text_color(colors.disabled)
.child("Interactive states, conditional styling, and theming"),
),
)
.child(section(
&colors,
"Interactive States",
interactive_states_section(&colors),
))
.child(section(
&colors,
"Focus States (Tab to navigate)",
div()
.flex()
.flex_col()
.gap_3()
.child(
div()
.text_xs()
.text_color(colors.disabled)
.child("focus() / focus_visible() - Keyboard navigation"),
)
.child(
div()
.flex()
.gap_2()
.child(focus_button(
"focus-1",
"Button 1",
&self.buttons[0],
&colors,
))
.child(focus_button(
"focus-2",
"Button 2",
&self.buttons[1],
&colors,
))
.child(focus_button(
"focus-3",
"Button 3",
&self.buttons[2],
&colors,
)),
),
))
.child(section(
&colors,
"Conditional Styling",
conditional_section(&colors),
))
.child(section(
&colors,
"Group Hover",
group_hover_section(&colors),
))
.child(section(
&colors,
"Default Colors",
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.text_xs()
.text_color(colors.disabled)
.child("Using Colors::for_appearance() for consistent theming"),
)
.child(
div()
.flex()
.flex_wrap()
.gap_2()
.child(color_swatch(&colors, "background", colors.background))
.child(color_swatch(&colors, "container", colors.container))
.child(color_swatch(&colors, "selected", colors.selected))
.child(color_swatch(&colors, "success", rgb(0x388e3c)))
.child(color_swatch(&colors, "warning", rgb(0xf9a825)))
.child(color_swatch(&colors, "error", rgb(0xd32f2f)))
.child(color_swatch(&colors, "border", colors.border)),
),
)),
)
}
}
fn section(colors: &Colors, title: &'static str, content: impl IntoElement) -> impl IntoElement {
let surface: Hsla = colors.container.into();
let border: Hsla = colors.border.into();
let surface: Hsla = colors.container.into();
let border: Hsla = colors.border.into();
div()
.flex()
.flex_col()
.gap_3()
.p_4()
.bg(surface.opacity(0.3))
.rounded_lg()
.border_1()
.border_color(border.opacity(0.5))
.child(
div()
.text_sm()
.font_weight(gpui::FontWeight::SEMIBOLD)
.text_color(colors.text)
.child(title),
)
.child(content)
div()
.flex()
.flex_col()
.gap_3()
.p_4()
.bg(surface.opacity(0.3))
.rounded_lg()
.border_1()
.border_color(border.opacity(0.5))
.child(
div()
.text_sm()
.font_weight(gpui::FontWeight::SEMIBOLD)
.text_color(colors.text)
.child(title),
)
.child(content)
}
fn color_swatch(colors: &Colors, name: &'static str, color: Rgba) -> impl IntoElement {
let text_muted = colors.disabled;
let text_muted = colors.disabled;
div()
.flex()
.flex_col()
.items_center()
.gap_1()
.child(
div()
.size_8()
.rounded_md()
.bg(color)
.border_1()
.border_color(gpui::white().opacity(0.2)),
)
.child(div().text_xs().text_color(text_muted).child(name))
div()
.flex()
.flex_col()
.items_center()
.gap_1()
.child(
div()
.size_8()
.rounded_md()
.bg(color)
.border_1()
.border_color(gpui::white().opacity(0.2)),
)
.child(div().text_xs().text_color(text_muted).child(name))
}
fn main() {
gpui_platform::application().run(|cx: &mut App| {
cx.activate(true);
cx.on_action(|_: &Quit, cx| cx.quit());
cx.bind_keys([
KeyBinding::new("cmd-q", Quit, None),
KeyBinding::new("tab", Tab, None),
KeyBinding::new("shift-tab", TabPrev, None),
]);
cx.set_menus(vec![Menu {
name: "Styling".into(),
items: vec![MenuItem::action("Quit", Quit)],
disabled: false,
}]);
cx.on_window_closed(|cx, _window_id| {
if cx.windows().is_empty() {
cx.quit();
}
})
.detach();
gpui_platform::application().run(|cx: &mut App| {
cx.activate(true);
cx.on_action(|_: &Quit, cx| cx.quit());
cx.bind_keys([
KeyBinding::new("cmd-q", Quit, None),
KeyBinding::new("tab", Tab, None),
KeyBinding::new("shift-tab", TabPrev, None),
]);
cx.set_menus(vec![Menu {
name: "Styling".into(),
items: vec![MenuItem::action("Quit", Quit)],
disabled: false,
}]);
cx.on_window_closed(|cx, _window_id| {
if cx.windows().is_empty() {
cx.quit();
}
})
.detach();
let bounds = Bounds::centered(None, size(px(550.), px(800.)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|window, cx| cx.new(|cx| StylingExample::new(window, cx)),
)
.expect("Failed to open window");
});
let bounds = Bounds::centered(None, size(px(550.), px(800.)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|window, cx| cx.new(|cx| StylingExample::new(window, cx)),
)
.expect("Failed to open window");
});
}
File diff suppressed because it is too large Load Diff
+136 -136
View File
@@ -15,13 +15,13 @@
// The modules under demo are skeletons whose bodies are `todo!()` by design.
#![allow(clippy::todo)]
use gpui::{
App, Bounds, Context, Entity, Pixels, Render, SharedString, Window, WindowBounds,
WindowOptions, div, prelude::*, px, size,
};
use gpui::timeline::{
ClipData, ClipId, Frame, FrameRange, FrameRate, TimelineDataSource, TimelineEvent,
TimelineView, TrackData, TrackKind,
ClipData, ClipId, Frame, FrameRange, FrameRate, TimelineDataSource, TimelineEvent,
TimelineView, TrackData, TrackKind,
};
use gpui::{
App, Bounds, Context, Entity, Pixels, Render, SharedString, Window, WindowBounds,
WindowOptions, div, prelude::*, px, size,
};
#[path = "../shared/prelude.rs"]
@@ -30,178 +30,178 @@ mod example_prelude;
// --- mock model ------------------------------------------------------------
struct MockClip {
id: ClipId,
range: FrameRange,
media_in: Frame,
label: SharedString,
id: ClipId,
range: FrameRange,
media_in: Frame,
label: SharedString,
}
impl ClipData for MockClip {
fn id(&self) -> ClipId {
self.id
}
fn id(&self) -> ClipId {
self.id
}
fn range(&self) -> FrameRange {
self.range
}
fn range(&self) -> FrameRange {
self.range
}
fn media_in(&self) -> Frame {
self.media_in
}
fn media_in(&self) -> Frame {
self.media_in
}
fn label(&self) -> SharedString {
self.label.clone()
}
fn label(&self) -> SharedString {
self.label.clone()
}
}
struct MockTrack {
kind: TrackKind,
name: SharedString,
height: Pixels,
clips: Vec<MockClip>,
kind: TrackKind,
name: SharedString,
height: Pixels,
clips: Vec<MockClip>,
}
impl TrackData for MockTrack {
type Clip = MockClip;
type Clip = MockClip;
fn kind(&self) -> TrackKind {
self.kind
}
fn kind(&self) -> TrackKind {
self.kind
}
fn name(&self) -> SharedString {
self.name.clone()
}
fn name(&self) -> SharedString {
self.name.clone()
}
fn height(&self) -> Pixels {
self.height
}
fn height(&self) -> Pixels {
self.height
}
fn clips(&self) -> &[Self::Clip] {
&self.clips
}
fn clips(&self) -> &[Self::Clip] {
&self.clips
}
}
struct MockSequence {
tracks: Vec<MockTrack>,
tracks: Vec<MockTrack>,
}
impl MockSequence {
fn demo() -> Self {
let clip = |id: u64, start: i64, end: i64, label: &str| MockClip {
id: ClipId(id),
range: FrameRange::new(Frame(start), Frame(end)),
media_in: Frame::ZERO,
label: label.into(),
};
MockSequence {
tracks: vec![
MockTrack {
kind: TrackKind::Video,
name: "V1".into(),
height: px(64.),
clips: vec![clip(1, 0, 240, "opening.mov"), clip(2, 240, 600, "b-roll.mp4")],
},
MockTrack {
kind: TrackKind::Video,
name: "V2".into(),
height: px(64.),
clips: vec![clip(3, 120, 300, "title.mov")],
},
MockTrack {
kind: TrackKind::Audio,
name: "A1".into(),
height: px(48.),
clips: vec![clip(4, 0, 600, "dialog.wav")],
},
MockTrack {
kind: TrackKind::Audio,
name: "A2".into(),
height: px(48.),
clips: vec![clip(5, 0, 480, "score.flac")],
},
],
}
}
fn demo() -> Self {
let clip = |id: u64, start: i64, end: i64, label: &str| MockClip {
id: ClipId(id),
range: FrameRange::new(Frame(start), Frame(end)),
media_in: Frame::ZERO,
label: label.into(),
};
MockSequence {
tracks: vec![
MockTrack {
kind: TrackKind::Video,
name: "V1".into(),
height: px(64.),
clips: vec![
clip(1, 0, 240, "opening.mov"),
clip(2, 240, 600, "b-roll.mp4"),
],
},
MockTrack {
kind: TrackKind::Video,
name: "V2".into(),
height: px(64.),
clips: vec![clip(3, 120, 300, "title.mov")],
},
MockTrack {
kind: TrackKind::Audio,
name: "A1".into(),
height: px(48.),
clips: vec![clip(4, 0, 600, "dialog.wav")],
},
MockTrack {
kind: TrackKind::Audio,
name: "A2".into(),
height: px(48.),
clips: vec![clip(5, 0, 480, "score.flac")],
},
],
}
}
}
impl TimelineDataSource for MockSequence {
type Track = MockTrack;
type Track = MockTrack;
fn frame_rate(&self) -> FrameRate {
FrameRate::NTSC_2997
}
fn frame_rate(&self) -> FrameRate {
FrameRate::NTSC_2997
}
fn sequence_length(&self) -> Frame {
Frame(600)
}
fn sequence_length(&self) -> Frame {
Frame(600)
}
fn track_count(&self) -> usize {
self.tracks.len()
}
fn track_count(&self) -> usize {
self.tracks.len()
}
fn track(&self, index: usize) -> Option<Self::Track> {
// A real host returns a lightweight snapshot; the mock simply
// reports the track's existence. Returning an owned value here is
// what the trait requires, so the mock clones its clips.
self.tracks.get(index).map(|t| MockTrack {
kind: t.kind,
name: t.name.clone(),
height: t.height,
clips: t
.clips
.iter()
.map(|c| MockClip {
id: c.id,
range: c.range,
media_in: c.media_in,
label: c.label.clone(),
})
.collect(),
})
}
fn track(&self, index: usize) -> Option<Self::Track> {
// A real host returns a lightweight snapshot; the mock simply
// reports the track's existence. Returning an owned value here is
// what the trait requires, so the mock clones its clips.
self.tracks.get(index).map(|t| MockTrack {
kind: t.kind,
name: t.name.clone(),
height: t.height,
clips: t
.clips
.iter()
.map(|c| MockClip {
id: c.id,
range: c.range,
media_in: c.media_in,
label: c.label.clone(),
})
.collect(),
})
}
}
// --- the example view ------------------------------------------------------
struct TimelineExample {
timeline: Entity<TimelineView<MockSequence>>,
timeline: Entity<TimelineView<MockSequence>>,
}
impl TimelineExample {
fn new(model: Entity<MockSequence>, window: &mut Window, cx: &mut Context<Self>) -> Self {
let timeline = cx.new(|cx| TimelineView::new(model, window, cx).zoom(2.0));
cx.subscribe(
&timeline,
|_this, _timeline, event: &TimelineEvent, _cx| {
// In Oak, each request becomes an undoable engine command
// here, followed by `model.update(cx, |_, cx| cx.notify())`.
println!("timeline edit request: {event:?}");
},
)
.detach();
TimelineExample { timeline }
}
fn new(model: Entity<MockSequence>, window: &mut Window, cx: &mut Context<Self>) -> Self {
let timeline = cx.new(|cx| TimelineView::new(model, window, cx).zoom(2.0));
cx.subscribe(&timeline, |_this, _timeline, event: &TimelineEvent, _cx| {
// In Oak, each request becomes an undoable engine command
// here, followed by `model.update(cx, |_, cx| cx.notify())`.
println!("timeline edit request: {event:?}");
})
.detach();
TimelineExample { timeline }
}
}
impl Render for TimelineExample {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().size_full().child(self.timeline.clone())
}
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().size_full().child(self.timeline.clone())
}
}
fn main() {
gpui_platform::application().run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(1000.), px(480.)), cx);
let model = cx.new(|_cx| MockSequence::demo());
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|window, cx| cx.new(|cx| TimelineExample::new(model, window, cx)),
)
.expect("Failed to open window");
gpui_platform::application().run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(1000.), px(480.)), cx);
let model = cx.new(|_cx| MockSequence::demo());
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|window, cx| cx.new(|cx| TimelineExample::new(model, window, cx)),
)
.expect("Failed to open window");
example_prelude::init_example(cx, "Timeline");
});
example_prelude::init_example(cx, "Timeline");
});
}
+70 -70
View File
@@ -8,8 +8,8 @@ mod example_prelude;
use std::time::Duration;
use gpui::{
AnyElement, App, AppContext, Bounds, Context, ElementId, Lerp, Rgba, Window, WindowBounds,
WindowOptions, actions, div, ease_in_out, prelude::*, px, rgb, size,
AnyElement, App, AppContext, Bounds, Context, ElementId, Lerp, Rgba, Window, WindowBounds,
WindowOptions, actions, div, ease_in_out, prelude::*, px, rgb, size,
};
use smallvec::SmallVec;
@@ -17,93 +17,93 @@ actions!(app, [Quit]);
#[derive(IntoElement)]
struct Button {
id: ElementId,
children: SmallVec<[AnyElement; 2]>,
id: ElementId,
children: SmallVec<[AnyElement; 2]>,
}
impl Button {
fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
children: SmallVec::new(),
}
}
fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
children: SmallVec::new(),
}
}
}
impl ParentElement for Button {
fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
self.children.extend(elements);
}
fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
self.children.extend(elements);
}
}
impl RenderOnce for Button {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
const HOVER_STRENGTH: f32 = 0.3;
let base_color: Rgba = rgb(0x663399);
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
const HOVER_STRENGTH: f32 = 0.3;
let base_color: Rgba = rgb(0x663399);
let hover_transition = window
.use_keyed_transition(
(self.id.clone(), "hover"),
cx,
Duration::from_millis(300),
|_window, _cx| 0.,
)
.with_easing(ease_in_out);
let hover_transition = window
.use_keyed_transition(
(self.id.clone(), "hover"),
cx,
Duration::from_millis(300),
|_window, _cx| 0.,
)
.with_easing(ease_in_out);
let bg_color = base_color.lerp(
&rgb(0x000),
*hover_transition.evaluate(window, cx) * HOVER_STRENGTH,
);
let bg_color = base_color.lerp(
&rgb(0x000),
*hover_transition.evaluate(window, cx) * HOVER_STRENGTH,
);
div()
.id(self.id)
.cursor_pointer()
.rounded(px(100.))
.pl(px(14.))
.pr(px(14.))
.pt(px(10.))
.pb(px(10.))
.bg(bg_color)
.text_color(rgb(0x110F15))
.children(self.children)
.on_hover(move |hover, _window, cx| {
hover_transition.update(cx, |this, cx| {
*this = *hover as u8 as f32;
cx.notify();
});
})
}
div()
.id(self.id)
.cursor_pointer()
.rounded(px(100.))
.pl(px(14.))
.pr(px(14.))
.pt(px(10.))
.pb(px(10.))
.bg(bg_color)
.text_color(rgb(0x110F15))
.children(self.children)
.on_hover(move |hover, _window, cx| {
hover_transition.update(cx, |this, cx| {
*this = *hover as u8 as f32;
cx.notify();
});
})
}
}
struct TransitionExample;
impl Render for TransitionExample {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div()
.size_full()
.flex()
.justify_center()
.items_center()
.absolute()
.bg(rgb(0x110F15))
.gap(px(20.))
.p(px(100.))
.child(Button::new("btn").child("Click me!"))
}
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div()
.size_full()
.flex()
.justify_center()
.items_center()
.absolute()
.bg(rgb(0x110F15))
.gap(px(20.))
.p(px(100.))
.child(Button::new("btn").child("Click me!"))
}
}
fn main() {
gpui_platform::application().run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(500.), px(650.)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|_, cx| cx.new(|_| TransitionExample),
)
.expect("Failed to open window");
gpui_platform::application().run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(500.), px(650.)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|_, cx| cx.new(|_| TransitionExample),
)
.expect("Failed to open window");
example_prelude::init_example(cx, "Transition");
});
example_prelude::init_example(cx, "Transition");
});
}