quinjet 0.0.40

A fast, live, keyboard-first Git source-control interface for the terminal
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
#[cfg_attr(not(test), expect(clippy::wildcard_imports, reason = "shared"))]
use super::*;

#[expect(
    clippy::too_many_lines,
    reason = "the draw pass reads better as one top-to-bottom pass"
)]
#[expect(
    clippy::too_many_arguments,
    reason = "rendering and hit registration share the same scrolled coordinate space"
)]
pub(super) fn draw_pull_request_details_scrolled(
    frame: &mut Frame<'_>,
    area: Rect,
    app: &App,
    scroll: usize,
    total_rows: usize,
    theme: &Theme,
    link_hits: &mut Vec<LinkHit>,
) {
    let Some(details) = app.document.pull_request_details.as_ref() else {
        return;
    };
    let block = Block::default()
        .title(format!(" Pull request #{} ยท details ", details.number))
        .borders(Borders::TOP | Borders::BOTTOM)
        .border_style(Style::default().fg(theme.border))
        .style(Style::default().bg(theme.panel_alt).fg(theme.text));
    let full_area = Rect::new(0, 0, area.width, cells(total_rows));
    let mut buffer = Buffer::empty(full_area);
    let inner = block.inner(full_area);
    block.render(full_area, &mut buffer);
    let state = if details.is_draft {
        "DRAFT"
    } else {
        details.state.as_str()
    };
    let head_repository = details.head_repository.as_deref().unwrap_or("deleted fork");
    let pull_request_target =
        (!details.url.is_empty()).then(|| OpenTarget::Browser(details.url.clone()));
    let title_width = details.title.width();
    let mut lines = vec![Line::from(link_span(
        details.title.clone(),
        pull_request_target,
        scrolled_detail_link_area(area, scroll, inner.y, inner.x, title_width),
        theme,
        link_hits,
    ))];
    let status_prefix = format!("{state}  ยท  ");
    let author = format!("@{}", details.author);
    lines.push(scrolled_link_detail_line(
        "Status",
        status_prefix,
        author,
        format!(
            "  ยท  updated {}",
            format_local_timestamp(&details.updated_at)
        ),
        app.account_open_target(&details.author),
        area,
        scroll,
        inner,
        1,
        theme,
        link_hits,
    ));
    for (index, description) in description_preview_lines(
        &details.description,
        inner.width.saturating_sub(12) as usize,
        3,
    )
    .into_iter()
    .enumerate()
    {
        lines.push(detail_line(
            if index == 0 { "Description" } else { "" },
            description,
            theme,
        ));
    }
    let mut selected_file = vec![Span::styled(
        format!("{:<DETAIL_LABEL_WIDTH$}", "Selected"),
        Style::default().fg(theme.muted),
    )];
    if let Some(path) = details.selected_file.as_deref() {
        selected_file.extend([
            file_icon_span(Path::new(path), theme),
            Span::raw(" "),
            Span::styled(path, Style::default().fg(theme.text)),
        ]);
    } else {
        selected_file.push(Span::styled(
            "Preparing files",
            Style::default().fg(theme.text),
        ));
    }
    selected_file.extend([
        Span::raw("  "),
        Span::styled(
            format!("+{}", details.selected_file_additions),
            Style::default()
                .fg(theme.added)
                .add_modifier(Modifier::BOLD),
        ),
        Span::raw("  "),
        Span::styled(
            format!("-{}", details.selected_file_deletions),
            Style::default()
                .fg(theme.removed)
                .add_modifier(Modifier::BOLD),
        ),
    ]);
    let source_row = lines.len();
    lines.push(scrolled_link_detail_line(
        "Source",
        String::new(),
        format!("{head_repository}:{}", details.head_ref),
        format!(
            "{}{}",
            remote_suffix(&details.head_remotes),
            if details.is_cross_repository {
                "  ยท  fork"
            } else {
                ""
            }
        ),
        app.pull_request_head_branch_open_target(),
        area,
        scroll,
        inner,
        source_row,
        theme,
        link_hits,
    ));
    let destination_row = lines.len();
    lines.push(scrolled_link_detail_line(
        "Destination",
        String::new(),
        format!("{}:{}", details.base_repository, details.base_ref),
        remote_suffix(&details.base_remotes),
        app.pull_request_base_branch_open_target(),
        area,
        scroll,
        inner,
        destination_row,
        theme,
        link_hits,
    ));
    let url_row = lines.len();
    lines.push(scrolled_link_detail_line(
        "URL",
        String::new(),
        details.url.clone(),
        String::new(),
        (!details.url.is_empty()).then(|| OpenTarget::Browser(details.url.clone())),
        area,
        scroll,
        inner,
        url_row,
        theme,
        link_hits,
    ));
    lines.extend([
        Line::from(selected_file),
        Line::from(vec![
            Span::styled("PR total   ", Style::default().fg(theme.muted)),
            Span::styled(
                format!(
                    "{} file{} changed  ",
                    details.changed_files,
                    if details.changed_files == 1 { "" } else { "s" }
                ),
                Style::default().fg(theme.text),
            ),
            Span::styled(
                format!("+{}", details.additions),
                Style::default()
                    .fg(theme.added)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled("  ", Style::default()),
            Span::styled(
                format!("-{}", details.deletions),
                Style::default()
                    .fg(theme.removed)
                    .add_modifier(Modifier::BOLD),
            ),
        ]),
    ]);
    Paragraph::new(lines).render(inner, &mut buffer);

    for destination_row in 0..area.height {
        let source_row = cells(scroll) + destination_row;
        if source_row >= full_area.height {
            break;
        }
        for column in 0..area.width {
            let source = buffer[(column, source_row)].clone();
            if let Some(destination) = frame
                .buffer_mut()
                .cell_mut((area.x + column, area.y + destination_row))
            {
                *destination = source;
            }
        }
    }
}

#[expect(
    clippy::too_many_arguments,
    reason = "the helper maps one linked detail value into a scrolled card"
)]
pub(super) fn scrolled_link_detail_line(
    label: &str,
    prefix: String,
    text: String,
    suffix: String,
    target: Option<OpenTarget>,
    area: Rect,
    scroll: usize,
    inner: Rect,
    row: usize,
    theme: &Theme,
    link_hits: &mut Vec<LinkHit>,
) -> Line<'static> {
    let link_x = inner
        .x
        .saturating_add(cells(DETAIL_LABEL_WIDTH))
        .saturating_add(cells(prefix.width()));
    let link_area = scrolled_detail_link_area(
        area,
        scroll,
        inner.y.saturating_add(cells(row)),
        link_x,
        text.width(),
    );
    Line::from(vec![
        Span::styled(
            format!("{label:<DETAIL_LABEL_WIDTH$}"),
            Style::default().fg(theme.muted),
        ),
        Span::styled(prefix, Style::default().fg(theme.text)),
        link_span(text, target, link_area, theme, link_hits),
        Span::styled(suffix, Style::default().fg(theme.text)),
    ])
}

