kanban-tui 0.7.2

Terminal user interface for the kanban project management tool
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
use crate::app::{App, AppMode, DialogMode, ExportDialogState, Focus, SettingsFocus};
use crate::edit_format::EditFormat;
use crate::editor::edit_in_external_editor;
use crate::events::EventHandler;
use crossterm::event::KeyCode;
use kanban_domain::export::{AllBoardsExport, BoardExporter};
use kanban_service::AppConfigDto;
use ratatui::backend::CrosstermBackend;
use ratatui::Terminal;
use std::io;

const EXPORT_BUTTON_STORAGE_INDEX: usize = 3;

impl App {
    pub fn settings_item_count(&self, panel: SettingsFocus) -> usize {
        match panel {
            SettingsFocus::Configuration => {
                if self.has_data_file {
                    if self.cli_file_override {
                        9
                    } else {
                        7
                    }
                } else {
                    5
                }
            }
            SettingsFocus::ConfigFile => 3,
            SettingsFocus::Storage => 4,
        }
    }

    pub fn handle_open_settings(&mut self) {
        if self.focus.active == Focus::Boards {
            self.focus.settings_focus = SettingsFocus::Configuration;
            self.selection.settings_config.set(Some(0));
            self.push_mode(AppMode::Settings);
        }
    }

    pub fn apply_config_edit(
        &mut self,
        new_content: &str,
        format: &EditFormat,
    ) -> Result<bool, String> {
        if !matches!(self.migration_state, crate::app::MigrationState::Idle) {
            return Err("Migration in progress, please wait".to_string());
        }
        let old_location =
            kanban_service::config::effective_configuration_location(&self.app_config);
        let old_storage_location =
            kanban_service::config::resolve_storage_location(&self.app_config);
        let old_config = self.app_config.clone();
        let mut config = self.app_config.clone();
        if self.cli_file_override {
            config.storage_backend = self.original_storage_backend.clone();
            config.storage_location = self.original_storage_location.clone();
        }

        let mut updated_dto: AppConfigDto = format
            .deserialize(new_content)
            .map_err(|e| format!("Failed to parse config: {}", e))?;

        // When cli_file_override is active the storage lines are commented out in
        // the editor. If the user deliberately uncomments them, the DTO will carry
        // storage fields — treat that as an explicit request to persist those
        // settings and drop the CLI override.
        let user_unlocked_storage = self.cli_file_override
            && (updated_dto.storage_backend.is_some() || updated_dto.storage_location.is_some());

        // Strip storage fields from the DTO unless the user explicitly changed the
        // storage path to a different file:
        // - CLI-supplied storage is always session-only (unless the user unlocks it).
        // - In the normal case, from_config puts the resolved absolute path into the
        //   DTO; if the user only changed non-storage fields, that same path comes
        //   back and must not be written to config (strip_defaults compares against
        //   the relative default, not the absolute, so it would survive stripping).
        let strip_storage = !user_unlocked_storage
            && (self.cli_file_override || {
                match updated_dto.storage_location.as_deref() {
                    None => false,
                    Some(loc) => {
                        let p = std::path::Path::new(loc);
                        let dto_resolved = if p.is_absolute() {
                            loc.to_string()
                        } else {
                            std::env::current_dir()
                                .map(|cwd| cwd.join(p).display().to_string())
                                .unwrap_or_else(|_| loc.to_string())
                        };
                        dto_resolved == old_storage_location
                    }
                }
            });
        if strip_storage {
            updated_dto.storage_backend = None;
            updated_dto.storage_location = None;
            // Also reset the working config to the original config-file values so
            // that any absolute path injected by App::new during CLI arg processing
            // does not survive into the saved file (strip_defaults can't recognise
            // an absolute path as the default relative "boards.json").
            config.storage_backend = self.original_storage_backend.clone();
            config.storage_location = self.original_storage_location.clone();
        }

        updated_dto
            .validate_and_apply(&mut config)
            .map_err(|e| format!("Invalid config: {}", e))?;

        if kanban_service::config::has_non_default_values(&config) {
            kanban_service::config::save(&config)
                .map_err(|e| format!("Failed to save config: {}", e))?;
            let new_location = kanban_service::config::effective_configuration_location(&config);
            if new_location != old_location {
                let old_path = std::path::Path::new(&old_location);
                if old_path.exists() {
                    if let Err(e) = std::fs::remove_file(old_path) {
                        tracing::warn!(
                            "Failed to remove old config file {}: {}",
                            old_path.display(),
                            e
                        );
                    }
                }
            }
        } else {
            let location = kanban_service::config::effective_configuration_location(&config);
            let path = std::path::Path::new(&location);
            if path.exists() {
                if let Err(e) = std::fs::remove_file(path) {
                    tracing::warn!("Failed to remove config file {}: {}", path.display(), e);
                }
            }
        }

        self.app_config = config;

        if self.cli_file_override {
            if user_unlocked_storage {
                // User explicitly uncommitted the storage fields → drop the override
                // so the new storage settings take effect permanently.
                self.cli_file_override = false;
                self.cli_file_provided = false;
            } else {
                // Storage lines were still commented out → keep the CLI-supplied
                // storage active for this session and skip migration.
                self.app_config.storage_backend = old_config.storage_backend.clone();
                self.app_config.storage_location = old_config.storage_location.clone();
                return Ok(true);
            }
        }

        self.apply_storage_location_change(old_config, &old_storage_location);
        Ok(true)
    }

