paperboy 0.3.0

A Rust TUI API tester
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
//! Centre-top panel: the request editor. A Postman-style method/URL bar plus
//! section tabs (Params, Headers, Body, Auth, Cookies, Options, Asserts,
//! Captures, Code) editing the selected [`HurlEntry`] in place.

use std::collections::{HashMap, HashSet};

use eframe::egui::text::LayoutJob;
use eframe::egui::{self, Color32, FontId, RichText, TextFormat};

use crate::hurl::{FormField, FormFieldKind, HurlEntry};
// Only the tests construct rows directly; the editor itself just borrows them.
#[cfg(test)]
use crate::hurl::KvRow;
use crate::i18n::Strings;
use crate::request::{SubstInfo, SubstKind, apply_request_json, build_request_json};

use super::app::{EditorSection, GuiApp};
use super::theme::GuiTheme;
use super::widgets;

/// Inline warning marker shown immediately before a substituted value whose
/// Global Environment source is shadowed by the collection's linked
/// Environment — matches the terminal UI's `SHADOW_ICON`.
const SHADOW_ICON: &str = "!";

/// Which substitution [`SubstKind`]s (and whether any shadowing) were actually
/// rendered in the Code preview, so the legend shows only the relevant dots.
#[derive(Default)]
struct SubstSeen {
    loaded: bool,
    literal: bool,
    pending: bool,
    failed: bool,
    shadowed: bool,
}

impl SubstSeen {
    fn mark(&mut self, kind: SubstKind) {
        match kind {
            SubstKind::Loaded => self.loaded = true,
            SubstKind::Literal => self.literal = true,
            SubstKind::Pending => self.pending = true,
            SubstKind::Failed => self.failed = true,
        }
    }

    fn any(&self) -> bool {
        self.loaded || self.literal || self.pending || self.failed
    }
}

/// The colour a substitution is drawn in, by resolution status — mirrors the
/// terminal UI's `subst_color` so both front-ends agree.
fn subst_color(kind: SubstKind, th: &GuiTheme) -> Color32 {
    match kind {
        SubstKind::Literal => th.subst,
        SubstKind::Loaded => th.ok,
        SubstKind::Pending => th.pending,
        SubstKind::Failed => th.err,
    }
}

/// Render the substitution legend (coloured dots for each status present, plus
/// the shadowed hint) beneath the Code preview, matching the terminal UI.
fn subst_legend(ui: &mut egui::Ui, seen: &SubstSeen, th: &GuiTheme, s: &Strings) {
    if !seen.any() {
        return;
    }
    ui.horizontal_wrapped(|ui| {
        for (present, word, color) in [
            (seen.loaded, s.subst_hint_loaded, th.ok),
            (seen.literal, s.subst_hint_literal, th.subst),
            (seen.pending, s.subst_hint_loading, th.pending),
            (seen.failed, s.subst_hint_missing, th.err),
        ] {
            if present {
                ui.colored_label(color, format!("\u{25cf} {word}"));
            }
        }
        if seen.shadowed {
            ui.colored_label(
                th.pending,
                format!("{SHADOW_ICON} {}", s.subst_hint_shadowed),
            );
        }
    });
}

/// Colour-code every `{{ VAR }}` token *in place* — i.e. without substituting
/// its value or inserting any marker — so the produced [`LayoutJob`] lays out
/// exactly the characters it was given. This is what an editable Code buffer
/// needs: egui's `TextEdit` layouter must return a galley for the buffer's own
/// text (a length change would corrupt the cursor). Known placeholders are
/// tinted by resolution status; unknown ones keep the default colour. `seen`
/// records which statuses appeared, for the legend.
fn highlight_code_editable(
    text: &str,
    vars: &HashMap<String, SubstInfo>,
    shadowed: &HashSet<String>,
    th: &GuiTheme,
    font: FontId,
    seen: &mut SubstSeen,
) -> LayoutJob {
    let fmt = |color: Color32| TextFormat::simple(font.clone(), color);
    let mut job = LayoutJob::default();
    let mut rest = text;
    while let Some(open) = rest.find("{{") {
        let Some(close_rel) = rest[open + 2..].find("}}") else {
            break;
        };
        let close = open + 2 + close_rel;
        let end = close + 2;
        let inner = rest[open + 2..close].trim();
        if open > 0 {
            job.append(&rest[..open], 0.0, fmt(th.text));
        }
        let token = &rest[open..end];
        match vars.get(inner) {
            Some(info) => {
                seen.mark(info.kind);
                if shadowed.contains(inner) {
                    seen.shadowed = true;
                }
                job.append(token, 0.0, fmt(subst_color(info.kind, th)));
            }
            None => job.append(token, 0.0, fmt(th.text)),
        }
        rest = &rest[end..];
    }
    if !rest.is_empty() {
        job.append(rest, 0.0, fmt(th.text));
    }
    job
}

