Cotton code
102 lines · 4.1 KB · RustRaw
//! A scene read as a conversation (the owner's idea, `scene.chat`): each//! speech a bubble under its speaker's name, action as narration between.use serde::{Deserialize, Serialize};use super::lines::{lines, same_name, unmarked, Kind};use super::names;#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Item {    /// `speech`, `action` or `transition`.    pub kind: String,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub who: Option<String>,    /// `left` or `right` in a two-hander; none otherwise.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub side: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub aside: Option<String>,    pub text: String,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Chat {    pub speakers: Vec<String>,    pub two_hander: bool,    pub items: Vec<Item>,}fn item(kind: &str, text: String) -> Item {    Item { kind: kind.to_string(), who: None, side: None, aside: None, text }}/// The scene as a chat. A speech is one bubble; an aside before its words is/// the bubble's aside, and one in the middle starts a new bubble from the/// same speaker.pub fn chat(body: &str, names_known: &[String]) -> Chat {    let read = lines(body, names_known);    let speakers = names::speakers(&read);    let two_hander = speakers.len() == 2;    let side = |who: &str| -> Option<String> {        two_hander.then(|| if same_name(&speakers[0], who) { "left" } else { "right" }.to_string())    };    let mut items = Vec::new();    let mut index = 0;    while index < read.len() {        let line = &read[index];        match line.kind {            Kind::Blank | Kind::Note | Kind::Heading => index += 1,            Kind::Action | Kind::Centered => {                let mut text = Vec::new();                while index < read.len() && matches!(read[index].kind, Kind::Action | Kind::Centered) {                    text.push(unmarked(read[index].kind, &read[index].text));                    index += 1;                }                items.push(item("action", text.join("\n")));            }            Kind::Transition => {                items.push(item("transition", unmarked(Kind::Transition, &line.text)));                index += 1;            }            Kind::Character | Kind::Dialogue | Kind::Parenthetical => {                let who = if line.kind == Kind::Character {                    index += 1;                    line.name.clone().unwrap_or_default()                } else {                    String::new()                };                let mut aside: Option<String> = None;                let mut said: Vec<String> = Vec::new();                let flush = |items: &mut Vec<Item>, aside: &mut Option<String>, said: &mut Vec<String>| {                    if said.is_empty() && aside.is_none() {                        return;                    }                    items.push(Item {                        kind: "speech".to_string(),                        who: (!who.is_empty()).then(|| who.clone()),                        side: side(&who),                        aside: aside.take(),                        text: std::mem::take(said).join("\n"),                    });                };                while index < read.len() && matches!(read[index].kind, Kind::Dialogue | Kind::Parenthetical | Kind::Note) {                    let line = &read[index];                    match line.kind {                        Kind::Parenthetical => {                            if !said.is_empty() {                                flush(&mut items, &mut aside, &mut said);                            }                            aside = Some(unmarked(Kind::Parenthetical, &line.text));                        }                        Kind::Dialogue => said.push(line.text.trim().to_string()),                        _ => {}                    }                    index += 1;                }                flush(&mut items, &mut aside, &mut said);            }        }    }    Chat { speakers, two_hander, items }}