    pub fn apply_storage_location_change(
        &mut self,
        old_config: kanban_core::AppConfig,
        old_storage_location: &str,
    ) {
        use crate::app::MigrationState;

        let new_storage_location =
            kanban_service::config::resolve_storage_location(&self.app_config);

        if self
            .store_manager
            .sync_backend_with_file(&new_storage_location, &mut self.app_config)
        {
            self.set_success(format!(
                "storage_backend changed to '{}' to match file at '{}'",
                self.app_config.effective_storage_backend(),
                new_storage_location
            ));
        }

        if !self.has_data_file || new_storage_location == old_storage_location {
            return;
        }

        let new_backend = self.app_config.effective_storage_backend().to_string();
        let old_backend = old_config.effective_storage_backend().to_string();
        let old_storage_location_owned = old_storage_location.to_string();
        let old_path_exists = std::path::Path::new(old_storage_location).exists();

        let (tx, rx) = tokio::sync::oneshot::channel();

        let new_storage_clone = new_storage_location.clone();
        let new_backend_clone = new_backend.clone();
        let store_manager = self.store_manager.clone();
        tokio::spawn(async move {
            let file_existed = std::path::Path::new(&new_storage_clone).exists();
            let result: Result<(kanban_domain::Snapshot, bool), String> = async {
                if !file_existed && old_path_exists {
                    store_manager
                        .migrate_store(
                            &old_backend,
                            &old_storage_location_owned,
                            &new_backend_clone,
                            &new_storage_clone,
                        )
                        .await
                        .map_err(|e| format!("Migration failed: {}", e))?;
                }

                let snapshot = store_manager
                    .validate_and_load_store(&new_backend_clone, &new_storage_clone)
                    .await
                    .map_err(|e| format!("Invalid storage file: {}", e))?;
                Ok((snapshot, file_existed))
            }
            .await;

            let _ = tx.send(result);
        });

        self.migration_state = MigrationState::Migrating {
            old_config,
            old_storage_location: old_storage_location.to_string(),
            result_rx: rx,
        };
        self.set_success("Migrating storage...".to_string());
    }

    pub async fn handle_migration_complete(
        &mut self,
        old_config: kanban_core::AppConfig,
        result: Result<(kanban_domain::Snapshot, bool), String>,
    ) {
        self.migration_state = crate::app::MigrationState::Idle;
        self.quit_with_migration = false;

        let (snapshot, file_existed) = match result {
            Ok(s) => s,
            Err(e) => {
                self.app_config = old_config;
                self.set_error(e);
                return;
            }
        };

        let new_storage_location =
            kanban_service::config::resolve_storage_location(&self.app_config);

        let new_backend = match self
            .store_manager
            .make_backend(&new_storage_location, &self.app_config)
            .await
        {
            Ok(b) => b,
            Err(e) => {
                self.app_config = old_config;
                self.set_error(format!("Store swap failed: {}", e));
                return;
            }
        };

        self.ctx.replace_backend(new_backend);
        let (save_rx, completion_rx) = self.ctx.save_coordinator.reset_save_channels();
        use crate::state::snapshot::TuiSnapshot;
        if let Err(e) = snapshot.apply_to_app(self) {
            tracing::error!("Failed to apply snapshot: {}", e);
        }
        self.ctx.mark_clean();
        if let Err(e) = self.ctx.clear_history() {
            tracing::error!("Failed to clear history: {}", e);
        }

        self.selection.active_board_index = if self.model.boards().is_empty() {
            None
        } else {
            Some(0)
        };
        self.selection.board.set(if self.model.boards().is_empty() {
            None
        } else {
            Some(0)
        });
        self.selection.active_card_id = None;
        self.selection.card_navigation_history.clear();

        self.persistence.save_file = Some(new_storage_location.clone());
        self.persistence.save_completion_rx = Some(completion_rx);
        self.spawn_save_worker(save_rx, None);
        self.cli_file_override = false;
        self.cli_file_provided = false;
        let msg = if file_existed {
            format!("Loaded from {}", new_storage_location)
        } else {
            format!("Migrated to {}", new_storage_location)
        };
        self.set_success(msg);
    }

