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
551
552
553
554
555
556
557
558
559
560
use std::collections::HashMap;

use chrono::{Datelike, Duration, Local};
use comemo::Prehashed;
use ecow::EcoVec;
use thiserror::Error;
use typst::diag::{FileError, FileResult, SourceDiagnostic, SourceResult};
use typst::eval::Tracer;
use typst::foundations::{Bytes, Datetime, Dict, Module, Scope};
use typst::model::Document;
use typst::syntax::package::PackageSpec;
use typst::syntax::{FileId, Source, VirtualPath};
use typst::text::{Font, FontBook};
use typst::Library;

// Inspired by https://github.com/tfachmann/typst-as-library/blob/main/src/lib.rs

#[derive(Debug, Clone)]
pub struct TypstTemplate {
    source: Source,
    collection: TypstTemplateCollection,
}

impl TypstTemplate {
    /// Initialize with fonts and a given source.
    /// - `source` can be of types:
    ///     - `&str/String`, creating a detached Source (Has vpath `/main.typ`)
    ///     - `(&str, &str/String)`, where &str is the absolute
    ///       virtual path of the Source file.
    ///     - `(typst::syntax::FileId, &str/String)`
    ///     - `typst::syntax::Source`
    ///
    /// (`&str/String` is always the template file content)
    ///
    /// Example:
    /// ```rust
    /// static TEMPLATE: &str = include_str!("./templates/template.typ");
    /// static FONT: &[u8] = include_bytes!("./fonts/texgyrecursor-regular.otf");
    /// // ...
    /// let font = Font::new(Bytes::from(FONT), 0).expect("Could not parse font!");
    /// let template = TypstTemplate::new(vec![font], TEMPLATE);
    /// ```
    pub fn new<V, S>(fonts: V, source: S) -> Self
    where
        V: Into<Vec<Font>>,
        S: Into<SourceNewType>,
    {
        let collection = TypstTemplateCollection::new(fonts);
        let SourceNewType(source) = source.into();
        Self { collection, source }
    }

