mindtape-eval 0.2.0

Typst evaluation and task extraction for MindTape
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
//! Evaluate a `.typ` file and extract tasks from the content tree.
//!
//! This module is the bridge between Typst evaluation and the task tracker.
//! It calls `typst_eval::eval()` to get a `Module`, then traverses the
//! resulting `Content` tree looking for `ListItem` elements whose body
//! text matches the checkbox convention (`[ ] ` / `[x] `).  Metadata
//! elements produced by `#due()` and `#id()` calls are extracted from
//! each item's body.

use std::fmt;
use std::ops::ControlFlow;

use comemo::Track;
use log::{debug, trace};
use thiserror::Error;
use typst::ROUTINES;
use typst::World;
use typst::engine::{Route, Sink, Traced};
use typst::foundations::{Content, Datetime, Module, StyleChain, Value};
use typst_library::foundations::SequenceElem;
use typst_library::introspection::MetadataElem;
use typst_library::model::{HeadingElem, ListItem};

/// Errors that can occur during Typst evaluation.
#[derive(Debug, Error)]
pub enum EvalError {
    /// The source file could not be read.
    #[error("file error: {0}")]
    File(String),

    /// Typst evaluation produced errors.
    #[error("eval error: {0}")]
    Eval(String),

    /// The world could not be constructed.
    #[error("{0}")]
    World(String),

    /// The file does not import a mindtape package.
    #[error("file does not import mindtape package")]
    NotMindtape,
}

impl EvalError {
    fn from_file_error(err: &typst::diag::FileError) -> Self {
        Self::File(err.to_string())
    }

    fn from_source_diagnostics(errors: &impl fmt::Debug) -> Self {
        Self::Eval(format!("{errors:?}"))
    }
}

/// A task extracted from a Typst checklist item.
#[derive(Debug, Clone, PartialEq)]
pub struct Task {
    pub title: String,
    pub done: bool,
    pub due: Option<Datetime>,
    pub start: Option<Datetime>,
    pub rank: Option<i64>,
    pub tags: Vec<String>,
    pub id: Option<String>,
    pub position: u32,
    /// Heading path leading to this task (e.g. "Header 1 > Subheader 1.1").
    pub milestone: Option<String>,
}

/// Full result from evaluating a `.typ` file.
#[derive(Debug, Clone)]
pub struct EvalResult {
    pub tasks: Vec<Task>,
    pub title: Option<String>,
    /// Bindings as `(name, value_type, value_json)` tuples.
    pub bindings: Vec<(String, String, String)>,
    /// File dependencies (relative paths from project root).
    pub dependencies: Vec<std::path::PathBuf>,
}

/// Evaluate the world's main `.typ` file and return all tasks found in its
/// content tree.
///
/// # Errors
/// Returns `Err` if the source file cannot be read or Typst evaluation fails.
pub fn eval_file(world: &dyn World) -> Result<Vec<Task>, EvalError> {
    eval_file_full(world).map(|r| r.tasks)
}

/// Evaluate the world's main `.typ` file and return tasks, title, and bindings.
///
/// # Errors
/// Returns `Err` if the source file cannot be read or Typst evaluation fails.
pub fn eval_file_full(world: &dyn World) -> Result<EvalResult, EvalError> {
    let source = world
        .source(world.main())
        .map_err(|err| EvalError::from_file_error(&err))?;

    if !has_mindtape_import(source.text()) {
        return Err(EvalError::NotMindtape);
    }

    debug!(
        "evaluating {}",
        source.id().vpath().as_rooted_path().display()
    );

    let mut sink = Sink::new();
    let traced = Traced::default();
    let route = Route::default();

    let module: Module = typst_eval::eval(
        &ROUTINES,
        world.track(),
        traced.track(),
        sink.track_mut(),
        route.track(),
        &source,
    )
    .map_err(|err| EvalError::from_source_diagnostics(&err))?;

    // Extract bindings BEFORE content() consumes the module.
    let bindings = extract_bindings(module.scope());
    trace!("extracted {} bindings", bindings.len());

    let content: Content = module.content();

    let title = extract_file_title(&content);

    let mut tasks = Vec::new();
    collect_tasks(&content, &mut tasks);

    debug!("found {} tasks, {} bindings", tasks.len(), bindings.len());

    Ok(EvalResult {
        tasks,
        title,
        bindings,
        dependencies: Vec::new(), // Generic World trait doesn't expose dependencies
    })
}

