pokeductor 0.1.0

A terminal-based Pokedex and Evolution Analyzer powered by PokeAPI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
//! Application state machine and async orchestration.
//!
//! The UI never blocks: network work is performed in detached `tokio` tasks
//! that report back over an `mpsc` channel. Each spawned task is a *producer*;
//! the main loop in [`App::run`] is the single *consumer*, draining the channel
//! alongside terminal input and a steady animation tick via `tokio::select!`.

use std::collections::{HashMap, HashSet};
use std::time::Duration;

use crossterm::event::{Event, EventStream, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use futures::StreamExt;
use ratatui::widgets::ListState;
use ratatui::DefaultTerminal;
use tokio::sync::mpsc;

use crate::api;
use crate::i18n::Language;
use crate::models::{EvolutionTree, PokemonDetail, PokemonEntry, Sprite};

/// Messages sent from background fetch tasks to the UI loop. The payloads are
/// large but short-lived and low-frequency, so the size difference between
/// variants isn't worth boxing around.
#[allow(clippy::large_enum_variant)]
#[derive(Debug)]
pub enum Message {
    /// The master Pokemon list finished loading.
    ListLoaded(Vec<PokemonEntry>),
    /// A Pokemon's details and evolution chain finished loading.
    PokemonLoaded {
        detail: PokemonDetail,
        evolution: EvolutionTree,
        /// Decoded artwork, if the species had a sprite we could fetch.
        sprite: Option<Sprite>,
    },
    /// A standalone sprite (for an evolution-chain member) finished loading.
    SpriteLoaded {
        name: String,
        sprite: Option<Sprite>,
    },
    /// A machine-translated flavor blurb finished loading.
    FlavorTranslated {
        name: String,
        lang: String,
        text: String,
    },
    /// A background task failed.
    Error(String),
}

/// Which panel currently receives keyboard input.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Focus {
    Search,
    List,
    /// The evolution panel: arrow keys move between chain members and Enter
    /// jumps to the highlighted one.
    Evolution,
}

/// The complete, observable state of the running application.
pub struct App {
    pub language: Language,
    pub all_pokemon: Vec<PokemonEntry>,
    /// Indices into `all_pokemon` that match the current search query.
    pub filtered: Vec<usize>,
    pub list_state: ListState,
    pub query: String,
    pub focus: Focus,
    /// In-memory cache so each Pokemon is fetched at most once per session.
    pub details: HashMap<String, PokemonDetail>,
    pub evolutions: HashMap<String, EvolutionTree>,
    /// Decoded sprites, keyed by Pokemon name. Absent if a species has no art.
    pub sprites: HashMap<String, Sprite>,
    /// Names whose sprite is being fetched on demand for the evolution panel,
    /// so we never queue the same request twice.
    pub sprite_loading: HashSet<String>,
    /// Cursor into the evolution chain (depth-first order) while the evolution
    /// panel is focused.
    pub evo_cursor: usize,
    /// Whether the language-picker card is open, and which row it highlights.
    pub language_picker: bool,
    pub lang_cursor: usize,
    /// Machine-translated flavor blurbs, keyed by `(pokemon name, lang code)`.
    pub translations: HashMap<(String, String), String>,
    /// Translation requests currently in flight, to avoid duplicating work.
    pub translating: HashSet<(String, String)>,
    /// Name of the Pokemon currently shown in the detail panel.
    pub selected_name: Option<String>,
    /// Name currently being fetched, if any (drives the detail spinner).
    pub loading_detail: Option<String>,
    pub list_loading: bool,
    pub error: Option<String>,
    /// Monotonic counter used to animate the loading spinner.
    pub spinner: usize,
    pub should_quit: bool,

    client: reqwest::Client,
    tx: mpsc::Sender<Message>,
}

impl App {
    /// Builds the app and returns it alongside the receiver half of the
    /// message channel (handed back to [`App::run`]).
    pub fn new() -> anyhow::Result<(Self, mpsc::Receiver<Message>)> {
        let client = api::build_client()?;
        let (tx, rx) = mpsc::channel(64);
        let app = App {
            language: Language::English,
            all_pokemon: Vec::new(),
            filtered: Vec::new(),
            list_state: ListState::default(),
            query: String::new(),
            focus: Focus::List,
            details: HashMap::new(),
            evolutions: HashMap::new(),
            sprites: HashMap::new(),
            sprite_loading: HashSet::new(),
            evo_cursor: 0,
            language_picker: false,
            lang_cursor: 0,
            translations: HashMap::new(),
            translating: HashSet::new(),
            selected_name: None,
            loading_detail: None,
            list_loading: false,
            error: None,
            spinner: 0,
            should_quit: false,
            client,
            tx,
        };
        Ok((app, rx))
    }