/// Re-parse edited Code-view `text` back into the selected entry. On success it
/// applies the result (preserving the UI-only `user_added` flag for Hurl; the
/// JSON view carries over the fields it doesn't expose from the current entry)
/// and clears the error; on failure it keeps the buffer untouched and records
/// the parse error. Returns whether the entry actually changed.
fn apply_code_edit(
    session: &mut crate::session::Session,
    code_edit: &mut super::app::CodeEdit,
    strings: &Strings,
    ci: usize,
    sel: usize,
    show_hurl: bool,
    text: &str,
) -> bool {
    if show_hurl {
        let entries = crate::hurl::parse_hurl(text);
        if entries.len() == 1 {
            let mut parsed = entries.into_iter().next().unwrap();
            let entry = &mut session.collections[ci].entries[sel];
            // `user_added` is UI-only and never written to Hurl text, so a
            // reparse always drops it; carry it over from the live entry.
            parsed.user_added = entry.user_added;
            *entry = parsed;
            code_edit.error = None;
            true
        } else {
            code_edit.error = Some(
                crate::hurl::parse_hurl_error(text)
                    .unwrap_or_else(|| strings.gui_code_parse_error.to_string()),
            );
            false
        }
    } else {
        let base = session.collections[ci].entries[sel].clone();
        match apply_request_json(&base, text) {
            Ok(parsed) => {
                session.collections[ci].entries[sel] = parsed;
                code_edit.error = None;
                true
            }
            Err(e) => {
                code_edit.error = Some(e);
                false
            }
        }
    }
}

/// The editable Code section: a full-height `TextEdit` holding either the Hurl
/// source or the resolved-JSON preview of the selected request, re-parsed on
/// every edit back into the entry. The buffer is the source of truth while you
/// type (never clobbered mid-edit); it re-syncs from the entry when you switch
/// request/representation or return to the tab. A parse failure keeps your text
/// and shows the error instead of discarding it. Returns whether the entry
/// changed.
#[allow(clippy::too_many_arguments)]
fn draw_code_section(
    app: &mut GuiApp,
    ui: &mut egui::Ui,
    theme: &GuiTheme,
    ci: usize,
    sel: usize,
    code_show_hurl: &mut bool,
    subst_vars: &HashMap<String, SubstInfo>,
    shadowed: &HashSet<String>,
) -> bool {
    let mut changed = false;

    // Representation toggle (Hurl source vs. resolved JSON), mirroring the TUI.
    ui.horizontal(|ui| {
        if widgets::selectable(ui, !*code_show_hurl, "JSON").clicked() {
            *code_show_hurl = false;
            app.code_edit.key = None;
        }
        if widgets::selectable(ui, *code_show_hurl, "Hurl").clicked() {
            *code_show_hurl = true;
            app.code_edit.key = None;
        }
    });
    ui.add_space(4.0);

    // Re-sync the buffer from the entry when it reflects a different
    // request/representation than we're now showing; otherwise leave the user's
    // in-progress edits untouched.
    let key = (ci, sel, *code_show_hurl);
    if app.code_edit.key != Some(key) {
        let entry = &app.session.collections[ci].entries[sel];
        app.code_edit.buf = if *code_show_hurl {
            entry.to_hurl()
        } else {
            build_request_json(entry)
        };
        app.code_edit.key = Some(key);
        app.code_edit.error = None;
    }

    // Legend: which substitution statuses appear in the current buffer.
    let mut seen = SubstSeen::default();
    let _ = highlight_code_editable(
        &app.code_edit.buf,
        subst_vars,
        shadowed,
        theme,
        FontId::monospace(12.0),
        &mut seen,
    );

    // A fixed-height editor that fills the panel (not shrink-wrapped to its
    // text), leaving room below for the legend and any parse error.
    let row_h = ui.text_style_height(&egui::TextStyle::Monospace);
    let reserved = 44.0
        + if app.code_edit.error.is_some() {
            24.0
        } else {
            0.0
        };
    let editor_h = (ui.available_height() - reserved).max(row_h * 6.0);
    let rows = (editor_h / row_h).floor().max(6.0) as usize;

    let subst_vars_l = subst_vars;
    let shadowed_l = shadowed;
    let theme_l = theme;
    let mut layouter = |ui: &egui::Ui, buf: &dyn egui::TextBuffer, wrap: f32| {
        let font = egui::TextStyle::Monospace.resolve(ui.style());
        let mut s = SubstSeen::default();
        let mut job = highlight_code_editable(
            buf.as_str(),
            subst_vars_l,
            shadowed_l,
            theme_l,
            font,
            &mut s,
        );
        job.wrap.max_width = wrap;
        ui.fonts_mut(|f| f.layout_job(job))
    };

    let resp = egui::ScrollArea::vertical()
        .max_height(editor_h)
        .auto_shrink([false, false])
        .show(ui, |ui| {
            ui.add(
                egui::TextEdit::multiline(&mut app.code_edit.buf)
                    .code_editor()
                    .desired_width(f32::INFINITY)
                    .desired_rows(rows)
                    .layouter(&mut layouter),
            )
        });

    if resp.inner.changed() {
        let text = app.code_edit.buf.clone();
        if apply_code_edit(
            &mut app.session,
            &mut app.code_edit,
            &app.strings,
            ci,
            sel,
            *code_show_hurl,
            &text,
        ) {
            changed = true;
        }
    }

    ui.add_space(4.0);
    if let Some(err) = &app.code_edit.error {
        ui.colored_label(theme.err, format!("\u{26a0} {err}"));
    }
    subst_legend(ui, &seen, theme, &app.strings);
    changed
}

