shared/domain/module/body/_groups/cards.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
/*
* The card modules not only share some base content
* But the editor steps are identical except for 3
*/
use crate::{
config,
domain::module::body::{Audio, Background, Image, ModeExt, ModuleAssist, StepExt, ThemeId},
};
use serde::{de, Deserialize, Serialize};
use std::collections::HashSet;
use std::fmt;
use unicode_segmentation::UnicodeSegmentation;
/// The base content for card modules
#[derive(Default, Clone, Serialize, Deserialize, Debug)]
pub struct BaseContent {
/// The editor state
pub editor_state: EditorState,
/// The instructions for the module.
pub instructions: ModuleAssist,
/// The feedback for the module.
#[serde(default)]
pub feedback: ModuleAssist,
/// The mode the module uses.
pub mode: Mode,
/// The pairs of cards that make up the module.
pub pairs: Vec<CardPair>,
/// The ID of the module's theme.
pub theme: ThemeId,
/// The optional background override
pub background: Option<Background>,
}
impl BaseContent {
/// Get a new BaseContent
pub fn new(mode: Mode) -> Self {
Self {
mode,
..Self::default()
}
}
/// Convenience method to determine whether pairs have been configured correctly
pub fn is_valid(&self) -> bool {
let pair_len = self.pairs.len();
pair_len >= config::MIN_LIST_WORDS && self.mode.pairs_valid(&self.pairs)
}
}
/// Editor state
#[derive(Default, Clone, Serialize, Deserialize, Debug)]
pub struct EditorState {
/// the current step
pub step: Step,
/// the completed steps
pub steps_completed: HashSet<Step>,
}
/// A pair of cards
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct CardPair(pub Card, pub Card);
/// Data for individual cards
#[derive(Clone, Serialize, Debug)]
pub struct Card {
/// Recorded audio associated with the card
pub audio: Option<Audio>,
/// Content associated with the card
pub card_content: CardContent,
}
/// Util fn to fetch the length of a cards text if its content is text
pub fn get_card_text_length(card: &Card) -> usize {
match &card.card_content {
CardContent::Text(text) => text.graphemes(true).count(),
_ => 0,
}
}
/// Util fn to fetch the longest card text in a list of card pair
pub fn get_longest_card_text_length<'c>(cards: impl Iterator<Item = &'c Card>) -> usize {
cards.fold(0, |acc, card| {
let longest_current = match &card.card_content {
CardContent::Text(a) => a.graphemes(true).count(),
_ => 0,
};
acc.max(longest_current)
})
}
// Required because we need to be able to handle the data for the original Card enum, and also data
// from the new Card struct.
//
// I.e. converts from
//
// [{"Text": "Some words"}, {"Image": {<Image data>}}]
//
// to
//
// [{
// audio: null,
// card_content: {"Text": "Some words"}
// }, {
// audio: null,
// card_content: {"Image": {<Image data>}}
// }]
//
// TODO Create a content migration to migrate all existing JIGs with card game modules so that
// their card data matches the new Card struct and delete this Deserialize implementation.
impl<'de> de::Deserialize<'de> for Card {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
#[derive(Debug, Deserialize)]
#[serde(field_identifier)]
enum CardField {
#[serde(rename = "audio")]
Audio,
#[serde(rename = "card_content")]
CardContent,
#[serde(rename = "Text")]
Text,
#[serde(rename = "Image")]
Image,
}
struct CardVisitor;
impl<'de> de::Visitor<'de> for CardVisitor {
type Value = Card;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("A CardContent or Card map")
}
fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
where
M: de::MapAccess<'de>,
{
let mut audio: Option<Option<Audio>> = None;
let mut card_content: Option<CardContent> = None;
while let Some(key) = access.next_key()? {
match key {
CardField::Text => {
if card_content.is_some() {
return Err(de::Error::duplicate_field("card_content"));
}
card_content = Some(CardContent::Text(access.next_value()?));
break;
}
CardField::Image => {
if card_content.is_some() {
return Err(de::Error::duplicate_field("card_content"));
}
card_content = Some(CardContent::Image(access.next_value()?));
break;
}
CardField::Audio => {
if audio.is_some() {
return Err(de::Error::duplicate_field("audio"));
}
audio = Some(access.next_value()?);
}
CardField::CardContent => {
if card_content.is_some() {
return Err(de::Error::duplicate_field("card_content"));
}
card_content = Some(access.next_value()?);
}
}
}
let audio = audio.map_or(None, |audio| audio);
let card_content =
card_content.ok_or_else(|| de::Error::missing_field("card_content"))?;
Ok(Card {
audio,
card_content,
})
}
}
deserializer.deserialize_map(CardVisitor)
}
}
/// The content of a card
#[derive(Clone, Serialize, Deserialize, Debug)]
pub enum CardContent {
// todo(@dakom): document this
#[allow(missing_docs)]
Text(String),
// todo(@dakom): document this
#[allow(missing_docs)]
Image(Option<Image>),
}
impl Card {
/// Whether the variants value is empty
pub fn is_empty(&self) -> bool {
match &self.card_content {
CardContent::Text(value) if value.trim().len() == 0 => true,
CardContent::Image(None) => true,
_ => false,
}
}
}
/// What mode the module runs in.
#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq, Hash)]
#[repr(i16)]
#[cfg_attr(feature = "backend", derive(sqlx::Type))]
pub enum Mode {
// todo(@dakom): document this
#[allow(missing_docs)]
Duplicate = 0,
// todo(@dakom): document this
#[allow(missing_docs)]
WordsAndImages = 1,
// todo(@dakom): document this
#[allow(missing_docs)]
BeginsWith = 2,
// todo(@dakom): document this
#[allow(missing_docs)]
Lettering = 3,
// todo(@dakom): document this
#[allow(missing_docs)]
Riddles = 4,
// todo(@dakom): document this
#[allow(missing_docs)]
Opposites = 5,
// todo(@dakom): document this
#[allow(missing_docs)]
Synonyms = 6,
/// Translate from one language to another
Translate = 7,
/// Pairs of cards with images only
Images = 8,
}
impl Mode {
/// Returns whether a list of card pairs are valid for the game mode
pub fn pairs_valid(&self, pairs: &Vec<CardPair>) -> bool {
match self {
// Text/Image pairs
Self::WordsAndImages => {
pairs
.iter()
.find(|pair| {
// Neither card should be empty; the first card should be a Text variant and
// the 2nd card should be an Image variant.
pair.0.is_empty()
|| pair.1.is_empty()
|| !matches!(pair.0.card_content, CardContent::Text(_))
|| !matches!(pair.1.card_content, CardContent::Image(_))
})
.is_none()
}
// Image/Image pairs
Self::Images => {
pairs
.iter()
.find(|pair| {
// Neither card should be empty, and both cards must be Image variants.
pair.0.is_empty()
|| pair.1.is_empty()
|| !matches!(pair.0.card_content, CardContent::Image(_))
|| !matches!(pair.1.card_content, CardContent::Image(_))
})
.is_none()
}
// Text/Text pairs
_ => {
pairs
.iter()
.find(|pair| {
// Neither card should be empty, and both cards must be Text variants.
pair.0.is_empty()
|| pair.1.is_empty()
|| !matches!(pair.0.card_content, CardContent::Text(_))
|| !matches!(pair.1.card_content, CardContent::Text(_))
})
.is_none()
}
}
}
}
impl Default for Mode {
fn default() -> Self {
Self::Duplicate
}
}
impl ModeExt for Mode {
fn get_list() -> Vec<Self> {
vec![
Self::Duplicate,
Self::WordsAndImages,
Self::Lettering,
Self::Images,
Self::BeginsWith,
Self::Riddles,
Self::Opposites,
Self::Synonyms,
Self::Translate,
]
}
fn as_str_id(&self) -> &'static str {
match self {
Self::Duplicate => "duplicate",
Self::WordsAndImages => "words-images",
Self::BeginsWith => "begins-with",
Self::Lettering => "lettering",
Self::Riddles => "riddles",
Self::Opposites => "opposites",
Self::Synonyms => "synonyms",
Self::Translate => "translate",
Self::Images => "images",
}
}
fn label(&self) -> &'static str {
const STR_DUPLICATE: &'static str = "Duplicate";
const STR_WORDS_IMAGES: &'static str = "Words & Images";
const STR_BEGINS_WITH: &'static str = "Begins with...";
const STR_LETTERING: &'static str = "Script & Print";
const STR_RIDDLES: &'static str = "Riddles";
const STR_OPPOSITES: &'static str = "Opposites";
const STR_SYNONYMS: &'static str = "Synonyms";
const STR_TRANSLATE: &'static str = "Translation";
const STR_IMAGES: &'static str = "Images";
match self {
Self::Duplicate => STR_DUPLICATE,
Self::WordsAndImages => STR_WORDS_IMAGES,
Self::BeginsWith => STR_BEGINS_WITH,
Self::Lettering => STR_LETTERING,
Self::Riddles => STR_RIDDLES,
Self::Opposites => STR_OPPOSITES,
Self::Synonyms => STR_SYNONYMS,
Self::Translate => STR_TRANSLATE,
Self::Images => STR_IMAGES,
}
}
}
/// The Steps
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Step {
/// Step 1
One,
/// Step 2
Two,
/// Step 3
Three,
/// Step 4
Four,
}
impl Default for Step {
fn default() -> Self {
Self::One
}
}
impl StepExt for Step {
fn next(&self) -> Option<Self> {
match self {
Self::One => Some(Self::Two),
Self::Two => Some(Self::Three),
Self::Three => Some(Self::Four),
Self::Four => None,
}
}
fn as_number(&self) -> usize {
match self {
Self::One => 1,
Self::Two => 2,
Self::Three => 3,
Self::Four => 4,
}
}
fn label(&self) -> &'static str {
//TODO - localizaton
const STR_CONTENT: &'static str = "Content";
const STR_DESIGN: &'static str = "Design";
const STR_SETTINGS: &'static str = "Settings";
const STR_PREVIEW: &'static str = "Preview";
match self {
Self::One => STR_CONTENT,
Self::Two => STR_DESIGN,
Self::Three => STR_SETTINGS,
Self::Four => STR_PREVIEW,
}
}
fn get_list() -> Vec<Self> {
vec![Self::One, Self::Two, Self::Three, Self::Four]
}
fn get_preview() -> Self {
Self::Four
}
}