    pub async fn await_migration(&mut self) {
        use crate::app::MigrationState;
        let (old_config, rx) =
            match std::mem::replace(&mut self.migration_state, MigrationState::Idle) {
                MigrationState::Migrating {
                    old_config,
                    result_rx,
                    ..
                } => (old_config, result_rx),
                MigrationState::Idle => return,
            };
        if let Ok(result) = rx.await {
            self.handle_migration_complete(old_config, result).await;
        }
    }

    fn open_config_editor(
        &mut self,
        terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
        event_handler: &EventHandler,
    ) -> bool {
        let format = EditFormat::parse(self.app_config.effective_editing_format());
        let ext = format.file_extension();
        let mut dto = AppConfigDto::from_config(&self.app_config, self.has_data_file);
        if self.cli_file_override {
            dto.storage_backend = if self.config_storage_backend.is_empty() {
                None
            } else {
                Some(self.config_storage_backend.clone())
            };
            dto.storage_location = if self.config_storage_location.is_empty() {
                None
            } else {
                Some(self.config_storage_location.clone())
            };
        }
        let serialized = format.serialize(&dto).unwrap_or_else(|_| "{}".to_string());
        let current_content = if self.cli_file_override {
            format.comment_storage_fields(&serialized)
        } else {
            serialized
        };
        let temp_file = std::env::temp_dir().join(format!("kanban_config_edit.{}", ext));
        match edit_in_external_editor(terminal, event_handler, temp_file, &current_content) {
            Ok(Some(new_content)) => {
                if new_content.trim() != current_content.trim() {
                    if let Err(e) = self.apply_config_edit(&new_content, &format) {
                        self.set_error(e);
                    }
                }
            }
            Ok(None) => {}
            Err(e) => {
                self.set_error(format!("Failed to edit config: {}", e));
            }
        }
        true
    }

    pub fn handle_settings_key(
        &mut self,
        key: KeyCode,
        terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
        event_handler: &EventHandler,
    ) -> bool {
        match key {
            KeyCode::Enter if self.focus.settings_focus == SettingsFocus::Configuration => {
                self.open_config_editor(terminal, event_handler)
            }
            KeyCode::Char('1')
            | KeyCode::Char('2')
            | KeyCode::Char('3')
            | KeyCode::Char('j')
            | KeyCode::Down
            | KeyCode::Char('k')
            | KeyCode::Up
            | KeyCode::Char('h')
            | KeyCode::Left
            | KeyCode::Char('l')
            | KeyCode::Right
            | KeyCode::Enter => self.handle_settings_key_nav(key),
            KeyCode::Char('e') => self.open_config_editor(terminal, event_handler),
            KeyCode::Char('x') => {
                let board_count = self.model.boards().len();
                if board_count == 0 {
                    self.set_error("No boards to export".to_string());
                    return false;
                }
                self.export_dialog = Some(ExportDialogState::new(board_count));
                self.push_mode(AppMode::Dialog(DialogMode::ExportBoards));
                false
            }
            KeyCode::Esc | KeyCode::Char('q') => {
                self.pop_mode();
                false
            }
            _ => false,
        }
    }

