Cotton code
89 lines · 4.2 KB · RustRaw
//! A poll drawn as a poll (FEEDBACK-3 "polls shown", CONTRACT "Polls shown"): the question, how many may be chosen,//! each option with its count, its bar and who chose it, and the total. A link poll counts its voters; an exported//! poll has only its totals.use super::list::say;use super::shapes::{PollCard, PollChoice};use crate::messages::MessagePoll;use crate::rules::shell_lines::LineSet;/// The owner's own vote, in `voters[].who`.pub const ME: &str = "me";/// `poll` as its bubble draws it; `name_of` names a voter by their number's digits, as the chat names people.pub fn card(lines: &LineSet, poll: &MessagePoll, name_of: &dyn Fn(&str) -> String) -> PollCard {    let live = poll.live();    let mut voters: Vec<_> = poll.voters.iter().filter(|v| !v.options.is_empty()).collect();    // "You" first, then in the order they voted.    voters.sort_by(|a, b| (a.who != ME, a.at.as_deref().unwrap_or("")).cmp(&(b.who != ME, b.at.as_deref().unwrap_or(""))));    let counts: Vec<u32> = (0..poll.options.len())        .map(|i| if live { voters.iter().filter(|v| v.options.contains(&(i as u32))).count() as u32 } else { poll.options[i].votes.max(0.0) as u32 })        .collect();    let total: u32 = if live { voters.len() as u32 } else { counts.iter().sum() };    let options: Vec<PollChoice> = poll        .options        .iter()        .enumerate()        .map(|(i, option)| {            let holding: Vec<_> = voters.iter().filter(|v| v.options.contains(&(i as u32))).collect();            let votes = counts[i];            PollChoice {                text: option.text.clone(),                votes,                said: if votes == 0 { say(lines, "app.poll.none", &[]) } else { say(lines, "app.poll.votes", &[("n", &votes.to_string())]) },                percent: if total == 0 { 0 } else { ((votes * 100 + total / 2) / total).min(100) },                voters: holding.iter().map(|v| if v.who == ME { say(lines, "app.poll.you", &[]) } else { name_of(&v.who) }).collect(),                mine: holding.iter().any(|v| v.who == ME),            }        })        .collect();    let choose = poll.selectable.map(|n| say(lines, if n == 1 { "app.poll.choose_one" } else { "app.poll.choose_many" }, &[]));    let said = if total == 0 { say(lines, "app.poll.none_yet", &[]) } else { say(lines, "app.poll.votes", &[("n", &total.to_string())]) };    let mut spoken = vec![say(lines, "app.poll.spoken", &[("question", &poll.question)])];    spoken.extend(choose.clone());    for o in &options {        let mut line = format!("{}, {}", o.text, o.said);        if o.mine {            line.push_str(", ");            line.push_str(&say(lines, "app.poll.yours", &[]));        }        spoken.push(line);    }    spoken.push(said.clone());    PollCard { question: poll.question.clone(), choose, options, said, spoken: sentences(&spoken), votes_title: say(lines, "app.poll.votes_title", &[]), votable: false }}/// His choice after a tap on option `at`: in a poll of one choice, that option (his own again takes it back); in a/// poll of several, that option added or taken away. Options past the end are no choice.pub fn tapped(poll: &MessagePoll, at: u32) -> Vec<u32> {    let mine: Vec<u32> = poll.voters.iter().find(|v| v.who == ME).map(|v| v.options.clone()).unwrap_or_default();    if at as usize >= poll.options.len() {        return mine;    }    if poll.selectable == Some(1) {        return if mine == [at] { Vec::new() } else { vec![at] };    }    let mut out: Vec<u32> = mine.iter().copied().filter(|o| *o != at).collect();    if !mine.contains(&at) {        out.push(at);    }    out.sort_unstable();    out}#[cfg(test)]#[path = "poll_tests.rs"]mod tests;/// The parts read one after another as sentences: a full stop between them, unless a part already ends one (a/// question's own "?"), so TalkBack and VoiceOver never read "Friday?." (seen on emulator-5554, 23 Nov 2026).fn sentences(parts: &[String]) -> String {    let mut out = String::new();    for part in parts.iter().filter(|p| !p.trim().is_empty()) {        if !out.is_empty() {            out.push_str(if out.ends_with(['.', '?', '!', '…']) { " " } else { ". " });        }        out.push_str(part.trim());    }    out}