pub fn ui(app: &mut GuiApp, ui: &mut egui::Ui) {
    let ci = app.active_ci();
    let theme = app.theme;

    if app.session.collections[ci].entries.is_empty() {
        let no_requests = app.strings.gui_no_requests_editor;
        let new_request_btn = format!("{} {}", super::icons::PLUS, app.strings.gui_new_request_btn);
        let new_request_title = app.strings.gui_new_request;
        ui.vertical_centered(|ui| {
            ui.add_space(30.0);
            ui.colored_label(theme.dim, no_requests);
            if ui.button(new_request_btn).clicked() {
                let mut e = HurlEntry::default();
                e.method = "GET".into();
                e.url = app.session.vars.base_url.clone();
                e.title = new_request_title.into();
                e.user_added = true;
                let col = &mut app.session.collections[ci];
                col.entries.push(e);
                col.selected_entry = 0;
                col.invalidate_request_json();
            }
        });
        return;
    }

    let sel = app.session.collections[ci]
        .selected_entry
        .min(app.session.collections[ci].entries.len() - 1);

    let mut changed = false;
    let mut send = false;
    let section = app.editor_section;
    // Local copy of the Code-view toggle; written back after the borrow of the
    // selected entry ends (egui closures can't borrow `app` again mid-frame).
    let mut code_show_hurl = app.show_hurl;

    // ── Name / Method / URL / Send bar ────────────────────────────────────
    // Mirrors the TUI edit-request wizard, which shows the request Name above
    // the Method/URL row. The Name is the display title in the request tree.
    let send_label = format!("{} {}", app.strings.gui_send, super::icons::PLAY);
    {
        let entry = &mut app.session.collections[ci].entries[sel];
        let name_label = app.strings.gui_name;
        ui.horizontal(|ui| {
            ui.label(RichText::new(name_label).color(theme.dim));
            let name = ui.add(
                egui::TextEdit::singleline(&mut entry.title)
                    .desired_width(f32::INFINITY)
                    .hint_text(name_label),
            );
            if name.changed() {
                changed = true;
            }
        });
        ui.add_space(2.0);
        ui.horizontal(|ui| {
            if widgets::method_combo(ui, "method", &mut entry.method) {
                changed = true;
            }
            let send_w = 92.0;
            let url = ui.add_sized(
                [ui.available_width() - send_w, 24.0],
                egui::TextEdit::singleline(&mut entry.url)
                    .hint_text("https://api.example.com/path")
                    .font(egui::TextStyle::Monospace),
            );
            if url.changed() {
                changed = true;
            }
            let btn = ui.add_sized(
                [80.0, 24.0],
                egui::Button::new(RichText::new(send_label).strong().color(theme.select_fg))
                    .fill(theme.accent),
            );
            if btn.clicked() {
                send = true;
            }
        });
    }

    ui.add_space(4.0);

    // ── Section tabs ──────────────────────────────────────────────────────
    {
        let entry = &app.session.collections[ci].entries[sel];
        let params_n = entry.queries.len();
        let headers_n = entry.headers.len();
        let cookies_n = entry.cookies.len();
        let options_n = entry.options.len();
        let asserts_n = entry.asserts.len();
        let captures_n = entry.captures.len();
        let has_body = entry.body.as_ref().map(|b| !b.is_empty()).unwrap_or(false)
            || !entry.form_fields.is_empty();
        let has_auth = entry.basic_auth.is_some();
        let mut cur = app.editor_section;
        let st = &app.strings;
        let tabs = [
            (EditorSection::All, st.tab_all.to_string()),
            (
                EditorSection::Params,
                format!("{}{}", st.gui_sec_params, widgets::count_suffix(params_n)),
            ),
            (
                EditorSection::Headers,
                format!("{}{}", st.gui_sec_headers, widgets::count_suffix(headers_n)),
            ),
            (
                EditorSection::Body,
                format!("{}{}", st.gui_sec_body, if has_body { "" } else { "" }),
            ),
            (
                EditorSection::Auth,
                format!("{}{}", st.gui_sec_auth, if has_auth { "" } else { "" }),
            ),
            (
                EditorSection::Cookies,
                format!("{}{}", st.gui_sec_cookies, widgets::count_suffix(cookies_n)),
            ),
            (
                EditorSection::Options,
                format!("{}{}", st.gui_sec_options, widgets::count_suffix(options_n)),
            ),
            (
                EditorSection::Asserts,
                format!("{}{}", st.gui_sec_asserts, widgets::count_suffix(asserts_n)),
            ),
            (
                EditorSection::Captures,
                format!(
                    "{}{}",
                    st.gui_sec_captures,
                    widgets::count_suffix(captures_n)
                ),
            ),
            (EditorSection::Code, st.gui_sec_code.to_string()),
        ];
        ui.horizontal_wrapped(|ui| {
            for (value, label) in &tabs {
                let selected = cur == *value;
                let mut text = RichText::new(label);
                text = if selected {
                    text.strong().color(theme.text)
                } else {
                    text.color(theme.dim)
                };
                if super::widgets::selectable(ui, selected, text).clicked() {
                    cur = *value;
                }
            }
        });
        app.editor_section = cur;
    }
    ui.separator();

    // Substitution preview data for the Code view: how each `{{ VAR }}` should
    // be shown/coloured, and which keys the linked env shadows. Computed here
    // (before the entry is mutably borrowed by the section closure) and only
    // when the Code tab is active, since it borrows the whole collection.
    let (subst_vars, shadowed) = if section == EditorSection::Code {
        let env = app.session.effective_env(ci);
        (
            crate::request::subst_map(&app.session.collections[ci], env.as_ref()),
            app.session.shadowed_env_keys(ci),
        )
    } else {
        (HashMap::new(), HashSet::new())
    };

    // ── Section body ──────────────────────────────────────────────────────
    // The editable Code buffer only mirrors the Code tab; drop its identity
    // whenever we leave so returning to Code re-syncs from the entry (which may
    // have been edited from another section in the meantime).
    if section != EditorSection::Code {
        app.code_edit.key = None;
    }
    if section == EditorSection::Code {
        // The Code editor needs mutable access to both `app.code_edit` and the
        // collection (to apply reparsed text), so it can't run inside the
        // closure below that borrows the selected entry.
        if draw_code_section(
            app,
            ui,
            &theme,
            ci,
            sel,
            &mut code_show_hurl,
            &subst_vars,
            &shadowed,
        ) {
            changed = true;
        }
    } else {
        // Resolved up front: the section body borrows the collection mutably,
        // so the session can't be consulted from inside it.
        let browse_fallback = app
            .session
            .picker_dir(crate::session::PickerKind::Other)
            .map(|p| p.to_path_buf());
        egui::ScrollArea::vertical()
            .auto_shrink([false, false])
            .show(ui, |ui| {
                let entry = &mut app.session.collections[ci].entries[sel];
                let st = &app.strings;
                match section {
                    EditorSection::All => {
                        // The combined view stacks every section, mirroring the
                        // TUI wizard's default "All" tab so the whole request is
                        // visible and editable without switching tabs.
                        const STACK: [EditorSection; 8] = [
                            EditorSection::Params,
                            EditorSection::Headers,
                            EditorSection::Body,
                            EditorSection::Auth,
                            EditorSection::Cookies,
                            EditorSection::Options,
                            EditorSection::Asserts,
                            EditorSection::Captures,
                        ];
                        for (i, sec) in STACK.iter().enumerate() {
                            if i > 0 {
                                ui.add_space(8.0);
                                ui.separator();
                            }
                            ui.label(
                                RichText::new(section_title(*sec, st))
                                    .strong()
                                    .color(theme.text),
                            );
                            if draw_section(*sec, ui, &theme, st, entry, browse_fallback.as_deref())
                            {
                                changed = true;
                            }
                        }
                    }
                    other => {
                        if draw_section(other, ui, &theme, st, entry, browse_fallback.as_deref()) {
                            changed = true;
                        }
                    }
                }
            });
    }

    app.show_hurl = code_show_hurl;
    if changed {
        let col = &mut app.session.collections[ci];
        col.entries[sel].modified = true;
        col.invalidate_request_json();
    }
    if send {
        app.session.collections[ci].selected_entry = sel;
        app.run_active();
    }
}

