knotra 0.34.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
// RFC-052 A1: `unused_imports`/`unused_variables` masked nothing in any
// target and are gone. `dead_code` is narrowed to the test build only —
// `view()` and `field_row` (only reachable from inside it) are called from
// `view.rs` in the real binary, but no `#[test]` in this crate calls into
// the render tree, so the test compilation's call graph never reaches them
// and flags both as dead. The binary build carries no suppression at all.
#![cfg_attr(test, allow(dead_code))]
//! RFC-0014 — Project detail side panel.
//!
//! Opens as a right-docked panel when the user clicks a project name.
//! Showing all status fields, recent operations, and available actions.
//!
//! RFC-048: every user-facing string here now routes through `state.t()`
//! under the `detail.*` prefix — the panel made zero `t()` calls before
//! this and was entirely English for every Japanese user. `detail.*` is
//! deliberately not a first-level prefix (RFC-048 D1): this is the expert
//! surface RFC-021's plain-language layer defers *to*, so `Branch`,
//! `Fetch`, `Conflict` etc. are translated, not re-worded.

use iced::{
    Alignment, Element, Length,
    widget::{Space, button, column, container, row, scrollable, text},
};

use knotra_ui::widget::{
    BUTTON_HEIGHT, Tokens, body_badge_diameter, centered_button_label, centered_button_row, icon,
    list, record_row, status_badge, strong, style,
};

use crate::{
    message::{DetailPanelMessage, Message, ProjectMessage, WorkspaceMessage},
    state::{AppState, dashboard::badge_for_operation_outcome, detail_panel::RecentCommitsPhase},
};

/// RFC-071 Amendment A2 commit 2: the label sits on its own line, the value
/// directly below it — replaces RFC-048 D3's two-column layout, whose fixed
/// `label_width` was always a guessed fit for one language at one font
/// size (Review 248 §4: at 14 px, "Remote:"/"Untracked:" already exceeded
/// their own guessed widths). A stacked layout needs nothing measured: no
/// font, language or zoom level can make a label not fit its own line, and
/// a long value (a path) wraps under its label instead of colliding with
/// it. The label stays `body_small`, now in `text_secondary` so it reads as
/// a caption rather than competing with its own value; the value keeps its
/// role unchanged.
///
/// RFC-071 Amendment A6 §2, correcting Amendment A3 D14's first pass: the
/// label stays `body_small` (a caption, in `text_secondary`), but the
/// value moves to `body` — the path, the branch, the VCS kind, the
/// counts are the content this panel exists to show, not incidental
/// metadata beside something else. D14's KEEP list names "the VCS kind,
/// the branch beside a name, counts inside metadata" for a value sitting
/// *beside* a name (a dashboard row's own sub-line); here the value is
/// the panel's entire content for that field, not a qualifier next to
/// anything else.
fn field_row<'a>(
    tokens: &Tokens,
    label: &'a str,
    value: impl std::fmt::Display,
) -> Element<'a, Message> {
    column![
        text(label)
            .size(snora::design::style::text::body_small_size(tokens))
            .line_height(snora::design::style::text::body_small_line_height(tokens))
            .color(snora::design::style::color::to_iced_color(
                tokens.palette.text_secondary
            )),
        text(value.to_string())
            .size(snora::design::style::text::body_size(tokens))
            .line_height(snora::design::style::text::body_line_height(tokens)),
    ]
    .spacing(1)
    .into()
}