    /// The main event loop. Owns the terminal and runs until the user quits.
    pub async fn run(
        mut self,
        mut terminal: DefaultTerminal,
        mut rx: mpsc::Receiver<Message>,
    ) -> anyhow::Result<()> {
        self.fetch_list();

        let mut events = EventStream::new();
        let mut ticker = tokio::time::interval(Duration::from_millis(120));

        while !self.should_quit {
            // Cheap, idempotent: requests a translation only when the current
            // selection+language needs one and none is cached or in flight.
            self.ensure_translation();
            terminal.draw(|frame| crate::ui::render(frame, &mut self))?;

            tokio::select! {
                maybe_msg = rx.recv() => {
                    if let Some(msg) = maybe_msg {
                        self.handle_message(msg);
                    }
                }
                maybe_event = events.next() => {
                    match maybe_event {
                        Some(Ok(event)) => self.handle_event(event),
                        Some(Err(_)) => {} // transient read error: ignore and redraw
                        None => self.should_quit = true,
                    }
                }
                _ = ticker.tick() => {
                    self.spinner = self.spinner.wrapping_add(1);
                }
            }
        }
        Ok(())
    }

    // --- Async fetch dispatch --------------------------------------------

    fn fetch_list(&mut self) {
        self.list_loading = true;
        let tx = self.tx.clone();
        let client = self.client.clone();
        tokio::spawn(async move {
            let msg = match api::fetch_pokemon_list(&client).await {
                Ok(list) => Message::ListLoaded(list),
                Err(err) => Message::Error(err.to_string()),
            };
            let _ = tx.send(msg).await;
        });
    }

    /// Loads (or reveals from cache) the currently highlighted Pokemon.
    fn request_selected(&mut self) {
        let Some(name) = self.current_name() else {
            return;
        };
        self.error = None;
        self.selected_name = Some(name.clone());

        // Cache hit: nothing to fetch, but make sure the chain sprites are on
        // their way (they may not have been requested yet).
        if self.details.contains_key(&name) {
            self.loading_detail = None;
            self.ensure_chain_sprites();
            return;
        }

        self.loading_detail = Some(name.clone());
        let tx = self.tx.clone();
        let client = self.client.clone();
        tokio::spawn(async move {
            let msg = match api::fetch_pokemon_bundle(&client, &name).await {
                Ok((detail, evolution, sprite)) => {
                    Message::PokemonLoaded { detail, evolution, sprite }
                }
                Err(err) => Message::Error(err.to_string()),
            };
            let _ = tx.send(msg).await;
        });
    }

    /// Requests a machine translation of the selected Pokemon's flavor text when
    /// the active language has no native PokeAPI entry (e.g. Turkish) and we
    /// haven't already translated or queued it.
    fn ensure_translation(&mut self) {
        let code = self.language.flavor_code();
        if code == "en" {
            return; // English is always the source; nothing to translate
        }
        // Gather what we need under a short immutable borrow, then release it.
        let (name, source) = {
            let Some(detail) = self.selected_detail() else {
                return;
            };
            if detail.flavors.contains_key(code) {
                return; // PokeAPI already has this language natively
            }
            match detail.flavors.get("en") {
                Some(src) => (detail.name.clone(), src.clone()),
                None => return, // no English source to translate from
            }
        };

        let key = (name.clone(), code.to_string());
        if self.translations.contains_key(&key) || self.translating.contains(&key) {
            return;
        }
        self.translating.insert(key);

        let tx = self.tx.clone();
        let client = self.client.clone();
        let lang = code.to_string();
        tokio::spawn(async move {
            // On failure we simply never send: the UI keeps the English text and
            // the in-flight flag stops us from hammering a rate-limited service.
            if let Ok(text) = api::translate_text(&client, &source, "en", &lang).await {
                let _ = tx.send(Message::FlavorTranslated { name, lang, text }).await;
            }
        });
    }

    /// A cached machine translation for `name` in `code`, if one exists.
    pub fn translation_for(&self, name: &str, code: &str) -> Option<&str> {
        self.translations
            .get(&(name.to_string(), code.to_string()))
            .map(String::as_str)
    }

    /// The names in the current evolution chain, depth-first. Empty if no
    /// evolution data is loaded for the selection.
    pub fn chain_names(&self) -> Vec<String> {
        let mut names = Vec::new();
        if let Some(tree) = self.selected_evolution() {
            tree.collect_names(&mut names);
        }
        names
    }

