jjj 0.4.1

Distributed project management and code review for Jujutsu
Documentation
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
use super::App;
use crate::error::Result;

impl App {
    pub(super) fn navigate_up(&mut self) {
        if self.ui.tree_index == 0 {
            return;
        }
        let mut target = self.ui.tree_index - 1;
        // Skip past non-selectable nodes (separators, structural)
        while !self.is_navigable(target) && target > 0 {
            target -= 1;
        }
        if !self.is_navigable(target) {
            return; // Nothing navigable above; stay put
        }
        self.ui.tree_index = target;
        self.update_selected_detail();
    }

    pub(super) fn navigate_down(&mut self) {
        let max = self.cache.tree_items.len().saturating_sub(1);
        if self.ui.tree_index >= max {
            return;
        }
        let mut target = self.ui.tree_index + 1;
        // Skip past non-selectable nodes (separators, structural)
        while !self.is_navigable(target) && target < max {
            target += 1;
        }
        if !self.is_navigable(target) {
            return; // Nothing navigable below; stay put
        }
        self.ui.tree_index = target;
        self.update_selected_detail();
    }

    /// Whether a tree item at the given index is a valid navigation target.
    fn is_navigable(&self, index: usize) -> bool {
        self.cache
            .tree_items
            .get(index)
            .map(|i| i.node.is_navigable())
            .unwrap_or(false)
    }

    /// Jump to the next (or previous) tree item that has an action symbol.
    ///
    /// Wraps around: going forward past the last action item cycles to the first;
    /// going backward past the first cycles to the last. Automatically expands
    /// ancestor nodes so the target is visible in the tree before navigating.
    pub(super) fn jump_to_next_action(&mut self, reverse: bool) {
        if self.cache.tree_items.is_empty() {
            return;
        }

        // Find indices of items with action symbols
        let action_indices: Vec<usize> = self
            .cache
            .tree_items
            .iter()
            .enumerate()
            .filter(|(_, item)| item.action_symbol.is_some())
            .map(|(i, _)| i)
            .collect();

        if action_indices.is_empty() {
            return;
        }

        // Find next action item
        let current = self.ui.tree_index;
        let next_index = if reverse {
            // Find previous action item (or wrap to last)
            action_indices
                .iter()
                .rev()
                .find(|&&i| i < current)
                .or_else(|| action_indices.last())
                .copied()
        } else {
            // Find next action item (or wrap to first)
            action_indices
                .iter()
                .find(|&&i| i > current)
                .or_else(|| action_indices.first())
                .copied()
        };

        if let Some(idx) = next_index {
            // Expand ancestors to reveal the item
            let target_id = self.cache.tree_items[idx].node.id().to_string();
            self.expand_to_reveal(&target_id);
            self.rebuild_tree();
            // Re-find the item after tree rebuild
            for (i, item) in self.cache.tree_items.iter().enumerate() {
                if item.node.id() == target_id {
                    self.ui.tree_index = i;
                    break;
                }
            }
            self.update_selected_detail();
        }
    }

    /// Ensure a target entity is visible by expanding its ancestor nodes.
    ///
    /// Walks up the entity hierarchy (critique → solution → problem → milestone)
    /// and inserts each ancestor's ID into `expanded_nodes`. Must be followed by
    /// `rebuild_tree()` to take effect.
    fn expand_to_reveal(&mut self, target_id: &str) {
        // For a solution, we need its problem expanded, and that problem's milestone expanded
        if let Some(solution) = self.data.solutions.iter().find(|s| s.id == target_id) {
            self.ui.expanded_nodes.insert(solution.problem_id.clone());

            if let Some(problem) = self
                .data
                .problems
                .iter()
                .find(|p| p.id == solution.problem_id)
            {
                if let Some(milestone_id) = &problem.milestone_id {
                    self.ui.expanded_nodes.insert(milestone_id.clone());
                } else {
                    self.ui.expanded_nodes.insert("backlog".to_string());
                }
            }
        }

        // For a problem, we need its milestone expanded
        if let Some(problem) = self.data.problems.iter().find(|p| p.id == target_id) {
            if let Some(milestone_id) = &problem.milestone_id {
                self.ui.expanded_nodes.insert(milestone_id.clone());
            } else {
                self.ui.expanded_nodes.insert("backlog".to_string());
            }
        }

        // For a critique, we need its solution and problem expanded
        if let Some(critique) = self.data.critiques.iter().find(|c| c.id == target_id) {
            self.ui.expanded_nodes.insert(critique.solution_id.clone());

            if let Some(solution) = self
                .data
                .solutions
                .iter()
                .find(|s| s.id == critique.solution_id)
            {
                self.ui.expanded_nodes.insert(solution.problem_id.clone());

                if let Some(problem) = self
                    .data
                    .problems
                    .iter()
                    .find(|p| p.id == solution.problem_id)
                {
                    if let Some(milestone_id) = &problem.milestone_id {
                        self.ui.expanded_nodes.insert(milestone_id.clone());
                    } else {
                        self.ui.expanded_nodes.insert("backlog".to_string());
                    }
                }
            }
        }
    }

