//! What changed between two states of one record — the whole of history's//! reading half, and pure. The port of//! `packages/core/src/engine/history/diff.ts`.//!//! Two levels. [`diff_fields`] answers "which columns moved, and how" over an//! explicit column list; [`diff_words`] answers "which words moved" inside one//! of them, so a rewritten paragraph reads as the three words somebody actually//! changed rather than as a wall of red beside a wall of green.//!//! No library, deliberately. A diff is the sentence history tells about an//! edit, and the phone, the tests and anything that later reads the same trail//! must tell the same one; a dependency is a second opinion waiting to happen.use cotton_store::protocol::js::{is_js_whitespace, json_stringify, number_to_string};use serde::{Deserialize, Serialize};use serde_json::{Map, Value};/// A record snapshot as the trigger stored it — snake_case column names/// against whatever the column held.////// A `serde_json::Map`, not a `HashMap`: the workspace turns on serde_json's/// `preserve_order`, so a row deserialised here and serialised back out keeps/// the column order the file wrote, and a caller comparing two patches as text/// gets the same bytes on both sides of the port.pubtypeRecordRow = Map<String, Value>;#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]pubenumWordSpanKind { #[serde(rename = "same")]Same, #[serde(rename = "added")]Added, #[serde(rename = "removed")]Removed,}implWordSpanKind {pubconstfn as_str(self) -> &'static str {matchself {WordSpanKind::Same => "same",WordSpanKind::Added => "added",WordSpanKind::Removed => "removed", } }}impl std::fmt::DisplayforWordSpanKind {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.as_str()) }}/// A run of text, all of one kind. Adjacent runs are merged before returning.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pubstructWordSpan {pub kind: WordSpanKind,pub text: String,}implWordSpan {fn new(kind: WordSpanKind, text: implInto<String>) -> Self {WordSpan { kind, text: text.into(), } }}/// The largest middle [`diff_words`] will align token by token, per side.////// The alignment is an O(n·m) table, so an unbounded one is a frozen phone on/// somebody's longest note. The common head and tail are trimmed first — which/// is what an ordinary edit leaves — so this ceiling is only reached when two/// texts genuinely share neither end, and there the honest answer IS "this was/// replaced".const MAX_ALIGNED_TOKENS: usize = 600;/// Words and the whitespace between them, each as its own token — the JS/// `text.match(/\s+|\S+/g)`.////// The class is the ECMAScript `\s`, not Rust's `char::is_whitespace`: JS/// counts U+FEFF (the byte-order mark) as whitespace and does not count U+0085/// (NEL), and Rust's does the opposite. Both directions change where a word/// ends, so both are pinned by Node vector — `a<BOM>b` is three tokens and/// `a<NEL>b` is one.////// Grouping by `char` rather than by UTF-16 code unit is equivalent here: a JS/// regex sees an astral character as two surrogate code units, but both are/// `\S`, so they fall in the same run either way.fn tokenize(text: &str) -> Vec<&str> {letmut tokens = Vec::new();letmut start = 0usize;letmut current: Option<bool> = None;for (index, ch) in text.char_indices() {let space = is_js_whitespace(ch);match current {Some(kind) if kind == space => {}Some(_) => { tokens.push(&text[start..index]); start = index; }None => start = index, } current = Some(space); }if current.is_some() { tokens.push(&text[start..]); } tokens}fn span(kind: WordSpanKind, tokens: &[&str]) -> Vec<WordSpan> {if tokens.is_empty() {Vec::new() } else { vec![WordSpan::new(kind, tokens.concat())] }}/// Fold neighbouring runs of one kind together, so the renderer draws few.fn merge(spans: Vec<WordSpan>) -> Vec<WordSpan> {letmut out: Vec<WordSpan> = Vec::new();for next in spans {if next.text.is_empty() {continue; }match out.last_mut() {Some(last) if last.kind == next.kind => last.text.push_str(&next.text), _ => out.push(next), } } out}/// Align two token runs on their longest common subsequence.////// `lengths[i][j]` is the LCS of the two tails starting at i and j, so the walk/// runs FORWARDS from the head. That direction is the whole reason a word/// inserted before a repeat lands where a reader expects it: walking back from/// the tail would attach "the" in "call the plumber" to the far space and tint/// the plumber too.////// The table is `u16` because the TypeScript's is a `Uint16Array`, and it/// cannot overflow: the caller refuses a side longer than/// `MAX_ALIGNED_TOKENS` (600), so no LCS can reach 65536.fn align_tokens<'a>(before: &[&'a str], after: &[&'a str]) -> Vec<WordSpan> {let n = before.len();let m = after.len();let width = m + 1;letmut lengths = vec![0u16; (n + 1) * width];for i in (0..n).rev() {for j in (0..m).rev() { lengths[i * width + j] = if before[i] == after[j] { lengths[(i + 1) * width + j + 1] + 1 } else { lengths[(i + 1) * width + j].max(lengths[i * width + j + 1]) }; } }letmut out = Vec::new();letmut i = 0usize;letmut j = 0usize;while i < n && j < m {if before[i] == after[j] { out.push(WordSpan::new(WordSpanKind::Same, before[i])); i += 1; j += 1; } elseif lengths[(i + 1) * width + j] >= lengths[i * width + j + 1] { out.push(WordSpan::new(WordSpanKind::Removed, before[i])); i += 1; } else { out.push(WordSpan::new(WordSpanKind::Added, after[j])); j += 1; } } out.extend(span(WordSpanKind::Removed, &before[i..])); out.extend(span(WordSpanKind::Added, &after[j..])); out}/// `before` → `after` as tinted runs, word by word.////// Whitespace is a token of its own rather than part of a word, so a paragraph/// break inserted between two unchanged words tints the break and not the/// words. No normalisation of any kind happens first: `cafe` + a combining/// acute and a precomposed `café` are two different words here, and the vector/// that says so is deliberate — history reports what the bytes did.pubfn diff_words(before: &str, after: &str) -> Vec<WordSpan> {if before == after {returnif before.is_empty() {Vec::new() } else { vec![WordSpan::new(WordSpanKind::Same, before)] }; }if before.is_empty() {return vec![WordSpan::new(WordSpanKind::Added, after)]; }if after.is_empty() {return vec![WordSpan::new(WordSpanKind::Removed, before)]; }let a = tokenize(before);let b = tokenize(after);letmut head = 0usize;while head < a.len() && head < b.len() && a[head] == b[head] { head += 1; }letmut tail = 0usize;while tail < a.len() - head && tail < b.len() - head && a[a.len() - 1 - tail] == b[b.len() - 1 - tail] { tail += 1; }let mid_a = &a[head..a.len() - tail];let mid_b = &b[head..b.len() - tail];let middle = if mid_a.len() > MAX_ALIGNED_TOKENS || mid_b.len() > MAX_ALIGNED_TOKENS {letmut both = span(WordSpanKind::Removed, mid_a); both.extend(span(WordSpanKind::Added, mid_b)); both } else { align_tokens(mid_a, mid_b) };letmut spans = span(WordSpanKind::Same, &a[..head]); spans.extend(middle); spans.extend(span(WordSpanKind::Same, &a[a.len() - tail..])); merge(spans)}#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]pubenumFieldChangeKind { #[serde(rename = "added")]Added, #[serde(rename = "removed")]Removed, #[serde(rename = "changed")]Changed,}implFieldChangeKind {pubconstfn as_str(self) -> &'static str {matchself {FieldChangeKind::Added => "added",FieldChangeKind::Removed => "removed",FieldChangeKind::Changed => "changed", } }}impl std::fmt::DisplayforFieldChangeKind {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.as_str()) }}/// One column that moved, with both stored values as they stand.////// `before` and `after` are the raw `Value`s, not renderings: the screen picks/// how to draw them from the kind's [`super::fields::HistoryField::form`], and/// a diff that had already turned a number into a string would have made that/// choice for it.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pubstructFieldChange {pub column: String,pub change: FieldChangeKind,pub before: Value,pub after: Value,}/// Nothing there. Only absence and blank text count — `0` and `false` are/// values somebody chose, and calling a priority of zero "empty" would report a/// cleared flag as a removal and hide the number it came from.////// The blank test is the ECMAScript `String.prototype.trim`, so a body holding/// only a byte-order mark is empty and one holding only U+0085 is not. Rust's/// own `trim` answers the opposite on both; both are pinned by vector.fn is_empty(value: &Value) -> bool {match value {Value::Null => true,Value::String(text) => text.trim_matches(is_js_whitespace).is_empty(), _ => false, }}/// The TypeScript's `typeof value === "object" && value !== null`, which — and/// this is load-bearing rather than sloppy — is TRUE for an array as well as/// for an object. `same_value` sends both down the `stable_string` path, and/// `stable_string` tells them apart itself.fn is_plain_object(value: &Value) -> bool { matches!(value, Value::Object(_) | Value::Array(_))}/// Key order is not content, so a json column is compared with keys sorted.////// The sort is on UTF-16 code units, which is what JavaScript's `<` on strings/// compares — Rust's `&str` ordering is by code POINT, and the two disagree/// once an astral key meets a key in U+E000..U+FFFF. Nothing observable/// depends on which order is chosen (both sides of a comparison are sorted by/// the same comparator, so the answer is the same either way); it is ported/// faithfully anyway, because "unobservable today" is how a difference gets/// left in place until something starts observing it.fn stable_string(value: &Value) -> String {match value {Value::Array(items) => {let parts: Vec<String> = items.iter().map(stable_string).collect(); format!("[{}]", parts.join(",")) }Value::Object(fields) => {// `Object.entries(...).filter(v !== undefined)` drops nothing here:// JSON has no `undefined`, and an explicit `null` is kept on both// sides (the vector `{a: null}` vs `{}` reports a change).letmut entries: Vec<(&String, &Value)> = fields.iter().collect(); entries.sort_by(|(a, _), (b, _)| a.encode_utf16().cmp(b.encode_utf16()));let parts: Vec<String> = entries .into_iter() .map(|(key, val)| { format!("{}:{}", json_stringify(&Value::String(key.clone())), stable_string(val) ) }) .collect(); format!("{{{}}}", parts.join(",")) }// `JSON.stringify(scalar)`. A number renders through// `number_to_string` rather than serde_json's own integer path, so a// magnitude beyond 2^53 reads the way JavaScript spells it.Value::Number(number) => match number.as_f64() {Some(float) => number_to_string(float),// Unreachable: `as_f64` only fails under serde_json's// `arbitrary_precision`, which this workspace does not enable.// `null` is what `JSON.stringify` writes for a number it cannot// render, so that is what is written here.None => "null".to_string(), }, other => json_stringify(other), }}/// `String(value)` for the scalars `same_value` compares.////// The object and array arms are unreachable — the caller's `is_plain_object`/// guard took every one of them — and they answer `stable_string`, which is the/// same answer that guard would have given. A pure library does not panic on/// caller-supplied data, and an arm that agrees with its own guard is not a/// fallback masking anything.fn js_to_string(value: &Value) -> String {match value {Value::Null => "null".to_string(),Value::Bool(true) => "true".to_string(),Value::Bool(false) => "false".to_string(),Value::Number(number) => match number.as_f64() {Some(float) => number_to_string(float),None => "null".to_string(), },Value::String(text) => text.clone(),Value::Array(_) | Value::Object(_) => stable_string(value), }}/// Whether two stored values say the same thing.////// Scalars are compared as text because the same column reaches us as a number/// from one reader and as its spelling from another — SQLite hands back what it/// stored, and a version row that survived a json round trip may differ in type/// without differing in fact. Reporting that as an edit would put a change in/// somebody's history that nobody made.////// It costs a surprise worth naming: `true` and the string `"true"` compare/// EQUAL, since `String(true)` is `"true"`, while `true` and `1` do not. Both/// are pinned by vector.fn same_value(before: &Value, after: &Value) -> bool {let empty_before = is_empty(before);let empty_after = is_empty(after);if empty_before || empty_after {return empty_before && empty_after; }if is_plain_object(before) || is_plain_object(after) {return stable_string(before) == stable_string(after); } js_to_string(before) == js_to_string(after)}/// Which of `columns` differ between two snapshots, in the order given.////// `after` is `None` when the record itself went: every column it had reads as/// a removal, which is what a delete row in history means.////// The column list is taken as given and not deduplicated — asking for the same/// column twice yields the change twice, exactly as the TypeScript's `for … of`/// does. It is meant to be [`super::fields::history_columns`] for the kind/// being drawn, which is what [`super::entries::history_entries`] passes; this/// is `pub` because the crates that draw a trail reach it through that/// function, and none of them should be assembling a column list of its own.pubfn diff_fields( before: &RecordRow, after: Option<&RecordRow>, columns: &[&str],) -> Vec<FieldChange> {letmut out = Vec::new();for column in columns {let was = before.get(*column).cloned().unwrap_or(Value::Null);let now = after .and_then(|row| row.get(*column)) .cloned() .unwrap_or(Value::Null);if same_value(&was, &now) {continue; }let change = if is_empty(&was) {FieldChangeKind::Added } elseif is_empty(&now) {FieldChangeKind::Removed } else {FieldChangeKind::Changed }; out.push(FieldChange { column: (*column).to_string(), change, before: was, after: now, }); } out}#[cfg(test)]#[path = "diff_tests.rs"]mod tests;