    /// Kicks off sprite fetches for every member of the current chain that isn't
    /// already cached or in flight, so the evolution panel can show its artwork.
    fn ensure_chain_sprites(&mut self) {
        for name in self.chain_names() {
            if self.sprites.contains_key(&name) || self.sprite_loading.contains(&name) {
                continue;
            }
            self.sprite_loading.insert(name.clone());
            let tx = self.tx.clone();
            let client = self.client.clone();
            tokio::spawn(async move {
                let msg = match api::fetch_named_sprite(&client, &name).await {
                    Ok(sprite) => Message::SpriteLoaded { name, sprite },
                    // A failed chain sprite is non-fatal: report no art so the
                    // panel shows a placeholder instead of an error banner.
                    Err(_) => Message::SpriteLoaded { name, sprite: None },
                };
                let _ = tx.send(msg).await;
            });
        }
    }

    /// Loads the chain member currently under the evolution cursor — the quick
    /// "jump to my next evolution" action.
    fn jump_to_evolution_member(&mut self) {
        let names = self.chain_names();
        let Some(name) = names.get(self.evo_cursor).cloned() else {
            return;
        };
        // Make sure the target is visible in the list and selected there, so the
        // sidebar stays in sync with the detail panel.
        self.query.clear();
        self.recompute_filter();
        if let Some(abs) = self.all_pokemon.iter().position(|p| p.name == name) {
            if let Some(pos) = self.filtered.iter().position(|&i| i == abs) {
                self.list_state.select(Some(pos));
            }
        }
        self.request_selected();
    }

    // --- Message handling ------------------------------------------------

    fn handle_message(&mut self, msg: Message) {
        match msg {
            Message::ListLoaded(list) => {
                self.all_pokemon = list;
                self.list_loading = false;
                self.recompute_filter();
            }
            Message::PokemonLoaded { detail, evolution, sprite } => {
                let name = detail.name.clone();
                if self.loading_detail.as_deref() == Some(name.as_str()) {
                    self.loading_detail = None;
                }
                self.evolutions.insert(name.clone(), evolution);
                if let Some(sprite) = sprite {
                    self.sprites.insert(name.clone(), sprite);
                }
                let is_selected = self.selected_name.as_deref() == Some(name.as_str());
                self.details.insert(name, detail);
                // Now that the chain is known, fetch its members' sprites for
                // the evolution panel.
                if is_selected {
                    self.ensure_chain_sprites();
                }
            }
            Message::SpriteLoaded { name, sprite } => {
                self.sprite_loading.remove(&name);
                if let Some(sprite) = sprite {
                    self.sprites.insert(name, sprite);
                }
            }
            Message::FlavorTranslated { name, lang, text } => {
                let key = (name, lang);
                self.translating.remove(&key);
                self.translations.insert(key, text);
            }
            Message::Error(err) => {
                self.error = Some(err);
                self.loading_detail = None;
                self.list_loading = false;
            }
        }
    }

    // --- Input handling --------------------------------------------------

