audium 0.8.0

A terminal music app
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
use crossterm::event::KeyCode;
use ratatui::{
    Frame,
    layout::{Alignment, Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, BorderType, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap},
};

use crate::library::{PlaylistId, TrackId};

// ── Colour palette (kept in sync with ui/) ─────────────────────────────────
const BG: Color = Color::Rgb(18, 18, 18);
const ACCENT: Color = Color::Rgb(100, 180, 255);
const SUBTLE: Color = Color::Rgb(80, 80, 80);
const TEXT: Color = Color::White;
const TEXT_DIM: Color = Color::Rgb(179, 179, 179);
const DANGER: Color = Color::Rgb(255, 80, 80);

// ── Text-input widget (shared by rename / new-playlist modals) ─────────────

#[derive(Debug, Default, Clone)]
pub struct TextInput {
    pub value: String,
    pub cursor: usize, // byte offset
}

impl TextInput {
    pub fn with_value(v: impl Into<String>) -> Self {
        let value = v.into();
        let cursor = value.len();
        Self { value, cursor }
    }

    pub fn push(&mut self, c: char) {
        self.value.insert(self.cursor, c);
        self.cursor += c.len_utf8();
    }

    pub fn backspace(&mut self) {
        if self.cursor == 0 {
            return;
        }
        // Step back one char boundary.
        let mut new_cursor = self.cursor - 1;
        while !self.value.is_char_boundary(new_cursor) {
            new_cursor -= 1;
        }
        self.value.remove(new_cursor);
        self.cursor = new_cursor;
    }

    pub fn move_left(&mut self) {
        if self.cursor == 0 {
            return;
        }
        let mut c = self.cursor - 1;
        while !self.value.is_char_boundary(c) {
            c -= 1;
        }
        self.cursor = c;
    }

    pub fn move_right(&mut self) {
        if self.cursor >= self.value.len() {
            return;
        }
        let mut c = self.cursor + 1;
        while !self.value.is_char_boundary(c) {
            c += 1;
        }
        self.cursor = c;
    }
}

// ── What action to take on a confirmed removal ────────────────────────────

#[derive(Debug, Clone)]
pub enum RemoveTarget {
    TrackFromQueue { queue_idx: usize },
    TrackFromLibrary { track_id: TrackId },
    Playlist { playlist_id: PlaylistId },
}

// ── Modal variants ─────────────────────────────────────────────────────────

#[derive(Debug, Clone)]
pub enum Modal {
    /// Brief notification: a track was added to the library.
    TrackAdded { name: String },

    /// Confirm before a destructive removal.
    ConfirmRemove {
        /// Human-readable description shown in the prompt.
        description: String,
        target: RemoveTarget,
    },

    /// Rename a track (library) or a playlist.
    Rename {
        /// "Track" | "Playlist"
        kind: String,
        id: u64,
        input: TextInput,
    },

    /// Create a new playlist.
    NewPlaylist { input: TextInput },

    /// Choose which playlist to add the selected track into.
    AddToPlaylist {
        track_id: TrackId,
        track_name: String,
        /// (id, name) pairs for every user playlist.
        choices: Vec<(PlaylistId, String)>,
        cursor: usize,
    },

    /// Full keybinding reference.
    Help,
}

/// Outcome returned from `Modal::handle_key`.
pub enum ModalOutcome {
    /// Modal handled the key; no further processing needed.
    Consumed,
    /// User confirmed.  Inner value carries semantic data for `AppState`.
    Confirm(ModalConfirm),
    /// User dismissed (Esc / q).
    Dismissed,
}

/// What `AppState` needs to act on when a modal is confirmed.
#[derive(Debug)]
#[allow(dead_code)]
pub enum ModalConfirm {
    Remove(RemoveTarget),
    Rename {
        kind: String,
        id: u64,
        new_name: String,
    },
    NewPlaylist {
        name: String,
    },
    AddToPlaylist {
        track_id: TrackId,
        playlist_id: PlaylistId,
    },
    /// Nothing to act on (e.g. TrackAdded notification just dismissed).
    None,
}

