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
use super::context::ContextConfig;
pub fn expand_tabs(s: &str, tab_width: usize) -> String {
if tab_width == 0 {
return s.replace('\t', "");
}
let mut result = String::with_capacity(s.len());
let mut col = 0;
for c in s.chars() {
if c == '\t' {
let spaces = tab_width - (col % tab_width);
for _ in 0..spaces {
result.push(' ');
}
col += spaces;
} else {
result.push(c);
col += 1;
}
}
result
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FileStatus {
Added,
Modified,
Deleted,
}
impl FileStatus {
pub fn symbol(&self) -> &'static str {
match self {
FileStatus::Added => "A",
FileStatus::Modified => "M",
FileStatus::Deleted => "D",
}
}
}
pub struct FileDiff {
pub filename: String,
pub old_content: String,
pub new_content: String,
pub status: FileStatus,
pub is_binary: bool,
}
/// Detect if content is binary by checking for null bytes in the first 8KB
pub fn is_binary_content(content: &str) -> bool {
content.bytes().take(8192).any(|b| b == 0)
}
/// Settings for the diff view UI. Designed to be easily extended
/// with additional configuration options in the future.
#[derive(Clone)]
pub struct DiffViewSettings {
pub context: ContextConfig,
pub tab_width: usize,
pub wrap: bool,
}
impl Default for DiffViewSettings {
fn default() -> Self {
Self {
context: ContextConfig::default(),
tab_width: 4,
wrap: false,
}
}
}
/// Represents a segment of text with optional emphasis for word-level highlighting
#[derive(Clone, Debug)]
pub struct InlineSegment {
pub text: String,
/// If true, this segment represents a changed word that should be emphasized
pub emphasized: bool,
}
pub struct DiffLine {
pub old_line: Option<(usize, String)>,
pub new_line: Option<(usize, String)>,
pub change_type: ChangeType,
/// Word-level segments for the old line (only populated for Modified lines)
pub old_segments: Option<Vec<InlineSegment>>,
/// Word-level segments for the new line (only populated for Modified lines)
pub new_segments: Option<Vec<InlineSegment>>,
}
impl DiffLine {
/// Get the line number for the given panel side.
pub fn line_number(&self, panel: DiffPanelFocus) -> Option<usize> {
match panel {
DiffPanelFocus::Old => self.old_line.as_ref().map(|(n, _)| *n),
DiffPanelFocus::New | DiffPanelFocus::None => self.new_line.as_ref().map(|(n, _)| *n),
}
}
}
#[derive(Clone, Copy)]
pub enum ChangeType {
Equal,
Delete,
Insert,
/// A paired delete+insert, shown on the same row (GitHub-style)
Modified,
}
#[derive(Clone, Copy, PartialEq, Default)]
pub enum FocusedPanel {
Sidebar,
#[default]
DiffView,
}
/// Which panel in the diff view has selection focus (old vs new)
#[derive(Clone, Copy, PartialEq, Default, Debug)]
pub enum DiffPanelFocus {
#[default]
None,
Old,
New,
}
/// Position within the diff content
#[derive(Clone, Copy, PartialEq, Default, Debug)]
pub struct CursorPosition {
/// Line index in side_by_side diff (0-indexed)
pub line: usize,
/// Column offset in content (0-indexed, after expanding tabs)
pub column: usize,
}
/// How the selection was initiated
#[derive(Clone, Copy, PartialEq, Default, Debug)]
pub enum SelectionMode {
#[default]
None,
/// Click-drag in content area
Character,
/// Click-drag on line numbers
Line,
}
/// Represents a text selection in one of the diff panels
#[derive(Clone, PartialEq, Default, Debug)]
pub struct Selection {
/// Which panel the selection is in
pub panel: DiffPanelFocus,
/// Where selection started (anchor point)
pub anchor: CursorPosition,
/// Current end of selection (moves during drag)
pub head: CursorPosition,
/// How the selection was initiated
pub mode: SelectionMode,
}
#[allow(dead_code)]
impl Selection {
/// Returns the selection range normalized so start <= end
pub fn normalized_range(&self) -> (CursorPosition, CursorPosition) {
if self.anchor.line < self.head.line
|| (self.anchor.line == self.head.line && self.anchor.column <= self.head.column)
{
(self.anchor, self.head)
} else {
(self.head, self.anchor)
}
}
/// Check if selection contains a given position
pub fn contains(&self, line: usize, column: usize) -> bool {
if !self.is_active() {
return false;
}
let (start, end) = self.normalized_range();
match self.mode {
SelectionMode::None => false,
SelectionMode::Line => {
// Line mode: entire lines are selected
line >= start.line && line <= end.line
}
SelectionMode::Character => {
// Character mode: check column bounds
if line < start.line || line > end.line {
return false;
}
if start.line == end.line {
// Single line selection
column >= start.column && column < end.column
} else if line == start.line {
// First line of multi-line selection
column >= start.column
} else if line == end.line {
// Last line of multi-line selection
column < end.column
} else {
// Middle lines are fully selected
true
}
}
}
}
/// Check if selection is active (has content selected)
pub fn is_active(&self) -> bool {
self.mode != SelectionMode::None && self.panel != DiffPanelFocus::None
}
/// Check if a whole line is selected (for line mode or fully-encompassed lines)
pub fn is_line_fully_selected(&self, line: usize) -> bool {
if !self.is_active() {
return false;
}
let (start, end) = self.normalized_range();
match self.mode {
SelectionMode::Line => line >= start.line && line <= end.line,
SelectionMode::Character => {
// In character mode, middle lines of multi-line selection are fully selected
line > start.line && line < end.line
}
SelectionMode::None => false,
}
}
}
#[derive(Clone, Copy, PartialEq, Default, Debug)]
pub enum DiffFullscreen {
#[default]
None,
OldOnly,
NewOnly,
}
#[derive(Clone)]
pub enum SidebarItem {
Directory {
name: String,
path: String,
depth: usize,
},
File {
name: String,
path: String,
file_index: usize,
depth: usize,
status: FileStatus,
},
}
pub fn build_file_tree(file_diffs: &[FileDiff]) -> Vec<SidebarItem> {
use std::collections::{BTreeMap, BTreeSet};
if file_diffs.is_empty() {
return Vec::new();
}
let mut file_paths: Vec<(String, usize, FileStatus)> = file_diffs
.iter()
.enumerate()
.map(|(idx, diff)| (diff.filename.clone(), idx, diff.status))
.collect();
file_paths.sort_by(|a, b| a.0.cmp(&b.0));
// Count children for each directory path
let mut dir_children: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
dir_children.insert(String::new(), BTreeSet::new()); // root
for (path, _, _) in &file_paths {
let parts: Vec<&str> = path.split('/').collect();
// Add file as child of its parent directory
if parts.len() > 1 {
let parent_path = parts[..parts.len() - 1].join("/");
dir_children
.entry(parent_path)
.or_default()
.insert(path.clone());
} else {
// File at root level
dir_children.get_mut("").unwrap().insert(path.clone());
}
// Add each directory as child of its parent
for i in 0..parts.len().saturating_sub(1) {
let dir_path = parts[..=i].join("/");
let parent_path = if i == 0 {
String::new()
} else {
parts[..i].join("/")
};
dir_children.entry(dir_path.clone()).or_default();
dir_children
.entry(parent_path)
.or_default()
.insert(dir_path);
}
}
// Find the collapsed path for a directory (collapse single-child chains)
fn get_collapsed_dir(
dir_path: &str,
dir_children: &BTreeMap<String, BTreeSet<String>>,
file_paths_set: &BTreeSet<String>,
) -> String {
let mut current = dir_path.to_string();
loop {
if let Some(children) = dir_children.get(¤t) {
// If directory has exactly one child and it's a directory (not a file)
if children.len() == 1 {
let child = children.iter().next().unwrap();
if !file_paths_set.contains(child) {
// It's a directory, continue collapsing
current = child.clone();
continue;
}
}
}
break;
}
current
}
let file_paths_set: BTreeSet<String> = file_paths.iter().map(|(p, _, _)| p.clone()).collect();
let mut items: Vec<SidebarItem> = Vec::new();
let mut added_dirs: BTreeSet<String> = BTreeSet::new();
// Maps any directory path to its collapsed version
let mut path_to_collapsed: BTreeMap<String, String> = BTreeMap::new();
// Maps collapsed path to its depth
let mut collapsed_depth: BTreeMap<String, usize> = BTreeMap::new();
for (path, file_idx, status) in &file_paths {
let parts: Vec<&str> = path.split('/').collect();
let file_name = parts.last().unwrap_or(&"").to_string();
// Process directories
let mut i = 0;
while i < parts.len().saturating_sub(1) {
let dir_path = parts[..=i].join("/");
// Check if this directory should be collapsed
let collapsed_path = get_collapsed_dir(&dir_path, &dir_children, &file_paths_set);
if !added_dirs.contains(&collapsed_path) {
added_dirs.insert(collapsed_path.clone());
// Register all intermediate paths as mapping to this collapsed path
// Use entry().or_insert() to avoid overwriting existing mappings
let collapsed_parts: Vec<&str> = collapsed_path.split('/').collect();
for j in 0..collapsed_parts.len() {
let intermediate = collapsed_parts[..=j].join("/");
path_to_collapsed
.entry(intermediate)
.or_insert(collapsed_path.clone());
}
// Calculate depth based on parent's collapsed path
let depth = if i == 0 {
0
} else {
let parent_dir = parts[..i].join("/");
if let Some(parent_collapsed) = path_to_collapsed.get(&parent_dir) {
collapsed_depth
.get(parent_collapsed)
.map(|d| d + 1)
.unwrap_or(0)
} else {
0
}
};
collapsed_depth.insert(collapsed_path.clone(), depth);
// Calculate display name: relative to parent collapsed directory
let display_name = if i == 0 {
collapsed_path.clone()
} else {
let parent_dir = parts[..i].join("/");
if let Some(parent_collapsed) = path_to_collapsed.get(&parent_dir) {
// Strip the parent collapsed path prefix
collapsed_path
.strip_prefix(&format!("{}/", parent_collapsed))
.unwrap_or(&collapsed_path)
.to_string()
} else {
collapsed_path.clone()
}
};
items.push(SidebarItem::Directory {
name: display_name,
path: collapsed_path.clone(),
depth,
});
// Skip to the end of the collapsed path
i = collapsed_parts.len();
continue;
} else {
// Directory already added, skip ahead
let collapsed_parts: Vec<&str> = collapsed_path.split('/').collect();
i = collapsed_parts.len();
continue;
}
}
// Calculate file depth based on its parent directory
let file_depth = if parts.len() > 1 {
let parent_dir = parts[..parts.len() - 1].join("/");
if let Some(parent_collapsed) = path_to_collapsed.get(&parent_dir) {
collapsed_depth
.get(parent_collapsed)
.map(|d| d + 1)
.unwrap_or(0)
} else {
0
}
} else {
0
};
items.push(SidebarItem::File {
name: file_name,
path: path.clone(),
file_index: *file_idx,
depth: file_depth,
status: *status,
});
}
items
}