Cotton code
238 lines · 12.3 KB · RustRaw
//! Cotton Story's drafts: the working copy marked as a named, dated draft//! that never changes again (`story_draft`, its scenes `story_draft_scene`,//! each line with its own id), drafts listed and read, what changed since a//! draft told by identity (`identity::changes`), and going back to one.//! History keeps every change in between, as for any row.use cotton_core::cotton_rules::story::{    beats::BeatKind,    fountain,    identity::{self, Held, SceneAt},    layout,};use super::*;pub const DRAFT: &str = "story_draft";pub const DRAFT_SCENE: &str = "story_draft_scene";/// The parts of a scene a draft keeps as they stood.const KEPT: [&str; 7] = ["heading", "setting", "place", "time", "day", "summary", "body"];fn no_draft() -> MethodError {    refused("not_found", line("refusal.no_draft", &[]).unwrap_or_default())}fn line_json(row: &Map<String, Value>, cast: &[Map<String, Value>]) -> Value {    let beat = desk::beat_of(row, cast);    json!({        "id": str_of(row, "id"),        "kind": beat.kind.word(),        "who": beat.who,        "character": row.get("character").filter(|value| !value.is_null()).cloned().unwrap_or(Value::Null),        "aside": beat.aside,        "form": beat.form,        "text": beat.text,    })}fn held_of(lines: &[Value]) -> Vec<Held> {    lines.iter().filter_map(|line| serde_json::from_value::<Held>(line.clone()).ok()).collect()}fn lines_in(row: &Map<String, Value>) -> Vec<Value> {    serde_json::from_str::<Vec<Value>>(str_of(row, "lines")).unwrap_or_default()}/// `story.drafts.mark { story?, name }` → `{ draft }`.pub(super) fn mark(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let story = story_named(ctx, request)?;    let name = text(request, "name").map(str::trim).filter(|name| !name.is_empty()).ok_or_else(|| bad("a draft has a name, like Second draft"))?.to_string();    ink::lay_story(ctx, &story)?;    let cast = characters_of(ctx, &story)?;    let places = rows(ctx, PLACE, json!({ "story": story }))?;    let scenes = scenes_of(ctx, &story)?;    let named = |list: &[Map<String, Value>]| -> String { json!(list.iter().map(|row| json!({ "id": str_of(row, "id"), "name": str_of(row, "name") })).collect::<Vec<_>>()).to_string() };    let pages: f64 = scenes.iter().map(|scene| num_of(scene, "pages")).sum();    let draft = create(        ctx,        DRAFT,        json!({ "story": story, "name": name, "made_at": now_iso(ctx), "scenes": scenes.len(), "pages": (pages * 10.0).round() / 10.0, "cast": named(&cast), "places": named(&places) }),    )?;    for (at, scene) in scenes.iter().enumerate() {        let lines: Vec<Value> = desk::line_rows(ctx, str_of(scene, "id"))?.iter().map(|row| line_json(row, &cast)).collect();        let mut data = object(json!({ "draft": draft, "story": story, "scene": str_of(scene, "id"), "position": at + 1, "lines": json!(lines).to_string() }));        for key in KEPT {            if let Some(value) = scene.get(key).filter(|value| !value.is_null()) {                data.insert(key.into(), value.clone());            }        }        create(ctx, DRAFT_SCENE, Value::Object(data))?;    }    Ok(json!({ "draft": draft }))}fn draft_json(row: &Map<String, Value>) -> Value {    json!({ "id": str_of(row, "id"), "name": str_of(row, "name"), "made_at": str_of(row, "made_at"), "scenes": num_of(row, "scenes") as u64, "pages": num_of(row, "pages") })}/// `story.drafts.list { story? }` → `{ drafts, hint }`, newest first; `hint`/// is the name field's suggestion for the next draft ("First draft" while/// there is none, then "Second draft", …).pub(super) fn list(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let story = story_named(ctx, request)?;    let mut drafts = rows(ctx, DRAFT, json!({ "story": story }))?;    drafts.sort_by(|a, b| str_of(b, "made_at").cmp(str_of(a, "made_at")));    Ok(json!({ "drafts": drafts.iter().map(draft_json).collect::<Vec<_>>(), "hint": next_hint(drafts.len() + 1)? }))}/// The name suggested for the `n`th draft.fn next_hint(n: usize) -> Result<String, MethodError> {    line(&format!("ink.draft_hints.{n}"), &[]).or_else(|_| line("ink.draft_hints.other", &[("n", &n.to_string())]))}fn draft_of(ctx: &mut Ctx<'_>, request: &Value) -> Result<(Map<String, Value>, Vec<Map<String, Value>>), MethodError> {    let id = id_of(request, "draft")?;    let draft = get(ctx, DRAFT, id).filter(|row| row.get("story").is_some()).ok_or_else(no_draft)?;    let mut scenes = rows(ctx, DRAFT_SCENE, json!({ "draft": id }))?;    scenes.sort_by(|a, b| num_of(a, "position").total_cmp(&num_of(b, "position")));    Ok((draft, scenes))}/// `story.drafts.read { draft }`: the draft whole, laid out and as Fountain.pub(super) fn read(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let (draft, scenes) = draft_of(ctx, request)?;    let names: Vec<String> = serde_json::from_str::<Vec<Value>>(str_of(&draft, "cast")).unwrap_or_default().iter().filter_map(|one| one["name"].as_str().map(str::to_string)).collect();    let laid = layout::script(        &scenes.iter().map(|scene| layout::SceneIn { id: str_of(scene, "scene").to_string(), heading: str_of(scene, "heading").to_string(), body: str_of(scene, "body").to_string() }).collect::<Vec<_>>(),        &names,    );    let story = get(ctx, STORY, str_of(&draft, "story")).unwrap_or_default();    let mut title = vec![("Title".to_string(), str_of(&story, "title").to_string())];    let author = written_by(ctx, &story);    if !author.is_empty() {        title.push(("Credit".to_string(), line("script.title_page_by", &[])?));        title.push(("Author".to_string(), author));    }    title.push(("Draft".to_string(), str_of(&draft, "name").to_string()));    title.push(("Draft date".to_string(), str_of(&draft, "made_at").chars().take(10).collect()));    let doc = fountain::Doc {        title,        scenes: scenes.iter().map(|scene| fountain::SceneDoc { heading: str_of(scene, "heading").to_string(), summary: Some(str_of(scene, "summary").to_string()).filter(|s| !s.trim().is_empty()), body: str_of(scene, "body").to_string() }).collect(),    };    let shown: Vec<Value> = scenes        .iter()        .enumerate()        .map(|(at, scene)| json!({ "scene": str_of(scene, "scene"), "number": at + 1, "heading": str_of(scene, "heading"), "summary": scene.get("summary").cloned().unwrap_or(Value::Null), "day": scene.get("day").cloned().unwrap_or(Value::Null), "body": str_of(scene, "body"), "lines": lines_in(scene) }))        .collect();    let name = file_name(&format!("{} - {}", str_of(&story, "title"), str_of(&draft, "name")));    Ok(json!({ "draft": draft_json(&draft), "scenes": shown, "pages": laid.pages, "fountain_text": fountain::write(&doc), "fountain_name": name }))}/// The story's scenes as they stand, each line with its id: a scene's rows,/// or (a body written whole and not laid yet) its body laid over its rows in/// memory, so the ids are the ones a write would keep.fn now_of(ctx: &mut Ctx<'_>, story: &str) -> Result<Vec<SceneAt>, MethodError> {    let cast = characters_of(ctx, story)?;    let names = names_in(&cast);    let mut out = Vec::new();    for scene in scenes_of(ctx, story)? {        let id = str_of(&scene, "id").to_string();        let held: Vec<Held> = desk::line_rows(ctx, &id)?.iter().map(|row| Held { id: str_of(row, "id").to_string(), beat: desk::beat_of(row, &cast) }).collect();        let laid = identity::reconcile(&held, &cotton_core::cotton_rules::story::beats::read(str_of(&scene, "body"), &names));        let lines = laid.lines.into_iter().enumerate().map(|(at, placed)| Held { id: placed.id.unwrap_or_else(|| format!("new:{at}")), beat: placed.beat }).collect();        out.push(SceneAt { scene: id, heading: str_of(&scene, "heading").to_string(), summary: Some(str_of(&scene, "summary").to_string()).filter(|s| !s.trim().is_empty()), lines });    }    Ok(out)}/// `story.drafts.changes { draft }`: what changed since, by identity.pub(super) fn changes(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let (draft, scenes) = draft_of(ctx, request)?;    let then: Vec<SceneAt> = scenes        .iter()        .map(|scene| SceneAt { scene: str_of(scene, "scene").to_string(), heading: str_of(scene, "heading").to_string(), summary: Some(str_of(scene, "summary").to_string()).filter(|s| !s.trim().is_empty()), lines: held_of(&lines_in(scene)) })        .collect();    let now = now_of(ctx, str_of(&draft, "story"))?;    let mut out = json!(identity::changes(&then, &now));    out["draft"] = draft_json(&draft);    Ok(out)}/// A row by its id, brought back from Deleted when it went there.fn live_or_back(ctx: &mut Ctx<'_>, table: &str, id: &str) -> Option<Map<String, Value>> {    // A binned row reads as itself here: bring it back first (a live one is left as it is).    cotton_tools::mcp::handlers::tables::restore_binned(ctx, id).ok()?;    get(ctx, table, id).filter(|row| row.get("story").is_some())}/// `story.drafts.restore { draft }`: the working copy becomes the draft/// again: its scenes in its order with their heading parts, words and lines/// (each line its own id again where it can be), scenes made since sent to/// Deleted. Going back is itself a change in history.pub(super) fn restore(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let (draft, scenes) = draft_of(ctx, request)?;    let story = str_of(&draft, "story").to_string();    let cast = characters_of(ctx, &story)?;    let mut kept_scenes: Vec<String> = Vec::new();    for (at, then) in scenes.iter().enumerate() {        let mut patch = object(json!({ "position": at + 1 }));        for key in KEPT.iter().filter(|key| **key != "body") {            patch.insert((*key).into(), then.get(*key).filter(|value| !value.is_null()).cloned().unwrap_or(Value::Null));        }        if patch.get("place").and_then(Value::as_str).is_some_and(|place| live_or_back(ctx, PLACE, place).is_none()) {            patch.insert("place".into(), Value::Null);        }        let scene = match live_or_back(ctx, SCENE, str_of(then, "scene")) {            Some(row) => {                let id = str_of(&row, "id").to_string();                update(ctx, SCENE, &id, patch)?;                id            }            None => {                patch.retain(|_, value| !value.is_null());                patch.insert("story".into(), json!(story));                patch.insert("status".into(), json!("draft"));                create(ctx, SCENE, Value::Object(patch))?            }        };        let lines = lines_in(then);        let mut wanted: Vec<String> = Vec::new();        for (n, line) in lines.iter().enumerate() {            let mut data = object(json!({ "scene": scene, "position": n + 1, "kind": line["kind"].as_str().and_then(BeatKind::parse).unwrap_or(BeatKind::Action).word(), "text": line["text"].as_str().unwrap_or_default() }));            for key in ["who", "aside", "form", "character"] {                data.insert(key.into(), line.get(key).filter(|value| value.is_string()).cloned().unwrap_or(Value::Null));            }            if data.get("character").and_then(Value::as_str).is_some_and(|who| !cast.iter().any(|one| str_of(one, "id") == who)) {                data.insert("character".into(), Value::Null);            }            let id = match line["id"].as_str().and_then(|id| live_or_back(ctx, desk::LINE, id)) {                Some(row) => {                    let id = str_of(&row, "id").to_string();                    update(ctx, desk::LINE, &id, data)?;                    id                }                None => {                    data.retain(|_, value| !value.is_null());                    data.insert("story".into(), json!(story));                    create(ctx, desk::LINE, Value::Object(data))?                }            };            wanted.push(id);        }        for row in desk::line_rows(ctx, &scene)? {            if !wanted.iter().any(|id| id == str_of(&row, "id")) {                desk::remove(ctx, desk::LINE, str_of(&row, "id"))?;            }        }        desk::keep(ctx, &scene)?;        kept_scenes.push(scene);    }    for scene in scenes_of(ctx, &story)? {        if !kept_scenes.iter().any(|id| id == str_of(&scene, "id")) {            desk::remove(ctx, SCENE, str_of(&scene, "id"))?;        }    }    recount(ctx, &story, &mut Vec::new())?;    Ok(json!({ "scenes": kept_scenes.len(), "draft": draft_json(&draft) }))}