    /// Add sources for template
    /// - `other_sources` The item of the IntoIterator can be of types:
    ///     - `&str/String`, creating a detached Source (Has vpath `/main.typ`)
    ///     - `(&str, &str/String)`, where &str is the absolute
    ///       virtual path of the Source file.
    ///     - `(typst::syntax::FileId, &str/String)`
    ///     - `typst::syntax::Source`
    ///
    /// (`&str/String` is always the template file content)
    ///
    /// Example:
    /// ```rust
    /// static OTHER_SOURCE: &str = include_str!("./templates/other_source.typ");
    /// // ...
    /// let source = ("/other_source.typ", OTHER_SOURCE);
    /// template = template.add_other_sources([source]);
    /// ```
    pub fn add_other_sources<I, S>(self, other_sources: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<SourceNewType>,
    {
        Self {
            collection: self.collection.add_sources(other_sources),
            ..self
        }
    }

    /// Add binary files for template
    /// Example:
    /// ```rust
    /// static IMAGE: &[u8] = include_bytes!("./images/image.png");
    /// // ...
    /// let tuple = ("/images/image.png", IMAGE);
    /// template = template.add_binary_files([tuple]);
    /// ```
    pub fn add_binary_files<I, F, B>(self, files: I) -> Self
    where
        I: IntoIterator<Item = (F, B)>,
        F: Into<FileIdNewType>,
        B: Into<Bytes>,
    {
        Self {
            collection: self.collection.add_binary_files(files),
            ..self
        }
    }

    /// Replace main source
    pub fn source<S>(self, source: S) -> Self
    where
        S: Into<SourceNewType>,
    {
        let SourceNewType(source) = source.into();
        Self { source, ..self }
    }

    /// Use other typst location for injected inputs
    /// (instead of`#import sys: inputs`, where `sys` is the `module_name`
    /// and `inputs` is the `value_name`).
    /// Also preinitializes the library for better performance,
    /// if the template will be reused.
    /// TypstTemplate::compile will panic in debug build,
    /// if the location is already used.
    pub fn custom_inject_location<S>(self, module_name: S, value_name: S) -> Self
    where
        S: Into<String>,
    {
        Self {
            collection: self
                .collection
                .custom_inject_location(module_name, value_name),
            ..self
        }
    }

    /// Add Fonts
    pub fn add_fonts<I, F>(self, fonts: I) -> Self
    where
        I: IntoIterator<Item = F>,
        F: Into<Font>,
    {
        Self {
            collection: self.collection.add_fonts(fonts),
            ..self
        }
    }

    /// Call `typst::compile()` with our template and a `Dict` as input, that will be availible
    /// in a typst script with `#import sys: inputs`.
    pub fn compile_with_input<D>(
        &self,
        tracer: &mut Tracer,
        inputs: D,
    ) -> Result<Document, TypstAsLibError>
    where
        D: Into<Dict>,
    {
        let Self {
            source, collection, ..
        } = self;
        let library = initialize_library(collection, inputs);
        let world = TypstWorld {
            library: Prehashed::new(library),
            collection,
            main_source: &source,
        };
        let doc = typst::compile(&world, tracer)?;
        Ok(doc)
    }

    /// Just call `typst::compile()`
    pub fn compile(&self, tracer: &mut Tracer) -> Result<Document, TypstAsLibError> {
        let Self {
            source, collection, ..
        } = self;
        let world = TypstWorld {
            library: Default::default(),
            collection,
            main_source: source,
        };
        let doc = typst::compile(&world, tracer)?;
        Ok(doc)
    }
}

#[derive(Debug, Clone)]
pub struct TypstTemplateCollection {
    book: Prehashed<FontBook>,
    sources: HashMap<FileId, Source>,
    files: HashMap<FileId, Bytes>,
    fonts: Vec<Font>,
    inject_location: Option<InjectLocation>,
}

impl TypstTemplateCollection {
    /// Initialize with fonts.
    ///
    /// Example:
    /// ```rust
    /// static FONT: &[u8] = include_bytes!("./fonts/texgyrecursor-regular.otf");
    /// // ...
    /// let font = Font::new(Bytes::from(FONT), 0).expect("Could not parse font!");
    /// let template = TypstTemplate::new(vec![font]);
    /// ```
    pub fn new<V>(fonts: V) -> Self
    where
        V: Into<Vec<Font>>,
    {
        let fonts = fonts.into();
        Self {
            book: Prehashed::new(FontBook::from_fonts(&fonts)),
            fonts,
            sources: Default::default(),
            files: Default::default(),
            inject_location: Default::default(),
        }
    }