/// Evaluate a `MindTapeWorld`'s main file and return tasks, title, bindings, and dependencies.
///
/// This variant works with concrete `MindTapeWorld` instances and can extract
/// cross-file dependencies discovered during evaluation.
///
/// # Errors
/// Returns `Err` if the source file cannot be read or Typst evaluation fails.
pub fn eval_file_full_with_deps(
    world: &crate::world::MindTapeWorld,
) -> Result<EvalResult, EvalError> {
    let source = world
        .source(world.main())
        .map_err(|err| EvalError::from_file_error(&err))?;

    if !has_mindtape_import(source.text()) {
        return Err(EvalError::NotMindtape);
    }

    debug!(
        "evaluating (with deps) {}",
        source.id().vpath().as_rooted_path().display()
    );

    let mut sink = Sink::new();
    let traced = Traced::default();
    let route = Route::default();

    // Cast to &dyn World for the track() method
    let world_dyn: &dyn World = world;

    let module: Module = typst_eval::eval(
        &ROUTINES,
        world_dyn.track(),
        traced.track(),
        sink.track_mut(),
        route.track(),
        &source,
    )
    .map_err(|err| EvalError::from_source_diagnostics(&err))?;

    // Extract bindings BEFORE content() consumes the module.
    let bindings = extract_bindings(module.scope());

    let content: Content = module.content();

    let title = extract_file_title(&content);

    let mut tasks = Vec::new();
    collect_tasks(&content, &mut tasks);

    let dependencies = world.get_dependencies()?;

    debug!(
        "found {} tasks, {} bindings, {} deps",
        tasks.len(),
        bindings.len(),
        dependencies.len()
    );

    Ok(EvalResult {
        tasks,
        title,
        bindings,
        dependencies,
    })
}

/// Recursively traverse `content` looking for `ListItem` nodes and
/// extract a `Task` from each one, assigning 0-based positions.
///
/// Tracks heading context so each task knows which headings precede it.
pub fn collect_tasks(content: &Content, tasks: &mut Vec<Task>) {
    let mut position: u32 = 0;
    // Stack of (depth, heading_text) tracking the current heading context.
    let mut heading_stack: Vec<(usize, String)> = Vec::new();

    let _ = content.traverse(&mut |node: Content| -> ControlFlow<()> {
        if let Some(heading) = node.to_packed::<HeadingElem>() {
            let depth = heading.depth.get(StyleChain::default()).get();
            let text = heading.body.plain_text().trim().to_string();
            // Pop headings at same or deeper level.
            heading_stack.retain(|(d, _)| *d < depth);
            heading_stack.push((depth, text));
        } else if let Some(item) = node.to_packed::<ListItem>()
            && let Some(mut task) = extract_task(item)
        {
            task.position = position;
            task.milestone = if heading_stack.is_empty() {
                None
            } else {
                Some(
                    heading_stack
                        .iter()
                        .map(|(_, t)| t.as_str())
                        .collect::<Vec<_>>()
                        .join(" > "),
                )
            };
            position += 1;
            tasks.push(task);
        }
        ControlFlow::Continue(())
    });
}

/// Extract plain text from content, excluding any nested `ListItem` children.
///
/// When a list item has sub-items, `plain_text()` would include their text too.
/// This function skips nested `ListItem` nodes so we get only the item's own text.
fn plain_text_shallow(content: &Content) -> String {
    if let Some(seq) = content.to_packed::<SequenceElem>() {
        let mut text = String::new();
        for child in &seq.children {
            if child.to_packed::<ListItem>().is_none() {
                text.push_str(&child.plain_text());
            }
        }
        text
    } else {
        content.plain_text().into()
    }
}

/// Try to interpret a single `ListItem` as a task.
///
/// Returns `None` if the item's text does not start with a checkbox marker.
#[allow(clippy::indexing_slicing)]
pub fn extract_task(item: &ListItem) -> Option<Task> {
    let body: &Content = &item.body;
    let text = plain_text_shallow(body);

    // Parse checkbox prefix.
    let (done, title) = if let Some(rest) = text
        .strip_prefix("[x] ")
        .or_else(|| text.strip_prefix("[X] "))
    {
        (true, rest.trim().to_string())
    } else if let Some(rest) = text.strip_prefix("[ ] ") {
        (false, rest.trim().to_string())
    } else {
        // Not a checkbox item — skip.
        return None;
    };

    // Walk the body content looking for MetadataElem nodes produced by
    // `#due()`, `#id()`, and `#tag()`.
    let mut due: Option<Datetime> = None;
    let mut start: Option<Datetime> = None;
    let mut rank: Option<i64> = None;
    let mut tags: Vec<String> = Vec::new();
    let mut id: Option<String> = None;

    let _ = body.traverse(&mut |node: Content| -> ControlFlow<()> {
        if let Some(meta) = node.to_packed::<MetadataElem>() {
            let value = meta.value.clone();
            if let Value::Array(arr) = value {
                let slice = arr.as_slice();
                if slice.len() == 2
                    && let Value::Str(key) = &slice[0]
                {
                    match key.as_str() {
                        "mindtape.due" => {
                            if let Value::Datetime(dt) = &slice[1] {
                                due = Some(*dt);
                            }
                        }
                        "mindtape.start" => {
                            if let Value::Datetime(dt) = &slice[1] {
                                start = Some(*dt);
                            }
                        }
                        "mindtape.rank" => {
                            if let Value::Int(n) = &slice[1] {
                                rank = Some(*n);
                            }
                        }
                        "mindtape.tag" => {
                            if let Value::Str(name) = &slice[1] {
                                tags.push(name.to_string());
                            }
                        }
                        "mindtape.id" => {
                            if let Value::Str(s) = &slice[1] {
                                id = Some(s.to_string());
                            }
                        }
                        _ => {}
                    }
                }
            }
        }
        ControlFlow::Continue(())
    });

    Some(Task {
        title,
        done,
        due,
        start,
        rank,
        tags,
        id,
        position: 0,
        milestone: None,
    })
}