    pub(super) fn collapse_or_parent(&mut self) {
        if let Some(item) = self.cache.tree_items.get(self.ui.tree_index) {
            let node_id = item.node.id().to_string();

            if item.node.is_expanded() {
                // Collapse current node
                self.ui.expanded_nodes.remove(&node_id);
                self.rebuild_tree();
            } else if item.depth > 0 {
                // Move to parent
                for i in (0..self.ui.tree_index).rev() {
                    if self.cache.tree_items[i].depth < item.depth {
                        self.ui.tree_index = i;
                        break;
                    }
                }
                self.update_selected_detail();
            }
        }
    }

    pub(super) fn expand_or_child(&mut self) {
        if let Some(item) = self.cache.tree_items.get(self.ui.tree_index) {
            if !item.has_children {
                return;
            }

            let node_id = item.node.id().to_string();

            if item.node.is_expanded() {
                // Move to first child
                if self.ui.tree_index + 1 < self.cache.tree_items.len() {
                    self.ui.tree_index += 1;
                }
            } else {
                // Expand
                self.ui.expanded_nodes.insert(node_id);
                self.rebuild_tree();
            }
        }
    }

    pub(super) fn scroll_detail_down(&mut self) {
        self.ui.detail_scroll = self.ui.detail_scroll.saturating_add(1);
    }

    pub(super) fn scroll_detail_up(&mut self) {
        self.ui.detail_scroll = self.ui.detail_scroll.saturating_sub(1);
    }

    pub(super) fn page_detail_up(&mut self) {
        self.ui.detail_scroll = self.ui.detail_scroll.saturating_sub(10);
    }

    pub(super) fn page_detail_down(&mut self) {
        self.ui.detail_scroll = self.ui.detail_scroll.saturating_add(10);
    }

    pub(super) fn detail_scroll_to_top(&mut self) {
        self.ui.detail_scroll = 0;
    }

    pub(super) fn detail_scroll_to_bottom(&mut self) {
        self.ui.detail_scroll = u16::MAX;
    }

    /// Toggle multi-select on the current tree item and advance cursor.
    pub(super) fn toggle_selection(&mut self) {
        if let Some(item) = self.cache.tree_items.get(self.ui.tree_index) {
            if item.node.is_selectable() {
                let id = item.node.id().to_string();
                if !self.ui.selected_ids.remove(&id) {
                    self.ui.selected_ids.insert(id);
                }
            }
        }
    }

    /// Select all visible selectable items, or clear if all already selected.
    pub(super) fn select_all_visible(&mut self) {
        let visible_ids: Vec<String> = self
            .cache
            .tree_items
            .iter()
            .filter(|item| item.node.is_selectable())
            .map(|item| item.node.id().to_string())
            .collect();

        let all_selected = visible_ids
            .iter()
            .all(|id| self.ui.selected_ids.contains(id));

        if all_selected {
            self.ui.selected_ids.clear();
        } else {
            self.ui.selected_ids.extend(visible_ids);
        }
    }

    /// Clear multi-selection.
    pub(super) fn clear_selection(&mut self) {
        self.ui.selected_ids.clear();
    }

    pub(super) fn toggle_related_panel(&mut self) {
        self.ui.show_related = !self.ui.show_related;
    }

    pub(super) fn toggle_filter(&mut self) {
        self.ui.filter_actions_only = !self.ui.filter_actions_only;
        let mode = if self.ui.filter_actions_only {
            "Actions only"
        } else {
            "Full tree"
        };
        self.show_flash(mode);
    }

    pub(super) fn start_search(&mut self) {
        use super::InputAction;
        use super::InputMode;
        let buffer = self.ui.search_filter.clone().unwrap_or_default();
        let cursor_pos = buffer.chars().count();
        self.ui.input_mode = InputMode::Input {
            prompt: "/".to_string(),
            buffer,
            action: InputAction::Search,
            cursor_pos,
        };
    }

    pub(super) fn toggle_help(&mut self) {
        use super::InputMode;
        self.ui.input_mode = match &self.ui.input_mode {
            InputMode::Help => InputMode::Normal,
            _ => InputMode::Help,
        };
    }

