Visual Studio Code, rebuilt in Rust
Rust
//! The multi diff editor's input and view model: multiDiffEditorInput.ts (name, resources), multiDiffEditorViewModel.ts
//! (each file's collapsed state) and the rows each file's read-only diff draws, with its unchanged regions hidden as
//! multiDiffEditor's `hideUnchangedRegions: { enabled: true }` does. Drawn by
//! `workbench/editor_view/multi_diff_editor_view.rs`.
use std::cell::Cell;
use std::collections::HashSet;
use std::path::PathBuf;
use std::rc::Rc;
use diff::{DiffOptions, LineRange};
use serde_json::{Value, json};
use crate::diff_editor::unchanged_regions::{OutlineSymbol, UnchangedDrag, UnchangedRegion};
use crate::diff_editor::{ComputedDiff, Side, ZoneSide, additional_heights, range_alignment};
use crate::editor::{OpenEditor, Position, Selection, split_query, uri_string, uri_value};
/// The scheme of a multi diff editor's tab entry; its `MultiDiffInput` names the models it shows.
pub const MULTI_DIFF_EDITOR_SCHEME: &str = "multi-diff-editor";
/// multiDiffEditorOptions.ts `noCards` variant (`multiDiffEditor.experimental.variant`'s default) `headerHeight`.
pub const HEADER_HEIGHT: f32 = 32.;
/// The `noCards` variant's `contentBottomPadding` below an expanded file.
pub const CONTENT_BOTTOM_PADDING: f32 = 8.;
/// The lines of a side without a resource: an empty model.
pub static EMPTY_MODEL: [String; 1] = [String::new()];
/// `MultiDiffEditorInput`: the source the editor is matched by, the preferred label and the files.
pub struct MultiDiffInput {
pub source: Option<Side>,
pub label: Option<String>,
pub files: Vec<FileDiff>,
pub scroll_top: f32,
/// The list's height as last laid out.
pub view_height: Rc<Cell<f32>>,
/// The list's bounds as last laid out, for its scrollbar.
pub view_bounds: Rc<Cell<gpui::Bounds<gpui::Pixels>>>,
/// The editor's width, diffs and file list, as last laid out.
pub body_width: Rc<Cell<f32>>,
/// The source's context keys for every file's toolbar (`IResolvedMultiDiffSource.contextKeys`).
pub context_keys: Vec<(String, Value)>,
/// The active file and the 1-based modified line its editor's cursor is on (`activeDiffItem`).
pub cursor: Option<(usize, usize)>,
/// The file whose header the pointer is over (`header-hovered`).
pub hovered_header: Option<usize>,
/// The active file's code editor with the focus is its original one (`_activeControl`), else its modified one.
pub original_focused: bool,
/// The file list's focused row, when it left the active file's (multiDiffEditorFileList.ts `setFocus`).
pub file_list_focus: Option<FileListRow>,
/// The file list tree's collapsed folders, relative to its root.
pub collapsed_folders: HashSet<PathBuf>,
/// The file and the unchanged region bar the pointer drags.
pub unchanged_drag: Option<(usize, UnchangedDrag)>,
}
/// A row of the file list: a file by its index, or a tree folder by its path relative to the tree's root.
#[derive(Clone, Debug, PartialEq)]
pub enum FileListRow {
File(usize),
Folder(PathBuf),
}
/// `DocumentDiffItemViewModel`: one file's sides (a missing one is an added or deleted file), where Open File goes,
/// whether it is collapsed, its diff and unchanged regions.
pub struct FileDiff {
pub original: Option<Side>,
pub modified: Option<Side>,
pub go_to_file: Option<Value>,
/// `goToFileEditorTitle`: the name Open File gives the editor it opens.
pub go_to_file_title: Option<String>,
pub collapsed: bool,
pub diff: Option<ComputedDiff>,
pub unchanged: Vec<UnchangedRegion>,
unchanged_key: Option<((u32, u32), usize, usize)>,
/// A side's model did not load (`isBinary`): the file shows the binary file placeholder.
pub unloadable: bool,
/// commentThreadFloatingWidgetRoom.ts: the space (original, modified) after each side's last line that makes the
/// side's editor tall enough for its floating comment widgets.
pub room: (f32, f32),
/// Each side's code editor (diffEditorItemTemplate.ts: the item's DiffEditorWidget), once its model is open.
pub original_editor: Option<OpenEditor>,
pub modified_editor: Option<OpenEditor>,
/// The view zones that align each side's editor with the rows, placed each frame.
pub placed_zones: (Vec<u32>, Vec<u32>),
/// The scroll top the list last gave both editors: one an editor moved since scrolls the list.
pub synced_scroll: f32,
/// findWidget.ts `_showViewZone`: the whitespace above line 1 (original, modified) of a side whose find widget shows.
pub find_space: (f32, f32),
/// The breadcrumbs source: the modified model's outline and the model version it was asked for.
pub symbols: Vec<OutlineSymbol>,
pub symbols_version: Option<u32>,
}
/// One row of a file's diff: lines of the original and modified models (0-based) drawn side by side, `None` where
/// the side has a fill (side by side) or nothing (inline: deleted lines have no modified line, inserted ones no
/// original), the placeholder of a hidden unchanged region, or the view zones that follow the row above: each side's
/// own below the line it names (0-based), the rest of `height` on either side a diagonal fill (`createFakeLinesDiv`);
/// `Top` is each side's own zones above line 1, the shorter side filled up to the taller.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Row {
Line { original: Option<usize>, modified: Option<usize> },
Hidden { region: usize, lines: usize },
Zones { original: Option<usize>, modified: Option<usize>, height: f32 },
Top { original: f32, modified: f32 },
}
impl Row {
pub fn height(&self, line_height: f32, placeholder_height: f32) -> f32 {
match self {
Row::Line { .. } => line_height,
Row::Hidden { .. } => placeholder_height,
Row::Zones { height, .. } => *height,
Row::Top { original, modified } => original.max(*modified),
}
}
}
impl MultiDiffInput {
pub fn new(source: Option<Side>, label: Option<String>, files: Vec<FileDiff>) -> Self {
MultiDiffInput { source, label, files, scroll_top: 0., view_height: Rc::default(), view_bounds: Rc::default(), body_width: Rc::default(), context_keys: Vec::new(), cursor: None, hovered_header: None, original_focused: false, file_list_focus: None, collapsed_folders: HashSet::new(), unchanged_drag: None }
}
/// `MultiDiffEditorInput` name: the label, else "Multi Diff Editor", with the file count.
pub fn name(&self) -> String {
let label = self.label.as_deref().unwrap_or("Multi Diff Editor");
match self.files.len() {
1 => format!("{label} (1 file)"),
count => format!("{label} ({count} files)"),
}
}
/// Whether a file shows `model`, which then stays open.
pub fn shows(&self, model: &OpenEditor) -> bool {
self.files.iter().flat_map(|file| [&file.original, &file.modified]).flatten().any(|side| model.document().is(&side.scheme, &side.path))
}
/// `multiDiffEditorAllCollapsed`.
pub fn all_collapsed(&self) -> bool {
self.files.iter().all(|file| file.collapsed)
}
/// `collapseAll` and `expandAll`.
pub fn set_all_collapsed(&mut self, collapsed: bool) {
for file in &mut self.files {
file.collapsed = collapsed;
}
}
/// Replaces the files when another open asks for other resources; the same ones keep their state.
/// multiDiffEditorInput.ts keys each item by its modified and original URIs: a file of the same sides keeps its
/// state, and the active file stays active while it is listed (`activeDiffItem`).
pub fn set_files(&mut self, files: Vec<FileDiff>) {
let active = self.cursor.map(|(file, line)| (self.files[file].original.clone(), self.files[file].modified.clone(), line));
let mut old = std::mem::take(&mut self.files);
for file in files {
let kept = old.iter().position(|old| old.original == file.original && old.modified == file.modified);
self.files.push(match kept {
Some(index) => old.swap_remove(index),
None => file,
});
}
self.cursor = active.and_then(|(original, modified, line)| Some((self.files.iter().position(|file| file.original == original && file.modified == modified)?, line)));
if self.cursor.is_none() {
self.original_focused = false;
}
self.hovered_header = None;
self.file_list_focus = None;
}
/// Puts the files in `order`, indexes into the current files, keeping the active file.
pub fn reorder(&mut self, order: &[usize]) {
let mut old: Vec<Option<FileDiff>> = std::mem::take(&mut self.files).into_iter().map(Some).collect();
self.files = order.iter().map(|&index| old[index].take().expect("each file once in the order")).collect();
self.cursor = self.cursor.map(|(file, line)| (order.iter().position(|&index| index == file).expect("every file is in the order"), line));
self.hovered_header = None;
self.file_list_focus = None;
}
/// The code editor with the focus: the active file's original or modified one.
pub fn focused_editor(&self) -> Option<&OpenEditor> {
let side = if self.original_focused { ZoneSide::Original } else { ZoneSide::Modified };
self.files.get(self.cursor?.0)?.editor(side)
}
pub fn focused_editor_mut(&mut self) -> Option<&mut OpenEditor> {
let side = if self.original_focused { ZoneSide::Original } else { ZoneSide::Modified };
self.files.get_mut(self.cursor?.0)?.editor_mut(side)
}
/// The file and side whose code editor is `model_id`.
pub fn side_of(&self, model_id: u32) -> Option<(usize, ZoneSide)> {
self.files.iter().enumerate().find_map(|(index, file)| {
[ZoneSide::Original, ZoneSide::Modified].into_iter().find(|side| file.editor(*side).is_some_and(|editor| editor.model_id == model_id)).map(|side| (index, side))
})
}
pub fn editors(&self) -> impl Iterator<Item = &OpenEditor> {
self.files.iter().flat_map(|file| [&file.original_editor, &file.modified_editor]).flatten()
}
pub fn editors_mut(&mut self) -> impl Iterator<Item = &mut OpenEditor> {
self.files.iter_mut().flat_map(|file| [file.original_editor.as_mut(), file.modified_editor.as_mut()]).flatten()
}
/// mainThreadEditorTabs.ts `_buildTabObject` of a `MultiDiffEditorInput`: its files with both sides as
/// `TextDiffInput`s, its resource the multi diff source.
pub fn tab_dto(&self, group: u32, entry: &OpenEditor, active: bool) -> Value {
let resource = match &self.source {
Some(source) => uri_string(&source.scheme, &source.path),
None => entry.document().uri_string(),
};
let uri = |side: &Side| uri_value(&side.scheme, &side.path);
let diff_editors: Vec<Value> = self
.files
.iter()
.filter_map(|file| Some(json!({ "kind": 2, "original": uri(file.original.as_ref()?), "modified": uri(file.modified.as_ref()?) })))
.collect();
json!({
"id": format!("{group}~default-workbench.input.multiDiffEditor-{resource} "),
"label": self.name(),
"input": { "kind": 11, "diffEditors": diff_editors },
"editorId": "default",
"isActive": active,
"isPinned": false,
"isPreview": entry.preview,
"isDirty": false,
})
}
}
impl MultiDiffInput {
/// multiDiffEditorWidgetImpl.ts `_navigateToChange`: the next (or previous) change of the active file after (before)
/// the cursor, else the first (last) change of the next (previous) file, wrapping; without an active file the first
/// file. The target file expands and its line is revealed; returns the file and its change's line, none without one.
pub fn navigate(&mut self, next: bool) -> Option<(usize, Option<usize>)> {
let count = self.files.len();
if count == 0 {
return None;
}
let target = match self.cursor {
None => (0, self.files[0].edge_change(true)),
Some((index, line)) => {
let changes = self.files[index].modified_changes();
let within = match next {
true => changes.iter().find(|range| range.start > line),
false => changes.iter().rev().find(|range| range.end <= line && range.start < line),
};
match within {
Some(range) => (index, Some(range.start)),
None => {
let other = if next { (index + 1) % count } else { (index + count - 1) % count };
(other, self.files[other].edge_change(next))
}
}
}
};
self.reveal(target.0, target.1);
Some(target)
}
/// Makes `file` the active one with its cursor on `line` (the first line without one), expanded and the line
/// out of any hidden region.
pub fn reveal(&mut self, file: usize, line: Option<usize>) {
let line = line.unwrap_or(1);
let target = &mut self.files[file];
target.collapsed = false;
if let Some(region) = target.unchanged.iter_mut().find(|region| region.hidden_modified().contains(line)) {
region.show_modified_line(line, crate::diff_editor::unchanged_regions::RevealPreference::FromCloserSide);
}
if let Some(editor) = target.modified_editor.as_mut() {
editor.set_selections(vec![Selection::caret(Position::new(line - 1, 0))]);
}
self.cursor = Some((file, line));
self.original_focused = false;
self.file_list_focus = None;
}
/// A press in a file side's code editor makes it the active control (`_activeControl`).
pub fn focus(&mut self, file: usize, side: ZoneSide) {
let line = self.files[file].modified_editor.as_ref().map_or(1, |editor| editor.selection().head.line + 1);
self.cursor = Some((file, line));
self.original_focused = side == ZoneSide::Original;
}
}
/// multiDiffEditorWidgetImpl.ts sticky header: the header's top in the list, at the viewport's top while the file
/// scrolls under it, pushed up by the file's end.
pub fn sticky_header_top(file_top: f32, file_height: f32, scroll_top: f32) -> f32 {
file_top + (scroll_top - file_top).clamp(0., (file_height - HEADER_HEIGHT).max(0.))
}
impl FileDiff {
pub fn new(original: Option<Side>, modified: Option<Side>, go_to_file: Option<Value>) -> Self {
FileDiff { original, modified, go_to_file, go_to_file_title: None, collapsed: false, diff: None, unchanged: Vec::new(), unchanged_key: None, unloadable: false, room: (0., 0.), original_editor: None, modified_editor: None, placed_zones: (Vec::new(), Vec::new()), synced_scroll: 0., find_space: (0., 0.), symbols: Vec::new(), symbols_version: None }
}
pub fn editor(&self, side: ZoneSide) -> Option<&OpenEditor> {
match side {
ZoneSide::Original => self.original_editor.as_ref(),
ZoneSide::Modified => self.modified_editor.as_ref(),
}
}
pub fn editor_mut(&mut self, side: ZoneSide) -> Option<&mut OpenEditor> {
match side {
ZoneSide::Original => self.original_editor.as_mut(),
ZoneSide::Modified => self.modified_editor.as_mut(),
}
}
/// A side editor's own view zones (comment threads, the find widget's space), without the ones `side_layout`
/// placed, as `additional_heights`.
pub fn own_zones(&self, side: ZoneSide) -> Vec<(usize, f32)> {
let Some(editor) = self.editor(side) else { return Vec::new() };
let (placed, find_space) = match side {
ZoneSide::Original => (&self.placed_zones.0, self.find_space.0),
ZoneSide::Modified => (&self.placed_zones.1, self.find_space.1),
};
let own = editor.view_zones.iter().zip(editor.view_zones_after_lines()).filter(|(zone, _)| !placed.contains(&zone.id));
let find = (find_space > 0.).then_some((0, find_space));
additional_heights(own.map(|(_, after)| after).chain(find))
}
/// Takes the placed zones and hidden lines back out of both side editors.
pub fn clear_layout(&mut self) {
for (editor, placed) in [(self.original_editor.as_mut(), &mut self.placed_zones.0), (self.modified_editor.as_mut(), &mut self.placed_zones.1)] {
let Some(editor) = editor else { continue };
for id in placed.drain(..) {
editor.remove_view_zone(id);
}
editor.folding.set_hidden_areas(Vec::new());
}
}
/// Places `side_layout` in `side`'s editor.
pub fn place_layout(&mut self, side: ZoneSide, rows: &[Row], line_height: f32, placeholder_height: f32) {
let (zones, hidden) = self.side_layout(rows, side, &self.own_zones(side), line_height, placeholder_height);
let (editor, placed) = match side {
ZoneSide::Original => (self.original_editor.as_mut(), &mut self.placed_zones.0),
ZoneSide::Modified => (self.modified_editor.as_mut(), &mut self.placed_zones.1),
};
let Some(editor) = editor else { return };
editor.folding.set_hidden_areas(hidden);
for (after, height) in zones {
placed.push(editor.add_view_zone(after.checked_sub(1).map(|line| Position::new(line, 0)), height));
}
}
/// diffEditorViewZones.ts and hideUnchangedRegionsFeature.ts for one side's editor of the file: the view zones
/// (after 1-based line, height) and hidden 0-based lines that draw each of its lines at its row. The rows where
/// the side has no line (the other side's lines, fills, placeholders, room) become whitespace; `own_zones` stay.
pub fn side_layout(&self, rows: &[Row], side: ZoneSide, own_zones: &[(usize, f32)], line_height: f32, placeholder_height: f32) -> (Vec<(usize, f32)>, Vec<std::ops::Range<usize>>) {
let pick = |original: Option<usize>, modified: Option<usize>| if side == ZoneSide::Original { original } else { modified };
let mut zones: Vec<(usize, f32)> = Vec::new();
let mut hidden = Vec::new();
let mut after = 0;
for row in rows {
let gap = match *row {
Row::Line { original, modified } => match pick(original, modified) {
Some(line) => {
after = line + 1;
continue;
}
None => line_height,
},
Row::Hidden { region, .. } => {
let region = &self.unchanged[region];
let range = if side == ZoneSide::Original { region.hidden_original() } else { region.hidden_modified() };
hidden.push(range.start - 1..range.end - 1);
placeholder_height
}
// A hidden last line's zones do not show (`showInHiddenAreas` false), only its room does.
Row::Zones { original, modified, height } => match pick(original, modified).filter(|line| line + 1 == after) {
Some(_) => height - own_zones.iter().find(|zone| zone.0 == after).map_or(0., |zone| zone.1),
None => height,
},
Row::Top { original, modified } => original.max(modified) - if side == ZoneSide::Original { original } else { modified },
};
match zones.last_mut() {
Some(last) if last.0 == after => last.1 += gap,
_ if gap > 0. => zones.push((after, gap)),
_ => {}
}
}
(zones, hidden)
}
/// The modified ranges of the changes, 1-based.
fn modified_changes(&self) -> Vec<LineRange> {
self.diff.as_ref().map_or(Vec::new(), |diff| diff.diff.changes.iter().map(|change| change.modified).collect())
}
/// The first (or last) change's modified line.
fn edge_change(&self, first: bool) -> Option<usize> {
let changes = self.modified_changes();
let change = if first { changes.first() } else { changes.last() };
change.map(|range| range.start)
}
/// The modified file's name and folder, else the original's (diffEditorItemTemplate.ts `setUri`).
pub fn label_side(&self) -> Option<&Side> {
self.modified.as_ref().or(self.original.as_ref())
}
/// diffEditorItemTemplate.ts status flag: `R` renamed, `D` deleted, `A` added.
pub fn status(&self) -> Option<&'static str> {
match (&self.original, &self.modified) {
(Some(original), Some(modified)) if split_query(&original.scheme, &original.path).0 != split_query(&modified.scheme, &modified.path).0 => Some("R"),
(Some(_), None) => Some("D"),
(None, Some(_)) => Some("A"),
_ => None,
}
}
/// Recomputes the diff when either side's version or an option changed, then the unchanged regions
/// (`min_hidden` and `min_context` lines) of a new diff. Each side is its lines and version.
pub fn update(&mut self, original: (&[String], u32), modified: (&[String], u32), options: DiffOptions, min_hidden: usize, min_context: usize) {
let versions = (original.1, modified.1);
let key = (options.ignore_trim_whitespace, options.max_computation_time_ms, options.compute_moves);
if !self.diff.as_ref().is_some_and(|diff| diff.versions == versions && diff.options == key) {
let diff = diff::compute_diff(original.0, modified.0, options);
self.diff = Some(ComputedDiff { versions, options: key, diff });
}
let unchanged_key = (versions, min_hidden, min_context);
if self.unchanged_key == Some(unchanged_key) {
return;
}
let changes = &self.diff.as_ref().expect("computed above").diff.changes;
let (original_count, modified_count) = (original.0.len(), modified.0.len());
self.unchanged = UnchangedRegion::from_diffs(changes, original_count, modified_count, min_hidden, min_context);
// hideUnchangedRegionsFeature.ts: one region covering the whole modified model (no change) shows nothing.
if let [only] = self.unchanged[..]
&& only.modified_line == 1
&& only.line_count == modified_count
{
self.unchanged.clear();
}
self.unchanged_key = Some(unchanged_key);
}
/// The rows of the diff: side by side each changed stretch of `range_alignment` with the shorter side filled,
/// inline each change's deleted lines above its inserted ones; the unchanged lines between, hidden regions as
/// one placeholder row each. Each side's view zones (`additional_heights`) follow their line's row; a hidden line's
/// are not shown (`showInHiddenAreas` false). Each side's `room` follows its last line, hidden or not.
pub fn rows(&self, original_lines: &[String], modified_count: usize, side_by_side: bool, original_zones: &[(usize, f32)], modified_zones: &[(usize, f32)]) -> Vec<Row> {
let mut rows = Vec::new();
let last = (original_lines.len().checked_sub(1), modified_count.checked_sub(1));
let mut room_left = self.room;
let above_first = |zones: &[(usize, f32)]| zones.first().filter(|zone| zone.0 == 0).map_or(0., |zone| zone.1);
let top = (above_first(original_zones), above_first(modified_zones));
if top.0 > 0. || top.1 > 0. {
rows.push(Row::Top { original: top.0, modified: top.1 });
}
let zones_after = |zones: &[(usize, f32)], line: Option<usize>, last: Option<usize>, room: &mut f32| {
let zones = line.and_then(|line| zones.iter().find(|zone| zone.0 == line + 1)).map_or(0., |zone| zone.1);
match line.is_some() && line == last {
true => zones + std::mem::take(room),
false => zones,
}
};
for row in self.line_rows(original_lines, modified_count, side_by_side) {
rows.push(row);
let Row::Line { original, modified } = row else { continue };
let original_height = zones_after(original_zones, original, last.0, &mut room_left.0);
let modified_height = zones_after(modified_zones, modified, last.1, &mut room_left.1);
if original_height > 0. || modified_height > 0. {
let original = original.filter(|_| original_height > 0.);
let modified = modified.filter(|_| modified_height > 0.);
rows.push(Row::Zones { original, modified, height: original_height.max(modified_height) });
}
}
if room_left.0 > 0. || room_left.1 > 0. {
rows.push(Row::Zones { original: last.0.filter(|_| room_left.0 > 0.), modified: last.1.filter(|_| room_left.1 > 0.), height: room_left.0.max(room_left.1) });
}
rows
}
fn line_rows(&self, original_lines: &[String], modified_count: usize, side_by_side: bool) -> Vec<Row> {
let Some(computed) = &self.diff else { return Vec::new() };
let mut rows = Vec::new();
let (mut original, mut modified) = (1, 1);
for stretch in range_alignment(&computed.diff, original_lines, side_by_side, &[], &[], 1.) {
self.push_unchanged(&mut rows, original, modified, stretch.modified.start - modified);
let (original_len, modified_len) = (stretch.original.len(), stretch.modified.len());
let line = |range: LineRange, offset: usize| (offset < range.len()).then_some(range.start - 1 + offset);
if side_by_side {
for offset in 0..original_len.max(modified_len) {
rows.push(Row::Line { original: line(stretch.original, offset), modified: line(stretch.modified, offset) });
}
} else {
rows.extend((0..original_len).map(|offset| Row::Line { original: line(stretch.original, offset), modified: None }));
rows.extend((0..modified_len).map(|offset| Row::Line { original: None, modified: line(stretch.modified, offset) }));
}
(original, modified) = (stretch.original.end, stretch.modified.end);
}
self.push_unchanged(&mut rows, original, modified, (modified_count + 1).saturating_sub(modified));
rows
}
/// `count` unchanged lines from 1-based `original` and `modified`, a hidden region's lines as its placeholder.
fn push_unchanged(&self, rows: &mut Vec<Row>, original: usize, modified: usize, count: usize) {
let mut offset = 0;
while offset < count {
let line = modified + offset;
let hidden = self.unchanged.iter().enumerate().filter(|(_, region)| !region.is_fully_revealed()).find(|(_, region)| region.hidden_modified().start == line);
if let Some((region, hidden)) = hidden {
let lines = hidden.hidden_modified().len();
rows.push(Row::Hidden { region, lines });
offset += lines;
continue;
}
rows.push(Row::Line { original: Some(original - 1 + offset), modified: Some(line - 1) });
offset += 1;
}
}
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use super::*;
fn lines(text: &str) -> Vec<String> {
text.split('\n').map(str::to_string).collect()
}
fn side(path: &str) -> Option<Side> {
Some(Side { scheme: "file".into(), path: PathBuf::from(path) })
}
fn computed(original: &[String], modified: &[String]) -> FileDiff {
let mut file = FileDiff::new(side("/a.txt"), side("/a.txt"), None);
file.update((original, 1), (modified, 1), DiffOptions::default(), 3, 3);
file
}
fn line(original: Option<usize>, modified: Option<usize>) -> Row {
Row::Line { original, modified }
}
#[test]
fn side_by_side_fills_the_shorter_side_and_inline_stacks_deleted_over_inserted() {
let (original, modified) = (lines("a\nb\nc"), lines("a\nB\nx\nc"));
let file = computed(&original, &modified);
assert_eq!(file.rows(&original, modified.len(), true, &[], &[]), vec![line(Some(0), Some(0)), line(Some(1), Some(1)), line(None, Some(2)), line(Some(2), Some(3))]);
assert_eq!(file.rows(&original, modified.len(), false, &[], &[]), vec![line(Some(0), Some(0)), line(Some(1), None), line(None, Some(1)), line(None, Some(2)), line(Some(2), Some(3))]);
}
#[test]
fn unchanged_regions_hide_behind_one_row_until_revealed() {
let original: Vec<String> = (1..=20).map(|line| format!("line {line}")).collect();
let mut modified = original.clone();
modified[9] = "changed".into();
let mut file = computed(&original, &modified);
let rows = file.rows(&original, modified.len(), true, &[], &[]);
// Lines 1-6 and 14-20 hide, 3 context lines on each side of line 10.
assert_eq!(rows[0], Row::Hidden { region: 0, lines: 6 });
assert_eq!(rows[1], line(Some(6), Some(6)));
assert_eq!(rows[8], Row::Hidden { region: 1, lines: 7 });
assert_eq!(rows.len(), 9);
file.unchanged[0].show_all();
assert_eq!(file.rows(&original, modified.len(), true, &[], &[]).len(), 14);
}
#[test]
fn view_zones_follow_their_line_and_leave_the_rest_to_the_fill() {
let (original, modified) = (lines("a\nb\nc"), lines("a\nB\nx\nc"));
let file = computed(&original, &modified);
let rows = file.rows(&original, modified.len(), true, &[(2, 30.)], &[(2, 50.), (3, 10.)]);
assert_eq!(rows[2], Row::Zones { original: Some(1), modified: Some(1), height: 50. });
assert_eq!(rows[4], Row::Zones { original: None, modified: Some(2), height: 10. });
// Inline, the original has no comments controller (`isEditorInlineOriginal`).
let rows = file.rows(&original, modified.len(), false, &[], &[(2, 50.)]);
assert_eq!(rows[3], Row::Zones { original: None, modified: Some(1), height: 50. });
}
#[test]
fn the_room_follows_the_last_line_even_when_it_hides() {
let (original, modified) = (lines("a\nb\nc"), lines("a\nB\nx\nc"));
let mut file = computed(&original, &modified);
file.room = (20., 40.);
let rows = file.rows(&original, modified.len(), true, &[], &[(4, 30.)]);
assert_eq!(rows.last(), Some(&Row::Zones { original: Some(2), modified: Some(3), height: 70. }));
let original: Vec<String> = (1..=20).map(|line| format!("line {line}")).collect();
let mut modified = original.clone();
modified[9] = "changed".into();
let mut file = computed(&original, &modified);
file.room = (0., 40.);
let rows = file.rows(&original, modified.len(), true, &[], &[]);
assert_eq!(rows[rows.len() - 2..], [Row::Hidden { region: 1, lines: 7 }, Row::Zones { original: None, modified: Some(19), height: 40. }]);
}
#[test]
fn an_added_file_diffs_against_an_empty_model() {
let modified = lines("one\ntwo");
let mut file = FileDiff::new(None, side("/new.txt"), None);
file.update((&EMPTY_MODEL, 0), (&modified, 1), DiffOptions::default(), 3, 3);
assert_eq!(file.status(), Some("A"));
assert_eq!(file.rows(&EMPTY_MODEL, modified.len(), true, &[], &[]), vec![line(Some(0), Some(0)), line(None, Some(1))]);
}
#[test]
fn each_side_editor_gets_whitespace_where_its_side_has_no_line() {
let (original, modified) = (lines("a\nb\nc"), lines("a\nB\nx\nc"));
let file = computed(&original, &modified);
let rows = file.rows(&original, modified.len(), true, &[], &[]);
assert_eq!(file.side_layout(&rows, ZoneSide::Original, &[], 18., 24.), (vec![(2, 18.)], vec![]));
assert_eq!(file.side_layout(&rows, ZoneSide::Modified, &[], 18., 24.), (vec![], vec![]));
// Inline the deleted line is whitespace in the modified editor.
let rows = file.rows(&original, modified.len(), false, &[], &[]);
assert_eq!(file.side_layout(&rows, ZoneSide::Modified, &[], 18., 24.), (vec![(1, 18.)], vec![]));
// A comment zone of 50 below modified line 2 stays; the original fills it with 50 less its own 30.
let rows = file.rows(&original, modified.len(), true, &[(2, 30.)], &[(2, 50.)]);
assert_eq!(file.side_layout(&rows, ZoneSide::Modified, &[(2, 50.)], 18., 24.), (vec![], vec![]));
assert_eq!(file.side_layout(&rows, ZoneSide::Original, &[(2, 30.)], 18., 24.), (vec![(2, 38.)], vec![]));
}
#[test]
fn a_hidden_region_folds_its_lines_behind_the_placeholder() {
let original: Vec<String> = (1..=20).map(|line| format!("line {line}")).collect();
let mut modified = original.clone();
modified[9] = "changed".into();
let file = computed(&original, &modified);
let rows = file.rows(&original, modified.len(), true, &[], &[]);
assert_eq!(file.side_layout(&rows, ZoneSide::Modified, &[], 18., 24.), (vec![(0, 24.), (13, 24.)], vec![0..6, 13..20]));
}
#[test]
fn name_counts_files_and_collapse_all_flips_every_file() {
let mut input = MultiDiffInput::new(None, Some("Changes".into()), vec![FileDiff::new(side("/a"), side("/a"), None)]);
assert_eq!(input.name(), "Changes (1 file)");
input.files.push(FileDiff::new(side("/b"), None, None));
assert_eq!(input.name(), "Changes (2 files)");
assert_eq!(input.files[1].status(), Some("D"));
input.set_all_collapsed(true);
assert!(input.all_collapsed());
input.files[0].collapsed = false;
assert!(!input.all_collapsed());
}
#[test]
fn navigation_walks_the_changes_then_the_next_file_and_wraps() {
let original: Vec<String> = (1..=20).map(|line| format!("line {line}")).collect();
let mut modified = original.clone();
modified[1] = "two".into();
modified[17] = "eighteen".into();
let mut input = MultiDiffInput::new(None, None, vec![computed(&original, &modified), computed(&original, &modified)]);
input.files[1].collapsed = true;
assert_eq!(input.navigate(true), Some((0, Some(2))));
// Line 18 sits in no hidden region: 3 context lines after line 2 and before 18 hide lines 6-14.
assert_eq!(input.navigate(true), Some((0, Some(18))));
assert_eq!(input.navigate(true), Some((1, Some(2))));
assert!(!input.files[1].collapsed);
assert_eq!(input.navigate(false), Some((0, Some(18))));
assert_eq!(input.navigate(false), Some((0, Some(2))));
assert_eq!(input.navigate(false), Some((1, Some(18))));
input.reveal(0, Some(10));
assert!(input.files[0].unchanged.iter().all(|region| !region.hidden_modified().contains(10)));
}
#[test]
fn the_header_sticks_to_the_viewport_top_within_its_file() {
assert_eq!(sticky_header_top(100., 300., 0.), 100.);
assert_eq!(sticky_header_top(100., 300., 150.), 150.);
assert_eq!(sticky_header_top(100., 300., 1000.), 368.);
}
}