//! Whether this particular record can be put back — and, when it cannot, the//! sentence saying why. The port of//! `packages/core/src/engine/history/restorable.ts`.//!//! Three refusals, and they are different in nature, which is why they are//! gathered in one pure function rather than scattered between the screen and//! the service. The kind's own refusal is a property of the KIND (its text is//! written in [`super::fields`]). The other two are properties of the ROW in//! front of you, and neither is visible from a version snapshot — so a screen//! deciding on its own would offer a way back that the write then refuses,//! which is the worst of the three answers.use serde_json::Value;usecrate::constants::VersionRecordKind;usesuper::diff::RecordRow;usecrate::rules::shell_lines::{self, LineRow};usesuper::fields::{history_restore_columns, restore_refusal};/// JavaScript truthiness for a stored column — `if (current.managed_by)`.////// Absent, `null`, `false`, `0` and the EMPTY string are falsy; every other/// value is truthy, and that includes a string of one space and an EMPTY/// ARRAY. All five of those are pinned by Node vector, because `[]` being/// truthy is exactly the sort of thing a Rust port re-derives wrongly by/// reaching for `is_empty`.////// `NaN` is the sixth falsy value and cannot occur: JSON has no syntax for one/// and `serde_json::Number` cannot hold one.fn is_truthy(value: Option<&Value>) -> bool {match value {None | Some(Value::Null) => false,Some(Value::Bool(flag)) => *flag,Some(Value::Number(number)) => number.as_f64().is_some_and(|float| float != 0.0),Some(Value::String(text)) => !text.is_empty(),Some(Value::Array(_)) | Some(Value::Object(_)) => true, }}/// Why a restore is not offered — a typed fact; the reading edge says it/// with the line [`RestoreBlock::line`] of set `refusal`, the database's row/// first (contract item 4: the engine never composes the sentence).#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubenumRestoreBlock {/// The kind restores nothing (`super::fields::Restore::Refusal`).Kind(VersionRecordKind),/// The record is gone: creating one would be a new record wearing an old/// record's name.Gone,/// An assistant keeps this note in step with its source.KeptInStep,}/// The line set a restore refusal is said in.pubconst LINES: &str = "refusal";implRestoreBlock {/// The refusal's line in set [`LINES`].pubfn line(self) -> String {matchself {RestoreBlock::Kind(kind) => format!("history.kind.{kind}"),RestoreBlock::Gone => "history.gone".into(),RestoreBlock::KeptInStep => "history.kept_in_step".into(), } }/// The refusal in words: the database's line row first, the kit's for/// one it has none of.pubfn words(self, lines: &[LineRow]) -> String {let line = self.line(); shell_lines::resolve(LINES, &line, lines, &[]) .unwrap_or_else(|| panic!("the refusal line set names no {line}")) }}/// Returns `None` when a restore is genuinely available.pubfn restore_block(kind: VersionRecordKind, current: Option<&RecordRow>) -> Option<RestoreBlock> {ifletSome(block) = restore_refusal(kind) {returnSome(block); }letSome(current) = current else {returnSome(RestoreBlock::Gone); };// A managed note's words belong to the mirror that writes them. Putting old// ones back would look like it worked right up until the next sync quietly// reverted them — the history is still worth reading, which is the point.if matches!(kind, VersionRecordKind::Note | VersionRecordKind::Journal) && is_truthy(current.get("managed_by")) {returnSome(RestoreBlock::KeptInStep); }None}/// What putting `version` back would write onto `current`: each of the kind's/// restore columns whose value in the version differs from the live row's.////// A column the version does not hold at all is left out, never written as/// null — a snapshot taken before the column existed says nothing about it,/// and reading that silence as "it was empty" would erase what is there now./// Empty when the kind cannot restore or nothing would change, which is what/// the screen reads as "nothing to put back".pubfn restore_patch(kind: VersionRecordKind, version: &RecordRow, current: &RecordRow) -> RecordRow {letmut patch = RecordRow::new();for column in history_restore_columns(kind) {letSome(was) = version.get(*column) else {continue; };if current.get(*column).unwrap_or(&Value::Null) != was { patch.insert((*column).to_string(), was.clone()); } } patch}/// The `(line id, account id)` pairs a transaction's version holds — the/// sides as they stood before the edit, which the trigger snapshots beside the/// header (`lines`). Empty for a version taken before the trigger kept them.pubfn version_lines(version: &RecordRow) -> Vec<(String, String)> {let lines = match version.get("lines") {Some(Value::Array(lines)) => lines.clone(),// SQLite's json_group_array inside json_object arrives as an array, but// a snapshot that stored it as text is read the same way.Some(Value::String(text)) => serde_json::from_str::<Vec<Value>>(text).unwrap_or_default(), _ => Vec::new(), }; lines .iter() .filter_map(|line| {Some(( line.get("id")?.as_str()?.to_string(), line.get("account_id")?.as_str()?.to_string(), )) }) .collect()}/// Whether a transaction's sides stand differently now than in `version` —/// a line that is still there on another account. A version with no lines/// snapshot says nothing, so it differs in nothing.pubfn lines_differ(version: &RecordRow, current: &[(String, String)]) -> bool { version_lines(version).iter().any(|(id, was)| { current .iter() .any(|(live_id, now)| live_id == id && now != was) })}#[cfg(test)]#[path = "restorable_tests.rs"]mod tests;