diffler 0.11.1

Terminal code review for AI coding agents
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
//! Flattening a file's diff and its review comments into the row list the
//! pane renders.

use std::collections::HashMap;

use diffler_core::highlight::Highlighter;
use diffler_core::model::{DiffModel, FileDiff, LineKind};
use diffler_core::session::{Anchor, Comment, Session};
use unicode_width::UnicodeWidthStr;

use crate::app::composer::{Composer, ComposerKind, card_budget};
use crate::app::markdown::{self, MdSpan};

/// One terminal row of the selected file's diff body. Indices point into the
/// model the view renders; the row list is rebuilt whenever the selected
/// file, the model, or the session change, so they never dangle. The `file`
/// field always equals the selected file index, kept so the shared
/// `diff_render` and anchor helpers read it unchanged.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiffRow {
    Hunk {
        file: usize,
        hunk: usize,
    },
    Line {
        file: usize,
        hunk: usize,
        line: usize,
    },
    /// One display line of a comment block; `line` indexes the block
    /// produced by [`comment_display`].
    Comment {
        comment: usize,
        line: usize,
        outdated: bool,
    },
    /// One display line of the open composer, sitting where its result will.
    Composer {
        line: usize,
    },
}

/// One display line of a comment block. Body and reply text carry markdown
/// styling as flag-tagged runs; [`crate::ui`] maps the flags to concrete styles.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CommentLine {
    Header,
    Body(Vec<MdSpan>),
    Reply {
        author: String,
        spans: Vec<MdSpan>,
        first: bool,
    },
    Footer,
}

/// The terminal lines a comment occupies at `row_width` columns, markdown
/// rendered and long text wrapped to fit. Shared by row flattening (for counts)
/// and rendering (for content) so they can never disagree.
pub fn comment_display(
    comment: &Comment,
    row_width: u16,
    highlighter: Option<&Highlighter>,
) -> Vec<CommentLine> {
    let budget = card_budget(row_width);
    let mut lines = vec![CommentLine::Header];
    for logical in markdown::parse(&comment.body, highlighter, budget) {
        lines.extend(
            markdown::wrap(&logical, budget, budget)
                .into_iter()
                .map(CommentLine::Body),
        );
    }
    for reply in &comment.replies {
        // the author label only renders on the first line; continuations get
        // the renderer's two-space indent
        let label = format!("└ {}: ", reply.author).width();
        let mut first = true;
        // a table lays out at parse time and `wrap` then leaves it alone, so
        // it has to fit the narrowest line of the reply: the labelled one
        let laid_out = budget.saturating_sub(label.max(2)).max(8);
        for logical in markdown::parse(&reply.body, highlighter, laid_out) {
            let head = budget.saturating_sub(if first { label } else { 2 }).max(8);
            for spans in markdown::wrap(&logical, head, budget.saturating_sub(2).max(8)) {
                lines.push(CommentLine::Reply {
                    author: reply.author.clone(),
                    spans,
                    first,
                });
                first = false;
            }
        }
    }
    lines.push(CommentLine::Footer);
    lines
}

/// Hunk and line indices a comment displays under; `None` when the
/// anchored line is absent from the file's hunks. Outdated detection lives
/// in [`Anchor::is_outdated`], which shares the same end-line semantics.
fn anchor_target(file: &FileDiff, anchor: &Anchor) -> Option<(usize, usize)> {
    // range comments display under the end of their range
    let target = anchor.line_end.or(anchor.line)?;
    for (hunk_idx, hunk) in file.hunks.iter().enumerate() {
        let found = hunk.lines.iter().position(|l| {
            let no = if anchor.on_old_side {
                l.old_no
            } else {
                l.new_no
            };
            no == Some(target)
        });
        if let Some(line_idx) = found {
            return Some((hunk_idx, line_idx));
        }
    }
    None
}

/// The open composer and the rows it draws, carried through row building so
/// its rows land exactly where its result will.
struct Draft<'a> {
    composer: &'a Composer,
    height: usize,
}

impl Draft<'_> {
    fn new(composer: Option<&Composer>, wrap_width: u16) -> Option<Draft<'_>> {
        let composer = composer?;
        Some(Draft {
            height: composer.display(wrap_width).len(),
            composer,
        })
    }

    fn edits(&self, id: &str) -> bool {
        matches!(self.composer.kind, ComposerKind::Edit { .. })
            && self.composer.comment_id() == Some(id)
    }

    fn replies_to(&self, id: &str) -> bool {
        matches!(self.composer.kind, ComposerKind::Reply { .. })
            && self.composer.comment_id() == Some(id)
    }

    /// The hunk and line the composer's new comment will display under, or
    /// `None` when it is file-level or belongs to another file.
    fn new_at(&self, file: &FileDiff) -> Option<(usize, usize)> {
        let anchor = self.composer.anchor()?;
        (anchor.file == file.path).then(|| anchor_target(file, anchor))?
    }

    /// A file-level new comment: the composer opens above the diff, where a
    /// whole-file comment renders.
    fn is_unanchored(&self, file: &FileDiff) -> bool {
        self.composer
            .anchor()
            .is_some_and(|anchor| anchor.file == file.path && anchor_target(file, anchor).is_none())
    }
}