/// Extract the title from the first heading in the content tree.
pub fn extract_file_title(content: &Content) -> Option<String> {
    let mut title = None;
    let _ = content.traverse(&mut |node: Content| -> ControlFlow<()> {
        if let Some(heading) = node.to_packed::<HeadingElem>() {
            title = Some(heading.body.plain_text().trim().to_string());
            return ControlFlow::Break(());
        }
        ControlFlow::Continue(())
    });
    title
}

/// Format a `Datetime` as `YYYY-MM-DD`.
#[must_use]
pub fn format_date(dt: &Datetime) -> String {
    format!(
        "{:04}-{:02}-{:02}",
        dt.year().unwrap_or(0),
        dt.month().unwrap_or(0),
        dt.day().unwrap_or(0),
    )
}

/// Extract `#let` bindings from a module's scope as `(name, value_type, value_json)`.
///
/// Skips functions and other non-data values.
pub fn extract_bindings(scope: &typst::foundations::Scope) -> Vec<(String, String, String)> {
    let mut bindings = Vec::new();
    for (name, binding) in scope.iter() {
        let value = binding.read();
        let (vtype, vjson) = match value {
            Value::Str(str_val) => ("string", format!("\"{}\"", str_val.as_str())),
            Value::Int(int_val) => ("int", int_val.to_string()),
            Value::Float(float_val) => ("float", float_val.to_string()),
            Value::Bool(bool_val) => ("bool", bool_val.to_string()),
            Value::Datetime(dt) => ("date", format!("\"{}\"", format_date(dt))),
            Value::None => ("none", "null".to_string()),
            _ => continue,
        };
        bindings.push((name.to_string(), vtype.to_string(), vjson));
    }
    bindings
}

/// Check whether source text imports a mindtape package.
///
/// Returns `true` if the text contains an `#import` of any package whose
/// name segment is `mindtape` (e.g. `@local/mindtape:…`, `@preview/mindtape:…`,
/// `@mindtape/mindtape:…`).
#[must_use]
pub fn has_mindtape_import(text: &str) -> bool {
    // Match patterns like `@namespace/mindtape:` where namespace is any word.
    text.lines().any(|line| {
        let trimmed = line.trim();
        trimmed.starts_with("#import") && trimmed.contains("/mindtape:")
    })
}

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

    #[test]
    fn has_import_local() {
        assert!(has_mindtape_import(
            r#"#import "@local/mindtape:0.1.0": due, tag, id"#
        ));
    }

    #[test]
    fn has_import_preview() {
        assert!(has_mindtape_import(
            r#"#import "@preview/mindtape:0.1.0": due, tag"#
        ));
    }

    #[test]
    fn has_import_project_namespace() {
        assert!(has_mindtape_import(
            r#"#import "@mindtape/mindtape:0.1.0": due, tag, id"#
        ));
    }

    #[test]
    fn has_import_with_surrounding_content() {
        let text = "= My Tasks\n\n#import \"@local/mindtape:0.1.0\": due\n\n- [ ] do stuff";
        assert!(has_mindtape_import(text));
    }

    #[test]
    fn no_import_plain_typst() {
        assert!(!has_mindtape_import("= Hello\n\n- [ ] a task\n"));
    }

    #[test]
    fn no_import_other_package() {
        assert!(!has_mindtape_import(
            r#"#import "@preview/tablex:0.1.0": tablex"#
        ));
    }

    #[test]
    fn no_import_empty() {
        assert!(!has_mindtape_import(""));
    }

    #[test]
    fn has_import_indented() {
        assert!(has_mindtape_import(
            r#"  #import "@local/mindtape:0.1.0": due"#
        ));
    }
}