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
#[allow(clippy::wildcard_imports)]
use super::*;
impl App {
#[allow(clippy::too_many_lines)]
pub(in crate::app) fn handle_form_key(&mut self, key: KeyEvent) -> Result<Action> {
if self.form_picker.is_some() {
return self.handle_form_picker_key(key);
}
let form = match self.form.as_mut() {
Some(f) => f,
None => return Ok(Action::None),
};
match key.code {
KeyCode::Esc => {
self.form = None;
self.mode = Mode::Board;
Ok(Action::None)
}
KeyCode::Enter => {
// The Target row is a toggle, not a submit: Enter flips Triage /
// Todo and writes the matching status, which is what determines
// the created issue's column. It has to be handled before the
// submit path, or choosing a target would create the issue.
if form.focus.is_target() {
let next = form.target.next();
self.set_form_target(next);
return Ok(Action::None);
}
// Likewise the Template row: Enter opens the picker rather than
// submitting a form whose template the user was reaching for.
if form.focus.is_template() {
self.open_template_picker();
return Ok(Action::None);
}
if form.is_date_focus() && !form.focused_date_is_complete() {
self.open_date_picker(Mode::Form);
return Ok(Action::None);
}
// A parent is chosen, never typed, so an **empty** Parent row has
// nothing to submit and Enter means "choose". This is the same rule
// the date fields follow one branch above — Enter opens the picker
// only while the value is missing, and submits once it is there.
//
// Not "always open the picker", which was the first attempt: that
// makes Parent a field the form can never be submitted from, because
// Enter there never submits and the only way out is to tab away. A
// chosen field that traps the submit key is worse than a plain text
// field.
if form.focus.is_parent() && form.parent.trim().is_empty() {
self.open_form_picker();
return Ok(Action::None);
}
// Status and Priority are chosen from their dropdowns and refuse
// typing (tix #1508), so Enter on either row means "choose" and
// never submits — the same way a Parent row keeps Enter for the
// picker. The user submits from another row.
if form.focus.is_status() || form.focus.is_priority() {
self.open_form_picker();
return Ok(Action::None);
}
// A stable-ID template selection resolves through the **shared**
// resolver and writes through the **shared** create core
// (C-007/NFR-002). Only the pick/toggle interactions above are
// handled first — this is the submit itself, so it runs before the
// form's own field checks: the resolver owns required/reference
// diagnostics and the create core owns column/planning/date
// validation, so neither is restated here (and the two paths
// cannot drift).
if let Some(scope) = form.template_scope.clone() {
let id = form.template.clone();
let input = template_input_from_form(form);
// WP06 T029: the template route carries the Projects row too, so
// the row is not a no-op on the one create path that goes through
// the shared resolver. Resolved through the service, before
// anything is written, exactly as the other route does — a refusal
// leaves the form and the store untouched.
let project_ids = match crate::commands::project::resolve_projects(
&self.store.config,
&form.projects,
) {
Ok(ids) => ids,
Err(e) => {
self.status_msg = Some(e.to_string());
return Ok(Action::None);
}
};
// WP06 T031: the template route carries the Epics row too,
// resolved through the epic service before anything is written —
// a refusal leaves the form and the store untouched, exactly as
// the other route does.
let epic_ids =
match crate::commands::epic::resolve_epics(&self.store.config, &form.epics)
{
Ok(ids) => ids,
Err(e) => {
self.status_msg = Some(e.to_string());
return Ok(Action::None);
}
};
return self.submit_stable_template(
&id,
&scope,
&input,
&project_ids,
&epic_ids,
);
}
if form.title.trim().is_empty() {
self.status_msg = Some("Title is required".to_string());
return Ok(Action::None);
}
let start_date = if form.start_date.trim().is_empty() {
None
} else {
Some(form.start_date.trim().to_string())
};
let due_date = if form.due_date.trim().is_empty() {
None
} else {
Some(form.due_date.trim().to_string())
};
if let Some(start) = start_date.as_deref()
&& !crate::model::validate_date(start)
{
self.status_msg = Some("Start date must be YYYY-MM-DD".to_string());
return Ok(Action::None);
}
if let Some(due) = due_date.as_deref()
&& !crate::model::validate_date(due)
{
self.status_msg = Some("Due date must be YYYY-MM-DD".to_string());
return Ok(Action::None);
}
if let (Some(start), Some(due)) = (start_date.as_deref(), due_date.as_deref())
&& due < start
{
self.status_msg = Some("Due date must be >= start date".to_string());
return Ok(Action::None);
}
let title = form.title.trim().to_string();
// The body is submitted verbatim — not trimmed, because leading or
// trailing blank lines in Markdown are content, and a template
// writes them on purpose.
let body = form.body.clone();
let status_str = if form.status.trim().is_empty() {
self.store
.config
.default_config()
.columns
.first()
.cloned()
.unwrap_or_else(|| "todo".to_string())
} else {
form.status.trim().to_string()
};
let priority: Priority = form.priority.parse().unwrap_or_default();
let identity = git_identity();
let assignee = if form.assignee.trim().is_empty() {
None
} else {
resolve_me(form.assignee.trim(), identity.as_ref())
};
let labels: Vec<String> = form
.labels
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
let estimate = if form.estimate.trim().is_empty() {
None
} else {
Some(form.estimate.trim().to_string())
};
let cycles = {
let values: Vec<String> = form
.cycles
.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string)
.collect();
if values.is_empty() {
// No explicit selection joins the default cycle, the
// same answer the CLI create core gives (tui-cycle-mode).
Some(vec![crate::commands::create::default_cycle_name(
&self.store.config,
)])
} else {
Some(values)
}
};
let milestones = {
let values: Vec<String> = form
.milestones
.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string)
.collect();
(!values.is_empty()).then_some(values)
};
let reviewer = if form.reviewer.trim().is_empty() {
None
} else {
Some(form.reviewer.trim().to_string())
};
// The parent is resolved and validated through the hierarchy
// service **before** anything is written, exactly as
// `commands::create` does it — same resolution, same
// `validate_new_parent`, so a bad parent creates no file, no
// number, and no History entry. The service's own diagnostic is
// what reaches `status_msg`, so the TUI says what the CLI says
// rather than a second wording of the same rule.
//
// `validate_new_parent`, not `set_parent`: the child does not exist
// yet, so it cannot be its own parent and cannot close a cycle. A
// self-parent and a cycle are both *unrepresentable* here, not merely
// rejected.
//
// **This call is not test-covered, and the reason is worth stating
// rather than leaving implied.** The picker's options come from the
// store, so every value the user can choose is a live issue; and
// `unknown_parent` needs a selector that *resolves* to a number the
// index does not hold. `resolve_issue` and `hierarchy_index` each
// re-read the store, so that state exists only for a delete landing
// between the two reads — a window no single-threaded test can enter,
// since deleting first makes `resolve_issue` fail instead (which is
// the refusal `t027_a_rejected_parent_keeps_the_form_open...` does
// assert). Reverting the line leaves the suite green, so this is
// defence in depth against a concurrent delete, kept because the CLI
// has the identical line and the charter's parity boundary is about
// what both surfaces *do*, not about which of them is covered.
//
// A rejection returns to the form with the field untouched, so the
// user keeps everything they typed and can pick again.
let (parent_ref, parent_number) = match form.parent.trim() {
"" => (None, None),
raw => match self.store.resolve_issue(raw).and_then(|target| {
let (index, _) = self.store.hierarchy_index()?;
crate::hierarchy::validate_new_parent(&index, target.number)?;
Ok(target)
}) {
Ok(target) => {
(Some(crate::id::canonical_ref(&target)), Some(target.number))
}
Err(e) => {
self.status_msg = Some(e.to_string());
return Ok(Action::None);
}
},
};
// WP06 T029 step 4/5: the associations are **the service's**. They
// are resolved before anything is written, through the same
// `create --projects` helper the CLI uses, so an unknown project
// refuses the whole create with the service's own diagnostic — the
// form stays open, the field keeps its value, and no file, number or
// History entry is made. The form constructs no project and validates
// none; it hands the service the ids the picker chose.
let project_ids = match crate::commands::project::resolve_projects(
&self.store.config,
&form.projects,
) {
Ok(ids) => ids,
Err(e) => {
self.status_msg = Some(e.to_string());
return Ok(Action::None);
}
};
// WP06 T031: the epic references are resolved through the service
// **before** anything is written, so an unknown epic refuses the whole
// create with the service's own diagnostic — the form stays open, the
// field keeps its value, and no file, number or History entry is made.
// The form constructs no epic and validates none; it hands the service
// the ids the picker chose.
let epic_ids =
match crate::commands::epic::resolve_epics(&self.store.config, &form.epics) {
Ok(ids) => ids,
Err(e) => {
self.status_msg = Some(e.to_string());
return Ok(Action::None);
}
};
let mut issue = Issue {
projects: None,
id: None,
number: 0,
type_: None,
title,
status: Status::new(status_str),
labels,
priority,
assignee,
estimate,
commit: None,
gitlab_id: None,
linear_id: None,
mission: None,
task: None,
relationships: vec![],
related_issues: vec![],
series: None,
health: None,
files: vec![],
cycles,
milestones,
reviewer,
start_date,
due_date,
created: today(),
updated: today(),
filename: String::new(),
body: String::new(),
history: crate::model::History::new(),
has_retired_links_key: false,
time_entries: vec![],
parent: parent_ref,
epics: None,
extra_frontmatter: std::collections::BTreeMap::new(),
archived: false,
entered_at: None,
source: None,
};
// Exactly one History entry, naming the parent (C-004). Appended to
// the in-memory issue so `store.create` writes it with the first
// content — an entry that only appeared on a later edit would
// describe a create that did not happen this way. This is the step
// the TUI's hand-built `Issue` was silently skipping (tix #1385).
if let Some(parent_number) = parent_number {
issue.history.append_now(
&crate::storage::actor_identity(),
crate::model::HistoryEventKind::ParentSet,
&crate::hierarchy::change_detail(None::<u32>, Some(parent_number)),
);
}
// The entry stamp, through the **same** rule the CLI's create core
// uses: without it this form was the one create path that entered the
// inbox without recording when, so the queue reported an `unknown` age
// for an issue the TUI had just created. (The form still builds its own
// `Issue` rather than calling `commands::create::create` — see tix #1385
// for the parent/History line that cost once already; what must not be
// duplicated is the *rule*, and it no longer is.) Applied **before** the
// write, so the file and the stamp cannot disagree.
crate::triage::record_entry_if_inbox(&self.store.config, &mut issue, "new")?;
self.store.create(&mut issue, &body, None)?;
// WP06 T029 step 4: one store-level association write per id, the
// same helper the CLI's create core calls — so the History entry is
// appended **exactly once** per project and the idempotence rule is
// the service's, not a second implementation here. The ids were
// resolved before the issue existed, so this cannot leave a
// half-associated create.
crate::commands::project::associate_created(&self.store, &issue, &project_ids)?;
// WP06 T031 step 4: the epic references are written through the
// **service's** own store helper, so the History entry is appended
// exactly once per epic and the idempotence rule stays the service's,
// not a second implementation here. The ids were resolved before the
// issue existed, so this cannot leave a half-referenced create.
crate::commands::epic::reference_created(&self.store, &issue, &epic_ids)?;
// `issue.filename` is the store-relative path (including the
// assignee segment); the board's cards key on that, so select
// with it — the basename would never match and the wrong card
// would stay selected.
let filename = issue.filename.clone();
let basename = filename.rsplit('/').next().unwrap_or(&filename).to_string();
self.status_msg = Some(format!("Created {basename}"));
self.form = None;
self.mode = Mode::Board;
self.refresh_corpus()?;
self.select_card_by_filename(&filename);
Ok(Action::None)
}
KeyCode::Tab | KeyCode::Down => {
form.move_focus_next();
Ok(Action::None)
}
KeyCode::BackTab | KeyCode::Up => {
form.move_focus_prev();
Ok(Action::None)
}
// On the Target row, Left/Right pick a side directly (Enter above
// toggles). Everywhere else they move the insertion point one
// character, or one word with Ctrl/Alt held (tix #1746).
KeyCode::Left => {
if form.focus.is_target() {
self.set_form_target(crate::ui::form::NewIssueTarget::Triage);
} else if key
.modifiers
.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
{
form.move_cursor_word_left();
} else {
form.move_cursor_left();
}
Ok(Action::None)
}
KeyCode::Right => {
if form.focus.is_target() {
self.set_form_target(crate::ui::form::NewIssueTarget::Todo);
} else if key
.modifiers
.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
{
form.move_cursor_word_right();
} else {
form.move_cursor_right();
}
Ok(Action::None)
}
KeyCode::Home => {
form.cursor_to_start();
Ok(Action::None)
}
KeyCode::End => {
form.cursor_to_end();
Ok(Action::None)
}
KeyCode::F(2) => {
if form.is_date_focus() {
self.open_date_picker(Mode::Form);
} else {
self.open_form_picker();
}
Ok(Action::None)
}
// The Emacs set (`Ctrl-A/E/B/F/H/D/K/U/W`) and `Ctrl-Backspace`,
// which is what readline-style prompts everywhere bind. Keys are
// matched on the **character**, case-folded, because a terminal may
// report Ctrl-Shift-A as either case.
KeyCode::Char(c) if key.modifiers.contains(KeyModifiers::CONTROL) => {
match c.to_ascii_lowercase() {
'a' => form.cursor_to_start(),
'e' => form.cursor_to_end(),
'b' => form.move_cursor_left(),
'f' => form.move_cursor_right(),
'h' => form.delete_char(),
'd' => form.delete_forward_char(),
'k' => form.delete_to_end(),
'u' => form.delete_to_start(),
'w' => form.delete_word_backward(),
_ => {}
}
Ok(Action::None)
}
KeyCode::Char(c) => {
form.insert_char(c);
Ok(Action::None)
}
KeyCode::Backspace => {
if key
.modifiers
.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
{
form.delete_word_backward();
} else {
form.delete_char();
}
Ok(Action::None)
}
KeyCode::Delete => {
form.delete_forward_char();
Ok(Action::None)
}
_ => Ok(Action::None),
}
}
/// Submit the form through the shared template resolver and create core
/// (WP05/T025).
///
/// The selection is resolved by [`crate::templates::resolve`], which is pure
/// and returns **every** diagnostic and no request on failure; a failed
/// resolution sets `status_msg` and leaves both the form and the store
/// untouched — no partial issue, exactly as the CLI's template path
/// (C-005/FR-004). On success the request is destructured straight into
/// [`crate::commands::create::create`], the same core `tix create --template`
/// and the MCP create tool use, so the created issue is equivalent to the
/// CLI's for the same template, scope and input (C-007/NFR-002). The template
/// ID and scope stay visible: they are on the form's Template row before
/// submit and in the result message after (FR-005).
pub(in crate::app) fn submit_stable_template(
&mut self,
id: &str,
scope: &str,
input: &TemplateInput,
project_ids: &[String],
epic_ids: &[String],
) -> Result<Action> {
let scope = match scope.parse::<TemplateScope>() {
Ok(scope) => scope,
Err(error) => {
self.status_msg = Some(error);
return Ok(Action::None);
}
};
let scope_label = scope.to_string();
let selection = TemplateSelection::new(id, scope);
let resolution = resolve(&self.store.config, &selection, input);
if !resolution.is_ok() {
let diagnostics = resolution
.diagnostics()
.iter()
.map(|diagnostic| format!("{}: {}", diagnostic.field(), diagnostic.message()))
.collect::<Vec<_>>()
.join(" | ");
self.status_msg = Some(format!(
"template `{}` at scope `{}` did not resolve: {diagnostics}",
resolution.template_id(),
resolution.scope()
));
return Ok(Action::None);
}
let request = resolution
.into_request()
.expect("a successful resolution always carries a request");
let issue = match crate::commands::create::create(
&self.store.config,
&self.store,
&request.title,
request.body.as_deref(),
request.status.clone(),
request.priority.clone(),
request.assignee.as_deref(),
request.labels.as_deref(),
request.files.as_deref(),
request.estimate.as_deref(),
request.cycles.as_deref(),
request.milestones.as_deref(),
request.reviewer.as_deref(),
request.start_date.as_deref(),
request.due_date.as_deref(),
request.parent.as_deref(),
request.related_issues.as_deref(),
request.type_.as_deref(),
) {
Ok(issue) => issue,
Err(error) => {
// The create core validates the column, planning references,
// dates and parent **before** `Store::create`, so a refusal here
// wrote nothing; the form keeps everything the user typed.
self.status_msg = Some(error.to_string());
return Ok(Action::None);
}
};
let filename = issue.filename.clone();
// WP06 T029 step 4: the same store-level association write the other create
// route uses, so the Project History entry is appended exactly once and the
// idempotence rule stays the service's. The ids were resolved before the
// create, so this cannot leave a half-associated issue.
crate::commands::project::associate_created(&self.store, &issue, project_ids)?;
// WP06 T031: the epic references, through the same store-level service path
// the other create route uses, so the History entry is appended exactly once
// per epic and the idempotence rule stays the service's.
crate::commands::epic::reference_created(&self.store, &issue, epic_ids)?;
let basename = filename.rsplit('/').next().unwrap_or(&filename).to_string();
self.status_msg = Some(format!(
"Created {basename} (template `{id}` at scope `{scope_label}`)"
));
self.form = None;
self.mode = Mode::Board;
self.refresh_corpus()?;
self.select_card_by_filename(&filename);
Ok(Action::None)
}
/// Open the calendar picker, seeded from the focused date field of the
/// modal identified by `return_to`.
pub(in crate::app) fn open_date_picker(&mut self, return_to: Mode) {
let current = match return_to {
Mode::Form => self.form.as_ref().map(|f| f.focused_value().to_string()),
Mode::PlanningForm => self
.planning_form
.as_ref()
.map(|f| f.focused_value().to_string()),
Mode::FilterModal => self.filter_modal.as_ref().map(|m| m.focused_value()),
_ => None,
};
self.date_picker = Some(DatePicker::new(current.as_deref().unwrap_or("")));
self.mode = Mode::DatePicker {
return_to: Box::new(return_to),
};
}
pub(in crate::app) fn handle_date_picker_key(&mut self, key: KeyEvent) -> Result<Action> {
let Some(picker) = self.date_picker.as_mut() else {
self.mode = Mode::Board;
return Ok(Action::None);
};
match picker.handle_key(key.code) {
DatePickerEvent::None => {}
DatePickerEvent::Cancelled => self.close_date_picker(),
DatePickerEvent::Selected(value) => {
self.apply_date_selection(&value);
self.close_date_picker();
}
DatePickerEvent::Cleared => {
self.apply_date_selection("");
self.close_date_picker();
}
}
Ok(Action::None)
}
/// Close the picker and restore the modal that opened it.
pub(in crate::app) fn close_date_picker(&mut self) {
let return_to = match std::mem::replace(&mut self.mode, Mode::Board) {
Mode::DatePicker { return_to } => *return_to,
_ => Mode::Board,
};
self.date_picker = None;
self.mode = return_to;
}
/// Write the picked `value` (empty clears) into the modal the picker was
/// opened from.
pub(in crate::app) fn apply_date_selection(&mut self, value: &str) {
let return_to = match &self.mode {
Mode::DatePicker { return_to } => (**return_to).clone(),
_ => return,
};
match return_to {
Mode::Form => {
if let Some(form) = self.form.as_mut() {
form.set_focused_date(value);
}
}
Mode::PlanningForm => {
if let Some(form) = self.planning_form.as_mut() {
form.set_focused_date(value);
}
}
Mode::FilterModal => {
if let Some(modal) = self.filter_modal.as_mut() {
modal.set_focused_date(value);
}
self.rebuild_board();
}
_ => {}
}
}
/// The status a New Issue target lands the created issue in.
///
/// Derived from configuration rather than hard-coded so a renamed column still
/// works: `Triage` is the inbox's `entry_status` when the project has one, and
/// `Todo` is a literal `todo` column when the board names one. The `Todo`
/// fallbacks keep a project whose columns are not named `todo` creating
/// *somewhere real* — its accepted status, then its first column — rather than
/// writing a status the board cannot show.
pub(in crate::app) fn new_issue_target_status(&self, target: NewIssueTarget) -> String {
let triage = self.store.config.triage.as_ref();
match target {
NewIssueTarget::Triage => triage
.and_then(|t| t.entry_status.as_deref())
.map(str::trim)
.filter(|s| !s.is_empty())
.unwrap_or("triage")
.to_string(),
NewIssueTarget::Todo => {
let columns = &self.store.config.default_config().columns;
if columns.iter().any(|c| c == "todo") {
return "todo".to_string();
}
triage
.and_then(|t| t.accepted_status.as_deref())
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string)
.or_else(|| columns.first().cloned())
.unwrap_or_else(|| "todo".to_string())
}
}
}
/// Choose a New Issue target and write its status into the Status row.
///
/// Writing the status is what makes the choice *determine* the created issue's
/// column: submit reads `form.status`, so the Target row cannot disagree with
/// what is created. The Status row stays editable afterwards, which is how a
/// column the two targets do not name is still reachable.
pub(in crate::app) fn set_form_target(&mut self, target: NewIssueTarget) {
let status = self.new_issue_target_status(target);
if let Some(form) = self.form.as_mut() {
form.target = target;
form.status = status;
}
}
/// Open the Template row's picker over the configured templates.
///
/// A `(none)` option comes first so the selection is clearable; choosing it
/// only drops the label, leaving whatever the template pre-filled in place,
/// because the user's typed values are the form's, not the template's.
///
/// **Applicability boundary (WP05/T026):** template *management* —
/// create/update/duplicate/delete and the preserved-unknown-metadata view —
/// lives on the CLI (`tix template …`) and is deliberately not duplicated
/// here. The TUI's surface is *selection*: it lists each stable template's
/// ID, display name and explicit scope and seeds the form from the chosen
/// one, which is the metadata this mode actually needs. Neither the board nor
/// the form mode is otherwise touched.
pub(in crate::app) fn open_template_picker(&mut self) {
if self.store.config.issue_templates.is_empty() && self.store.config.templates.is_empty() {
self.status_msg = Some(
"No templates configured; add [issue_templates.<id>] or [templates.<name>] to \
tix.toml"
.to_string(),
);
return;
}
let mut options = vec![PickerItem {
id: String::new(),
label: "(none)".to_string(),
}];
options.extend(self.template_picker_options());
let mut state = DropdownState::single(options);
self.seed_picker_selection(FormPickerField::Template, &mut state);
self.form_picker = Some(FormPicker {
field: FormPickerField::Template,
state,
});
}
/// Pre-fill the form from a named **legacy** template, or clear the selection
/// for an empty/unknown name.
///
/// Clears any stable scope, so the submit path cannot keep resolving through
/// the stable resolver after a legacy record is chosen.
pub(in crate::app) fn select_template(&mut self, name: &str) {
let template = self.store.config.templates.get(name).cloned();
if let Some(form) = self.form.as_mut() {
match template {
Some(template) => form.apply_template(name, &template),
None => {
form.template.clear();
form.template_scope = None;
}
}
}
}
/// Pre-fill the form from a stable-ID template and record its ID + scope, or
/// clear the selection when the ID is unknown.
///
/// The scope is the template's **own declared scope**, which is explicit and
/// visible (C-003/FR-005); the shared resolver re-checks it at submit, so a
/// mismatch can never reach a write.
pub(in crate::app) fn select_stable_template(&mut self, id: &str) {
let template = self.store.config.issue_templates.get(id).cloned();
if let Some(form) = self.form.as_mut() {
match template {
Some(template) => {
let scope = template.scope.to_string();
form.apply_stable_template(id, &scope, &template);
}
None => {
form.template.clear();
form.template_scope = None;
}
}
}
}
/// Decode a namespaced Template picker option id and apply it.
///
/// An empty id is `(none)` and clears the selection without emptying the
/// form. An unprefixed non-empty id is treated as a legacy name, so a raw
/// name still selects the legacy record rather than silently clearing the row.
pub(in crate::app) fn apply_template_choice(&mut self, raw_id: &str) {
if let Some(id) = raw_id.strip_prefix(STABLE_TEMPLATE_PREFIX) {
self.select_stable_template(id);
} else if let Some(name) = raw_id.strip_prefix(LEGACY_TEMPLATE_PREFIX) {
self.select_template(name);
} else if raw_id.is_empty() {
if let Some(form) = self.form.as_mut() {
form.template.clear();
form.template_scope = None;
}
} else {
self.select_template(raw_id);
}
}
/// Run a New Issue-mode pointer action recorded during the draw. Public so the
/// hit-region tests drive the same path the run loop does.
pub fn apply_new_issue_action(&mut self, action: Action) -> Result<Action> {
match action {
Action::TemplateOpen => self.open_template_picker(),
Action::TemplatePickOption(row) => {
let chosen = self.form_picker.as_ref().and_then(|picker| {
if picker.field != FormPickerField::Template {
return None;
}
let index = *picker.state.visible_indices().get(row)?;
Some(picker.state.options.get(index)?.id.clone())
});
if let Some(id) = chosen {
self.form_picker = None;
self.apply_template_choice(&id);
}
}
_ => {}
}
Ok(Action::None)
}
/// Open the F4 New Issue mode — `n` on the board, the F4 shell chord, and
/// where `tix new` starts the session (#1398, tui-new-issue-mode).
///
/// Seeds the default target's status and the git identity (FR-028, best effort:
/// empty when git is absent, never an error). One method rather than copies,
/// because the key, the shell switch, and the command must produce the *same*
/// form — entry points into one mode that default differently is how a bug is
/// born.
pub fn open_new_issue_form(&mut self) {
let default_assignee = crate::assignee::git_identity()
.map(|id| id.to_string())
.unwrap_or_default();
let target = NewIssueTarget::default();
let default_status = self.new_issue_target_status(target);
let mut form = FormState::with_default_assignee(&default_status, &default_assignee);
form.target = target;
self.enter_form(form);
}
/// Put `form` on screen as the New Issue mode and record the shell mode.
pub(in crate::app) fn enter_form(&mut self, form: FormState) {
self.form = Some(form);
self.mode = Mode::Form;
// `sync_top_mode` would derive this on the next key, but the direct entry
// points (`tix new`, the F4 switch) draw the navigation highlight before any
// key arrives, so the mode must be recorded here rather than a frame later.
self.top_mode = TopMode::NewIssue;
}
}