// ── Input handling ─────────────────────────────────────────────────────────

impl Modal {
    /// Returns the outcome of handling a keypress for this modal.
    pub fn handle_key(&mut self, code: KeyCode) -> ModalOutcome {
        match self {
            // ── Informational: any key dismisses ─────────────────────────
            Modal::TrackAdded { .. } | Modal::Help => ModalOutcome::Dismissed,

            // ── Confirm/cancel ────────────────────────────────────────────
            Modal::ConfirmRemove { target, .. } => match code {
                KeyCode::Char('y') | KeyCode::Char('Y') => {
                    ModalOutcome::Confirm(ModalConfirm::Remove(target.clone()))
                }
                KeyCode::Esc | KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Char('q') => {
                    ModalOutcome::Dismissed
                }
                _ => ModalOutcome::Consumed,
            },

            // ── Text inputs ───────────────────────────────────────────────
            Modal::Rename { kind, id, input } => match code {
                KeyCode::Enter => {
                    let name = input.value.trim().to_string();
                    if name.is_empty() {
                        return ModalOutcome::Consumed;
                    }
                    ModalOutcome::Confirm(ModalConfirm::Rename {
                        kind: kind.clone(),
                        id: *id,
                        new_name: name,
                    })
                }
                KeyCode::Esc => ModalOutcome::Dismissed,
                KeyCode::Char(c) => {
                    input.push(c);
                    ModalOutcome::Consumed
                }
                KeyCode::Backspace => {
                    input.backspace();
                    ModalOutcome::Consumed
                }
                KeyCode::Left => {
                    input.move_left();
                    ModalOutcome::Consumed
                }
                KeyCode::Right => {
                    input.move_right();
                    ModalOutcome::Consumed
                }
                _ => ModalOutcome::Consumed,
            },

            Modal::NewPlaylist { input } => match code {
                KeyCode::Enter => {
                    let name = input.value.trim().to_string();
                    if name.is_empty() {
                        return ModalOutcome::Consumed;
                    }
                    ModalOutcome::Confirm(ModalConfirm::NewPlaylist { name })
                }
                KeyCode::Esc => ModalOutcome::Dismissed,
                KeyCode::Char(c) => {
                    input.push(c);
                    ModalOutcome::Consumed
                }
                KeyCode::Backspace => {
                    input.backspace();
                    ModalOutcome::Consumed
                }
                KeyCode::Left => {
                    input.move_left();
                    ModalOutcome::Consumed
                }
                KeyCode::Right => {
                    input.move_right();
                    ModalOutcome::Consumed
                }
                _ => ModalOutcome::Consumed,
            },

            // ── List selection ────────────────────────────────────────────
            Modal::AddToPlaylist {
                choices,
                cursor,
                track_id,
                ..
            } => match code {
                KeyCode::Char('j') | KeyCode::Down => {
                    if !choices.is_empty() {
                        *cursor = (*cursor + 1).min(choices.len() - 1);
                    }
                    ModalOutcome::Consumed
                }
                KeyCode::Char('k') | KeyCode::Up => {
                    *cursor = cursor.saturating_sub(1);
                    ModalOutcome::Consumed
                }
                KeyCode::Enter => {
                    if let Some((playlist_id, _)) = choices.get(*cursor) {
                        ModalOutcome::Confirm(ModalConfirm::AddToPlaylist {
                            track_id: *track_id,
                            playlist_id: *playlist_id,
                        })
                    } else {
                        ModalOutcome::Dismissed
                    }
                }
                KeyCode::Esc | KeyCode::Char('q') => ModalOutcome::Dismissed,
                _ => ModalOutcome::Consumed,
            },
        }
    }
}

// ── Rendering ──────────────────────────────────────────────────────────────

