knotra 0.19.0

knotra: multi-project VCS dashboard and bulk-operation tool
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
#![allow(unused_imports)]
//! Dashboard view: card grid with filter chips, grouping, and add-project dialog.

use knotra_vcs::model::{project::Project, status::ProjectStatus};
use iced::{
    widget::{button, column, container, row, scrollable, text, text_input, Space},
    Alignment, Element, Length, Padding,
};
use knotra_ui::{theme::StatusColor, widget::CARD_GAP};

use crate::{
    message::{
        DetailPanelMessage, FilterMessage, Message, ProjectMessage,
        SelectionMessage, StatusFilter, SyncMessage, TierMessage, WorkspaceMessage,
    },
    state::{
        AttentionTier, GroupingMode,
        dashboard::{build_display_groups, project_status_color},
        tier::compute_tier,
        AppState, LoadPhase,
    },
};

// ---------------------------------------------------------------------------
// Top-level
// ---------------------------------------------------------------------------

pub fn view(state: &AppState) -> Element<'_, Message> {
    let header  = view_header(state);
    let toolbar = view_toolbar(state);

    let body: Element<'_, Message> = match &state.load_phase {
        LoadPhase::Startup     => placeholder(state.t("status.refreshing")),
        LoadPhase::Refreshing  => {
            // Show stale cards (if any) with a "refreshing" notice overlaid.
            if state.workspace_status.is_some() {
                column![
                    text(state.t("dashboard.refreshing_count")).size(12),
                    view_card_grid(state),
                ]
                .spacing(4)
                .into()
            } else {
                placeholder(state.t("status.refreshing"))
            }
        }
        LoadPhase::Error(_)    => view_error(state),
        LoadPhase::Ready       => {
            if state.grouping_mode == GroupingMode::Auto {
                view_tier_grid(state)
            } else {
                view_card_grid(state)
            }
        }
    };

    // Layer dialogs on top when open.
    let mut root = column![header, toolbar, scrollable(body).height(Length::Fill)]
        .height(Length::Fill);

    // Persistent status bar.
    if let Some(ref msg) = state.status_bar {
        root = root.push(
            container(text(msg.as_str()).size(12))
                .width(Length::Fill)
                .padding([2, 8]),
        );
    }

    // add_project_dialog is now rendered as a centered stack overlay in view/mod.rs.

    if state.confirm_remove_dialog.is_some() {
        return column![root, view_confirm_remove_dialog(state)]
            .height(Length::Fill)
            .into();
    }

    root.into()
}

// ---------------------------------------------------------------------------
// Header
// ---------------------------------------------------------------------------

fn view_header(state: &AppState) -> Element<'_, Message> {
    let workspace_name = state
        .workspace
        .as_ref()
        .map(|ws| ws.name.as_str())
        .unwrap_or("—");

    // Minimal header: workspace name + refresh indicator.
    // Add project / bulk sync are accessible via ⌘K or the selection bar.
    let right: Element<'_, Message> = if state.is_refreshing {
        text("⟳").size(14).into()
    } else {
        button(text("⟳").size(14))
            .on_press(Message::Workspace(WorkspaceMessage::RefreshRequested))
            .into()
    };

    row![
        text(workspace_name).size(18),
        Space::new().width(Length::Fill),
        right,
    ]
    .align_y(Alignment::Center)
    .padding([8, 14])
    .into()
}


fn view_toolbar(state: &AppState) -> Element<'_, Message> {
    // Filter chips row.
    let chips = view_filter_chips(state);

    // Clear-all button (only shown when a filter is active).
    let clear_btn: Option<Element<'_, Message>> = if state.filter.is_active() {
        Some(
            button(text("✕ Clear"))
                .on_press(Message::Filter(FilterMessage::AllFiltersCleared))
                .into(),
        )
    } else {
        None
    };

    // Search box.
    let search = text_input(
        state.t("dashboard.search_placeholder"),
        &state.filter.search_text,
    )
    .on_input(|s| Message::Filter(FilterMessage::SearchChanged(s)))
    .width(200);

    // Group selector placeholder (full picker in Phase 6).
    let group_btn = button(text(state.t("dashboard.group_by")));

    let mut toolbar_row = row![chips].spacing(6).align_y(Alignment::Center);
    if let Some(btn) = clear_btn {
        toolbar_row = toolbar_row.push(btn);
    }
    toolbar_row = toolbar_row
        .push(Space::new().width(Length::Fill))
        .push(group_btn)
        .push(search);

    container(toolbar_row)
        .width(Length::Fill)
        .padding(Padding { top: 0.0, bottom: 8.0, left: 12.0, right: 12.0 })
        .into()
}

