Files
arena-tracker/crates/app/src/settings.rs
T
nessar 797b7e83e0
CI / core (pull_request) Successful in 1m9s
Address title-bar review findings (#24)
2026-11-18 23:24:23 +01:00

372 lines
13 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! The first-launch Riot API key prompt and the settings view.
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;
use arena_tracker_core::{Config, Error, Preferences, RiotApi, ThemePreference};
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::input::{Input, InputEvent, InputState};
use gpui_kit::component::radio::RadioGroup;
use gpui_kit::component::switch::Switch;
use gpui_kit::component::{ActiveTheme as _, StyledExt as _, Theme, ThemeMode};
use gpui_kit::*;
use crate::tray::{Tray, UNAVAILABLE};
const PLACEHOLDER_SAVED: &str = "Clé enregistrée";
const PLACEHOLDER_EMPTY: &str = "Clé API Riot";
const THEMES: [(ThemePreference, &str); 3] = [
(ThemePreference::System, "Système"),
(ThemePreference::Light, "Clair"),
(ThemePreference::Dark, "Sombre"),
];
fn theme_mode(preference: ThemePreference, system: ThemeMode) -> ThemeMode {
match preference {
ThemePreference::System => system,
ThemePreference::Light => ThemeMode::Light,
ThemePreference::Dark => ThemeMode::Dark,
}
}
pub fn apply_theme(preference: ThemePreference, window: &mut Window, cx: &mut App) {
let mode = theme_mode(preference, ThemeMode::from(window.appearance()));
if cx.theme().mode != mode {
Theme::change(mode, Some(window), cx);
}
}
/// The local config file and the running Riot client that uses its key.
pub struct KeyStore {
path: PathBuf,
config: Config,
api: Arc<RiotApi>,
}
impl KeyStore {
pub fn new(path: PathBuf, config: Config, api: Arc<RiotApi>) -> KeyStore {
KeyStore { path, config, api }
}
pub fn has_key(&self) -> bool {
!self.config.riot_api_key.is_empty()
}
/// Writes the key to the config file and hands it to the Riot client, no restart needed.
fn save(&mut self, key: &str) -> Result<(), Error> {
let previous = std::mem::replace(&mut self.config.riot_api_key, key.to_string());
if let Err(e) = self.config.save(&self.path) {
self.config.riot_api_key = previous;
return Err(e);
}
self.api.set_key(key.to_string());
Ok(())
}
fn save_preferences(&mut self, preferences: Preferences) -> Result<(), Error> {
let previous = std::mem::replace(&mut self.config.preferences, preferences);
if let Err(error) = self.config.save(&self.path) {
self.config.preferences = previous;
return Err(error);
}
Ok(())
}
}
pub enum KeyEvent {
Saved,
Back,
}
pub struct KeyForm {
store: KeyStore,
input: Entity<InputState>,
scroll: ScrollHandle,
key_focus: FocusHandle,
preferences_focus: FocusHandle,
/// The first-launch prompt (no key and nothing stored yet) has no way back.
first_launch: bool,
error: Option<String>,
preference_error: Option<&'static str>,
tray: Option<Rc<Tray>>,
_subscriptions: [Subscription; 4],
}
impl EventEmitter<KeyEvent> for KeyForm {}
impl KeyForm {
pub fn has_key(&self) -> bool {
self.store.has_key()
}
pub fn new(
store: KeyStore,
first_launch: bool,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let preferences = store.config.preferences;
apply_theme(preferences.theme, window, cx);
let tray = Tray::install_saved(window, preferences.close_to_tray, cx);
let appearance = cx.observe_window_appearance(window, |this, window, cx| {
apply_theme(this.store.config.preferences.theme, window, cx);
});
let placeholder = if store.has_key() {
PLACEHOLDER_SAVED
} else {
PLACEHOLDER_EMPTY
};
let input = cx.new(|cx| {
InputState::new(window, cx)
.masked(true)
.placeholder(placeholder)
});
let subscription =
cx.subscribe_in(&input, window, |this, _, event: &InputEvent, window, cx| {
if matches!(event, InputEvent::PressEnter { .. }) {
this.save(window, cx);
}
});
let key_focus = cx.focus_handle();
let preferences_focus = cx.focus_handle();
let reveal_key = cx.on_focus_in(&key_focus, window, |this, window, cx| {
if this.scroll.max_offset().y > px(0.) {
this.scroll.scroll_to_bottom();
window.defer(cx, |window, _| window.refresh());
}
});
let reveal_preferences = cx.on_focus_in(&preferences_focus, window, |this, window, cx| {
if this.scroll.offset().y < px(0.) {
this.scroll.set_offset(point(px(0.), px(0.)));
window.defer(cx, |window, _| window.refresh());
}
});
KeyForm {
first_launch,
store,
input,
scroll: ScrollHandle::new(),
key_focus,
preferences_focus,
error: None,
preference_error: None,
tray,
_subscriptions: [subscription, appearance, reveal_key, reveal_preferences],
}
}
/// Back to an empty field, as when the form is opened again.
pub fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.error = None;
self.preference_error = None;
self.scroll.set_offset(point(px(0.), px(0.)));
self.clear(window, cx);
cx.notify();
}
fn set_preferences(
&mut self,
preferences: Preferences,
window: &mut Window,
cx: &mut Context<Self>,
) {
let previous = self.store.config.preferences;
if previous == preferences {
return;
}
if preferences.close_to_tray && !previous.close_to_tray {
self.tray = Tray::install(window, cx);
if self.tray.is_none() {
self.preference_error = Some(UNAVAILABLE);
cx.notify();
return;
}
}
self.preference_error = if self.store.save_preferences(preferences).is_err() {
Some("Impossible d’enregistrer les préférences.")
} else {
apply_theme(preferences.theme, window, cx);
None
};
if !self.store.config.preferences.close_to_tray
&& let Some(tray) = self.tray.take()
{
tray.uninstall();
}
cx.notify();
}
fn preferences(&self, cx: &mut Context<Self>) -> impl IntoElement {
let preferences = self.store.config.preferences;
let danger = cx.theme().danger;
div()
.id("preferences")
.track_focus(&self.preferences_focus)
.v_flex()
.gap_3()
.child(
Switch::new("close-to-tray")
.label("Fermer dans la zone de notification")
.checked(preferences.close_to_tray)
.on_change(cx.listener(|this, enabled, window, cx| {
this.set_preferences(
Preferences {
close_to_tray: *enabled,
..this.store.config.preferences
},
window,
cx,
);
})),
)
.child(
div().v_flex().gap_1().child("Thème").child(
RadioGroup::horizontal("theme")
.children(THEMES.map(|(_, label)| label))
.selected_index(
THEMES
.iter()
.position(|(theme, _)| *theme == preferences.theme),
)
.on_change(cx.listener(|this, index: &usize, window, cx| {
this.set_preferences(
Preferences {
theme: THEMES[*index].0,
..this.store.config.preferences
},
window,
cx,
);
})),
),
)
.children(
self.preference_error
.map(|error| div().text_color(danger).child(error)),
)
}
fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let placeholder = if self.store.has_key() {
PLACEHOLDER_SAVED
} else {
PLACEHOLDER_EMPTY
};
self.input.update(cx, |input, cx| {
input.set_value("", window, cx);
input.set_placeholder(placeholder, window, cx);
});
}
fn save(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let key = self.input.read(cx).value();
let key = key.trim();
if key.is_empty() {
self.error = Some("Saisissez une clé API.".into());
} else {
match self.store.save(key) {
Ok(()) => {
self.error = None;
self.first_launch = false;
self.clear(window, cx);
cx.emit(KeyEvent::Saved);
}
Err(e) => self.error = Some(format!("Enregistrement impossible : {e}")),
}
}
cx.notify();
}
}
impl Render for KeyForm {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let (title, explanation) = if self.first_launch {
(
"Clé API Riot",
"Une clé API Riot est nécessaire pour importer vos Parties : demandez-en une sur le portail développeur Riot (developer.riotgames.com). Elle reste enregistrée sur cet ordinateur.",
)
} else {
(
"Paramètres",
"Saisissez une nouvelle clé API Riot pour remplacer celle qui est enregistrée. Elle reste enregistrée sur cet ordinateur.",
)
};
let (muted, danger) = (cx.theme().muted_foreground, cx.theme().danger);
let buttons = div()
.h_flex()
.gap_2()
.child(
Button::new("save")
.primary()
.label(if self.first_launch {
"Enregistrer"
} else {
"Enregistrer la clé"
})
.on_click(cx.listener(|this, _, window, cx| this.save(window, cx))),
)
.children((!self.first_launch).then(|| {
Button::new("back")
.label("Retour")
.on_click(cx.listener(|_, _, _, cx| cx.emit(KeyEvent::Back)))
}));
let fields = div()
.v_flex()
.w(px(520.))
.max_w_full()
.px_4()
.gap_3()
.child(
div()
.text_xl()
.font_weight(FontWeight::SEMIBOLD)
.child(title),
)
.children((!self.first_launch).then(|| self.preferences(cx)))
.child(div().text_color(muted).child(explanation))
.child(
div()
.id("key-form-controls")
.track_focus(&self.key_focus)
.v_flex()
.gap_3()
.child(Input::new(&self.input).mask_toggle())
.children(
self.error
.clone()
.map(|error| div().text_color(danger).child(error)),
)
.child(buttons),
);
div()
.id("key-form")
.size_full()
.overflow_y_scroll()
.track_scroll(&self.scroll)
.child(
div()
.v_flex()
.min_h_full()
.items_center()
.justify_center()
.py_4()
.child(fields),
)
}
}
#[cfg(test)]
mod tests {
use super::{ThemeMode, ThemePreference, theme_mode};
#[test]
fn system_tracks_the_current_appearance_and_manual_choices_override_it() {
for system in [ThemeMode::Light, ThemeMode::Dark] {
assert_eq!(theme_mode(ThemePreference::System, system), system);
assert_eq!(theme_mode(ThemePreference::Light, system), ThemeMode::Light);
assert_eq!(theme_mode(ThemePreference::Dark, system), ThemeMode::Dark);
}
}
}