/// Renders `modal` as a centered overlay on top of whatever was drawn already.
pub fn render_modal(frame: &mut Frame, modal: &Modal) {
    match modal {
        Modal::TrackAdded { name } => {
            render_notification(
                frame,
                "Track Added",
                &format!("\"{}\" added to library.", name),
            );
        }
        Modal::Help => render_help(frame),
        Modal::ConfirmRemove { description, .. } => {
            render_confirm(frame, description);
        }
        Modal::Rename { kind, input, .. } => {
            render_text_input(frame, &format!("Rename {}", kind), input);
        }
        Modal::NewPlaylist { input } => {
            render_text_input(frame, "New Playlist", input);
        }
        Modal::AddToPlaylist {
            track_name,
            choices,
            cursor,
            ..
        } => {
            render_playlist_picker(frame, track_name, choices, *cursor);
        }
    }
}

// ── Overlay helpers ────────────────────────────────────────────────────────

/// Returns a centred `Rect` that is `width` × `height` within `area`.
fn centered_rect(width: u16, height: u16, area: Rect) -> Rect {
    let x = area.x + area.width.saturating_sub(width) / 2;
    let y = area.y + area.height.saturating_sub(height) / 2;
    Rect {
        x,
        y,
        width: width.min(area.width),
        height: height.min(area.height),
    }
}

fn modal_block(title: &str) -> Block<'_> {
    Block::default()
        .title(format!(" {} ", title))
        .title_alignment(Alignment::Center)
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(ACCENT))
        .style(Style::default().bg(BG))
}

fn render_notification(frame: &mut Frame, title: &str, message: &str) {
    let area = frame.area();
    let rect = centered_rect(50, 5, area);
    frame.render_widget(Clear, rect);
    frame.render_widget(
        Paragraph::new(vec![
            Line::from(""),
            Line::from(Span::styled(message, Style::default().fg(TEXT))),
            Line::from(Span::styled(
                "Press any key to dismiss",
                Style::default().fg(TEXT_DIM),
            )),
        ])
        .alignment(Alignment::Center)
        .block(modal_block(title)),
        rect,
    );
}

fn render_confirm(frame: &mut Frame, description: &str) {
    let area = frame.area();
    let rect = centered_rect(52, 7, area);
    frame.render_widget(Clear, rect);
    frame.render_widget(
        Paragraph::new(vec![
            Line::from(""),
            Line::from(Span::styled(description, Style::default().fg(TEXT))),
            Line::from(""),
            Line::from(vec![
                Span::styled(
                    "[Y]",
                    Style::default().fg(DANGER).add_modifier(Modifier::BOLD),
                ),
                Span::styled(" confirm    ", Style::default().fg(TEXT_DIM)),
                Span::styled("[N / Esc]", Style::default().fg(ACCENT)),
                Span::styled(" cancel", Style::default().fg(TEXT_DIM)),
            ]),
        ])
        .alignment(Alignment::Center)
        .wrap(Wrap { trim: true })
        .block(modal_block("Confirm")),
        rect,
    );
}

fn render_text_input(frame: &mut Frame, title: &str, input: &TextInput) {
    let area = frame.area();
    let rect = centered_rect(52, 7, area);
    frame.render_widget(Clear, rect);

    let block = modal_block(title);
    let inner = block.inner(rect);
    frame.render_widget(block, rect);

    let rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1),
            Constraint::Length(1),
            Constraint::Length(1),
        ])
        .split(inner);

    frame.render_widget(
        Paragraph::new(Span::styled("Enter name:", Style::default().fg(TEXT_DIM))),
        rows[0],
    );

    // Input field with a fake cursor drawn as a block character.
    let before = &input.value[..input.cursor];
    let after = &input.value[input.cursor..];
    let spans = vec![
        Span::styled(before.to_string(), Style::default().fg(TEXT)),
        Span::styled("", Style::default().fg(ACCENT)),
        Span::styled(after.to_string(), Style::default().fg(TEXT)),
    ];
    frame.render_widget(Paragraph::new(Line::from(spans)), rows[1]);

    frame.render_widget(
        Paragraph::new(Span::styled(
            "[Enter] confirm  [Esc] cancel",
            Style::default().fg(SUBTLE),
        )),
        rows[2],
    );
}

