nu-explore 0.112.2

Nushell table pager
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
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
696
697
698
699
//! Tree building, path operations, and CLI tree printing utilities.

use crate::explore_config::types::{NodeInfo, NuValueType, ValueType};
use serde_json::Value;
use std::collections::HashMap;
use tui_tree_widget::TreeItem;

/// Check if a JSON value is a leaf node (not an object or array)
pub fn is_leaf(value: &Value) -> bool {
    !value.is_object() && !value.is_array()
}

/// Render a leaf value as a string
pub fn render_leaf(value: &Value) -> String {
    serde_json::to_string(value).unwrap_or_else(|_| "<unserializable>".to_string())
}

/// Print a JSON tree structure to stdout (for CLI mode)
pub fn print_json_tree(value: &Value, prefix: &str, is_tail: bool, key: Option<&str>) {
    if let Some(k) = key {
        let connector = if is_tail { "└── " } else { "├── " };
        let leaf_part = if is_leaf(value) {
            format!(" {}", render_leaf(value))
        } else {
            String::new()
        };
        println!("{}{}{}:{}", prefix, connector, k, leaf_part);
    }

    if !is_leaf(value) {
        let branch = if is_tail { "    " } else { "" };
        let child_prefix = if key.is_none() {
            prefix.to_string()
        } else {
            format!("{}{}", prefix, branch)
        };

        match value {
            Value::Object(map) => {
                let mut entries: Vec<(&str, &Value)> =
                    map.iter().map(|(kk, vv)| (kk.as_str(), vv)).collect();
                entries.sort_by_key(|(kk, _)| *kk);
                for (idx, &(kk, vv)) in entries.iter().enumerate() {
                    let child_tail = idx == entries.len() - 1;
                    print_json_tree(vv, &child_prefix, child_tail, Some(kk));
                }
            }
            Value::Array(arr) => {
                for (idx, vv) in arr.iter().enumerate() {
                    let child_tail = idx == arr.len() - 1;
                    let idx_str = idx.to_string();
                    print_json_tree(vv, &child_prefix, child_tail, Some(&idx_str));
                }
            }
            _ => {}
        }
    }
}

/// Filter tree items based on a search query.
/// Returns a new tree with only items (and their ancestors) that match the query.
/// The search is case-insensitive and matches against the item's identifier (path).
pub fn filter_tree_items(
    items: &[TreeItem<'static, String>],
    query: &str,
) -> Vec<TreeItem<'static, String>> {
    let query_lower = query.to_lowercase();
    filter_tree_items_recursive(items, &query_lower)
}

/// Recursively filter tree items based on a search query.
///
/// This function traverses the tree and includes items that either:
/// 1. Have an identifier that contains the query string (case-insensitive match)
/// 2. Have descendants that match the query (ancestor preservation)
///
/// # Arguments
/// * `items` - The tree items to filter
/// * `query` - The lowercase search query to match against identifiers
///
/// # Returns
/// A new vector of tree items containing only matching items and their ancestors.
/// - Leaf items that match are cloned directly
/// - Parent items with matching children are rebuilt with only the filtered children
/// - Parent items that match but have no matching children are shown as collapsed leaves
///
/// # Note
/// If rebuilding a parent with filtered children fails (e.g., due to duplicate identifiers),
/// the item is included as a collapsed leaf to ensure no matches are silently dropped.
fn filter_tree_items_recursive(
    items: &[TreeItem<'static, String>],
    query: &str,
) -> Vec<TreeItem<'static, String>> {
    let mut result = Vec::new();

    for item in items {
        let identifier = item.identifier().clone();
        let identifier_lower = identifier.to_lowercase();

        // Check if this item's identifier matches the query
        let self_matches = identifier_lower.contains(query);

        // Recursively filter children
        let filtered_children = filter_tree_items_recursive(item.children(), query);

        // Include this item if it matches OR if any of its children matched
        if self_matches || !filtered_children.is_empty() {
            if item.children().is_empty() {
                // Leaf item - just clone it
                result.push(item.clone());
            } else if !filtered_children.is_empty() {
                // Has matching children - rebuild with filtered children
                match rebuild_item_with_children(item, filtered_children) {
                    Ok(new_item) => result.push(new_item),
                    Err(_) => {
                        // Fallback: if rebuild fails, include as collapsed leaf
                        // This ensures matching items aren't silently dropped
                        result.push(TreeItem::new_leaf(identifier, format_collapsed_label(item)));
                    }
                }
            } else {
                // Self matches but has children that don't match
                // Include as a leaf (collapsed view of matching parent)
                result.push(TreeItem::new_leaf(identifier, format_collapsed_label(item)));
            }
        }
    }

    result
}