/// Human-readable heading for a section, used above each block in the "All"
/// combined view. Reads the same i18n tab labels as the section tab bar.
fn section_title(section: EditorSection, s: &Strings) -> &'static str {
    match section {
        EditorSection::All => s.tab_all,
        EditorSection::Params => s.gui_sec_params,
        EditorSection::Headers => s.gui_sec_headers,
        EditorSection::Body => s.gui_sec_body,
        EditorSection::Auth => s.gui_sec_auth,
        EditorSection::Cookies => s.gui_sec_cookies,
        EditorSection::Options => s.gui_sec_options,
        EditorSection::Asserts => s.gui_sec_asserts,
        EditorSection::Captures => s.gui_sec_captures,
        EditorSection::Code => s.gui_sec_code,
    }
}

/// Draw one editable request section into `ui`, returning whether the entry
/// changed. Shared by the single-section tabs and the combined "All" view.
/// `All` and `Code` are handled by the caller (they need extra state) and are
/// no-ops here.
fn draw_section(
    section: EditorSection,
    ui: &mut egui::Ui,
    theme: &super::theme::GuiTheme,
    st: &Strings,
    entry: &mut HurlEntry,
    // Where a `[Form]` file picker opens when the field is still blank.
    browse_fallback: Option<&std::path::Path>,
) -> bool {
    let mut changed = false;
    match section {
        EditorSection::All | EditorSection::Code => {}
        EditorSection::Params => {
            ui.label(RichText::new(st.gui_query_parameters).color(theme.dim));
            if widgets::kv_editor(
                ui,
                theme,
                st,
                "params",
                &mut entry.queries,
                st.gui_hint_key,
                st.gui_hint_value,
                st.hdr_key,
                st.hdr_value,
            ) {
                changed = true;
            }
        }
        EditorSection::Headers => {
            if widgets::kv_editor(
                ui,
                theme,
                st,
                "headers",
                &mut entry.headers,
                st.gui_hint_header,
                st.gui_hint_value,
                st.gui_hint_header,
                st.hdr_value,
            ) {
                changed = true;
            }
        }
        EditorSection::Body => {
            if !entry.form_fields.is_empty() {
                ui.colored_label(theme.pending, st.gui_form_mutually_exclusive);
            }
            let mut body = entry.body.take().unwrap_or_default();
            let resp = ui.add(
                egui::TextEdit::multiline(&mut body)
                    .code_editor()
                    .desired_rows(10)
                    .desired_width(f32::INFINITY)
                    .hint_text(st.gui_raw_body_hint),
            );
            if resp.changed() {
                changed = true;
            }
            entry.body = if body.is_empty() { None } else { Some(body) };

            ui.add_space(8.0);
            ui.separator();
            ui.label(RichText::new(st.gui_form_fields).color(theme.dim));
            if form_editor(ui, theme, st, &mut entry.form_fields, browse_fallback) {
                changed = true;
            }
        }
        EditorSection::Auth => {
            let mut enabled = entry.basic_auth.is_some();
            if ui.checkbox(&mut enabled, st.gui_basic_auth).changed() {
                entry.basic_auth = if enabled {
                    Some((String::new(), String::new()))
                } else {
                    None
                };
                changed = true;
            }
            if let Some((user, pass)) = entry.basic_auth.as_mut() {
                egui::Grid::new("auth").num_columns(2).show(ui, |ui| {
                    ui.label(st.gui_username);
                    if ui.text_edit_singleline(user).changed() {
                        changed = true;
                    }
                    ui.end_row();
                    ui.label(st.gui_password);
                    if ui
                        .add(egui::TextEdit::singleline(pass).password(true))
                        .changed()
                    {
                        changed = true;
                    }
                    ui.end_row();
                });
            }
        }
        EditorSection::Cookies => {
            if widgets::kv_editor(
                ui,
                theme,
                st,
                "cookies",
                &mut entry.cookies,
                st.gui_hint_name,
                st.gui_hint_value,
                st.hdr_name,
                st.hdr_value,
            ) {
                changed = true;
            }
        }
        EditorSection::Options => {
            ui.label(RichText::new(st.gui_per_request_options).color(theme.dim));
            if widgets::kv_editor(
                ui,
                theme,
                st,
                "options",
                &mut entry.options,
                st.gui_hint_option,
                st.gui_hint_value,
                st.hdr_option,
                st.hdr_value,
            ) {
                changed = true;
            }
        }
        EditorSection::Asserts => {
            ui.label(RichText::new(st.gui_response_assertions).color(theme.dim));
            if assert_editor(ui, theme, st, &mut entry.asserts) {
                changed = true;
            }
            ui.add_space(6.0);
            ui.horizontal(|ui| {
                ui.label(st.gui_expected_status);
                let mut s = entry
                    .expected_status
                    .map(|v| v.to_string())
                    .unwrap_or_default();
                if ui
                    .add(egui::TextEdit::singleline(&mut s).desired_width(60.0))
                    .changed()
                {
                    entry.expected_status = s.trim().parse::<u16>().ok();
                    changed = true;
                }
            });
        }
        EditorSection::Captures => {
            ui.label(RichText::new(st.gui_captures_help).color(theme.dim));
            if widgets::pair_editor(
                ui,
                theme,
                st,
                "captures",
                &mut entry.captures,
                st.gui_hint_name,
                st.gui_hint_query,
                st.hdr_name,
                st.hdr_query,
            ) {
                changed = true;
            }
        }
    }
    changed
}

