tix-tracker 0.6.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
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
use ratatui::Frame;
use ratatui::layout::{Position, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Paragraph};

use crate::model::Issue;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FormFocus {
    Title,
    Status,
    Priority,
    Labels,
    Assignee,
    Estimate,
    Cycles,
    Milestones,
    Reviewer,
    StartDate,
    DueDate,
    /// The parent issue (WP06 / T026). Appended **last**, not slotted next to
    /// `Assignee` where it would read better: every existing row's index is the
    /// identity of that row in `render_with_bindings`'s `fields` array, and
    /// inserting in the middle renumbers all five rows after it. Appending keeps
    /// the eleven existing indices stable, so no render or golden assertion moves.
    Parent,
    /// The entry target of the F4 New Issue mode (`tui-new-issue-mode`): Triage or
    /// Todo. Appended, per the rule above. It is a **toggle**, not a text field:
    /// Enter/Space flips it and Left/Right pick a side, and typing into it does
    /// nothing. Choosing a side writes the same status the submit path would use,
    /// so the Status row below stays the authoritative value.
    Target,
    /// The selected new-issue template's name, or empty for none. Enter/F2 opens
    /// the template picker (a scratch [`crate::ui::pickers::DropdownState`] over
    /// the configured `[templates.<name>]` names); selecting one pre-fills the
    /// rows. Not a free-text field: the value names a configured record.
    Template,
    /// The issue body (Markdown), which a template pre-fills. Editable like the
    /// other text rows; newlines are escaped as `\n` on screen so the row stays a
    /// single line, but the submitted body keeps them verbatim.
    Body,
}

/// Where a new issue created from the F4 New Issue mode enters the board.
///
/// The explicit choice the mode exists for: a form can default to one entry point
/// but cannot *say* which one it is using, and the two destinations mean different
/// things (the inbox is a queue with an age; `todo` is scheduled work). The chosen
/// target's status is written into [`FormState::status`], which remains the value
/// submitted — so the Status row reflects the choice and can still be overridden
/// for a column the target does not name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum NewIssueTarget {
    /// Enter the triage inbox's entry status.
    Triage,
    /// Enter the todo status directly.
    #[default]
    Todo,
}

impl NewIssueTarget {
    /// The label shown in the Target row.
    pub fn label(self) -> &'static str {
        match self {
            NewIssueTarget::Triage => "Triage",
            NewIssueTarget::Todo => "Todo",
        }
    }

    /// The other side of the toggle.
    pub fn next(self) -> Self {
        match self {
            NewIssueTarget::Triage => NewIssueTarget::Todo,
            NewIssueTarget::Todo => NewIssueTarget::Triage,
        }
    }
}

impl FormFocus {
    pub fn next(self) -> Self {
        match self {
            FormFocus::Title => FormFocus::Status,
            FormFocus::Status => FormFocus::Priority,
            FormFocus::Priority => FormFocus::Labels,
            FormFocus::Labels => FormFocus::Assignee,
            FormFocus::Assignee => FormFocus::Estimate,
            FormFocus::Estimate => FormFocus::Cycles,
            FormFocus::Cycles => FormFocus::Milestones,
            FormFocus::Milestones => FormFocus::Reviewer,
            FormFocus::Reviewer => FormFocus::StartDate,
            FormFocus::StartDate => FormFocus::DueDate,
            FormFocus::DueDate => FormFocus::Parent,
            FormFocus::Parent => FormFocus::Target,
            FormFocus::Target => FormFocus::Template,
            FormFocus::Template => FormFocus::Body,
            FormFocus::Body => FormFocus::Title,
        }
    }

    pub fn prev(self) -> Self {
        match self {
            // `Body`, not `DueDate`: `RING` now ends at `Body`, and the two must
            // agree or the backward wrap lands on a different field than the
            // forward one. This drift was real — `form_arrows_navigate_fields` is
            // what caught it, and it is why that test compares against `RING` now
            // instead of a literal.
            FormFocus::Title => FormFocus::Body,
            FormFocus::Status => FormFocus::Title,
            FormFocus::Priority => FormFocus::Status,
            FormFocus::Labels => FormFocus::Priority,
            FormFocus::Assignee => FormFocus::Labels,
            FormFocus::Estimate => FormFocus::Assignee,
            FormFocus::Cycles => FormFocus::Estimate,
            FormFocus::Milestones => FormFocus::Cycles,
            FormFocus::Reviewer => FormFocus::Milestones,
            FormFocus::StartDate => FormFocus::Reviewer,
            FormFocus::DueDate => FormFocus::StartDate,
            FormFocus::Parent => FormFocus::DueDate,
            FormFocus::Target => FormFocus::Parent,
            FormFocus::Template => FormFocus::Target,
            FormFocus::Body => FormFocus::Template,
        }
    }