/// Rebuild a tree item with new children, preserving the display format
fn rebuild_item_with_children(
    original: &TreeItem<'static, String>,
    new_children: Vec<TreeItem<'static, String>>,
) -> Result<TreeItem<'static, String>, std::io::Error> {
    let identifier = original.identifier().clone();
    // Extract the display text by getting the height (number of lines) and reconstructing
    // Since we can't access the text directly, use the identifier as a base for the label
    // The original label format is preserved in the clone, so we just need the identifier
    // to build a similar looking label
    let label = format_parent_label(&identifier, new_children.len());
    TreeItem::new(identifier, label, new_children)
}

/// Format a label for a parent node based on identifier
fn format_parent_label(identifier: &str, child_count: usize) -> String {
    // Extract the key name from the identifier (last part after the last dot)
    let key = identifier
        .rsplit('.')
        .next()
        .unwrap_or(identifier)
        .trim_start_matches('[')
        .trim_end_matches(']');
    format!("{} {{{} keys}}", key, child_count)
}

/// Format a display label for a tree item shown in collapsed form.
///
/// This is used when a parent item matches the search query but none of its
/// children match. The item is displayed as a leaf node with a label indicating
/// how many children it contains.
///
/// # Arguments
/// * `item` - The tree item to create a collapsed label for
///
/// # Returns
/// A string label in the format:
/// - `"key {N keys}"` for items with children (where N is the child count)
/// - `"key"` for leaf items (no children)
///
/// # Example
/// For an item with identifier `"color_config.string"` and 3 children,
/// this returns `"string {3 keys}"`.
fn format_collapsed_label(item: &TreeItem<'static, String>) -> String {
    let identifier = item.identifier();
    let key = identifier
        .rsplit('.')
        .next()
        .unwrap_or(identifier)
        .trim_start_matches('[')
        .trim_end_matches(']');
    let child_count = item.children().len();
    if child_count > 0 {
        format!("{} {{{} keys}}", key, child_count)
    } else {
        key.to_string()
    }
}

/// Build tree items for the TUI tree widget
pub fn build_tree_items(
    json_data: &Value,
    node_map: &mut HashMap<String, NodeInfo>,
    nu_type_map: &Option<HashMap<String, NuValueType>>,
    doc_map: &Option<HashMap<String, String>>,
) -> Vec<TreeItem<'static, String>> {
    build_tree_items_recursive(
        json_data,
        node_map,
        nu_type_map,
        doc_map,
        Vec::new(),
        String::new(),
    )
}

