Added a toaster system, and custom theme coloring for toasters
Moorly CI / windows-build (push) Successful in 2m47s
Moorly CI / linux-build (push) Successful in 3m32s

This commit is contained in:
Squid committed 2026-11-06 22:39:33 +01:00
1 parent 8d9f4584dd
commit 891bb85d92
2 files changed
+927 -19

No files matched your search

+432 -19
View File
@@ -16,6 +16,7 @@ use iced::{
#[allow(dead_code)] #[allow(dead_code)]
mod terminal; mod terminal;
mod notifications;
mod theme; mod theme;
const MENUBAR_HEIGHT: f32 = 40.0; const MENUBAR_HEIGHT: f32 = 40.0;
@@ -96,6 +97,14 @@ fn subscription(state: &Moorly) -> Subscription<Message> {
{ {
Some(Message::AddTab) Some(Message::AddTab)
} }
keyboard::Key::Character(key)
if cfg!(debug_assertions)
&& key.eq_ignore_ascii_case("n")
&& modifiers.control()
&& modifiers.shift() =>
{
Some(Message::ShowNotificationDemo)
}
keyboard::Key::Character(key) keyboard::Key::Character(key)
if key.eq_ignore_ascii_case("w") if key.eq_ignore_ascii_case("w")
&& modifiers.control() && modifiers.control()
@@ -127,6 +136,17 @@ fn subscription(state: &Moorly) -> Subscription<Message> {
subscriptions.push(window::frames().map(Message::Frame)); subscriptions.push(window::frames().map(Message::Frame));
} }
// Timed notifications only need a coarse expiry timer; fades use frames.
if state.notifications.has_timed() {
subscriptions.push(
iced::time::every(Duration::from_millis(250)).map(Message::NotificationTick),
);
}
if state.notifications.is_animating(now) {
subscriptions.push(window::frames().map(Message::NotificationTick));
}
Subscription::batch(subscriptions) Subscription::batch(subscriptions)
} }
@@ -641,7 +661,10 @@ struct Moorly {
advanced_open: bool, advanced_open: bool,
colors: [Color; 5], colors: [Color; 5],
saved_colors: [Color; 5], saved_colors: [Color; 5],
custom_toasts: bool,
toast_colors: [Color; 9],
open_color_picker: Option<ColorOption>, open_color_picker: Option<ColorOption>,
open_toast_color_picker: Option<ToastColorOption>,
fade_animation: Animation<bool>, fade_animation: Animation<bool>,
hovered_tab: Option<Tab>, hovered_tab: Option<Tab>,
tab_close_fades: HashMap<Tab, Animation<bool>>, tab_close_fades: HashMap<Tab, Animation<bool>>,
@@ -657,6 +680,7 @@ struct Moorly {
tab_offset: f32, tab_offset: f32,
tab_viewport_width: f32, tab_viewport_width: f32,
tab_content_width: f32, tab_content_width: f32,
notifications: notifications::NotificationManager,
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
@@ -723,6 +747,61 @@ const DEFAULT_COLORS: [Color; 5] = [
theme::TAB_TEXT, theme::TAB_TEXT,
]; ];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ToastColorOption {
Background,
Text,
Title,
Border,
Info,
Success,
Warning,
Error,
Dismiss,
}
impl ToastColorOption {
const ALL: [Self; 9] = [
Self::Background,
Self::Text,
Self::Title,
Self::Border,
Self::Info,
Self::Success,
Self::Warning,
Self::Error,
Self::Dismiss,
];
fn label(self) -> &'static str {
match self {
Self::Background => "Notification background",
Self::Text => "Notification text",
Self::Title => "Notification title",
Self::Border => "Notification border",
Self::Info => "Info accent",
Self::Success => "Success accent",
Self::Warning => "Warning accent",
Self::Error => "Error accent",
Self::Dismiss => "Dismiss icon",
}
}
fn index(self) -> usize {
match self {
Self::Background => 0,
Self::Text => 1,
Self::Title => 2,
Self::Border => 3,
Self::Info => 4,
Self::Success => 5,
Self::Warning => 6,
Self::Error => 7,
Self::Dismiss => 8,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
enum ThemeChoice { enum ThemeChoice {
BuiltIn(theme::Preference), BuiltIn(theme::Preference),
@@ -768,6 +847,8 @@ struct CustomTheme {
name: String, name: String,
based_on: theme::Preference, based_on: theme::Preference,
colors: [Color; 5], colors: [Color; 5],
custom_toasts: bool,
toast_colors: [Color; 9],
} }
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
@@ -784,6 +865,32 @@ struct ThemeFile {
sidebar_background: Option<String>, sidebar_background: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
text: Option<String>, text: Option<String>,
#[serde(default)]
toast: ToastFile,
}
#[derive(Debug, Default, Serialize, Deserialize)]
struct ToastFile {
#[serde(default)]
enabled: bool,
#[serde(skip_serializing_if = "Option::is_none")]
background: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
text: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
title: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
border: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
info: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
success: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
warning: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
error: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
dismiss: Option<String>,
} }
impl ThemeFile { impl ThemeFile {
@@ -792,6 +899,8 @@ impl ThemeFile {
based_on: theme::Preference, based_on: theme::Preference,
colors: &[Color; 5], colors: &[Color; 5],
base: &[Color; 5], base: &[Color; 5],
custom_toasts: bool,
toast_colors: &[Color; 9],
) -> Self { ) -> Self {
let changed = |option: ColorOption| { let changed = |option: ColorOption| {
let index = option.index(); let index = option.index();
@@ -807,6 +916,7 @@ impl ThemeFile {
main_background: changed(ColorOption::MainBackground), main_background: changed(ColorOption::MainBackground),
sidebar_background: changed(ColorOption::SidebarBackground), sidebar_background: changed(ColorOption::SidebarBackground),
text: changed(ColorOption::Text), text: changed(ColorOption::Text),
toast: ToastFile::from_colors(custom_toasts, toast_colors),
} }
} }
@@ -829,10 +939,55 @@ impl ThemeFile {
} }
} }
impl ToastFile {
fn from_colors(enabled: bool, colors: &[Color; 9]) -> Self {
Self {
enabled,
background: Some(color_to_hex(colors[0])),
text: Some(color_to_hex(colors[1])),
title: Some(color_to_hex(colors[2])),
border: Some(color_to_hex(colors[3])),
info: Some(color_to_hex(colors[4])),
success: Some(color_to_hex(colors[5])),
warning: Some(color_to_hex(colors[6])),
error: Some(color_to_hex(colors[7])),
dismiss: Some(color_to_hex(colors[8])),
}
}
fn colors(&self, based_on: theme::Preference) -> [Color; 9] {
let mut colors = builtin_toast_colors(based_on);
for (color, value) in colors.iter_mut().zip([
&self.background,
&self.text,
&self.title,
&self.border,
&self.info,
&self.success,
&self.warning,
&self.error,
&self.dismiss,
]) {
if let Some(parsed) = value.as_deref().and_then(color_from_hex) {
*color = parsed;
}
}
colors
}
}
fn builtin_colors(_preference: theme::Preference) -> [Color; 5] { fn builtin_colors(_preference: theme::Preference) -> [Color; 5] {
DEFAULT_COLORS DEFAULT_COLORS
} }
fn builtin_toast_colors(preference: theme::Preference) -> [Color; 9] {
let theme = preference.iced().unwrap_or(iced::Theme::Dark);
notifications::ToastColors::default_for(&theme).as_array()
}
/// Everything persisted in `config.toml`, grouped by settings tab. /// Everything persisted in `config.toml`, grouped by settings tab.
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
struct ConfigFile { struct ConfigFile {
@@ -1012,11 +1167,14 @@ fn load_custom_themes() -> Vec<CustomTheme> {
}; };
let colors = file.colors(based_on); let colors = file.colors(based_on);
let toast_colors = file.toast.colors(based_on);
themes.push(CustomTheme { themes.push(CustomTheme {
id, id,
name: file.name, name: file.name,
based_on, based_on,
colors, colors,
custom_toasts: file.toast.enabled,
toast_colors,
}); });
} }
@@ -1064,12 +1222,21 @@ fn write_custom_theme(
name: &str, name: &str,
based_on: theme::Preference, based_on: theme::Preference,
colors: &[Color; 5], colors: &[Color; 5],
custom_toasts: bool,
toast_colors: &[Color; 9],
) -> Option<()> { ) -> Option<()> {
let dir = themes_dir()?; let dir = themes_dir()?;
std::fs::create_dir_all(&dir).ok()?; std::fs::create_dir_all(&dir).ok()?;
let base = builtin_colors(based_on); let base = builtin_colors(based_on);
let file = ThemeFile::from_colors(name.to_owned(), based_on, colors, &base); let file = ThemeFile::from_colors(
name.to_owned(),
based_on,
colors,
&base,
custom_toasts,
toast_colors,
);
let text = toml::to_string_pretty(&file).ok()?; let text = toml::to_string_pretty(&file).ok()?;
std::fs::write(dir.join(format!("{id}.toml")), text).ok()?; std::fs::write(dir.join(format!("{id}.toml")), text).ok()?;
@@ -1081,11 +1248,15 @@ fn apply_theme_choice(state: &mut Moorly, choice: ThemeChoice) {
ThemeChoice::BuiltIn(preference) => { ThemeChoice::BuiltIn(preference) => {
state.theme = *preference; state.theme = *preference;
state.colors = builtin_colors(*preference); state.colors = builtin_colors(*preference);
state.custom_toasts = false;
state.toast_colors = builtin_toast_colors(*preference);
} }
ThemeChoice::Custom { id, .. } => { ThemeChoice::Custom { id, .. } => {
if let Some(theme) = state.custom_themes.iter().find(|theme| theme.id == *id) { if let Some(theme) = state.custom_themes.iter().find(|theme| theme.id == *id) {
state.theme = theme.based_on; state.theme = theme.based_on;
state.colors = theme.colors; state.colors = theme.colors;
state.custom_toasts = theme.custom_toasts;
state.toast_colors = theme.toast_colors;
state.theme_choice = ThemeChoice::Custom { state.theme_choice = ThemeChoice::Custom {
id: theme.id.clone(), id: theme.id.clone(),
name: theme.name.clone(), name: theme.name.clone(),
@@ -1181,7 +1352,7 @@ fn load_config() -> ConfigFile {
fn resolve_theme( fn resolve_theme(
appearance: &AppearanceConfig, appearance: &AppearanceConfig,
custom_themes: &[CustomTheme], custom_themes: &[CustomTheme],
) -> (ThemeChoice, theme::Preference, [Color; 5]) { ) -> (ThemeChoice, theme::Preference, [Color; 5], bool, [Color; 9]) {
if let Some(id) = &appearance.custom_theme if let Some(id) = &appearance.custom_theme
&& let Some(theme) = custom_themes.iter().find(|theme| theme.id == *id) && let Some(theme) = custom_themes.iter().find(|theme| theme.id == *id)
{ {
@@ -1192,12 +1363,20 @@ fn resolve_theme(
}, },
theme.based_on, theme.based_on,
theme.colors, theme.colors,
theme.custom_toasts,
theme.toast_colors,
); );
} }
let preference = theme::Preference::parse(&appearance.theme).unwrap_or_default(); let preference = theme::Preference::parse(&appearance.theme).unwrap_or_default();
(ThemeChoice::BuiltIn(preference), preference, builtin_colors(preference)) (
ThemeChoice::BuiltIn(preference),
preference,
builtin_colors(preference),
false,
builtin_toast_colors(preference),
)
} }
/// 0.5s total: 250ms fading out plus 250ms fading in. /// 0.5s total: 250ms fading out plus 250ms fading in.
@@ -1247,6 +1426,19 @@ fn undo_settings(state: &mut Moorly) {
state.theme_choice = state.saved_theme_choice.clone(); state.theme_choice = state.saved_theme_choice.clone();
state.theme = state.saved_theme; state.theme = state.saved_theme;
state.colors = state.saved_colors; state.colors = state.saved_colors;
let (custom_toasts, toast_colors) = match &state.saved_theme_choice {
ThemeChoice::BuiltIn(preference) => (false, builtin_toast_colors(*preference)),
ThemeChoice::Custom { id, .. } => state
.custom_themes
.iter()
.find(|theme| theme.id == *id)
.map(|theme| (theme.custom_toasts, theme.toast_colors))
.unwrap_or_else(|| (false, builtin_toast_colors(state.saved_theme))),
};
state.custom_toasts = custom_toasts;
state.toast_colors = toast_colors;
} }
fn save_config(state: &Moorly) { fn save_config(state: &Moorly) {
@@ -1301,7 +1493,8 @@ impl Default for Moorly {
fn default() -> Self { fn default() -> Self {
let config = load_config(); let config = load_config();
let custom_themes = load_custom_themes(); let custom_themes = load_custom_themes();
let (theme_choice, theme, colors) = resolve_theme(&config.appearance, &custom_themes); let (theme_choice, theme, colors, custom_toasts, toast_colors) =
resolve_theme(&config.appearance, &custom_themes);
let show_start_tab = config.startup.show_start_tab; let show_start_tab = config.startup.show_start_tab;
let fade_settings = config.general.fade_settings; let fade_settings = config.general.fade_settings;
let hide_tab_close = config.appearance.hide_tab_close; let hide_tab_close = config.appearance.hide_tab_close;
@@ -1340,7 +1533,10 @@ impl Default for Moorly {
advanced_open: false, advanced_open: false,
colors, colors,
saved_colors: colors, saved_colors: colors,
custom_toasts,
toast_colors,
open_color_picker: None, open_color_picker: None,
open_toast_color_picker: None,
fade_animation: new_fade_animation(), fade_animation: new_fade_animation(),
hovered_tab: None, hovered_tab: None,
tab_close_fades: HashMap::new(), tab_close_fades: HashMap::new(),
@@ -1356,6 +1552,7 @@ impl Default for Moorly {
tab_offset: 0.0, tab_offset: 0.0,
tab_viewport_width: 0.0, tab_viewport_width: 0.0,
tab_content_width: 0.0, tab_content_width: 0.0,
notifications: notifications::NotificationManager::default(),
} }
} }
} }
@@ -1383,11 +1580,17 @@ enum Message {
SetFadeSettings(bool), SetFadeSettings(bool),
SetHideTabClose(bool), SetHideTabClose(bool),
ToggleAdvanced, ToggleAdvanced,
SetCustomToasts(bool),
OpenColorPicker(ColorOption), OpenColorPicker(ColorOption),
SubmitColor(ColorOption, Color), SubmitColor(ColorOption, Color),
OpenToastColorPicker(ToastColorOption),
SubmitToastColor(ToastColorOption, Color),
CancelColorPicker, CancelColorPicker,
SaveSettings, SaveSettings,
UndoChanges, UndoChanges,
Notification(notifications::Message),
NotificationTick(Instant),
ShowNotificationDemo,
Frame(Instant), Frame(Instant),
ProfileFilterChanged(String), ProfileFilterChanged(String),
ClearProfileFilter, ClearProfileFilter,
@@ -1519,7 +1722,16 @@ fn update(state: &mut Moorly, message: Message) -> Task<Message> {
let id = uuid::Uuid::new_v4().to_string(); let id = uuid::Uuid::new_v4().to_string();
if write_custom_theme(&id, &name, based_on, &state.colors).is_none() { if write_custom_theme(
&id,
&name,
based_on,
&state.colors,
state.custom_toasts,
&state.toast_colors,
)
.is_none()
{
return Task::none(); return Task::none();
} }
@@ -1546,13 +1758,24 @@ fn update(state: &mut Moorly, message: Message) -> Task<Message> {
{ {
let based_on = theme.based_on; let based_on = theme.based_on;
if write_custom_theme(id, name, based_on, &state.colors).is_some() { if write_custom_theme(
id,
name,
based_on,
&state.colors,
state.custom_toasts,
&state.toast_colors,
)
.is_some()
{
if let Some(theme) = state if let Some(theme) = state
.custom_themes .custom_themes
.iter_mut() .iter_mut()
.find(|theme| theme.id == *id) .find(|theme| theme.id == *id)
{ {
theme.colors = state.colors; theme.colors = state.colors;
theme.custom_toasts = state.custom_toasts;
theme.toast_colors = state.toast_colors;
} }
if matches!( if matches!(
@@ -1572,6 +1795,8 @@ fn update(state: &mut Moorly, message: Message) -> Task<Message> {
{ {
state.theme = theme.based_on; state.theme = theme.based_on;
state.colors = theme.colors; state.colors = theme.colors;
state.custom_toasts = theme.custom_toasts;
state.toast_colors = theme.toast_colors;
if matches!( if matches!(
&state.saved_theme_choice, &state.saved_theme_choice,
@@ -1590,15 +1815,20 @@ fn update(state: &mut Moorly, message: Message) -> Task<Message> {
ThemeChoice::Custom { id, .. } => Some(id.clone()), ThemeChoice::Custom { id, .. } => Some(id.clone()),
ThemeChoice::BuiltIn(_) => None, ThemeChoice::BuiltIn(_) => None,
}; };
let old_theme_colors = selected_id.as_ref().and_then(|id| { let old_theme = selected_id.as_ref().and_then(|id| {
state state
.custom_themes .custom_themes
.iter() .iter()
.find(|theme| theme.id == *id) .find(|theme| theme.id == *id)
.map(|theme| theme.colors) .cloned()
}); });
let had_no_edits = old_theme_colors let had_no_edits = old_theme
.map(|colors| colors == state.colors) .as_ref()
.map(|theme| {
theme.colors == state.colors
&& theme.custom_toasts == state.custom_toasts
&& theme.toast_colors == state.toast_colors
})
.unwrap_or(true); .unwrap_or(true);
state.custom_themes = load_custom_themes(); state.custom_themes = load_custom_themes();
@@ -1614,6 +1844,8 @@ fn update(state: &mut Moorly, message: Message) -> Task<Message> {
if had_no_edits { if had_no_edits {
state.theme = theme.based_on; state.theme = theme.based_on;
state.colors = theme.colors; state.colors = theme.colors;
state.custom_toasts = theme.custom_toasts;
state.toast_colors = theme.toast_colors;
} }
if matches!( if matches!(
@@ -1626,6 +1858,8 @@ fn update(state: &mut Moorly, message: Message) -> Task<Message> {
} else { } else {
state.theme_choice = ThemeChoice::BuiltIn(state.theme); state.theme_choice = ThemeChoice::BuiltIn(state.theme);
state.colors = builtin_colors(state.theme); state.colors = builtin_colors(state.theme);
state.custom_toasts = false;
state.toast_colors = builtin_toast_colors(state.theme);
if matches!( if matches!(
&state.saved_theme_choice, &state.saved_theme_choice,
@@ -1677,17 +1911,71 @@ fn update(state: &mut Moorly, message: Message) -> Task<Message> {
Message::SetFadeSettings(value) => state.fade_settings_draft = value, Message::SetFadeSettings(value) => state.fade_settings_draft = value,
Message::SetHideTabClose(value) => state.hide_tab_close_draft = value, Message::SetHideTabClose(value) => state.hide_tab_close_draft = value,
Message::ToggleAdvanced => state.advanced_open = !state.advanced_open, Message::ToggleAdvanced => state.advanced_open = !state.advanced_open,
Message::OpenColorPicker(option) => state.open_color_picker = Some(option), Message::SetCustomToasts(value) => {
state.custom_toasts = value;
if !value {
state.open_toast_color_picker = None;
}
}
Message::OpenColorPicker(option) => {
state.open_color_picker = Some(option);
state.open_toast_color_picker = None;
}
Message::SubmitColor(option, color) => { Message::SubmitColor(option, color) => {
state.colors[option.index()] = color; state.colors[option.index()] = color;
state.open_color_picker = None; state.open_color_picker = None;
} }
Message::CancelColorPicker => state.open_color_picker = None, Message::OpenToastColorPicker(option) => {
state.open_toast_color_picker = Some(option);
state.open_color_picker = None;
}
Message::SubmitToastColor(option, color) => {
state.toast_colors[option.index()] = color;
state.open_toast_color_picker = None;
}
Message::CancelColorPicker => {
state.open_color_picker = None;
state.open_toast_color_picker = None;
}
Message::SaveSettings => { Message::SaveSettings => {
apply_settings(state); apply_settings(state);
save_config(state); save_config(state);
} }
Message::UndoChanges => undo_settings(state), Message::UndoChanges => undo_settings(state),
Message::Notification(action) => match action {
notifications::Message::Dismiss(id) => state.notifications.dismiss(id),
},
Message::NotificationTick(now) => state.notifications.remove_expired(now),
Message::ShowNotificationDemo => {
use notifications::{Notification, NotificationKind};
state.notifications.add(
Notification::new(NotificationKind::Info, "This is a timed info notification.")
.title("Info"),
);
state.notifications.add(
Notification::new(NotificationKind::Success, "The operation completed successfully.")
.title("Success")
.timed(Duration::from_secs(8)),
);
state.notifications.add(
Notification::new(
NotificationKind::Warning,
"This warning stays until you dismiss it.",
)
.title("Persistent warning")
.persistent(),
);
state.notifications.add(
Notification::new(
NotificationKind::Error,
"This error is persistent as well.\nUse the close button to dismiss it.",
)
.title("Persistent error")
.persistent(),
);
}
Message::Frame(now) => { Message::Frame(now) => {
if !state.fade_animation.is_animating(now) if !state.fade_animation.is_animating(now)
&& !state.fade_animation.value() && !state.fade_animation.value()
@@ -2374,6 +2662,22 @@ fn advanced_panel(state: &Moorly) -> Element<'_, Message> {
rows = rows.push(color_row(state, option)); rows = rows.push(color_row(state, option));
} }
rows = rows.push(rule::horizontal(1));
rows = rows.push(
row![
text("Custom toaster colors"),
space::horizontal(),
toggler(state.custom_toasts).on_toggle(Message::SetCustomToasts),
]
.align_y(Alignment::Center),
);
if state.custom_toasts {
for option in ToastColorOption::ALL {
rows = rows.push(toast_color_row(state, option));
}
}
let actions = match &state.theme_choice { let actions = match &state.theme_choice {
ThemeChoice::BuiltIn(_) => row![ ThemeChoice::BuiltIn(_) => row![
space::horizontal(), space::horizontal(),
@@ -2412,10 +2716,35 @@ fn advanced_panel(state: &Moorly) -> Element<'_, Message> {
.into() .into()
} }
/// One color option: label on the left, clickable swatch on the right. /// One theme color option: label on the left, clickable swatch on the right.
fn color_row(state: &Moorly, option: ColorOption) -> Element<'_, Message> { fn color_row(state: &Moorly, option: ColorOption) -> Element<'_, Message> {
let color = state.colors[option.index()]; color_swatch_row(
option.label(),
state.colors[option.index()],
state.open_color_picker == Some(option),
Message::OpenColorPicker(option),
move |color| Message::SubmitColor(option, color),
)
}
/// One custom-toast color option, using the same swatch control as the theme.
fn toast_color_row(state: &Moorly, option: ToastColorOption) -> Element<'_, Message> {
color_swatch_row(
option.label(),
state.toast_colors[option.index()],
state.open_toast_color_picker == Some(option),
Message::OpenToastColorPicker(option),
move |color| Message::SubmitToastColor(option, color),
)
}
fn color_swatch_row<'a>(
label: &'static str,
color: Color,
open: bool,
on_open: Message,
on_submit: impl Fn(Color) -> Message + 'static,
) -> Element<'a, Message> {
let swatch = container(space::horizontal()) let swatch = container(space::horizontal())
.width(24) .width(24)
.height(24) .height(24)
@@ -2430,19 +2759,19 @@ fn color_row(state: &Moorly, option: ColorOption) -> Element<'_, Message> {
}); });
let button = button(swatch) let button = button(swatch)
.on_press(Message::OpenColorPicker(option)) .on_press(on_open)
.padding(3) .padding(3)
.style(button::text); .style(button::text);
let picker = iced_aw::color_picker( let picker = iced_aw::color_picker(
state.open_color_picker == Some(option), open,
color, color,
button, button,
Message::CancelColorPicker, Message::CancelColorPicker,
move |color| Message::SubmitColor(option, color), on_submit,
); );
row![text(option.label()), space::horizontal(), picker] row![text(label), space::horizontal(), picker]
.align_y(Alignment::Center) .align_y(Alignment::Center)
.into() .into()
} }
@@ -3563,7 +3892,7 @@ fn tab_scroll_limits(state: &Moorly) -> (bool, bool) {
(can_scroll_left, can_scroll_right) (can_scroll_left, can_scroll_right)
} }
fn view(state: &Moorly) -> Element<'_, Message> { fn main_view(state: &Moorly) -> Element<'_, Message> {
// Tab strip: size tabs to the strip's current width so as many as // Tab strip: size tabs to the strip's current width so as many as
// possible fit before scrolling starts. // possible fit before scrolling starts.
let tabs = state.tabs.clone(); let tabs = state.tabs.clone();
@@ -3784,6 +4113,30 @@ fn view(state: &Moorly) -> Element<'_, Message> {
.into() .into()
} }
/// The application content with the notification stack rendered above it.
fn view(state: &Moorly) -> Element<'_, Message> {
let content = main_view(state);
if state.notifications.is_empty() {
return content;
}
let toasts = state
.notifications
.view(
Instant::now(),
state
.custom_toasts
.then(|| notifications::ToastColors::from_array(state.toast_colors)),
)
.map(Message::Notification);
stack![content, toasts]
.width(Length::Fill)
.height(Length::Fill)
.into()
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::{Message, Moorly, Tab, theme, update}; use super::{Message, Moorly, Tab, theme, update};
@@ -3816,7 +4169,10 @@ mod tests {
advanced_open: false, advanced_open: false,
colors: super::DEFAULT_COLORS, colors: super::DEFAULT_COLORS,
saved_colors: super::DEFAULT_COLORS, saved_colors: super::DEFAULT_COLORS,
custom_toasts: false,
toast_colors: super::builtin_toast_colors(theme::Preference::default()),
open_color_picker: None, open_color_picker: None,
open_toast_color_picker: None,
fade_animation: super::new_fade_animation(), fade_animation: super::new_fade_animation(),
hovered_tab: None, hovered_tab: None,
tab_close_fades: Default::default(), tab_close_fades: Default::default(),
@@ -3832,6 +4188,7 @@ mod tests {
tab_offset: 0.0, tab_offset: 0.0,
tab_viewport_width: 0.0, tab_viewport_width: 0.0,
tab_content_width: 0.0, tab_content_width: 0.0,
notifications: super::notifications::NotificationManager::default(),
} }
} }
@@ -3999,6 +4356,14 @@ mod tests {
assert_eq!(state.saved_shortcuts, state.shortcuts); assert_eq!(state.saved_shortcuts, state.shortcuts);
} }
#[test]
fn notification_demo_adds_all_types() {
let mut state = state();
let _ = update(&mut state, Message::ShowNotificationDemo);
assert_eq!(state.notifications.len(), 4);
}
#[test] #[test]
fn long_titles_are_ellipsized_to_max_width() { fn long_titles_are_ellipsized_to_max_width() {
assert_eq!(super::fit_title("Settings"), "Settings"); assert_eq!(super::fit_title("Settings"), "Settings");
@@ -4041,6 +4406,8 @@ mod tests {
theme::Preference::Dark, theme::Preference::Dark,
&colors, &colors,
&super::DEFAULT_COLORS, &super::DEFAULT_COLORS,
true,
&super::builtin_toast_colors(theme::Preference::Dark),
); );
let text = toml::to_string(&file).unwrap(); let text = toml::to_string(&file).unwrap();
@@ -4048,6 +4415,10 @@ mod tests {
assert!(text.contains("based_on = \"dark\"")); assert!(text.contains("based_on = \"dark\""));
assert!(text.contains("accent = \"#010203\"")); assert!(text.contains("accent = \"#010203\""));
assert!(!text.contains("active_tab_outline")); assert!(!text.contains("active_tab_outline"));
assert!(text.contains("[toast]"));
assert!(text.contains("enabled = true"));
assert!(text.contains("background = \"#"));
assert!(file.toast.enabled);
let loaded = file.colors(theme::Preference::Dark); let loaded = file.colors(theme::Preference::Dark);
assert_eq!( assert_eq!(
@@ -4074,6 +4445,48 @@ mod tests {
assert_eq!(state.open_color_picker, None); assert_eq!(state.open_color_picker, None);
} }
#[test]
fn toaster_color_picker_updates_only_toast_colors() {
let mut state = state();
let option = super::ToastColorOption::Info;
let color = iced::Color::from_rgb(0.4, 0.5, 0.6);
let _ = update(&mut state, Message::SetCustomToasts(true));
let _ = update(&mut state, Message::OpenToastColorPicker(option));
assert_eq!(state.open_toast_color_picker, Some(option));
let _ = update(&mut state, Message::SubmitToastColor(option, color));
assert_eq!(state.toast_colors[option.index()], color);
assert_eq!(state.open_toast_color_picker, None);
assert_eq!(state.colors, super::DEFAULT_COLORS);
let _ = update(&mut state, Message::SetCustomToasts(false));
assert!(!state.custom_toasts);
}
#[test]
fn theme_file_round_trips_toast_settings() {
let mut toast = super::builtin_toast_colors(theme::Preference::Dark);
toast[super::ToastColorOption::Background.index()] = iced::Color::from_rgb8(1, 2, 3);
let file = super::ThemeFile::from_colors(
"Test theme".to_owned(),
theme::Preference::Dark,
&super::DEFAULT_COLORS,
&super::DEFAULT_COLORS,
true,
&toast,
);
let text = toml::to_string_pretty(&file).unwrap();
let loaded: super::ThemeFile = toml::from_str(&text).unwrap();
assert!(loaded.toast.enabled);
assert_eq!(
loaded.toast.colors(theme::Preference::Dark)[super::ToastColorOption::Background.index()],
iced::Color::from_rgb8(1, 2, 3)
);
}
#[test] #[test]
fn tab_close_fades_in_and_out() { fn tab_close_fades_in_and_out() {
let mut state = state(); let mut state = state();
+495
View File
@@ -0,0 +1,495 @@
//! Reusable in-app notification manager and toast rendering.
//!
//! The manager owns notification state independently from the widgets that
//! render it, so it can later be shared by more than one window.
use std::time::Duration;
use iced::time::Instant;
use iced::widget::{button, column, container, opaque, responsive, row, scrollable, text};
use iced::{Alignment, Border, Color, Element, Length, Shadow, Theme, Vector};
/// Default lifetime of a timed notification.
pub const DEFAULT_DURATION: Duration = Duration::from_secs(5);
const FADE_IN: Duration = Duration::from_millis(160);
const FADE_OUT: Duration = Duration::from_millis(140);
const MAX_WIDTH: f32 = 340.0;
const MARGIN: f32 = 16.0;
const SPACING: f32 = 8.0;
/// Colors used to render toasts. The defaults follow the active iced theme;
/// a theme can override every field.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ToastColors {
pub background: Color,
pub text: Color,
pub title: Color,
pub border: Color,
pub info: Color,
pub success: Color,
pub warning: Color,
pub error: Color,
pub dismiss: Color,
}
impl ToastColors {
pub fn default_for(theme: &Theme) -> Self {
let palette = theme.extended_palette();
Self {
background: mix(
palette.background.weak.color,
palette.primary.base.color,
0.06,
),
text: palette.background.weak.text,
title: palette.background.weak.text,
border: palette.background.strong.color,
info: palette.primary.base.color,
success: palette.success.base.color,
warning: palette.warning.base.color,
error: palette.danger.base.color,
dismiss: palette.background.weak.text,
}
}
pub fn as_array(self) -> [Color; 9] {
[
self.background,
self.text,
self.title,
self.border,
self.info,
self.success,
self.warning,
self.error,
self.dismiss,
]
}
pub fn from_array(colors: [Color; 9]) -> Self {
Self {
background: colors[0],
text: colors[1],
title: colors[2],
border: colors[3],
info: colors[4],
success: colors[5],
warning: colors[6],
error: colors[7],
dismiss: colors[8],
}
}
}
/// Unique identifier for a notification within a manager.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct NotificationId(u64);
/// The four supported notification severities.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NotificationKind {
Info,
Success,
Warning,
Error,
}
impl NotificationKind {
fn icon(self) -> &'static str {
match self {
Self::Info => "ℹ",
Self::Success => "✓",
Self::Warning => "⚠",
Self::Error => "✕",
}
}
fn accent(self, colors: ToastColors) -> Color {
match self {
Self::Info => colors.info,
Self::Success => colors.success,
Self::Warning => colors.warning,
Self::Error => colors.error,
}
}
}
/// How long a notification stays visible.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NotificationLifetime {
Timed(Duration),
Persistent,
}
impl Default for NotificationLifetime {
fn default() -> Self {
Self::Timed(DEFAULT_DURATION)
}
}
/// A single notification. Create it with [`Notification::new`] and configure
/// it with the builder methods before handing it to a manager.
#[derive(Debug, Clone)]
pub struct Notification {
id: NotificationId,
kind: NotificationKind,
title: Option<String>,
message: String,
lifetime: NotificationLifetime,
born: Instant,
closing: Option<Instant>,
}
impl Notification {
pub fn new(kind: NotificationKind, message: impl Into<String>) -> Self {
Self {
id: NotificationId(0),
kind,
title: None,
message: message.into(),
lifetime: NotificationLifetime::default(),
born: Instant::now(),
closing: None,
}
}
pub fn title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
pub fn persistent(mut self) -> Self {
self.lifetime = NotificationLifetime::Persistent;
self
}
pub fn timed(mut self, duration: Duration) -> Self {
self.lifetime = NotificationLifetime::Timed(duration);
self
}
fn expires_at(&self) -> Option<Instant> {
match self.lifetime {
NotificationLifetime::Timed(duration) => Some(self.born + duration),
NotificationLifetime::Persistent => None,
}
}
fn opacity(&self, now: Instant) -> f32 {
let fade_in = (now.saturating_duration_since(self.born).as_secs_f32()
/ FADE_IN.as_secs_f32())
.clamp(0.0, 1.0);
let fade_out = self
.closing
.map(|at| {
1.0 - (now.saturating_duration_since(at).as_secs_f32() / FADE_OUT.as_secs_f32())
.clamp(0.0, 1.0)
})
.unwrap_or(1.0);
fade_in.min(fade_out)
}
fn is_finished(&self, now: Instant) -> bool {
self.closing
.is_some_and(|at| now.saturating_duration_since(at) >= FADE_OUT)
}
}
/// Owns all live notifications. New entries are inserted at the top.
#[derive(Debug)]
pub struct NotificationManager {
next_id: u64,
notifications: Vec<Notification>,
}
impl Default for NotificationManager {
fn default() -> Self {
Self {
next_id: 1,
notifications: Vec::new(),
}
}
}
impl NotificationManager {
pub fn add(&mut self, notification: Notification) -> NotificationId {
self.add_at(Instant::now(), notification)
}
fn add_at(&mut self, now: Instant, mut notification: Notification) -> NotificationId {
let id = NotificationId(self.next_id);
self.next_id = self.next_id.saturating_add(1);
notification.id = id;
notification.born = now;
notification.closing = None;
self.notifications.insert(0, notification);
id
}
/// Starts dismissing a notification; it is removed after the fade-out.
pub fn dismiss(&mut self, id: NotificationId) {
self.dismiss_at(id, Instant::now());
}
fn dismiss_at(&mut self, id: NotificationId, now: Instant) {
if let Some(notification) = self
.notifications
.iter_mut()
.find(|notification| notification.id == id)
&& notification.closing.is_none()
{
notification.closing = Some(now);
}
}
/// Expires due timed notifications and removes finished fade-outs.
pub fn remove_expired(&mut self, now: Instant) {
for notification in &mut self.notifications {
if notification.closing.is_none()
&& notification.expires_at().is_some_and(|at| now >= at)
{
notification.closing = Some(now);
}
}
self.notifications
.retain(|notification| !notification.is_finished(now));
}
#[allow(dead_code)] // Public manager API for future call sites.
pub fn clear(&mut self) {
self.notifications.clear();
}
pub fn is_empty(&self) -> bool {
self.notifications.is_empty()
}
#[allow(dead_code)] // Public manager API for future call sites.
pub fn len(&self) -> usize {
self.notifications.len()
}
/// Whether another timed notification still needs an expiry timer.
pub fn has_timed(&self) -> bool {
self.notifications.iter().any(|notification| {
notification.closing.is_none()
&& matches!(notification.lifetime, NotificationLifetime::Timed(_))
})
}
/// Whether any notification is fading in or out and needs frame updates.
pub fn is_animating(&self, now: Instant) -> bool {
self.notifications.iter().any(|notification| {
notification.closing.is_some()
|| now.saturating_duration_since(notification.born) < FADE_IN
})
}
/// Renders the toast stack in the bottom-right corner.
pub fn view(&self, now: Instant, colors: Option<ToastColors>) -> Element<'_, Message> {
responsive(move |size| {
let mut list = column![].spacing(SPACING).width(Length::Fill);
for notification in &self.notifications {
let opacity = notification.opacity(now);
if opacity > 0.0 {
list = list.push(toast(notification, opacity, colors));
}
}
let width = (size.width - MARGIN * 2.0).clamp(220.0, MAX_WIDTH);
let max_height = (size.height * 0.6).clamp(160.0, 480.0);
let stack = container(scrollable(list).width(Length::Fill))
.width(Length::Fixed(width))
.max_height(max_height);
container(opaque(stack))
.width(Length::Fill)
.height(Length::Fill)
.align_x(Alignment::End)
.align_y(Alignment::End)
.padding(MARGIN)
.into()
})
.into()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Message {
Dismiss(NotificationId),
}
fn toast(
notification: &Notification,
opacity: f32,
colors: Option<ToastColors>,
) -> Element<'_, Message> {
let kind = notification.kind;
let mut body = column![].spacing(2).width(Length::Fill);
if let Some(title) = &notification.title {
let title = container(text(title).size(14).width(Length::Fill)).style(move |theme| {
let colors = colors.unwrap_or_else(|| ToastColors::default_for(theme));
container::Style {
text_color: Some(colors.title.scale_alpha(opacity)),
..container::Style::default()
}
});
body = body.push(title);
}
body = body.push(text(&notification.message).size(13).width(Length::Fill));
let icon = container(text(kind.icon()).size(16)).style(move |theme| {
let colors = colors.unwrap_or_else(|| ToastColors::default_for(theme));
container::Style {
text_color: Some(kind.accent(colors).scale_alpha(opacity)),
..container::Style::default()
}
});
let dismiss = button(text("✕").size(14))
.on_press(Message::Dismiss(notification.id))
.padding([2, 6])
.style(move |theme, status| dismiss_style(theme, status, opacity, colors));
container(
row![icon, body, dismiss]
.spacing(8)
.align_y(Alignment::Start),
)
.width(Length::Fill)
.padding(10)
.style(move |theme| {
panel_style(
colors.unwrap_or_else(|| ToastColors::default_for(theme)),
opacity,
)
})
.into()
}
fn dismiss_style(
theme: &Theme,
status: button::Status,
opacity: f32,
colors: Option<ToastColors>,
) -> button::Style {
let colors = colors.unwrap_or_else(|| ToastColors::default_for(theme));
let mut style = button::text(theme, status);
style.text_color = colors.dismiss.scale_alpha(opacity);
style
}
fn panel_style(colors: ToastColors, opacity: f32) -> container::Style {
container::Style {
background: Some(colors.background.scale_alpha(opacity).into()),
text_color: Some(colors.text.scale_alpha(opacity)),
border: Border {
color: colors.border.scale_alpha(opacity * 0.7),
width: 1.0,
radius: 6.0.into(),
},
shadow: Shadow {
color: Color::BLACK.scale_alpha(0.18 * opacity),
offset: Vector::new(0.0, 2.0),
blur_radius: 8.0,
},
..container::Style::default()
}
}
fn mix(left: Color, right: Color, amount: f32) -> Color {
Color {
r: left.r + (right.r - left.r) * amount,
g: left.g + (right.g - left.g) * amount,
b: left.b + (right.b - left.b) * amount,
a: left.a + (right.a - left.a) * amount,
}
}
#[cfg(test)]
mod tests {
use super::{
DEFAULT_DURATION, Notification, NotificationKind, NotificationLifetime, NotificationManager,
};
use iced::time::{Duration, Instant};
#[test]
fn new_notifications_are_unique_and_stack_newest_first() {
let mut manager = NotificationManager::default();
let now = Instant::now();
let first = manager.add_at(now, Notification::new(NotificationKind::Info, "first"));
let second = manager.add_at(now, Notification::new(NotificationKind::Error, "second"));
assert_ne!(first, second);
assert_eq!(manager.len(), 2);
assert_eq!(manager.notifications[0].id, second);
assert_eq!(manager.notifications[1].id, first);
}
#[test]
fn timed_notifications_expire_but_persistent_ones_do_not() {
let mut manager = NotificationManager::default();
let now = Instant::now();
let timed = manager.add_at(
now,
Notification::new(NotificationKind::Success, "timed").timed(Duration::from_secs(2)),
);
let persistent = manager.add_at(
now,
Notification::new(NotificationKind::Warning, "persistent").persistent(),
);
manager.remove_expired(now + Duration::from_secs(1));
assert_eq!(manager.len(), 2);
assert!(manager.notifications.iter().any(|n| n.id == timed));
assert!(manager.notifications.iter().any(|n| n.id == persistent));
// Expiry starts a fade-out, then the entry is removed.
manager.remove_expired(now + Duration::from_secs(2));
assert_eq!(manager.len(), 2);
manager.remove_expired(now + Duration::from_secs(3));
assert!(manager.notifications.iter().all(|n| n.id != timed));
assert!(manager.notifications.iter().any(|n| n.id == persistent));
}
#[test]
fn dismissing_starts_the_fade_out_and_clear_removes_everything() {
let mut manager = NotificationManager::default();
let now = Instant::now();
let id = manager.add_at(now, Notification::new(NotificationKind::Info, "hello"));
manager.dismiss_at(id, now);
assert_eq!(manager.len(), 1);
manager.remove_expired(now + Duration::from_secs(1));
assert!(manager.is_empty());
manager.add_at(now, Notification::new(NotificationKind::Info, "one"));
manager.add_at(now, Notification::new(NotificationKind::Info, "two"));
manager.clear();
assert!(manager.is_empty());
}
#[test]
fn default_lifetime_is_five_seconds() {
let notification = Notification::new(NotificationKind::Info, "hello");
assert_eq!(
notification.lifetime,
NotificationLifetime::Timed(DEFAULT_DURATION)
);
}
}