Merge pull request #72 from ModProg/button-fun

button fun
This commit is contained in:
Jonathan Johnson 2023-11-11 20:27:51 -08:00 committed by GitHub
commit 9182b04c0d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 195 additions and 205 deletions

View file

@ -21,7 +21,7 @@ fn main() -> gooey::Result {
.and(Input::new(chat_message.clone()).on_key(move |input| {
match (input.state, input.logical_key) {
(ElementState::Pressed, Key::Enter) => {
let new_message = chat_message.map_mut(|text| std::mem::take(text));
let new_message = chat_message.map_mut(std::mem::take);
chat_log.map_mut(|chat_log| {
chat_log.push_str(&new_message);
chat_log.push('\n');

View file

@ -15,7 +15,7 @@ use kludgine::{Color, Kludgine};
use crate::graphics::Graphics;
use crate::styles::components::{HighlightColor, VisualOrder, WidgetBackground};
use crate::styles::{ComponentDefaultvalue, ComponentDefinition, Styles, Theme, ThemePair};
use crate::value::{Dynamic, Value};
use crate::value::{Dynamic, IntoValue, Value};
use crate::widget::{EventHandling, ManagedWidget, WidgetId, WidgetInstance, WidgetRef};
use crate::window::sealed::WindowCommand;
use crate::window::{RunningWindow, ThemeMode};
@ -196,7 +196,7 @@ impl<'context, 'window> EventContext<'context, 'window> {
}
true
}
Err(_) => false,
Err(()) => false,
};
if new {
if let Some(active) = self.pending_state.active.clone() {
@ -250,7 +250,7 @@ impl<'context, 'window> EventContext<'context, 'window> {
}
true
}
Err(_) => false,
Err(()) => false,
};
if new {
if let Some(focus) = self.pending_state.focus.clone() {
@ -890,8 +890,8 @@ impl<'context, 'window> WidgetContext<'context, 'window> {
///
/// Style queries for children will return any values matching this
/// collection.
pub fn attach_styles(&self, styles: Value<Styles>) {
self.current_node.attach_styles(styles);
pub fn attach_styles(&self, styles: impl IntoValue<Styles>) {
self.current_node.attach_styles(styles.into_value());
}
/// Attaches `theme` to the widget hierarchy for this widget.

View file

@ -9,6 +9,7 @@ pub mod animation;
pub mod context;
mod graphics;
mod names;
#[macro_use]
pub mod styles;
mod tick;
mod tree;

View file

@ -22,6 +22,7 @@ use crate::styles::components::{FocusableWidgets, VisualOrder};
use crate::utils::Lazy;
use crate::value::{Dynamic, IntoValue, Value};
#[macro_use]
pub mod components;
/// A collection of style components organized by their name.
@ -58,7 +59,7 @@ impl Styles {
/// Adds a [`Component`] for the name provided and returns self.
#[must_use]
pub fn with(mut self, name: &impl NamedComponent, component: impl Into<Component>) -> Self {
pub fn with(mut self, name: &impl NamedComponent, component: impl IntoComponentValue) -> Self {
self.insert(name, component);
self
}
@ -1007,7 +1008,7 @@ impl SurfaceTheme {
Self {
color: neutral.color(98),
dim_color: neutral_variant.color(70),
bright_color: neutral.color(99),
bright_color: neutral.color(100),
lowest_container: neutral.color(100),
low_container: neutral.color(96),
container: neutral.color(95),
@ -1027,7 +1028,7 @@ impl SurfaceTheme {
Self {
color: neutral.color(10),
dim_color: neutral_variant.color(2),
bright_color: neutral.color(10),
bright_color: neutral.color(11),
lowest_container: neutral.color(15),
low_container: neutral.color(20),
container: neutral.color(25),
@ -1158,6 +1159,7 @@ impl ColorSource {
#[must_use]
pub fn contrast_between(self, other: Self) -> ZeroToOne {
let saturation_delta = self.saturation.difference_between(other.saturation);
let self_hue = self.hue.into_positive_degrees();
let other_hue = other.hue.into_positive_degrees();
// Calculate the shortest distance between the hues, taking into account
@ -1277,7 +1279,7 @@ impl ColorExt for Color {
let other_alpha = ZeroToOne::new(self.alpha_f32());
let alpha_delta = check_alpha.difference_between(other_alpha);
lightness_delta * source_change * alpha_delta
ZeroToOne::new((*lightness_delta + *source_change + *alpha_delta) / 3.)
}
fn most_contrasting(self, others: &[Self]) -> Self

View file

@ -12,6 +12,52 @@ use crate::styles::{
Component, ComponentDefinition, ComponentName, Dimension, Global, NamedComponent,
};
macro_rules! define_components {
($($widget:ident { $($(#$doc:tt)* $component:ident($type:ty, $name:expr, $($default:tt)*))* })*) => {$($(
$(#$doc)*
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
pub struct $component;
const _: () = {
use $crate::styles::{ComponentDefinition, ComponentName, NamedComponent};
impl NamedComponent for $component {
fn name(&self) -> Cow<'_, ComponentName> {
Cow::Owned(ComponentName::named::<Button>($name))
}
}
impl ComponentDefinition for $component {
type ComponentType = $type;
define_components!($type, $($default)*);
}
};
)*)*};
($type:ty, . $($path:tt)*) => {
define_components!($type, |context| context.theme().$($path)*);
};
($type:ty, |$context:ident| $($expr:tt)*) => {
fn default_value(&self, $context: &WidgetContext<'_, '_>) -> Color {
$($expr)*
}
};
($type:ty, @$path:path) => {
define_components!($type, |context| context.query_style(&$path));
};
($type:ty, contrasting!($bg:ident, $($fg:ident),+ $(,)?)) => {
define_components!($type, |context| {
let styles = context.query_styles(&[&$bg, $(&$fg),*]);
styles.get(&$bg, context).most_contrasting(&[
$(styles.get(&$fg, context)),+
])
});
};
($type:ty, $($expr:tt)*) => {
define_components!($type, |_context| $($expr)*);
};
}
/// The [`Dimension`] to use as the size to render text.
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
pub struct TextSize;

View file

@ -572,6 +572,12 @@ pub trait MakeWidget: Sized {
fn horizontal_scroll(self) -> Scroll {
Scroll::horizontal(self)
}
/// Creates a [`WidgetRef`] for use as child widget.
#[must_use]
fn widget_ref(self) -> WidgetRef {
WidgetRef::new(self)
}
}
/// A type that can create a [`WidgetInstance`] with a preallocated

View file

@ -4,50 +4,48 @@ use std::panic::UnwindSafe;
use std::time::Duration;
use kludgine::app::winit::event::{DeviceId, ElementState, KeyEvent, MouseButton};
use kludgine::figures::units::{Lp, Px, UPx};
use kludgine::figures::{IntoUnsigned, Point, Rect, ScreenScale, Size};
use kludgine::shapes::StrokeOptions;
use kludgine::text::Text;
use kludgine::figures::units::{Px, UPx};
use kludgine::figures::{IntoSigned, IntoUnsigned, Point, Rect, ScreenScale, Size};
use kludgine::Color;
use crate::animation::{AnimationHandle, AnimationTarget, LinearInterpolate, Spawn};
use crate::context::{EventContext, GraphicsContext, LayoutContext, WidgetContext};
use crate::animation::{AnimationHandle, AnimationTarget, Spawn};
use crate::context::{AsEventContext, EventContext, GraphicsContext, LayoutContext, WidgetContext};
use crate::names::Name;
use crate::styles::components::{
AutoFocusableControls, DisabledOutlineColor, Easing, IntrinsicPadding, OutlineColor,
SurfaceColor, TextColor,
AutoFocusableControls, Easing, IntrinsicPadding, SurfaceColor, TextColor,
};
use crate::styles::{ColorExt, ComponentDefinition, ComponentGroup, ComponentName, NamedComponent};
use crate::styles::{ColorExt, ComponentGroup, Styles};
use crate::utils::ModifiersExt;
use crate::value::{Dynamic, IntoValue, Value};
use crate::widget::{Callback, EventHandling, Widget, HANDLED, IGNORED};
use crate::widget::{Callback, EventHandling, MakeWidget, Widget, WidgetRef, HANDLED, IGNORED};
/// A clickable button.
#[derive(Debug)]
pub struct Button {
/// The label to display on the button.
pub label: Value<String>,
pub content: WidgetRef,
/// The callback that is invoked when the button is clicked.
pub on_click: Option<Callback<()>>,
/// The enabled state of the button.
pub enabled: Value<bool>,
currently_enabled: bool,
buttons_pressed: usize,
colors: Option<Dynamic<Colors>>,
background_color: Option<Dynamic<Color>>,
text_color: Option<Dynamic<Color>>,
color_animation: AnimationHandle,
}
impl Button {
/// Returns a new button with the provided label.
pub fn new(label: impl IntoValue<String>) -> Self {
pub fn new(content: impl MakeWidget) -> Self {
Self {
label: label.into_value(),
content: content.widget_ref(),
on_click: None,
enabled: Value::Constant(true),
currently_enabled: true,
buttons_pressed: 0,
colors: None,
background_color: None,
text_color: None,
color_animation: AnimationHandle::default(),
}
}
@ -86,109 +84,75 @@ impl Button {
&ButtonBackground,
&ButtonHoverBackground,
&ButtonDisabledBackground,
&ButtonActiveForeground,
&ButtonForeground,
&ButtonHoverForeground,
&ButtonDisabledForeground,
&Easing,
&TextColor,
&SurfaceColor,
&OutlineColor,
&DisabledOutlineColor,
]);
let text_color = styles.get(&TextColor, context);
let surface_color = styles.get(&SurfaceColor, context);
let outline_color = styles.get(&OutlineColor, context);
let (background, outline, text_color, surface_color) = if !self.enabled.get() {
(
let (background_color, text_color) = match () {
() if !self.enabled.get() => (
styles.get(&ButtonDisabledBackground, context),
styles.get(&DisabledOutlineColor, context),
text_color,
surface_color,
)
} else if context.is_default() {
// TODO this probably should be de-prioritized if ButtonBackground is explicitly set.
(
context.theme().primary.color,
styles.get(&ButtonDisabledForeground, context),
),
// TODO this probably should use actual style.
() if context.is_default() => (
context.theme().primary.color,
context.theme().primary.on_color,
context.theme().primary.color,
)
} else if context.active() {
(
),
() if context.active() => (
styles.get(&ButtonActiveBackground, context),
outline_color,
text_color,
surface_color,
)
} else if context.hovered() {
(
styles.get(&ButtonActiveForeground, context),
),
() if context.hovered() => (
styles.get(&ButtonHoverBackground, context),
outline_color,
text_color,
surface_color,
)
} else {
(
styles.get(&ButtonHoverForeground, context),
),
() => (
styles.get(&ButtonBackground, context),
outline_color,
text_color,
surface_color,
)
styles.get(&ButtonForeground, context),
),
};
let text = background.most_contrasting(&[text_color, surface_color]);
let new_colors = Colors {
background,
text,
outline,
};
match (immediate, &self.colors) {
(false, Some(colors)) => {
self.color_animation = colors
.transition_to(new_colors)
match (immediate, &self.background_color, &self.text_color) {
(false, Some(bg), Some(text)) => {
self.color_animation = (
bg.transition_to(background_color),
text.transition_to(text_color),
)
.over(Duration::from_millis(150))
.with_easing(styles.get(&Easing, context))
.spawn();
}
(true, Some(colors)) => {
colors.update(new_colors);
(true, Some(bg), Some(text)) => {
bg.update(background_color);
text.update(text_color);
self.color_animation.clear();
}
_ => {
self.colors = Some(Dynamic::new(new_colors));
self.background_color = Some(Dynamic::new(background_color));
let text_color = Dynamic::new(text_color);
self.text_color = Some(text_color.clone());
context.attach_styles(Styles::new().with(&TextColor, text_color));
}
}
}
fn current_colors(&mut self, context: &WidgetContext<'_, '_>) -> Colors {
if self.colors.is_none() {
fn current_background(&mut self, context: &WidgetContext<'_, '_>) -> Color {
if self.background_color.is_none() {
self.update_colors(context, false);
}
let colors = self.colors.as_ref().expect("always initialized");
context.redraw_when_changed(colors);
colors.get()
}
}
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
struct Colors {
background: Color,
text: Color,
outline: Color,
}
impl LinearInterpolate for Colors {
fn lerp(&self, target: &Self, percent: f32) -> Self {
Self {
background: self.background.lerp(&target.background, percent),
text: self.text.lerp(&target.text, percent),
outline: self.outline.lerp(&target.outline, percent),
}
let background_color = self.background_color.as_ref().expect("always initialized");
context.redraw_when_changed(background_color);
background_color.get()
}
}
impl Widget for Button {
fn redraw(&mut self, context: &mut GraphicsContext<'_, '_, '_, '_, '_>) {
#![allow(clippy::similar_names)]
let enabled = self.enabled.get();
// TODO This seems ugly. It needs context, so it can't be moved into the
// dynamic system.
@ -197,30 +161,17 @@ impl Widget for Button {
self.currently_enabled = enabled;
}
let size = context.gfx.region().size;
let center = Point::from(size) / 2;
self.label.redraw_when_changed(context);
self.enabled.redraw_when_changed(context);
let colors = self.current_colors(context);
context.gfx.fill(colors.background);
let background_color = self.current_background(context);
context.gfx.fill(background_color);
if context.focused() {
context.draw_focus_ring();
} else {
context.stroke_outline::<Lp>(colors.outline, StrokeOptions::default());
}
self.label.map(|label| {
context.gfx.draw_text(
Text::new(label, colors.text)
.origin(kludgine::text::TextOrigin::Center)
.wrap_at(size.width),
center,
None,
None,
);
});
let content = self.content.mounted(&mut context.as_event_context());
context.for_other(&content).redraw();
}
fn hit_test(&mut self, _location: Point<Px>, _context: &mut EventContext<'_, '_>) -> bool {
@ -295,17 +246,13 @@ impl Widget for Button {
.query_style(&IntrinsicPadding)
.into_px(context.gfx.scale())
.into_unsigned();
let width = available_space.width.max().try_into().unwrap_or(Px::MAX);
self.label.map(|label| {
let measured = context
.gfx
.measure_text::<Px>(Text::from(label).wrap_at(width));
let mut size = measured.size.into_unsigned();
size.width += padding * 2;
size.height = size.height.max(measured.line_height.into_unsigned()) + padding * 2;
size
})
let mounted = self.content.mounted(&mut context.as_event_context());
let size = context.for_other(&mounted).layout(available_space);
context.set_child_layout(
&mounted,
Rect::new(Point::new(padding, padding), size).into_signed(),
);
size + padding * 2
}
fn keyboard_input(
@ -373,76 +320,27 @@ impl ComponentGroup for Button {
}
}
/// The background color of the button.
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
pub struct ButtonBackground;
impl NamedComponent for ButtonBackground {
fn name(&self) -> Cow<'_, ComponentName> {
Cow::Owned(ComponentName::named::<Button>("background_color"))
}
}
impl ComponentDefinition for ButtonBackground {
type ComponentType = Color;
fn default_value(&self, context: &WidgetContext<'_, '_>) -> Color {
context.theme().surface.color
}
}
/// The background color of the button when it is active (depressed).
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
pub struct ButtonActiveBackground;
impl NamedComponent for ButtonActiveBackground {
fn name(&self) -> Cow<'_, ComponentName> {
Cow::Owned(ComponentName::named::<Button>("active_background_color"))
}
}
impl ComponentDefinition for ButtonActiveBackground {
type ComponentType = Color;
fn default_value(&self, context: &WidgetContext<'_, '_>) -> Color {
context.theme().surface.dim_color
}
}
/// The background color of the button when the mouse cursor is hovering over
/// it.
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
pub struct ButtonHoverBackground;
impl NamedComponent for ButtonHoverBackground {
fn name(&self) -> Cow<'_, ComponentName> {
Cow::Owned(ComponentName::named::<Button>("hover_background_color"))
}
}
impl ComponentDefinition for ButtonHoverBackground {
type ComponentType = Color;
fn default_value(&self, context: &WidgetContext<'_, '_>) -> Color {
context.theme().surface.bright_color
}
}
/// The background color of the button when the mouse cursor is hovering over
/// it.
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
pub struct ButtonDisabledBackground;
impl NamedComponent for ButtonDisabledBackground {
fn name(&self) -> Cow<'_, ComponentName> {
Cow::Owned(ComponentName::named::<Button>("disabled_background_color"))
}
}
impl ComponentDefinition for ButtonDisabledBackground {
type ComponentType = Color;
fn default_value(&self, context: &WidgetContext<'_, '_>) -> Color {
context.theme().surface.dim_color
define_components! {
Button {
/// The background color of the button.
ButtonBackground(Color, "background_color", .surface.highest_container) // TODO highest_container seems wrong, but it's what material uses. Perhaps we should add another color so that buttons don't blend with the highest container level.
/// The background color of the button when it is active (depressed).
ButtonActiveBackground(Color, "active_background_color", .surface.color)
/// The background color of the button when the mouse cursor is hovering over
/// it.
ButtonHoverBackground(Color, "hover_background_color", .surface.bright_color)
/// The background color of the button when the mouse cursor is hovering over
/// it.
ButtonDisabledBackground(Color, "disabled_background_color", .surface.dim_color)
/// The foreground color of the button.
ButtonForeground(Color, "foreground_color", contrasting!(ButtonBackground, TextColor, SurfaceColor))
/// The foreground color of the button when it is active (depressed).
ButtonActiveForeground(Color, "active_foreground_color", contrasting!(ButtonActiveBackground, ButtonForeground, TextColor, SurfaceColor))
/// The foreground color of the button when the mouse cursor is hovering over
/// it.
ButtonHoverForeground(Color, "hover_foreground_color", contrasting!(ButtonHoverBackground, ButtonForeground, TextColor, SurfaceColor))
/// The foreground color of the button when the mouse cursor is hovering over
/// it.
ButtonDisabledForeground(Color, "disabled_foreground_color", contrasting!(ButtonDisabledBackground, ButtonForeground, TextColor, SurfaceColor))
}
}

View file

@ -1,14 +1,17 @@
//! A read-only text widget.
use std::borrow::Cow;
use kludgine::figures::units::{Px, UPx};
use kludgine::figures::{IntoUnsigned, Point, ScreenScale, Size};
use kludgine::text::{MeasuredText, Text, TextOrigin};
use kludgine::Color;
use crate::context::{GraphicsContext, LayoutContext};
use crate::context::{GraphicsContext, LayoutContext, WidgetContext};
use crate::styles::components::{IntrinsicPadding, TextColor};
use crate::styles::ComponentGroup;
use crate::value::{IntoValue, Value};
use crate::widget::Widget;
use crate::styles::{ComponentDefinition, ComponentGroup, ComponentName, NamedComponent};
use crate::value::{Dynamic, IntoValue, Value};
use crate::widget::{MakeWidget, Widget, WidgetInstance};
use crate::{ConstraintLimit, Name};
/// A read-only text widget.
@ -35,13 +38,17 @@ impl Widget for Label {
let size = context.gfx.region().size;
let center = Point::from(size) / 2;
let styles = context.query_styles(&[&TextColor, &LabelBackground]);
let background = styles.get(&LabelBackground, context);
context.gfx.fill(background);
if let Some(measured) = &self.prepared_text {
context
.gfx
.draw_measured_text(measured, TextOrigin::Center, center, None, None);
} else {
let text_color = context.query_style(&TextColor);
let text_color = styles.get(&TextColor, context);
self.text.map(|contents| {
context.gfx.draw_text(
Text::new(contents, text_color)
@ -84,3 +91,33 @@ impl ComponentGroup for Label {
Name::new("Label")
}
}
/// A [`Color`] to be used as a highlight color.
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
pub struct LabelBackground;
impl NamedComponent for LabelBackground {
fn name(&self) -> Cow<'_, ComponentName> {
Cow::Owned(ComponentName::named::<Label>("background_color"))
}
}
impl ComponentDefinition for LabelBackground {
type ComponentType = Color;
fn default_value(&self, _context: &WidgetContext<'_, '_>) -> Color {
Color::CLEAR_WHITE
}
}
macro_rules! impl_make_widget {
($($type:ty),*) => {
$(impl MakeWidget for $type {
fn make_widget(self) -> WidgetInstance {
Label::new(self).make_widget()
}
})*
};
}
impl_make_widget!(&'_ str, String, Value<String>, Dynamic<String>);

View file

@ -406,7 +406,7 @@ impl ComponentDefinition for InactiveTrackColor {
type ComponentType = Color;
fn default_value(&self, context: &WidgetContext<'_, '_>) -> Self::ComponentType {
context.theme().surface.outline
context.theme().surface.highest_container // TODO this is the same as ButtonBackground. This should be abstracted into its own component both can depend on.
}
}