    /// Add sources for template
    /// - `sources` The item of the IntoIterator can be of types:
    ///     - `&str/String`, creating a detached Source (Has vpath `/main.typ`)
    ///     - `(&str, &str/String)`, where &str is the absolute
    ///       virtual path of the Source file.
    ///     - `(typst::syntax::FileId, &str/String)`
    ///     - `typst::syntax::Source`
    ///
    /// (`&str/String` is always the template file content)
    ///
    /// Example:
    /// ```rust
    /// static SOURCE: &str = include_str!("./templates/source.typ");
    /// // ...
    /// let source = ("/source.typ", SOURCE);
    /// template = template.add_sources([source]);
    /// ```
    pub fn add_sources<I, S>(mut self, sources: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<SourceNewType>,
    {
        let new_sources = sources.into_iter().map(|s| {
            let SourceNewType(s) = s.into();
            (s.id(), s)
        });
        self.sources.extend(new_sources);
        self
    }

    /// Add binary files for template
    /// Example:
    /// ```rust
    /// static IMAGE: &[u8] = include_bytes!("./images/image.png");
    /// // ...
    /// let tuple = ("/images/image.png", IMAGE);
    /// template = template.add_binary_files([tuple]);
    /// ```
    pub fn add_binary_files<I, F, B>(mut self, files: I) -> Self
    where
        I: IntoIterator<Item = (F, B)>,
        F: Into<FileIdNewType>,
        B: Into<Bytes>,
    {
        let new_files = files.into_iter().map(|(id, b)| {
            let FileIdNewType(id) = id.into();
            (id, b.into())
        });
        self.files.extend(new_files);
        self
    }

    /// Use other typst location for injected inputs
    /// (instead of`#import sys: inputs`, where `sys` is the `module_name`
    /// and `inputs` is the `value_name`).
    /// Also preinitializes the library for better performance,
    /// if the template will be reused.
    /// TypstTemplate::compile will panic in debug build,
    /// if the location is already used.
    pub fn custom_inject_location<S>(self, module_name: S, value_name: S) -> Self
    where
        S: Into<String>,
    {
        Self {
            inject_location: Some(InjectLocation {
                preinitialized_library: Default::default(),
                module_name: module_name.into(),
                value_name: value_name.into(),
            }),
            ..self
        }
    }

    /// Add Fonts
    pub fn add_fonts<I, F>(mut self, fonts: I) -> Self
    where
        I: IntoIterator<Item = F>,
        F: Into<Font>,
    {
        let fonts = fonts.into_iter().map(Into::into);
        self.fonts.extend(fonts);
        self
    }

    /// Call `typst::compile()` with our template and a `Dict` as input, that will be availible
    /// in a typst script with `#import sys: inputs`.
    ///
    /// Example:
    ///
    /// ```rust
    /// static TEMPLATE: &str = include_str!("./templates/template.typ");
    /// static FONT: &[u8] = include_bytes!("./fonts/texgyrecursor-regular.otf");
    /// static TEMPLATE_ID: &str = "/template.typ";
    /// // ...
    /// let font = Font::new(Bytes::from(FONT), 0).expect("Could not parse font!");
    /// let template_collection = TypstTemplateCollection::new(vec![font])
    ///     .add_sources([(TEMPLATE_ID, TEMPLATE)]);
    /// // Struct that implements Into<Dict>.
    /// let inputs = todo!();
    /// let tracer = Default::default();
    /// let doc = template_collection.compile_with_inputs(&mut tracer, TEMPLATE_ID, inputs)
    ///     .expect("Typst error!");
    /// ```
    pub fn compile_with_input<F, D>(
        &self,
        tracer: &mut Tracer,
        main_source: F,
        inputs: D,
    ) -> Result<Document, TypstAsLibError>
    where
        F: Into<FileIdNewType>,
        D: Into<Dict>,
    {
        let Self { sources, .. } = self;
        let FileIdNewType(main_source) = main_source.into();
        let main_source = sources
            .get(&main_source)
            .ok_or_else(|| TypstAsLibError::MainSourceFileDoesNotExist(main_source))?;
        let library = initialize_library(self, inputs);
        let world = TypstWorld {
            library: Prehashed::new(library),
            collection: self,
            main_source,
        };
        let doc = typst::compile(&world, tracer)?;
        Ok(doc)
    }

    /// Just call `typst::compile()`
    pub fn compile<F>(
        &self,
        tracer: &mut Tracer,
        main_source: F,
    ) -> Result<Document, TypstAsLibError>
    where
        F: Into<FileIdNewType>,
    {
        let Self { sources, .. } = self;
        let FileIdNewType(main_source) = main_source.into();
        let main_source = sources
            .get(&main_source)
            .ok_or_else(|| TypstAsLibError::MainSourceFileDoesNotExist(main_source))?;
        let world = TypstWorld {
            library: Default::default(),
            collection: self,
            main_source,
        };
        let doc = typst::compile(&world, tracer)?;
        Ok(doc)
    }
}

fn initialize_library<D>(collection: &TypstTemplateCollection, inputs: D) -> Library
where
    D: Into<Dict>,
{
    let inputs = inputs.into();
    let TypstTemplateCollection {
        inject_location, ..
    } = collection;
    if let Some(InjectLocation {
        preinitialized_library,
        module_name,
        value_name,
    }) = inject_location
    {
        let mut lib = preinitialized_library.clone();
        let global = lib.global.scope_mut();
        let mut scope = Scope::new();
        scope.define(value_name, inputs);
        let module = Module::new(module_name, scope);
        global.define_module(module);
        lib
    } else {
        Library::builder().with_inputs(inputs).build()
    }
}

struct TypstWorld<'a> {
    library: Prehashed<Library>,
    main_source: &'a Source,
    collection: &'a TypstTemplateCollection,
}

impl typst::World for TypstWorld<'_> {
    fn library(&self) -> &Prehashed<Library> {
        &self.library
    }

    fn book(&self) -> &Prehashed<FontBook> {
        &self.collection.book
    }