pub fn view<'a>(state: &'a AppState) -> Option<Element<'a, Message>> {
    let tokens = &state.theme.tokens;
    let id = state.detail_panel.open_project_id.as_ref()?;

    let project = state
        .workspace
        .as_ref()
        .and_then(|ws| ws.projects.iter().find(|p| &p.id == id))?;

    let status = state
        .workspace_status
        .as_ref()
        .and_then(|ws| ws.projects.iter().find(|ps| &ps.project_id == id));

    // --- Header ---
    // Review 249 §2: the close control is not the panel's main action — it
    // takes `overlay::surface`'s own close button whole (the lucide `X`
    // icon, `ghost` style, plus a focus ring that never lights, since this
    // panel has no focus-order wiring), not only its colour.
    // RFC-073 D8: `BUTTON_HEIGHT`, matching `overlay::surface`'s own close
    // button, whose shape this takes whole.
    let close_btn = button(centered_button_row(row![
        icon::icon_element(&icon::close())
    ]))
    .height(Length::Fixed(BUTTON_HEIGHT))
    .width(Length::Fixed(BUTTON_HEIGHT))
    .on_press(Message::DetailPanel(DetailPanelMessage::Closed))
    .style({
        let t = tokens.clone();
        move |_theme, status| style::with_focus_ring(&t, false, style::ghost(&t, status))
    });

    let header = row![
        text(project.name.clone())
            .size(snora::design::style::text::body_size(tokens))
            .line_height(snora::design::style::text::body_line_height(tokens)),
        Space::new().width(Length::Fill),
        close_btn,
    ]
    .align_y(Alignment::Center);

    // --- Identity section ---
    let vcs = status
        .map(|s| s.identity.vcs_kind.to_string())
        .unwrap_or_else(|| "—".into());
    let path = project.path.clone();
    let remote = status
        .and_then(|s| s.remote.upstream.clone())
        .unwrap_or_else(|| "—".into());

    let identity = column![
        // RFC-071 Amendment A3 D14: a section header is dialog-body
        // structure the user reads to orient themselves — `body`.
        // Amendment A5 §4: `strong` (Bold), the same weight every other
        // section heading in this app already uses.
        strong(
            text(state.t("detail.section_identity"))
                .size(snora::design::style::text::body_size(tokens))
                .line_height(snora::design::style::text::body_line_height(tokens)),
        ),
        field_row(tokens, state.t("detail.label_vcs"), vcs),
        field_row(tokens, state.t("detail.label_path"), path),
        field_row(tokens, state.t("detail.label_remote"), remote),
    ]
    .spacing(3);

    // --- Status section ---
    let status_col = if let Some(s) = status {
        let branch = s.context.as_ref().map(|c| c.label.as_str()).unwrap_or("—");
        let ahead = s.remote.ahead;
        let behind = s.remote.behind;
        let dirty = s.working_tree.uncommitted_count;
        let untracked = s.working_tree.untracked_count;
        let conflict = if s.conflict.has_conflict {
            state.t("detail.conflict_yes")
        } else if s.conflict.detection_unavailable {
            state.t("detail.conflict_unknown")
        } else {
            state.t("detail.conflict_no")
        };

        column![
            strong(
                text(state.t("detail.section_status"))
                    .size(snora::design::style::text::body_size(tokens))
                    .line_height(snora::design::style::text::body_line_height(tokens)),
            ),
            field_row(tokens, state.t("detail.label_branch"), branch),
            field_row(tokens, state.t("detail.label_ahead"), ahead),
            field_row(tokens, state.t("detail.label_behind"), behind),
            field_row(tokens, state.t("detail.label_dirty"), dirty),
            field_row(tokens, state.t("detail.label_untracked"), untracked),
            field_row(tokens, state.t("detail.label_conflict"), conflict),
        ]
        .spacing(3)
    } else {
        column![
            strong(
                text(state.t("detail.section_status"))
                    .size(snora::design::style::text::body_size(tokens))
                    .line_height(snora::design::style::text::body_line_height(tokens)),
            ),
            // RFC-071 Amendment A3 D14: a status message — `body`.
            text(state.t("detail.loading"))
                .size(snora::design::style::text::body_size(tokens))
                .line_height(snora::design::style::text::body_line_height(tokens))
        ]
    };

    // --- Recent operations section (last 5 involving this project) ---
    let recent_ops: Vec<Element<'_, Message>> = state
        .operation_logs
        .iter()
        .rev()
        .filter(|log| log.result.per_project.iter().any(|pp| &pp.project_id == id))
        .take(5)
        .map(|log| {
            // RFC-073 handoff Amendment A3 §1: `badge_for_operation_outcome`,
            // the same exhaustive mapping History's own per-project rows
            // use — not a screen-specific "✓"/"✗" glyph.
            let outcome = log
                .result
                .per_project
                .iter()
                .find(|pp| &pp.project_id == id)
                .map(|pp| pp.effective_outcome())
                .unwrap_or(knotra_vcs::model::operation::ProjectOperationOutcome::Failed);
            let (tone, glyph) = badge_for_operation_outcome(outcome);
            // RFC-048 §2: `operation_kind_label` (`view.rs`), not
            // `log.result.kind`'s raw English `Display` — the fourth
            // consumer, after `activity_strip.rs` and `history.rs`'s two.
            // RFC-071 Amendment A3 D14: list content (a recent-operation
            // entry) — `body`, the same role History gives its own entry
            // titles.
            //
            // Amendment A5 §6: `[7, 8]`, the same vertical padding every
            // other list row in this app wraps itself in
            // (`dashboard/row.rs`'s own project row) — this row had none
            // at all, so a wrapped time ran up against the next row's own
            // rule line (`widget::list`'s own doc comment: the separator
            // sits directly between adjacent items, with no padding of
            // its own — a row's padding is its own call site's concern).
            // `align_y::Start`, not `Center`: the badge sits beside the
            // text's *first* line, not the vertical centre of however
            // many lines the kind-and-time string wraps to.
            container(
                row![
                    status_badge(tokens, tone, &glyph, body_badge_diameter(tokens)),
                    text(format!(
                        "{} — {}",
                        super::operation_kind_label(state, &log.result.kind),
                        log.result.started_at.strftime("%m/%d %H:%M")
                    ))
                    .size(snora::design::style::text::body_size(tokens))
                    .line_height(snora::design::style::text::body_line_height(tokens)),
                ]
                .spacing(6)
                .align_y(Alignment::Start),
            )
            .padding([7, 8])
            .into()
        })
        .collect();

    // RFC-071 D8a: the section header sits outside `list(...)` — the same
    // "header never gets its own separator line" rule the dashboard's
    // section header and History's entries follow.
    let recent = column![
        // RFC-071 Amendment A3 D14: section header — `body`.
        strong(
            text(state.t("detail.section_recent_operations"))
                .size(snora::design::style::text::body_size(tokens))
                .line_height(snora::design::style::text::body_line_height(tokens)),
        ),
        list(
            tokens,
            if recent_ops.is_empty() {
                vec![
                    // RFC-071 Amendment A3 D14: a status message — `body`.
                    text(state.t("detail.none"))
                        .size(snora::design::style::text::body_size(tokens))
                        .line_height(snora::design::style::text::body_line_height(tokens))
                        .into(),
                ]
            } else {
                recent_ops
            },
        ),
    ]
    .spacing(3);

    // --- Recent commits section (RFC-039 D3/D5) ---
    // Three states, three sentences (D5/R5) — none of them an empty section
    // (RFC-044 D3). The VCS layer's `error` string is shown, not discarded
    // (§5's explicit anti-pattern: `ProjectConflictDetail.note`, deleted
    // unread by RFC-045).
    let commits_body: Vec<Element<'_, Message>> = match &state.detail_panel.commits_phase {
        RecentCommitsPhase::Loading(loading_id) if loading_id == id => {
            // RFC-071 Amendment A3 D14: a status message — `body`.
            vec![
                text(state.t("detail.commits_loading"))
                    .size(snora::design::style::text::body_size(tokens))
                    .line_height(snora::design::style::text::body_line_height(tokens))
                    .into(),
            ]
        }
        RecentCommitsPhase::Loaded {
            project_id,
            commits,
        } if project_id == id => {
            if let Some(err) = &commits.error {
                // RFC-071 Amendment A3 D14: an error message — `body`.
                vec![
                    text(format!("{} {}", state.t("detail.commits_error"), err))
                        .size(snora::design::style::text::body_size(tokens))
                        .line_height(snora::design::style::text::body_line_height(tokens))
                        .into(),
                ]
            } else if commits.entries.is_empty() {
                // RFC-071 Amendment A3 D14: a status message — `body`.
                vec![
                    text(state.t("detail.commits_empty"))
                        .size(snora::design::style::text::body_size(tokens))
                        .line_height(snora::design::style::text::body_line_height(tokens))
                        .into(),
                ]
            } else {
                commits
                    .entries
                    .iter()
                    .map(|entry| {
                        let short_hash = &entry.hash[..entry.hash.len().min(7)];
                        // RFC-071 Amendment A3 D14: list content (a commit's
                        // own subject) — `body`.
                        let summary = text(format!("{short_hash}  {}", entry.subject))
                            .size(snora::design::style::text::body_size(tokens))
                            .line_height(snora::design::style::text::body_line_height(tokens));
                        // RFC-071 Amendment A3 D14: kept `body_small` —
                        // author and date are metadata beside the commit,
                        // the same role as a project's VCS kind beside its
                        // name.
                        let detail = text(format!(
                            "{} — {}",
                            entry.author,
                            entry.date.strftime("%Y-%m-%d %H:%M")
                        ))
                        .size(snora::design::style::text::body_small_size(tokens))
                        .line_height(snora::design::style::text::body_small_line_height(tokens));
                        record_row(summary.into(), Some(detail.into()))
                    })
                    .collect()
            }
        }
        // RFC-071 Amendment A3 D14: a status message — `body`.
        _ => vec![
            text(state.t("detail.commits_loading"))
                .size(snora::design::style::text::body_size(tokens))
                .line_height(snora::design::style::text::body_line_height(tokens))
                .into(),
        ],
    };

    // RFC-071 D8a: same header-outside-the-list composition as `recent`
    // above.
    let commits = column![
        // RFC-071 Amendment A3 D14: section header — `body`.
        strong(
            text(state.t("detail.section_recent_commits"))
                .size(snora::design::style::text::body_size(tokens))
                .line_height(snora::design::style::text::body_line_height(tokens)),
        ),
        list(tokens, commits_body),
    ]
    .spacing(3);

    // --- Actions ---
    // Review 249 §2: Refresh and Fetch become `secondary` — neither is the
    // panel's one mutating action. None of the three is a focus target
    // today (no focus-order wiring here), so `false` is passed explicitly.
    // RFC-073 D8: all three `BUTTON_HEIGHT`.
    let refresh_btn = button(centered_button_label(
        // RFC-071 Amendment A3 D14: a button label — `body`.
        text(state.t("detail.refresh"))
            .size(snora::design::style::text::body_size(tokens))
            .line_height(snora::design::style::text::body_line_height(tokens)),
    ))
    .height(Length::Fixed(BUTTON_HEIGHT))
    .padding([0, 18])
    .on_press(Message::Project(ProjectMessage::StatusRefreshRequested(
        id.clone(),
    )))
    .style({
        let t = tokens.clone();
        move |_theme, status| style::with_focus_ring(&t, false, style::secondary(&t, status))
    });

    let fetch_btn = button(centered_button_label(
        // RFC-071 Amendment A3 D14: a button label — `body`.
        text(state.t("detail.fetch"))
            .size(snora::design::style::text::body_size(tokens))
            .line_height(snora::design::style::text::body_line_height(tokens)),
    ))
    .height(Length::Fixed(BUTTON_HEIGHT))
    .padding([0, 18])
    .on_press_maybe(
        (!state.operation_interlock.is_busy())
            .then_some(Message::Project(ProjectMessage::FetchRequested(id.clone()))),
    )
    .style({
        let t = tokens.clone();
        move |_theme, status| style::with_focus_ring(&t, false, style::secondary(&t, status))
    });

    // Review 249 §2: "Remove from workspace" becomes `danger` — the one
    // mutating action in this area, styled so it looks like what it does.
    // Its confirmation window (RFC-066 D6) is unchanged.
    let remove_btn = button(centered_button_label(
        // RFC-071 Amendment A3 D14: a button label — `body`.
        text(state.t("detail.remove_from_workspace"))
            .size(snora::design::style::text::body_size(tokens))
            .line_height(snora::design::style::text::body_line_height(tokens)),
    ))
    .height(Length::Fixed(BUTTON_HEIGHT))
    .padding([0, 18])
    .on_press(Message::Workspace(
        WorkspaceMessage::RemoveProjectRequested(id.clone()),
    ))
    .style({
        let t = tokens.clone();
        move |_theme, status| style::with_focus_ring(&t, false, style::danger(&t, status))
    });

    let actions = column![
        // RFC-071 Amendment A3 D14: section header — `body`.
        strong(
            text(state.t("detail.section_actions"))
                .size(snora::design::style::text::body_size(tokens))
                .line_height(snora::design::style::text::body_line_height(tokens)),
        ),
        // RFC-073 Amendment A7 §1: wraps, same as the dashboard's own chip
        // row (Task 110) — "Check for updates" (Stage 4's renaming of
        // "Fetch") no longer fits beside "Refresh" at every width/zoom
        // this panel's fixed 300px is shown at; wrapped, it moves to its
        // own line instead of clipping inside the shared row.
        row![refresh_btn, fetch_btn].spacing(6).wrap(),
        remove_btn,
    ]
    .spacing(6);

    let content = column![header, identity, status_col, recent, commits, actions,]
        .spacing(16)
        .padding(16);

    // Task 117: the panel's own surface, not the page's `background` — the
    // only thing between it and the main column used to be the main
    // column's own scrollbar, with nothing on screen saying where the page
    // ends and the panel begins. `view.rs` draws the panel's leading edge
    // (`palette.border`) as its own element; this container only needs its
    // own fill.
    let surface = snora::design::style::color::to_iced_color(tokens.palette.surface);
    Some(
        container(scrollable(content))
            .width(Length::Fixed(300.0))
            .height(Length::Fill)
            .style(move |_theme| iced::widget::container::Style {
                background: Some(surface.into()),
                ..iced::widget::container::Style::default()
            })
            .into(),
    )
}

#[cfg(test)]
mod tests {
    /// Task 113: this file's own two inline directive strings — a recent
    /// operation's `started_at` and a recent commit's `entry.date` — read
    /// here exactly as the real call sites spell them (`%m/%d %H:%M` and
    /// `%Y-%m-%d %H:%M`), the same precedent `persistence.rs`'s own
    /// `write_corrupt_file` test helper already sets for a literal this
    /// file has no standalone function to call directly. Fixed instant:
    /// 1_709_528_767 = 2024-03-04T05:06:07Z.
    #[test]
    fn recent_operation_timestamp_format_is_stable() {
        let ts = jiff::Timestamp::from_second(1_709_528_767).unwrap();
        assert_eq!(ts.strftime("%m/%d %H:%M").to_string(), "03/04 05:06");
    }

    #[test]
    fn recent_commit_date_format_is_stable() {
        let ts = jiff::Timestamp::from_second(1_709_528_767).unwrap();
        assert_eq!(
            ts.strftime("%Y-%m-%d %H:%M").to_string(),
            "2024-03-04 05:06"
        );
    }
}