//! Stored board differences. Identity is an explicit part `id`, or the kind //! for legacy single-kind parts (`kind#2` etc. for repeated legacy kinds). //! Shipped ids must remain stable across revisions. Variants are keyed by //! their `when` selector. Only storage uses this form; every reader gets a //! whole board, so renderers and packages need no overlay implementation. //! //! The parts a person dropped from a screen are the row's `dropped` list //! (the ids of the screen's own `parts`), written only when a board the //! person sent lacks a shipped part. A part they never had is not dropped: //! a legacy whole board, and an overlay written before `dropped` existed //! (`board_overlay: 1`, whose part tombstones were made by the conversion //! and by whole-list writes), gain every shipped part they lack at its //! shipped position ([`convert`]). use serde_json::{json, Map, Value}; /// The overlay form this build writes: `dropped` holds the person's drops. const OVERLAY: u64 = 2; /// The form written before `dropped`: its part tombstones are no drops. const OVERLAY_WITHOUT_DROPS: u64 = 1; pub fn is_overlay(raw: &Value) -> bool { matches!(raw.get("board_overlay").and_then(Value::as_u64), Some(OVERLAY | OVERLAY_WITHOUT_DROPS)) } /// An overlay in this build's form, which the seed leaves as it is. pub fn is_current(raw: &Value) -> bool { raw.get("board_overlay").and_then(Value::as_u64) == Some(OVERLAY) } /// Encode a whole board the person sent relative to its shipped base: a /// shipped part their list lacks is one they dropped. pub fn difference(raw: &Value, base: &Value) -> Value { let mut changes = diff(raw, base, ""); let dropped = take_part_removals(&mut changes); json!({"id":raw["id"],"board_overlay":OVERLAY,"dropped":dropped,"changes":changes}) } /// The seed's one-pass move of a stored board this build did not write /// whole — a legacy whole board or an overlay without `dropped` — onto its /// shipped base. Nothing is dropped: every shipped part the board lacks /// arrives at its shipped position, after the nearest shipped part the /// person kept, and every part they have keeps its settings and order. pub fn convert(raw: &Value, base: &Value) -> Value { let mut next = if is_overlay(raw) { let mut next = raw.clone(); take_part_removals(&mut next["changes"]); next["board_overlay"] = json!(OVERLAY); next } else { difference(raw, base) }; next["dropped"] = json!([]); next } /// Preserve removals whose ids the current shipped copy no longer contains. /// An explicitly reintroduced id clears its tombstone. pub fn difference_preserving(raw: &Value, base: &Value, previous: &Value) -> Value { let mut next = difference(raw, base); if is_overlay(previous) { let previous = convert_unless_current(previous, base); retain_removals(&mut next["changes"], &previous["changes"], raw, ""); let sent = part_ids(raw); let held: Vec = previous["dropped"] .as_array() .into_iter() .flatten() .filter(|id| id.as_str().is_some_and(|id| !sent.iter().any(|key| key == id))) .cloned() .collect(); let dropped = next["dropped"].as_array_mut().expect("difference writes dropped"); for id in held { if !dropped.contains(&id) { dropped.push(id); } } } next } fn convert_unless_current(raw: &Value, base: &Value) -> Value { if is_current(raw) { raw.clone() } else { convert(raw, base) } } /// The ids of a board's own parts, as the overlay keys them. fn part_ids(raw: &Value) -> Vec { keyed(raw["parts"].as_array().map(Vec::as_slice).unwrap_or(&[]), "parts").into_iter().map(|(id, _)| id).collect() } /// Lift the tombstones of the screen's own parts out of `changes`. fn take_part_removals(changes: &mut Value) -> Vec { changes .get_mut("fields") .and_then(|fields| fields.get_mut("parts")) .and_then(Value::as_object_mut) .and_then(|parts| parts.remove("removed")) .and_then(|removed| removed.as_array().cloned()) .unwrap_or_default() } fn retain_removals(next: &mut Value, previous: &Value, raw: &Value, slot: &str) { if let Some(removed) = previous["removed"].as_array() { // An item inside `parts` is an object, even though it carries the // list's slot name. Only the list itself uses an `items` patch; // confusing them emits both fields and items and refuses the edit. let keyed_list = raw.is_array() && matches!(slot, "parts" | "variants"); let visible: Vec = if keyed_list { keyed(raw.as_array().map(Vec::as_slice).unwrap_or(&[]), slot).into_iter().map(|(id, _)| id).collect() } else { raw.as_object().into_iter().flatten().map(|(key, _)| key.clone()).collect() }; let kept: Vec<_> = removed.iter().filter(|id| id.as_str().is_some_and(|id| !visible.iter().any(|key| key == id))).cloned().collect(); if !kept.is_empty() { // An equal subtree normally encodes as {}, so give it the // appropriate identity patch before adding dormant tombstones. if keyed_list && next.get("items").is_none() { next["items"] = json!({}); } else if next.get("fields").is_none() && next.get("items").is_none() { next["fields"] = json!({}); } if !next["removed"].is_array() { next["removed"] = json!([]); } let target = next["removed"].as_array_mut().expect("array"); for id in kept { if !target.contains(&id) { target.push(id); } } } } if let Some(fields) = previous["fields"].as_object() { for (key, patch) in fields { let missing_variants = key == "variants" && raw.get(key).is_none(); let empty = json!([]); if let Some(raw) = raw.get(key).or_else(|| missing_variants.then_some(&empty)) { let mut subtree = next["fields"].get(key).cloned().unwrap_or_else(|| json!({})); retain_removals(&mut subtree, patch, raw, key); if subtree != json!({}) { if missing_variants { subtree["absent"] = json!(true); } next["fields"][key] = subtree; } } } } if let Some(items) = previous["items"].as_object() { let visible = keyed(raw.as_array().map(Vec::as_slice).unwrap_or(&[]), slot); for (id, patch) in items { if let Some((_, raw)) = visible.iter().find(|(key, _)| key == id) { let mut subtree = next["items"].get(id).cloned().unwrap_or_else(|| json!({})); retain_removals(&mut subtree, patch, raw, slot); if subtree != json!({}) { next["items"][id] = subtree; } } } } } /// Resolve stored differences; legacy whole boards stand until the seed's /// one-pass conversion. No read mutates a database. pub fn resolve(raw: &Value, base: &Value) -> Value { if !is_overlay(raw) || !valid_patch(&raw["changes"]) || !valid_drops(raw) { return raw.clone(); } let mut changes = convert_unless_current(raw, base)["changes"].clone(); let dropped = raw["dropped"].as_array().filter(|_| is_current(raw)).cloned().unwrap_or_default(); if !dropped.is_empty() { if changes["fields"].get("parts").is_none() { changes["fields"]["parts"] = json!({"items":{}}); } changes["fields"]["parts"]["removed"] = json!(dropped); } let mut drawn = apply(&changes, base, ""); if let Some(object) = drawn.as_object_mut() { object.remove("base_hash"); } drawn } /// `dropped` is a list of distinct ids on the current form, and absent before it. fn valid_drops(raw: &Value) -> bool { match raw.get("dropped") { None => !is_current(raw), Some(dropped) => { let mut seen = std::collections::BTreeSet::new(); is_current(raw) && dropped.as_array().is_some_and(|ids| ids.iter().all(|id| id.as_str().is_some_and(|id| seen.insert(id)))) && raw["changes"]["fields"]["parts"].get("removed").is_none() } } } fn valid_patch(patch: &Value) -> bool { let Some(object) = patch.as_object() else { return false; }; if object.is_empty() { return true; } if object.contains_key("value") { return object.len() == 1; } let string_list = |value: &Value| { value.as_array().is_some_and(|values| { let mut seen = std::collections::BTreeSet::new(); values.iter().all(|value| value.as_str().is_some_and(|id| seen.insert(id))) }) }; let (Some(key), Some(children)) = ( ["fields", "items"].into_iter().find(|key| object.contains_key(*key)), object.get("fields").or_else(|| object.get("items")).and_then(Value::as_object), ) else { return false; }; if object.keys().any(|held| ![key, "removed", "order", "absent"].contains(&held.as_str())) { return false; } if key == "fields" && object.contains_key("order") { return false; } if object.get("removed").is_some_and(|value| !string_list(value)) { return false; } if object.get("order").is_some_and(|value| !string_list(value)) { return false; } if object.get("absent").is_some_and(|value| !value.is_boolean()) { return false; } children.values().all(valid_patch) } fn keyed(values: &[Value], slot: &str) -> Vec<(String, Value)> { let mut counts = std::collections::BTreeMap::new(); let mut selectors = std::collections::BTreeMap::new(); values .iter() .map(|value| { let kind = value["kind"].as_str().unwrap_or(""); let count = counts.entry(kind).or_insert(0); *count += 1; let id = if slot == "variants" { // `when` is an object: canonical key order keeps selector identity // independent of the JSON writer's insertion order. let when: std::collections::BTreeMap<_, _> = value["when"].as_object().into_iter().flatten().collect(); let selector = serde_json::to_string(&when).expect("selector serializes"); let count = selectors.entry(selector.clone()).or_insert(0); *count += 1; if *count == 1 { selector } else { format!("{selector}#{count}") } } else if let Some(id) = value["id"].as_str() { id.to_string() } else { if *count == 1 { kind.to_string() } else { format!("{kind}#{count}") } }; (id, value.clone()) }) .collect() } fn diff(raw: &Value, base: &Value, slot: &str) -> Value { if raw == base { return json!({}); } if raw.is_object() && !base.is_object() { let patch = diff(raw, &json!({}), slot); return if patch == json!({}) { json!({"fields":{},"removed":[]}) } else { patch }; } if let (Some(raw), Some(base)) = (raw.as_object(), base.as_object()) { let mut fields: Map<_, _> = raw .iter() .filter_map(|(key, value)| { let empty = json!([]); let missing = if matches!(key.as_str(), "parts" | "variants") && value.is_array() { &empty } else { &Value::Null }; let change = diff(value, base.get(key).unwrap_or(missing), key); (change != json!({})) .then(|| (key.clone(), change)) // An explicit null on an absent key is still authored data. .or_else(|| { (!base.contains_key(key)).then(|| { let patch = if matches!(key.as_str(), "parts" | "variants") && value.is_array() { json!({"items":{},"removed":[]}) } else { json!({"value":value}) }; (key.clone(), patch) }) }) }) .collect(); let removed: Vec<_> = base.keys().filter(|key| !raw.contains_key(*key) && key.as_str() != "variants").collect(); if !raw.contains_key("variants") && base.get("variants").is_some_and(Value::is_array) { let mut change = diff(&json!([]), &base["variants"], "variants"); if change == json!({}) { change = json!({"items":{},"removed":[]}); } change["absent"] = json!(true); fields.insert("variants".into(), change); } return json!({"fields":fields,"removed":removed}); } if matches!(slot, "parts" | "variants") { if let (Some(raw), Some(base)) = (raw.as_array(), base.as_array()) { let (raw, base) = (keyed(raw, slot), keyed(base, slot)); let items: Map<_, _> = raw .iter() .filter_map(|(id, value)| { let before = base.iter().find(|(key, _)| key == id).map(|(_, v)| v).unwrap_or(&Value::Null); let change = diff(value, before, slot); (change != json!({})).then(|| (id.clone(), change)) }) .collect(); let removed: Vec<_> = base.iter().filter(|(id, _)| !raw.iter().any(|(key, _)| key == id)).map(|(id, _)| id).collect(); let order: Vec<_> = raw.iter().map(|(id, _)| id).collect(); let inherited: Vec<_> = base.iter().filter(|(id, _)| !removed.contains(&id)).map(|(id, _)| id).collect(); let mut patch = json!({"items":items,"removed":removed}); if order != inherited { patch["order"] = json!(order); } return patch; } } json!({"value":raw}) } fn apply(patch: &Value, base: &Value, slot: &str) -> Value { if let Some(value) = patch.get("value") { return value.clone(); } if let Some(fields) = patch["fields"].as_object() { let mut out = base.as_object().cloned().unwrap_or_default(); for key in patch["removed"].as_array().into_iter().flatten().filter_map(Value::as_str) { out.remove(key); } for (key, change) in fields { let value = apply(change, base.get(key).unwrap_or(&Value::Null), key); if change["absent"] == json!(true) && value.as_array().is_some_and(Vec::is_empty) { out.remove(key); } else { out.insert(key.clone(), value); } } return Value::Object(out); } if let Some(items) = patch["items"].as_object() { let values = keyed(base.as_array().map(Vec::as_slice).unwrap_or(&[]), slot); let removed = patch["removed"].as_array().cloned().unwrap_or_default(); let mut order: Vec = patch["order"] .as_array() .map(|v| v.iter().filter_map(Value::as_str).map(str::to_string).collect()) .unwrap_or_else(|| values.iter().map(|(id, _)| id.clone()).collect()); // A new shipped item follows its nearest preceding shipped anchor. // This keeps all authored pairs ordered while additions retain their // shipped neighbourhood. Consecutive additions become anchors too. for (index, (id, _)) in values.iter().enumerate() { if order.contains(id) || removed.contains(&json!(id)) { continue; } let at = values[..index] .iter() .rev() .find_map(|(anchor, _)| order.iter().position(|key| key == anchor).map(|at| at + 1)) .unwrap_or(0); order.insert(at, id.clone()); } order.retain(|id| !removed.contains(&json!(id))); let out: Vec<_> = order .iter() .filter_map(|id| { let before = values.iter().find(|(key, _)| key == id).map(|(_, v)| v); match items.get(id) { Some(change) => Some(apply(change, before.unwrap_or(&Value::Null), slot)), None => before.cloned(), } }) .collect(); return json!(out); } base.clone() } #[cfg(test)] #[path = "board_overlay_tests.rs"] mod tests;