pub(super) fn description_preview_lines(
    value: &str,
    width: usize,
    maximum_lines: usize,
) -> Vec<String> {
    let description = markdown_preview_text(value);
    text_preview_lines(
        if description.is_empty() {
            "No description provided"
        } else {
            &description
        },
        width,
        maximum_lines,
    )
}

pub(super) fn markdown_preview_text(value: &str) -> String {
    let mut output = String::new();
    for raw_line in value.lines() {
        let line = raw_line.trim();
        if line.is_empty() {
            continue;
        }
        let heading = line.starts_with('#');
        let line = line.trim_start_matches('#').trim_start();
        let (line, bullet) = ["- ", "* ", "+ "]
            .into_iter()
            .find_map(|marker| line.strip_prefix(marker).map(|line| (line, true)))
            .unwrap_or((line, false));
        let line = strip_inline_markdown(line);
        if line.is_empty()
            || (heading
                && matches!(
                    line.to_ascii_lowercase().as_str(),
                    "summary" | "description" | "overview"
                ))
        {
            continue;
        }
        if !output.is_empty() {
            output.push_str(if bullet { " โ€ข " } else { " " });
        }
        output.push_str(&line);
    }
    output
}

pub(super) fn strip_inline_markdown(value: &str) -> String {
    value
        .chars()
        .filter(|character| !matches!(character, '*' | '`'))
        .collect()
}

pub(super) fn text_preview_lines(value: &str, width: usize, maximum_lines: usize) -> Vec<String> {
    if maximum_lines == 0 {
        return Vec::new();
    }
    let width = width.max(1);
    let normalized = value.split_whitespace().collect::<Vec<_>>().join(" ");
    let total_width = normalized.width();
    let mut lines = Vec::with_capacity(maximum_lines);
    let mut skipped = 0;
    while skipped < total_width && lines.len() < maximum_lines {
        while skipped < total_width && slice_width(&normalized, skipped, 1) == " " {
            skipped += 1;
        }
        let chunk = slice_width(&normalized, skipped, width);
        if chunk.is_empty() {
            break;
        }
        let reaches_end = skipped.saturating_add(chunk.width()) >= total_width;
        let (line, used) = if reaches_end {
            let used = chunk.width();
            (chunk, used)
        } else if let Some(space) = chunk.rfind(' ').filter(|space| *space > 0) {
            let line = chunk.get(..space).unwrap_or_default().to_owned();
            let used = line.width().saturating_add(1);
            (line, used)
        } else {
            let used = chunk.width();
            (chunk, used)
        };
        if used == 0 {
            break;
        }
        skipped = skipped.saturating_add(used);
        lines.push(line);
    }
    if skipped < total_width
        && let Some(last) = lines.last_mut()
    {
        *last = format!(
            "{}โ€ฆ",
            slice_width(last.trim_end(), 0, width.saturating_sub(1))
        );
    }
    while lines.len() < maximum_lines {
        lines.push(String::new());
    }
    lines
}