fn build_tree_items_recursive(
    value: &Value,
    node_map: &mut HashMap<String, NodeInfo>,
    nu_type_map: &Option<HashMap<String, NuValueType>>,
    doc_map: &Option<HashMap<String, String>>,
    current_path: Vec<String>,
    parent_id: String,
) -> Vec<TreeItem<'static, String>> {
    match value {
        Value::Object(map) => {
            // Sort keys alphabetically
            let mut entries: Vec<(&String, &Value)> = map.iter().collect();
            entries.sort_by_key(|(k, _)| *k);

            entries
                .into_iter()
                .map(|(key, val)| {
                    let mut path = current_path.clone();
                    path.push(key.clone());

                    let identifier = if parent_id.is_empty() {
                        key.clone()
                    } else {
                        format!("{}.{}", parent_id, key)
                    };

                    let value_type = ValueType::from_value(val);
                    let nu_type = nu_type_map
                        .as_ref()
                        .and_then(|m| m.get(&identifier).cloned());

                    // Check if documentation exists for this path
                    let config_path = path.join(".");
                    let has_doc = doc_map
                        .as_ref()
                        .is_some_and(|m| m.contains_key(&config_path))
                        || should_suppress_doc_warning(&path);

                    node_map.insert(
                        identifier.clone(),
                        NodeInfo {
                            path: path.clone(),
                            value_type,
                            nu_type,
                        },
                    );

                    let display = format_tree_label(key, val, has_doc, doc_map.is_some());

                    if is_leaf(val) {
                        TreeItem::new_leaf(identifier, display)
                    } else {
                        let children = build_tree_items_recursive(
                            val,
                            node_map,
                            nu_type_map,
                            doc_map,
                            path,
                            identifier.clone(),
                        );
                        TreeItem::new(identifier, display, children)
                            .expect("all item identifiers are unique")
                    }
                })
                .collect()
        }
        Value::Array(arr) => arr
            .iter()
            .enumerate()
            .map(|(idx, val)| {
                let mut path = current_path.clone();
                path.push(idx.to_string());

                let identifier = if parent_id.is_empty() {
                    format!("[{}]", idx)
                } else {
                    format!("{}[{}]", parent_id, idx)
                };

                let value_type = ValueType::from_value(val);
                let nu_type = nu_type_map
                    .as_ref()
                    .and_then(|m| m.get(&identifier).cloned());

                // Check if documentation exists for this path
                let config_path = path.join(".");
                let has_doc = doc_map
                    .as_ref()
                    .is_some_and(|m| m.contains_key(&config_path))
                    || should_suppress_doc_warning(&path);

                node_map.insert(
                    identifier.clone(),
                    NodeInfo {
                        path: path.clone(),
                        value_type,
                        nu_type,
                    },
                );

                let display = format_array_item_label(idx, val, has_doc, doc_map.is_some());

                if is_leaf(val) {
                    TreeItem::new_leaf(identifier, display)
                } else {
                    let children = build_tree_items_recursive(
                        val,
                        node_map,
                        nu_type_map,
                        doc_map,
                        path,
                        identifier.clone(),
                    );
                    TreeItem::new(identifier, display, children)
                        .expect("all item identifiers are unique")
                }
            })
            .collect(),
        _ => Vec::new(),
    }
}

/// Escape control characters that would cause multi-line rendering in tree labels
fn escape_for_display(s: &str) -> String {
    s.replace('\r', "\\r")
        .replace('\n', "\\n")
        .replace('\t', "\\t")
}

/// Check if a path should suppress the "missing documentation" warning.
/// This is used for user-defined list items like keybindings and menus entries,
/// where individual items won't have documentation.
fn should_suppress_doc_warning(path: &[String]) -> bool {
    // Suppress warnings for any nested items under keybindings or menus
    // e.g., ["keybindings", "0", "name"] or ["menus", "1", "source"]
    if path.len() >= 2 {
        let first = path[0].as_str();
        if first == "keybindings" || first == "menus" {
            return true;
        }
    }
    false
}

fn format_tree_label(key: &str, value: &Value, has_doc: bool, is_config_mode: bool) -> String {
    let doc_marker = if is_config_mode && !has_doc {
        ""
    } else {
        ""
    };
    // Escape control characters in key to prevent multi-line tree items
    let safe_key = escape_for_display(key);
    match value {
        Value::Null => format!("{}{}: null", doc_marker, safe_key),
        Value::Bool(b) => format!("{}{}: {}", doc_marker, safe_key, b),
        Value::Number(n) => format!("{}{}: {}", doc_marker, safe_key, n),
        Value::String(s) => {
            // Truncate safely at char boundary, not byte boundary
            // Use nth() to check if string has more than 40 chars without counting all chars
            let needs_truncation = s.chars().nth(40).is_some();
            let preview = if needs_truncation {
                let truncated: String = s.chars().take(37).collect();
                format!("{}...", truncated)
            } else {
                s.clone()
            };
            format!(
                "{}{}: \"{}\"",
                doc_marker,
                safe_key,
                escape_for_display(&preview)
            )
        }
        Value::Array(arr) => format!("{}{} [{} items]", doc_marker, safe_key, arr.len()),
        Value::Object(obj) => format!("{}{} {{{} keys}}", doc_marker, safe_key, obj.len()),
    }
}

