//! THE order memory reads in — one comparator, every surface. The port of //! `packages/core/src/engine/memoryOrder.ts`. //! //! Until schema v14 the order was a RULE (pinned, then oldest first, slug as //! the tiebreak): a decent default nobody chose. Since v14 it is the OWNER'S: a //! REAL midpoint `position` they arrange by hand, with pinned entries on top //! because pinned is what every assistant receives at connect time. //! //! Pure and platform-neutral on purpose — the Me page, the project page's //! Memory band and the briefing compiler all read this, so none of them can //! hold a second opinion about the same list. use std::cmp::Ordering; /// Backfill spacing, and the step a new entry appends by. /// /// Mirrors `MEMORY_POSITION_STEP` in the store's `memory.v14` migration — the /// migration writes it, this writes every position after it. pub const POSITION_STEP: f64 = 1000.0; /// What the comparator needs; every memory shape in the product satisfies it. #[derive(Debug, Clone, PartialEq)] pub struct Positioned { pub pinned: bool, pub position: f64, pub slug: String, } /// Pinned first, then the owner's arrangement, slug as the total-order /// tiebreak. /// /// Two rows can share a position after a renumber race; a list must still have /// ONE order. Never `localeCompare` — a stable byte order is the point, and /// that is one of the few places the TypeScript and Rust agree exactly. pub fn position_order(a: &Positioned, b: &Positioned) -> Ordering { if a.pinned != b.pinned { return if a.pinned { Ordering::Less } else { Ordering::Greater }; } // `!==` then `<`: NaN would compare unequal and then not-less, giving // `Greater`. `partial_cmp` would give `None` there, so the comparison is // spelled out rather than delegated. if a.position != b.position { return if a.position < b.position { Ordering::Less } else { Ordering::Greater }; } a.slug.as_str().cmp(b.slug.as_str()) } /// The position a row takes when dropped between two neighbours — either may be /// `None`, meaning "the end of the list on that side". /// /// Answers `None` when the two neighbours are adjacent floats and no value fits /// between them. That is not a failure to swallow: the caller renumbers the /// list explicitly, as a story's scenes are numbered again, because a silent no-op /// would be a drag that visibly does nothing. pub fn position_between(before: Option, after: Option) -> Option { match (before, after) { (None, None) => Some(POSITION_STEP), (None, Some(after)) => Some(after - POSITION_STEP), (Some(before), None) => Some(before + POSITION_STEP), (Some(before), Some(after)) => { let midpoint = (before + after) / 2.0; if midpoint > before && midpoint < after { Some(midpoint) } else { None } } } } #[cfg(test)] #[path = "memory_order_tests.rs"] mod tests;