flux-tui 0.5.0

Fast and lightweight Terminal UI drawing library
Documentation
use super::*;
use crate::canvas::*;

use crossterm::event::{Event, KeyCode};
use std::num::NonZero;
use std::rc::Rc;
use unicode_width::UnicodeWidthStr;

pub type ExecuteCallback = dyn Fn(&mut Button);
pub type ButtonKeyHandler = fn(&mut Button, event: &mut WindowEvent);

/// Button shows a text and executes a callback when pressing Enter (while focused)
/// Focus highlights the inner text
///
/// Design (optional Border):
/// ```text
/// ┌──────┐
/// │Button│
/// └──────┘
/// ```
pub struct Button {
	text: String,
	text_alignment: HorizontalAlignment,
	callback: Rc<ExecuteCallback>,
	key_handler: ButtonKeyHandler,
	has_focus: bool,
	base: WidgetBase,
}

impl Default for Button {
	fn default() -> Self {
		let mut s = Self {
			text: String::default(),
			text_alignment: HorizontalAlignment::default(),
			callback: Rc::new(Self::default_callback),
			key_handler: Self::default_key_handler,
			has_focus: false,
			base: WidgetBase::default(),
		};
		s.base.constraints.y.min = NonZero::<TSize>::MIN;
		s.base.constraints.y.max = Size::Fixed(NonZero::<TSize>::MIN);
		s
	}
}

impl Button {
	pub fn default_callback(_: &mut Self) {}

	pub fn default_key_handler(&mut self, event: &mut WindowEvent) {
		if let Event::Key(k) = event.raw() {
			if self.base.enabled && k.code == KeyCode::Enter {
				self.execute();
				event.handled = true;
			}
		}
	}

	/// Sets the callback, which is called when pressing `Enter`
	pub fn set_callback<F: Fn(&mut Self) + 'static>(&mut self, callback: F) {
		self.callback = Rc::new(callback);
	}

	pub fn set_key_handler(&mut self, f: ButtonKeyHandler) {
		self.key_handler = f;
	}

	/// Sets the alignment for the inner text
	pub fn set_text_alignment(&mut self, alignment: HorizontalAlignment) {
		self.text_alignment = alignment;
	}

	/// Returns the internal text
	pub fn get_text(&self) -> &str {
		&self.text
	}

	/// Sets the internal shown text
	pub fn set_text(&mut self, text: &str) {
		self.text.clear();
		self.text.push_str(text);
	}

	/// Executes the callback
	pub fn execute(&mut self) {
		let cb = self.callback.clone();
		cb(self);
	}
}

impl Window for Button {
	fn render(&self, canvas: &mut Canvas) {
		let mut row = canvas.get_row_variable_width(TSize::MIN).unwrap();
		let width = self.text.width() as TSize;
		let mut skip = TSize::MIN;

		match self.text_alignment {
			HorizontalAlignment::Center => {
				if row.width() > width {
					skip = (row.width() - width) / 2;
				}
			}
			// default behaviour
			HorizontalAlignment::Left => {}
			HorizontalAlignment::Right => {
				if row.width() > width {
					skip = row.width() - width;
				}
			}
		}

		row.skip(skip);
		row.add_string(
			&self.text,
			self.base.colors.base_fg,
			self.base.colors.base_bg,
			Style::Reverse.when(self.has_focus),
			Some(VariableWidthGlyphRow::DOT3_REPLACEMENT),
		)
		.ok();
		if let Some(color) = self.base.colors.disabled
			&& !self.base.enabled
		{
			row.fill_foreground(color);
		}
	}

	fn handle_event(&mut self, event: &mut WindowEvent) {
		match event.raw() {
			Event::FocusGained => self.has_focus = true,
			Event::FocusLost => self.has_focus = false,
			_ => (self.key_handler)(self, event),
		}
	}

	fn is_enabled(&self) -> bool {
		self.base.enabled
	}
}

impl WindowLayout for Button {
	fn desired_size(&self, available_size: TPoint) -> TPoint {
		self.base.desired_size(available_size)
	}

	fn border(&self) -> BorderStyle {
		self.base.border
	}

	fn alignment(&self) -> (HorizontalAlignment, VerticalAlignment) {
		self.base.alignment
	}

	fn is_visible(&self) -> bool {
		self.base.visibility
	}

	fn margin(&self) -> Thickness {
		self.base.margin
	}
}

impl HasWindowUID for Button {
	fn uid(&self) -> WindowUID {
		self.base.uid
	}
}

impl Widget for Button {
	fn set_visibility(&mut self, visibility: bool) {
		self.base.visibility = visibility;
		self.provoke_changed_property(WindowProperty::IsVisible);
	}

	fn set_width(&mut self, width: Size) {
		self.base.size.x = width;
		self.provoke_changed_property(WindowProperty::Size);
	}

	fn set_height(&mut self, _: Size) {}

	fn set_margin(&mut self, margin: Thickness) {
		self.base.margin = margin;
		self.provoke_changed_property(WindowProperty::Margin);
	}

	fn set_border(&mut self, border: BorderStyle) {
		self.base.border = border;
		self.provoke_changed_property(WindowProperty::Border);
	}

	fn set_alignment(&mut self, horizontal: HorizontalAlignment, vertical: VerticalAlignment) {
		self.base.alignment = (horizontal, vertical);
		self.provoke_changed_property(WindowProperty::Alignment);
	}

	fn set_enabled_state(&mut self, is_enabled: bool) {
		self.base.enabled = is_enabled;
	}

	fn set_width_constraint(&mut self, width: SizeConstraint) {
		self.base.constraints.x = width;
		self.provoke_changed_property(WindowProperty::Size);
	}

	fn set_height_constraint(&mut self, _: SizeConstraint) {}
}

impl WidgetColors for Button {
	fn set_disabled_color(&mut self, color: Option<Color>) {
		self.base.colors.disabled = color;
	}

	fn set_base_fg_color(&mut self, color: Option<Color>) {
		self.base.colors.base_fg = color;
	}

	fn set_base_bg_color(&mut self, color: Option<Color>) {
		self.base.colors.base_bg = color;
	}
}