    pub fn label(self) -> &'static str {
        match self {
            FormFocus::Title => "Title",
            FormFocus::Status => "Status",
            FormFocus::Priority => "Priority",
            FormFocus::Labels => "Labels",
            FormFocus::Assignee => "Assignee",
            FormFocus::Estimate => "Estimate",
            FormFocus::Cycles => "Cycles",
            FormFocus::Milestones => "Milestones",
            FormFocus::Reviewer => "Reviewer",
            FormFocus::StartDate => "Start date",
            FormFocus::DueDate => "Due date",
            FormFocus::Parent => "Parent",
            FormFocus::Target => "Target",
            FormFocus::Template => "Template",
            FormFocus::Body => "Body",
        }
    }

    /// The focus ring, in `next()` order, starting at `Title`.
    ///
    /// One list, so `render_with_bindings` can derive both the focus index and the
    /// row labels from it. It used to hold a hand-written `match` for the index
    /// beside a positional array of labels, which agree only by inspection — and
    /// the two disagree *silently*, as a bold cursor on the wrong row.
    pub const RING: [FormFocus; 15] = [
        FormFocus::Title,
        FormFocus::Status,
        FormFocus::Priority,
        FormFocus::Labels,
        FormFocus::Assignee,
        FormFocus::Estimate,
        FormFocus::Cycles,
        FormFocus::Milestones,
        FormFocus::Reviewer,
        FormFocus::StartDate,
        FormFocus::DueDate,
        FormFocus::Parent,
        FormFocus::Target,
        FormFocus::Template,
        FormFocus::Body,
    ];

    /// This field's row in [`FormFocus::RING`].
    pub fn index(self) -> usize {
        Self::RING
            .iter()
            .position(|f| *f == self)
            .expect("every FormFocus variant is in RING")
    }

    /// Whether this field holds a date (picker-only, no free typing).
    pub fn is_date(self) -> bool {
        matches!(self, FormFocus::StartDate | FormFocus::DueDate)
    }

    /// Whether this field holds a parent (picker-only, single-select).
    pub fn is_parent(self) -> bool {
        matches!(self, FormFocus::Parent)
    }

    /// Whether this field holds the issue's board column (Status).
    ///
    /// Chosen from the active board's columns, never typed: a board column is a
    /// named position on a board, not a value to invent by hand, and free text
    /// could name one the board does not configure.
    pub fn is_status(self) -> bool {
        matches!(self, FormFocus::Status)
    }

    /// Whether this field holds the issue's priority.
    ///
    /// Chosen from the built-in set plus the priorities the project already uses,
    /// never typed, for the same reason as Status — with the picker's `+` inline
    /// create as the escape hatch for a priority the options do not list yet.
    pub fn is_priority(self) -> bool {
        matches!(self, FormFocus::Priority)
    }

    /// Whether this field is the New Issue target toggle.
    pub fn is_target(self) -> bool {
        matches!(self, FormFocus::Target)
    }

    /// Whether this field names a selected template.
    ///
    /// Chosen from the template picker, never typed: the value has to name a
    /// configured `[templates.<name>]` record, and free text could only ever fail
    /// to resolve to one.
    pub fn is_template(self) -> bool {
        matches!(self, FormFocus::Template)
    }

    /// Whether typing and backspace are refused on this field.
    ///
    /// `Parent` (picked by number), `Target` (toggled), `Template` (picked by
    /// name), `Status` and `Priority` (picked from their dropdowns) all hold
    /// values that are *chosen*, so a character has no meaning here. They guard
    /// `insert_char`/`delete_char` from one predicate rather than five inline
    /// checks, so a further control field cannot be added and silently left
    /// typeable.
    pub fn refuses_typing(self) -> bool {
        self.is_parent()
            || self.is_target()
            || self.is_template()
            || self.is_status()
            || self.is_priority()
    }

    /// Whether the field's value is **chosen** from a picker rather than typed.
    ///
    /// Typing is refused on the chosen rows, because a half-typed number or a
    /// hand-typed priority is not a value: the service validates a parent by
    /// resolved number, and Status/Priority are picked from their dropdowns, so
    /// free text here could only ever fail or invent a column. This is the
    /// general form of what `is_date` was already doing for dates alone.
    pub fn is_picker_only(self) -> bool {
        self.is_date() || self.is_parent() || self.is_status() || self.is_priority()
    }
}