fn view_filter_chips(state: &AppState) -> Element<'_, Message> {
    let filters: &[(StatusFilter, &'static str)] = &[
        (StatusFilter::Healthy,  "filter.healthy"),
        (StatusFilter::Behind,   "filter.behind"),
        (StatusFilter::Ahead,    "filter.ahead"),
        (StatusFilter::Dirty,    "filter.dirty"),
        (StatusFilter::Conflict, "filter.conflict"),
        (StatusFilter::Error,    "filter.error"),
    ];

    let mut chips: Vec<Element<'_, Message>> = Vec::new();

    for (sf, key) in filters {
        let active = state.filter.has_status_filter(sf);
        let label = format!("{}{}", state.t(key), if active { " ✓" } else { "" });
        let btn = button(text(label).size(12))
            .on_press(Message::Filter(FilterMessage::StatusFilterToggled(sf.clone())));
        chips.push(btn.into());
    }

    row(chips).spacing(4).into()
}

// ---------------------------------------------------------------------------
// Card grid with grouping
// ---------------------------------------------------------------------------


// ---------------------------------------------------------------------------
// Tier-based card grid (RFC-0010)
// ---------------------------------------------------------------------------

fn view_tier_grid(state: &AppState) -> Element<'_, Message> {
    use iced::widget::{button, column, container, row, text};
    use iced::Length;
    use knotra_ui::widget::CARD_GAP;

    let projects = state.workspace.as_ref()
        .map(|w| w.projects.as_slice()).unwrap_or(&[]);
    let wss = state.workspace_status.as_ref();

    // Classify all projects into tiers.
    let mut needs_att: Vec<_> = Vec::new();
    let mut active:    Vec<_> = Vec::new();
    let mut clean:     Vec<_> = Vec::new();

    for p in projects {
        let status   = wss.and_then(|w| w.projects.iter().find(|ps| ps.project_id == p.id));
        let missing  = state.missing_projects.contains(&p.id);
        let (tier, cause) = compute_tier(status, !missing);
        match tier {
            AttentionTier::NeedsAttention => needs_att.push((p, status, cause)),
            AttentionTier::Active         => active.push((p, status, cause)),
            AttentionTier::Clean          => clean.push((p, status, cause)),
        }
    }

    let mut page: Vec<Element<'_, Message>> = Vec::new();

    // Helper: render a collapsible tier section.
    macro_rules! tier_section {
        ($entries:expr, $label:expr, $icon:expr, $tier:expr, $collapsed:expr) => {{
            if !$entries.is_empty() {
                let toggle_btn = button(
                    text(format!("{} {} ({})  {}",
                        $icon, $label, $entries.len(),
                        if $collapsed { "▶" } else { "▼" }
                    )).size(13)
                )
                .on_press(Message::Tier(TierMessage::Toggled($tier)));
                page.push(
                    container(toggle_btn)
                        .width(Length::Fill)
                        .padding([4, 0])
                        .into()
                );
                if !$collapsed {
                    for (proj, status, _cause) in &$entries {
                        page.push(view_project_card(state, proj, *status));
                    }
                }
            }
        }};
    }

    tier_section!(needs_att, state.t("tier.needs_attention"), "🔴",
        AttentionTier::NeedsAttention, state.tier_collapse.needs_attention);
    tier_section!(active, state.t("tier.active"), "🟡",
        AttentionTier::Active, state.tier_collapse.active);
    tier_section!(clean, state.t("tier.clean"), "⚪",
        AttentionTier::Clean, state.tier_collapse.clean);

    if page.is_empty() {
        return placeholder("No projects match the current filter.");
    }
    column(page).spacing(CARD_GAP).padding(12).into()
}

