Cotton code
356 lines · 16.3 KB · RustRaw
//! How a project's members are GROUPED, and in what order the groups read.//!//! The grouping is platform-neutral and three surfaces need it verbatim — the//! phone's project page and its per-section screen, and the Mac window's//! project page — so it is declared once, here, and carries no label, icon or//! address that would tie it to one of them. The repo's rule for kind maps is//! one declaration, gates holding the rest.//!//! What is HERE: which kind lands in which section, the editorial order of the//! sections, the recency sort inside one, and the cap a small surface may reach//! for. What is NOT: a label, an icon or an address. Those are each surface's//! own, keyed by [`ProjectSectionKey`] so a new key fails their build rather//! than disappearing from their page.use std::cmp::Ordering;use cotton_store::protocol::js::parse_date_ms;use crate::constants::{ProjectLinkKind, ProjectSectionKey};/// Three rows, then "See all N" — what a PHONE-sized surface shows of a section/// (spec §D2).////// [`project_sections_for`] never applies it: a cap is a decision about space,/// and a desktop window has it (mac spec §D5, "every member row, no cap")./// Declared here so the surfaces that DO cap read one number.pub const SECTION_ROW_CAP: usize = 3;/// Kind → the section that names it.////// TOTAL by construction. The TypeScript needs two mechanisms for this —/// `Record<ProjectLinkKind, …>` at compile time and a loop that throws at/// module load — because a kind missing from a read registry is SILENTLY/// INVISIBLE (the `list_by_tag` lesson): the page answers nothing for it and/// reports no error, so the hole reads as "there is none of that". Here the/// exhaustive `match` is both mechanisms at once, and a new/// [`ProjectLinkKind`] fails the BUILD.////// Some section keys match the SERVER's own group keys on purpose/// (`thoughts` — `kind_source`'s `group`, crates//// cotton-tools/src/mcp/handlers/projects/kinds.rs), so an assistant reading/// `get_project` and the owner reading the page name one group.pub const fn section_of_kind(kind: ProjectLinkKind) -> ProjectSectionKey {    match kind {        ProjectLinkKind::Album => ProjectSectionKey::Albums,        ProjectLinkKind::Person => ProjectSectionKey::People,        ProjectLinkKind::Thread => ProjectSectionKey::Chats,        ProjectLinkKind::EmailThread => ProjectSectionKey::Email,        ProjectLinkKind::Document => ProjectSectionKey::Documents,        ProjectLinkKind::Todo => ProjectSectionKey::Todos,        // Notes are what the person WROTE about the project; the journal is its        // PROGRESS HISTORY, mostly written by an assistant at the end of a        // working day. They shared one heading until 2026-09-02 (journal spec        // §2.4), and folding a dated running record into "what did I write" hid        // the one section a person opens to ask "what happened lately".        ProjectLinkKind::Note => ProjectSectionKey::Notes,        ProjectLinkKind::Journal => ProjectSectionKey::Journal,        // A memory entry (v34) — the section that sorts by the OWNER'S        // arrangement, not by recency ([`by_arrangement`]).        ProjectLinkKind::Memory => ProjectSectionKey::Memory,        ProjectLinkKind::Event => ProjectSectionKey::Events,        ProjectLinkKind::Transaction => ProjectSectionKey::Money,        // Two sections, not one "Media": a photo grid and a video grid are read        // differently — one is scanned, the other is played — and the kinds are        // two for the same reason (D1).        ProjectLinkKind::Photo => ProjectSectionKey::Photos,        ProjectLinkKind::Video => ProjectSectionKey::Videos,        // A call (v36). The section is DERIVED for a linked person's calls as        // well as explicitly linked ones (spec §D8) — this map is what says        // where an explicit link lands, and the derived rows land in the same        // place so a reader never has to know which kind of membership put a        // row there.        ProjectLinkKind::Call => ProjectSectionKey::Calls,        // A password (v6 of the Rust ladder). Last, and its own section: what        // you need to GET IN to a client's portal is not material you read        // about the work, and folding it into Documents would put a sealed row        // in a list of things a person opens to read.        ProjectLinkKind::Secret => ProjectSectionKey::Passwords,        // A repository (v19): the project's code, beside the containers a        // project is created FOR rather than the material filed into it.        ProjectLinkKind::Repository => ProjectSectionKey::Code,    }}/// The fields the grouping actually reads.////// The TypeScript's `SectionMember` is an interface every richer member shape/// in the product (`IProjectMember`) satisfies, and its `projectSectionsFor` is/// generic so the caller's own shape comes back untouched — core groups and/// orders, it does not project. In Rust that is a TRAIT the caller implements/// on its own row type, and [`project_sections_for`] hands back BORROWS of the/// caller's rows, so "untouched" is a promise the type makes.pub trait SectionMember {    fn kind(&self) -> ProjectLinkKind;    /// The record's OWN moment, which is what orders rows inside a section.    fn recency(&self) -> Option<&str>;    /// The member is still OPEN, and sorts above the settled ones.    ///    /// `None` is the TypeScript's `undefined` — the reader never asked. Set by    /// the TWO kinds whose section is a working queue rather than a history:    /// `thought` (nothing came of it and it was not dismissed) and `todo`    /// (status `open`). Every other kind leaves it `None`, so no other    /// section's order moves by a row; a per-section comparator was the    /// alternative, and it would have made "what order is this section in" a    /// question with as many answers as there are sections instead of one.    ///    /// It is also what [`counts_in_section`] counts by, which is why a todo    /// declares it rather than carrying a `status` of its own: "is this member    /// still owed" is ONE question, and a second field asking it is how a    /// page's figure and a card's figure come to disagree.    fn standing_open(&self) -> Option<bool> {        None    }    /// The LINK's arrangement, set by ONE kind today (`memory`, v34): pinned    /// entries first, then the owner's `position`. Every other kind leaves both    /// `None` and its section sorts by recency; the memory section sorts by    /// [`by_arrangement`] instead, because "what order is my memory in" has    /// exactly one answer — the owner's — and recency is not it.    fn pinned(&self) -> Option<bool> {        None    }    fn position(&self) -> Option<f64> {        None    }    /// The total-order tiebreak [`by_arrangement`] falls to. The TypeScript    /// reads `a.id ?? ""` off an optional field, which is what this default is.    fn id(&self) -> &str {        ""    }}/// Does this member count toward the FIGURE a surface prints for its section —/// the project page's "12 todos", the card's counts line, the Mac window's?////// One declaration, three readers (`projects.service`'s `projectOverview`, the/// app's `projectSectionsFor`, and whatever draws next), because a count is a/// claim about the same set from every surface. The rule is the owner's, from/// seeing "120 to-dos" on a project whose todos were nearly all finished/// (2026-09-05): *"We should only show number of open todos here. Even though/// when we click through there will be links to Done todos and dropped/// todos."*////// TODOS ONLY, and deliberately not "every kind with a standing": a thought's/// section is a queue too, but its count answers "how many captures does this/// project hold", and a settled thought still landed somewhere here. A todo is/// the one kind whose figure a person reads as WORK REMAINING.////// Membership is untouched — every todo linked to the project is still a/// member, still on its section's screen, still reachable through the Done and/// Dropped links there. Only the number is narrowed.pub fn counts_in_section<M: SectionMember + ?Sized>(member: &M) -> bool {    if member.kind() != ProjectLinkKind::Todo {        return true;    }    // `standing_open() == None` means the reader never asked (an older cached    // member shape); that is not the same claim as "this todo is finished", but    // a figure has to choose, and a stale count that RISES on the next read is    // the safer of the two errors.    member.standing_open() == Some(true)}/// One group of a project's members, in the registry's order.#[derive(Debug, Clone, PartialEq, Eq)]pub struct ProjectSectionGroup<'a, M> {    pub key: ProjectSectionKey,    /// Every member of this section, newest first. Never empty, never capped.    pub members: Vec<&'a M>,}/// Group a project's members into its sections, in the registry's fixed order.////// Empty sections are dropped — a heading over nothing is a section that failed/// to load, as far as a reader can tell.////// The TypeScript also steps over a member whose kind it has no section for,/// which cannot happen in a build whose map is total but CAN happen to a file/// synced from a newer server. Rust's [`ProjectLinkKind`] cannot hold such a/// kind at all — the parse at the row boundary answers `None` first — so the/// additive-degradation rule is enforced one layer out, at whoever reads the/// column.pub fn project_sections_for<M: SectionMember>(members: &[M]) -> Vec<ProjectSectionGroup<'_, M>> {    // Insertion-ordered rather than a `HashMap`, so the pre-sort order inside a    // section is the caller's own — which is what the stable sorts below then    // preserve for ties. A hasher's seed must not be able to move a row.    let mut by_section: Vec<(ProjectSectionKey, Vec<&M>)> = Vec::new();    for member in members {        let key = section_of_kind(member.kind());        match by_section.iter_mut().find(|(k, _)| *k == key) {            Some((_, mine)) => mine.push(member),            None => by_section.push((key, vec![member])),        }    }    let mut out = Vec::new();    for key in ProjectSectionKey::ALL {        let Some((_, mine)) = by_section.iter().find(|(k, _)| *k == key) else {            continue;        };        if mine.is_empty() {            continue;        }        let mut sorted = mine.clone();        if key == ProjectSectionKey::Memory {            stable_sort(&mut sorted, |a, b| by_arrangement(*a, *b));        } else {            stable_sort(&mut sorted, |a, b| by_recency_desc(*a, *b));        }        out.push(ProjectSectionGroup {            key,            members: sorted,        });    }    out}/// Pinned first, then the owner's position, then the id as the total-order/// tiebreak — the order a project's MEMORY section reads in (`positionOrder`,/// `rules/memory_order.rs`, over a link's fields).////// A member with no position sorts LAST: the CHECK forbids one on a memory/// link, so it can only be a row from a newer file, and it must not jump to the/// top.////// The id comparison is by BYTES where the TypeScript compares UTF-16 code/// units. The two orders differ only where a supplementary-plane character/// meets one in U+E000..U+FFFF, and every id this sorts is a ULID — ASCII, on/// which the two agree exactly.pub fn by_arrangement<M: SectionMember + ?Sized>(a: &M, b: &M) -> Ordering {    let ap = a.pinned() == Some(true);    let bp = b.pinned() == Some(true);    if ap != bp {        return if ap {            Ordering::Less        } else {            Ordering::Greater        };    }    // `?? Number.POSITIVE_INFINITY`, spelled the same way so a NaN position    // (which `!=` reports as different from everything, itself included, and    // `<` then answers false for) lands where JavaScript puts it: last.    let apos = a.position().unwrap_or(f64::INFINITY);    let bpos = b.position().unwrap_or(f64::INFINITY);    if apos != bpos {        return if apos < bpos {            Ordering::Less        } else {            Ordering::Greater        };    }    a.id().cmp(b.id())}/// Open first, then newest; a member with no moment sorts LAST, never to the/// top.////// EXPORTED because it is the ONE answer to "what order is a section in", and/// `projects.service.ts` sorts its own read with it. A second copy is how a/// project page and the Mac window come to draw one project two ways.////// Compared by PARSED value, not lexically — the same rule `project_activity`/// keeps, because an offset-bearing instant sorts wrong as a string.////// **This comparator is not a total order, and that is the TypeScript's own/// shape.** `undefined !== false` in JavaScript, so a member that declares/// `standingOpen: false` and one that declares nothing take the first branch/// and it answers `0` — EQUAL — instead of falling through to recency. Two such/// members therefore never sort against each other by date, while two members/// that agree on the field do. Reachable only where a section mixes a fresh/// member shape with a cached one that predates the field; see the module's/// [`stable_sort`] for what this port does about it.pub fn by_recency_desc<M: SectionMember + ?Sized>(a: &M, b: &M) -> Ordering {    if a.standing_open() != b.standing_open() {        // `undefined` and `false` are the same answer here: not open. Only a        // kind that says `true` is lifted, which is why no other section moves.        let av = i32::from(a.standing_open() == Some(true));        let bv = i32::from(b.standing_open() == Some(true));        return bv.cmp(&av);    }    let an = instant(a.recency());    let bn = instant(b.recency());    // `bn - an`, sign only. Both are `Option<i64>` here rather than    // `-Infinity`, and `None` compares below every `Some`, which is the same    // ordering the TypeScript's sentinel produces.    bn.cmp(&an)}/// `Date.parse`, with the TypeScript's two sentinels folded into one `None`:/// an absent value and an unparseable one both sort to the bottom.fn instant(value: Option<&str>) -> Option<i64> {    value.filter(|v| !v.is_empty()).and_then(parse_date_ms)}/// A stable bottom-up merge sort, used instead of `slice::sort_by`.////// [`by_recency_desc`] is not a total order (see its note), and Rust's standard/// sort documents that it MAY PANIC when it detects one — a pure library in a/// server may not panic on rows a caller handed it. A merge sort has no such/// detection and no such failure mode: whatever the comparator says, every/// element comes back, in a deterministic order, with equal elements left in/// input order.////// Where the comparator IS a total order this is exactly `Array.prototype.sort`/// (stable since ES2019) and the two agree element for element. Where it is/// not, the resulting order is the sort ALGORITHM's, and V8's TimSort and this/// merge sort may place the ambiguous pair differently — which is the honest/// answer to a comparator that declines to order it.fn stable_sort<T: Copy>(items: &mut [T], compare: impl Fn(&T, &T) -> Ordering) {    let n = items.len();    if n < 2 {        return;    }    let mut buffer: Vec<T> = items.to_vec();    let mut width = 1;    while width < n {        let mut start = 0;        while start < n {            let middle = (start + width).min(n);            let end = (start + 2 * width).min(n);            let (mut left, mut right, mut out) = (start, middle, start);            while left < middle && right < end {                // Take from the RIGHT run only when it is STRICTLY smaller —                // which is what makes the merge stable.                if compare(&items[right], &items[left]) == Ordering::Less {                    buffer[out] = items[right];                    right += 1;                } else {                    buffer[out] = items[left];                    left += 1;                }                out += 1;            }            while left < middle {                buffer[out] = items[left];                left += 1;                out += 1;            }            while right < end {                buffer[out] = items[right];                right += 1;                out += 1;            }            start = end;        }        items.copy_from_slice(&buffer);        width *= 2;    }}#[cfg(test)]#[path = "project_sections_tests.rs"]mod tests;