fn push_comment_rows(
    rows: &mut Vec<DiffRow>,
    session: &Session,
    comments: &[(usize, bool)],
    wrap_width: u16,
    draft: Option<&Draft<'_>>,
) {
    for &(comment, outdated) in comments {
        let Some(c) = session.comments.get(comment) else {
            continue;
        };
        if draft.is_some_and(|d| d.edits(&c.id)) {
            push_draft_rows(rows, draft);
            continue;
        }
        let count = comment_display(c, wrap_width, None).len();
        rows.extend((0..count).map(|line| DiffRow::Comment {
            comment,
            line,
            outdated,
        }));
        if draft.is_some_and(|d| d.replies_to(&c.id)) {
            push_draft_rows(rows, draft);
        }
    }
}

fn push_draft_rows(rows: &mut Vec<DiffRow>, draft: Option<&Draft<'_>>) {
    let Some(draft) = draft else { return };
    rows.extend((0..draft.height).map(|line| DiffRow::Composer { line }));
}

/// Bucket a file's comments by their `(hunk, line)` anchor for inline display.
/// A line anchor that no longer exists is outdated, and a file-level comment
/// has no line: both land in the unanchored list, rendered at the top.
type CommentBuckets = (
    HashMap<(usize, usize), Vec<(usize, bool)>>,
    Vec<(usize, bool)>,
);

fn collect_comments(file: &FileDiff, session: &Session, model: &DiffModel) -> CommentBuckets {
    let mut by_line: HashMap<(usize, usize), Vec<(usize, bool)>> = HashMap::new();
    let mut unanchored: Vec<(usize, bool)> = Vec::new();
    for (comment_idx, comment) in session.comments.iter().enumerate() {
        if comment.anchor.file != file.path {
            continue;
        }
        let outdated = comment.anchor.is_outdated(model);
        match anchor_target(file, &comment.anchor) {
            Some((hunk, line)) => by_line
                .entry((hunk, line))
                .or_default()
                .push((comment_idx, outdated)),
            None => unanchored.push((comment_idx, outdated)),
        }
    }
    (by_line, unanchored)
}

/// Build the diff-pane rows for one file: its hunks and lines, with comment
/// blocks under their anchored line, file-level (or orphaned) comments first.
pub(super) fn build_rows(
    model: &DiffModel,
    session: &Session,
    selected: usize,
    wrap_width: u16,
    composer: Option<&Composer>,
) -> Vec<DiffRow> {
    let mut rows = Vec::new();
    let Some(file) = model.files.get(selected) else {
        return rows;
    };
    let draft = Draft::new(composer, wrap_width);
    let draft = draft.as_ref();
    let (by_line, unanchored) = collect_comments(file, session, model);
    push_comment_rows(&mut rows, session, &unanchored, wrap_width, draft);
    if draft.is_some_and(|d| d.is_unanchored(file)) {
        push_draft_rows(&mut rows, draft);
    }
    let new_at = draft.and_then(|d| d.new_at(file));
    for (hunk_idx, hunk) in file.hunks.iter().enumerate() {
        rows.push(DiffRow::Hunk {
            file: selected,
            hunk: hunk_idx,
        });
        for line_idx in 0..hunk.lines.len() {
            rows.push(DiffRow::Line {
                file: selected,
                hunk: hunk_idx,
                line: line_idx,
            });
            if let Some(list) = by_line.get(&(hunk_idx, line_idx)) {
                push_comment_rows(&mut rows, session, list, wrap_width, draft);
            }
            if new_at == Some((hunk_idx, line_idx)) {
                push_draft_rows(&mut rows, draft);
            }
        }
    }
    rows
}

/// Which column of a side-by-side row a line belongs to: the old side renders
/// on the left, the new side on the right.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SplitSide {
    Left,
    Right,
}

