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