/// Editable list of `[Asserts]` expression strings.
fn assert_editor(
    ui: &mut egui::Ui,
    theme: &super::theme::GuiTheme,
    s: &Strings,
    asserts: &mut Vec<String>,
) -> bool {
    let mut changed = false;
    let mut remove = None;
    for i in 0..asserts.len() {
        // Pin the remove ✕ to the right and let the value fill everything to its
        // left: an infinite-width field laid out left-to-right would instead
        // claim the whole row and shove the ✕ off the edge (see `kv_editor`).
        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
            if ui
                .button(RichText::new(super::icons::CLOSE).color(theme.err))
                .clicked()
            {
                remove = Some(i);
            }
            let r = ui.add(
                egui::TextEdit::singleline(&mut asserts[i])
                    .desired_width(f32::INFINITY)
                    .font(egui::TextStyle::Monospace)
                    .hint_text("jsonpath \"$.status\" == \"ok\""),
            );
            if r.changed() {
                changed = true;
            }
        });
    }
    if let Some(i) = remove {
        asserts.remove(i);
        changed = true;
    }
    if ui.button(s.gui_add_assert).clicked() {
        asserts.push(String::new());
        changed = true;
    }
    changed
}

/// Editable list of `[Form]`/`[Multipart]` fields.
fn form_editor(
    ui: &mut egui::Ui,
    theme: &super::theme::GuiTheme,
    s: &Strings,
    fields: &mut Vec<FormField>,
    browse_fallback: Option<&std::path::Path>,
) -> bool {
    let mut changed = false;
    let mut remove = None;
    // A grid (not a per-row `ui.horizontal`) keeps every column vertically
    // aligned across rows: the kind ComboBox is taller than the text cells, so
    // laying each row out independently let the dropdowns and values drift down
    // the further right they sat. The grid pins them to shared column edges and
    // gives the key ~40% of the free width (the value fills the rest as the
    // last column — see `widgets::split_key_width`).
    let key_w = super::widgets::split_key_width(ui, 160.0);
    egui::Grid::new("form_fields")
        .num_columns(4)
        .spacing([8.0, 4.0])
        .striped(true)
        .min_col_width(0.0)
        .show(ui, |ui| {
            for i in 0..fields.len() {
                if ui.checkbox(&mut fields[i].enabled, "").changed() {
                    changed = true;
                }
                // Grey a disabled form field's key/value so it reads as inactive
                // (it isn't sent), matching the terminal UI.
                let row_color = if fields[i].enabled {
                    theme.text
                } else {
                    theme.dim
                };
                if super::widgets::sized_key(
                    ui,
                    key_w,
                    &mut fields[i].key,
                    s.gui_hint_field,
                    row_color,
                )
                .changed()
                {
                    changed = true;
                }
                // Kind picker.
                let mut kind = fields[i].kind;
                egui::ComboBox::from_id_salt(("formkind", i))
                    .selected_text(match kind {
                        FormFieldKind::Text => s.gui_kind_text,
                        FormFieldKind::File => s.gui_kind_file,
                        FormFieldKind::Base64File => s.gui_kind_base64,
                    })
                    .width(80.0)
                    .show_ui(ui, |ui| {
                        for (k, label) in [
                            (FormFieldKind::Text, s.gui_kind_text),
                            (FormFieldKind::File, s.gui_kind_file),
                            (FormFieldKind::Base64File, s.gui_kind_base64),
                        ] {
                            if super::widgets::selectable(ui, kind == k, label).clicked() {
                                kind = k;
                                changed = true;
                            }
                        }
                    });
                fields[i].kind = kind;
                let hint = match kind {
                    FormFieldKind::Text => s.gui_hint_value,
                    _ => "/path/to/file",
                };
                // Value fills the last column; the remove ✕ is tucked to its
                // right (see the note in `widgets::kv_editor`).
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    if ui
                        .button(RichText::new(super::icons::CLOSE).color(theme.err))
                        .clicked()
                    {
                        remove = Some(i);
                    }
                    // File/Base64 values are paths — offer a native file picker
                    // (the terminal UI has its in-app browser for the same).
                    if matches!(kind, FormFieldKind::File | FormFieldKind::Base64File)
                        && ui.button(s.gui_browse).clicked()
                    {
                        if let Some(p) = super::filepick::pick_file(
                            s.gui_browse,
                            super::filepick::seed_dir(&fields[i].value)
                                .as_deref()
                                .or(browse_fallback),
                            &[],
                        ) {
                            fields[i].value = p.to_string_lossy().into_owned();
                            changed = true;
                        }
                    }
                    if ui
                        .add(
                            egui::TextEdit::singleline(&mut fields[i].value)
                                .desired_width(f32::INFINITY)
                                .text_color(row_color)
                                .hint_text(hint),
                        )
                        .changed()
                    {
                        changed = true;
                    }
                });
                ui.end_row();
                if fields[i].kind == FormFieldKind::Base64File {
                    ui.label(""); // checkbox column
                    ui.label(RichText::new(s.gui_base64_prefix).color(theme.dim).small());
                    ui.label(""); // kind column
                    let mut prefix = fields[i].base64_prefix.clone().unwrap_or_default();
                    if ui
                        .add(egui::TextEdit::singleline(&mut prefix).desired_width(f32::INFINITY))
                        .changed()
                    {
                        fields[i].base64_prefix = if prefix.is_empty() {
                            None
                        } else {
                            Some(prefix)
                        };
                        changed = true;
                    }
                    ui.end_row();
                }
            }
        });
    if let Some(i) = remove {
        fields.remove(i);
        changed = true;
    }
    if ui.button(s.gui_add_field).clicked() {
        fields.push(FormField {
            enabled: true,
            ..Default::default()
        });
        changed = true;
    }
    changed
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::i18n::Language;
    use crate::session::Session;
    use eframe::egui::FontId;

    fn session_with_entry() -> Session {
        let mut s = Session::default();
        let mut e = HurlEntry::default();
        e.method = "GET".into();
        e.url = "https://example.com/api".into();
        e.title = "Demo".into();
        s.collections[0].entries = vec![e];
        s.collections[0].selected_entry = 0;
        s
    }

    /// The in-place highlighter is used as a `TextEdit` layouter, so its galley
    /// must lay out *exactly* the buffer's characters — a length change would
    /// desync the cursor. This asserts the produced job text is identical to
    /// the input, `{{ VAR }}` tokens included (i.e. never substituted).
    #[test]
    fn editable_highlighter_preserves_the_buffer_text_verbatim() {
        let th = GuiTheme::from_spec(&Session::default().active_theme_spec());
        let vars = HashMap::new();
        let shadowed = HashSet::new();
        let mut seen = SubstSeen::default();
        for text in [
            "GET https://x/{{ host }}/api\nAuthorization: {{ token }}",
            "no placeholders here",
            "trailing {{ unclosed",
            "{{a}}{{b}} back to back",
        ] {
            let job = highlight_code_editable(
                text,
                &vars,
                &shadowed,
                &th,
                FontId::monospace(12.0),
                &mut seen,
            );
            assert_eq!(job.text, text, "layouter must not alter the buffer text");
        }
    }

    #[test]
    fn editing_the_hurl_buffer_roundtrips_a_new_header_into_the_entry() {
        let strings = Strings::for_language(&Language::English);
        let mut session = session_with_entry();
        let mut code = super::super::app::CodeEdit::default();

        // The same request, plus one extra header, serialised back to Hurl.
        let mut edited = session.collections[0].entries[0].clone();
        edited.headers.push(KvRow::toggled("X-Test", "hello", true));
        let text = edited.to_hurl();

        let changed = apply_code_edit(&mut session, &mut code, &strings, 0, 0, true, &text);
        assert!(changed, "a valid edit should report a change");
        assert!(code.error.is_none(), "a valid edit clears the error");
        let hdrs = &session.collections[0].entries[0].headers;
        assert!(
            hdrs.iter().any(|r| r.key == "X-Test" && r.value == "hello"),
            "expected the new header to be applied, got {hdrs:?}"
        );
    }

    #[test]
    fn invalid_hurl_keeps_the_entry_and_records_an_error() {
        let strings = Strings::for_language(&Language::English);
        let mut session = session_with_entry();
        let before = session.collections[0].entries[0].clone();
        let mut code = super::super::app::CodeEdit::default();

        // Lowercase "not" is not a valid HTTP method → zero parsed entries.
        let changed = apply_code_edit(
            &mut session,
            &mut code,
            &strings,
            0,
            0,
            true,
            "not a request",
        );
        assert!(!changed, "an unparseable edit must not report a change");
        assert!(code.error.is_some(), "an unparseable edit records an error");
        let entry = &session.collections[0].entries[0];
        assert_eq!(entry.method, before.method);
        assert_eq!(entry.url, before.url);
        assert_eq!(entry.headers, before.headers);
    }

    #[test]
    fn editing_the_json_buffer_roundtrips_the_method_into_the_entry() {
        let strings = Strings::for_language(&Language::English);
        let mut session = session_with_entry();
        let mut code = super::super::app::CodeEdit::default();

        let mut edited = session.collections[0].entries[0].clone();
        edited.method = "POST".into();
        let text = build_request_json(&edited);

        let changed = apply_code_edit(&mut session, &mut code, &strings, 0, 0, false, &text);
        assert!(changed, "a valid JSON edit should report a change");
        assert!(code.error.is_none());
        assert_eq!(session.collections[0].entries[0].method, "POST");
    }

    #[test]
    fn invalid_json_keeps_the_entry_and_records_an_error() {
        let strings = Strings::for_language(&Language::English);
        let mut session = session_with_entry();
        let before_method = session.collections[0].entries[0].method.clone();
        let mut code = super::super::app::CodeEdit::default();

        let changed = apply_code_edit(&mut session, &mut code, &strings, 0, 0, false, "{ not json");
        assert!(!changed, "malformed JSON must not report a change");
        assert!(code.error.is_some(), "malformed JSON records an error");
        assert_eq!(session.collections[0].entries[0].method, before_method);
    }
}