/// One row of the side-by-side diff body. `left`/`right` index into the hunk's
/// lines: a context row carries the same index on both sides, a modified row
/// pairs a deletion with an addition, and a lone deletion or addition fills one
/// side with `None`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SplitRow {
    Hunk {
        hunk: usize,
    },
    Pair {
        hunk: usize,
        left: Option<usize>,
        right: Option<usize>,
    },
    Comment {
        comment: usize,
        line: usize,
        outdated: bool,
    },
    Composer {
        line: usize,
    },
}

fn push_split_comments(
    rows: &mut Vec<SplitRow>,
    session: &Session,
    comments: &[(usize, bool)],
    wrap_width: u16,
    draft: Option<&Draft<'_>>,
) {
    for &(comment, outdated) in comments {
        let Some(c) = session.comments.get(comment) else {
            continue;
        };
        if draft.is_some_and(|d| d.edits(&c.id)) {
            push_split_draft_rows(rows, draft);
            continue;
        }
        let count = comment_display(c, wrap_width, None).len();
        rows.extend((0..count).map(|line| SplitRow::Comment {
            comment,
            line,
            outdated,
        }));
        if draft.is_some_and(|d| d.replies_to(&c.id)) {
            push_split_draft_rows(rows, draft);
        }
    }
}

fn push_split_draft_rows(rows: &mut Vec<SplitRow>, draft: Option<&Draft<'_>>) {
    let Some(draft) = draft else { return };
    rows.extend((0..draft.height).map(|line| SplitRow::Composer { line }));
}

/// Emit a change block as aligned pairs: deletions on the left, additions on
/// the right, zipped by position with `None` filling the shorter side. Any
/// comment anchored to a paired line follows its row.
#[allow(clippy::too_many_arguments)]
fn flush_change_block(
    rows: &mut Vec<SplitRow>,
    session: &Session,
    by_line: &HashMap<(usize, usize), Vec<(usize, bool)>>,
    hunk: usize,
    dels: &[usize],
    adds: &[usize],
    wrap_width: u16,
    draft: Option<&Draft<'_>>,
    new_at: Option<(usize, usize)>,
) {
    for k in 0..dels.len().max(adds.len()) {
        let left = dels.get(k).copied();
        let right = adds.get(k).copied();
        rows.push(SplitRow::Pair { hunk, left, right });
        for line in [left, right].into_iter().flatten() {
            if let Some(list) = by_line.get(&(hunk, line)) {
                push_split_comments(rows, session, list, wrap_width, draft);
            }
            if new_at == Some((hunk, line)) {
                push_split_draft_rows(rows, draft);
            }
        }
    }
}

/// Build the side-by-side rows for one file, the split-mode counterpart to
/// [`build_rows`]. Same comment placement; lines are paired old-to-new.
pub(super) fn build_split_rows(
    model: &DiffModel,
    session: &Session,
    selected: usize,
    wrap_width: u16,
    composer: Option<&Composer>,
) -> Vec<SplitRow> {
    let mut rows = Vec::new();
    let Some(file) = model.files.get(selected) else {
        return rows;
    };
    let draft = Draft::new(composer, wrap_width);
    let draft = draft.as_ref();
    let (by_line, unanchored) = collect_comments(file, session, model);
    push_split_comments(&mut rows, session, &unanchored, wrap_width, draft);
    if draft.is_some_and(|d| d.is_unanchored(file)) {
        push_split_draft_rows(&mut rows, draft);
    }
    let new_at = draft.and_then(|d| d.new_at(file));
    for (hunk_idx, hunk) in file.hunks.iter().enumerate() {
        rows.push(SplitRow::Hunk { hunk: hunk_idx });
        let mut dels: Vec<usize> = Vec::new();
        let mut adds: Vec<usize> = Vec::new();
        for (line_idx, line) in hunk.lines.iter().enumerate() {
            match line.kind {
                LineKind::Context => {
                    flush_change_block(
                        &mut rows, session, &by_line, hunk_idx, &dels, &adds, wrap_width, draft,
                        new_at,
                    );
                    dels.clear();
                    adds.clear();
                    rows.push(SplitRow::Pair {
                        hunk: hunk_idx,
                        left: Some(line_idx),
                        right: Some(line_idx),
                    });
                    if let Some(list) = by_line.get(&(hunk_idx, line_idx)) {
                        push_split_comments(&mut rows, session, list, wrap_width, draft);
                    }
                    if new_at == Some((hunk_idx, line_idx)) {
                        push_split_draft_rows(&mut rows, draft);
                    }
                }
                LineKind::Deleted => dels.push(line_idx),
                LineKind::Added => adds.push(line_idx),
            }
        }
        flush_change_block(
            &mut rows, session, &by_line, hunk_idx, &dels, &adds, wrap_width, draft, new_at,
        );
    }
    rows
}