fn view_card_grid(state: &AppState) -> Element<'_, Message> {
    let projects = state
        .workspace
        .as_ref()
        .map(|w| w.projects.as_slice())
        .unwrap_or(&[]);

    if projects.is_empty() {
        // Empty state — clear call to action, no clutter.
        return container(
            column![
                text(state.t("dashboard.no_projects")).size(16),
                text(state.t("dashboard.no_projects_hint")).size(13),
                button(text(state.t("dashboard.add_project")).size(14))
                    .on_press(Message::Workspace(WorkspaceMessage::AddProjectDialogOpened))
                    .padding([10, 20]),
            ]
            .spacing(16)
            .align_x(iced::Alignment::Center)
        )
        .width(iced::Length::Fill)
        .height(iced::Length::Fill)
        .center(iced::Length::Fill)
        .into();
    }

    let groups = build_display_groups(
        projects,
        state.workspace_status.as_ref(),
        &state.filter,
    );

    if groups.iter().all(|g| g.entries.is_empty()) {
        return placeholder("No projects match the current filter.");
    }

    const COLS: usize = 4;
    let mut page: Vec<Element<'_, Message>> = Vec::new();

    for group in &groups {
        // Group header (skip for the lone-ungrouped case when no named groups).
        if let Some(name) = group.name {
            page.push(
                container(text(name).size(13))
                    .width(Length::Fill)
                    .padding([4, 0])
                    .into(),
            );
        }

        // Card rows.
        let mut current_row: Vec<Element<'_, Message>> = Vec::new();
        for entry in &group.entries {
            current_row.push(view_project_card(state, entry.project, entry.status));
            if current_row.len() == COLS {
                let r: Vec<Element<'_, Message>> = std::mem::take(&mut current_row);
                page.push(row(r).spacing(CARD_GAP).into());
            }
        }
        if !current_row.is_empty() {
            page.push(row(current_row).spacing(CARD_GAP).into());
        }
    }

    column(page).spacing(CARD_GAP).padding(12).into()
}

// ---------------------------------------------------------------------------
// Project card
// ---------------------------------------------------------------------------

fn view_project_card<'a>(
    state: &'a AppState,
    project: &'a Project,
    status: Option<&'a ProjectStatus>,
) -> Element<'a, Message> {
    let vcs_label = status
        .map(|s| s.identity.vcs_kind.to_string())
        .unwrap_or_else(|| "—".to_owned());

    let context_label = status
        .and_then(|s| s.context.as_ref())
        .map(|c| c.label.clone())
        .unwrap_or_else(|| "—".to_owned());

    let status_color = status.map(project_status_color).unwrap_or(StatusColor::Unknown);
    let status_label = status_color_label(state, status_color);

    let ahead       = status.map(|s| s.remote.ahead).unwrap_or(0);
    let behind      = status.map(|s| s.remote.behind).unwrap_or(0);
    let uncommitted = status.map(|s| s.working_tree.uncommitted_count).unwrap_or(0);
    let untracked   = status.map(|s| s.working_tree.untracked_count).unwrap_or(0);
    let updated     = status
        .map(|s| s.refreshed_at.format("%H:%M:%S").to_string())
        .unwrap_or_else(|| "—".to_owned());

    let is_fetching = state.fetching_projects.contains(&project.id);

    // Header row: checkbox | name  |  VCS badge
    let is_selected = state.selection.contains(&project.id);
    let checkbox_label = if is_selected { "☑" } else { "☐" };
    let select_btn = button(text(checkbox_label).size(13))
        .on_press(Message::Selection(SelectionMessage::Toggled(project.id.clone())));

    // Clicking the name opens the detail panel (RFC-0014)
    let name_btn = button(text(project.name.clone()).size(14))
        .on_press(Message::DetailPanel(DetailPanelMessage::Opened(project.id.clone())));

    let header_row = row![
        select_btn,
        name_btn,
        Space::new().width(Length::Fill),
        text(vcs_label).size(11),
    ]
    .align_y(Alignment::Center);

    // Status badge + context
    let status_row = row![
        text(status_label).size(12),
        text("  ").size(12),
        text(context_label).size(12),
    ]
    .align_y(Alignment::Center);

    // Stat cells
    let stats_row = row![
        stat_cell("↑", state.t("card.ahead"),       ahead),
        stat_cell("↓", state.t("card.behind"),      behind),
        stat_cell("●", state.t("card.uncommitted"),  uncommitted),
        stat_cell("?", state.t("card.untracked"),    untracked),
    ]
    .spacing(10);

    // Action buttons
    let fetch_label = if is_fetching { "Fetching…" } else { state.t("card.action.fetch") };
    let fetch_btn = button(text(fetch_label).size(11))
        .on_press_maybe(
            if is_fetching { None }
            else { Some(Message::Project(ProjectMessage::FetchRequested(project.id.clone()))) }
        );

    let remove_btn = button(text(state.t("card.action.remove")).size(11))
        .on_press(Message::Workspace(WorkspaceMessage::RemoveProjectRequested(project.id.clone())));

    let actions_row = row![fetch_btn, remove_btn]
        .spacing(4)
        .align_y(Alignment::Center);

    // Error row
    let mut card_col = column![
        header_row,
        status_row,
        stats_row,
        text(format!("{} {}", state.t("card.updated"), updated)).size(10),
        actions_row,
    ]
    .spacing(5)
    .padding([12, 14]);

    if let Some(err) = status.and_then(|s| s.read_error.as_ref()) {
        card_col = card_col.push(text(format!("⚠ {}", err)).size(11));
    }

    // Missing-path warning (repo directory not found).
    if state.missing_projects.contains(&project.id) {
        card_col = card_col.push(text("✗ Repository path not found").size(11));
    }

    container(card_col).width(Length::FillPortion(1)).into()
}

