ankify 0.1.0

Generate and sync Anki flashcards from your Typst documents.
Documentation
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
//! This module compiles temporary Typst files and manages output files.
//!
//! The compile module has two primary functions:
//!
//! 1. Compile the temporary Typst file generated by the `generate` module using
//!    the appropriate Typst commands (PNG, SVG, or both based on note formats).
//!
//! 2. Associate output files with corresponding notes and fields. It queries the
//!    Typst file for metadata using the `query` module and builds a vector of
//!    `Note` structs. Output files are systematically renamed using the format:
//!    `<label>@@<field>@@<timestamp>.<format>` and added to the `picture` field
//!    of the `Note` struct. For Plain format, no output file is generated and
//!    the string value is passed directly to the note's fields.

use crate::ankiconnect::{Deck, Field, FieldValue, MediaFile, Model, Note as AnkiNote, Tag};
use crate::error::{Error, Result};
use crate::metadata::CompletedNote;
use crate::query;
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

use tokio::process::Command as AsyncCommand;

/// Format types for rendering note fields.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Format {
    /// Plain text format - no compilation needed.
    Plain,
    /// SVG vector format.
    Svg,
    /// PNG raster format.
    Png,
}

impl Format {
    /// Get the file extension for this format.
    pub fn extension(&self) -> &'static str {
        match self {
            Format::Plain => "txt",
            Format::Svg => "svg",
            Format::Png => "png",
        }
    }

    /// Parse a format name, rejecting anything that is not a known format.
    pub fn parse(s: &str) -> Result<Self> {
        match s.to_lowercase().as_str() {
            "plain" => Ok(Format::Plain),
            "svg" => Ok(Format::Svg),
            "png" => Ok(Format::Png),
            other => Err(Error::custom(format!(
                "unknown card format '{}' (expected \"svg\", \"png\", or \"plain\")",
                other
            ))),
        }
    }

    /// Get the typst format argument for this format.
    pub fn typst_arg(&self) -> &'static str {
        match self {
            Format::Plain => panic!("Plain format should not be compiled"),
            Format::Svg => "svg",
            Format::Png => "png",
        }
    }
}

/// Configuration for compiling Typst files.
#[derive(Debug, Clone)]
pub struct CompileConfig {
    /// The temporary Typst file to compile.
    pub temp_file: PathBuf,
    /// Output directory for compiled files.
    pub output_dir: PathBuf,
    /// Additional arguments to pass to typst compile.
    pub extra_args: Vec<String>,
    /// Note metadata with all defaults applied, in document order.
    pub completed_notes_metadata: Vec<CompletedNote>,
    /// The image formats that must be compiled for this run.
    pub required_formats: Vec<Format>,
}

impl CompileConfig {
    /// Create a new compile configuration.
    pub fn new(
        temp_file: PathBuf,
        output_dir: PathBuf,
        completed_notes_metadata: Vec<CompletedNote>,
    ) -> Result<Self> {
        Ok(Self {
            temp_file,
            output_dir,
            extra_args: Vec::new(),
            required_formats: query::determine_required_formats(&completed_notes_metadata)?,
            completed_notes_metadata,
        })
    }

    /// Add extra arguments to the typst compile command.
    pub fn with_extra_args(mut self, args: Vec<String>) -> Self {
        self.extra_args = args;
        self
    }
}

/// Result of a compilation operation.
#[derive(Debug)]
pub struct CompileResult {
    /// The notes with associated media files.
    pub notes: Vec<AnkiNote>,
    /// Paths to generated output files.
    pub output_files: HashMap<Format, Vec<PathBuf>>,
}

