Skip to main content

ftui_widgets/
json_view.rs

1//! JSON view widget for pretty-printing JSON text.
2//!
3//! Renders formatted JSON with indentation and optional syntax highlighting.
4//! Does not depend on serde; operates on raw JSON strings with a minimal
5//! tokenizer.
6//!
7//! # Example
8//!
9//! ```
10//! use ftui_widgets::json_view::JsonView;
11//!
12//! let json = r#"{"name": "Alice", "age": 30}"#;
13//! let view = JsonView::new(json);
14//! let lines = view.formatted_lines();
15//! assert!(lines.len() > 1); // Pretty-printed across multiple lines
16//! ```
17
18use std::collections::HashSet;
19
20use crate::{StatefulWidget, Widget, draw_text_span};
21use ftui_core::event::{Event, KeyCode, KeyEvent, KeyEventKind};
22use ftui_core::geometry::Rect;
23use ftui_render::frame::Frame;
24use ftui_style::Style;
25
26/// A classified JSON token for rendering.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub enum JsonToken {
29    /// Object key (string before colon).
30    Key(String),
31    /// String value.
32    StringVal(String),
33    /// Number value.
34    Number(String),
35    /// Boolean or null literal.
36    Literal(String),
37    /// Structural character: `{`, `}`, `[`, `]`, `:`, `,`.
38    Punctuation(String),
39    /// Whitespace / indentation.
40    Whitespace(String),
41    /// Newline.
42    Newline,
43    /// Error text (invalid JSON portion).
44    Error(String),
45}
46
47/// One segment of a [`JsonPath`]: an object key or an array index.
48#[derive(Debug, Clone, PartialEq, Eq, Hash)]
49pub enum JsonPathSegment {
50    /// Object member key.
51    Key(String),
52    /// Array element index.
53    Index(usize),
54}
55
56/// A stable path to a foldable node, from the root (empty path) down. Object
57/// members contribute a [`JsonPathSegment::Key`], array elements a
58/// [`JsonPathSegment::Index`]. Folds are keyed by path so they survive a
59/// [`set_source`](JsonView::set_source) that leaves the node in place.
60pub type JsonPath = Vec<JsonPathSegment>;
61
62/// A rendered line produced by [`JsonView::lines_with_state`]: its tokens plus
63/// the fold metadata needed to draw and navigate the tree.
64#[derive(Debug, Clone)]
65pub struct FormattedLine {
66    /// The tokens to draw (already the fold placeholder for a folded node).
67    pub tokens: Vec<JsonToken>,
68    /// The path of the foldable node this line opens, or `None` for a leaf or
69    /// closing line.
70    pub path: Option<JsonPath>,
71    /// Whether this line opens a foldable object/array node.
72    pub foldable: bool,
73    /// Whether this line is currently rendered folded (a placeholder).
74    pub folded: bool,
75    /// Nesting depth (0 at the root).
76    pub depth: usize,
77}
78
79/// Internal annotation of one line of [`JsonView::formatted_lines`].
80#[derive(Debug, Clone)]
81struct LineInfo {
82    tokens: Vec<JsonToken>,
83    path: Option<JsonPath>,
84    foldable: bool,
85    depth: usize,
86    /// Index of the matching closing line (for a foldable opener).
87    close_line: usize,
88    /// Number of direct children (for the folded placeholder count).
89    child_count: usize,
90    /// Whether the closing line of this node carries a trailing comma.
91    trailing_comma: bool,
92}
93
94/// Fold state and cursor for a [`JsonView`] rendered as a [`StatefulWidget`].
95///
96/// Owned by the caller (like `List`/`Table` state). Folds are keyed by
97/// [`JsonPath`]. After each render the visible foldable paths are cached so
98/// [`handle_event`](JsonViewState::handle_event) can resolve the cursor line to
99/// a node without borrowing the view.
100#[derive(Debug, Clone, Default)]
101pub struct JsonViewState {
102    folded: HashSet<JsonPath>,
103    /// The highlighted line (index into the visible lines).
104    pub cursor_line: usize,
105    /// First visible line (vertical scroll offset).
106    pub scroll: usize,
107    /// Foldable path per visible line, cached on render for `handle_event`.
108    visible_paths: Vec<Option<JsonPath>>,
109}
110
111impl JsonViewState {
112    /// A fresh state with nothing folded and the cursor at the top.
113    #[must_use]
114    pub fn new() -> Self {
115        Self::default()
116    }
117
118    /// Toggle the fold state of `path`.
119    pub fn toggle(&mut self, path: &JsonPath) {
120        if !self.folded.remove(path) {
121            self.folded.insert(path.clone());
122        }
123    }
124
125    /// Fold `path`.
126    pub fn fold(&mut self, path: &JsonPath) {
127        self.folded.insert(path.clone());
128    }
129
130    /// Unfold `path`.
131    pub fn unfold(&mut self, path: &JsonPath) {
132        self.folded.remove(path);
133    }
134
135    /// Whether `path` is folded.
136    #[must_use]
137    pub fn is_folded(&self, path: &JsonPath) -> bool {
138        self.folded.contains(path)
139    }
140
141    /// Fold every foldable node in `view`.
142    pub fn fold_all(&mut self, view: &JsonView) {
143        for info in view.line_infos() {
144            if info.foldable
145                && let Some(path) = info.path
146            {
147                self.folded.insert(path);
148            }
149        }
150    }
151
152    /// Unfold everything.
153    pub fn unfold_all(&mut self) {
154        self.folded.clear();
155    }
156
157    /// Number of folded nodes.
158    #[must_use]
159    pub fn folded_count(&self) -> usize {
160        self.folded.len()
161    }
162
163    /// Handle a key event against the last rendered layout: `Enter`/`Space`
164    /// toggle the node on the cursor line (no-op on a leaf), `Up`/`Down` move
165    /// the cursor, `PageUp`/`PageDown` move by ten, `Home`/`End` jump to the
166    /// ends. Returns whether the state changed. Requires a prior render to have
167    /// cached the visible layout.
168    pub fn handle_event(&mut self, event: &Event) -> bool {
169        let Event::Key(KeyEvent { code, kind, .. }) = event else {
170            return false;
171        };
172        if *kind == KeyEventKind::Release {
173            return false;
174        }
175        let count = self.visible_paths.len();
176        if count == 0 {
177            return false;
178        }
179        let last = count - 1;
180        match code {
181            KeyCode::Enter | KeyCode::Char(' ') => {
182                if let Some(Some(path)) = self.visible_paths.get(self.cursor_line) {
183                    let path = path.clone();
184                    self.toggle(&path);
185                    true
186                } else {
187                    false
188                }
189            }
190            KeyCode::Up => {
191                let next = self.cursor_line.saturating_sub(1);
192                self.set_cursor(next)
193            }
194            KeyCode::Down => {
195                let next = (self.cursor_line + 1).min(last);
196                self.set_cursor(next)
197            }
198            KeyCode::PageUp => {
199                let next = self.cursor_line.saturating_sub(10);
200                self.set_cursor(next)
201            }
202            KeyCode::PageDown => {
203                let next = (self.cursor_line + 10).min(last);
204                self.set_cursor(next)
205            }
206            KeyCode::Home => self.set_cursor(0),
207            KeyCode::End => self.set_cursor(last),
208            _ => false,
209        }
210    }
211
212    fn set_cursor(&mut self, line: usize) -> bool {
213        if line == self.cursor_line {
214            false
215        } else {
216            self.cursor_line = line;
217            true
218        }
219    }
220}
221
222/// Widget that renders pretty-printed JSON with syntax coloring.
223#[derive(Debug, Clone)]
224pub struct JsonView {
225    source: String,
226    indent: usize,
227    key_style: Style,
228    string_style: Style,
229    number_style: Style,
230    literal_style: Style,
231    punct_style: Style,
232    error_style: Style,
233    cursor_style: Style,
234}
235
236impl Default for JsonView {
237    fn default() -> Self {
238        Self::new("")
239    }
240}
241
242impl JsonView {
243    /// Create a new JSON view from a raw JSON string.
244    #[must_use]
245    pub fn new(source: impl Into<String>) -> Self {
246        Self {
247            source: source.into(),
248            indent: 2,
249            key_style: Style::new().bold(),
250            string_style: Style::default(),
251            number_style: Style::default(),
252            literal_style: Style::default(),
253            punct_style: Style::default(),
254            error_style: Style::default(),
255            cursor_style: Style::new().reverse(),
256        }
257    }
258
259    /// Set the indentation width.
260    #[must_use]
261    pub fn with_indent(mut self, indent: usize) -> Self {
262        self.indent = indent;
263        self
264    }
265
266    /// Set style for object keys.
267    #[must_use]
268    pub fn with_key_style(mut self, style: Style) -> Self {
269        self.key_style = style;
270        self
271    }
272
273    /// Set style for string values.
274    #[must_use]
275    pub fn with_string_style(mut self, style: Style) -> Self {
276        self.string_style = style;
277        self
278    }
279
280    /// Set style for numbers.
281    #[must_use]
282    pub fn with_number_style(mut self, style: Style) -> Self {
283        self.number_style = style;
284        self
285    }
286
287    /// Set style for boolean/null literals.
288    #[must_use]
289    pub fn with_literal_style(mut self, style: Style) -> Self {
290        self.literal_style = style;
291        self
292    }
293
294    /// Set style for punctuation.
295    #[must_use]
296    pub fn with_punct_style(mut self, style: Style) -> Self {
297        self.punct_style = style;
298        self
299    }
300
301    /// Set style for error text.
302    #[must_use]
303    pub fn with_error_style(mut self, style: Style) -> Self {
304        self.error_style = style;
305        self
306    }
307
308    /// Set the style for the highlighted cursor line in the stateful
309    /// (foldable) rendering. Defaults to reverse video.
310    #[must_use]
311    pub fn with_cursor_style(mut self, style: Style) -> Self {
312        self.cursor_style = style;
313        self
314    }
315
316    /// Set the source JSON.
317    pub fn set_source(&mut self, source: impl Into<String>) {
318        self.source = source.into();
319    }
320
321    /// Get the source JSON.
322    #[must_use]
323    pub fn source(&self) -> &str {
324        &self.source
325    }
326
327    /// Pretty-format the JSON into lines of tokens for rendering.
328    #[must_use]
329    pub fn formatted_lines(&self) -> Vec<Vec<JsonToken>> {
330        let trimmed = self.source.trim();
331        if trimmed.is_empty() {
332            return vec![];
333        }
334
335        let mut lines: Vec<Vec<JsonToken>> = Vec::new();
336        let mut current_line: Vec<JsonToken> = Vec::new();
337        let mut depth: usize = 0;
338        let mut chars = trimmed.chars().peekable();
339
340        while let Some(&ch) = chars.peek() {
341            match ch {
342                '{' | '[' => {
343                    chars.next();
344                    current_line.push(JsonToken::Punctuation(ch.to_string()));
345                    // Check if next non-whitespace is closing bracket
346                    skip_ws(&mut chars);
347                    let next = chars.peek().copied();
348                    if next == Some('}') || next == Some(']') {
349                        // Empty object/array
350                        let closing = chars.next().unwrap();
351                        current_line.push(JsonToken::Punctuation(closing.to_string()));
352                        // Check for comma
353                        skip_ws(&mut chars);
354                        if chars.peek() == Some(&',') {
355                            chars.next();
356                            current_line.push(JsonToken::Punctuation(",".to_string()));
357                        }
358                    } else {
359                        depth += 1;
360                        lines.push(current_line);
361                        current_line = vec![JsonToken::Whitespace(make_indent(
362                            depth.min(32),
363                            self.indent,
364                        ))];
365                    }
366                }
367                '}' | ']' => {
368                    chars.next();
369                    depth = depth.saturating_sub(1);
370                    lines.push(current_line);
371                    current_line = vec![
372                        JsonToken::Whitespace(make_indent(depth, self.indent)),
373                        JsonToken::Punctuation(ch.to_string()),
374                    ];
375                    // Check for comma
376                    skip_ws(&mut chars);
377                    if chars.peek() == Some(&',') {
378                        chars.next();
379                        current_line.push(JsonToken::Punctuation(",".to_string()));
380                    }
381                }
382                '"' => {
383                    let s = read_string(&mut chars);
384                    skip_ws(&mut chars);
385                    if chars.peek() == Some(&':') {
386                        // This is a key
387                        current_line.push(JsonToken::Key(s));
388                        chars.next();
389                        current_line.push(JsonToken::Punctuation(": ".to_string()));
390                        skip_ws(&mut chars);
391                    } else {
392                        current_line.push(JsonToken::StringVal(s));
393                        // Check for comma
394                        skip_ws(&mut chars);
395                        if chars.peek() == Some(&',') {
396                            chars.next();
397                            current_line.push(JsonToken::Punctuation(",".to_string()));
398                            lines.push(current_line);
399                            current_line = vec![JsonToken::Whitespace(make_indent(
400                                depth.min(32),
401                                self.indent,
402                            ))];
403                        }
404                    }
405                }
406                ',' => {
407                    chars.next();
408                    current_line.push(JsonToken::Punctuation(",".to_string()));
409                    lines.push(current_line);
410                    current_line = vec![JsonToken::Whitespace(make_indent(
411                        depth.min(32),
412                        self.indent,
413                    ))];
414                }
415                ':' => {
416                    chars.next();
417                    current_line.push(JsonToken::Punctuation(": ".to_string()));
418                    skip_ws(&mut chars);
419                }
420                ' ' | '\t' | '\r' | '\n' => {
421                    chars.next();
422                }
423                _ => {
424                    // Number, boolean, null, or error
425                    let literal = read_literal(&mut chars);
426                    let tok = classify_literal(&literal);
427                    current_line.push(tok);
428                    // Check for comma
429                    skip_ws(&mut chars);
430                    if chars.peek() == Some(&',') {
431                        chars.next();
432                        current_line.push(JsonToken::Punctuation(",".to_string()));
433                        lines.push(current_line);
434                        current_line = vec![JsonToken::Whitespace(make_indent(
435                            depth.min(32),
436                            self.indent,
437                        ))];
438                    }
439                }
440            }
441        }
442
443        if !current_line.is_empty() {
444            lines.push(current_line);
445        }
446
447        lines
448    }
449
450    /// Annotate [`formatted_lines`](Self::formatted_lines) with fold metadata:
451    /// each line's nesting depth, whether it opens a foldable object/array
452    /// node, that node's [`JsonPath`], its matching closing line and its direct
453    /// child count. Tokens are copied unchanged, so
454    /// `lines_with_state(&JsonViewState::default())` reproduces the flat output
455    /// exactly.
456    fn line_infos(&self) -> Vec<LineInfo> {
457        let lines = self.formatted_lines();
458
459        struct Frame {
460            child_count: usize,
461            path: JsonPath,
462            opener: usize,
463        }
464
465        let mut infos: Vec<LineInfo> = Vec::with_capacity(lines.len());
466        let mut stack: Vec<Frame> = Vec::new();
467
468        // The pretty-printer can put a closing bracket and the next sibling on
469        // the same line (`},"k": {` or `},"k": 1`). Each line therefore may
470        // close the innermost container (at its start) and then open or start a
471        // new sibling (its rest). Both are handled here.
472        for (i, tokens) in lines.into_iter().enumerate() {
473            let closes = line_closes(&tokens);
474            let opens = line_opens(&tokens);
475
476            // A leading close pops and finalises the innermost container.
477            if closes && let Some(frame) = stack.pop() {
478                infos[frame.opener].close_line = i;
479                infos[frame.opener].child_count = frame.child_count;
480                infos[frame.opener].trailing_comma = line_close_has_comma(&tokens);
481            }
482
483            // Whatever remains on the line (an opener or a leaf value) is a new
484            // direct child of the current parent frame; a bare closing line is
485            // not.
486            let contributes = opens || !closes || line_has_content_after_close(&tokens);
487            let index = if contributes {
488                stack.last().map(|f| f.child_count)
489            } else {
490                None
491            };
492            if contributes && let Some(frame) = stack.last_mut() {
493                frame.child_count += 1;
494            }
495
496            let depth = stack.len();
497
498            if opens {
499                let mut path = stack.last().map(|f| f.path.clone()).unwrap_or_default();
500                if let Some(key) = line_key(&tokens) {
501                    path.push(JsonPathSegment::Key(key));
502                } else if let Some(idx) = index {
503                    path.push(JsonPathSegment::Index(idx));
504                }
505                // (no segment for the root container: its path stays empty)
506                infos.push(LineInfo {
507                    tokens,
508                    path: Some(path.clone()),
509                    foldable: true,
510                    depth,
511                    close_line: i,
512                    child_count: 0,
513                    trailing_comma: false,
514                });
515                stack.push(Frame {
516                    child_count: 0,
517                    path,
518                    opener: i,
519                });
520            } else {
521                infos.push(LineInfo {
522                    tokens,
523                    path: None,
524                    foldable: false,
525                    depth,
526                    close_line: i,
527                    child_count: 0,
528                    trailing_comma: false,
529                });
530            }
531        }
532
533        // Unclosed containers (malformed JSON) are not foldable.
534        for frame in stack {
535            infos[frame.opener].foldable = false;
536            infos[frame.opener].path = None;
537        }
538
539        infos
540    }
541
542    /// Format the JSON into display lines honouring `state`'s fold set: a folded
543    /// node collapses to a single placeholder line (`key: ▸ {…} (n keys)` /
544    /// `▸ […] (n items)`) and its descendants and closing line are hidden. With
545    /// the default (empty) state this equals [`formatted_lines`](Self::formatted_lines).
546    #[must_use]
547    pub fn lines_with_state(&self, state: &JsonViewState) -> Vec<FormattedLine> {
548        let infos = self.line_infos();
549        let mut out = Vec::with_capacity(infos.len());
550        let mut i = 0;
551        // When the previous folded node's closing bracket shares a line with the
552        // next sibling, that sibling line is emitted with the leading close
553        // stripped (the bracket and its comma are already in the placeholder).
554        let mut strip = false;
555        while i < infos.len() {
556            let info = &infos[i];
557            let tokens = if strip {
558                strip_close_prefix(&info.tokens)
559            } else {
560                info.tokens.clone()
561            };
562            strip = false;
563
564            if info.foldable
565                && let Some(path) = &info.path
566                && state.is_folded(path)
567            {
568                out.push(placeholder_from_tokens(tokens, info));
569                let close = info.close_line;
570                if close > i && line_has_content_after_close(&infos[close].tokens) {
571                    // The closing line also starts a sibling: strip its close.
572                    i = close;
573                    strip = true;
574                } else {
575                    // A bare closing line is fully represented by the placeholder.
576                    i = close.max(i) + 1;
577                }
578                continue;
579            }
580
581            out.push(FormattedLine {
582                tokens,
583                path: info.path.clone(),
584                foldable: info.foldable,
585                folded: false,
586                depth: info.depth,
587            });
588            i += 1;
589        }
590        out
591    }
592
593    /// Draw one line's tokens at row `y`, optionally highlighting it as the
594    /// cursor line.
595    fn draw_line(
596        &self,
597        frame: &mut Frame,
598        area: Rect,
599        y: u16,
600        tokens: &[JsonToken],
601        is_cursor: bool,
602        styling: bool,
603    ) {
604        let max_x = area.right();
605        let mut x = area.x;
606        for token in tokens {
607            let (text, style) = match token {
608                JsonToken::Key(s) => (s.as_str(), self.key_style),
609                JsonToken::StringVal(s) => (s.as_str(), self.string_style),
610                JsonToken::Number(s) => (s.as_str(), self.number_style),
611                JsonToken::Literal(s) => (s.as_str(), self.literal_style),
612                JsonToken::Punctuation(s) => (s.as_str(), self.punct_style),
613                JsonToken::Whitespace(s) => (s.as_str(), Style::default()),
614                JsonToken::Error(s) => (s.as_str(), self.error_style),
615                JsonToken::Newline => continue,
616            };
617            let style = if styling { style } else { Style::default() };
618            x = draw_text_span(frame, x, y, text, style, max_x);
619        }
620        if is_cursor && styling {
621            for cx in area.x..area.right() {
622                if let Some(cell) = frame.buffer.get_mut(cx, y) {
623                    crate::apply_style(cell, self.cursor_style);
624                }
625            }
626        }
627    }
628}
629
630/// Build the placeholder line for a folded node from its (possibly
631/// close-stripped) opener tokens: drop the opening bracket and append a
632/// `▸ {…} (n keys)` / `▸ […] (n items)` marker, carrying the node's trailing
633/// comma if it had one.
634fn placeholder_from_tokens(mut tokens: Vec<JsonToken>, info: &LineInfo) -> FormattedLine {
635    let is_array = matches!(tokens.last(), Some(JsonToken::Punctuation(p)) if p == "[");
636    tokens.pop(); // drop the opening bracket
637    let (open, close, unit) = if is_array {
638        ('[', ']', "items")
639    } else {
640        ('{', '}', "keys")
641    };
642    let comma = if info.trailing_comma { "," } else { "" };
643    let summary = format!("▸ {open}…{close} ({} {unit}){comma}", info.child_count);
644    tokens.push(JsonToken::Punctuation(summary));
645    FormattedLine {
646        tokens,
647        path: info.path.clone(),
648        foldable: true,
649        folded: true,
650        depth: info.depth,
651    }
652}
653
654fn line_opens(tokens: &[JsonToken]) -> bool {
655    matches!(tokens.last(), Some(JsonToken::Punctuation(p)) if p == "{" || p == "[")
656}
657
658fn line_closes(tokens: &[JsonToken]) -> bool {
659    for t in tokens {
660        match t {
661            JsonToken::Whitespace(_) => {}
662            JsonToken::Punctuation(p) => return p == "}" || p == "]",
663            _ => return false,
664        }
665    }
666    false
667}
668
669fn line_key(tokens: &[JsonToken]) -> Option<String> {
670    tokens.iter().find_map(|t| {
671        if let JsonToken::Key(k) = t {
672            let unquoted = k
673                .strip_prefix('"')
674                .and_then(|s| s.strip_suffix('"'))
675                .unwrap_or(k);
676            Some(unquoted.to_string())
677        } else {
678            None
679        }
680    })
681}
682
683/// Whether the leading closing bracket of `tokens` is followed by a comma
684/// (`},` or `],`) — the folded node's trailing comma.
685fn line_close_has_comma(tokens: &[JsonToken]) -> bool {
686    let mut it = tokens
687        .iter()
688        .skip_while(|t| matches!(t, JsonToken::Whitespace(_)));
689    match it.next() {
690        Some(JsonToken::Punctuation(p)) if p == "}" || p == "]" => {
691            matches!(it.next(), Some(JsonToken::Punctuation(c)) if c == ",")
692        }
693        _ => false,
694    }
695}
696
697/// Whether, after any leading close bracket and comma, the line still carries a
698/// sibling (a key or value) — i.e. the closing bracket shares the line with the
699/// next member.
700fn line_has_content_after_close(tokens: &[JsonToken]) -> bool {
701    strip_close_prefix(tokens)
702        .iter()
703        .any(|t| !matches!(t, JsonToken::Whitespace(_)))
704}
705
706/// Remove a leading closing bracket (and its trailing comma) from a line,
707/// preserving the indentation, so a merged `},"k": {` becomes `"k": {`.
708fn strip_close_prefix(tokens: &[JsonToken]) -> Vec<JsonToken> {
709    let mut result = Vec::with_capacity(tokens.len());
710    let mut idx = 0;
711    while let Some(JsonToken::Whitespace(_)) = tokens.get(idx) {
712        result.push(tokens[idx].clone());
713        idx += 1;
714    }
715    if let Some(JsonToken::Punctuation(p)) = tokens.get(idx)
716        && (p == "}" || p == "]")
717    {
718        idx += 1;
719        if let Some(JsonToken::Punctuation(c)) = tokens.get(idx)
720            && c == ","
721        {
722            idx += 1;
723        }
724    }
725    result.extend_from_slice(&tokens[idx..]);
726    result
727}
728
729fn make_indent(depth: usize, width: usize) -> String {
730    " ".repeat(depth * width)
731}
732
733fn skip_ws(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) {
734    while let Some(&ch) = chars.peek() {
735        if ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' {
736            chars.next();
737        } else {
738            break;
739        }
740    }
741}
742
743fn read_string(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> String {
744    let mut s = String::new();
745    s.push('"');
746    chars.next(); // consume opening quote
747    let mut escaped = false;
748    for ch in chars.by_ref() {
749        s.push(ch);
750        if escaped {
751            escaped = false;
752        } else if ch == '\\' {
753            escaped = true;
754        } else if ch == '"' {
755            break;
756        }
757    }
758    s
759}
760
761fn read_literal(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> String {
762    let mut s = String::new();
763    while let Some(&ch) = chars.peek() {
764        if ch == ','
765            || ch == '}'
766            || ch == ']'
767            || ch == ':'
768            || ch == ' '
769            || ch == '\n'
770            || ch == '\r'
771            || ch == '\t'
772        {
773            break;
774        }
775        s.push(ch);
776        chars.next();
777    }
778    s
779}
780
781fn classify_literal(s: &str) -> JsonToken {
782    match s {
783        "true" | "false" | "null" => JsonToken::Literal(s.to_string()),
784        _ => {
785            // Try as number
786            if s.bytes().all(|b| {
787                b.is_ascii_digit() || b == b'.' || b == b'-' || b == b'+' || b == b'e' || b == b'E'
788            }) && !s.is_empty()
789            {
790                JsonToken::Number(s.to_string())
791            } else {
792                JsonToken::Error(s.to_string())
793            }
794        }
795    }
796}
797
798impl Widget for JsonView {
799    fn render(&self, area: Rect, frame: &mut Frame) {
800        if area.width == 0 || area.height == 0 {
801            return;
802        }
803
804        let deg = frame.buffer.degradation;
805        frame.buffer.fill(area, ftui_render::cell::Cell::default());
806        if !deg.render_content() {
807            return;
808        }
809        let lines = self.formatted_lines();
810        let max_x = area.right();
811
812        for (row_idx, tokens) in lines.iter().enumerate() {
813            if row_idx >= area.height as usize {
814                break;
815            }
816
817            let y = area.y.saturating_add(row_idx as u16);
818            let mut x = area.x;
819
820            for token in tokens {
821                let (text, style) = match token {
822                    JsonToken::Key(s) => (s.as_str(), self.key_style),
823                    JsonToken::StringVal(s) => (s.as_str(), self.string_style),
824                    JsonToken::Number(s) => (s.as_str(), self.number_style),
825                    JsonToken::Literal(s) => (s.as_str(), self.literal_style),
826                    JsonToken::Punctuation(s) => (s.as_str(), self.punct_style),
827                    JsonToken::Whitespace(s) => (s.as_str(), Style::default()),
828                    JsonToken::Error(s) => (s.as_str(), self.error_style),
829                    JsonToken::Newline => continue,
830                };
831
832                if deg.apply_styling() {
833                    x = draw_text_span(frame, x, y, text, style, max_x);
834                } else {
835                    x = draw_text_span(frame, x, y, text, Style::default(), max_x);
836                }
837            }
838        }
839    }
840
841    fn is_essential(&self) -> bool {
842        false
843    }
844}
845
846impl StatefulWidget for JsonView {
847    type State = JsonViewState;
848
849    fn render(&self, area: Rect, frame: &mut Frame, state: &mut JsonViewState) {
850        if area.width == 0 || area.height == 0 {
851            return;
852        }
853        let deg = frame.buffer.degradation;
854        frame.buffer.fill(area, ftui_render::cell::Cell::default());
855        if !deg.render_content() {
856            state.visible_paths.clear();
857            return;
858        }
859
860        #[cfg(feature = "tracing")]
861        let _span = tracing::debug_span!(
862            "widget_render",
863            widget = "JsonView",
864            folded_count = state.folded_count(),
865        )
866        .entered();
867
868        let lines = self.lines_with_state(state);
869        state.visible_paths = lines
870            .iter()
871            .map(|l| if l.foldable { l.path.clone() } else { None })
872            .collect();
873
874        let visible = lines.len();
875        if visible == 0 {
876            state.cursor_line = 0;
877            state.scroll = 0;
878            return;
879        }
880        if state.cursor_line >= visible {
881            state.cursor_line = visible - 1;
882        }
883        // Keep the cursor inside the viewport.
884        let height = area.height as usize;
885        if state.cursor_line < state.scroll {
886            state.scroll = state.cursor_line;
887        } else if state.cursor_line >= state.scroll + height {
888            state.scroll = state.cursor_line + 1 - height;
889        }
890        if state.scroll >= visible {
891            state.scroll = visible - 1;
892        }
893
894        for row in 0..height {
895            let idx = state.scroll + row;
896            if idx >= visible {
897                break;
898            }
899            let y = area.y + row as u16;
900            self.draw_line(
901                frame,
902                area,
903                y,
904                &lines[idx].tokens,
905                idx == state.cursor_line,
906                deg.apply_styling(),
907            );
908        }
909    }
910}
911
912#[cfg(test)]
913mod tests {
914    use super::*;
915    use ftui_render::budget::DegradationLevel;
916    use ftui_render::cell::{CellAttrs, PackedRgba};
917    use ftui_render::frame::Frame;
918    use ftui_render::grapheme_pool::GraphemePool;
919
920    #[test]
921    fn empty_source() {
922        let view = JsonView::new("");
923        assert!(view.formatted_lines().is_empty());
924    }
925
926    #[test]
927    fn simple_object() {
928        let view = JsonView::new(r#"{"a": 1}"#);
929        let lines = view.formatted_lines();
930        assert!(lines.len() >= 3); // { + content + }
931    }
932
933    #[test]
934    fn nested_object() {
935        let view = JsonView::new(r#"{"a": {"b": 2}}"#);
936        let lines = view.formatted_lines();
937        assert!(lines.len() >= 3);
938    }
939
940    #[test]
941    fn array() {
942        let view = JsonView::new(r#"[1, 2, 3]"#);
943        let lines = view.formatted_lines();
944        assert!(lines.len() >= 3);
945    }
946
947    #[test]
948    fn empty_object() {
949        let view = JsonView::new(r#"{}"#);
950        let lines = view.formatted_lines();
951        assert!(!lines.is_empty());
952        // Should be compact: single line with {}
953    }
954
955    #[test]
956    fn empty_array() {
957        let view = JsonView::new(r#"[]"#);
958        let lines = view.formatted_lines();
959        assert!(!lines.is_empty());
960    }
961
962    #[test]
963    fn string_values() {
964        let view = JsonView::new(r#"{"msg": "hello world"}"#);
965        let lines = view.formatted_lines();
966        // Should contain StringVal token with quoted string
967        let has_string = lines.iter().any(|line| {
968            line.iter()
969                .any(|t| matches!(t, JsonToken::StringVal(s) if s.contains("hello")))
970        });
971        assert!(has_string);
972    }
973
974    #[test]
975    fn boolean_and_null() {
976        let view = JsonView::new(r#"{"a": true, "b": false, "c": null}"#);
977        let lines = view.formatted_lines();
978        let has_literal = lines.iter().any(|line| {
979            line.iter()
980                .any(|t| matches!(t, JsonToken::Literal(s) if s == "true"))
981        });
982        assert!(has_literal);
983    }
984
985    #[test]
986    fn numbers() {
987        let view = JsonView::new(r#"{"x": 42, "y": -3.14}"#);
988        let lines = view.formatted_lines();
989        let has_number = lines.iter().any(|line| {
990            line.iter()
991                .any(|t| matches!(t, JsonToken::Number(s) if s == "42"))
992        });
993        assert!(has_number);
994    }
995
996    #[test]
997    fn escaped_string() {
998        let view = JsonView::new(r#"{"msg": "hello \"world\""}"#);
999        let lines = view.formatted_lines();
1000        let has_escaped = lines.iter().any(|line| {
1001            line.iter()
1002                .any(|t| matches!(t, JsonToken::StringVal(s) if s.contains("\\\"")))
1003        });
1004        assert!(has_escaped);
1005    }
1006
1007    #[test]
1008    fn indent_width() {
1009        let view = JsonView::new(r#"{"a": 1}"#).with_indent(4);
1010        let lines = view.formatted_lines();
1011        let has_4_indent = lines.iter().any(|line| {
1012            line.iter()
1013                .any(|t| matches!(t, JsonToken::Whitespace(s) if s == "    "))
1014        });
1015        assert!(has_4_indent);
1016    }
1017
1018    #[test]
1019    fn render_basic() {
1020        let view = JsonView::new(r#"{"key": "value"}"#);
1021        let mut pool = GraphemePool::new();
1022        let mut frame = Frame::new(40, 10, &mut pool);
1023        let area = Rect::new(0, 0, 40, 10);
1024        Widget::render(&view, area, &mut frame);
1025
1026        // First char should be '{'
1027        let cell = frame.buffer.get(0, 0).unwrap();
1028        assert_eq!(cell.content.as_char(), Some('{'));
1029    }
1030
1031    #[test]
1032    fn render_zero_area() {
1033        let view = JsonView::new(r#"{"a": 1}"#);
1034        let mut pool = GraphemePool::new();
1035        let mut frame = Frame::new(40, 10, &mut pool);
1036        Widget::render(&view, Rect::new(0, 0, 0, 0), &mut frame); // No panic
1037    }
1038
1039    #[test]
1040    fn render_truncated_height() {
1041        let view = JsonView::new(r#"{"a": 1, "b": 2, "c": 3}"#);
1042        let mut pool = GraphemePool::new();
1043        let mut frame = Frame::new(40, 2, &mut pool);
1044        let area = Rect::new(0, 0, 40, 2);
1045        Widget::render(&view, area, &mut frame); // Only first 2 lines, no panic
1046    }
1047
1048    #[test]
1049    fn is_not_essential() {
1050        let view = JsonView::new("");
1051        assert!(!view.is_essential());
1052    }
1053
1054    #[test]
1055    fn default_impl() {
1056        let view = JsonView::default();
1057        assert!(view.source().is_empty());
1058    }
1059
1060    #[test]
1061    fn set_source() {
1062        let mut view = JsonView::new("");
1063        view.set_source(r#"{"a": 1}"#);
1064        assert!(!view.formatted_lines().is_empty());
1065    }
1066
1067    #[test]
1068    fn plain_literal() {
1069        let view = JsonView::new("42");
1070        let lines = view.formatted_lines();
1071        assert_eq!(lines.len(), 1);
1072    }
1073
1074    // ─── Edge-case tests (bd-2agoi) ────────────────────────────────────
1075
1076    #[test]
1077    fn whitespace_only_source() {
1078        let view = JsonView::new("   \n\t  ");
1079        assert!(view.formatted_lines().is_empty());
1080    }
1081
1082    #[test]
1083    fn deeply_nested_objects() {
1084        // 35 levels deep — depth clamped at 32 for indent
1085        let open: String = "{\"a\": ".repeat(35);
1086        let close: String = "}".repeat(35);
1087        let json = format!("{open}1{close}");
1088        let view = JsonView::new(json);
1089        let lines = view.formatted_lines();
1090        // Should not panic and produce output
1091        assert!(lines.len() > 10);
1092    }
1093
1094    #[test]
1095    fn scientific_notation_number() {
1096        let view = JsonView::new(r#"{"x": 1.23e+10}"#);
1097        let lines = view.formatted_lines();
1098        let has_sci = lines.iter().any(|line| {
1099            line.iter()
1100                .any(|t| matches!(t, JsonToken::Number(s) if s.contains("e+")))
1101        });
1102        assert!(has_sci, "scientific notation should be Number: {lines:?}");
1103    }
1104
1105    #[test]
1106    fn empty_string_key_and_value() {
1107        let view = JsonView::new(r#"{"": ""}"#);
1108        let lines = view.formatted_lines();
1109        let has_empty_key = lines.iter().any(|line| {
1110            line.iter()
1111                .any(|t| matches!(t, JsonToken::Key(s) if s == "\"\""))
1112        });
1113        assert!(has_empty_key, "empty key should be present: {lines:?}");
1114    }
1115
1116    #[test]
1117    fn unicode_in_strings() {
1118        let view = JsonView::new(r#"{"emoji": "🎉🚀"}"#);
1119        let lines = view.formatted_lines();
1120        let has_emoji = lines.iter().any(|line| {
1121            line.iter()
1122                .any(|t| matches!(t, JsonToken::StringVal(s) if s.contains('🎉')))
1123        });
1124        assert!(has_emoji);
1125    }
1126
1127    #[test]
1128    fn unclosed_string() {
1129        // Missing closing quote — tokenizer reads until EOF
1130        let view = JsonView::new(r#"{"key": "val"#);
1131        let lines = view.formatted_lines();
1132        // Should not panic; produces some output
1133        assert!(!lines.is_empty());
1134    }
1135
1136    #[test]
1137    fn unclosed_object() {
1138        let view = JsonView::new(r#"{"a": 1"#);
1139        let lines = view.formatted_lines();
1140        assert!(!lines.is_empty());
1141    }
1142
1143    #[test]
1144    fn unclosed_array() {
1145        let view = JsonView::new(r#"[1, 2, 3"#);
1146        let lines = view.formatted_lines();
1147        assert!(!lines.is_empty());
1148    }
1149
1150    #[test]
1151    fn nested_empty_containers() {
1152        let view = JsonView::new(r#"{"a": [], "b": {}}"#);
1153        let lines = view.formatted_lines();
1154        // [] and {} should appear compact
1155        let flat = lines
1156            .iter()
1157            .map(|line| {
1158                line.iter()
1159                    .filter_map(|t| match t {
1160                        JsonToken::Punctuation(s) => Some(s.as_str()),
1161                        _ => None,
1162                    })
1163                    .collect::<String>()
1164            })
1165            .collect::<String>();
1166        assert!(flat.contains("[]"), "empty array should be compact: {flat}");
1167        assert!(
1168            flat.contains("{}"),
1169            "empty object should be compact: {flat}"
1170        );
1171    }
1172
1173    #[test]
1174    fn array_of_mixed_types() {
1175        let view = JsonView::new(r#"[1, "two", true, null]"#);
1176        let lines = view.formatted_lines();
1177        let all_tokens: Vec<&JsonToken> = lines.iter().flat_map(|l| l.iter()).collect();
1178        assert!(all_tokens.iter().any(|t| matches!(t, JsonToken::Number(_))));
1179        assert!(
1180            all_tokens
1181                .iter()
1182                .any(|t| matches!(t, JsonToken::StringVal(_)))
1183        );
1184        assert!(
1185            all_tokens
1186                .iter()
1187                .any(|t| matches!(t, JsonToken::Literal(s) if s == "true"))
1188        );
1189        assert!(
1190            all_tokens
1191                .iter()
1192                .any(|t| matches!(t, JsonToken::Literal(s) if s == "null"))
1193        );
1194    }
1195
1196    #[test]
1197    fn zero_indent_width() {
1198        let view = JsonView::new(r#"{"a": 1}"#).with_indent(0);
1199        let lines = view.formatted_lines();
1200        // Indentation should be empty strings
1201        for line in &lines {
1202            for token in line {
1203                if let JsonToken::Whitespace(s) = token {
1204                    assert!(s.is_empty(), "zero indent should produce empty whitespace");
1205                }
1206            }
1207        }
1208    }
1209
1210    #[test]
1211    fn bare_string_top_level() {
1212        let view = JsonView::new(r#""hello""#);
1213        let lines = view.formatted_lines();
1214        assert_eq!(lines.len(), 1);
1215        assert!(
1216            lines[0]
1217                .iter()
1218                .any(|t| matches!(t, JsonToken::StringVal(s) if s.contains("hello")))
1219        );
1220    }
1221
1222    #[test]
1223    fn error_token_for_invalid_literal() {
1224        let view = JsonView::new(r#"{"a": undefined}"#);
1225        let lines = view.formatted_lines();
1226        let has_error = lines
1227            .iter()
1228            .any(|line| line.iter().any(|t| matches!(t, JsonToken::Error(_))));
1229        assert!(has_error, "undefined should produce Error token");
1230    }
1231
1232    #[test]
1233    fn clone_independence() {
1234        let view = JsonView::new(r#"{"a": 1}"#);
1235        let cloned = view.clone();
1236        assert_eq!(view.source(), cloned.source());
1237    }
1238
1239    #[test]
1240    fn debug_format() {
1241        let view = JsonView::new("{}");
1242        let dbg = format!("{view:?}");
1243        assert!(dbg.contains("JsonView"));
1244    }
1245
1246    #[test]
1247    fn style_builders_chain() {
1248        let view = JsonView::new("{}")
1249            .with_indent(4)
1250            .with_key_style(Style::new().bold())
1251            .with_string_style(Style::default())
1252            .with_number_style(Style::default())
1253            .with_literal_style(Style::default())
1254            .with_punct_style(Style::default())
1255            .with_error_style(Style::default());
1256        assert_eq!(view.indent, 4);
1257    }
1258
1259    #[test]
1260    fn render_width_one() {
1261        let view = JsonView::new(r#"{"a": 1}"#);
1262        let mut pool = GraphemePool::new();
1263        let mut frame = Frame::new(1, 10, &mut pool);
1264        Widget::render(&view, Rect::new(0, 0, 1, 10), &mut frame);
1265        // Should render first char of each line without panic
1266        let cell = frame.buffer.get(0, 0).unwrap();
1267        assert_eq!(cell.content.as_char(), Some('{'));
1268    }
1269
1270    #[test]
1271    fn render_no_styling_drops_token_styles() {
1272        let key_color = PackedRgba::rgb(1, 2, 3);
1273        let number_color = PackedRgba::rgb(4, 5, 6);
1274        let view = JsonView::new(r#"{"key": 1}"#)
1275            .with_key_style(Style::new().fg(key_color).bold())
1276            .with_number_style(Style::new().fg(number_color).italic());
1277        let mut pool = GraphemePool::new();
1278        let mut frame = Frame::new(40, 10, &mut pool);
1279        frame.buffer.degradation = DegradationLevel::NoStyling;
1280        Widget::render(&view, Rect::new(0, 0, 40, 10), &mut frame);
1281
1282        let key_cell = frame.buffer.get(2, 1).unwrap();
1283        assert_eq!(key_cell.content.as_char(), Some('"'));
1284        assert_ne!(key_cell.fg, key_color);
1285        assert_eq!(key_cell.attrs, CellAttrs::NONE);
1286
1287        let number_cell = frame.buffer.get(9, 1).unwrap();
1288        assert_eq!(number_cell.content.as_char(), Some('1'));
1289        assert_ne!(number_cell.fg, number_color);
1290        assert_eq!(number_cell.attrs, CellAttrs::NONE);
1291    }
1292
1293    #[test]
1294    fn render_skeleton_is_noop() {
1295        let view = JsonView::new(r#"{"key": "value"}"#);
1296        let mut pool = GraphemePool::new();
1297        let mut frame = Frame::new(40, 10, &mut pool);
1298        let area = Rect::new(0, 0, 40, 10);
1299        Widget::render(&view, area, &mut frame);
1300        frame.buffer.degradation = DegradationLevel::Skeleton;
1301        Widget::render(&view, area, &mut frame);
1302
1303        for y in 0..10 {
1304            for x in 0..40 {
1305                assert_eq!(
1306                    frame.buffer.get(x, y),
1307                    Some(&ftui_render::cell::Cell::default())
1308                );
1309            }
1310        }
1311    }
1312
1313    #[test]
1314    fn render_shorter_json_clears_stale_suffix_and_rows() {
1315        let long = JsonView::new(r#"{"alpha": 1000, "beta": 2000}"#);
1316        let short = JsonView::new(r#"{"a": 1}"#);
1317        let mut pool = GraphemePool::new();
1318        let mut frame = Frame::new(40, 10, &mut pool);
1319        let area = Rect::new(0, 0, 40, 10);
1320
1321        Widget::render(&long, area, &mut frame);
1322        Widget::render(&short, area, &mut frame);
1323
1324        for y in 0..10u16 {
1325            for x in 0..40u16 {
1326                if y >= 3 {
1327                    assert_eq!(
1328                        frame.buffer.get(x, y),
1329                        Some(&ftui_render::cell::Cell::default())
1330                    );
1331                }
1332            }
1333        }
1334    }
1335
1336    #[test]
1337    fn json_token_eq() {
1338        assert_eq!(JsonToken::Key("a".into()), JsonToken::Key("a".into()));
1339        assert_ne!(JsonToken::Key("a".into()), JsonToken::StringVal("a".into()));
1340        assert_ne!(JsonToken::Newline, JsonToken::Whitespace("".into()));
1341    }
1342
1343    #[test]
1344    fn json_token_clone_and_debug() {
1345        let tokens = vec![
1346            JsonToken::Key("k".into()),
1347            JsonToken::StringVal("s".into()),
1348            JsonToken::Number("1".into()),
1349            JsonToken::Literal("true".into()),
1350            JsonToken::Punctuation("{".into()),
1351            JsonToken::Whitespace("  ".into()),
1352            JsonToken::Newline,
1353            JsonToken::Error("bad".into()),
1354        ];
1355        for tok in &tokens {
1356            let cloned = tok.clone();
1357            assert_eq!(tok, &cloned);
1358            let _ = format!("{tok:?}");
1359        }
1360    }
1361
1362    #[test]
1363    fn classify_literal_empty_string() {
1364        // Empty literal should be Error (not a number or keyword)
1365        let result = classify_literal("");
1366        assert!(matches!(result, JsonToken::Error(s) if s.is_empty()));
1367    }
1368
1369    #[test]
1370    fn negative_number() {
1371        assert_eq!(
1372            classify_literal("-42"),
1373            JsonToken::Number("-42".to_string())
1374        );
1375    }
1376
1377    #[test]
1378    fn number_with_exponent() {
1379        assert_eq!(
1380            classify_literal("5E-3"),
1381            JsonToken::Number("5E-3".to_string())
1382        );
1383    }
1384
1385    // ─── End edge-case tests (bd-2agoi) ──────────────────────────────
1386
1387    #[test]
1388    fn classify_literal_types() {
1389        assert_eq!(
1390            classify_literal("true"),
1391            JsonToken::Literal("true".to_string())
1392        );
1393        assert_eq!(
1394            classify_literal("false"),
1395            JsonToken::Literal("false".to_string())
1396        );
1397        assert_eq!(
1398            classify_literal("null"),
1399            JsonToken::Literal("null".to_string())
1400        );
1401        assert_eq!(classify_literal("42"), JsonToken::Number("42".to_string()));
1402        assert_eq!(
1403            classify_literal("-3.14"),
1404            JsonToken::Number("-3.14".to_string())
1405        );
1406        assert!(matches!(classify_literal("invalid!"), JsonToken::Error(_)));
1407    }
1408
1409    mod fold_tests {
1410        use super::*;
1411
1412        fn key(k: &str) -> JsonPath {
1413            vec![JsonPathSegment::Key(k.to_string())]
1414        }
1415
1416        fn line_text(tokens: &[JsonToken]) -> String {
1417            tokens
1418                .iter()
1419                .filter_map(|t| match t {
1420                    JsonToken::Key(s)
1421                    | JsonToken::StringVal(s)
1422                    | JsonToken::Number(s)
1423                    | JsonToken::Literal(s)
1424                    | JsonToken::Punctuation(s)
1425                    | JsonToken::Whitespace(s)
1426                    | JsonToken::Error(s) => Some(s.as_str()),
1427                    JsonToken::Newline => None,
1428                })
1429                .collect()
1430        }
1431
1432        fn texts(view: &JsonView, state: &JsonViewState) -> Vec<String> {
1433            view.lines_with_state(state)
1434                .iter()
1435                .map(|l| line_text(&l.tokens))
1436                .collect()
1437        }
1438
1439        #[test]
1440        fn default_state_matches_formatted_lines() {
1441            // The unfolded stateful output is byte-identical to the flat one.
1442            let view = JsonView::new(r#"{"a": 1, "b": {"c": 2}, "arr": [1, 2]}"#);
1443            let flat = view.formatted_lines();
1444            let stateful: Vec<Vec<JsonToken>> = view
1445                .lines_with_state(&JsonViewState::default())
1446                .into_iter()
1447                .map(|l| l.tokens)
1448                .collect();
1449            assert_eq!(flat, stateful);
1450        }
1451
1452        #[test]
1453        fn toggle_folds_object_and_array() {
1454            let view = JsonView::new(r#"{"obj": {"x": 1}, "arr": [1, 2]}"#);
1455            let mut state = JsonViewState::new();
1456
1457            state.toggle(&key("obj"));
1458            assert!(state.is_folded(&key("obj")));
1459            let t = texts(&view, &state);
1460            assert!(
1461                t.iter().any(|l| l.contains("obj") && l.contains('▸')),
1462                "obj folded to a placeholder: {t:?}"
1463            );
1464            assert!(!t.iter().any(|l| l.contains("\"x\"")), "descendants hidden");
1465            assert!(t.iter().any(|l| l.trim() == "1,"), "arr still expanded");
1466
1467            state.toggle(&key("obj"));
1468            assert!(!state.is_folded(&key("obj")));
1469            assert!(texts(&view, &state).iter().any(|l| l.contains("\"x\"")));
1470        }
1471
1472        #[test]
1473        fn folded_node_renders_placeholder_with_count() {
1474            let view = JsonView::new(r#"{"o": {"a": 1, "b": 2, "c": 3}, "arr": [10, 20, 30, 40]}"#);
1475            let mut state = JsonViewState::new();
1476            state.fold(&key("o"));
1477            state.fold(&key("arr"));
1478            let t = texts(&view, &state);
1479            assert!(t.iter().any(|l| l.contains("▸ {…} (3 keys)")), "{t:?}");
1480            assert!(t.iter().any(|l| l.contains("▸ […] (4 items)")), "{t:?}");
1481        }
1482
1483        #[test]
1484        fn nested_fold_hides_descendants() {
1485            let view = JsonView::new(r#"{"a": {"b": {"c": 1}}}"#);
1486            let mut state = JsonViewState::new();
1487            state.fold(&key("a"));
1488            let t = texts(&view, &state);
1489            assert!(!t.iter().any(|l| l.contains("\"b\"")));
1490            assert!(!t.iter().any(|l| l.contains("\"c\"")));
1491            // root open, folded "a", root close.
1492            assert_eq!(t.len(), 3, "{t:?}");
1493        }
1494
1495        #[test]
1496        fn fold_survives_set_source_when_path_exists() {
1497            let mut view = JsonView::new(r#"{"a": {"x": 1}, "b": 2}"#);
1498            let mut state = JsonViewState::new();
1499            state.fold(&key("a"));
1500
1501            // Change the contents of "a" but keep it an object at the same path.
1502            view.set_source(r#"{"a": {"x": 99, "y": 100}, "b": 3}"#);
1503            let lines = view.lines_with_state(&state);
1504            assert!(
1505                lines
1506                    .iter()
1507                    .any(|l| l.folded && l.path.as_deref() == Some(key("a").as_slice())),
1508                "a stays folded across set_source"
1509            );
1510            assert!(!texts(&view, &state).iter().any(|l| l.contains("\"x\"")));
1511        }
1512
1513        #[test]
1514        fn invalid_json_keeps_error_tokens_when_folding() {
1515            let view = JsonView::new(r#"{"a": nope}"#);
1516            let flat = view.formatted_lines();
1517            assert!(
1518                flat.iter()
1519                    .flatten()
1520                    .any(|t| matches!(t, JsonToken::Error(e) if e == "nope")),
1521                "invalid literal is an Error token"
1522            );
1523            // Folding then unfolding must not corrupt the tokens.
1524            let mut state = JsonViewState::new();
1525            state.fold_all(&view);
1526            state.unfold_all();
1527            let restored: Vec<Vec<JsonToken>> = view
1528                .lines_with_state(&state)
1529                .into_iter()
1530                .map(|l| l.tokens)
1531                .collect();
1532            assert_eq!(flat, restored);
1533        }
1534
1535        #[test]
1536        fn fold_all_then_unfold_all_restores_formatted_lines() {
1537            let cases = [
1538                r#"{"a": 1}"#,
1539                r#"{"a": {"b": [1, 2, {"c": 3}]}, "d": "e"}"#,
1540                r#"[1, [2, [3, [4]]], {}]"#,
1541                r#"{"x": [], "y": {}, "z": [1]}"#,
1542                r#"42"#,
1543                r#""bare""#,
1544            ];
1545            for src in cases {
1546                let view = JsonView::new(src);
1547                let flat = view.formatted_lines();
1548                let mut state = JsonViewState::new();
1549                state.fold_all(&view);
1550                state.unfold_all();
1551                let restored: Vec<Vec<JsonToken>> = view
1552                    .lines_with_state(&state)
1553                    .into_iter()
1554                    .map(|l| l.tokens)
1555                    .collect();
1556                assert_eq!(flat, restored, "src={src}");
1557            }
1558        }
1559
1560        #[test]
1561        fn foldable_paths_are_unique() {
1562            let view = JsonView::new(r#"{"a": {"b": 1}, "c": [{"d": 2}, {"d": 3}]}"#);
1563            let lines = view.lines_with_state(&JsonViewState::default());
1564            let paths: Vec<JsonPath> = lines
1565                .iter()
1566                .filter(|l| l.foldable)
1567                .filter_map(|l| l.path.clone())
1568                .collect();
1569            let unique: HashSet<JsonPath> = paths.iter().cloned().collect();
1570            assert_eq!(paths.len(), unique.len(), "paths not unique: {paths:?}");
1571            // The two `{"d": ..}` array elements have distinct index paths.
1572            assert!(paths.contains(&vec![
1573                JsonPathSegment::Key("c".into()),
1574                JsonPathSegment::Index(0)
1575            ]));
1576            assert!(paths.contains(&vec![
1577                JsonPathSegment::Key("c".into()),
1578                JsonPathSegment::Index(1)
1579            ]));
1580        }
1581
1582        #[test]
1583        fn enter_toggles_node_at_cursor() {
1584            let view = JsonView::new(r#"{"a": {"x": 1}}"#);
1585            let mut state = JsonViewState::new();
1586            state.cursor_line = 1; // the `"a": {` opener line
1587
1588            let mut pool = GraphemePool::new();
1589            let mut frame = Frame::new(40, 12, &mut pool);
1590            StatefulWidget::render(&view, Rect::new(0, 0, 40, 12), &mut frame, &mut state);
1591
1592            assert!(state.handle_event(&Event::Key(KeyEvent::new(KeyCode::Enter))));
1593            assert!(state.is_folded(&key("a")));
1594            // Space toggles it back.
1595            assert!(state.handle_event(&Event::Key(KeyEvent::new(KeyCode::Char(' ')))));
1596            assert!(!state.is_folded(&key("a")));
1597        }
1598
1599        #[test]
1600        fn arrows_move_cursor_and_leaf_toggle_is_noop() {
1601            let view = JsonView::new(r#"{"a": 1, "b": 2}"#);
1602            let mut state = JsonViewState::new();
1603            let mut pool = GraphemePool::new();
1604            let mut frame = Frame::new(40, 12, &mut pool);
1605            StatefulWidget::render(&view, Rect::new(0, 0, 40, 12), &mut frame, &mut state);
1606
1607            assert!(state.handle_event(&Event::Key(KeyEvent::new(KeyCode::Down))));
1608            assert_eq!(state.cursor_line, 1);
1609            // Line 1 is `"a": 1,` — a leaf; Enter changes nothing.
1610            assert!(!state.handle_event(&Event::Key(KeyEvent::new(KeyCode::Enter))));
1611            assert_eq!(state.folded_count(), 0);
1612            // Home/End.
1613            assert!(state.handle_event(&Event::Key(KeyEvent::new(KeyCode::End))));
1614            assert!(state.cursor_line > 0);
1615            assert!(state.handle_event(&Event::Key(KeyEvent::new(KeyCode::Home))));
1616            assert_eq!(state.cursor_line, 0);
1617        }
1618
1619        #[test]
1620        fn stateful_render_equals_widget_when_unfolded() {
1621            // The default stateful render draws the same glyphs as the stateless
1622            // Widget (no cursor styling difference in the content itself).
1623            let view = JsonView::new(r#"{"a": {"b": 1}}"#);
1624            let area = Rect::new(0, 0, 20, 6);
1625
1626            let mut pool_a = GraphemePool::new();
1627            let mut fa = Frame::new(20, 6, &mut pool_a);
1628            Widget::render(&view, area, &mut fa);
1629
1630            let mut pool_b = GraphemePool::new();
1631            let mut fb = Frame::new(20, 6, &mut pool_b);
1632            let mut state = JsonViewState::new();
1633            // Use a no-op cursor style so the cursor row is not reverse-video.
1634            let view_plain = view.clone().with_cursor_style(Style::default());
1635            StatefulWidget::render(&view_plain, area, &mut fb, &mut state);
1636
1637            for y in 0..6 {
1638                for x in 0..20 {
1639                    assert_eq!(
1640                        fa.buffer.get(x, y).unwrap().content.as_char(),
1641                        fb.buffer.get(x, y).unwrap().content.as_char(),
1642                        "cell ({x},{y})"
1643                    );
1644                }
1645            }
1646        }
1647    }
1648}