hnr 0.1.0

A fast terminal UI for Hacker News — browse feeds, read threaded comments, vote and reply
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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
use crate::api::{fetch_ask_ids, fetch_best_ids, fetch_new_ids, fetch_show_ids, fetch_top_ids, Item, User};
use crate::session::Session;
use std::collections::HashMap;

#[derive(Debug, Clone, PartialEq)]
pub enum Feed {
    Top,
    New,
    Best,
    Ask,
    Show,
}

impl Feed {
    pub fn label(&self) -> &str {
        match self {
            Feed::Top => "Top",
            Feed::New => "New",
            Feed::Best => "Best",
            Feed::Ask => "Ask HN",
            Feed::Show => "Show HN",
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum Pane {
    Stories,
    Comments,
}

#[derive(Debug, Clone, PartialEq)]
pub enum ViewMode {
    Story,
    User,
}

#[derive(Debug, Clone, PartialEq)]
pub enum LoginField {
    Username,
    Password,
}

#[derive(Debug, Clone)]
pub struct LoginState {
    pub username: String,
    pub password: String,
    pub field: LoginField,
    pub error: String,
}

impl LoginState {
    pub fn new() -> Self {
        Self {
            username: String::new(),
            password: String::new(),
            field: LoginField::Username,
            error: String::new(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct ComposeState {
    pub text: String,
    pub parent_id: u64,
    pub story_id: u64,
    pub hmac: String,
    pub parent_by: String,
}

#[derive(Debug, Clone, PartialEq)]
pub enum Mode {
    Normal,
    Command,
    Login,
    Compose,
}

#[derive(Clone)]
pub struct CommentNode {
    pub item: Item,
    pub depth: usize,
    pub collapsed: bool,
    pub children: Vec<CommentNode>,
}

impl CommentNode {
    pub fn new(item: Item, depth: usize) -> Self {
        Self { item, depth, collapsed: false, children: vec![] }
    }

    pub fn flatten(&self) -> Vec<(&CommentNode, usize)> {
        let mut out = vec![(self, self.depth)];
        if !self.collapsed {
            for child in &self.children {
                out.extend(child.flatten());
            }
        }
        out
    }
}

pub struct App {
    pub feed: Feed,
    pub stories: Vec<Item>,
    pub story_ids: Vec<u64>,
    pub story_cursor: usize,
    pub story_scroll: usize,

    pub comments: Vec<CommentNode>,
    pub comment_cursor: usize,
    pub comment_scroll: usize,

    pub active_pane: Pane,
    pub mode: Mode,
    pub command_input: String,
    pub status_message: String,

    pub view_mode: ViewMode,
    pub user_profile: Option<User>,

    pub session: Option<Session>,
    pub login_state: LoginState,
    pub compose_state: Option<ComposeState>,

    pub loading: bool,
    pub client: reqwest::Client,
    pub item_cache: HashMap<u64, Item>,
}

impl App {
    pub fn new(client: reqwest::Client) -> Self {
        Self {
            feed: Feed::Top,
            stories: vec![],
            story_ids: vec![],
            story_cursor: 0,
            story_scroll: 0,
            comments: vec![],
            comment_cursor: 0,
            comment_scroll: 0,
            active_pane: Pane::Stories,
            mode: Mode::Normal,
            command_input: String::new(),
            status_message: String::from("Loading..."),
            view_mode: ViewMode::Story,
            user_profile: None,
            session: Session::load(),
            login_state: LoginState::new(),
            compose_state: None,
            loading: false,
            client,
            item_cache: HashMap::new(),
        }
    }

    pub fn selected_story(&self) -> Option<&Item> {
        self.stories.get(self.story_cursor)
    }

    pub fn flat_comments(&self) -> Vec<(&CommentNode, usize)> {
        self.comments.iter().flat_map(|c| c.flatten()).collect()
    }

    pub fn scroll_story_down(&mut self, visible: usize) {
        if self.story_cursor + 1 < self.stories.len() {
            self.story_cursor += 1;
            if self.story_cursor >= self.story_scroll + visible {
                self.story_scroll += 1;
            }
        }
    }

    pub fn scroll_story_up(&mut self) {
        if self.story_cursor > 0 {
            self.story_cursor -= 1;
            if self.story_cursor < self.story_scroll {
                self.story_scroll = self.story_cursor;
            }
        }
    }

    pub fn scroll_comment_down(&mut self, visible: usize) {
        let total = self.flat_comments().len();
        if self.comment_cursor + 1 < total {
            self.comment_cursor += 1;
            if self.comment_cursor >= self.comment_scroll + visible {
                self.comment_scroll += 1;
            }
        }
    }

    pub fn scroll_comment_up(&mut self) {
        if self.comment_cursor > 0 {
            self.comment_cursor -= 1;
            if self.comment_cursor < self.comment_scroll {
                self.comment_scroll = self.comment_cursor;
            }
        }
    }

    pub fn toggle_current_comment(&mut self) {
        let id = {
            let flat = self.flat_comments();
            flat.get(self.comment_cursor).map(|(node, _)| node.item.id)
        };
        if let Some(id) = id {
            toggle_in_tree(&mut self.comments, id);
        }
    }

    pub fn username_at_cursor(&self) -> Option<String> {
        match self.active_pane {
            Pane::Stories => self.selected_story().and_then(|s| s.by.clone()),
            Pane::Comments => {
                let flat = self.flat_comments();
                flat.get(self.comment_cursor)
                    .and_then(|(node, _)| node.item.by.clone())
            }
        }
    }

    // ── Auth ──────────────────────────────────────────────────────────────

    pub fn start_login(&mut self) {
        self.login_state = LoginState::new();
        self.mode = Mode::Login;
    }

    pub async fn submit_login(&mut self) {
        let username = self.login_state.username.trim().to_string();
        let password = self.login_state.password.clone();
        if username.is_empty() || password.is_empty() {
            self.login_state.error = "Username and password required".into();
            return;
        }
        self.login_state.error = "Logging in...".into();
        match crate::api::login(&username, &password).await {
            Ok(cookie) => {
                let session = Session { username: username.clone(), cookie };
                session.save();
                self.session = Some(session);
                self.mode = Mode::Normal;
                self.status_message = format!("Logged in as {username} | v vote | c comment");
            }
            Err(e) => {
                self.login_state.error = e.to_string();
            }
        }
    }

    pub fn logout(&mut self) {
        Session::delete();
        self.session = None;
        self.status_message = "Logged out.".into();
    }

    // ── Vote ──────────────────────────────────────────────────────────────

    pub async fn vote_current(&mut self) {
        let session = match &self.session {
            Some(s) => s.clone(),
            None => {
                self.status_message = "Not logged in — /login first".into();
                return;
            }
        };

        let (item_id, story_id) = match self.active_pane {
            Pane::Stories => {
                match self.selected_story() {
                    Some(s) => (s.id, s.id),
                    None => return,
                }
            }
            Pane::Comments => {
                let story_id = match self.selected_story() {
                    Some(s) => s.id,
                    None => return,
                };
                let flat = self.flat_comments();
                match flat.get(self.comment_cursor) {
                    Some((node, _)) => (node.item.id, story_id),
                    None => return,
                }
            }
        };

        self.status_message = "Fetching vote token...".into();
        self.loading = true;
        let client = self.client.clone();
        match crate::api::fetch_vote_auth(&client, &session.cookie, item_id, story_id).await {
            Ok(auth) => {
                match crate::api::vote_item(&client, &session.cookie, item_id, &auth, story_id).await {
                    Ok(_) => self.status_message = "Voted!".into(),
                    Err(e) => self.status_message = format!("Vote failed: {e}"),
                }
            }
            Err(e) => self.status_message = format!("Vote: {e}"),
        }
        self.loading = false;
    }

    // ── Compose ───────────────────────────────────────────────────────────

    pub async fn start_compose(&mut self) {
        let session = match &self.session {
            Some(s) => s.clone(),
            None => {
                self.status_message = "Not logged in — /login first".into();
                return;
            }
        };

        let (parent_id, story_id, parent_by) = match self.active_pane {
            Pane::Stories => {
                match self.selected_story() {
                    Some(s) => (s.id, s.id, s.display_by().to_string()),
                    None => return,
                }
            }
            Pane::Comments => {
                let story_id = match self.selected_story() {
                    Some(s) => s.id,
                    None => return,
                };
                let flat = self.flat_comments();
                match flat.get(self.comment_cursor) {
                    Some((node, _)) => (node.item.id, story_id, node.item.display_by().to_string()),
                    None => return,
                }
            }
        };

        self.status_message = "Fetching reply token...".into();
        self.loading = true;
        let client = self.client.clone();
        match crate::api::fetch_reply_hmac(&client, &session.cookie, parent_id).await {
            Ok(hmac) => {
                self.compose_state = Some(ComposeState {
                    text: String::new(),
                    parent_id,
                    story_id,
                    hmac,
                    parent_by,
                });
                self.mode = Mode::Compose;
                self.status_message = "Ctrl+S submit | Esc cancel".into();
            }
            Err(e) => self.status_message = format!("Compose: {e}"),
        }
        self.loading = false;
    }

    pub async fn submit_comment(&mut self) {
        let session = match &self.session {
            Some(s) => s.clone(),
            None => return,
        };
        let state = match self.compose_state.take() {
            Some(s) => s,
            None => return,
        };
        if state.text.trim().is_empty() {
            self.compose_state = Some(state);
            self.status_message = "Comment is empty.".into();
            return;
        }
        self.mode = Mode::Normal;
        self.status_message = "Posting comment...".into();
        self.loading = true;
        let client = self.client.clone();
        match crate::api::post_comment(
            &client,
            &session.cookie,
            state.parent_id,
            state.story_id,
            &state.hmac,
            &state.text,
        )
        .await
        {
            Ok(_) => {
                self.status_message = "Comment posted! Reloading...".into();
                self.load_comments().await;
            }
            Err(e) => self.status_message = format!("Post failed: {e}"),
        }
        self.loading = false;
    }

    // ── Feed / comments ───────────────────────────────────────────────────

    pub async fn load_feed(&mut self) {
        self.loading = true;
        self.status_message = format!("Loading {} stories...", self.feed.label());
        let client = self.client.clone();
        let ids = match self.feed {
            Feed::Top => fetch_top_ids(&client).await,
            Feed::New => fetch_new_ids(&client).await,
            Feed::Best => fetch_best_ids(&client).await,
            Feed::Ask => fetch_ask_ids(&client).await,
            Feed::Show => fetch_show_ids(&client).await,
        };
        match ids {
            Ok(mut ids) => {
                ids.truncate(60);
                self.story_ids = ids.clone();
                self.status_message = format!("Fetching {} items...", ids.len());
                let items = crate::api::fetch_items(&client, &ids).await;
                for item in &items {
                    self.item_cache.insert(item.id, item.clone());
                }
                self.stories = ids
                    .iter()
                    .filter_map(|id| self.item_cache.get(id).cloned())
                    .collect();
                self.story_cursor = 0;
                self.story_scroll = 0;
                self.comments = vec![];
                self.comment_cursor = 0;
                self.comment_scroll = 0;
                self.active_pane = Pane::Stories;
                self.status_message = format!(
                    "{} stories | j/k navigate | Enter comments | Tab pane | v vote | c reply | / cmd",
                    self.stories.len()
                );
            }
            Err(e) => self.status_message = format!("Error: {e}"),
        }
        self.loading = false;
    }

    pub async fn load_comments(&mut self) {
        if let Some(story) = self.selected_story().cloned() {
            let kids = story.kids.clone().unwrap_or_default();
            if kids.is_empty() {
                self.status_message = "No comments.".into();
                self.comments = vec![];
                return;
            }
            self.status_message = "Loading comments...".into();
            let client = self.client.clone();
            let nodes = load_comment_tree(&client, &kids, 0).await;
            self.comments = nodes;
            self.comment_cursor = 0;
            self.comment_scroll = 0;
            self.status_message = format!(
                "{} top-level threads | j/k | Space collapse | u profile | v vote | c reply | Tab back",
                self.comments.len()
            );
        }
    }

    pub async fn load_user(&mut self, username: String) {
        self.status_message = format!("Loading profile for {username}...");
        self.loading = true;
        let client = self.client.clone();
        match crate::api::fetch_user(&client, &username).await {
            Ok(user) => {
                self.status_message = format!("{} | {} karma | Esc back", user.id, user.karma);
                self.user_profile = Some(user);
                self.view_mode = ViewMode::User;
            }
            Err(e) => self.status_message = format!("Failed to load user: {e}"),
        }
        self.loading = false;
    }

    pub fn close_user_profile(&mut self) {
        self.view_mode = ViewMode::Story;
        self.user_profile = None;
        self.status_message = "j/k navigate | Enter open | Tab switch pane | / command".into();
    }

    pub fn open_story_in_browser(&self) {
        if let Some(story) = self.selected_story() {
            let url = story
                .url
                .clone()
                .unwrap_or_else(|| format!("https://news.ycombinator.com/item?id={}", story.id));
            let _ = open::that(url);
        }
    }

    pub fn open_hn_page_in_browser(&self) {
        if let Some(story) = self.selected_story() {
            let url = format!("https://news.ycombinator.com/item?id={}", story.id);
            let _ = open::that(url);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::api::make_item;

    fn make_node(id: u64, children: Vec<CommentNode>) -> CommentNode {
        CommentNode { item: make_item(id), depth: 0, collapsed: false, children }
    }

    fn make_node_depth(id: u64, depth: usize, children: Vec<CommentNode>) -> CommentNode {
        CommentNode { item: make_item(id), depth, collapsed: false, children }
    }

    // ── CommentNode::flatten ──────────────────────────────────────────────

    #[test]
    fn flatten_leaf_returns_self() {
        let node = make_node(1, vec![]);
        let flat = node.flatten();
        assert_eq!(flat.len(), 1);
        assert_eq!(flat[0].0.item.id, 1);
    }

    #[test]
    fn flatten_includes_children() {
        let child = make_node(2, vec![]);
        let parent = make_node(1, vec![child]);
        let flat = parent.flatten();
        assert_eq!(flat.len(), 2);
        assert_eq!(flat[0].0.item.id, 1);
        assert_eq!(flat[1].0.item.id, 2);
    }

    #[test]
    fn flatten_collapsed_hides_children() {
        let child = make_node(2, vec![]);
        let mut parent = make_node(1, vec![child]);
        parent.collapsed = true;
        let flat = parent.flatten();
        assert_eq!(flat.len(), 1);
        assert_eq!(flat[0].0.item.id, 1);
    }

    #[test]
    fn flatten_nested_depth_order() {
        let grandchild = make_node_depth(3, 2, vec![]);
        let child = make_node_depth(2, 1, vec![grandchild]);
        let parent = make_node_depth(1, 0, vec![child]);
        let flat = parent.flatten();
        assert_eq!(flat.len(), 3);
        assert_eq!(flat[0].0.item.id, 1);
        assert_eq!(flat[1].0.item.id, 2);
        assert_eq!(flat[2].0.item.id, 3);
    }

    #[test]
    fn flatten_collapsed_mid_tree_hides_subtree() {
        let grandchild = make_node_depth(3, 2, vec![]);
        let mut child = make_node_depth(2, 1, vec![grandchild]);
        child.collapsed = true;
        let parent = make_node_depth(1, 0, vec![child]);
        let flat = parent.flatten();
        // parent + collapsed child visible, grandchild hidden
        assert_eq!(flat.len(), 2);
        assert_eq!(flat[1].0.item.id, 2);
    }

    // ── toggle_in_tree ────────────────────────────────────────────────────

    #[test]
    fn toggle_root_node() {
        let child = make_node(2, vec![]);
        let mut nodes = vec![make_node(1, vec![child])];
        assert!(!nodes[0].collapsed);
        toggle_in_tree(&mut nodes, 1);
        assert!(nodes[0].collapsed);
        toggle_in_tree(&mut nodes, 1);
        assert!(!nodes[0].collapsed);
    }

    #[test]
    fn toggle_nested_node() {
        let child = make_node(2, vec![]);
        let mut nodes = vec![make_node(1, vec![child])];
        assert!(!nodes[0].children[0].collapsed);
        toggle_in_tree(&mut nodes, 2);
        assert!(nodes[0].children[0].collapsed);
    }

    #[test]
    fn toggle_nonexistent_id_is_noop() {
        let mut nodes = vec![make_node(1, vec![])];
        toggle_in_tree(&mut nodes, 99);
        assert!(!nodes[0].collapsed);
    }

    // ── App scroll ────────────────────────────────────────────────────────

    fn make_app_with_stories(n: usize) -> App {
        let client = reqwest::Client::new();
        let mut app = App::new(client);
        app.stories = (1..=n as u64).map(make_item).collect();
        app
    }

    #[test]
    fn story_scroll_down_increments_cursor() {
        let mut app = make_app_with_stories(5);
        app.scroll_story_down(10);
        assert_eq!(app.story_cursor, 1);
        assert_eq!(app.story_scroll, 0);
    }

    #[test]
    fn story_scroll_advances_when_cursor_hits_visible_boundary() {
        let mut app = make_app_with_stories(10);
        for _ in 0..5 {
            app.scroll_story_down(5);
        }
        assert_eq!(app.story_cursor, 5);
        assert_eq!(app.story_scroll, 1);
    }

    #[test]
    fn story_scroll_up_decrements_cursor() {
        let mut app = make_app_with_stories(5);
        app.story_cursor = 3;
        app.story_scroll = 2;
        app.scroll_story_up();
        assert_eq!(app.story_cursor, 2);
        assert_eq!(app.story_scroll, 2);
    }

    #[test]
    fn story_scroll_up_adjusts_scroll_when_cursor_above_window() {
        let mut app = make_app_with_stories(5);
        app.story_cursor = 2;
        app.story_scroll = 3;
        app.scroll_story_up();
        assert_eq!(app.story_cursor, 1);
        assert_eq!(app.story_scroll, 1);
    }

    #[test]
    fn story_scroll_down_stops_at_end() {
        let mut app = make_app_with_stories(3);
        app.story_cursor = 2;
        app.scroll_story_down(10);
        assert_eq!(app.story_cursor, 2);
    }

    #[test]
    fn story_scroll_up_stops_at_zero() {
        let mut app = make_app_with_stories(3);
        app.story_cursor = 0;
        app.scroll_story_up();
        assert_eq!(app.story_cursor, 0);
        assert_eq!(app.story_scroll, 0);
    }

    #[test]
    fn selected_story_returns_correct_item() {
        let mut app = make_app_with_stories(5);
        app.story_cursor = 2;
        assert_eq!(app.selected_story().unwrap().id, 3);
    }

    #[test]
    fn selected_story_none_when_empty() {
        let client = reqwest::Client::new();
        let app = App::new(client);
        assert!(app.selected_story().is_none());
    }
}

fn toggle_in_tree(nodes: &mut Vec<CommentNode>, id: u64) {
    for node in nodes.iter_mut() {
        if node.item.id == id {
            node.collapsed = !node.collapsed;
            return;
        }
        toggle_in_tree(&mut node.children, id);
    }
}

async fn load_comment_tree(client: &reqwest::Client, ids: &[u64], depth: usize) -> Vec<CommentNode> {
    let items = crate::api::fetch_items(client, ids).await;
    let mut nodes = vec![];
    for item in items {
        if item.is_deleted_or_dead() {
            continue;
        }
        let kids = item.kids.clone().unwrap_or_default();
        let mut node = CommentNode::new(item, depth);
        if !kids.is_empty() && depth < 6 {
            node.children = Box::pin(load_comment_tree(client, &kids, depth + 1)).await;
        }
        nodes.push(node);
    }
    nodes
}