/// Compile a temporary Typst file and generate Anki notes.
///
/// This function:
/// 1. Queries the temporary file for note metadata
/// 2. Determines which formats need to be compiled
/// 3. Runs the appropriate typst compile commands
/// 4. Associates output files with notes and fields
/// 5. Returns structured note data for AnkiConnect
///
/// # Arguments
///
/// * `config` - Compilation configuration
///
/// # Returns
///
/// Returns a `CompileResult` containing the generated notes and output file paths.
///
/// # Errors
///
/// Returns an error if:
/// - The temporary file cannot be queried for metadata
/// - Typst compilation fails
/// - Output files cannot be read or renamed
pub async fn compile_temp_file(config: &CompileConfig) -> Result<CompileResult> {
    if config.completed_notes_metadata.is_empty() {
        return Ok(CompileResult {
            notes: Vec::new(),
            output_files: HashMap::new(),
        });
    }

    // Compile the files for each required format, in parallel
    let futures: Vec<_> = config
        .required_formats
        .iter()
        .map(|format| {
            let format_clone = format.clone();
            async move {
                let files = compile_format(config, &format_clone).await;
                (format_clone, files)
            }
        })
        .collect();
    let results = futures::future::join_all(futures).await;
    let mut output_files = HashMap::new();
    for (format, files_result) in results {
        let files = files_result?;
        output_files.insert(format, files);
    }

    // Associate output files with notes and fields
    let notes =
        associate_files_with_notes(config, &config.completed_notes_metadata, &output_files).await?;

    Ok(CompileResult {
        notes,
        output_files,
    })
}

/// Compile the temporary file for a specific format.
async fn compile_format(config: &CompileConfig, format: &Format) -> Result<Vec<PathBuf>> {
    // Use {p} pattern to generate one file per page
    let output_pattern = config
        .output_dir
        .join(format!("output-{{p}}.{}", format.extension()));

    // Build the typst compile command. `extra_args` already carries a resolved
    // `--root` (and any `--font-path`s) set up by the sync module, so the
    // compile and the metadata query share one project root.
    let mut cmd = AsyncCommand::new("typst");
    cmd.arg("compile").arg("--format").arg(format.typst_arg());
    for arg in &config.extra_args {
        cmd.arg(arg);
    }
    cmd.arg(&config.temp_file).arg(&output_pattern);

    // Execute the command
    let output = cmd
        .output()
        .await
        .map_err(|e| Error::custom(format!("Failed to execute typst compile: {}", e)))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(Error::custom(format!(
            "Typst compilation failed: {}",
            stderr
        )));
    }

    // Find all generated output files (output-1.ext, output-2.ext, etc.)
    let mut output_files = Vec::new();
    let output_dir = config.output_dir.as_path();

    if output_dir.exists() {
        let entries = fs::read_dir(output_dir).map_err(|e| {
            Error::custom(format!(
                "Failed to read output directory {}: {}",
                output_dir.display(),
                e
            ))
        })?;

        for entry in entries {
            let entry = entry
                .map_err(|e| Error::custom(format!("Failed to read directory entry: {}", e)))?;

            let path = entry.path();
            if let Some(filename) = path.file_name().and_then(|n| n.to_str()) {
                // Check for pattern: output-<number>.extension
                if filename.starts_with("output-")
                    && path
                        .extension()
                        .is_some_and(|ext| ext == format.extension())
                {
                    output_files.push(path);
                }
            }
        }
    }

    // Sort output files by page number to ensure consistent ordering
    output_files.sort_by(|a, b| {
        let extract_page_num = |path: &PathBuf| -> u32 {
            path.file_stem()
                .and_then(|stem| stem.to_str())
                .and_then(|s| s.strip_prefix("output-"))
                .and_then(|s| s.parse().ok())
                .unwrap_or(0)
        };
        extract_page_num(a).cmp(&extract_page_num(b))
    });

    Ok(output_files)
}