#[derive(Debug, Clone)]
pub struct FormState {
    pub title: String,
    pub status: String,
    pub priority: String,
    pub labels: String,
    pub assignee: String,
    pub estimate: String,
    pub cycles: String,
    pub milestones: String,
    pub reviewer: String,
    pub start_date: String,
    pub due_date: String,
    /// The chosen parent's **number**, as a string (WP06 / T026).
    ///
    /// A `String` for the same reason `assignee` is one: the form's fields are
    /// uniformly text, and each is parsed and validated at submit rather than at
    /// Empty means no parent, which carries the same meaning as an
    /// empty `--parent ""` on the CLI.
    pub parent: String,
    /// The entry target of the F4 New Issue mode. Choosing a side writes the
    /// matching status into [`Self::status`], which is what submit reads.
    pub target: NewIssueTarget,
    /// The selected `[templates.<name>]` record's name, or empty for none. A label
    /// only: the fields it filled are held separately, so clearing the selection
    /// keeps what was typed.
    pub template: String,
    /// The issue body (Markdown). Submitted verbatim; rendered with newlines
    /// escaped so the row stays one line.
    pub body: String,
    pub focus: FormFocus,
}

impl FormState {
    pub fn new(default_status: &str) -> Self {
        Self::with_default_assignee(default_status, "")
    }

    pub fn with_default_assignee(default_status: &str, default_assignee: &str) -> Self {
        FormState {
            title: String::new(),
            status: default_status.to_string(),
            priority: String::new(),
            labels: String::new(),
            assignee: default_assignee.to_string(),
            estimate: String::new(),
            cycles: String::new(),
            milestones: String::new(),
            reviewer: String::new(),
            start_date: String::new(),
            due_date: String::new(),
            parent: String::new(),
            target: NewIssueTarget::default(),
            template: String::new(),
            body: String::new(),
            focus: FormFocus::Title,
        }
    }

    /// Pre-fill the rows a template sets, leaving rows it omits untouched.
    ///
    /// *Untouched* rather than *cleared* is the whole point: a template is applied
    /// to a form the user may already have typed into, and a template that named
    /// only `labels` must not silently erase their title. Vector fields follow the
    /// same rule as the submit path — they are the comma-joined spelling of the
    /// list they would create.
    pub fn apply_template(&mut self, name: &str, template: &crate::config::IssueTemplate) {
        if let Some(title) = &template.title {
            self.title = title.clone();
        }
        if let Some(body) = &template.body {
            self.body = body.clone();
        }
        if !template.labels.is_empty() {
            self.labels = template.labels.join(",");
        }
        if let Some(status) = &template.status {
            self.status = status.clone();
        }
        if let Some(priority) = &template.priority {
            self.priority = priority.clone();
        }
        if let Some(assignee) = &template.assignee {
            self.assignee = assignee.clone();
        }
        if let Some(estimate) = &template.estimate {
            self.estimate = estimate.clone();
        }
        if let Some(reviewer) = &template.reviewer {
            self.reviewer = reviewer.clone();
        }
        if !template.cycles.is_empty() {
            self.cycles = template.cycles.join(",");
        }
        if !template.milestones.is_empty() {
            self.milestones = template.milestones.join(",");
        }
        if let Some(start) = &template.start_date {
            self.start_date = start.clone();
        }
        if let Some(due) = &template.due_date {
            self.due_date = due.clone();
        }
        self.template = name.to_string();
    }

    /// This form with every field prefilled from an existing issue — the TUI's
    /// "clone issue" action (tix #1484).
    ///
    /// Exactly the fields the form *has* are carried over, which is exactly the
    /// fields creation takes: `number`, `created`, `commit` and `History` are not
    /// creation inputs, so they are not carried. The title is copied **verbatim**
    /// rather than suffixed with "copy": the user asked for the source's data, a
    /// title is not an identity (numbers are), and inventing a naming convention
    /// here would put a string in the user's issue that no command in this tool
    /// produces.
    ///
    /// Multivalued fields are filled in the same comma-separated form the submit
    /// path parses (`labels`, `cycles`, `milestones`), so a clone submitted
    /// unchanged round-trips the source's values exactly.
    pub fn from_issue(issue: &Issue) -> Self {
        fn joined(values: &Option<Vec<String>>) -> String {
            values.as_deref().map(|v| v.join(",")).unwrap_or_default()
        }
        FormState {
            title: issue.title.clone(),
            status: issue.status.to_string(),
            priority: issue.priority.to_string(),
            labels: issue.labels.join(","),
            assignee: issue.assignee.clone().unwrap_or_default(),
            estimate: issue.estimate.clone().unwrap_or_default(),
            cycles: joined(&issue.cycles),
            milestones: joined(&issue.milestones),
            reviewer: issue.reviewer.clone().unwrap_or_default(),
            start_date: issue.start_date.clone().unwrap_or_default(),
            due_date: issue.due_date.clone().unwrap_or_default(),
            parent: issue.parent.map(|n| n.to_string()).unwrap_or_default(),
            // The body is a form row now (`tui-new-issue-mode`), so a clone that
            // dropped it would be the partial copy #1484's own doc warns about.
            body: issue.body.clone(),
            // A clone copies the source's status verbatim; the target is set to
            // match it so the Target row does not claim a destination the form is
            // not using. `App` refines `Triage` when the source sits in the inbox.
            target: NewIssueTarget::Todo,
            template: String::new(),
            focus: FormFocus::Title,
        }
    }

