//! Cotton Story's rings one to four under the surface (Ink redesign, //! assets/design/story/CONTRACT.md): every line of a scene a row that keeps //! its id however the scene is written; scenes split and merged with their //! lines' ids; characters and places merged; a character's and a place's //! page whole; pictures at three levels; things and costumes; Final Draft //! out. The phone draws what these answer and decides nothing. use cotton_core::cotton_rules::story::{ beats::{self, Beat}, fdx, identity::{self, Held}, }; use super::*; pub const PICTURE: &str = "story_picture"; pub const THING: &str = "story_thing"; pub const COSTUME: &str = "story_costume"; pub const USE: &str = "story_use"; /// What a picture, use or costume may be of: the columns that link it. const OF: [&str; 5] = ["character", "place", "scene", "costume", "thing"]; fn line_of(beat: &Beat, cast: &[Map]) -> Map { let mut data = object(json!({ "kind": beat.kind.word(), "text": beat.text })); let who = beat.who.as_deref().map(str::trim).filter(|who| !who.is_empty()); data.insert("who".into(), who.map(Value::from).unwrap_or(Value::Null)); let character = who.and_then(|who| cast.iter().find(|one| same_name(str_of(one, "name"), who))).map(|one| json!(str_of(one, "id"))); data.insert("character".into(), character.unwrap_or(Value::Null)); for (key, value) in [("aside", &beat.aside), ("form", &beat.form)] { data.insert(key.into(), value.as_deref().map(Value::from).unwrap_or(Value::Null)); } data } /// Lay the scene's body over its line rows: a line kept or edited in place /// keeps its row, a new one is made, one gone is removed; every row's order /// key is written 1, 2, 3 in the body's order. pub(super) fn lay(ctx: &mut Ctx<'_>, scene: &Map) -> Result<(), MethodError> { let id = str_of(scene, "id").to_string(); let story = str_of(scene, "story").to_string(); let cast = characters_of(ctx, &story)?; let held: Vec = 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, &beats::read(str_of(scene, "body"), &names_in(&cast))); for gone in &laid.removed { desk::remove(ctx, desk::LINE, gone)?; } for (at, placed) in laid.lines.iter().enumerate() { let mut data = line_of(&placed.beat, &cast); data.insert("position".into(), json!(at + 1)); match &placed.id { Some(row) => update(ctx, desk::LINE, row, data)?, None => { data.retain(|_, value| !value.is_null()); data.insert("story".into(), json!(story)); data.insert("scene".into(), json!(id)); create(ctx, desk::LINE, Value::Object(data))?; } } } Ok(()) } /// Every scene of a story laid over its rows (a story just read in or copied). pub(super) fn lay_story(ctx: &mut Ctx<'_>, story: &str) -> Result<(), MethodError> { for scene in scenes_of(ctx, story)? { desk::adopted(ctx, str_of(&scene, "id"))?; } Ok(()) } fn not_found(key: &str) -> MethodError { refused("not_found", line(key, &[]).unwrap_or_default()) } fn row_of(ctx: &mut Ctx<'_>, table: &str, id: &str, missing: &str) -> Result, MethodError> { get(ctx, table, id).filter(|row| !row.is_empty() && row.get("story").is_some()).ok_or_else(|| not_found(missing)) } /// Move every row of `table` whose `column` is `from` to `to`. fn relink(ctx: &mut Ctx<'_>, table: &str, story: &str, column: &str, from: &str, to: &str) -> Result { let mut moved = 0; for row in rows(ctx, table, json!({ "story": story, column: from }))? { update(ctx, table, str_of(&row, "id"), object(json!({ column: to })))?; moved += 1; } Ok(moved) } // ── scenes split and merged ───────────────────────────────────────────────── /// `story.scene.split { id, at }`: a new scene right after this one holding /// the lines from `at` on, their ids kept; same place, setting, time, day. pub(super) fn scene_split(ctx: &mut Ctx<'_>, request: &Value) -> Result { let id = id_of(request, "id")?.to_string(); let at = id_of(request, "at")?.to_string(); let held = desk::adopted(ctx, &id)?; let from = held.iter().position(|row| str_of(row, "id") == at).ok_or_else(|| not_found("refusal.no_line_id"))?; let scene = desk::scene_row(ctx, &id)?; let story = str_of(&scene, "story").to_string(); let position = desk::scene_key(ctx, &story, None, Some(&id), false)?; let mut data = object(json!({ "story": story, "position": position, "status": "draft", "words": 0, "pages": 0, "minutes": 0, "speakers": "" })); for key in ["setting", "place", "time", "heading", "day"] { if let Some(value) = scene.get(key).filter(|value| !value.is_null()) { data.insert(key.into(), value.clone()); } } let made = create(ctx, SCENE, Value::Object(data))?; for (n, row) in held[from..].iter().enumerate() { update(ctx, desk::LINE, str_of(row, "id"), object(json!({ "scene": made, "position": n + 1 })))?; } desk::keep(ctx, &id)?; desk::keep(ctx, &made)?; recount(ctx, &story, &mut Vec::new())?; Ok(json!({ "scene": made, "scenes": desk::scenes_view(ctx, &story)? })) } /// `story.scene.merge { id, into }`: scene `id`'s lines follow `into`'s, /// their ids kept; its pictures, things, costumes and notes go with them; /// `id` goes to Deleted. pub(super) fn scene_merge(ctx: &mut Ctx<'_>, request: &Value) -> Result { let id = id_of(request, "id")?.to_string(); let into = id_of(request, "into")?.to_string(); if id == into { return Err(bad("a scene is merged into another scene")); } let story = str_of(&desk::scene_row(ctx, &id)?, "story").to_string(); if str_of(&desk::scene_row(ctx, &into)?, "story") != story { return Err(bad("both scenes are of one story")); } let kept = desk::adopted(ctx, &into)?.len(); for (n, row) in desk::adopted(ctx, &id)?.iter().enumerate() { update(ctx, desk::LINE, str_of(row, "id"), object(json!({ "scene": into, "position": kept + n + 1 })))?; } for table in [PICTURE, USE, NOTE] { relink(ctx, table, &story, "scene", &id, &into)?; } desk::keep(ctx, &into)?; desk::remove(ctx, SCENE, &id)?; recount(ctx, &story, &mut Vec::new())?; Ok(json!({ "scene": into, "scenes": desk::scenes_view(ctx, &story)? })) } // ── characters and places merged ──────────────────────────────────────────── /// `story.merge { table, id, into }`: two characters or two places become /// one, `into`, whose own name and words stand. pub(super) fn merge(ctx: &mut Ctx<'_>, request: &Value) -> Result { let table = text(request, "table").unwrap_or_default(); let id = id_of(request, "id")?.to_string(); let into = id_of(request, "into")?.to_string(); if !matches!(table, CHARACTER | PLACE) { return Err(bad("`table` is story_character or story_place")); } if id == into { return Err(bad("a row is merged into another row")); } let missing = if table == CHARACTER { "refusal.no_character" } else { "refusal.no_place" }; let gone = row_of(ctx, table, &id, missing)?; let kept = row_of(ctx, table, &into, missing)?; let story = str_of(&gone, "story").to_string(); if str_of(&kept, "story") != story { return Err(bad("both are of one story")); } let mut changed = 0usize; if table == CHARACTER { let name = str_of(&kept, "name").to_string(); let old = str_of(&gone, "name").to_string(); for scene in scenes_of(ctx, &story)? { let scene_id = str_of(&scene, "id").to_string(); let mut touched = false; for row in desk::adopted(ctx, &scene_id)? { if str_of(&row, "character") == id || (str_of(&row, "character").is_empty() && same_name(str_of(&row, "who"), &old)) { update(ctx, desk::LINE, str_of(&row, "id"), object(json!({ "character": into, "who": name })))?; touched = true; } } if touched { changed += 1; desk::keep(ctx, &scene_id)?; } } for table in [PICTURE, COSTUME, USE] { relink(ctx, table, &story, "character", &id, &into)?; } desk::remove(ctx, CHARACTER, &id)?; recount(ctx, &story, &mut Vec::new())?; } else { let name = str_of(&kept, "name").to_string(); for scene in rows(ctx, SCENE, json!({ "story": story, "place": id }))? { write_scene(ctx, str_of(&scene, "id"), &json!({ "place": name }))?; changed += 1; } relink(ctx, PICTURE, &story, "place", &id, &into)?; desk::remove(ctx, PLACE, &id)?; } Ok(json!({ "scenes": changed, "into": into })) } // ── a place's and a person's page ─────────────────────────────────────────── fn picture_json(row: &Map) -> Value { let mut out = json!({ "id": str_of(row, "id"), "picture": str_of(row, "picture"), "caption": row.get("caption").cloned().unwrap_or(Value::Null), "day": row.get("day").cloned().unwrap_or(Value::Null) }); for key in OF { out[key] = row.get(key).filter(|value| !value.is_null()).cloned().unwrap_or(Value::Null); } out } fn ordered(mut found: Vec>) -> Vec> { 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")))); found } fn pictures_where(ctx: &mut Ctx<'_>, filter: Value) -> Result>, MethodError> { Ok(ordered(rows(ctx, PICTURE, filter)?)) } fn place_json(row: &Map, scene_ids: Vec) -> Value { json!({ "id": str_of(row, "id"), "name": desk::softened(str_of(row, "name")), "about": row.get("about").cloned().unwrap_or(Value::Null), "picture": row.get("picture").cloned().unwrap_or(Value::Null), "scenes": scene_ids.len(), "scene_ids": scene_ids, }) } fn scenes_at(scenes: &[Map], place: &str) -> Vec { scenes.iter().filter(|scene| str_of(scene, "place") == place).map(|scene| json!(str_of(scene, "id"))).collect() } /// `story.places { story? }`: the story's places, most used first. pub(super) fn places(ctx: &mut Ctx<'_>, request: &Value) -> Result { let story = story_named(ctx, request)?; let scenes = scenes_of(ctx, &story)?; let mut found: Vec<(usize, String, Value)> = rows(ctx, PLACE, json!({ "story": story }))? .iter() .map(|row| { let ids = scenes_at(&scenes, str_of(row, "id")); (ids.len(), str_of(row, "name").to_lowercase(), place_json(row, ids)) }) .collect(); found.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1))); let pictures = rows(ctx, PICTURE, json!({ "story": story }))?; for (_, _, place) in found.iter_mut() { let id = str_of(place.as_object().expect("a place"), "id").to_string(); let here: Vec<&Map> = scenes.iter().filter(|scene| str_of(scene, "place") == id).collect(); let count = pictures.iter().filter(|one| str_of(one, "place") == id).count(); let mut parts = vec![inside_outside(&here)?, counted("length.scenes", here.len() as i64)?]; let times = times_at(&here); if !times.is_empty() { parts.push(times.iter().map(|(time, _)| time.clone()).collect::>().join(", ")); } parts.push(if count == 0 { line("ink.no_pictures", &[])? } else { counted("ink.pictures", count as i64)? }); place["line"] = json!(parts.into_iter().filter(|part| !part.is_empty()).collect::>().join(" · ")); } Ok(json!({ "places": found.into_iter().map(|(_, _, place)| place).collect::>() })) } /// `story.place { id }`: a place's page whole. pub(super) fn place(ctx: &mut Ctx<'_>, request: &Value) -> Result { let id = id_of(request, "id")?; let row = row_of(ctx, PLACE, id, "refusal.no_place")?; let scenes = scenes_of(ctx, str_of(&row, "story"))?; let mut out = place_json(&row, scenes_at(&scenes, id)); out["pictures"] = json!(pictures_where(ctx, json!({ "place": id }))?.iter().map(picture_json).collect::>()); let here: Vec<&Map> = scenes.iter().filter(|scene| str_of(scene, "place") == id).collect(); let minutes: f64 = here.iter().map(|scene| num_of(scene, "minutes")).sum(); let mut parts = vec![inside_outside(&here)?, counted("length.scenes", here.len() as i64)?]; if minutes >= 0.5 { parts.push(line("ink.of_the_film", &[("minutes", &counted("length.minutes", minutes.round().max(1.0) as i64)?)])?); } out["line"] = json!(parts.into_iter().filter(|part| !part.is_empty()).collect::>().join(" · ")); out["times"] = json!(times_at(&here).into_iter().map(|(time, scenes)| json!({ "time": time, "scenes": scenes })).collect::>()); // Who speaks in each scene here, as the scene row's second line. let mut people = Map::new(); for scene in &here { let said: Vec = str_of(scene, "speakers").lines().map(str::trim).filter(|name| !name.is_empty()).map(desk::softened).collect(); people.insert(str_of(scene, "id").to_string(), json!(said.join(", "))); } out["people"] = Value::Object(people); Ok(out) } /// Inside, Outside, or both, from the scenes' settings; empty when none says. fn inside_outside(scenes: &[&Map]) -> Result { let (mut inside, mut outside) = (false, false); for scene in scenes { match str_of(scene, "setting") { "INT." => inside = true, "EXT." => outside = true, "INT./EXT." => { inside = true; outside = true; } _ => {} } } match (inside, outside) { (true, true) => line("ink.inside_outside", &[]), (true, false) => line("picker.inside", &[]), (false, true) => line("picker.outside", &[]), (false, false) => Ok(String::new()), } } /// The times of day the scenes are at, as written, in the story's order, with how many scenes each. fn times_at(scenes: &[&Map]) -> Vec<(String, usize)> { let mut out: Vec<(String, usize)> = Vec::new(); for scene in scenes { let time = str_of(scene, "time").trim(); if time.is_empty() { continue; } match out.iter_mut().find(|(seen, _)| seen.to_lowercase() == time.to_lowercase()) { Some((_, count)) => *count += 1, None => out.push((desk::softened(time), 1)), } } out } /// After a picture comes, goes or moves: a person's or a place's face is /// its first picture of itself (not of a story day), or none. fn face_follows(ctx: &mut Ctx<'_>, row: &Map) -> Result<(), MethodError> { if !day_less(row) { return Ok(()); } for (key_of, table) in [("character", CHARACTER), ("place", PLACE)] { let owner = str_of(row, key_of).to_string(); if owner.is_empty() { continue; } let first = pictures_where(ctx, json!({ key_of: owner }))?.into_iter().find(|one| day_less(one)).map(|one| str_of(&one, "picture").to_string()); let now = get(ctx, table, &owner).map(|row| str_of(&row, "picture").to_string()).unwrap_or_default(); let want = first.unwrap_or_default(); if now != want { update(ctx, table, &owner, object(json!({ "picture": if want.is_empty() { Value::Null } else { json!(want) } })))?; } } Ok(()) } fn costume_json(row: &Map, scene_ids: Vec) -> Value { json!({ "id": str_of(row, "id"), "character": str_of(row, "character"), "name": row.get("name").cloned().unwrap_or(Value::Null), "about": row.get("about").cloned().unwrap_or(Value::Null), "day": row.get("day").cloned().unwrap_or(Value::Null), "picture": row.get("picture").cloned().unwrap_or(Value::Null), "scene_ids": scene_ids, }) } fn used_in(uses: &[Map], column: &str, id: &str) -> Vec { let mut out: Vec = Vec::new(); for row in uses.iter().filter(|row| str_of(row, column) == id) { let scene = json!(str_of(row, "scene")); if !out.contains(&scene) { out.push(scene); } } out } /// `story.person { id }`: a character's page whole: theirs on top (picture, /// words, pictures, costumes), the script's beneath (scenes, counts). pub(super) fn person(ctx: &mut Ctx<'_>, request: &Value) -> Result { let id = id_of(request, "id")?; let row = row_of(ctx, CHARACTER, id, "refusal.no_character")?; let story = str_of(&row, "story").to_string(); let name = str_of(&row, "name").to_string(); let scene_ids: Vec = scenes_of(ctx, &story)? .iter() .filter(|scene| str_of(scene, "speakers").lines().any(|speaker| same_name(speaker, &name))) .map(|scene| json!(str_of(scene, "id"))) .collect(); let uses = rows(ctx, USE, json!({ "story": story }))?; let costumes: Vec = ordered(rows(ctx, COSTUME, json!({ "character": id }))?).iter().map(|one| costume_json(one, used_in(&uses, "costume", str_of(one, "id")))).collect(); let mut out = desk::person(&row); for key in ["role", "about", "want", "picture"] { out[key] = row.get(key).cloned().unwrap_or(Value::Null); } out["scenes"] = json!(num_of(&row, "scenes") as u64); out["lines"] = json!(num_of(&row, "lines") as u64); out["scene_ids"] = json!(scene_ids); // Their speeches in each scene, and the story days they are in. let mut lines_in = Map::new(); let mut days: Vec = Vec::new(); for scene in scenes_of(ctx, &story)?.iter().filter(|scene| scene_ids.contains(&json!(str_of(scene, "id")))) { let said = story_lines::lines(str_of(scene, "body"), std::slice::from_ref(&name)) .iter() .filter(|line| line.kind == Kind::Character && same_name(&unmarked(Kind::Character, &line.text), &name)) .count(); lines_in.insert(str_of(scene, "id").to_string(), json!(counted("character.speaks", said as i64)?)); if let Some(day) = scene.get("day").and_then(Value::as_f64).filter(|day| *day >= 1.0) { if !days.contains(&(day as i64)) { days.push(day as i64); } } } days.sort_unstable(); out["lines_in"] = Value::Object(lines_in); out["days"] = json!(days.iter().map(|day| Ok(json!({ "day": day, "label": line("ink.day", &[("n", &day.to_string())])? }))).collect::, MethodError>>()?); out["pictures"] = json!(pictures_where(ctx, json!({ "character": id }))?.iter().map(picture_json).collect::>()); out["costumes"] = json!(costumes); Ok(out) } // ── pictures ──────────────────────────────────────────────────────────────── /// The `of` columns a request names, each checked to be a row of the story. fn of_request(ctx: &mut Ctx<'_>, request: &Value) -> Result<(Map, Option), MethodError> { let mut of = Map::new(); let mut story = None; for key in OF { if let Some(id) = text(request, key).map(str::trim).filter(|id| !id.is_empty()) { let table = match key { "character" => CHARACTER, "place" => PLACE, "scene" => SCENE, "costume" => COSTUME, _ => THING, }; let row = get(ctx, table, id).filter(|row| row.get("story").is_some()).ok_or_else(|| refused("not_found", format!("no {table} {id}")))?; let of_story = str_of(&row, "story").to_string(); if story.as_ref().is_some_and(|known| *known != of_story) { return Err(bad("a picture is of rows of one story")); } story = Some(of_story); of.insert(key.into(), json!(id)); } } if let Some(day) = request.get("day").filter(|day| day.is_number()) { of.insert("day".into(), day.clone()); } Ok((of, story)) } /// `story.pictures { story?, character?, place?, scene?, costume?, thing?, day? }`. pub(super) fn pictures(ctx: &mut Ctx<'_>, request: &Value) -> Result { let (mut filter, story) = of_request(ctx, request)?; let story = match story { Some(story) => story, None => story_named(ctx, request)?, }; filter.insert("story".into(), json!(story)); Ok(json!({ "pictures": pictures_where(ctx, Value::Object(filter))?.iter().map(picture_json).collect::>() })) } /// A picture of the person themself, not of them on a story day (a costume). fn day_less(data: &Map) -> bool { data.get("day").is_none_or(Value::is_null) && data.get("costume").is_none_or(Value::is_null) } /// `story.picture.add { picture, caption?, character? | place? | scene? | costume? | thing?, day?, story? }`. pub(super) fn picture_add(ctx: &mut Ctx<'_>, request: &Value) -> Result { let key = id_of(request, "picture")?.to_string(); let (of, story) = of_request(ctx, request)?; let story = match story { Some(story) => story, None => story_named(ctx, request)?, }; let mut siblings = of.clone(); siblings.insert("story".into(), json!(story)); let last = pictures_where(ctx, Value::Object(siblings))?.last().map(|row| num_of(row, "position")); let mut data = of; data.insert("story".into(), json!(story)); data.insert("picture".into(), json!(key)); data.insert("position".into(), json!(beats::between(last, None).unwrap_or(1.0))); if let Some(caption) = text(request, "caption").map(str::trim).filter(|caption| !caption.is_empty()) { data.insert("caption".into(), json!(caption)); } // A person's or a place's first picture becomes its face (the `picture` column) until another is chosen. for (key_of, table) in [("character", CHARACTER), ("place", PLACE)] { if let Some(owner) = data.get(key_of).and_then(Value::as_str).map(str::to_string) { if day_less(&data) && get(ctx, table, &owner).is_some_and(|row| str_of(&row, "picture").trim().is_empty()) { update(ctx, table, &owner, object(json!({ "picture": key })))?; } } } let id = create(ctx, PICTURE, Value::Object(data))?; let row = get(ctx, PICTURE, &id).unwrap_or_default(); Ok(json!({ "picture": picture_json(&row) })) } /// `story.picture.remove { id }`: to Deleted. pub(super) fn picture_remove(ctx: &mut Ctx<'_>, request: &Value) -> Result { let id = id_of(request, "id")?; let row = row_of(ctx, PICTURE, id, "refusal.no_picture")?; desk::remove(ctx, PICTURE, id)?; face_follows(ctx, &row)?; Ok(json!({ "removed": id })) } /// The pictures of just what `row` is of: the same rows linked, the same day. fn siblings(ctx: &mut Ctx<'_>, filter: &Map, row: &Map) -> Result>, MethodError> { let same = |one: &Map| OF.iter().copied().chain(["day"]).all(|key| one.get(key).filter(|v| !v.is_null()) == row.get(key).filter(|v| !v.is_null())); Ok(pictures_where(ctx, Value::Object(filter.clone()))?.into_iter().filter(same).collect()) } /// `story.picture.move { id, after }`: among the pictures of the same thing, /// after another (`start` for the first place). pub(super) fn picture_move(ctx: &mut Ctx<'_>, request: &Value) -> Result { let id = id_of(request, "id")?.to_string(); let row = row_of(ctx, PICTURE, &id, "refusal.no_picture")?; let mut filter = object(json!({ "story": str_of(&row, "story") })); for key in OF.iter().copied().chain(["day"]) { if let Some(value) = row.get(key).filter(|value| !value.is_null()) { filter.insert(key.into(), value.clone()); } } for _ in 0..2 { let others: Vec> = siblings(ctx, &filter, &row)?.into_iter().filter(|one| str_of(one, "id") != id).collect(); let key_at = |at: usize| others.get(at).map(|one| num_of(one, "position")); let (low, high) = match text(request, "after").map(str::trim).filter(|after| !after.is_empty()) { None | Some("start") => (None, key_at(0)), Some(after) => { let at = others.iter().position(|one| str_of(one, "id") == after).ok_or_else(|| not_found("refusal.no_picture"))?; (key_at(at), key_at(at + 1)) } }; if let Some(position) = beats::between(low, high) { update(ctx, PICTURE, &id, object(json!({ "position": position })))?; face_follows(ctx, &row)?; return Ok(json!({ "pictures": siblings(ctx, &filter, &row)?.iter().map(picture_json).collect::>() })); } for (at, one) in others.iter().enumerate() { update(ctx, PICTURE, str_of(one, "id"), object(json!({ "position": (at + 1) as f64 * 2.0 })))?; } } Err(MethodError::new("write_refused", "the pictures' order could not be opened")) } // ── things and costumes ───────────────────────────────────────────────────── /// `story.things { story? }`: the story's things by name, each with the scenes it is in. pub(super) fn things(ctx: &mut Ctx<'_>, request: &Value) -> Result { let story = story_named(ctx, request)?; let uses = rows(ctx, USE, json!({ "story": story }))?; let mut found = rows(ctx, THING, json!({ "story": story }))?; found.sort_by_key(|row| str_of(row, "name").to_lowercase()); let things: Vec = found .iter() .map(|row| { json!({ "id": str_of(row, "id"), "name": str_of(row, "name"), "kind": row.get("kind").cloned().unwrap_or(json!("prop")), "about": row.get("about").cloned().unwrap_or(Value::Null), "picture": row.get("picture").cloned().unwrap_or(Value::Null), "scene_ids": used_in(&uses, "thing", str_of(row, "id")), }) }) .collect(); Ok(json!({ "things": things })) } /// `story.costumes { story?, character? }`: by story day, each with its scenes. pub(super) fn costumes(ctx: &mut Ctx<'_>, request: &Value) -> Result { let story = match text(request, "character").map(str::trim).filter(|id| !id.is_empty()) { Some(character) => str_of(&row_of(ctx, CHARACTER, character, "refusal.no_character")?, "story").to_string(), None => story_named(ctx, request)?, }; let mut filter = object(json!({ "story": story })); if let Some(character) = text(request, "character").map(str::trim).filter(|id| !id.is_empty()) { filter.insert("character".into(), json!(character)); } let uses = rows(ctx, USE, json!({ "story": story }))?; let mut found = rows(ctx, COSTUME, Value::Object(filter))?; found.sort_by(|a, b| num_of(a, "day").total_cmp(&num_of(b, "day")).then_with(|| str_of(a, "created_at").cmp(str_of(b, "created_at")))); Ok(json!({ "costumes": found.iter().map(|one| costume_json(one, used_in(&uses, "costume", str_of(one, "id")))).collect::>() })) } // ── Final Draft out ───────────────────────────────────────────────────────── /// `story.fdx.write { story? }` → `{ text, name }`. pub(super) fn fdx_write(ctx: &mut Ctx<'_>, request: &Value) -> Result { let id = story_named(ctx, request)?; let (doc, title) = doc_of(ctx, &id)?; let names = names_in(&characters_of(ctx, &id)?); let name = file_name(&title).trim_end_matches(".fountain").to_string() + ".fdx"; Ok(json!({ "text": fdx::write(&doc, &names), "name": name })) } #[cfg(test)] #[path = "story_ink_tests.rs"] mod tests;