/// Associate output files with notes and fields.
async fn associate_files_with_notes(
    _config: &CompileConfig,
    metadata_notes: &[CompletedNote],
    output_files: &HashMap<Format, Vec<PathBuf>>,
) -> Result<Vec<AnkiNote>> {
    let mut anki_notes = Vec::new();
    let timestamp = chrono::Utc::now().timestamp();

    // Create a mapping of (note_index, field_name) to output file
    let file_associations = create_file_associations(metadata_notes, output_files)?;

    for (note_index, metadata_note) in metadata_notes.iter().enumerate() {
        let mut fields = HashMap::new();
        let mut picture_files = Vec::new();

        // Sort field names to ensure consistent ordering (as per documentation)
        let mut sorted_fields: Vec<_> = metadata_note.data.keys().collect();
        sorted_fields.sort();

        for field_name in sorted_fields {
            let field_value = &metadata_note.data[field_name];
            let field_format = Format::parse(field_value.format.as_str())?;
            let output_file = file_associations.get(&(note_index, field_name.as_str()));
            match field_format {
                Format::Plain => {
                    // Plain text goes straight into the field.
                    fields.insert(
                        Field::new(field_name.clone()),
                        FieldValue::new(field_value.value.clone()),
                    );
                }
                Format::Svg => {
                    // SVG is inlined directly into the field, recoloured so it
                    // follows the Anki card's (themed) text colour. Being part
                    // of the card's DOM, an inline SVG can use `currentColor`;
                    // an `<img>`-embedded SVG could not. No media file needed.
                    match output_file.and_then(|files| files.get(&Format::Svg)) {
                        Some(svg_path) => {
                            let svg = fs::read_to_string(svg_path).map_err(|e| {
                                Error::custom(format!(
                                    "Failed to read SVG '{}': {}",
                                    svg_path.display(),
                                    e
                                ))
                            })?;
                            fields.insert(
                                Field::new(field_name.clone()),
                                FieldValue::new(Some(theme_svg(&svg))),
                            );
                        }
                        None => {
                            fields.insert(
                                Field::new(field_name.clone()),
                                FieldValue::new(field_value.value.clone()),
                            );
                        }
                    }
                }
                Format::Png => {
                    // PNG is stored as an Anki media file, referenced via the
                    // note's `picture` array.
                    if let Some(output_file) = output_file {
                        let media_file = create_media_file(
                            output_file,
                            &metadata_note.label,
                            field_name,
                            timestamp,
                            &field_format,
                        )?;
                        fields.insert(
                            Field::new(field_name.clone()),
                            FieldValue::new(Some(String::new())),
                        );
                        picture_files.push(media_file);
                    } else {
                        fields.insert(
                            Field::new(field_name.clone()),
                            FieldValue::new(field_value.value.clone()),
                        );
                    }
                }
            }
        }

        // Create the Anki note
        let anki_note = AnkiNote {
            deck_name: Deck::new(metadata_note.deck.clone()),
            model_name: Model::new(metadata_note.model.clone()),
            fields,
            tags: Some(
                metadata_note
                    .tags
                    .iter()
                    .map(|tag| Tag::new(tag.clone()))
                    .collect(),
            ),
            options: None,
            audio: None,
            video: None,
            picture: if picture_files.is_empty() {
                None
            } else {
                Some(picture_files)
            },
        };

        anki_notes.push(anki_note);
    }

    Ok(anki_notes)
}

/// Maps `(note index, field name)` to the rendered output file for each format.
type FileAssociations<'a> = HashMap<(usize, &'a str), HashMap<Format, PathBuf>>;

/// Create a mapping of (note_index, field_name) to record { [format]: output_file }.
fn create_file_associations<'a>(
    metadata_notes: &'a [CompletedNote],
    output_files: &'a HashMap<Format, Vec<PathBuf>>,
) -> Result<FileAssociations<'a>> {
    let mut associations = HashMap::new();

    // For each format, get a reference to the Vec<PathBuf>
    let mut format_to_files: HashMap<Format, &Vec<PathBuf>> = HashMap::new();
    for (format, files) in output_files.iter() {
        format_to_files.insert(format.clone(), files);
    }

    // For each field, we need to know which index it is in the global field order
    // The order is: for all notes, for all fields (sorted), in order
    let mut global_field_index = 0;
    for (note_index, metadata_note) in metadata_notes.iter().enumerate() {
        let mut sorted_fields: Vec<_> = metadata_note.data.keys().collect();
        sorted_fields.sort();

        for field_name in sorted_fields {
            // For this (note_index, field_name), build a HashMap<Format, PathBuf>
            let mut field_files = HashMap::new();
            for (format, files) in &format_to_files {
                if global_field_index < files.len() {
                    field_files.insert(format.clone(), files[global_field_index].clone());
                }
            }
            associations.insert((note_index, field_name.as_str()), field_files);
            global_field_index += 1;
        }
    }

    Ok(associations)
}