fn stat_cell<'a>(icon: &'a str, label: &'a str, value: u32) -> Element<'a, Message> {
    column![
        row![text(icon).size(11), text(value.to_string()).size(14)]
            .spacing(2)
            .align_y(Alignment::Center),
        text(label).size(9),
    ]
    .align_x(Alignment::Center)
    .into()
}

fn status_color_label(state: &AppState, color: StatusColor) -> &'static str {
    // First-level wording uses plain language (UX review). The technical terms
    // (Synced / Behind / Ahead / Uncommitted / Conflict) remain available in
    // the project detail panel and operation history under "Show details".
    match color {
        StatusColor::Healthy  => state.t("plain.status.all_set"),
        StatusColor::Behind   => state.t("plain.status.behind"),
        StatusColor::Ahead    => state.t("plain.status.ahead"),
        StatusColor::Dirty    => state.t("plain.status.unsaved_work"),
        StatusColor::Conflict => state.t("plain.status.needs_choice"),
        StatusColor::Unknown  => state.t("plain.status.not_sure"),
    }
}

// ---------------------------------------------------------------------------
// Add-project dialog
// ---------------------------------------------------------------------------


// ---------------------------------------------------------------------------
// Confirm-remove dialog
// ---------------------------------------------------------------------------

fn view_confirm_remove_dialog(state: &AppState) -> Element<'_, Message> {
    let dialog = match &state.confirm_remove_dialog {
        Some(d) => d,
        None    => return Space::new().into(),
    };

    let id = dialog.project_id.clone();
    let _id2 = id.clone();

    container(
        column![
            text(state.t("confirm.remove_project")).size(15),
            text(dialog.project_name.as_str()).size(14),
            row![
                button(text(state.t("confirm.remove_yes")))
                    .on_press(Message::Workspace(WorkspaceMessage::RemoveProjectConfirmed(id))),
                button(text(state.t("confirm.remove_no")))
                    .on_press(Message::Workspace(WorkspaceMessage::RemoveProjectCancelled)),
            ]
            .spacing(8),
        ]
        .spacing(12)
        .padding(24),
    )
    .width(360)
    .into()
}

// ---------------------------------------------------------------------------
// Error + placeholder
// ---------------------------------------------------------------------------

fn view_error(state: &AppState) -> Element<'_, Message> {
    let msg = match &state.load_phase {
        LoadPhase::Error(m) => m.as_str(),
        _ => "",
    };
    column![
        text(state.t("error.read_failed")).size(16),
        text(msg).size(13),
        button(text(state.t("dashboard.refresh")))
            .on_press(Message::Workspace(WorkspaceMessage::RefreshRequested)),
    ]
    .spacing(8)
    .padding(24)
    .into()
}