    /// This form's value for `focus`, regardless of which field is focused.
    ///
    /// `focused_value` is `value_of(self.focus)`. The indirection exists so the
    /// renderer can walk [`FormFocus::RING`] and read each field in turn, which is
    /// what lets one list drive both the labels and the focus index.
    pub fn value_of(&self, focus: FormFocus) -> &str {
        match focus {
            FormFocus::Title => &self.title,
            FormFocus::Status => &self.status,
            FormFocus::Priority => &self.priority,
            FormFocus::Labels => &self.labels,
            FormFocus::Assignee => &self.assignee,
            FormFocus::Estimate => &self.estimate,
            FormFocus::Cycles => &self.cycles,
            FormFocus::Milestones => &self.milestones,
            FormFocus::Reviewer => &self.reviewer,
            FormFocus::StartDate => &self.start_date,
            FormFocus::DueDate => &self.due_date,
            FormFocus::Parent => &self.parent,
            // Not a stored string: the target is an enum with two labels, and
            // rendering its label here is what keeps it a row like every other.
            FormFocus::Target => self.target.label(),
            FormFocus::Template => &self.template,
            FormFocus::Body => &self.body,
        }
    }

    /// The text actually drawn for `focus`.
    ///
    /// Identical to [`Self::value_of`] everywhere but the body, whose newlines are
    /// escaped (`\n`) so a multi-line Markdown body occupies one row and the row
    /// arithmetic the caret depends on stays true. The submitted value keeps the
    /// real newlines; only the display is folded.
    pub fn display_value(&self, focus: FormFocus) -> std::borrow::Cow<'_, str> {
        let value = self.value_of(focus);
        if focus == FormFocus::Body && value.contains('\n') {
            return std::borrow::Cow::Owned(value.replace('\n', "\\n"));
        }
        std::borrow::Cow::Borrowed(value)
    }

    /// [`Self::display_value`] for the focused row.
    pub fn focused_display_value(&self) -> std::borrow::Cow<'_, str> {
        self.display_value(self.focus)
    }

    pub fn focused_value(&self) -> &str {
        self.value_of(self.focus)
    }

    /// The focused field's editable buffer, or `None` when the field has none.
    ///
    /// `Option` rather than a `panic` for the control rows: `Target` is an enum
    /// with no buffer of its own, and the alternative — a `&mut String` arm that
    /// panics — would make a guard in `insert_char` the only thing standing
    /// between a mis-set focus and an abort. A `None` makes the callers handle it.
    pub fn focused_value_mut(&mut self) -> Option<&mut String> {
        match self.focus {
            FormFocus::Title => Some(&mut self.title),
            FormFocus::Status => Some(&mut self.status),
            FormFocus::Priority => Some(&mut self.priority),
            FormFocus::Labels => Some(&mut self.labels),
            FormFocus::Assignee => Some(&mut self.assignee),
            FormFocus::Estimate => Some(&mut self.estimate),
            FormFocus::Cycles => Some(&mut self.cycles),
            FormFocus::Milestones => Some(&mut self.milestones),
            FormFocus::Reviewer => Some(&mut self.reviewer),
            FormFocus::StartDate => Some(&mut self.start_date),
            FormFocus::DueDate => Some(&mut self.due_date),
            FormFocus::Parent => Some(&mut self.parent),
            FormFocus::Template => Some(&mut self.template),
            FormFocus::Body => Some(&mut self.body),
            FormFocus::Target => None,
        }
    }

    pub fn insert_char(&mut self, c: char) {
        if self.focus.refuses_typing() {
            // Picked or toggled, never typed: a parent by number, a target by
            // side, a template by name.
            return;
        }
        if self.focus.is_date() {
            if let Some(next) = crate::ui::date_picker::type_date(self.focused_value(), c)
                && let Some(value) = self.focused_value_mut()
            {
                *value = next;
            }
            return;
        }
        if let Some(value) = self.focused_value_mut() {
            value.push(c);
        }
    }

    pub fn delete_char(&mut self) {
        if self.focus.refuses_typing() {
            return;
        }
        if self.focus.is_date() {
            let next = crate::ui::date_picker::backspace_date(self.focused_value());
            if let Some(value) = self.focused_value_mut() {
                *value = next;
            }
            return;
        }
        if let Some(value) = self.focused_value_mut() {
            value.pop();
        }
    }

    /// Whether the focused field is a picker-only date field.
    pub fn is_date_focus(&self) -> bool {
        self.focus.is_date()
    }

    /// Whether the focused date field already holds a complete, valid date.
    pub fn focused_date_is_complete(&self) -> bool {
        self.focus.is_date() && crate::ui::date_picker::is_complete_date(self.focused_value())
    }

    /// Overwrite the focused date field (no-op when it isn't a date field).
    pub fn set_focused_date(&mut self, value: &str) {
        if self.focus.is_date()
            && let Some(field) = self.focused_value_mut()
        {
            *field = value.to_string();
        }
    }

    pub fn move_focus_next(&mut self) {
        self.focus = self.focus.next();
    }

    pub fn move_focus_prev(&mut self) {
        self.focus = self.focus.prev();
    }
}

