Cotton code
294 lines · 13.9 KB · RustRaw
//! Cotton Notes' side page and pins (assets/design/notes/CONTRACT.md 1, 3, 7)://! `notes.side` in one answer, pinning a note in Notes or inside a tag,//! pinning a root tag, and a tag's icon.//!//! **Where it is kept.** A note's pin in Notes is its `pinned` column; the//! tags it is pinned inside are its `pinned_in` (a JSON list of tag keys).//! The side page's own choices — the root tags pinned, in the order pinned,//! and an icon a person chose for a tag — are two columns of Notes' face//! settings row (`face_settings` keyed `notes`: `pinned_tags`, a JSON list of//! tag keys; `tag_icons`, a JSON object of tag key to icon id), synced as the//! look and type are. Two phones changing them apart: the later write wins.use std::collections::{BTreeMap, BTreeSet};use serde_json::{json, Map, Value};use cotton_core::cotton_rules::writing::{derive, icons};use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::common::update_row;use cotton_tools::mcp::handlers::tables::groups;use super::notes::{self, bad, every_note, line, note, Held, NOTE, NOTES};use crate::handle::CottonHandle;use crate::methods::MethodError;/// The side page's own choices, as the settings row keeps them.#[derive(Debug, Clone, Default)]pub(crate) struct SidePrefs {    /// Root tag keys pinned, in the order pinned.    pub pinned_tags: Vec<String>,    /// Tag key → the icon a person chose.    pub icons: BTreeMap<String, String>,}pub(crate) fn side_prefs(handle: &CottonHandle) -> Result<SidePrefs, MethodError> {    let row = notes::settings_row(handle, notes::SETTINGS_ROW)?;    let pinned_tags = row.get("pinned_tags").and_then(Value::as_str).and_then(|said| serde_json::from_str::<Vec<String>>(said).ok()).unwrap_or_default();    let icons = row        .get("tag_icons")        .and_then(Value::as_str)        .and_then(|said| serde_json::from_str::<BTreeMap<String, String>>(said).ok())        .unwrap_or_default()        .into_iter()        .filter(|(_, icon)| icons::known(icon))        .collect();    Ok(SidePrefs { pinned_tags, icons })}fn write_prefs(handle: &CottonHandle, prefs: &SidePrefs) -> Result<(), MethodError> {    let mut patch = Map::new();    patch.insert("pinned_tags".into(), json!(serde_json::to_string(&prefs.pinned_tags).unwrap_or_default()));    patch.insert("tag_icons".into(), json!(serde_json::to_string(&prefs.icons).unwrap_or_default()));    notes::write_settings_row(handle, notes::SETTINGS_ROW, patch)}/// The icon a tag wears: the person's, else the catalogue's.fn icon_of(prefs: &SidePrefs, tag: &str) -> (String, bool) {    match prefs.icons.get(&derive::tag_key(tag)) {        Some(chosen) => (chosen.clone(), true),        None => (icons::for_tag(tag).to_string(), false),    }}/// Is this note live (not archived, not binned)?pub(crate) fn live(held: &Held) -> bool {    !held.archived && !held.binned}fn place(id: &str, icon: &str, count: Option<usize>, list: Value) -> Result<Value, MethodError> {    let mut out = json!({ "id": id, "view": id, "label": line(&format!("side.{id}"), &[])?, "icon": icon, "list": list });    if let Some(count) = count {        out["count"] = json!(count);    }    Ok(out)}/// `notes.side { zone? }`: the side page in one answer.pub(crate) fn side(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    notes::refile(handle)?;    let prefs = side_prefs(handle)?;    let zone = request.get("zone").and_then(Value::as_str).map(str::to_string);    notes::with_read(handle, "notes.side", |ctx| side_in(ctx, &prefs, zone.as_deref()))}pub(crate) fn side_in(ctx: &mut Ctx<'_>, prefs: &SidePrefs, zone: Option<&str>) -> Result<Value, MethodError> {    let all = every_note(ctx)?;    let tagged: BTreeSet<String> = notes::tag_groups(ctx)?.into_iter().flat_map(|group| group.members).collect();    let every_live: Vec<&Held> = all.iter().filter(|n| live(n)).collect();    // The person's own places count the notes they wrote (an assistant's are under "From your assistant").    let live_notes: Vec<&Held> = every_live.iter().copied().filter(|n| !n.by_assistant).collect();    let mut todo = 0;    let mut today = 0;    for held in &live_notes {        let derived = notes::derived(&notes::text_of(ctx, held)?);        if derived.checks > derived.checks_done {            todo += 1;        }        if notes::is_today(ctx, held, zone) {            today += 1;        }    }    let places = vec![        place("all", "notes", Some(live_notes.len()), json!({ "view": "all" }))?,        place("pinned", "pinned", Some(every_live.iter().filter(|n| n.pinned).count()), json!({ "view": "pinned" }))?,        place("todo", "todo", Some(todo), json!({ "view": "todo" }))?,        place("today", "today", Some(today), json!({ "view": "today" }))?,        place("untagged", "untagged", Some(live_notes.iter().filter(|n| !tagged.contains(&n.id)).count()), json!({ "view": "untagged" }))?,    ];    let foot = vec![        place("archive", "archive", Some(all.iter().filter(|n| n.archived && !n.binned).count()), json!({ "view": "archive" }))?,        place("bin", "bin", Some(all.iter().filter(|n| n.binned).count()), json!({ "view": "bin" }))?,    ];    let more = vec![        json!({ "id": "settings", "label": line("side.settings", &[])?, "icon": "settings" }),        json!({ "id": "account", "label": line("side.account", &[])?, "icon": "account" }),    ];    // What the person's assistant wrote: its notes and web pages, and its memory, read-only (21 Nov 2026).    // Null while no assistant has written or kept anything (a new person, signed out, or one who never connected one):    // a section for something they do not have would only puzzle them (the launch walk, 22 Nov 2026).    let assistant_count = every_live.iter().filter(|n| n.by_assistant).count() + super::notes_assistant::pages(ctx)?.len();    let memory_count = super::notes_assistant::memory_count(ctx)?;    let assistant = if assistant_count == 0 && memory_count == 0 {        Value::Null    } else {        json!({            "label": line("side.assistant_section", &[])?,            "items": [                place("assistant", "assistant", Some(assistant_count), json!({ "view": "assistant" }))?,                { "id": "memory", "view": "memory", "label": line("side.memory", &[])?, "icon": "memory", "count": memory_count, "opens": "memory" },            ],        })    };    let mut tree = notes::tag_tree(ctx)?;    dress(&mut tree, prefs);    // Pinned roots first, in the order pinned; the rest as the tree answers.    let place_of = |node: &Value| prefs.pinned_tags.iter().position(|key| Some(key.as_str()) == node["tag"].as_str().map(derive::tag_key).as_deref());    tree.sort_by_key(|node| place_of(node).unwrap_or(usize::MAX));    let lists = hand_lists(ctx)?;    Ok(json!({        "current": "all",        "places": places,        "tags": { "label": line("side.tags", &[])?, "tree": tree },        "lists": { "label": line("side.lists", &[])?, "items": lists },        "assistant": assistant,        "foot": foot,        "more": more,        "words": {            "pin_tag": line("side.pin_tag", &[])?,            "unpin_tag": line("side.unpin_tag", &[])?,            "choose_icon": line("side.choose_icon", &[])?,            "open": line("side.open", &[])?,            "close": line("side.close", &[])?,        },    }))}/// Each tag node gains its icon, whether a person chose it, whether it is/// pinned (a root only), and the list it opens.fn dress(nodes: &mut [Value], prefs: &SidePrefs) {    for node in nodes.iter_mut() {        let tag = node["tag"].as_str().unwrap_or_default().to_string();        let (icon, chosen) = icon_of(prefs, &tag);        let root = node["depth"].as_u64() == Some(0);        node["icon"] = json!(icon);        node["icon_chosen"] = json!(chosen);        node["pinned"] = json!(root && prefs.pinned_tags.contains(&derive::tag_key(&tag)));        node["list"] = json!({ "view": "tag", "tag": tag });        if let Some(children) = node.get_mut("children").and_then(Value::as_array_mut) {            dress(children, prefs);        }    }}/// The person's hand-made lists of notes (groups not named `#…`, picked by/// hand), in their own order, each with its live notes' count.pub(crate) fn hand_lists(ctx: &mut Ctx<'_>) -> Result<Vec<Value>, MethodError> {    let notes_live: BTreeSet<String> = every_note(ctx)?.into_iter().filter(live).map(|n| n.id).collect();    let live_groups = groups::live_groups(ctx.read.driver(), Some(ctx.workspace_id)).map_err(|why| MethodError::new("unreadable", why))?;    let order = groups::list_order(ctx, NOTE).unwrap_or_default();    let mut found: Vec<(usize, Value)> = live_groups        .into_iter()        .filter(|(_, data)| data.get("table").and_then(Value::as_str) == Some(NOTE) && data.get("where").is_none())        .filter(|(_, data)| !groups::name_of(data).starts_with('#'))        .map(|(id, data)| {            let count = groups::members_of(&data).iter().filter(|m| notes_live.contains(*m)).count();            let at = order.iter().position(|o| *o == id).unwrap_or(usize::MAX);            (at, json!({ "id": id, "name": groups::name_of(&data), "icon": "lists", "count": count, "list": { "view": "list", "list": id } }))        })        .collect();    found.sort_by_key(|(at, _)| *at);    Ok(found.into_iter().map(|(_, list)| list).collect())}/// The members of one hand-made list.pub(crate) fn list_members(ctx: &mut Ctx<'_>, id: &str) -> Result<(String, BTreeSet<String>), MethodError> {    let live_groups = groups::live_groups(ctx.read.driver(), Some(ctx.workspace_id)).map_err(|why| MethodError::new("unreadable", why))?;    let (_, data) = live_groups        .into_iter()        .find(|(group, data)| group == id && data.get("table").and_then(Value::as_str) == Some(NOTE))        .ok_or_else(|| MethodError::new("not_found", line("refusal.no_list", &[]).unwrap_or_default()))?;    Ok((groups::name_of(&data).to_string(), groups::members_of(&data).into_iter().collect()))}// ── pins ────────────────────────────────────────────────────────────────────/// `notes.pin { id, tag? }` / `notes.unpin { id, tag? }`.pub(crate) fn pin(ctx: &mut Ctx<'_>, request: &Value, on: bool) -> Result<Value, MethodError> {    let held = note(ctx, notes::id_of(request)?)?;    let tag = request.get("tag").and_then(Value::as_str).map(|t| t.trim().trim_start_matches('#').trim()).filter(|t| !t.is_empty());    let mut patch = Map::new();    match tag {        None => {            if held.pinned != on {                patch.insert("pinned".into(), json!(on));            }        }        Some(tag) => {            let key = derive::tag_key(tag);            let mut inside = held.pinned_in.clone();            inside.retain(|k| *k != key);            if on {                inside.push(key);            }            if inside != held.pinned_in {                patch.insert("pinned_in".into(), json!(serde_json::to_string(&inside).unwrap_or_default()));            }        }    }    if !patch.is_empty() {        // A pin is no edit: the note keeps its edit date.        patch.insert("updated_at".into(), json!(held.edited));        update_row(ctx, NOTES, &held.id, patch).map_err(notes::tool)?;        ctx.commit().map_err(notes::tool)?;    }    let now = note(ctx, &held.id)?;    Ok(json!({        "id": now.id,        "pinned_in_notes": now.pinned,        "pinned_in": now.pinned_in,        "said": line(if on { "acts.pinned" } else { "acts.unpinned" }, &[])?,    }))}/// `notes.pin_tag { tag, pinned }`: a root tag pinned to the top of the/// side page's tags (or not). Answers the side page.pub(crate) fn pin_tag(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let tag = request.get("tag").and_then(Value::as_str).map(|t| t.trim().trim_start_matches('#').trim()).filter(|t| !t.is_empty()).ok_or_else(|| bad("this names the `tag`"))?;    if tag.contains('/') {        return Err(MethodError::new("refused", line("refusal.pin_nested", &[])?));    }    let on = request.get("pinned").and_then(Value::as_bool).unwrap_or(true);    let mut prefs = side_prefs(handle)?;    let key = derive::tag_key(tag);    let before = prefs.pinned_tags.clone();    prefs.pinned_tags.retain(|k| *k != key);    if on {        prefs.pinned_tags.push(key);    }    if prefs.pinned_tags != before {        write_prefs(handle, &prefs)?;    }    side(handle, request)}/// `notes.tag_icon { tag, icon | null }`: the icon a person chose for a tag/// (null: the catalogue's again). Answers the side page.pub(crate) fn tag_icon(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let tag = request.get("tag").and_then(Value::as_str).map(|t| t.trim().trim_start_matches('#').trim()).filter(|t| !t.is_empty()).ok_or_else(|| bad("this names the `tag`"))?;    let icon = request.get("icon").and_then(Value::as_str).map(str::trim).filter(|i| !i.is_empty());    if let Some(icon) = icon {        if !icons::known(icon) {            return Err(MethodError::new("bad_request", line("refusal.no_icon", &[])?));        }    }    let mut prefs = side_prefs(handle)?;    let key = derive::tag_key(tag);    match icon {        Some(icon) => prefs.icons.insert(key, icon.to_string()),        None => prefs.icons.remove(&key),    };    write_prefs(handle, &prefs)?;    side(handle, request)}/// `notes.tag_icons {}`: the icons a person may choose for a tag.pub(crate) fn tag_icons() -> Result<Value, MethodError> {    let shipped = icons::catalogue();    let mut out = Vec::new();    for icon in &shipped.icons {        out.push(json!({ "id": icon.id, "label": line(&format!("icons.{}", icon.id), &[])? }));    }    out.push(json!({ "id": shipped.fallback, "label": line(&format!("icons.{}", shipped.fallback), &[])? }));    Ok(json!({ "icons": out, "fallback": shipped.fallback, "title": line("side.choose_icon", &[])? }))}