use serde_json::json;
use crate::buffer::text_utils::char_to_byte_index;
use crate::canvas_editor::lsp::{LspPosition, LspTextChange};
pub(super) struct TextModel {
lines: Vec<String>,
}
impl TextModel {
pub(super) fn from_text(text: &str) -> Self {
let lines = if text.is_empty() {
vec![String::new()]
} else {
text.lines().map(String::from).collect()
};
Self { lines }
}
fn apply_change(&mut self, change: &LspTextChange) -> bool {
let start_line = change.range.start.line as usize;
let end_line = change.range.end.line as usize;
if start_line >= self.lines.len() || end_line >= self.lines.len() {
return false;
}
let start_col = change.range.start.character as usize;
let end_col = change.range.end.character as usize;
let start_byte = char_to_byte_index(&self.lines[start_line], start_col);
let end_byte = char_to_byte_index(&self.lines[end_line], end_col);
let prefix = self.lines[start_line][..start_byte].to_string();
let suffix = self.lines[end_line][end_byte..].to_string();
let inserted: Vec<&str> = change.text.split('\n').collect();
let mut replacement: Vec<String> = Vec::new();
if inserted.len() == 1 {
replacement.push(format!("{}{}{}", prefix, inserted[0], suffix));
} else {
replacement.push(format!("{}{}", prefix, inserted[0]));
for mid in inserted.iter().take(inserted.len() - 1).skip(1) {
replacement.push((*mid).to_string());
}
replacement.push(format!(
"{}{}",
inserted[inserted.len() - 1],
suffix
));
}
self.lines.splice(start_line..=end_line, replacement);
true
}
pub(super) fn to_utf16_position(
&self,
position: LspPosition,
) -> LspPosition {
let line_index = position.line as usize;
let char_index = position.character as usize;
let line = self.lines.get(line_index).map_or("", |l| l.as_str());
let utf16_col =
line.chars().take(char_index).map(|c| c.len_utf16() as u32).sum();
LspPosition { line: position.line, character: utf16_col }
}
}
pub(super) struct DocumentState {
pub(super) text: TextModel,
}
pub(super) fn apply_changes_to_document(
state: &mut DocumentState,
changes: &[LspTextChange],
) -> Option<Vec<serde_json::Value>> {
let mut out = Vec::with_capacity(changes.len());
for change in changes {
let start = state.text.to_utf16_position(change.range.start);
let end = state.text.to_utf16_position(change.range.end);
if !state.text.apply_change(change) {
return None;
}
out.push(json!({
"range": {
"start": { "line": start.line, "character": start.character },
"end": { "line": end.line, "character": end.character }
},
"text": change.text
}));
}
Some(out)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::canvas_editor::lsp::LspRange;
fn change(
start_line: u32,
start_char: u32,
end_line: u32,
end_char: u32,
text: &str,
) -> LspTextChange {
LspTextChange {
range: LspRange {
start: LspPosition { line: start_line, character: start_char },
end: LspPosition { line: end_line, character: end_char },
},
text: text.to_string(),
}
}
#[test]
fn test_text_model_apply_change_in_range_succeeds() {
let mut model = TextModel::from_text("hello\nworld");
let applied = model.apply_change(&change(0, 0, 0, 5, "goodbye"));
assert!(applied);
assert_eq!(
model.lines,
vec!["goodbye".to_string(), "world".to_string()]
);
}
#[test]
fn test_text_model_apply_change_out_of_range_line_fails_without_mutating() {
let mut model = TextModel::from_text("hello\nworld");
let original = model.lines.clone();
let applied = model.apply_change(&change(5, 0, 5, 0, "x"));
assert!(!applied);
assert_eq!(model.lines, original);
}
#[test]
#[allow(clippy::panic)]
fn test_apply_changes_to_document_converts_every_change() {
let mut state =
DocumentState { text: TextModel::from_text("hello\nworld") };
let changes =
vec![change(0, 0, 0, 5, "hi"), change(1, 0, 1, 5, "earth")];
let Some(out) = apply_changes_to_document(&mut state, &changes) else {
panic!("in-range changes must convert");
};
assert_eq!(out.len(), 2);
assert_eq!(out[0]["text"], "hi");
assert_eq!(out[1]["text"], "earth");
assert_eq!(
state.text.lines,
vec!["hi".to_string(), "earth".to_string()]
);
}
#[test]
fn test_apply_changes_to_document_stops_at_first_desync() {
let mut state = DocumentState { text: TextModel::from_text("hello") };
let changes =
vec![change(0, 0, 0, 5, "hi"), change(9, 0, 9, 0, "unreachable")];
let out = apply_changes_to_document(&mut state, &changes);
assert!(out.is_none());
assert_eq!(state.text.lines, vec!["hi".to_string()]);
}
}