Visual Studio Code, rebuilt in Rust
Rust
use serde_json::{Value, json};
use super::*;
fn file_uri(path: &str) -> Value {
json!({ "$mid": 1, "scheme": "file", "authority": "", "path": path, "query": "", "fragment": "" })
}
fn code_cell(source: &str) -> Value {
json!({ "cellKind": CODE, "language": "typescript", "source": source, "outputs": [], "metadata": {} })
}
fn notebook(sources: &[&str]) -> NotebookModel {
let cells: Vec<Value> = sources.iter().map(|source| code_cell(source)).collect();
NotebookModel::new(file_uri("/w/a.nb"), "test", &json!({ "metadata": {}, "cells": cells }), json!({})).0
}
fn texts(model: &NotebookModel, all: &[NewCellText]) -> Vec<String> {
model.cells.iter().map(|cell| all.iter().find(|text| text.uri == cell.uri).expect("created").source.clone()).collect()
}
#[test]
fn cell_uris_encode_the_handle_in_base_7_and_the_scheme() {
let uri = cell_uri(&file_uri("/w/a.nb"), 0);
assert_eq!(uri["scheme"], CELL_SCHEME);
assert_eq!(uri["fragment"], "W0sZmlsZQ==");
assert_eq!(cell_uri(&file_uri("/w/a.nb"), 7)["fragment"], "X10sZmlsZQ==");
assert_eq!(parse_cell_uri(&cell_uri(&file_uri("/w/a.nb"), 50)), Some((file_uri("/w/a.nb"), 50)));
}
#[test]
fn edits_apply_from_the_last_index_and_send_one_event() {
let (mut model, mut created) = {
let cells = vec![code_cell("a"), code_cell("b"), code_cell("c")];
NotebookModel::new(file_uri("/w/a.nb"), "test", &json!({ "cells": cells }), json!({}))
};
let edits = [json!({ "editType": 1, "index": 0, "count": 1, "cells": [] }), json!({ "editType": 1, "index": 2, "count": 1, "cells": [] })];
let applied = model.apply_edits(&edits).unwrap();
created.extend(applied.added);
assert_eq!(texts(&model, &created), ["b"]);
assert_eq!(applied.removed.len(), 2);
let event = applied.event.unwrap();
assert_eq!(event["versionId"], 1);
assert_eq!(event["rawEvents"][0]["changes"][0][0], 2);
assert_eq!(event["rawEvents"][1]["changes"][0][0], 0);
assert!(model.dirty);
}
#[test]
fn inserted_cells_get_new_handles_and_their_text() {
let mut model = notebook(&["a"]);
let applied = model.apply_edits(&[json!({ "editType": 1, "index": 0, "count": 0, "cells": [code_cell("x"), code_cell("y")] })]).unwrap();
assert_eq!(model.cells.iter().map(|cell| cell.handle).collect::<Vec<_>>(), [1, 2, 0]);
assert_eq!(applied.added.iter().map(|text| text.source.as_str()).collect::<Vec<_>>(), ["x", "y"]);
let dto = &applied.event.unwrap()["rawEvents"][0]["changes"][0][2][0];
assert_eq!(dto["source"], json!(["x"]));
assert_eq!(dto["handle"], 1);
}
#[test]
fn transient_changes_leave_the_notebook_clean() {
let cells = vec![code_cell("a")];
let (mut model, _) = NotebookModel::new(file_uri("/w/a.nb"), "test", &json!({ "cells": cells }), json!({ "transientOutputs": true, "transientCellMetadata": { "trusted": true } }));
let output = json!({ "outputId": "o1", "items": [{ "mime": "text/plain", "valueBytes": [104, 105] }] });
let applied = model.apply_edits(&[json!({ "editType": 2, "index": 0, "outputs": [output] })]).unwrap();
assert_eq!(applied.event.unwrap()["rawEvents"][0]["outputs"][0]["items"][0]["valueBytes"], json!({ "$vsbuffer": "aGk=" }));
model.apply_edits(&[json!({ "editType": 8, "index": 0, "metadata": { "trusted": true } })]).unwrap();
model.apply_edits(&[json!({ "editType": 9, "handle": 0, "internalMetadata": { "executionOrder": 1 } })]).unwrap();
assert!(!model.dirty);
assert_eq!(model.version_id, 3);
model.apply_edits(&[json!({ "editType": 8, "index": 0, "metadata": { "inputCollapsed": true } })]).unwrap();
assert!(model.dirty);
assert_eq!(model.cells[0].metadata, json!({ "trusted": true, "inputCollapsed": true }));
}
#[test]
fn output_items_find_their_cell_by_output_id() {
let mut model = notebook(&["a", "b"]);
let output = json!({ "outputId": "o1", "items": [{ "mime": "text/plain", "valueBytes": [1] }] });
model.apply_edits(&[json!({ "editType": 2, "handle": 1, "outputs": [output] })]).unwrap();
let item = json!({ "mime": "text/plain", "valueBytes": { "$vsbuffer": "Ag==" } });
let applied = model.apply_edits(&[json!({ "editType": 7, "outputId": "o1", "append": true, "items": [item] })]).unwrap();
assert_eq!(model.cells[1].outputs[0].items.iter().map(|item| item.data.clone()).collect::<Vec<_>>(), [vec![1], vec![2]]);
assert_eq!(applied.event.unwrap()["rawEvents"][0]["index"], 1);
// An output no cell has any more drops the edit.
let applied = model.apply_edits(&[json!({ "editType": 7, "outputId": "gone", "items": [] })]).unwrap();
assert!(applied.event.is_none());
}
#[test]
fn snapshots_leave_out_transient_metadata() {
let cells = vec![json!({ "cellKind": CODE, "language": "python", "source": "x", "outputs": [], "metadata": { "keep": 1, "drop": 2 } })];
let (model, _) = NotebookModel::new(file_uri("/w/a.nb"), "test", &json!({ "cells": cells, "metadata": { "doc": 1 } }), json!({ "transientCellMetadata": { "drop": true } }));
let snapshot = model.snapshot(|_| "x2".into());
assert_eq!(snapshot["cells"][0]["metadata"], json!({ "keep": 1 }));
assert_eq!(snapshot["cells"][0]["source"], "x2");
assert_eq!(snapshot["metadata"], json!({ "doc": 1 }));
}
/// notebookCommon.test.ts "Notebook stream compression".
const STREAM_CASES: [(&str, &str); 22] = [
("", ""),
("plain\ntext", "plain\ntext"),
("abcdef\rxy", "xycdef"),
("abcdef\rxy\rz", "zycdef"),
("xy\rlonger\rz", "zonger"),
("abc\r", "abc\r"),
("abc\r\r", "abc"),
("abc\r\r\r", "abc"),
("abcdef\rxy\r", "xycdef\r"),
("abc\r\n", "abc\n"),
("abc\r\r\n", "abc\n"),
("abc\rx\ndef\ry", "xbc\nyef"),
("abc\u{2028}def\rx\u{2029}ghi\ry", "abc\u{2028}xef\u{2029}yhi"),
("\u{6f22}\u{5b57}\rX", "X\u{5b57}"),
("\u{1f600}xyz\rA", "A\u{fffd}xyz"),
("abc\x08\x08X\rY", "YX"),
("a\n\x08", "a\n\x08"),
("abc\r\x08X", "abcX"),
("$$\r\r", "$"),
("abc\r$xy", "abc\r$xy"),
("abc\r$xy\nq\rr", "$xy\nr"),
("price $5\nabcdef\rxy", "price $5\nxycdef"),
];
#[test]
fn stream_compression_preserves_overwrite_line_ending_backspace_unicode_and_dollar_semantics() {
for (input, expected) in STREAM_CASES {
assert_eq!(String::from_utf8(compress_output_item_streams(vec![input.as_bytes().to_vec()])).unwrap(), expected, "{input:?}");
}
}
#[test]
fn stream_compression_preserves_normalization_when_input_is_split_across_byte_buffers() {
for (input, expected) in STREAM_CASES {
let bytes = input.as_bytes();
for index in 0..=bytes.len() {
let result = compress_output_item_streams(vec![bytes[..index].to_vec(), bytes[index..].to_vec()]);
assert_eq!(String::from_utf8(result).unwrap(), expected, "{input:?} split at {index}");
}
}
}
#[test]
fn stream_compression_combines_thousands_of_carriage_return_segments_on_one_line() {
let input = format!("abcdefghijklmnop{}\n", "\r01234567\rxy\rz".repeat(4000));
assert_eq!(compress_output_item_streams(vec![input.into_bytes()]), b"zy234567ijklmnop\n");
}
#[test]
fn a_stream_moving_the_cursor_up_replaces_the_previous_last_line() {
assert_eq!(compress_output_item_streams(vec![b"1\n2\n".to_vec(), b"\x1b[A3\n".to_vec()]), b"1\n23\n");
assert_eq!(compress_output_item_streams(vec![b"no line feed".to_vec(), b"\x1b[Ax".to_vec()]), b"no line feed\x1b[Ax");
}
/// markupCell.ts creates a markup cell's editor in edit mode and disposes it with the row; a code template keeps
/// its model after the row leaves, until listView.ts gives it to the next row, the last new row first.
#[test]
fn cell_list_editors_follow_the_rendered_rows() {
let mut list = CellList::default();
assert!(list.render(&[(1, true, false), (2, false, false), (3, true, false)]));
assert!(list.has_editor(1) && !list.has_editor(2) && list.has_editor(3));
assert!(list.render(&[(2, false, true), (3, true, false)]));
assert!(list.has_editor(1) && list.has_editor(2), "a released template keeps cell 1, markup 2 edits");
assert!(!list.render(&[(2, false, true), (3, true, false)]), "the same rows change no editor");
assert!(list.render(&[(4, true, false), (5, true, false)]));
assert!(!list.has_editor(1) && !list.has_editor(2) && !list.has_editor(3) && list.has_editor(4) && list.has_editor(5));
}