pub fn render(form: &FormState, f: &mut Frame, area: Rect) {
    let bindings =
        crate::keybindings::KeyBindings::resolve(&crate::keybindings::KeyBindings::default())
            .expect("built-in bindings are valid");
    render_with_bindings(
        form,
        f,
        area,
        &bindings,
        crate::keybindings::InputContext::Form,
    );
    // This entry point renders the form as the active surface, so it places the
    // caret too. `render_with_bindings` cannot: it is also what draws the form as a
    // backdrop under a picker, where the cursor belongs to the overlay.
    place_caret(form, f, area);
}

pub fn render_with_bindings(
    form: &FormState,
    f: &mut Frame,
    area: Rect,
    bindings: &crate::keybindings::EffectiveBindings,
    context: crate::keybindings::InputContext,
) {
    // Both the focus index and the row labels come from `FormFocus::RING`, so the
    // cursor and the label it labels cannot drift apart. The value for each field
    // is read through `focused_value`-style indexing into `FormState` below, which
    // is why the pairing is by position and not by name.
    let focus_idx = form.focus.index();
    let fields: Vec<(&'static str, std::borrow::Cow<'_, str>)> = FormFocus::RING
        .iter()
        .map(|focus| (focus.label(), form.display_value(*focus)))
        .collect();

    let mut lines: Vec<Line<'static>> = Vec::new();
    for (i, (label, value)) in fields.iter().enumerate() {
        let cursor = if i == focus_idx { "> " } else { "  " };
        let label_style = if i == focus_idx {
            Style::default()
                .add_modifier(Modifier::BOLD)
                .fg(Color::Cyan)
        } else {
            Style::default()
        };
        let (display, value_style) = if value.is_empty() && i != focus_idx {
            ("(empty)".to_string(), Style::default().fg(Color::DarkGray))
        } else if i == focus_idx {
            (
                value.to_string(),
                Style::default().add_modifier(Modifier::UNDERLINED),
            )
        } else {
            (value.to_string(), Style::default())
        };
        lines.push(Line::from(vec![
            Span::styled(format!("{cursor}{label}: "), label_style),
            Span::styled(display, value_style),
        ]));
    }

    lines.push(Line::from(""));
    let submit = bindings.label(context, crate::keybindings::TuiAction::Submit);
    let cancel = bindings.label(context, crate::keybindings::TuiAction::Cancel);
    let next = bindings.label(context, crate::keybindings::TuiAction::Next);
    let previous = bindings.label(context, crate::keybindings::TuiAction::Previous);
    let picker = bindings.label(context, crate::keybindings::TuiAction::OpenPicker);
    lines.push(Line::from(Span::styled(
        format!(
            "{submit}: Submit | {cancel}: Cancel | {next}/{previous}: Fields | \
             {picker}: Picker/Date/Parent | Left/Right: Target"
        ),
        Style::default().fg(Color::DarkGray),
    )));

    let para =
        Paragraph::new(lines).block(Block::default().borders(Borders::ALL).title("New Issue"));

    f.render_widget(para, area);
}

/// Where the terminal caret belongs for `form` rendered into `area`, or `None`
/// when this form shows no insertion point.
///
/// Split from [`place_caret`] so the arithmetic — the part that can be wrong — is
/// testable without a terminal.
///
/// The form is **append-only** editing: `insert_char` pushes and `delete_char`
/// pops, so the insertion point is always the end of the focused value's text and
/// that is where the caret belongs. A picker-only field gets none, because
/// `insert_char` returns early on it: a caret on `Parent` would advertise an
/// insertion point that does not exist. The date fields do accept typed digits, so
/// they keep one.
///
/// A value wider than the field is clipped by `Paragraph` (which does not wrap
/// here) and its true caret is off-screen, so the column is clamped into the
/// visible row rather than handed back out of bounds. Making the value scroll is a
/// larger change than this fix.
pub fn caret_position(form: &FormState, area: Rect) -> Option<Position> {
    if form.focus.refuses_typing() {
        return None;
    }
    let row = field_row_rect(area, form.focus)?;
    // The same prefix the row renderer writes: focus marker, label, colon, space.
    // Measured on the rendered spans rather than by character count, so a value
    // wider than it is long (any non-ASCII in a title) still lands the caret
    // correctly.
    let prefix = format!("> {}: ", form.focus.label());
    let column =
        Span::raw(prefix).width() + Span::raw(form.focused_display_value().into_owned()).width();
    let column = u16::try_from(column).unwrap_or(u16::MAX);
    Some(Position::new(
        row.x + column.min(row.width.saturating_sub(1)),
        row.y,
    ))
}

