Skip to main content

ankit_builder/
schema.rs

1//! TOML schema types for deck definitions.
2//!
3//! # Example TOML
4//!
5//! ```toml
6//! [package]
7//! name = "Spanish Vocabulary"
8//! version = "1.0.0"
9//! author = "Your Name"
10//!
11//! [[models]]
12//! name = "Basic Spanish"
13//! fields = ["Spanish", "English", "Example"]
14//! # Optional: specify which field to sort by (default: first field)
15//! sort_field = "Spanish"
16//!
17//! [[models.templates]]
18//! name = "Spanish -> English"
19//! front = "{{Spanish}}"
20//! back = "{{FrontSide}}<hr>{{English}}<br><i>{{Example}}</i>"
21//!
22//! [[models.templates]]
23//! name = "English -> Spanish"
24//! front = "{{English}}"
25//! back = "{{FrontSide}}<hr>{{Spanish}}"
26//!
27//! [[decks]]
28//! name = "Spanish::Vocabulary"
29//! description = "Core Spanish vocabulary"
30//!
31//! [[notes]]
32//! deck = "Spanish::Vocabulary"
33//! model = "Basic Spanish"
34//! tags = ["chapter1", "nouns"]
35//!
36//! [notes.fields]
37//! Spanish = "el gato"
38//! English = "the cat"
39//! Example = "El gato es negro."
40//! ```
41
42use serde::{Deserialize, Serialize};
43use std::collections::HashMap;
44use std::path::Path;
45
46use crate::error::{Error, Result};
47
48/// Root structure for a deck definition file.
49#[derive(Debug, Clone, Serialize, Deserialize)]
50pub struct DeckDefinition {
51    /// Package metadata.
52    pub package: PackageInfo,
53
54    /// Model (note type) definitions.
55    #[serde(default)]
56    pub models: Vec<ModelDef>,
57
58    /// Deck definitions.
59    #[serde(default)]
60    pub decks: Vec<DeckDef>,
61
62    /// Note definitions.
63    #[serde(default)]
64    pub notes: Vec<NoteDef>,
65
66    /// Media file definitions.
67    #[serde(default)]
68    pub media: Vec<MediaDef>,
69}
70
71impl DeckDefinition {
72    /// Load a deck definition from a TOML file.
73    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    /// Parse a deck definition from a TOML string.
79    pub fn parse(content: &str) -> Result<Self> {
80        let def: DeckDefinition = toml::from_str(content)?;
81        def.validate()?;
82        Ok(def)
83    }
84
85    /// Validate the deck definition for consistency.
86    pub fn validate(&self) -> Result<()> {
87        // Check that all notes reference valid models
88        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            // Check that note fields match model fields
97            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        // Check that all notes reference valid decks
109        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    /// Get a model by name.
122    pub fn get_model(&self, name: &str) -> Option<&ModelDef> {
123        self.models.iter().find(|m| m.name == name)
124    }
125
126    /// Get a deck by name.
127    pub fn get_deck(&self, name: &str) -> Option<&DeckDef> {
128        self.decks.iter().find(|d| d.name == name)
129    }
130
131    /// Get notes for a specific deck.
132    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    /// Convert HTML to Markdown in fields marked as `markdown_fields`.
137    ///
138    /// Call this after exporting from Anki to get cleaner, more readable TOML.
139    ///
140    /// # Example
141    ///
142    /// ```no_run
143    /// use ankit_builder::DeckDefinition;
144    ///
145    /// # fn example() -> ankit_builder::Result<()> {
146    /// let mut definition = DeckDefinition::from_file("deck.toml")?;
147    /// definition.html_to_markdown();
148    /// definition.write_toml("deck_markdown.toml")?;
149    /// # Ok(())
150    /// # }
151    /// ```
152    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    /// Convert Markdown to HTML in fields marked as `markdown_fields`.
167    ///
168    /// Call this before importing to Anki to convert readable Markdown to HTML.
169    ///
170    /// # Example
171    ///
172    /// ```no_run
173    /// use ankit_builder::DeckDefinition;
174    ///
175    /// # fn example() -> ankit_builder::Result<()> {
176    /// let mut definition = DeckDefinition::from_file("deck.toml")?;
177    /// definition.markdown_to_html();
178    /// // Now ready to import to Anki
179    /// # Ok(())
180    /// # }
181    /// ```
182    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    /// Set markdown fields for a model.
197    ///
198    /// Convenience method to mark which fields should use Markdown format.
199    ///
200    /// # Example
201    ///
202    /// ```no_run
203    /// use ankit_builder::DeckDefinition;
204    ///
205    /// # fn example() -> ankit_builder::Result<()> {
206    /// let mut definition = DeckDefinition::from_file("deck.toml")?;
207    /// definition.set_markdown_fields("Basic", &["Back", "Extra"]);
208    /// # Ok(())
209    /// # }
210    /// ```
211    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/// Package metadata.
219#[derive(Debug, Clone, Serialize, Deserialize)]
220pub struct PackageInfo {
221    /// Package name (used as default deck name if no decks defined).
222    pub name: String,
223
224    /// Package version.
225    #[serde(default = "default_version")]
226    pub version: String,
227
228    /// Package author.
229    #[serde(default)]
230    pub author: Option<String>,
231
232    /// Package description.
233    #[serde(default)]
234    pub description: Option<String>,
235}
236
237fn default_version() -> String {
238    "1.0.0".to_string()
239}
240
241/// Model (note type) definition.
242#[derive(Debug, Clone, Serialize, Deserialize)]
243pub struct ModelDef {
244    /// Model name (must be unique).
245    pub name: String,
246
247    /// Field names in order.
248    pub fields: Vec<String>,
249
250    /// Card templates.
251    pub templates: Vec<TemplateDef>,
252
253    /// CSS styling for cards.
254    #[serde(default)]
255    pub css: Option<String>,
256
257    /// Which field to sort by (default: first field).
258    #[serde(default)]
259    pub sort_field: Option<String>,
260
261    /// Model ID (auto-generated if not specified).
262    #[serde(default)]
263    pub id: Option<i64>,
264
265    /// Fields that use Markdown format (converted to/from HTML).
266    ///
267    /// When pushing to Anki, markdown in these fields is converted to HTML.
268    /// When pulling from Anki, HTML in these fields is converted to markdown.
269    #[serde(default)]
270    pub markdown_fields: Vec<String>,
271
272    /// Model type: "standard" (default) or "cloze".
273    ///
274    /// When set to "cloze", templates are optional and a default cloze template is used.
275    #[serde(default)]
276    pub model_type: Option<String>,
277}
278
279impl ModelDef {
280    /// Create a new cloze model with default template.
281    ///
282    /// # Example
283    ///
284    /// ```
285    /// use ankit_builder::ModelDef;
286    ///
287    /// let model = ModelDef::cloze("My Cloze Model", vec!["Text", "Extra"]);
288    /// assert_eq!(model.name, "My Cloze Model");
289    /// assert!(model.is_cloze());
290    /// ```
291    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    /// Check if this is a cloze model.
309    pub fn is_cloze(&self) -> bool {
310        self.model_type.as_deref() == Some("cloze")
311    }
312}
313
314impl ModelDef {
315    /// Get the sort field index.
316    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/// Card template definition.
326#[derive(Debug, Clone, Serialize, Deserialize)]
327pub struct TemplateDef {
328    /// Template name.
329    pub name: String,
330
331    /// Front template (question side).
332    pub front: String,
333
334    /// Back template (answer side).
335    pub back: String,
336}
337
338/// Deck definition.
339#[derive(Debug, Clone, Serialize, Deserialize)]
340pub struct DeckDef {
341    /// Deck name (use :: for hierarchy, e.g., "Parent::Child").
342    pub name: String,
343
344    /// Deck description.
345    #[serde(default)]
346    pub description: Option<String>,
347
348    /// Deck ID (auto-generated if not specified).
349    #[serde(default)]
350    pub id: Option<i64>,
351}
352
353/// Note definition.
354#[derive(Debug, Clone, Serialize, Deserialize)]
355pub struct NoteDef {
356    /// Deck name to add note to.
357    pub deck: String,
358
359    /// Model name for this note.
360    pub model: String,
361
362    /// Field values.
363    pub fields: HashMap<String, String>,
364
365    /// Tags for this note.
366    #[serde(default)]
367    pub tags: Vec<String>,
368
369    /// Custom GUID (auto-generated if not specified).
370    #[serde(default)]
371    pub guid: Option<String>,
372
373    /// Anki note ID (assigned after sync, used for tracking).
374    #[serde(default, skip_serializing_if = "Option::is_none")]
375    pub note_id: Option<i64>,
376}
377
378impl NoteDef {
379    /// Get field values in model field order.
380    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    /// Get tags as a space-separated string with surrounding spaces.
389    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    /// Get fields with markdown converted to HTML for specified fields.
398    ///
399    /// Returns a new HashMap with markdown fields converted to HTML.
400    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    /// Convert HTML to markdown in specified fields (mutates in place).
417    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/// Media file definition.
429#[derive(Debug, Clone, Serialize, Deserialize)]
430pub struct MediaDef {
431    /// Filename as referenced in note fields (e.g., "audio.mp3").
432    pub name: String,
433
434    /// Path to the source file.
435    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        // B is missing, should be empty
576
577        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}