    pub fn handle_settings_key_nav(&mut self, key: KeyCode) -> bool {
        match key {
            KeyCode::Char('1') => {
                self.focus.settings_focus = SettingsFocus::Configuration;
                self.selection
                    .settings_config
                    .auto_select_first_if_empty(true);
            }
            KeyCode::Char('2') => {
                self.focus.settings_focus = SettingsFocus::ConfigFile;
                self.selection
                    .settings_config_file
                    .auto_select_first_if_empty(true);
            }
            KeyCode::Char('3') => {
                self.focus.settings_focus = SettingsFocus::Storage;
                self.selection
                    .settings_storage
                    .auto_select_first_if_empty(true);
            }
            KeyCode::Char('j') | KeyCode::Down => {
                self.handle_settings_nav_down();
            }
            KeyCode::Char('k') | KeyCode::Up => {
                self.handle_settings_nav_up();
            }
            KeyCode::Char('h') | KeyCode::Left => {
                if self.focus.settings_focus == SettingsFocus::Storage {
                    self.focus.settings_focus = SettingsFocus::Configuration;
                    self.selection
                        .settings_config
                        .auto_select_first_if_empty(true);
                }
            }
            KeyCode::Char('l') | KeyCode::Right => {
                if self.focus.settings_focus != SettingsFocus::Storage {
                    self.focus.settings_focus = SettingsFocus::Storage;
                    self.selection
                        .settings_storage
                        .auto_select_first_if_empty(true);
                }
            }
            KeyCode::Enter => {
                if self.focus.settings_focus == SettingsFocus::Storage
                    && self.selection.settings_storage.get() == Some(EXPORT_BUTTON_STORAGE_INDEX)
                {
                    return self.trigger_export();
                }
            }
            _ => {}
        }
        false
    }

    pub fn handle_settings_nav_down(&mut self) {
        match self.focus.settings_focus {
            SettingsFocus::Configuration => {
                let count = self.settings_item_count(SettingsFocus::Configuration);
                let current = self.selection.settings_config.get().unwrap_or(0);
                if self.cli_file_override && self.has_data_file {
                    match current {
                        c if c >= count - 1 => {
                            self.focus.settings_focus = SettingsFocus::ConfigFile;
                            self.selection.settings_config_file.set(Some(0));
                        }
                        4 => self.selection.settings_config.set(Some(7)),
                        _ => self.selection.settings_config.next(count),
                    }
                } else if current >= count - 1 {
                    self.focus.settings_focus = SettingsFocus::ConfigFile;
                    self.selection.settings_config_file.set(Some(0));
                } else {
                    self.selection.settings_config.next(count);
                }
            }
            SettingsFocus::ConfigFile => {
                let count = self.settings_item_count(SettingsFocus::ConfigFile);
                let current = self.selection.settings_config_file.get().unwrap_or(0);
                if current >= count - 1 {
                    self.focus.settings_focus = SettingsFocus::Configuration;
                    self.selection.settings_config.set(Some(0));
                } else {
                    self.selection.settings_config_file.next(count);
                }
            }
            SettingsFocus::Storage => {
                let count = self.settings_item_count(SettingsFocus::Storage);
                let current = self.selection.settings_storage.get().unwrap_or(0);
                if current >= count - 1 {
                    self.selection.settings_storage.set(Some(0));
                } else {
                    self.selection.settings_storage.next(count);
                }
            }
        }
    }

    fn handle_settings_nav_up(&mut self) {
        match self.focus.settings_focus {
            SettingsFocus::Configuration => {
                let current = self.selection.settings_config.get().unwrap_or(0);
                if current == 0 {
                    let count = self.settings_item_count(SettingsFocus::ConfigFile);
                    self.focus.settings_focus = SettingsFocus::ConfigFile;
                    self.selection.settings_config_file.set(Some(count - 1));
                } else if self.cli_file_override && self.has_data_file && current == 7 {
                    self.selection.settings_config.set(Some(4));
                } else {
                    self.selection.settings_config.prev();
                }
            }
            SettingsFocus::ConfigFile => {
                let current = self.selection.settings_config_file.get().unwrap_or(0);
                if current == 0 {
                    let count = self.settings_item_count(SettingsFocus::Configuration);
                    self.focus.settings_focus = SettingsFocus::Configuration;
                    self.selection.settings_config.set(Some(count - 1));
                } else {
                    self.selection.settings_config_file.prev();
                }
            }
            SettingsFocus::Storage => {
                let current = self.selection.settings_storage.get().unwrap_or(0);
                if current == 0 {
                    let count = self.settings_item_count(SettingsFocus::Storage);
                    self.selection.settings_storage.set(Some(count - 1));
                } else {
                    self.selection.settings_storage.prev();
                }
            }
        }
    }

    fn trigger_export(&mut self) -> bool {
        let board_count = self.model.boards().len();
        if board_count == 0 {
            self.set_error("No boards to export".to_string());
            return false;
        }
        self.export_dialog = Some(ExportDialogState::new(board_count));
        self.push_mode(AppMode::Dialog(DialogMode::ExportBoards));
        false
    }