/// The one-row inner rectangle `focus` occupies when the form is drawn into
/// `area`, or `None` when that row is outside the visible form.
///
/// The single arithmetic shared by the caret and by the hit region the New Issue
/// mode records for the Template row: two copies of "inner rect plus the focus
/// index" would be two chances to disagree about where a row is.
pub fn field_row_rect(area: Rect, focus: FormFocus) -> Option<Rect> {
    let inner = Block::default().borders(Borders::ALL).inner(area);
    if inner.width == 0 || inner.height == 0 {
        return None;
    }
    let y = inner.y.checked_add(u16::try_from(focus.index()).ok()?)?;
    if y >= inner.y + inner.height {
        return None;
    }
    Some(Rect {
        x: inner.x,
        y,
        width: inner.width,
        height: 1,
    })
}

/// Put the terminal's text cursor at the end of the focused field's value.
///
/// Until this existed, `set_cursor_position` was never called anywhere in the
/// crate: the cursor stayed wherever the previously rendered widget left it, and
/// the form showed no insertion point at all. "Create issue" opened on an empty
/// Title row that was underlined and nothing else, and characters appeared with the
/// caret parked elsewhere (#1486).
///
/// Called by the owner of the frame rather than from `render_with_bindings`,
/// because where the form is a **backdrop** — under the date-picker overlay — the
/// overlay owns the cursor and a caret on the row behind it would point at the
/// wrong surface.
pub fn place_caret(form: &FormState, f: &mut Frame, area: Rect) {
    if let Some(position) = caret_position(form, area) {
        f.set_cursor_position(position);
    }
}

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

    #[test]
    fn focus_cycles_forward() {
        assert_eq!(FormFocus::Title.next(), FormFocus::Status);
        assert_eq!(FormFocus::DueDate.next(), FormFocus::Parent);
        assert_eq!(FormFocus::Parent.next(), FormFocus::Target);
        assert_eq!(FormFocus::Target.next(), FormFocus::Template);
        assert_eq!(FormFocus::Template.next(), FormFocus::Body);
        assert_eq!(FormFocus::Body.next(), FormFocus::Title);
    }

    #[test]
    fn focus_cycles_backward() {
        assert_eq!(FormFocus::Title.prev(), FormFocus::Body);
        assert_eq!(FormFocus::Status.prev(), FormFocus::Title);
        assert_eq!(FormFocus::Body.prev(), FormFocus::Template);
    }

    /// `next`, `prev`, and `RING` are three statements of the same order, and the
    /// compiler cannot check that they agree — an out-of-date arm compiles and
    /// silently sends the cursor to the wrong field.
    ///
    /// Asserted as a walk over the ring rather than as a list of pairs, so adding a
    /// field cannot leave the pairs stale: the test has to be updated to pass, and
    /// updating it means reading the ring.
    #[test]
    fn the_ring_and_the_next_prev_chains_agree() {
        let ring = FormFocus::RING;
        for (i, focus) in ring.iter().enumerate() {
            let forward = ring[(i + 1) % ring.len()];
            let backward = ring[(i + ring.len() - 1) % ring.len()];
            assert_eq!(focus.next(), forward, "next() after {focus:?} in RING");
            assert_eq!(focus.prev(), backward, "prev() after {focus:?} in RING");
        }
    }

    /// `RING` must contain every variant, or a field becomes unreachable: there is
    /// no way to tab onto it and no way off whatever precedes it. `index()` panics
    /// on a variant missing from `RING`, so this is that panic's guard, as a test.
    #[test]
    fn the_ring_covers_every_field() {
        for (i, focus) in FormFocus::RING.iter().enumerate() {
            assert_eq!(focus.index(), i, "{focus:?} must sit at its RING position");
        }
        // And a fresh form starts on a field that is in the ring.
        assert!(FormFocus::RING.contains(&FormState::new("todo").focus));
    }

    /// The parent field is chosen from a picker, so typing into it must do nothing.
    /// A half-typed number is not a parent, and the service validates by resolved
    /// number — free text here could only ever be a value that fails at submit.
    #[test]
    fn the_parent_field_refuses_typed_characters() {
        let mut form = FormState::new("todo");
        form.move_focus_next();
        for _ in 0..FormFocus::RING.len() {
            if form.focus == FormFocus::Parent {
                break;
            }
            form.move_focus_next();
        }
        assert_eq!(form.focus, FormFocus::Parent, "the ring must reach Parent");
        assert!(form.focus.is_picker_only());
        assert!(!form.focus.is_date(), "Parent is picker-only, not a date");

        form.insert_char('9');
        form.insert_char('x');
        form.delete_char();
        assert_eq!(form.parent, "", "typing must not reach the parent field");
        assert_eq!(form.focused_value(), "");

        // But a *picked* value does, and it reads back through the same accessor.
        form.parent = "42".to_string();
        assert_eq!(form.focused_value(), "42");
    }

    #[test]
    fn form_insert_and_delete() {
        let mut form = FormState::new("todo");
        form.insert_char('h');
        form.insert_char('i');
        assert_eq!(form.title, "hi");
        form.delete_char();
        assert_eq!(form.title, "h");
    }

    #[test]
    fn form_move_focus() {
        let mut form = FormState::new("todo");
        assert_eq!(form.focus, FormFocus::Title);
        form.move_focus_next();
        assert_eq!(form.focus, FormFocus::Status);
        form.move_focus_prev();
        assert_eq!(form.focus, FormFocus::Title);
    }

    #[test]
    fn render_smoke() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        // Tall enough for every row: the ring is 15 fields, plus the blank
        // separator, the hint, and the two border rows.
        let backend = TestBackend::new(80, 22);
        let mut terminal = Terminal::new(backend).unwrap();
        let form = FormState::new("todo");
        terminal.draw(|f| render(&form, f, f.area())).unwrap();

        let buf = terminal.backend().buffer();
        let mut text = String::new();
        for y in 0..buf.area.height {
            for x in 0..buf.area.width {
                text.push_str(buf[(x, y)].symbol());
            }
            text.push('\n');
        }
        assert!(text.contains("F2: Picker"), "got {text:?}");
    }

    /// The regression from #1486: with nothing drawn over it, rendering the create
    /// form leaves the terminal cursor **on the focused row**. Before this,
    /// `set_cursor_position` was called nowhere in the crate, so the cursor stayed
    /// wherever the previous frame put it and the form showed no insertion point.
    #[test]
    fn rendering_the_create_form_puts_the_caret_on_the_title_row() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let mut terminal = Terminal::new(TestBackend::new(60, 16)).unwrap();
        let form = FormState::new("todo");
        terminal.draw(|f| render(&form, f, f.area())).unwrap();

        // The block's border puts the inner area at (1, 1); the row prefix for an
        // empty title is "> Title: ".
        assert_eq!(
            terminal.backend().cursor_position(),
            Position::new(1 + "> Title: ".len() as u16, 1)
        );
    }

    #[test]
    fn caret_follows_the_typed_value() {
        let area = Rect::new(10, 5, 40, 20);
        let mut form = FormState::new("todo");
        form.title = "abc".to_string();
        assert_eq!(
            caret_position(&form, area),
            // inner starts one cell inside the border, at (11, 6).
            Some(Position::new(11 + "> Title: abc".len() as u16, 6))
        );
    }

    #[test]
    fn caret_moves_with_the_focused_row() {
        let area = Rect::new(0, 0, 40, 20);
        let mut form = FormState::new("todo");
        // Status and Priority are picker rows and show no caret (tix #1508), so
        // walk on to the first typeable row below them: the caret moved with the
        // focused row, and it is on *that* row.
        for _ in 0..3 {
            form.move_focus_next();
        }
        assert_eq!(form.focus, FormFocus::Labels);
        assert_eq!(
            caret_position(&form, area),
            // Row 3 of the ring, and the inner area already starts one row down.
            Some(Position::new(1 + "> Labels: ".len() as u16, 4))
        );
    }

    /// Width is not length: a two-character title occupies four cells, and the caret
    /// follows the cells.
    #[test]
    fn caret_measures_display_width_not_char_count() {
        let area = Rect::new(0, 0, 40, 20);
        let mut form = FormState::new("todo");
        form.title = "中日".to_string();
        assert_eq!(
            caret_position(&form, area),
            Some(Position::new(1 + "> Title: ".len() as u16 + 4, 1))
        );
    }

    /// A value wider than the field is clipped, so its true caret is off-screen; the
    /// position must stay inside the row rather than point past the border.
    #[test]
    fn caret_is_clamped_into_the_visible_row() {
        let area = Rect::new(0, 0, 20, 20);
        let mut form = FormState::new("todo");
        form.title = "x".repeat(100);
        // Inner width is 18, so the row's last cell is x = 18.
        assert_eq!(caret_position(&form, area), Some(Position::new(18, 1)));
    }

    #[test]
    fn no_caret_on_a_picker_only_field() {
        let area = Rect::new(0, 0, 40, 20);
        let mut form = FormState::new("todo");
        form.focus = FormFocus::Parent;
        assert_eq!(caret_position(&form, area), None);
    }

    #[test]
    fn caret_is_not_placed_outside_the_visible_form() {
        // Four rows: the ring's later fields are below the fold and get no caret,
        // because a position outside the rendered area would be drawn nowhere.
        let area = Rect::new(0, 0, 40, 4);
        let mut form = FormState::new("todo");
        form.focus = FormFocus::Reviewer;
        assert_eq!(caret_position(&form, area), None);
    }

    #[test]
    fn with_default_assignee_populates_assignee_field() {
        let form = FormState::with_default_assignee("in progress", "alice");
        assert_eq!(form.assignee, "alice");
        assert_eq!(form.status, "in progress");
        assert_eq!(form.focus, FormFocus::Title);
    }

    /// The control rows are chosen or toggled, never typed: a keypress on them
    /// must not reach a buffer.
    #[test]
    fn control_rows_refuse_typed_characters() {
        let mut form = FormState::new("todo");
        for (focus, before) in [
            (FormFocus::Target, form.target.label().to_string()),
            (FormFocus::Template, form.template.clone()),
        ] {
            form.focus = focus;
            assert!(focus.refuses_typing(), "{focus:?} refuses typing");
            form.insert_char('9');
            form.delete_char();
            assert_eq!(
                form.value_of(focus),
                before,
                "typing must not reach {focus:?}"
            );
        }
        // The body is *not* a control row: it accepts typed text like the rest.
        form.focus = FormFocus::Body;
        form.insert_char('h');
        form.insert_char('i');
        assert_eq!(form.body, "hi");
    }

    /// Status and Priority are chosen from dropdowns (tix #1508), so typed
    /// characters and backspace must leave their buffers exactly as they were —
    /// free text could name a column the board does not configure, or a priority
    /// no issue carries.
    #[test]
    fn the_status_and_priority_rows_refuse_typed_characters() {
        let mut form = FormState::new("todo");
        form.priority = "high".to_string();
        for (focus, before) in [
            (FormFocus::Status, form.status.clone()),
            (FormFocus::Priority, form.priority.clone()),
        ] {
            form.focus = focus;
            assert!(focus.refuses_typing(), "{focus:?} refuses typing");
            assert!(focus.is_picker_only(), "{focus:?} is picker-only");
            assert!(!focus.is_date(), "{focus:?} is not a date row");
            form.insert_char('9');
            form.insert_char('x');
            form.delete_char();
            assert_eq!(
                form.value_of(focus),
                before,
                "typing must not reach {focus:?}"
            );
        }
        // But a *picked* value does reach them, through the same accessors.
        form.focus = FormFocus::Status;
        form.status = "in progress".to_string();
        assert_eq!(form.focused_value(), "in progress");
        form.focus = FormFocus::Priority;
        assert_eq!(form.focused_value(), "high");
    }

    /// A chosen row shows no insertion point: the caret must not advertise an
    /// editing affordance the row refuses (tix #1508).
    #[test]
    fn no_caret_on_the_status_and_priority_rows() {
        let area = Rect::new(0, 0, 40, 30);
        let mut form = FormState::new("todo");
        form.focus = FormFocus::Status;
        assert_eq!(caret_position(&form, area), None);
        form.focus = FormFocus::Priority;
        assert_eq!(caret_position(&form, area), None);
    }

    /// A multi-line body is folded to one display row, so the row arithmetic the
    /// caret depends on holds; the stored value keeps the real newlines.
    #[test]
    fn body_newlines_are_escaped_for_display_only() {
        let mut form = FormState::new("todo");
        form.body = "a\nb".to_string();
        assert_eq!(form.body, "a\nb", "the stored body is verbatim");
        assert_eq!(form.display_value(FormFocus::Body), "a\\nb");

        let area = Rect::new(0, 0, 40, 30);
        form.focus = FormFocus::Body;
        let row = field_row_rect(area, FormFocus::Body).expect("body row is visible");
        assert_eq!(
            caret_position(&form, area),
            Some(Position::new(row.x + "> Body: a\\nb".len() as u16, row.y)),
            "the caret follows the folded display, not the raw newline"
        );
    }

    /// A template pre-fills the rows it sets and leaves the rest alone, so a
    /// labels-only template cannot erase a title the user already typed.
    #[test]
    fn apply_template_fills_set_fields_and_keeps_the_others() {
        let mut form = FormState::new("todo");
        form.title = "typed".to_string();
        let template = crate::config::IssueTemplate {
            body: Some("template body".to_string()),
            labels: vec!["bug".to_string(), "urgent".to_string()],
            ..crate::config::IssueTemplate::default()
        };
        form.apply_template("bug-report", &template);
        assert_eq!(form.template, "bug-report");
        assert_eq!(form.body, "template body");
        assert_eq!(form.labels, "bug,urgent");
        assert_eq!(form.title, "typed", "an omitted field is left untouched");
    }

    #[test]
    fn no_caret_on_a_target_or_template_row() {
        let area = Rect::new(0, 0, 40, 30);
        let mut form = FormState::new("todo");
        form.focus = FormFocus::Target;
        assert_eq!(caret_position(&form, area), None);
        form.focus = FormFocus::Template;
        assert_eq!(caret_position(&form, area), None);
    }
}