pub(super) fn remote_suffix(remotes: &[String]) -> String {
    if remotes.is_empty() {
        String::new()
    } else {
        format!(
            "  ยท  remote{} {}",
            if remotes.len() == 1 { "" } else { "s" },
            remotes.join(", ")
        )
    }
}

pub(super) fn detail_line<'a>(label: &'a str, value: String, theme: &Theme) -> Line<'a> {
    Line::from(vec![
        Span::styled(
            format!("{label:<DETAIL_LABEL_WIDTH$}"),
            Style::default().fg(theme.muted),
        ),
        Span::styled(value, Style::default().fg(theme.text)),
    ])
}

pub(super) fn link_detail_line<'a>(label: &'a str, value: String, theme: &Theme) -> Line<'a> {
    Line::from(vec![
        Span::styled(
            format!("{label:<DETAIL_LABEL_WIDTH$}"),
            Style::default().fg(theme.muted),
        ),
        Span::styled(value, Link::style(theme)),
    ])
}

pub(super) fn link_style(theme: &Theme) -> Style {
    Style::default()
        .fg(theme.accent)
        .add_modifier(Modifier::BOLD)
}

pub(super) fn link_span(
    text: String,
    target: Option<OpenTarget>,
    area: Rect,
    theme: &Theme,
    hits: &mut Vec<LinkHit>,
) -> Span<'static> {
    match target {
        None => Span::styled(
            text,
            Style::default().fg(theme.text).add_modifier(Modifier::BOLD),
        ),
        Some(target) => Link::new(target).span(text, area, theme, hits),
    }
}

pub(super) fn clipped_link_area(x: u16, y: u16, width: usize, container: Rect) -> Rect {
    if y < container.y || y >= container.bottom() || x >= container.right() {
        return Rect::default();
    }
    Rect::new(
        x.max(container.x),
        y,
        cells(width).min(container.right().saturating_sub(x.max(container.x))),
        1,
    )
}

pub(super) fn horizontally_scrolled_link_area(
    container: Rect,
    scroll: usize,
    start: usize,
    width: usize,
) -> Rect {
    let end = start.saturating_add(width);
    if end <= scroll {
        return Rect::default();
    }
    let visible_start = start.max(scroll);
    clipped_link_area(
        container
            .x
            .saturating_add(cells(visible_start.saturating_sub(scroll))),
        container.y,
        end.saturating_sub(visible_start),
        container,
    )
}

pub(super) fn scrolled_detail_link_area(
    area: Rect,
    scroll: usize,
    source_y: u16,
    source_x: u16,
    width: usize,
) -> Rect {
    let scroll = cells(scroll);
    if source_y < scroll {
        return Rect::default();
    }
    let row = source_y - scroll;
    clipped_link_area(
        area.x.saturating_add(source_x),
        area.y.saturating_add(row),
        width,
        area,
    )
}

pub(super) fn pull_request_reference(text: &str) -> Option<(usize, usize, u64)> {
    text.match_indices('#').find_map(|(start, _)| {
        let rest = text.get(start.saturating_add(1)..)?;
        let digits = rest.bytes().take_while(u8::is_ascii_digit).count();
        if digits == 0 {
            return None;
        }
        let end = start.saturating_add(1).saturating_add(digits);
        let number = text.get(start.saturating_add(1)..end)?.parse().ok()?;
        Some((start, end, number))
    })
}

pub(super) fn unified_row_indices(document: &DiffDocument, app: &App) -> Vec<usize> {
    let mut rows = Vec::new();
    let mut index = 0;
    while let Some(line) = document.lines.get(index) {
        if line.kind == DiffLineKind::HunkHeader {
            index += 1;
            continue;
        }
        rows.push(index);
        let collapsed = line.kind == DiffLineKind::FileHeader
            && file_header_path(line).is_some_and(|path| app.preview_file_collapsed(path));
        index += 1;
        if collapsed {
            while document
                .lines
                .get(index)
                .is_some_and(|line| line.kind != DiffLineKind::FileFooter)
            {
                index += 1;
            }
            if index < document.lines.len() {
                index += 1;
            }
        }
    }
    rows
}