    pub fn handle_export_boards_dialog(&mut self, key_code: KeyCode) {
        let Some(ref mut dialog) = self.export_dialog else {
            return;
        };

        match dialog.step {
            crate::app::ExportStep::SelectBoards => match key_code {
                KeyCode::Char(' ') => {
                    dialog.toggle(dialog.cursor);
                }
                KeyCode::Char('a') => {
                    dialog.select_all();
                }
                KeyCode::Char('j') | KeyCode::Down => {
                    let len = dialog.board_selections.len();
                    if len > 0 {
                        dialog.cursor = (dialog.cursor + 1) % len;
                    }
                }
                KeyCode::Char('k') | KeyCode::Up => {
                    let len = dialog.board_selections.len();
                    if len > 0 {
                        dialog.cursor = (dialog.cursor + len - 1) % len;
                    }
                }
                KeyCode::Enter => {
                    if dialog.any_selected() {
                        dialog.step = crate::app::ExportStep::ExportOptions;
                    }
                }
                KeyCode::Esc => {
                    self.export_dialog = None;
                    self.pop_mode();
                }
                _ => {}
            },
            crate::app::ExportStep::ExportOptions => match key_code {
                KeyCode::Tab | KeyCode::BackTab => {
                    dialog.format = match dialog.format {
                        crate::app::ExportFormat::Json => crate::app::ExportFormat::Sqlite,
                        crate::app::ExportFormat::Sqlite => crate::app::ExportFormat::Json,
                    };
                    let stem = dialog
                        .filename
                        .rsplit_once('.')
                        .map(|(s, _)| s)
                        .unwrap_or(&dialog.filename)
                        .to_string();
                    dialog.filename = match dialog.format {
                        crate::app::ExportFormat::Json => format!("{}.json", stem),
                        crate::app::ExportFormat::Sqlite => format!("{}.sqlite", stem),
                    };
                }
                KeyCode::Backspace => {
                    dialog.filename.pop();
                }
                KeyCode::Char(c)
                    if !matches!(
                        c,
                        '/' | '\\' | '\0' | ':' | '*' | '?' | '"' | '<' | '>' | '|'
                    ) =>
                {
                    dialog.filename.push(c);
                }
                KeyCode::Enter => {
                    self.execute_export();
                }
                KeyCode::Esc => {
                    dialog.step = crate::app::ExportStep::SelectBoards;
                }
                _ => {}
            },
        }
    }

    fn execute_export(&mut self) {
        let Some(ref dialog) = self.export_dialog else {
            return;
        };

        let filename = dialog.filename.clone();
        let selected_indices: Vec<usize> = dialog
            .board_selections
            .iter()
            .enumerate()
            .filter(|(_, &selected)| selected)
            .map(|(i, _)| i)
            .collect();

        if selected_indices.is_empty() || filename.is_empty() {
            self.set_error("No boards selected or filename empty".to_string());
            return;
        }

        let boards = self.model.boards();
        let columns = self.model.columns();
        let cards = self.model.cards();
        let archived = self.model.archived_cards();
        let sprints = self.model.sprints();
        let board_exports: Vec<_> = selected_indices
            .iter()
            .filter_map(|&i| boards.get(i))
            .map(|board| BoardExporter::export_board(board, columns, cards, archived, sprints))
            .collect();

        let export = AllBoardsExport::from_boards(board_exports);

        match dialog.format {
            crate::app::ExportFormat::Json => {
                match BoardExporter::export_to_file(&export, &filename) {
                    Ok(()) => self.set_success(format!("Exported to {}", filename)),
                    Err(e) => self.set_error(format!("Export failed: {}", e)),
                }
            }
            crate::app::ExportFormat::Sqlite => {
                let filename_clone = filename.clone();
                let export_clone = export.clone();
                let store_manager = self.store_manager.clone();
                let (tx, rx) = tokio::sync::oneshot::channel();
                tokio::spawn(async move {
                    let result = store_manager
                        .export_to_sqlite(export_clone, &filename_clone)
                        .await
                        .map(|_| filename_clone)
                        .map_err(|e| format!("Export failed: {}", e));
                    let _ = tx.send(result);
                });
                self.export_result_rx = Some(rx);
                self.set_success("Exporting...".to_string());
            }
        }

        self.export_dialog = None;
        self.pop_mode();
    }
}