fn placeholder(msg: &str) -> Element<'_, Message> {
    container(text(msg).size(14))
        .width(Length::Fill)
        .height(250)
        .center_x(Length::Fill)
        .center_y(250)
        .into()
}
#[allow(dead_code)]
fn card_needs_attention<'a>(
    state: &'a AppState,
    project: &'a knotra_vcs::Project,
    status: Option<&'a knotra_vcs::ProjectStatus>,
    cause: Option<crate::state::tier::AttentionCause>,
) -> Element<'a, Message> {
    use crate::state::tier::AttentionCause;

    // One-line problem description — no technical jargon.
    let problem = match &cause {
        Some(AttentionCause::PathNotFound)                 => "folder not found".to_owned(),
        Some(AttentionCause::Conflict)                     => "merge conflict".to_owned(),
        Some(AttentionCause::ConflictDetectionUnavailable) => "conflict status unknown".to_owned(),
        Some(AttentionCause::DetachedHead)                 => "detached HEAD".to_owned(),
        Some(AttentionCause::OperationFailed)              => "last operation failed".to_owned(),
        Some(AttentionCause::DirtyForLong)                 => "uncommitted for a long time".to_owned(),
        None => status.and_then(|s| s.read_error.as_deref())
                      .map(|e| e.to_owned())
                      .unwrap_or_else(|| "needs attention".to_owned()),
    };

    // One focused action button.
    let action: Element<'_, Message> = match &cause {
        Some(AttentionCause::Conflict) => {
            button(text("Resolve").size(12))
                .on_press(Message::ConflictOps(
                    crate::message::ConflictOpsMessage::OpenRequested(Some(project.id.clone()))
                ))
                .into()
        }
        Some(AttentionCause::PathNotFound) => {
            button(text("Remove").size(12))
                .on_press(Message::Workspace(
                    crate::message::WorkspaceMessage::RemoveProjectRequested(project.id.clone())
                ))
                .into()
        }
        _ => {
            button(text("Refresh").size(12))
                .on_press(Message::Project(
                    crate::message::ProjectMessage::StatusRefreshRequested(project.id.clone())
                ))
                .into()
        }
    };

    let name_btn = button(text(project.name.as_str()).size(13))
        .on_press(Message::DetailPanel(crate::message::DetailPanelMessage::Opened(project.id.clone())));

    let inner = row![
        name_btn,
        text("  —  ").size(12),
        text(problem).size(12),
        Space::new().width(Length::Fill),
        action,
    ]
    .align_y(iced::Alignment::Center)
    .padding([8, 12]);

    // Selection mode: show checkbox on the left
    let inner: Element<'_, Message> = if state.selection_mode {
        let is_sel = state.selection.contains(&project.id);
        let cb = button(text(if is_sel { "☑" } else { "☐" }).size(12))
            .on_press(Message::Selection(crate::message::SelectionMessage::Toggled(project.id.clone())));
        row![cb, inner].align_y(iced::Alignment::Center).into()
    } else {
        inner.into()
    };

    container(inner).width(iced::Length::Fill).into()
}

// ---------------------------------------------------------------------------
// Active card: name  branch
// ---------------------------------------------------------------------------

#[allow(dead_code)]
fn card_active<'a>(
    state: &'a AppState,
    project: &'a knotra_vcs::Project,
    status: Option<&'a knotra_vcs::ProjectStatus>,
) -> Element<'a, Message> {
    let branch = status
        .and_then(|s| s.context.as_ref())
        .map(|ctx| ctx.label.as_str())
        .unwrap_or("");

    let name_btn = button(text(project.name.as_str()).size(13))
        .on_press(Message::DetailPanel(crate::message::DetailPanelMessage::Opened(project.id.clone())));

    let inner = row![
        name_btn,
        text(branch).size(11),
    ]
    .spacing(8)
    .align_y(iced::Alignment::Center)
    .padding([6, 12]);

    let inner: Element<'_, Message> = if state.selection_mode {
        let is_sel = state.selection.contains(&project.id);
        let cb = button(text(if is_sel { "☑" } else { "☐" }).size(12))
            .on_press(Message::Selection(crate::message::SelectionMessage::Toggled(project.id.clone())));
        row![cb, inner].align_y(iced::Alignment::Center).into()
    } else {
        inner.into()
    };

    iced::widget::container(inner).width(iced::Length::Fill).into()
}

// ---------------------------------------------------------------------------
// Clean card: name only (single line, subdued)
// ---------------------------------------------------------------------------

#[allow(dead_code)]
fn card_clean<'a>(
    state: &'a AppState,
    project: &'a knotra_vcs::Project,
) -> Element<'a, Message> {
    let name_btn = button(text(project.name.as_str()).size(13))
        .on_press(Message::DetailPanel(crate::message::DetailPanelMessage::Opened(project.id.clone())));

    let inner: Element<'_, Message> = if state.selection_mode {
        let is_sel = state.selection.contains(&project.id);
        let cb = button(text(if is_sel { "☑" } else { "☐" }).size(12))
            .on_press(Message::Selection(crate::message::SelectionMessage::Toggled(project.id.clone())));
        row![cb, name_btn].align_y(iced::Alignment::Center).padding([4, 12]).into()
    } else {
        iced::widget::container(name_btn.padding([4, 12])).width(iced::Length::Fill).into()
    };

    inner
}