    pub(super) fn goto_change(&mut self) -> Result<()> {
        use super::super::tree::TreeNode;

        let solution_id = if let Some(item) = self.cache.tree_items.get(self.ui.tree_index) {
            match &item.node {
                TreeNode::Solution { id, .. } => id.clone(),
                _ => return Ok(()),
            }
        } else {
            return Ok(());
        };

        let solution = match self.data.solutions.iter().find(|s| s.id == solution_id) {
            Some(s) => s,
            None => {
                self.show_flash("Solution not found");
                return Ok(());
            }
        };

        if let Some(change_id) = solution.change_ids.last() {
            match self.store.jj_client.edit(change_id) {
                Ok(_) => self.show_flash(&format!("Switched to {}", change_id)),
                Err(e) => self.show_flash(&format!("Error: {}", e)),
            }
        } else {
            self.show_flash("No changes attached");
        }

        Ok(())
    }

    pub fn rebuild_tree(&mut self) {
        let tree_ctx = super::super::tree::TreeBuildContext {
            solutions: &self.data.solutions,
            critiques: &self.data.critiques,
            expanded_nodes: &self.ui.expanded_nodes,
            personal_orderings: &self.ui.personal_orderings,
        };
        self.cache.tree_items = super::super::tree::build_flat_tree_ranked(
            &self.data.milestones,
            &self.data.problems,
            &tree_ctx,
            self.ui.show_personal_ordering,
            &self.ui.tier_drill,
        );
        super::super::annotate_tree_with_actions(
            &mut self.cache.tree_items,
            &self.cache.next_actions,
        );
        // Re-apply search filter if active
        if self.ui.search_filter.is_some() {
            self.apply_search_filter_to_tree();
        }
    }

    pub(super) fn apply_search_filter(&mut self) {
        self.rebuild_tree();
        // Clamp tree_index
        let max_index = self.cache.tree_items.len().saturating_sub(1);
        if self.ui.tree_index > max_index {
            self.ui.tree_index = max_index;
        }
        self.update_selected_detail();
    }

    fn apply_search_filter_to_tree(&mut self) {
        if let Some(ref query) = self.ui.search_filter {
            let query_lower = query.to_lowercase();
            self.cache.tree_items.retain(|item| {
                let title = item.node.title().to_lowercase();
                let id = item.node.id().to_lowercase();
                title.contains(&query_lower) || id.contains(&query_lower)
            });
        }
    }

    pub fn context_hints(&self) -> String {
        use super::super::tree::TreeNode;

        if !self.ui.selected_ids.is_empty() {
            return format!(
                "{} selected: [s]olve [d]ecline [A]ssign [m]ove [x]delete [Esc]clear",
                self.ui.selected_ids.len()
            );
        }

        if let Some(item) = self.cache.tree_items.get(self.ui.tree_index) {
            match &item.node {
                TreeNode::ProjectRoot { .. } => "[n]ew milestone".to_string(),
                TreeNode::Milestone { id, .. } => {
                    format!(
                        "{}: [n]ew problem [e]dit [E]ditor [s] complete [o] activate [D] cancel [A]ssign [x] delete",
                        id
                    )
                }
                TreeNode::Backlog { .. } => "[n]ew problem".to_string(),
                TreeNode::Problem { id, .. } => {
                    format!(
                        "{}: [n]ew solution [s]olve [d]issolve [o] reopen [A]ssign [m]ove [e]dit [t]ags [E]ditor [x] delete",
                        id
                    )
                }
                TreeNode::Solution { id, .. } => {
                    format!(
                        "{}: [n]ew critique [u] submit [a]pprove [d] withdraw [A]ssign [g]o to change [e]dit [t]ags [E]ditor [x] delete",
                        id
                    )
                }
                TreeNode::Critique { id, .. } => {
                    format!(
                        "{}: [a]ddress [d]ismiss [v]alidate [e]dit [E]ditor [x] delete",
                        id
                    )
                }
                TreeNode::TierSeparator { .. } => String::new(),
            }
        } else {
            "No selection".to_string()
        }
    }

    pub fn update_selected_detail(&mut self) {
        use super::super::tree::TreeNode;

        if let Some(item) = self.cache.tree_items.get(self.ui.tree_index) {
            self.cache.selected_detail = match &item.node {
                TreeNode::Milestone { id, .. } => self
                    .data
                    .milestones
                    .iter()
                    .find(|m| m.id == *id)
                    .cloned()
                    .map(super::super::DetailContent::Milestone)
                    .unwrap_or(super::super::DetailContent::None),
                TreeNode::ProjectRoot { .. }
                | TreeNode::Backlog { .. }
                | TreeNode::TierSeparator { .. } => super::super::DetailContent::None,
                TreeNode::Problem { id, .. } => {
                    if let Some(problem) = self.data.problems.iter().find(|p| p.id == *id).cloned()
                    {
                        let rank_info = self.build_problem_rank_info(&problem);
                        super::super::DetailContent::Problem(problem, rank_info)
                    } else {
                        super::super::DetailContent::None
                    }
                }
                TreeNode::Solution { id, .. } => self
                    .data
                    .solutions
                    .iter()
                    .find(|s| s.id == *id)
                    .cloned()
                    .map(super::super::DetailContent::Solution)
                    .unwrap_or(super::super::DetailContent::None),
                TreeNode::Critique { id, .. } => self
                    .data
                    .critiques
                    .iter()
                    .find(|c| c.id == *id)
                    .cloned()
                    .map(super::super::DetailContent::Critique)
                    .unwrap_or(super::super::DetailContent::None),
            };
        }
        self.ui.detail_scroll = 0; // Reset scroll on new selection
        self.load_related_for_selected(); // Load related items for new selection
    }