/// Recolour a Typst-rendered SVG so it adapts to the Anki card's theme.
///
/// The card pages are rendered with no page fill, so the SVG is already
/// transparent and the card's own (light/dark) background shows through. The
/// foreground is rendered black by Typst; rewriting it to `currentColor` makes
/// it follow the card's CSS `color`, which Anki themes for light/dark mode.
/// Non-black colours (e.g. a coloured diagram) are deliberately left untouched.
fn theme_svg(svg: &str) -> String {
    svg.replace("fill=\"#000000\"", "fill=\"currentColor\"")
        .replace("stroke=\"#000000\"", "stroke=\"currentColor\"")
}

/// Reduce a label or field name to characters safe for a media filename, so a
/// note label cannot smuggle path separators into Anki's media directory.
fn sanitize_filename_part(s: &str) -> String {
    s.chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_') {
                c
            } else {
                '_'
            }
        })
        .collect()
}

/// Create a media file from an output file.
pub fn create_media_file(
    output_file: &HashMap<Format, PathBuf>,
    note_label: &str,
    field_name: &str,
    timestamp: i64,
    format: &Format,
) -> Result<MediaFile> {
    // AnkiConnect resolves a media file's `path` relative to Anki's own working
    // directory, not ours — so it must be sent as an absolute path.
    let path = &output_file[format];
    let absolute_path = std::fs::canonicalize(path).map_err(|e| {
        Error::custom(format!(
            "Failed to resolve output file path '{}': {}",
            path.display(),
            e
        ))
    })?;

    Ok(MediaFile {
        filename: format!(
            "{}@@{}@@{}.{}",
            sanitize_filename_part(note_label),
            sanitize_filename_part(field_name),
            timestamp,
            format.extension()
        ),
        data: None,
        path: Some(absolute_path.to_string_lossy().to_string()),
        url: None,
        skip_hash: None,
        fields: Some(vec![Field::new(field_name.to_string())]),
    })
}

/// Clean up output files in the given directory.
///
/// This function removes all files matching the pattern `output-*` in the
/// specified directory.
///
/// # Arguments
///
/// * `dir` - The directory to clean up
///
/// # Errors
///
/// Returns an error if the directory cannot be read or files cannot be removed.
pub fn cleanup_output_files(dir: &Path) -> Result<()> {
    if !dir.exists() {
        return Ok(()); // Nothing to clean up
    }

    let entries = fs::read_dir(dir)
        .map_err(|e| Error::custom(format!("Failed to read directory {}: {}", dir.display(), e)))?;

    for entry in entries {
        let entry = entry.map_err(|e| {
            Error::custom(format!(
                "Failed to read directory entry in {}: {}",
                dir.display(),
                e
            ))
        })?;

        let path = entry.path();
        if let Some(filename) = path.file_name().and_then(|n| n.to_str()) {
            // Clean up both pattern: output-<number>.ext and temp render files
            if filename.starts_with("output-") || filename.ends_with("_render.typ") {
                fs::remove_file(&path).map_err(|e| {
                    Error::custom(format!(
                        "Failed to remove output file {}: {}",
                        path.display(),
                        e
                    ))
                })?;
            }
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn format_parse_accepts_known_formats_case_insensitively() {
        assert_eq!(Format::parse("svg").unwrap(), Format::Svg);
        assert_eq!(Format::parse("PNG").unwrap(), Format::Png);
        assert_eq!(Format::parse("Plain").unwrap(), Format::Plain);
    }

    #[test]
    fn format_parse_rejects_unknown_formats() {
        assert!(Format::parse("jpeg").is_err());
        assert!(Format::parse("").is_err());
    }

    #[test]
    fn format_extension_matches_the_format() {
        assert_eq!(Format::Svg.extension(), "svg");
        assert_eq!(Format::Png.extension(), "png");
        assert_eq!(Format::Plain.extension(), "txt");
    }

    #[test]
    fn theme_svg_recolours_black_to_currentcolor() {
        let themed = theme_svg(r##"<path fill="#000000"/><path stroke="#000000"/>"##);
        assert!(themed.contains(r#"fill="currentColor""#));
        assert!(themed.contains(r#"stroke="currentColor""#));
        assert!(!themed.contains("#000000"));
    }

    #[test]
    fn theme_svg_leaves_non_black_colours_untouched() {
        let svg = r##"<path fill="#0074d9"/>"##;
        assert_eq!(theme_svg(svg), svg);
    }
}