fn render_playlist_picker(
    frame: &mut Frame,
    track_name: &str,
    choices: &[(PlaylistId, String)],
    cursor: usize,
) {
    let area = frame.area();
    let height = (choices.len() as u16 + 6).min(area.height.saturating_sub(4));
    let rect = centered_rect(52, height, area);
    frame.render_widget(Clear, rect);

    let block = modal_block("Add to Playlist");
    let inner = block.inner(rect);
    frame.render_widget(block, rect);

    let rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // subtitle
            Constraint::Length(1), // spacer
            Constraint::Min(0),    // list
            Constraint::Length(1), // hint
        ])
        .split(inner);

    frame.render_widget(
        Paragraph::new(Span::styled(
            format!("Track: {}", track_name),
            Style::default().fg(TEXT_DIM),
        )),
        rows[0],
    );

    if choices.is_empty() {
        frame.render_widget(
            Paragraph::new(Span::styled(
                "No playlists yet.  Press N to create one.",
                Style::default().fg(SUBTLE),
            )),
            rows[2],
        );
    } else {
        let items: Vec<ListItem> = choices
            .iter()
            .map(|(_, name)| ListItem::new(name.clone()))
            .collect();

        let mut list_state = ListState::default();
        list_state.select(Some(cursor));

        frame.render_stateful_widget(
            List::new(items)
                .highlight_style(
                    Style::default()
                        .fg(TEXT)
                        .bg(Color::Rgb(40, 40, 40))
                        .add_modifier(Modifier::BOLD),
                )
                .highlight_symbol("> "),
            rows[2],
            &mut list_state,
        );
    }

    frame.render_widget(
        Paragraph::new(Span::styled(
            "[Enter] add  [j/k] navigate  [Esc] cancel",
            Style::default().fg(SUBTLE),
        )),
        rows[3],
    );
}

fn render_help(frame: &mut Frame) {
    let area = frame.area();
    let rect = centered_rect(60, 28, area);
    frame.render_widget(Clear, rect);

    let block = modal_block("Help — Keybindings");
    let inner = block.inner(rect);
    frame.render_widget(block, rect);

    let bindings: &[(&str, &str)] = &[
        // Global
        ("q", "Quit"),
        ("Tab", "Cycle panel focus"),
        ("?", "Toggle this help"),
        ("", ""),
        // Navigation
        ("j / ↓", "Move cursor down"),
        ("k / ↑", "Move cursor up"),
        ("", ""),
        // Playback
        ("Space", "Play / Pause"),
        ("n", "Next track"),
        ("N", "Previous track"),
        ("+ / =", "Volume up"),
        ("-", "Volume down"),
        ("", ""),
        // Library actions
        ("Enter", "Play selected track"),
        ("a", "Add track to queue"),
        ("p", "Add track to playlist"),
        ("d", "Remove track from library"),
        ("r", "Rename track / playlist"),
        ("", ""),
        // Playlist / queue
        ("c", "Create new playlist"),
        ("x", "Remove item from queue"),
        ("", ""),
        // File picker
        ("f", "Open file picker"),
    ];

    let items: Vec<Line> = bindings
        .iter()
        .map(|(key, desc)| {
            if key.is_empty() {
                Line::from("")
            } else {
                Line::from(vec![
                    Span::styled(format!("  {:>10}  ", key), Style::default().fg(ACCENT)),
                    Span::styled(*desc, Style::default().fg(TEXT_DIM)),
                ])
            }
        })
        .collect();

    frame.render_widget(Paragraph::new(items), inner);
}