Cotton code
118 lines · 4.4 KB · RustRaw
//! The database settings row's theme writes.//!//! `database` is an engine row, not a `cotton_records` row. Its look is its//! picture, its cap colour and its theme — the look (paper or plain) and the//! cap's finish, written as the database's own theme row, which syncs. No//! brand is drawn or edited on the phone (owner, 16 Oct 2026).use serde_json::{json, Map, Value};use crate::{handle::CottonHandle, methods::MethodError};/// Handle the database fields whose source is the theme.////// `None` leaves appearance fields (`name`, `colour`) for/// [`crate::phone::database_appearance`].  The caller has already checked the/// generic envelope; this method still validates it before a tool write.pub fn update(handle: &CottonHandle, request: &Value) -> Result<Option<Value>, MethodError> {    if request["table"].as_str() != Some("database") {        return Ok(None);    }    let id = request["id"]        .as_str()        .filter(|id| !id.trim().is_empty())        .ok_or_else(|| MethodError::new("bad_request", "`records.update` needs a database id"))?;    let patch = request["patch"]        .as_object()        .ok_or_else(|| MethodError::new("bad_request", "database updates need a patch"))?;    if patch.len() != 1 {        return Err(MethodError::new(            "bad_request",            "change one database setting at a time",        ));    }    let (field, value) = patch.iter().next().expect("one patch field");    match field.as_str() {        "family" | "cap_texture" => update_theme(handle, id, field, value).map(Some),        _ => Ok(None),    }}fn update_theme(    handle: &CottonHandle,    id: &str,    field: &str,    value: &Value,) -> Result<Value, MethodError> {    // Go through the declared native method for the displayed definition, but    // keep the sparse own row as the write base.  A resolved definition would    // bake every shipped value into an override and lose future theme changes.    let shown = crate::methods::dispatch(handle, "definitions.theme", &json!({"database": id}))?;    let client = handle.client();    let _scope = client        .name_database(Some(id))        .map_err(|reason| MethodError::new("database_not_held", reason))?;    let own = client        .read_rows("settings_database.theme_overrides", &mut |ctx| {            cotton_tools::presentation::theme_overrides(ctx.read.driver(), ctx.workspace_id)                .map(|definition| json!({"definition": definition}))        })        .map_err(|reason| MethodError::new("unreadable", reason))?;    let mut definition = own["definition"]        .as_object()        .cloned()        .or_else(|| shown["definition"].as_object().cloned())        .unwrap_or_default();    definition.insert(        "id".into(),        Value::from(cotton_tools::presentation::OWN_THEME),    );    match field {        "family" => set_text(&mut definition, "family", value, field)?,        "cap_texture" => {            let texture = required_text(value, field)?;            let cap = definition                .entry("cap")                .or_insert_with(|| Value::Object(Map::new()))                .as_object_mut()                .ok_or_else(|| MethodError::new("bad_request", "the theme cap is not an object"))?;            cap.insert("texture".into(), Value::from(texture));        }        _ => unreachable!("checked by update"),    }    let engine = crate::methods::dispatch(        handle,        "definitions.saveTheme",        &json!({"database": id, "definition": definition}),    )?;    let observed = crate::methods::dispatch(handle, "definitions.theme", &json!({"database": id}))?;    Ok(json!({"record": theme_record(id, &observed), "engine": engine}))}fn theme_record(id: &str, observed: &Value) -> Value {    let definition = &observed["definition"];    json!({"id": id, "data": {        "family": definition["family"],        "cap_texture": definition["cap"]["texture"]    }, "deleted_at": Value::Null})}fn required_text(value: &Value, field: &str) -> Result<String, MethodError> {    value        .as_str()        .map(str::trim)        .filter(|value| !value.is_empty())        .map(str::to_string)        .ok_or_else(|| MethodError::new("bad_request", format!("`{field}` needs text")))}fn set_text(    object: &mut Map<String, Value>,    key: &str,    value: &Value,    field: &str,) -> Result<(), MethodError> {    object.insert(key.into(), Value::from(required_text(value, field)?));    Ok(())}