    /// Build rank/vote info for a problem from milestone rankings and personal orderings.
    fn build_problem_rank_info(
        &self,
        problem: &crate::models::Problem,
    ) -> Option<super::super::ProblemRankInfo> {
        let milestone_id = problem.milestone_id.as_ref()?;

        // Use personal ordering rank when in personal view, global when in global view
        let (rank_pos, _voter_count) = if self.ui.show_personal_ordering {
            let ordering = self.ui.personal_orderings.get(milestone_id)?;
            let pos = ordering.order.iter().position(|id| id == &problem.id)?;
            (pos + 1, 1usize)
        } else {
            let milestone_rankings = self.data.rankings.get(milestone_id)?;
            let (pos, voter_str) = milestone_rankings.get(&problem.id)?;
            (*pos, voter_str.parse().unwrap_or(0))
        };

        // Look up current user's QV vote allocation for this problem
        let (my_votes, budget_used, budget_total) =
            if let Some(ordering) = self.ui.personal_orderings.get(milestone_id) {
                let v = ordering.votes.get(&problem.id).copied().unwrap_or(0);
                let used = crate::ranking::borda::vote_cost(v);
                let problem_count = ordering.order.len();
                let total = crate::ranking::borda::qv_budget(problem_count);
                (v, used, total)
            } else {
                (0, 0, 0)
            };

        Some(super::super::ProblemRankInfo {
            rank: Some(rank_pos),
            votes: my_votes,
            budget_used,
            budget_total,
        })
    }

    pub(super) fn get_selected_entity(
        &self,
    ) -> Option<(String, super::super::next_actions::EntityType)> {
        use super::super::tree::TreeNode;

        self.cache
            .tree_items
            .get(self.ui.tree_index)
            .and_then(|item| match &item.node {
                TreeNode::Problem { id, .. } => {
                    Some((id.clone(), super::super::next_actions::EntityType::Problem))
                }
                TreeNode::Solution { id, .. } => {
                    Some((id.clone(), super::super::next_actions::EntityType::Solution))
                }
                TreeNode::Critique { id, .. } => {
                    Some((id.clone(), super::super::next_actions::EntityType::Critique))
                }
                TreeNode::Milestone { id, .. } => Some((
                    id.clone(),
                    super::super::next_actions::EntityType::Milestone,
                )),
                _ => None,
            })
    }

    /// Returns entity IDs and types to act on.
    /// If multi-selection is active, returns selected items.
    /// Otherwise returns the single cursor item (if selectable).
    pub(super) fn action_targets(&self) -> Vec<(String, super::super::next_actions::EntityType)> {
        use super::super::tree::TreeNode;

        if !self.ui.selected_ids.is_empty() {
            self.cache
                .tree_items
                .iter()
                .filter(|item| self.ui.selected_ids.contains(item.node.id()))
                .filter_map(|item| match &item.node {
                    TreeNode::Problem { id, .. } => {
                        Some((id.clone(), super::super::next_actions::EntityType::Problem))
                    }
                    TreeNode::Solution { id, .. } => {
                        Some((id.clone(), super::super::next_actions::EntityType::Solution))
                    }
                    TreeNode::Critique { id, .. } => {
                        Some((id.clone(), super::super::next_actions::EntityType::Critique))
                    }
                    TreeNode::Milestone { id, .. } => Some((
                        id.clone(),
                        super::super::next_actions::EntityType::Milestone,
                    )),
                    _ => None,
                })
                .collect()
        } else {
            self.get_selected_entity().into_iter().collect()
        }
    }

    pub(super) fn get_selected_entity_info(&self) -> Option<(String, String)> {
        use super::super::tree::TreeNode;

        self.cache
            .tree_items
            .get(self.ui.tree_index)
            .and_then(|item| match &item.node {
                TreeNode::Problem { id, .. } => Some(("problem".to_string(), id.clone())),
                TreeNode::Solution { id, .. } => Some(("solution".to_string(), id.clone())),
                TreeNode::Critique { id, .. } => Some(("critique".to_string(), id.clone())),
                TreeNode::Milestone { id, .. } => Some(("milestone".to_string(), id.clone())),
                TreeNode::ProjectRoot { .. }
                | TreeNode::Backlog { .. }
                | TreeNode::TierSeparator { .. } => None,
            })
    }
}