fn format_array_item_label(
    idx: usize,
    value: &Value,
    has_doc: bool,
    is_config_mode: bool,
) -> String {
    let doc_marker = if is_config_mode && !has_doc {
        ""
    } else {
        ""
    };
    match value {
        Value::Null => format!("{}[{}]: null", doc_marker, idx),
        Value::Bool(b) => format!("{}[{}]: {}", doc_marker, idx, b),
        Value::Number(n) => format!("{}[{}]: {}", doc_marker, idx, n),
        Value::String(s) => {
            // Truncate safely at char boundary, not byte boundary
            // Use nth() to check if string has more than 40 chars without counting all chars
            let needs_truncation = s.chars().nth(40).is_some();
            let preview = if needs_truncation {
                let truncated: String = s.chars().take(37).collect();
                format!("{}...", truncated)
            } else {
                s.clone()
            };
            format!(
                "{}[{}]: \"{}\"",
                doc_marker,
                idx,
                escape_for_display(&preview)
            )
        }
        Value::Array(arr) => format!("{}[{}] [{} items]", doc_marker, idx, arr.len()),
        Value::Object(obj) => format!("{}[{}] {{{} keys}}", doc_marker, idx, obj.len()),
    }
}

/// Get a value at a specific path in the JSON tree
pub fn get_value_at_path<'a>(value: &'a Value, path: &[String]) -> Option<&'a Value> {
    let mut current = value;
    for part in path {
        match current {
            Value::Object(map) => {
                current = map.get(part)?;
            }
            Value::Array(arr) => {
                let idx: usize = part.parse().ok()?;
                current = arr.get(idx)?;
            }
            _ => return None,
        }
    }
    Some(current)
}

