1use serde::{Deserialize, Serialize};
43use std::collections::HashMap;
44use std::path::Path;
45
46use crate::error::{Error, Result};
47
48#[derive(Debug, Clone, Serialize, Deserialize)]
50pub struct DeckDefinition {
51 pub package: PackageInfo,
53
54 #[serde(default)]
56 pub models: Vec<ModelDef>,
57
58 #[serde(default)]
60 pub decks: Vec<DeckDef>,
61
62 #[serde(default)]
64 pub notes: Vec<NoteDef>,
65
66 #[serde(default)]
68 pub media: Vec<MediaDef>,
69}
70
71impl DeckDefinition {
72 pub fn from_file(path: impl AsRef<Path>) -> Result<Self> {
74 let content = std::fs::read_to_string(path)?;
75 Self::parse(&content)
76 }
77
78 pub fn parse(content: &str) -> Result<Self> {
80 let def: DeckDefinition = toml::from_str(content)?;
81 def.validate()?;
82 Ok(def)
83 }
84
85 pub fn validate(&self) -> Result<()> {
87 let model_names: std::collections::HashSet<_> =
89 self.models.iter().map(|m| m.name.as_str()).collect();
90
91 for note in &self.notes {
92 if !model_names.contains(note.model.as_str()) {
93 return Err(Error::ModelNotFound(note.model.clone()));
94 }
95
96 let model = self.models.iter().find(|m| m.name == note.model).unwrap();
98 for field_name in note.fields.keys() {
99 if !model.fields.contains(field_name) {
100 return Err(Error::FieldNotFound {
101 model: note.model.clone(),
102 field: field_name.clone(),
103 });
104 }
105 }
106 }
107
108 let deck_names: std::collections::HashSet<_> =
110 self.decks.iter().map(|d| d.name.as_str()).collect();
111
112 for note in &self.notes {
113 if !deck_names.contains(note.deck.as_str()) {
114 return Err(Error::DeckNotFound(note.deck.clone()));
115 }
116 }
117
118 Ok(())
119 }
120
121 pub fn get_model(&self, name: &str) -> Option<&ModelDef> {
123 self.models.iter().find(|m| m.name == name)
124 }
125
126 pub fn get_deck(&self, name: &str) -> Option<&DeckDef> {
128 self.decks.iter().find(|d| d.name == name)
129 }
130
131 pub fn notes_for_deck(&self, deck_name: &str) -> impl Iterator<Item = &NoteDef> {
133 self.notes.iter().filter(move |n| n.deck == deck_name)
134 }
135
136 pub fn html_to_markdown(&mut self) {
153 use crate::markdown::html_to_markdown;
154
155 for note in &mut self.notes {
156 if let Some(model) = self.models.iter().find(|m| m.name == note.model) {
157 for field_name in &model.markdown_fields {
158 if let Some(value) = note.fields.get_mut(field_name) {
159 *value = html_to_markdown(value);
160 }
161 }
162 }
163 }
164 }
165
166 pub fn markdown_to_html(&mut self) {
183 use crate::markdown::markdown_to_html;
184
185 for note in &mut self.notes {
186 if let Some(model) = self.models.iter().find(|m| m.name == note.model) {
187 for field_name in &model.markdown_fields {
188 if let Some(value) = note.fields.get_mut(field_name) {
189 *value = markdown_to_html(value);
190 }
191 }
192 }
193 }
194 }
195
196 pub fn set_markdown_fields(&mut self, model_name: &str, fields: &[&str]) {
212 if let Some(model) = self.models.iter_mut().find(|m| m.name == model_name) {
213 model.markdown_fields = fields.iter().map(|s| s.to_string()).collect();
214 }
215 }
216}
217
218#[derive(Debug, Clone, Serialize, Deserialize)]
220pub struct PackageInfo {
221 pub name: String,
223
224 #[serde(default = "default_version")]
226 pub version: String,
227
228 #[serde(default)]
230 pub author: Option<String>,
231
232 #[serde(default)]
234 pub description: Option<String>,
235}
236
237fn default_version() -> String {
238 "1.0.0".to_string()
239}
240
241#[derive(Debug, Clone, Serialize, Deserialize)]
243pub struct ModelDef {
244 pub name: String,
246
247 pub fields: Vec<String>,
249
250 pub templates: Vec<TemplateDef>,
252
253 #[serde(default)]
255 pub css: Option<String>,
256
257 #[serde(default)]
259 pub sort_field: Option<String>,
260
261 #[serde(default)]
263 pub id: Option<i64>,
264
265 #[serde(default)]
270 pub markdown_fields: Vec<String>,
271
272 #[serde(default)]
276 pub model_type: Option<String>,
277}
278
279impl ModelDef {
280 pub fn cloze(name: impl Into<String>, fields: Vec<impl Into<String>>) -> Self {
292 Self {
293 name: name.into(),
294 fields: fields.into_iter().map(Into::into).collect(),
295 templates: vec![TemplateDef {
296 name: "Cloze".to_string(),
297 front: "{{cloze:Text}}".to_string(),
298 back: "{{cloze:Text}}<br>{{Extra}}".to_string(),
299 }],
300 css: None,
301 sort_field: None,
302 id: None,
303 markdown_fields: vec![],
304 model_type: Some("cloze".to_string()),
305 }
306 }
307
308 pub fn is_cloze(&self) -> bool {
310 self.model_type.as_deref() == Some("cloze")
311 }
312}
313
314impl ModelDef {
315 pub fn sort_field_index(&self) -> usize {
317 if let Some(ref name) = self.sort_field {
318 self.fields.iter().position(|f| f == name).unwrap_or(0)
319 } else {
320 0
321 }
322 }
323}
324
325#[derive(Debug, Clone, Serialize, Deserialize)]
327pub struct TemplateDef {
328 pub name: String,
330
331 pub front: String,
333
334 pub back: String,
336}
337
338#[derive(Debug, Clone, Serialize, Deserialize)]
340pub struct DeckDef {
341 pub name: String,
343
344 #[serde(default)]
346 pub description: Option<String>,
347
348 #[serde(default)]
350 pub id: Option<i64>,
351}
352
353#[derive(Debug, Clone, Serialize, Deserialize)]
355pub struct NoteDef {
356 pub deck: String,
358
359 pub model: String,
361
362 pub fields: HashMap<String, String>,
364
365 #[serde(default)]
367 pub tags: Vec<String>,
368
369 #[serde(default)]
371 pub guid: Option<String>,
372
373 #[serde(default, skip_serializing_if = "Option::is_none")]
375 pub note_id: Option<i64>,
376}
377
378impl NoteDef {
379 pub fn fields_ordered(&self, model: &ModelDef) -> Vec<String> {
381 model
382 .fields
383 .iter()
384 .map(|f| self.fields.get(f).cloned().unwrap_or_default())
385 .collect()
386 }
387
388 pub fn tags_string(&self) -> String {
390 if self.tags.is_empty() {
391 String::new()
392 } else {
393 format!(" {} ", self.tags.join(" "))
394 }
395 }
396
397 pub fn fields_as_html(&self, markdown_fields: &[String]) -> HashMap<String, String> {
401 use crate::markdown::markdown_to_html;
402
403 self.fields
404 .iter()
405 .map(|(name, value)| {
406 let converted = if markdown_fields.contains(name) {
407 markdown_to_html(value)
408 } else {
409 value.clone()
410 };
411 (name.clone(), converted)
412 })
413 .collect()
414 }
415
416 pub fn convert_html_to_markdown(&mut self, markdown_fields: &[String]) {
418 use crate::markdown::html_to_markdown;
419
420 for field_name in markdown_fields {
421 if let Some(value) = self.fields.get_mut(field_name) {
422 *value = html_to_markdown(value);
423 }
424 }
425 }
426}
427
428#[derive(Debug, Clone, Serialize, Deserialize)]
430pub struct MediaDef {
431 pub name: String,
433
434 pub path: String,
436}
437
438#[cfg(test)]
439mod tests {
440 use super::*;
441
442 #[test]
443 fn test_parse_basic_definition() {
444 let toml = r#"
445[package]
446name = "Test Deck"
447version = "1.0.0"
448
449[[models]]
450name = "Basic"
451fields = ["Front", "Back"]
452
453[[models.templates]]
454name = "Card 1"
455front = "{{Front}}"
456back = "{{FrontSide}}<hr>{{Back}}"
457
458[[decks]]
459name = "Test Deck"
460
461[[notes]]
462deck = "Test Deck"
463model = "Basic"
464tags = ["test"]
465
466[notes.fields]
467Front = "Question"
468Back = "Answer"
469"#;
470
471 let def = DeckDefinition::parse(toml).unwrap();
472 assert_eq!(def.package.name, "Test Deck");
473 assert_eq!(def.models.len(), 1);
474 assert_eq!(def.models[0].fields, vec!["Front", "Back"]);
475 assert_eq!(def.decks.len(), 1);
476 assert_eq!(def.notes.len(), 1);
477 assert_eq!(def.notes[0].fields.get("Front").unwrap(), "Question");
478 }
479
480 #[test]
481 fn test_invalid_model_reference() {
482 let toml = r#"
483[package]
484name = "Test"
485
486[[decks]]
487name = "Test Deck"
488
489[[notes]]
490deck = "Test Deck"
491model = "NonExistent"
492
493[notes.fields]
494Front = "Q"
495"#;
496
497 let result = DeckDefinition::parse(toml);
498 assert!(matches!(result, Err(Error::ModelNotFound(_))));
499 }
500
501 #[test]
502 fn test_invalid_deck_reference() {
503 let toml = r#"
504[package]
505name = "Test"
506
507[[models]]
508name = "Basic"
509fields = ["Front"]
510
511[[models.templates]]
512name = "Card 1"
513front = "{{Front}}"
514back = "{{Front}}"
515
516[[notes]]
517deck = "NonExistent"
518model = "Basic"
519
520[notes.fields]
521Front = "Q"
522"#;
523
524 let result = DeckDefinition::parse(toml);
525 assert!(matches!(result, Err(Error::DeckNotFound(_))));
526 }
527
528 #[test]
529 fn test_invalid_field_reference() {
530 let toml = r#"
531[package]
532name = "Test"
533
534[[models]]
535name = "Basic"
536fields = ["Front", "Back"]
537
538[[models.templates]]
539name = "Card 1"
540front = "{{Front}}"
541back = "{{Back}}"
542
543[[decks]]
544name = "Test Deck"
545
546[[notes]]
547deck = "Test Deck"
548model = "Basic"
549
550[notes.fields]
551Front = "Q"
552InvalidField = "X"
553"#;
554
555 let result = DeckDefinition::parse(toml);
556 assert!(matches!(result, Err(Error::FieldNotFound { .. })));
557 }
558
559 #[test]
560 fn test_fields_ordered() {
561 let model = ModelDef {
562 name: "Test".to_string(),
563 fields: vec!["A".to_string(), "B".to_string(), "C".to_string()],
564 templates: vec![],
565 css: None,
566 sort_field: None,
567 id: None,
568 markdown_fields: vec![],
569 model_type: None,
570 };
571
572 let mut fields = HashMap::new();
573 fields.insert("C".to_string(), "third".to_string());
574 fields.insert("A".to_string(), "first".to_string());
575 let note = NoteDef {
578 deck: "Test".to_string(),
579 model: "Test".to_string(),
580 fields,
581 tags: vec![],
582 guid: None,
583 note_id: None,
584 };
585
586 let ordered = note.fields_ordered(&model);
587 assert_eq!(ordered, vec!["first", "", "third"]);
588 }
589
590 #[test]
591 fn test_cloze_model() {
592 let model = ModelDef::cloze("My Cloze", vec!["Text", "Extra"]);
593
594 assert_eq!(model.name, "My Cloze");
595 assert_eq!(model.fields, vec!["Text", "Extra"]);
596 assert!(model.is_cloze());
597 assert_eq!(model.model_type, Some("cloze".to_string()));
598 assert_eq!(model.templates.len(), 1);
599 assert_eq!(model.templates[0].name, "Cloze");
600 assert!(model.templates[0].front.contains("{{cloze:Text}}"));
601 }
602
603 #[test]
604 fn test_standard_model_is_not_cloze() {
605 let model = ModelDef {
606 name: "Basic".to_string(),
607 fields: vec!["Front".to_string(), "Back".to_string()],
608 templates: vec![],
609 css: None,
610 sort_field: None,
611 id: None,
612 markdown_fields: vec![],
613 model_type: None,
614 };
615
616 assert!(!model.is_cloze());
617 }
618
619 #[test]
620 fn test_parse_cloze_model_from_toml() {
621 let toml = r#"
622[package]
623name = "Cloze Test"
624
625[[models]]
626name = "My Cloze"
627model_type = "cloze"
628fields = ["Text", "Extra"]
629
630[[models.templates]]
631name = "Cloze"
632front = "{{cloze:Text}}"
633back = "{{cloze:Text}}<br>{{Extra}}"
634
635[[decks]]
636name = "Cloze Test"
637"#;
638
639 let def = DeckDefinition::parse(toml).unwrap();
640 assert!(def.models[0].is_cloze());
641 }
642}