    fn main(&self) -> Source {
        self.main_source.clone()
    }

    fn source(&self, id: FileId) -> FileResult<Source> {
        let TypstWorld {
            collection: TypstTemplateCollection { sources, .. },
            ..
        } = self;

        if let Some(source) = sources.get(&id).cloned() {
            return Ok(source);
        }

        if id == self.main().id() {
            return Ok(self.main());
        }

        Err(FileError::NotFound(
            id.vpath().as_rooted_path().to_path_buf(),
        ))
    }

    fn file(&self, id: FileId) -> FileResult<Bytes> {
        let TypstWorld {
            collection: TypstTemplateCollection { files, .. },
            ..
        } = self;

        files
            .get(&id)
            .cloned()
            .ok_or_else(|| FileError::NotFound(id.vpath().as_rooted_path().to_path_buf()))
    }

    fn font(&self, id: usize) -> Option<Font> {
        self.collection.fonts.get(id).cloned()
    }

    fn today(&self, offset: Option<i64>) -> Option<Datetime> {
        let mut now = Local::now();
        if let Some(offset) = offset {
            now += Duration::hours(offset);
        }
        let date = now.date_naive();
        let year = date.year();
        let month = (date.month0() + 1) as u8;
        let day = (date.day0() + 1) as u8;
        Datetime::from_ymd(year, month, day)
    }
}

#[derive(Debug, Clone)]
struct InjectLocation {
    preinitialized_library: Library,
    module_name: String,
    value_name: String,
}

#[derive(Debug, Clone, Error)]
pub enum TypstAsLibError {
    #[error("Typst source error: {}", 0.to_string())]
    TypstSource(EcoVec<SourceDiagnostic>),
    #[error("Source file does not exist in collection")]
    MainSourceFileDoesNotExist(FileId),
}

impl From<EcoVec<SourceDiagnostic>> for TypstAsLibError {
    fn from(value: EcoVec<SourceDiagnostic>) -> Self {
        TypstAsLibError::TypstSource(value)
    }
}

#[derive(Clone, Debug, Hash)]
pub struct FileIdNewType(FileId);

impl From<FileId> for FileIdNewType {
    fn from(value: FileId) -> Self {
        FileIdNewType(value)
    }
}

impl From<FileIdNewType> for FileId {
    fn from(file_id: FileIdNewType) -> Self {
        let FileIdNewType(file_id) = file_id;
        file_id
    }
}

impl From<&str> for FileIdNewType {
    fn from(value: &str) -> Self {
        FileIdNewType(FileId::new(None, VirtualPath::new(value)))
    }
}

impl From<(PackageSpec, &str)> for FileIdNewType {
    fn from((p, id): (PackageSpec, &str)) -> Self {
        FileIdNewType(FileId::new(Some(p), VirtualPath::new(id)))
    }
}

#[derive(Clone, Debug, Hash)]
pub struct SourceNewType(Source);

impl From<Source> for SourceNewType {
    fn from(source: Source) -> Self {
        SourceNewType(source)
    }
}

impl From<SourceNewType> for Source {
    fn from(source: SourceNewType) -> Self {
        let SourceNewType(source) = source;
        source
    }
}

impl From<(&str, String)> for SourceNewType {
    fn from((path, source): (&str, String)) -> Self {
        let id = FileId::new(None, VirtualPath::new(path));
        let source = Source::new(id, source);
        SourceNewType(source)
    }
}

impl From<(&str, &str)> for SourceNewType {
    fn from((path, source): (&str, &str)) -> Self {
        SourceNewType::from((path, source.to_owned()))
    }
}

impl From<(FileId, String)> for SourceNewType {
    fn from((id, source): (FileId, String)) -> Self {
        let source = Source::new(id, source);
        SourceNewType(source)
    }
}

impl From<(FileId, &str)> for SourceNewType {
    fn from((id, source): (FileId, &str)) -> Self {
        SourceNewType::from((id, source.to_owned()))
    }
}

impl From<String> for SourceNewType {
    fn from(source: String) -> Self {
        let source = Source::detached(source);
        SourceNewType(source)
    }
}

impl From<&str> for SourceNewType {
    fn from(source: &str) -> Self {
        SourceNewType::from(source.to_owned())
    }
}