/// Set a value at a specific path in the JSON tree
pub fn set_value_at_path(value: &mut Value, path: &[String], new_value: Value) -> bool {
    if path.is_empty() {
        *value = new_value;
        return true;
    }

    let mut current = value;
    for (i, part) in path.iter().enumerate() {
        if i == path.len() - 1 {
            // Last part, set the value
            match current {
                Value::Object(map) => {
                    map.insert(part.clone(), new_value);
                    return true;
                }
                Value::Array(arr) => {
                    if let Ok(idx) = part.parse::<usize>()
                        && idx < arr.len()
                    {
                        arr[idx] = new_value;
                        return true;
                    }
                    return false;
                }
                _ => return false,
            }
        } else {
            // Navigate deeper
            match current {
                Value::Object(map) => {
                    if let Some(next) = map.get_mut(part) {
                        current = next;
                    } else {
                        return false;
                    }
                }
                Value::Array(arr) => {
                    if let Ok(idx) = part.parse::<usize>() {
                        if idx < arr.len() {
                            current = &mut arr[idx];
                        } else {
                            return false;
                        }
                    } else {
                        return false;
                    }
                }
                _ => return false,
            }
        }
    }
    false
}

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

    #[test]
    fn test_escape_for_display_newlines() {
        assert_eq!(escape_for_display("hello\nworld"), "hello\\nworld");
        assert_eq!(escape_for_display("a\nb\nc"), "a\\nb\\nc");
    }

    #[test]
    fn test_escape_for_display_carriage_returns() {
        assert_eq!(escape_for_display("hello\rworld"), "hello\\rworld");
        assert_eq!(escape_for_display("line\r\nend"), "line\\r\\nend");
    }

    #[test]
    fn test_escape_for_display_tabs() {
        assert_eq!(escape_for_display("hello\tworld"), "hello\\tworld");
    }

    #[test]
    fn test_escape_for_display_mixed() {
        assert_eq!(
            escape_for_display("line1\nline2\r\nline3\tend"),
            "line1\\nline2\\r\\nline3\\tend"
        );
    }

    #[test]
    fn test_escape_for_display_no_special_chars() {
        assert_eq!(escape_for_display("hello world"), "hello world");
        assert_eq!(escape_for_display(""), "");
    }

    #[test]
    fn test_format_tree_label_escapes_newlines_in_string_value() {
        let value = Value::String("line1\nline2\nline3".to_string());
        let label = format_tree_label("key", &value, false, false);
        assert!(
            !label.contains('\n'),
            "Label should not contain actual newlines"
        );
        assert!(
            label.contains("\\n"),
            "Label should contain escaped newlines"
        );
    }

    #[test]
    fn test_format_tree_label_truncates_long_strings() {
        let long_string = "a".repeat(100);
        let value = Value::String(long_string);
        let label = format_tree_label("key", &value, false, false);
        assert!(label.contains("..."), "Long strings should be truncated");
        assert!(label.len() < 100, "Label should be shorter than original");
    }

    #[test]
    fn test_format_tree_label_handles_closure_like_strings() {
        // Simulate a closure string with newlines like what we'd get from Nushell
        let closure_str = "{|| (date now) - $in |\n    if $in < 1hr {\n        'red'\n    }\n}";
        let value = Value::String(closure_str.to_string());
        let label = format_tree_label("datetime", &value, false, false);

        // The label should NOT contain any actual newlines
        assert!(
            !label.contains('\n'),
            "Label should not contain actual newlines: {}",
            label
        );
        // But it SHOULD contain escaped newlines
        assert!(
            label.contains("\\n"),
            "Label should contain escaped newlines: {}",
            label
        );
    }

    #[test]
    fn test_format_array_item_label_escapes_newlines() {
        let value = Value::String("line1\nline2".to_string());
        let label = format_array_item_label(0, &value, false, false);
        assert!(
            !label.contains('\n'),
            "Label should not contain actual newlines"
        );
        assert!(
            label.contains("\\n"),
            "Label should contain escaped newlines"
        );
    }

    #[test]
    fn test_should_suppress_doc_warning_keybindings() {
        // Top-level keybindings should NOT suppress (it has its own doc)
        assert!(!should_suppress_doc_warning(&["keybindings".to_string()]));

        // Nested keybindings items SHOULD suppress
        assert!(should_suppress_doc_warning(&[
            "keybindings".to_string(),
            "0".to_string()
        ]));
        assert!(should_suppress_doc_warning(&[
            "keybindings".to_string(),
            "0".to_string(),
            "name".to_string()
        ]));
        assert!(should_suppress_doc_warning(&[
            "keybindings".to_string(),
            "1".to_string(),
            "keycode".to_string()
        ]));
    }

    #[test]
    fn test_should_suppress_doc_warning_menus() {
        // Top-level menus should NOT suppress (it has its own doc)
        assert!(!should_suppress_doc_warning(&["menus".to_string()]));

        // Nested menus items SHOULD suppress
        assert!(should_suppress_doc_warning(&[
            "menus".to_string(),
            "0".to_string()
        ]));
        assert!(should_suppress_doc_warning(&[
            "menus".to_string(),
            "0".to_string(),
            "source".to_string()
        ]));
    }

    #[test]
    fn test_filter_tree_items_empty_query() {
        // Empty query should return all items unchanged
        let items = vec![
            TreeItem::new_leaf("a".to_string(), "a: value"),
            TreeItem::new_leaf("b".to_string(), "b: value"),
        ];
        let filtered = filter_tree_items(&items, "");
        assert_eq!(filtered.len(), 2);
    }

    #[test]
    fn test_filter_tree_items_matching_leaf() {
        let items = vec![
            TreeItem::new_leaf("color".to_string(), "color: red"),
            TreeItem::new_leaf("size".to_string(), "size: large"),
        ];
        let filtered = filter_tree_items(&items, "color");
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].identifier(), "color");
    }

    #[test]
    fn test_filter_tree_items_case_insensitive() {
        let items = vec![
            TreeItem::new_leaf("Color".to_string(), "Color: red"),
            TreeItem::new_leaf("SIZE".to_string(), "SIZE: large"),
        ];
        let filtered = filter_tree_items(&items, "color");
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].identifier(), "Color");

        let filtered2 = filter_tree_items(&items, "SIZE");
        assert_eq!(filtered2.len(), 1);
    }

    #[test]
    fn test_filter_tree_items_no_matches() {
        let items = vec![
            TreeItem::new_leaf("color".to_string(), "color: red"),
            TreeItem::new_leaf("size".to_string(), "size: large"),
        ];
        let filtered = filter_tree_items(&items, "nonexistent");
        assert_eq!(filtered.len(), 0);
    }

    #[test]
    fn test_filter_tree_items_partial_match() {
        let items = vec![
            TreeItem::new_leaf("color_config".to_string(), "color_config: {}"),
            TreeItem::new_leaf("history".to_string(), "history: {}"),
        ];
        let filtered = filter_tree_items(&items, "color");
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].identifier(), "color_config");
    }

    #[test]
    fn test_should_suppress_doc_warning_other_paths() {
        // Other config paths should NOT suppress
        assert!(!should_suppress_doc_warning(&["history".to_string()]));
        assert!(!should_suppress_doc_warning(&[
            "history".to_string(),
            "file_format".to_string()
        ]));
        assert!(!should_suppress_doc_warning(&[
            "color_config".to_string(),
            "string".to_string()
        ]));
        assert!(!should_suppress_doc_warning(&[]));
    }
}