Cotton code
1288 lines · 60.5 KB · RustRaw
//! Cotton Story's four screens, answered whole: the fan's list of stories//! (`story.list`), the scene list (`story.scenes`), Your story//! (`story.interview`), one scene being written (`story.scene`) and its draft//! page (`story.draft`), and every write they offer. The phone draws what//! these answer and decides nothing; every word is a `story` line.//!//! A scene written beat by beat keeps its rows in `story_line` and its//! Fountain body from them, `lines_sum` naming the body the rows were kept//! for. A body that no longer matches was written elsewhere (an assistant, an//! older phone), and the body is then the truth: such a scene, like every//! scene written before these rows, reads from its body with ids `body:<n>`,//! and takes rows the first time a line in it is written.//!//! Minutes: one screenplay page is one minute, a page being 55 lines of the//! laid-out script counted in eighths (`figures::of_scene`). A scene with//! nothing written is no minutes; a written one says at least 1 min.use sha2::{Digest, Sha256};use cotton_core::rules::story_writing::{band_of, next_tint, tint_of, writing, Tint};use cotton_core::cotton_rules::story::beats::{self, Beat, BeatKind};use super::*;pub const LINE: &str = "story_line";pub const ANSWER: &str = "story_answer";pub const SEQUENCE: &str = "story_sequence";const FROM_BODY: &str = "body:";const START: &str = "start";pub(super) fn remove(ctx: &mut Ctx<'_>, table: &str, id: &str) -> Result<(), MethodError> {    tables::delete_record(ctx, &object(json!({ "table": table, "id": id }))).map_err(tool)?;    Ok(())}fn no_scene() -> MethodError {    refused("not_found", line("refusal.no_scene", &[]).unwrap_or_default())}pub(super) fn scene_row(ctx: &mut Ctx<'_>, id: &str) -> Result<Map<String, Value>, MethodError> {    get(ctx, SCENE, id).ok_or_else(no_scene)}// ── words ───────────────────────────────────────────────────────────────────fn tint_json(tint: &Tint) -> Value {    json!({ "key": tint.key, "ink": tint.ink, "paper": tint.paper })}fn initial(name: &str) -> String {    name.trim().chars().next().map(|first| first.to_uppercase().collect()).unwrap_or_default()}pub(super) fn person(row: &Map<String, Value>) -> Value {    let name = &softened(str_of(row, "name"));    let picture = some_text(row, "picture");    json!({ "id": str_of(row, "id"), "name": name, "initial": initial(name), "tint": tint_json(tint_of(str_of(row, "tint"), name)), "picture": picture, "lines": num_of(row, "lines") as i64 })}/// The one line a scene's row tells it apart by: the person's summary if/// written, else its first line (a speech as `NAME: words`).fn telling(scene: &Map<String, Value>, held: &[Shown]) -> Result<Value, MethodError> {    if let Some(summary) = some_text(scene, "summary") {        return Ok(json!(summary));    }    let Some(first) = held.iter().find(|one| matches!(one.beat.kind, BeatKind::Dialogue | BeatKind::Action) && !one.beat.text.trim().is_empty()) else {        return Ok(Value::Null);    };    let words = first.beat.text.replace('\n', " ");    Ok(json!(match first.beat.kind {        BeatKind::Dialogue => line("scenes.said", &[("name", &first.beat.who.clone().unwrap_or_default().to_uppercase()), ("text", &words)])?,        _ => words,    }))}/// A name written all in capitals, as a heading has it, set as a name.pub(super) fn softened(text: &str) -> String {    let text = text.trim();    if text.chars().any(char::is_lowercase) || !text.chars().any(char::is_uppercase) {        return text.to_string();    }    text.split(' ')        .map(|word| {            let mut letters = word.chars();            letters.next().map(|first| first.to_uppercase().chain(letters.flat_map(char::to_lowercase)).collect::<String>()).unwrap_or_default()        })        .collect::<Vec<_>>()        .join(" ")}fn minutes_word(minutes: f64) -> Result<Value, MethodError> {    if minutes <= 0.0 {        return Ok(Value::Null);    }    let shown = (minutes.round() as i64).max(1).to_string();    Ok(json!(line("minutes.short", &[("n", &shown)])?))}/// "5 scenes · 7 min".fn tally(scenes: usize, minutes: f64) -> Result<String, MethodError> {    let said = (minutes.round() as i64).max(i64::from(minutes > 0.0)).to_string();    line("list.summary", &[("scenes", &counted("length.scenes", scenes as i64)?), ("minutes", &line("minutes.short", &[("n", &said)])?)])}// ── a scene's beats ─────────────────────────────────────────────────────────fn sum(body: &str) -> String {    hex::encode(Sha256::digest(body.as_bytes()))}/// Do this scene's rows speak for its body?fn kept(scene: &Map<String, Value>) -> bool {    let held = str_of(scene, "lines_sum");    !held.is_empty() && held == sum(str_of(scene, "body"))}pub(super) fn line_rows(ctx: &mut Ctx<'_>, scene: &str) -> Result<Vec<Map<String, Value>>, MethodError> {    let mut found = lines_where(ctx, "scene", scene)?;    in_line_order(&mut found);    Ok(found)}fn in_line_order(found: &mut [Map<String, Value>]) {    found.sort_by(|a, b| num_of(a, "position").total_cmp(&num_of(b, "position")).then_with(|| str_of(a, "created_at").cmp(str_of(b, "created_at"))).then_with(|| str_of(a, "id").cmp(str_of(b, "id"))));}/// The line columns a read answers (`story_line`'s kit table).const LINE_COLUMNS: [&str; 9] = ["story", "scene", "position", "kind", "character", "who", "aside", "form", "text"];/// The live lines whose `column` (`scene` or `story`) is `id`, read straight/// from this copy's table, as Story's `rows` answers them (the columns that/// hold a value, the id, created_at). Lines are the rows a screen reads by/// the thousand; the records tool's list (a counted total, each row shaped/// as a record) cost ten times this, and put Story's first read over the/// launch budget (rust-main 16198: 100 scenes of 40 lines, 1.6 s).fn lines_where(ctx: &mut Ctx<'_>, column: &str, id: &str) -> Result<Vec<Map<String, Value>>, MethodError> {    use rusqlite::types::Value as Sql;    debug_assert!(column == "scene" || column == "story");    let made = tables::made_table(LINE);    let sql = format!("SELECT id, created_at, {} FROM {made} WHERE workspace_id = ? AND deleted_at IS NULL AND {column} = ?", LINE_COLUMNS.join(", "));    let found = ctx        .db()        .all(&sql, &[Sql::Text(ctx.workspace_id.to_string()), Sql::Text(id.to_string())])        .map_err(|error| MethodError::new("unreadable", error.to_string()))?;    Ok(found        .iter()        .map(|row| {            row.columns()                .iter()                .filter_map(|(name, value)| {                    let value = match value {                        Sql::Null | Sql::Blob(_) => return None,                        Sql::Integer(n) => Value::from(*n),                        Sql::Real(x) => Value::from(*x),                        Sql::Text(text) => Value::from(text.clone()),                    };                    Some((name.clone(), value))                })                .collect()        })        .collect())}/// A story's line rows by scene, each in [`line_rows`]' order: one read for a/// screen over every scene. Every writer names the story on a line/// (`line_add`, `ink::lay`, the Worker's story_line tools), as `ink`'s own/// reads by story rely on.fn lines_by_scene(ctx: &mut Ctx<'_>, story: &str) -> Result<std::collections::HashMap<String, Vec<Map<String, Value>>>, MethodError> {    let mut by: std::collections::HashMap<String, Vec<Map<String, Value>>> = std::collections::HashMap::new();    for row in lines_where(ctx, "story", story)? {        by.entry(str_of(&row, "scene").to_string()).or_default().push(row);    }    for held in by.values_mut() {        in_line_order(held);    }    Ok(by)}fn some_text(row: &Map<String, Value>, key: &str) -> Option<String> {    Some(str_of(row, key).trim().to_string()).filter(|text| !text.is_empty())}pub(super) fn beat_of(row: &Map<String, Value>, cast: &[Map<String, Value>]) -> Beat {    let named = cast.iter().find(|one| str_of(one, "id") == str_of(row, "character")).map(|one| str_of(one, "name").to_string());    Beat {        kind: BeatKind::parse(str_of(row, "kind")).unwrap_or(BeatKind::Action),        who: named.or_else(|| some_text(row, "who")),        aside: some_text(row, "aside"),        form: some_text(row, "form"),        text: str_of(row, "text").to_string(),    }}/// One beat as a scene shows it, with the id a write names it by.struct Shown {    id: String,    beat: Beat,}fn shown(ctx: &mut Ctx<'_>, scene: &Map<String, Value>, cast: &[Map<String, Value>]) -> Result<Vec<Shown>, MethodError> {    if kept(scene) {        let held = line_rows(ctx, str_of(scene, "id"))?;        return Ok(shown_held(&held, cast));    }    Ok(shown_body(scene, cast))}/// [`shown`] with the story's lines already read ([`lines_by_scene`]).fn shown_in(scene: &Map<String, Value>, cast: &[Map<String, Value>], lines: &std::collections::HashMap<String, Vec<Map<String, Value>>>) -> Vec<Shown> {    if kept(scene) {        return shown_held(lines.get(str_of(scene, "id")).map(Vec::as_slice).unwrap_or_default(), cast);    }    shown_body(scene, cast)}fn shown_held(held: &[Map<String, Value>], cast: &[Map<String, Value>]) -> Vec<Shown> {    held.iter().map(|row| Shown { id: str_of(row, "id").to_string(), beat: beat_of(row, cast) }).collect()}fn shown_body(scene: &Map<String, Value>, cast: &[Map<String, Value>]) -> Vec<Shown> {    let read = beats::read(str_of(scene, "body"), &names_in(cast));    read.into_iter().enumerate().map(|(at, beat)| Shown { id: format!("{FROM_BODY}{at}"), beat }).collect()}pub(super) fn entrance(name: &str) -> String {    line("composer.enters_page", &[("name", name)]).unwrap_or_default()}/// Write the scene's body from its rows, its figures and speakers with it.pub(super) fn keep(ctx: &mut Ctx<'_>, id: &str) -> Result<(), MethodError> {    let scene = scene_row(ctx, id)?;    let cast = characters_of(ctx, str_of(&scene, "story"))?;    let held: Vec<Beat> = line_rows(ctx, id)?.iter().map(|row| beat_of(row, &cast)).collect();    let body = beats::compose(&held, &names_in(&cast), &entrance);    write_scene(ctx, id, &json!({ "body": body }))?;    update(ctx, SCENE, id, object(json!({ "lines_sum": sum(&body) })))}/// The scene's rows, laid over its body when the body was written whole/// elsewhere (an assistant, a rename, a Fountain file): a line kept or edited/// in place keeps its row and id (`identity::reconcile`).pub(super) fn adopted(ctx: &mut Ctx<'_>, id: &str) -> Result<Vec<Map<String, Value>>, MethodError> {    let scene = scene_row(ctx, id)?;    if kept(&scene) {        return line_rows(ctx, id);    }    super::ink::lay(ctx, &scene)?;    keep(ctx, id)?;    line_rows(ctx, id)}/// The row a request's line id names, `body:<n>` read in the adopted order.fn named_line<'a>(held: &'a [Map<String, Value>], id: &str) -> Result<&'a Map<String, Value>, MethodError> {    let found = match id.strip_prefix(FROM_BODY) {        Some(at) => at.parse::<usize>().ok().and_then(|at| held.get(at)),        None => held.iter().find(|row| str_of(row, "id") == id),    };    found.ok_or_else(|| refused("not_found", line("refusal.no_line_id", &[]).unwrap_or_default()))}/// The order key for a line after `after` (`start`, a line, or the end).fn line_key(held: &[Map<String, Value>], after: Option<&str>) -> Result<Option<f64>, MethodError> {    let key = |at: usize| held.get(at).map(|row| num_of(row, "position"));    Ok(match after {        None => beats::between(held.last().map(|row| num_of(row, "position")), None),        Some(START) => beats::between(None, key(0)),        Some(id) => {            let row = named_line(held, id)?;            let at = held.iter().position(|one| str_of(one, "id") == str_of(row, "id")).unwrap_or(0);            beats::between(key(at), key(at + 1))        }    })}// ── reading a scene ─────────────────────────────────────────────────────────/// Where and when a scene happens, as the list says it.struct Spot {    place: String,    time: String,}fn spot(scene: &Map<String, Value>, places: &[Map<String, Value>]) -> Spot {    let parts = heading::parse(str_of(scene, "heading"));    let kept_place = places.iter().find(|place| str_of(place, "id") == str_of(scene, "place")).map(|place| str_of(place, "name").to_string());    let time = Some(str_of(scene, "time").to_string()).filter(|time| !time.trim().is_empty()).or(parts.time).unwrap_or_default();    Spot { place: softened(&kept_place.unwrap_or(parts.place)), time: time.trim().to_lowercase() }}fn spot_title(spot: &Spot) -> Result<String, MethodError> {    match (spot.place.is_empty(), spot.time.is_empty()) {        (true, true) => line("heading.untitled", &[]),        (false, true) => Ok(spot.place.clone()),        (true, false) => Ok(spot.time.clone()),        (false, false) => line("scenes.place_time", &[("place", &spot.place), ("time", &spot.time)]),    }}fn band_json(spot: &Spot) -> (Value, Value) {    band_of(&spot.time).map(|band| (json!(band.band), json!(band.dot))).unwrap_or((Value::Null, Value::Null))}fn tint_for(who: &str, cast: &[Map<String, Value>]) -> &'static Tint {    let kept = cast.iter().find(|one| same_name(str_of(one, "name"), who)).map(|one| str_of(one, "tint")).unwrap_or_default();    tint_of(kept, who)}/// The line a scene's row in the list shows: its last speech, else its first/// action.fn preview(held: &[Shown], cast: &[Map<String, Value>]) -> Result<Value, MethodError> {    if let Some(speech) = held.iter().rev().find(|one| one.beat.kind == BeatKind::Dialogue) {        let who = speech.beat.who.clone().unwrap_or_default();        let said = speech.beat.text.replace('\n', " ");        let words = line("scenes.said", &[("name", &who.to_uppercase()), ("text", &said)])?;        return Ok(json!({ "kind": "dialogue", "who": who, "text": words, "tint": tint_json(tint_for(&who, cast)) }));    }    Ok(match held.iter().find(|one| one.beat.kind == BeatKind::Action) {        Some(action) => json!({ "kind": "action", "who": Value::Null, "text": action.beat.text.replace('\n', " "), "tint": Value::Null }),        None => Value::Null,    })}/// A scene's minutes: none while nothing is written, else the minutes its figures keep. Every writer of a heading or a/// body works them out then (`derived` here, the Worker's story_scene_write with the same rule), and a character added/// since refigures the story (`refigure`); a row from before figures were kept is worked out from its body. Reading/// every body again here made Story's first read 0.4 s of a 0.75 s launch over 100 scenes (23 Nov 2026).fn minutes_of(scene: &Map<String, Value>, written: bool, names: &[String]) -> f64 {    if !written {        return 0.0;    }    match scene.get("minutes").and_then(Value::as_f64) {        Some(kept) => kept,        None => figures::of_scene(str_of(scene, "heading"), str_of(scene, "body"), names).minutes,    }}/// Is anything written in the scene, read without its lines or its beats: a body with words. A scene kept from its rows/// has its body written from them; a body of notes alone counts as written here.fn written(scene: &Map<String, Value>) -> bool {    !str_of(scene, "body").trim().is_empty()}/// The chips a scene offers: the story's characters, most used first.fn chips(cast: &[Map<String, Value>]) -> Vec<Value> {    cast.iter().filter(|one| !str_of(one, "name").trim().is_empty()).map(person).collect()}/// Where the next line goes in `held`: the index it will stand at.fn point_of(held: &[Shown], after: Option<&str>, editing: Option<&str>) -> usize {    if let Some(at) = editing.and_then(|id| held.iter().position(|one| one.id == id)) {        return at;    }    match after {        None => held.len(),        Some(START) => 0,        Some(id) => held.iter().position(|one| one.id == id).map_or(held.len(), |at| at + 1),    }}/// The characters who speak or enter in `beats`, most recent first, each once.fn speakers_back<'a>(beats: impl Iterator<Item = &'a Shown>, cast: &'a [Map<String, Value>]) -> Vec<&'a Map<String, Value>> {    let mut found: Vec<&Map<String, Value>> = Vec::new();    for one in beats.filter(|one| matches!(one.beat.kind, BeatKind::Dialogue | BeatKind::Enters)) {        let who = one.beat.who.as_deref().unwrap_or_default();        if let Some(row) = cast.iter().find(|row| same_name(str_of(row, "name"), who)) {            if !found.iter().any(|seen| str_of(seen, "id") == str_of(row, "id")) {                found.push(row);            }        }    }    found}/// The composer's pick (contract, 19 Nov 2026, the shared composer): who or/// what the next line is, and the menu its chip opens.////// RULE (owner, 19 Nov 2026): Action and Note first, their own section; then/// the characters by full name: the speaker suggested next at the top, then/// those already speaking in this scene, most recent first, then everyone/// else by their lines in the whole screenplay; New character… last. The/// phone never sorts or counts.////// The suggestion: a line being changed keeps its own; someone who just/// entered speaks; in an exchange between two people, the other one; after/// one speaker alone, the next character in the order; before any speech,/// Action.////// Shape:/// `{ "next": { "kind": "action"|"note"|"character", "character": id|null },///    "sections": [ { "key": "kinds", "rows": [row…] }, { "key": "characters", "rows": [row…] } ],///    "new": { "label", "hint" }, "label" }`, `label` the chip's spoken name, a row being/// `{ "kind", "character": id|null, "name", "initial"|null, "tint": {key, ink, paper}|null, "suggested": bool }`.fn pick(held: &[Shown], cast: &[Map<String, Value>], after: Option<&str>, editing: Option<&str>) -> Result<Value, MethodError> {    let point = point_of(held, after, editing);    let before = speakers_back(held[..point].iter().rev(), cast);    let after_point = speakers_back(held[point.min(held.len())..].iter(), cast);    let mut order: Vec<&Map<String, Value>> = Vec::new();    for row in before.iter().chain(after_point.iter()).copied().chain(cast.iter()) {        if !str_of(row, "name").trim().is_empty() && !order.iter().any(|seen| str_of(seen, "id") == str_of(row, "id")) {            order.push(row);        }    }    let changing = editing.and_then(|id| held.iter().find(|one| one.id == id));    let last = held[..point].last();    let next: (&str, Option<&Map<String, Value>>) = match changing {        Some(one) => match one.beat.kind {            BeatKind::Dialogue | BeatKind::Enters => ("character", speakers_back(std::iter::once(one), cast).first().copied()),            BeatKind::Note => ("note", None),            BeatKind::Action => ("action", None),        },        None if last.is_some_and(|one| one.beat.kind == BeatKind::Enters) => ("character", speakers_back(last.into_iter(), cast).first().copied()),        None => match before.as_slice() {            [] => ("action", None),            [only] => ("character", order.iter().copied().find(|row| str_of(row, "id") != str_of(only, "id")).or(Some(*only))),            [_, other, ..] => ("character", Some(*other)),        },    };    let next = match next {        ("character", None) => ("action", None),        found => found,    };    let suggested = next.1.map(|row| str_of(row, "id"));    if let Some(at) = suggested.and_then(|id| order.iter().position(|row| str_of(row, "id") == id)) {        let row = order.remove(at);        order.insert(0, row);    }    let kind_row = |kind: &str, key: &str| -> Result<Value, MethodError> {        Ok(json!({ "kind": kind, "character": Value::Null, "name": line(key, &[])?, "initial": Value::Null, "tint": Value::Null, "suggested": next.0 == kind }))    };    let people: Vec<Value> = order        .iter()        .map(|row| {            let name = &softened(str_of(row, "name"));            json!({ "kind": "character", "character": str_of(row, "id"), "name": name, "initial": initial(name), "tint": tint_json(tint_of(str_of(row, "tint"), name)), "suggested": suggested == Some(str_of(row, "id")) })        })        .collect();    Ok(json!({        "next": { "kind": next.0, "character": suggested },        // The chooser lists characters only; Action and Note are the bar's two switches beside it (DECISIONS, 20 Nov).        "sections": [{ "key": "characters", "rows": people }],        "switches": [kind_row("action", "composer.action")?, kind_row("note", "composer.note")?],        "new": { "label": line("pick.new", &[])?, "hint": line("pick.new_hint", &[])? },        "label": line("pick.label", &[])?,    }))}fn insert_words(held: &[Shown], after: Option<&str>) -> Result<Value, MethodError> {    let Some(after) = after else { return Ok(Value::Null) };    if after == START {        return Ok(json!({ "after": START, "words": line("adding.at_start", &[])? }));    }    let Some(found) = held.iter().find(|one| one.id == after) else { return Ok(Value::Null) };    let who = softened(found.beat.who.as_deref().unwrap_or_default());    let words = match found.beat.kind {        BeatKind::Dialogue => line("adding.after_speech", &[("name", &who)])?,        BeatKind::Enters => line("adding.after_enters", &[("name", &who)])?,        BeatKind::Note => line("adding.after_note", &[])?,        BeatKind::Action => line("adding.after_action", &[])?,    };    Ok(json!({ "after": after, "words": words }))}/// What the composer says while a line is being changed.fn changing_words(found: &Shown) -> Result<String, MethodError> {    let who = softened(found.beat.who.as_deref().unwrap_or_default());    match found.beat.kind {        BeatKind::Dialogue => line("changing.speech", &[("name", &who)]),        BeatKind::Enters => line("changing.enters", &[("name", &who)]),        BeatKind::Note => line("changing.note", &[]),        BeatKind::Action => line("changing.action", &[]),    }}/// How a screen reader says a line whole.fn label_of(one: &Shown, text: &str) -> Result<String, MethodError> {    let who = softened(one.beat.who.as_deref().unwrap_or_default());    match one.beat.kind {        BeatKind::Dialogue => line("label.dialogue", &[("name", &who), ("text", text)]),        BeatKind::Action => line("label.action", &[("text", text)]),        BeatKind::Note => line("label.note", &[("text", text)]),        BeatKind::Enters => Ok(text.to_string()),    }}/// The sheet that sets a scene's place and time of day./// The places a story has used, most scenes first: the picker's offer.fn used_places(ctx: &mut Ctx<'_>, story: &str, places: &[Map<String, Value>]) -> Result<Vec<String>, MethodError> {    let scenes = scenes_of(ctx, story)?;    let mut counted: Vec<(usize, String)> = places        .iter()        .map(|place| (scenes.iter().filter(|scene| str_of(scene, "place") == str_of(place, "id")).count(), softened(str_of(place, "name"))))        .filter(|(n, name)| *n > 0 && !name.is_empty())        .collect();    counted.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1)));    Ok(counted.into_iter().map(|(_, name)| name).collect())}fn picker(scene: &Map<String, Value>, where_when: &Spot, used: Vec<String>) -> Result<Value, MethodError> {    let times = writing().times.iter().map(|band| Ok(json!({ "band": band.band, "word": line(&format!("picker.time.{}", band.band), &[])?, "dot": band.dot }))).collect::<Result<Vec<Value>, MethodError>>()?;    let settings = [("INT.", "picker.inside"), ("EXT.", "picker.outside")].iter().map(|(setting, word)| Ok(json!({ "setting": setting, "word": line(word, &[])? }))).collect::<Result<Vec<Value>, MethodError>>()?;    let setting = some_text(scene, "setting").or_else(|| heading::parse(str_of(scene, "heading")).setting);    Ok(json!({        "title": line("picker.title", &[])?,        "hint": line("heading.place_hint", &[])?,        "place": where_when.place,        "used_label": line("picker.used", &[])?,        "used": used,        "setting": setting,        "settings": settings,        "band": band_of(&where_when.time).map(|band| band.band.as_str()),        "times": times,        "summary": some_text(scene, "summary"),        "summary_hint": line("picker.summary_hint", &[])?,        "done": line("picker.done", &[])?,    }))}fn line_json(one: &Shown, cast: &[Map<String, Value>]) -> Result<Value, MethodError> {    let who = one.beat.who.as_deref().unwrap_or_default();    let shown_name = softened(who);    let person_of = cast.iter().find(|row| same_name(str_of(row, "name"), who));    let text = match one.beat.kind {        BeatKind::Enters => line("composer.enters", &[("name", &shown_name)])?,        _ => one.beat.text.clone(),    };    let speaks = matches!(one.beat.kind, BeatKind::Dialogue | BeatKind::Enters);    Ok(json!({        "id": one.id,        "kind": one.beat.kind.word(),        "text": text,        "who": if speaks { json!(who.to_uppercase()) } else { Value::Null },        "character": person_of.map(|row| json!(str_of(row, "id"))).unwrap_or(Value::Null),        "initial": if speaks { json!(initial(who)) } else { Value::Null },        "tint": if speaks { tint_json(tint_for(who, cast)) } else { Value::Null },        "aside": one.beat.aside,        "form": one.beat.form,        "label": label_of(one, &text)?,    }))}fn scene_view(ctx: &mut Ctx<'_>, id: &str, after: Option<&str>) -> Result<Value, MethodError> {    scene_composing(ctx, id, after, None)}fn scene_composing(ctx: &mut Ctx<'_>, id: &str, after: Option<&str>, editing: Option<&str>) -> Result<Value, MethodError> {    let scene = scene_row(ctx, id)?;    let story = str_of(&scene, "story").to_string();    let cast = characters_of(ctx, &story)?;    let places = rows(ctx, PLACE, json!({ "story": story }))?;    let held = shown(ctx, &scene, &cast)?;    let where_when = spot(&scene, &places);    let (band, dot) = band_json(&where_when);    let minutes = minutes_of(&scene, !held.is_empty(), &names_in(&cast));    let lines = held.iter().map(|one| line_json(one, &cast)).collect::<Result<Vec<_>, _>>()?;    let changing = editing.and_then(|editing| held.iter().find(|one| one.id == editing));    let insert = if changing.is_some() { Value::Null } else { insert_words(&held, after)? };    let banner = match changing {        Some(found) => json!(changing_words(found)?),        None => insert["words"].clone(),    };    Ok(json!({        "id": id,        "story": story,        "title": spot_title(&where_when)?,        "place": where_when.place,        "time": where_when.time,        "band": band,        "dot": dot,        "slugline": slugline(&scene, &where_when),        "minutes": minutes,        "minutes_word": minutes_word(minutes)?,        "question": some_text(&scene, "question"),        "lines": lines,        "chips": chips(&cast),        "pick": pick(&held, &cast, if changing.is_some() { None } else { after }, changing.map(|found| found.id.as_str()))?,        "insert": insert,        "editing": changing.map(|found| found.id.as_str()),        "picker": picker(&scene, &where_when, used_places(ctx, &story, &places)?)?,        "composer": {            "action": line("composer.action", &[])?,            "note": line("composer.note", &[])?,            "hint": line("composer.hint", &[])?,            "draft": line("composer.draft", &[])?,            "banner": banner,            "text": changing.map(|found| found.beat.text.as_str()),            "close": line("composer.close", &[])?,            "send": line("composer.send", &[])?,            "insert": line("composer.insert", &[])?,            "remove": line("composer.remove", &[])?,        },    }))}/// The standard heading: the one written, else worked out from its parts.fn slugline(scene: &Map<String, Value>, spot: &Spot) -> String {    let written = str_of(scene, "heading").trim();    if !written.is_empty() {        return written.to_string();    }    heading::compose(&heading::Parts { setting: some_text(scene, "setting"), place: spot.place.clone(), time: Some(spot.time.clone()).filter(|time| !time.is_empty()) })}pub(super) fn scene(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let named = |key: &str| text(request, key).filter(|value| !value.trim().is_empty());    scene_composing(ctx, id_of(request, "id")?, named("after"), named("editing"))}// ── the list of stories and the scene list ─────────────────────────────────fn story_minutes(ctx: &mut Ctx<'_>, story: &str) -> Result<(usize, f64), MethodError> {    let names = names_in(&characters_of(ctx, story)?);    let scenes = scenes_of(ctx, story)?;    let minutes = scenes.iter().map(|scene| minutes_of(scene, written(scene), &names)).sum();    Ok((scenes.len(), minutes))}pub(super) fn list(ctx: &mut Ctx<'_>) -> Result<Value, MethodError> {    let mut stories = rows(ctx, STORY, json!({}))?;    stories.sort_by(|a, b| str_of(b, "chosen_at").cmp(str_of(a, "chosen_at")).then_with(|| str_of(b, "made_at").cmp(str_of(a, "made_at"))));    let current = current_story(ctx)?.0.map(|row| str_of(&row, "id").to_string());    let mut out = Vec::new();    for story in &stories {        let id = str_of(story, "id");        let (scenes, minutes) = story_minutes(ctx, id)?;        out.push(json!({ "id": id, "title": str_of(story, "title"), "scenes": scenes, "minutes": minutes, "summary": tally(scenes, minutes)?, "current": current.as_deref() == Some(id) }));    }    Ok(json!({ "stories": out, "empty": line("list.empty", &[])? }))}/// The fan's card for a screenplay.pub(super) fn fan_card_id(story: &str) -> String {    format!("story:{story}")}/// Cotton Story's fan after Account: one card a screenplay, in the order they/// were started so a card never moves when another is chosen, then the card/// that starts a new one. Answers the cards and the current screenplay's card.pub(super) fn fan_cards(ctx: &mut Ctx<'_>) -> Result<Value, MethodError> {    let mut stories = rows(ctx, STORY, json!({}))?;    stories.sort_by(|a, b| str_of(a, "made_at").cmp(str_of(b, "made_at")).then_with(|| str_of(a, "created_at").cmp(str_of(b, "created_at"))).then_with(|| str_of(a, "id").cmp(str_of(b, "id"))));    let mut cards = Vec::new();    for story in &stories {        let id = str_of(story, "id");        let label = match str_of(story, "title").trim() {            "" => line("fan.untitled", &[])?,            title => title.to_string(),        };        cards.push(json!({ "id": fan_card_id(id), "label": label, "default": false, "count": null, "face": "screenplay", "story": id, "read": { "table": SCENE, "where": { "story": id } } }));    }    cards.push(json!({        "id": "new_story",        "label": line("fan.new", &[])?,        "default": false,        "count": null,        "face": "screenplay_new",        // A table the app has a definition for: this card draws its own page.        "read": { "table": SCENE },        "create": { "method": "story.start", "hint": line("stories.title_hint", &[])? },    }));    let current = current_story(ctx)?.0.map(|row| fan_card_id(str_of(&row, "id")));    Ok(json!({ "cards": cards, "current": current }))}fn sequences_of(ctx: &mut Ctx<'_>, story: &str) -> Result<Vec<Map<String, Value>>, MethodError> {    let mut found = rows(ctx, SEQUENCE, json!({ "story": story }))?;    found.sort_by(|a, b| num_of(a, "position").total_cmp(&num_of(b, "position")));    Ok(found)}fn answers_of(ctx: &mut Ctx<'_>, story: &str) -> Result<Vec<Map<String, Value>>, MethodError> {    rows(ctx, ANSWER, json!({ "story": story }))}fn answered(row: &Map<String, Value>) -> bool {    !str_of(row, "answer").trim().is_empty()}/// The question to ask next: the first neither answered nor skipped, then/// the first skipped; none when every question has its answer.fn next_question(answers: &[Map<String, Value>]) -> Option<&'static String> {    let row = |key: &str| answers.iter().find(|row| str_of(row, "question") == key);    let questions = &writing().questions;    questions.iter().find(|key| row(key).is_none_or(|one| !answered(one) && one.get("skipped") != Some(&json!(true)))).or_else(|| questions.iter().find(|key| row(key).is_none_or(|one| !answered(one))))}fn question_words(question: &str) -> Result<String, MethodError> {    line(&format!("question.{question}"), &[])}fn slip(answers: &[Map<String, Value>]) -> Result<Value, MethodError> {    let next = next_question(answers);    Ok(json!({        "title": line("your_story.title", &[])?,        "key": next,        "question": match next { Some(key) => question_words(key)?, None => line("your_story.all_answered", &[])? },    }))}/// One scene's row in the list.fn scene_item(scene: &Map<String, Value>, number: usize, held: &[Shown], cast: &[Map<String, Value>], places: &[Map<String, Value>]) -> Result<(Value, f64), MethodError> {    let where_when = spot(scene, places);    let (band, dot) = band_json(&where_when);    let minutes = minutes_of(scene, !held.is_empty(), &names_in(cast));    let unwritten = held.is_empty();    let question = some_text(scene, "question").or_else(|| some_text(scene, "summary"));    Ok((        json!({            "kind": "scene",            "id": str_of(scene, "id"),            "number": number,            "title": spot_title(&where_when)?,            "band": band,            "dot": dot,            "minutes": minutes,            "minutes_word": minutes_word(minutes)?,            "preview": preview(held, cast)?,            "line": telling(scene, held)?,            "unwritten": unwritten,            "question": if unwritten { json!(question) } else { Value::Null },        }),        minutes,    ))}/// The script home's fixed pills, in order: Read, then Places once the/// script has a place, then All views (the last always).fn doors(places: &[Map<String, Value>]) -> Result<Vec<Value>, MethodError> {    let mut out = vec![json!({ "key": "read", "words": line("home.read", &[])? })];    if places.iter().any(|one| !str_of(one, "name").trim().is_empty()) {        out.push(json!({ "key": "places", "words": line("home.places", &[])? }));    }    out.push(json!({ "key": "views", "words": line("home.all_views", &[])? }));    Ok(out)}pub(super) fn scenes_view(ctx: &mut Ctx<'_>, story: &str) -> Result<Value, MethodError> {    let row = get(ctx, STORY, story).ok_or_else(|| refused("not_found", line("refusal.no_story", &[]).unwrap_or_default()))?;    let cast = characters_of(ctx, story)?;    let places = rows(ctx, PLACE, json!({ "story": story }))?;    let scenes = scenes_of(ctx, story)?;    let sequences = sequences_of(ctx, story)?;    let lines = lines_by_scene(ctx, story)?;    let mut items: Vec<(f64, Value, f64)> = Vec::new();    for (at, scene) in scenes.iter().enumerate() {        let held = shown_in(scene, &cast, &lines);        let (item, minutes) = scene_item(scene, at + 1, &held, &cast, &places)?;        items.push((num_of(scene, "position"), item, minutes));    }    let total: f64 = items.iter().map(|(_, _, minutes)| minutes).sum();    let interval = row.get("interval_at").and_then(Value::as_f64);    let mut out: Vec<Value> = Vec::new();    let mut interval_said = false;    let mut said_interval = |out: &mut Vec<Value>, before: Option<f64>| -> Result<(), MethodError> {        if let Some(at) = interval.filter(|at| !interval_said && before.is_none_or(|position| *at <= position)) {            out.push(json!({ "kind": "interval", "at": at, "words": line("scenes.interval", &[])? }));            interval_said = true;        }        Ok(())    };    let opening = sequences.first().map_or(f64::INFINITY, |first| num_of(first, "position"));    for (position, item, _) in items.iter().filter(|(position, _, _)| *position < opening) {        said_interval(&mut out, Some(*position))?;        out.push(item.clone());    }    for (at, sequence) in sequences.iter().enumerate() {        let from = num_of(sequence, "position");        let to = sequences.get(at + 1).map_or(f64::INFINITY, |next| num_of(next, "position"));        let inside: Vec<&(f64, Value, f64)> = items.iter().filter(|(position, _, _)| *position >= from && *position < to).collect();        let minutes: f64 = inside.iter().map(|(_, _, minutes)| minutes).sum();        let folded = sequence.get("folded") == Some(&json!(true));        said_interval(&mut out, Some(from))?;        out.push(json!({ "kind": "sequence", "id": str_of(sequence, "id"), "title": str_of(sequence, "title"), "folded": folded, "scenes": inside.len(), "summary": tally(inside.len(), minutes)? }));        for (position, item, _) in inside {            said_interval(&mut out, Some(*position))?;            if !folded {                out.push(item.clone());            }        }    }    said_interval(&mut out, None)?;    Ok(json!({        "story": {            "id": story, "title": str_of(&row, "title"), "summary": tally(scenes.len(), total)?,            "logline": some_text(&row, "logline"), "written_by": Some(super::written_by(ctx, &row)).filter(|by| !by.is_empty()),        },        "slip": slip(&answers_of(ctx, story)?)?,        "cast": chips(&cast),        "doors": doors(&places)?,        "rows": out,        "add": line("scenes.add", &[])?,    }))}pub(super) fn scenes(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let story = story_named(ctx, request)?;    scenes_view(ctx, &story)}// ── Your story ─────────────────────────────────────────────────────────────fn interview_view(ctx: &mut Ctx<'_>, story: &str) -> Result<Value, MethodError> {    let answers = answers_of(ctx, story)?;    let places = rows(ctx, PLACE, json!({ "story": story }))?;    let scenes = scenes_of(ctx, story)?;    let mut questions = Vec::new();    let mut read_back = Vec::new();    for key in &writing().questions {        let row = answers.iter().find(|row| str_of(row, "question") == key);        let words = question_words(key)?;        let said = row.filter(|one| answered(one)).map(|one| str_of(one, "answer").trim().to_string());        let state = match (&said, row.is_some_and(|one| one.get("skipped") == Some(&json!(true)))) {            (Some(_), _) => "answered",            (None, true) => "skipped",            (None, false) => "open",        };        let mut pointed = Vec::new();        if let Some(one) = row {            for scene in scenes.iter().filter(|scene| str_of(scene, "answer") == str_of(one, "id")) {                pointed.push(json!({ "id": str_of(scene, "id"), "title": spot_title(&spot(scene, &places))? }));            }        }        if let Some(answer) = &said {            read_back.push(json!({ "question": words, "answer": answer }));        }        questions.push(json!({ "key": key, "text": words, "state": state, "answer": said, "scenes": pointed }));    }    let page = read_back.iter().filter_map(|item| item["answer"].as_str()).collect::<Vec<_>>().join("\n\n");    Ok(json!({        "story": story,        "title": line("your_story.title", &[])?,        "questions": questions,        "current": next_question(&answers),        "done": line("your_story.all_answered", &[])?,        "skip": line("your_story.skip", &[])?,        "hint": line("your_story.answer_hint", &[])?,        "send": line("your_story.send", &[])?,        "summary": {            "label": line("your_story.summary", &[])?,            "items": read_back,            "text": page,            "empty": if page.is_empty() { json!(line("your_story.summary_empty", &[])?) } else { Value::Null },        },    }))}pub(super) fn interview(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let story = story_named(ctx, request)?;    interview_view(ctx, &story)}fn question_of(request: &Value) -> Result<String, MethodError> {    let key = id_of(request, "question")?;    if writing().questions.iter().any(|known| known == key) {        return Ok(key.to_string());    }    Err(refused("not_found", line("refusal.no_question", &[])?))}/// The answer row for a question, made when the story has none.fn answer_row(ctx: &mut Ctx<'_>, story: &str, question: &str) -> Result<String, MethodError> {    if let Some(row) = answers_of(ctx, story)?.iter().find(|row| str_of(row, "question") == question) {        return Ok(str_of(row, "id").to_string());    }    create(ctx, ANSWER, json!({ "story": story, "question": question }))}pub(super) fn answer(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let story = story_named(ctx, request)?;    let question = question_of(request)?;    let said = text(request, "text").map(str::trim).filter(|said| !said.is_empty()).ok_or_else(|| bad(line("refusal.empty_line", &[]).unwrap_or_default()))?;    let id = answer_row(ctx, &story, &question)?;    update(ctx, ANSWER, &id, object(json!({ "answer": said, "skipped": false, "answered_at": now_iso(ctx) })))?;    if let Some(pointed) = request.get("scenes").and_then(Value::as_array) {        for scene in pointed.iter().filter_map(Value::as_str) {            scene_row(ctx, scene)?;            update(ctx, SCENE, scene, object(json!({ "answer": id })))?;        }    }    interview_view(ctx, &story)}pub(super) fn skip(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let story = story_named(ctx, request)?;    let question = question_of(request)?;    let id = answer_row(ctx, &story, &question)?;    update(ctx, ANSWER, &id, object(json!({ "skipped": true })))?;    interview_view(ctx, &story)}// ── order: scenes, the interval and sequences on one line ──────────────────/// A mark standing between scenes: the interval or a sequence's start.pub(super) enum Mark {    Interval,    Sequence(String),}/// The marks of a story, each with how many scenes stand before it.pub(super) fn marks_held(ctx: &mut Ctx<'_>, story: &str, ordered: &[Map<String, Value>]) -> Result<Vec<(Mark, usize)>, MethodError> {    let before = |at: f64| ordered.iter().filter(|scene| num_of(scene, "position") < at).count();    let mut held = Vec::new();    if let Some(at) = get(ctx, STORY, story).and_then(|row| row.get("interval_at").and_then(Value::as_f64)) {        held.push((Mark::Interval, before(at)));    }    for sequence in sequences_of(ctx, story)? {        held.push((Mark::Sequence(str_of(&sequence, "id").to_string()), before(num_of(&sequence, "position"))));    }    Ok(held)}/// Stand the marks where they stood, the scenes numbered 1, 2, 3 again.pub(super) fn marks_put(ctx: &mut Ctx<'_>, story: &str, held: Vec<(Mark, usize)>) -> Result<(), MethodError> {    for (mark, before) in held {        let at = before as f64 + 0.5;        match mark {            Mark::Interval => update(ctx, STORY, story, object(json!({ "interval_at": at })))?,            Mark::Sequence(id) => update(ctx, SEQUENCE, &id, object(json!({ "position": at })))?,        }    }    Ok(())}/// Every mark at or after `from` moves down one with the scenes.pub(super) fn marks_shift(ctx: &mut Ctx<'_>, story: &str, from: f64) -> Result<(), MethodError> {    if let Some(at) = get(ctx, STORY, story).and_then(|row| row.get("interval_at").and_then(Value::as_f64)).filter(|at| *at >= from) {        update(ctx, STORY, story, object(json!({ "interval_at": at + 1.0 })))?;    }    for sequence in sequences_of(ctx, story)? {        let at = num_of(&sequence, "position");        if at >= from {            update(ctx, SEQUENCE, str_of(&sequence, "id"), object(json!({ "position": at + 1.0 })))?;        }    }    Ok(())}fn marks_at(ctx: &mut Ctx<'_>, story: &str) -> Result<Vec<f64>, MethodError> {    let mut at: Vec<f64> = sequences_of(ctx, story)?.iter().map(|row| num_of(row, "position")).collect();    at.extend(get(ctx, STORY, story).and_then(|row| row.get("interval_at").and_then(Value::as_f64)));    at.sort_by(f64::total_cmp);    Ok(at)}/// The key between two scenes. A mark in the gap keeps the new key on the/// earlier scene's side of it unless `across` says past it.fn gap_key(low: Option<f64>, high: Option<f64>, marks: &[f64], across: bool) -> Option<f64> {    let inside: Vec<f64> = marks.iter().copied().filter(|at| low.is_none_or(|low| *at > low) && high.is_none_or(|high| *at < high)).collect();    match (inside.first(), inside.last()) {        (Some(_), Some(last)) if across => beats::between(Some(*last), high),        (Some(first), Some(_)) => beats::between(low, Some(*first)),        _ => beats::between(low, high),    }}/// Where a scene goes after `after` (a scene, `start`, or the end).pub(super) fn scene_key(ctx: &mut Ctx<'_>, story: &str, moving: Option<&str>, after: Option<&str>, across: bool) -> Result<f64, MethodError> {    for _ in 0..2 {        let others: Vec<Map<String, Value>> = scenes_of(ctx, story)?.into_iter().filter(|scene| Some(str_of(scene, "id")) != moving).collect();        let key_at = |at: usize| others.get(at).map(|scene| num_of(scene, "position"));        let (low, high) = match after {            None => (others.last().map(|scene| num_of(scene, "position")), None),            Some(START) => (None, key_at(0)),            Some(id) => {                let at = others.iter().position(|scene| str_of(scene, "id") == id).ok_or_else(no_scene)?;                (key_at(at), key_at(at + 1))            }        };        let marks = marks_at(ctx, story)?;        if let Some(key) = gap_key(low, high, &marks, across) {            return Ok(key);        }        let ordered = scenes_of(ctx, story)?;        let held = marks_held(ctx, story, &ordered)?;        renumber(ctx, &ordered)?;        marks_put(ctx, story, held)?;    }    Err(MethodError::new("write_refused", "the scenes' order could not be opened"))}fn after_of(request: &Value) -> Option<&str> {    text(request, "after").map(str::trim).filter(|after| !after.is_empty())}fn across_of(request: &Value) -> bool {    request.get("across").and_then(Value::as_bool).unwrap_or(false)}pub(super) fn scene_add(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let story = story_named(ctx, request)?;    let position = scene_key(ctx, &story, None, after_of(request), across_of(request))?;    let id = create(ctx, SCENE, json!({ "story": story, "position": position, "setting": "INT.", "status": "draft", "words": 0, "pages": 0, "minutes": 0, "speakers": "" }))?;    if ["setting", "place", "time"].iter().any(|key| request.get(*key).is_some()) {        let parts = json!({ "setting": request.get("setting"), "place": request.get("place"), "time": request.get("time") });        let sent: Map<String, Value> = object(parts).into_iter().filter(|(_, value)| value.is_string()).collect();        write_scene(ctx, &id, &Value::Object(sent))?;    }    if let Some(question) = text(request, "question").map(str::trim).filter(|question| !question.is_empty()) {        update(ctx, SCENE, &id, object(json!({ "question": question })))?;    }    Ok(json!({ "scene": id, "scenes": scenes_view(ctx, &story)? }))}pub(super) fn scene_place(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let id = id_of(request, "id")?;    let story = str_of(&scene_row(ctx, id)?, "story").to_string();    // A scene dropped after itself stays where it stands.    if after_of(request) == Some(id) {        return scenes_view(ctx, &story);    }    let position = scene_key(ctx, &story, Some(id), Some(after_of(request).unwrap_or(START)), across_of(request))?;    update(ctx, SCENE, id, object(json!({ "position": position })))?;    scenes_view(ctx, &story)}pub(super) fn scene_remove(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let id = id_of(request, "id")?;    let story = str_of(&scene_row(ctx, id)?, "story").to_string();    remove(ctx, SCENE, id)?;    recount(ctx, &story, &mut Vec::new())?;    scenes_view(ctx, &story)}/// Has nothing at all been set down in this scene?fn blank(ctx: &mut Ctx<'_>, scene: &Map<String, Value>) -> Result<bool, MethodError> {    let said = ["body", "heading", "place", "time", "summary", "question", "answer"].iter().any(|key| !str_of(scene, key).trim().is_empty());    Ok(!said && line_rows(ctx, str_of(scene, "id"))?.is_empty())}/// The writer left a scene Plus just made: one with nothing in it goes, so/// Plus and back adds no scene. A scene holding anything at all stays.pub(super) fn scene_leave(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let id = id_of(request, "id")?;    let scene = scene_row(ctx, id)?;    let story = str_of(&scene, "story").to_string();    if blank(ctx, &scene)? {        remove(ctx, SCENE, id)?;    }    scenes_view(ctx, &story)}pub(super) fn interval(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let story = story_named(ctx, request)?;    let at = match after_of(request) {        Some(after) => json!(scene_key(ctx, &story, None, Some(after), true)?),        None => Value::Null,    };    update(ctx, STORY, &story, object(json!({ "interval_at": at })))?;    scenes_view(ctx, &story)}fn sequence_row(ctx: &mut Ctx<'_>, id: &str) -> Result<Map<String, Value>, MethodError> {    get(ctx, SEQUENCE, id).ok_or_else(|| refused("not_found", line("refusal.no_sequence", &[]).unwrap_or_default()))}fn title_of(request: &Value) -> Result<&str, MethodError> {    text(request, "title").map(str::trim).filter(|title| !title.is_empty()).ok_or_else(|| bad("this names the `title`"))}pub(super) fn sequence_add(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let story = story_named(ctx, request)?;    let title = title_of(request)?;    let position = scene_key(ctx, &story, None, Some(after_of(request).unwrap_or(START)), true)?;    create(ctx, SEQUENCE, json!({ "story": story, "title": title, "position": position, "folded": false }))?;    scenes_view(ctx, &story)}pub(super) fn sequence_edit(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let id = id_of(request, "id")?;    let story = str_of(&sequence_row(ctx, id)?, "story").to_string();    let mut patch = Map::new();    if request.get("title").is_some() {        patch.insert("title".into(), json!(title_of(request)?));    }    if let Some(folded) = request.get("folded").and_then(Value::as_bool) {        patch.insert("folded".into(), json!(folded));    }    update(ctx, SEQUENCE, id, patch)?;    scenes_view(ctx, &story)}pub(super) fn sequence_remove(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let id = id_of(request, "id")?;    let story = str_of(&sequence_row(ctx, id)?, "story").to_string();    remove(ctx, SEQUENCE, id)?;    scenes_view(ctx, &story)}// ── writing lines ──────────────────────────────────────────────────────────fn beat_kind(request: &Value) -> Result<BeatKind, MethodError> {    let word = text(request, "kind").unwrap_or_default();    BeatKind::parse(word).ok_or_else(|| bad(line("refusal.not_a_kind", &[("kind", word)]).unwrap_or_default()))}fn character_named(ctx: &mut Ctx<'_>, id: &str) -> Result<Map<String, Value>, MethodError> {    get(ctx, CHARACTER, id).ok_or_else(|| refused("not_found", line("refusal.no_character", &[]).unwrap_or_default()))}/// Write each line's order key afresh, 1, 2, 3.fn open_lines(ctx: &mut Ctx<'_>, held: &[Map<String, Value>]) -> Result<(), MethodError> {    for (at, row) in held.iter().enumerate() {        update(ctx, LINE, str_of(row, "id"), object(json!({ "position": at + 1 })))?;    }    Ok(())}pub(super) fn line_add(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let scene = id_of(request, "scene")?.to_string();    let kind = beat_kind(request)?;    let said = text(request, "text").map(str::trim).unwrap_or_default().to_string();    if said.is_empty() && kind != BeatKind::Enters {        return Err(bad(line("refusal.empty_line", &[])?));    }    let needs_character = matches!(kind, BeatKind::Dialogue | BeatKind::Enters);    let character = match text(request, "character").map(str::trim).filter(|id| !id.is_empty()) {        Some(id) => Some(character_named(ctx, id)?),        None if needs_character => return Err(bad(line("refusal.needs_character", &[])?)),        None => None,    };    let after = after_of(request);    let mut held = adopted(ctx, &scene)?;    let mut position = line_key(&held, after)?;    if position.is_none() {        open_lines(ctx, &held)?;        held = line_rows(ctx, &scene)?;        position = line_key(&held, after)?;    }    let position = position.ok_or_else(|| MethodError::new("write_refused", "the scene's order could not be opened"))?;    let story = str_of(&scene_row(ctx, &scene)?, "story").to_string();    let mut data = object(json!({ "story": story, "scene": scene, "position": position, "kind": kind.word(), "text": said }));    if let Some(character) = character.filter(|_| needs_character) {        data.insert("character".into(), json!(str_of(&character, "id")));        data.insert("who".into(), json!(str_of(&character, "name")));    }    if let Some(aside) = text(request, "aside").map(str::trim).filter(|aside| !aside.is_empty()) {        data.insert("aside".into(), json!(aside));    }    let id = create(ctx, LINE, Value::Object(data))?;    keep(ctx, &scene)?;    // Writing between two lines goes on from the line just written.    let next = after.map(|_| id.as_str());    Ok(json!({ "line": id, "scene": scene_view(ctx, &scene, next)? }))}pub(super) fn line_edit(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let scene = id_of(request, "scene")?.to_string();    let held = adopted(ctx, &scene)?;    let row = named_line(&held, id_of(request, "id")?)?.clone();    let mut patch = Map::new();    if let Some(said) = text(request, "text") {        patch.insert("text".into(), json!(said.trim()));    }    if request.get("kind").is_some() {        patch.insert("kind".into(), json!(beat_kind(request)?.word()));    }    if let Some(aside) = request.get("aside").filter(|aside| aside.is_string() || aside.is_null()) {        patch.insert("aside".into(), aside.clone());    }    if let Some(id) = text(request, "character").map(str::trim).filter(|id| !id.is_empty()) {        let character = character_named(ctx, id)?;        patch.insert("character".into(), json!(id));        patch.insert("who".into(), json!(str_of(&character, "name")));    }    let kind = patch.get("kind").and_then(Value::as_str).unwrap_or(str_of(&row, "kind"));    let said = patch.get("text").and_then(Value::as_str).unwrap_or(str_of(&row, "text"));    if said.trim().is_empty() && kind != "enters" {        return Err(bad(line("refusal.empty_line", &[])?));    }    let who = patch.get("who").and_then(Value::as_str).unwrap_or(str_of(&row, "who"));    if matches!(kind, "dialogue" | "enters") && who.trim().is_empty() {        return Err(bad(line("refusal.needs_character", &[])?));    }    update(ctx, LINE, str_of(&row, "id"), patch)?;    keep(ctx, &scene)?;    scene_view(ctx, &scene, None)}/// A line one place earlier (`by: -1`) or later (`by: 1`) in its scene, its id/// kept; at either end it stays where it is.pub(super) fn line_move(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let scene = id_of(request, "scene")?.to_string();    let mut held = adopted(ctx, &scene)?;    let id = str_of(named_line(&held, id_of(request, "id")?)?, "id").to_string();    let by = request.get("by").and_then(Value::as_i64).unwrap_or(1);    let at = held.iter().position(|row| str_of(row, "id") == id).unwrap_or(0);    let to = (at as i64 + by.signum()).clamp(0, held.len() as i64 - 1) as usize;    if to != at {        let mut others: Vec<Map<String, Value>> = held.iter().filter(|row| str_of(row, "id") != id).cloned().collect();        let after = if to == 0 { START.to_string() } else { str_of(&others[to - 1], "id").to_string() };        let mut position = line_key(&others, Some(&after))?;        if position.is_none() {            open_lines(ctx, &held)?;            held = line_rows(ctx, &scene)?;            others = held.iter().filter(|row| str_of(row, "id") != id).cloned().collect();            position = line_key(&others, Some(&after))?;        }        let position = position.ok_or_else(|| MethodError::new("write_refused", "the scene's order could not be opened"))?;        update(ctx, LINE, &id, object(json!({ "position": position })))?;        keep(ctx, &scene)?;    }    scene_view(ctx, &scene, None)}/// `story.person.lines { id }`: everything one character says across the/// script, in order, each with its scene's number and place and time, to read/// whether they sound like one person.pub(super) fn person_lines(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let id = id_of(request, "id")?;    let row = get(ctx, CHARACTER, id).ok_or_else(|| refused("not_found", line("refusal.no_character", &[]).unwrap_or_default()))?;    let story = str_of(&row, "story").to_string();    let name = str_of(&row, "name").to_string();    let cast = characters_of(ctx, &story)?;    let places = rows(ctx, PLACE, json!({ "story": story }))?;    let mut out = Vec::new();    for (at, scene) in scenes_of(ctx, &story)?.iter().enumerate() {        let title = spot_title(&spot(scene, &places))?;        for one in shown(ctx, scene, &cast)? {            if one.beat.kind == BeatKind::Dialogue && one.beat.who.as_deref().is_some_and(|who| same_name(who, &name)) {                out.push(json!({ "scene": str_of(scene, "id"), "line": one.id, "number": at + 1, "title": title, "text": one.beat.text, "aside": one.beat.aside }));            }        }    }    Ok(json!({ "id": id, "name": softened(&name), "lines": out }))}pub(super) fn line_remove(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let scene = id_of(request, "scene")?.to_string();    let held = adopted(ctx, &scene)?;    let id = str_of(named_line(&held, id_of(request, "id")?)?, "id").to_string();    remove(ctx, LINE, &id)?;    keep(ctx, &scene)?;    scene_view(ctx, &scene, None)}pub(super) fn character_add(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(line("refusal.no_name", &[]).unwrap_or_default()))?;    let cast = characters_of(ctx, &story)?;    let id = match cast.iter().find(|one| same_name(str_of(one, "name"), name)) {        Some(known) => str_of(known, "id").to_string(),        None => {            let worn: Vec<String> = cast.iter().map(|one| tint_of(str_of(one, "tint"), str_of(one, "name")).key.clone()).collect();            let made = create(ctx, CHARACTER, json!({ "story": story, "name": name, "tint": next_tint(&worn, name).key, "scenes": 0, "lines": 0 }))?;            // A new name can change how a body reads (a cue is a known name): the kept figures follow.            super::refigure(ctx, &story)?;            made        }    };    let row = character_named(ctx, &id)?;    Ok(json!({ "character": person(&row), "chips": chips(&characters_of(ctx, &story)?) }))}// ── the draft page ─────────────────────────────────────────────────────────pub(super) fn draft(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let one = text(request, "scene").map(str::trim).filter(|id| !id.is_empty());    let story = match one {        Some(id) => str_of(&scene_row(ctx, id)?, "story").to_string(),        None => story_named(ctx, request)?,    };    let row = get(ctx, STORY, &story).unwrap_or_default();    let cast = characters_of(ctx, &story)?;    let places = rows(ctx, PLACE, json!({ "story": story }))?;    let scenes: Vec<layout::SceneIn> = scenes_of(ctx, &story)?        .iter()        .filter(|scene| one.is_none_or(|id| id == str_of(scene, "id")))        .map(|scene| layout::SceneIn { id: str_of(scene, "id").to_string(), heading: slugline(scene, &spot(scene, &places)), body: str_of(scene, "body").to_string() })        .collect();    let laid = layout::script(&scenes, &names_in(&cast));    let (doc, title) = doc_of(ctx, &story)?;    Ok(json!({        "label": line("composer.draft", &[])?,        "title": str_of(&row, "title"),        "paper": paper(request),        "pages": laid.pages,        "scenes": laid.scenes,        "share": line("draft.share", &[])?,        "pdf": line("acts.share_pdf", &[])?,        "fountain": line("acts.share_fountain", &[])?,        "fountain_text": fountain::write(&doc),        "fountain_name": file_name(&title),    }))}#[cfg(test)]#[path = "story_desk_tests.rs"]mod tests;