    fn handle_event(&mut self, event: Event) {
        let Event::Key(key) = event else {
            return; // resize/mouse: the next draw already adapts
        };
        if key.kind != KeyEventKind::Press {
            return;
        }
        // Ctrl-C always quits, regardless of focus.
        if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
            self.should_quit = true;
            return;
        }
        // The language picker is modal: it grabs all input while open.
        if self.language_picker {
            self.handle_language_key(key);
            return;
        }
        match self.focus {
            Focus::List => self.handle_list_key(key),
            Focus::Search => self.handle_search_key(key),
            Focus::Evolution => self.handle_evolution_key(key),
        }
    }

    /// Opens the language picker, parking the cursor on the active language.
    fn open_language_picker(&mut self) {
        self.lang_cursor = self.language.index();
        self.language_picker = true;
    }

    fn handle_language_key(&mut self, key: KeyEvent) {
        let len = Language::ALL.len();
        match key.code {
            KeyCode::Esc => self.language_picker = false,
            KeyCode::Up | KeyCode::Char('k') => {
                self.lang_cursor = (self.lang_cursor + len - 1) % len;
            }
            KeyCode::Down | KeyCode::Char('j') => {
                self.lang_cursor = (self.lang_cursor + 1) % len;
            }
            KeyCode::Enter | KeyCode::Char(' ') | KeyCode::Char('l') | KeyCode::Char('L') => {
                self.language = Language::ALL[self.lang_cursor];
                self.language_picker = false;
            }
            _ => {}
        }
    }

    fn handle_list_key(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Char('q') | KeyCode::Char('Q') | KeyCode::Esc => self.should_quit = true,
            KeyCode::Up | KeyCode::Char('k') => self.move_selection(-1),
            KeyCode::Down | KeyCode::Char('j') => self.move_selection(1),
            KeyCode::PageUp => self.move_selection(-10),
            KeyCode::PageDown => self.move_selection(10),
            KeyCode::Enter => self.request_selected(),
            KeyCode::Char('e') | KeyCode::Char('E') => self.focus_evolution(),
            KeyCode::Tab | KeyCode::Char('/') => self.focus = Focus::Search,
            KeyCode::Char('l') | KeyCode::Char('L') => self.open_language_picker(),
            _ => {}
        }
    }

    /// Moves focus into the evolution panel, parking the cursor on the species
    /// currently shown in the detail panel.
    fn focus_evolution(&mut self) {
        let names = self.chain_names();
        if names.is_empty() {
            return; // no chain to navigate yet
        }
        self.evo_cursor = self
            .selected_name
            .as_ref()
            .and_then(|sel| names.iter().position(|n| n == sel))
            .unwrap_or(0);
        self.focus = Focus::Evolution;
    }

    fn handle_evolution_key(&mut self, key: KeyEvent) {
        let len = self.chain_names().len();
        match key.code {
            KeyCode::Esc | KeyCode::Tab => self.focus = Focus::List,
            KeyCode::Char('q') | KeyCode::Char('Q') => self.should_quit = true,
            KeyCode::Left | KeyCode::Up | KeyCode::Char('h') | KeyCode::Char('k')
                if self.evo_cursor > 0 =>
            {
                self.evo_cursor -= 1;
            }
            KeyCode::Right | KeyCode::Down | KeyCode::Char('l') | KeyCode::Char('j')
                if self.evo_cursor + 1 < len =>
            {
                self.evo_cursor += 1;
            }
            KeyCode::Enter => self.jump_to_evolution_member(),
            _ => {}
        }
    }

    fn handle_search_key(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Esc | KeyCode::Tab => self.focus = Focus::List,
            KeyCode::Enter => {
                self.request_selected();
                self.focus = Focus::List;
            }
            KeyCode::Up => self.move_selection(-1),
            KeyCode::Down => self.move_selection(1),
            KeyCode::Backspace => {
                self.query.pop();
                self.recompute_filter();
            }
            KeyCode::Char(c) => {
                self.query.push(c);
                self.recompute_filter();
            }
            _ => {}
        }
    }

    // --- List / filter helpers -------------------------------------------

    fn recompute_filter(&mut self) {
        let query = self.query.to_lowercase();
        self.filtered = self
            .all_pokemon
            .iter()
            .enumerate()
            .filter(|(_, p)| query.is_empty() || p.name.to_lowercase().contains(&query))
            .map(|(idx, _)| idx)
            .collect();

        if self.filtered.is_empty() {
            self.list_state.select(None);
        } else {
            let clamped = self
                .list_state
                .selected()
                .unwrap_or(0)
                .min(self.filtered.len() - 1);
            self.list_state.select(Some(clamped));
        }
    }

    fn move_selection(&mut self, delta: i32) {
        if self.filtered.is_empty() {
            return;
        }
        let len = self.filtered.len() as i32;
        let current = self.list_state.selected().unwrap_or(0) as i32;
        let next = (current + delta).rem_euclid(len);
        self.list_state.select(Some(next as usize));
    }

    /// Raw API name of the highlighted list entry, if any.
    pub fn current_name(&self) -> Option<String> {
        let selected = self.list_state.selected()?;
        let idx = *self.filtered.get(selected)?;
        self.all_pokemon.get(idx).map(|p| p.name.clone())
    }

    /// Detail record for the panel, if the selection is loaded.
    pub fn selected_detail(&self) -> Option<&PokemonDetail> {
        let name = self.selected_name.as_ref()?;
        self.details.get(name)
    }

    /// Evolution tree for the selected Pokemon, if loaded.
    pub fn selected_evolution(&self) -> Option<&EvolutionTree> {
        let name = self.selected_name.as_ref()?;
        self.evolutions.get(name)
    }

    /// Decoded sprite for the selected Pokemon, if one was loaded.
    pub fn selected_sprite(&self) -> Option<&Sprite> {
        let name = self.selected_name.as_ref()?;
        self.sprites.get(name)
    }

    /// True while the detail panel is awaiting its current selection.
    pub fn detail_is_loading(&self) -> bool {
        match (&self.loading_detail, &self.selected_name) {
            (Some(loading), Some(selected)) => loading == selected,
            _ => false,
        }
    }
}