renderreport 0.7.2

Data-driven report generation with Typst as embedded render engine — no CLI dependency
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
//! Core rendering engine
//!
//! The Engine is the main entry point for rendering reports.
//! It manages template packs, themes, and the Typst rendering pipeline.

mod builder;
mod config;
pub mod world;

pub use builder::ReportBuilder;
pub use config::EngineConfig;
pub use world::ReportWorld;

use crate::components::catalog::LayoutHint;
use crate::components::{
    dispatcher_template, is_dispatcher, normalize_components, ComponentId, ComponentRegistry,
};
use crate::error::PackError;
use crate::pack::{Pack, PackId, PackLoader};
use crate::render::{RenderOutput, RenderRequest};
use crate::theme::Theme;
use crate::Result;

use std::collections::HashMap;
use std::sync::Arc;

use world::FontCache;

/// The main rendering engine
pub struct Engine {
    /// Engine configuration
    config: EngineConfig,
    /// Loaded template packs
    packs: HashMap<PackId, Arc<Pack>>,
    /// Component registry
    components: ComponentRegistry,
    /// Default theme
    default_theme: Theme,
    /// Pack loader
    pack_loader: PackLoader,
    /// Cached font data, built once at construction time
    font_cache: Arc<FontCache>,
}

impl Engine {
    /// Create a new engine with default configuration
    pub fn new() -> Result<Self> {
        Self::with_config(EngineConfig::default())
    }

    /// Create a new engine with custom configuration
    pub fn with_config(config: EngineConfig) -> Result<Self> {
        Self::with_config_and_fonts(config, &[])
    }

    /// Create a new engine with custom configuration and additional embedded
    /// font byte buffers (e.g. `include_bytes!`-loaded fonts), on top of
    /// whatever `config.use_system_fonts`/`use_embedded_fonts`/`font_paths`
    /// already select. See [`world::FontCache::with_extra_fonts`].
    pub fn with_config_and_fonts(config: EngineConfig, extra_fonts: &[&[u8]]) -> Result<Self> {
        let components = ComponentRegistry::with_standard_components();
        let pack_loader = PackLoader::new(&config.pack_paths);
        let font_cache = Arc::new(FontCache::with_extra_fonts(&config, extra_fonts));

        Ok(Self {
            config,
            packs: HashMap::new(),
            components,
            default_theme: Theme::default_theme(),
            pack_loader,
            font_cache,
        })
    }

    /// Rebuild the font cache from the current configuration.
    ///
    /// Call this if font paths or system font availability change at runtime.
    pub fn reload_fonts(&mut self) {
        self.font_cache = Arc::new(FontCache::new(&self.config));
    }

    /// Set the default theme
    pub fn set_default_theme(&mut self, theme: Theme) {
        self.default_theme = theme;
    }

    /// Get the default theme
    pub fn default_theme(&self) -> &Theme {
        &self.default_theme
    }

    /// Load a template pack from the configured paths
    pub fn load_pack(&mut self, pack_id: &str) -> Result<()> {
        let pack = self.pack_loader.load(pack_id)?;
        self.packs.insert(PackId::new(pack_id), Arc::new(pack));
        Ok(())
    }

    /// Register an embedded pack
    pub fn register_pack(&mut self, pack: Pack) {
        self.packs.insert(pack.id.clone(), Arc::new(pack));
    }

    /// Get a loaded pack
    pub fn get_pack(&self, pack_id: &PackId) -> Option<&Arc<Pack>> {
        self.packs.get(pack_id)
    }

    /// List loaded packs
    pub fn loaded_packs(&self) -> Vec<&PackId> {
        self.packs.keys().collect()
    }

    /// Get the component registry
    pub fn components(&self) -> &ComponentRegistry {
        &self.components
    }

    /// Get mutable component registry
    pub fn components_mut(&mut self) -> &mut ComponentRegistry {
        &mut self.components
    }

    /// Create a new report builder
    pub fn report(&self, template_id: impl Into<String>) -> ReportBuilder {
        ReportBuilder::new(template_id)
    }

    /// Render a report to PDF
    pub fn render_pdf(&self, request: &RenderRequest) -> Result<Vec<u8>> {
        self.render(request).map(|output| output.into_bytes())
    }

    /// Render a report
    pub fn render(&self, request: &RenderRequest) -> Result<RenderOutput> {
        let request = &normalized(request);
        let theme = self.resolve_theme(request)?;
        let typst_source = self.generate_typst_source(request, &theme)?;
        let pdf_bytes = self.compile_typst(&typst_source, request)?;
        Ok(RenderOutput::Pdf(pdf_bytes))
    }

    /// Render a report to its intermediate Typst source.
    ///
    /// Returns the full `.typ` source that would be compiled by [`Self::render`] /
    /// [`Self::render_pdf`]. Useful for snapshot testing, lint/format pipelines
    /// (e.g. `typstyle`), and downstream tooling that wants to inspect or
    /// post-process the source before compilation.
    pub fn render_typ(&self, request: &RenderRequest) -> Result<String> {
        let request = &normalized(request);
        let theme = self.resolve_theme(request)?;
        self.generate_typst_source(request, &theme)
    }

    /// The pack the request names, or `None` without `pack_id`. A pack that
    /// is named but not loaded is an error rather than silently ignored.
    fn request_pack(&self, request: &RenderRequest) -> Result<Option<&Pack>> {
        let Some(pack_id) = &request.pack_id else {
            return Ok(None);
        };
        match self.packs.get(pack_id) {
            Some(pack) => Ok(Some(pack.as_ref())),
            None => Err(PackError::NotFound(pack_id.to_string()).into()),
        }
    }

    /// Name of the pack template the request selects. `template_id` "default"
    /// falls back to the built-in layout when the pack has no such template;
    /// any other unknown name is an error.
    fn request_template<'p>(
        &self,
        pack: Option<&'p Pack>,
        request: &RenderRequest,
    ) -> Result<Option<&'p str>> {
        let Some(pack) = pack else {
            return Ok(None);
        };
        let name = request.template_id.as_str();
        match pack.templates.get_key_value(name) {
            Some((name, _)) => Ok(Some(name.as_str())),
            None if name == "default" => Ok(None),
            None => {
                let mut available: Vec<&str> = pack.templates.keys().map(String::as_str).collect();
                available.sort_unstable();
                Err(PackError::TemplateNotFound {
                    pack: pack.id.to_string(),
                    template: name.to_string(),
                    available: if available.is_empty() {
                        "none".into()
                    } else {
                        available.join(", ")
                    },
                }
                .into())
            }
        }
    }

    /// Merge themes: default -> pack -> pack template -> request
    fn resolve_theme(&self, request: &RenderRequest) -> Result<Theme> {
        let mut theme = self.default_theme.clone();

        let pack = self.request_pack(request)?;
        if let Some(pack) = pack {
            if let Some(pack_theme) = &pack.default_theme {
                theme.merge(pack_theme);
            }
            if let Some(template) = self.request_template(Some(pack), request)? {
                let template_theme = pack.manifest.templates[template]
                    .default_theme
                    .as_ref()
                    .and_then(|name| pack.themes.get(name));
                if let Some(template_theme) = template_theme {
                    theme.merge(template_theme);
                }
            }
        }

        if let Some(request_theme) = &request.theme {
            theme.merge(request_theme);
        }

        Ok(theme)
    }

    /// Generate Typst source from request
    fn generate_typst_source(&self, request: &RenderRequest, theme: &Theme) -> Result<String> {
        let mut source = String::new();

        // Add theme token definitions
        source.push_str("// Theme Tokens\n");
        source.push_str(&theme.tokens.to_typst_definitions());
        source.push_str("\n\n");

        // Add theme helper functions
        source.push_str("// Theme Helpers\n");
        source.push_str(include_str!("../../templates/theme_helpers.typ"));
        source.push_str("\n\n");

        // Inject metadata as Typst variables (needed by header/footer)
        source.push_str("// Report Metadata\n");
        // Reports that use the `cover-page` component as their front page
        // typically don't set `RenderRequest.title` (the component renders its
        // own dashboard-style title instead of the plain built-in title page).
        // PDF/UA-1 requires a document title regardless, so fall back to the
        // cover page's own title (or the first section's, for reports without
        // a cover page) so `#set document(title: ..)` (and the running
        // header, which also reads `report-title`) still get one.
        let fallback_title = fallback_document_title(&request.components);
        let title_str = request
            .title
            .as_deref()
            .filter(|t| !t.is_empty())
            .or(fallback_title.as_deref())
            .unwrap_or("");
        let date_str = request
            .metadata
            .get("date")
            .map(|s| s.as_str())
            .unwrap_or("");
        let author_str = request
            .metadata
            .get("author")
            .map(|s| s.as_str())
            .unwrap_or("");
        let footer_link_url = request
            .metadata
            .get("footer_link_url")
            .map(|s| s.as_str())
            .unwrap_or("");
        let footer_prefix = request
            .metadata
            .get("footer_prefix")
            .map(|s| s.as_str())
            .unwrap_or("");
        let footer_tagline = request
            .metadata
            .get("footer_tagline")
            .map(|s| s.as_str())
            .unwrap_or("");
        let lang_str = request
            .metadata
            .get("lang")
            .map(|s| s.as_str())
            .unwrap_or("en");
        source.push_str(&format!(
            "#let report-title = \"{}\"\n#let report-date = \"{}\"\n#let report-author = \"{}\"\n#let report-footer-link-url = \"{}\"\n#let report-footer-prefix = \"{}\"\n#let report-footer-tagline = \"{}\"\n\n",
            escape_for_typst_string(title_str),
            escape_for_typst_string(date_str),
            escape_for_typst_string(author_str),
            escape_for_typst_string(footer_link_url),
            escape_for_typst_string(footer_prefix),
            escape_for_typst_string(footer_tagline),
        ));

        // Add page setup
        source.push_str(&self.generate_page_setup(theme, &request.page_setup, lang_str));
        source.push_str("\n\n");

        // Add component functions — only those actually used in this request.
        // When flow-group or grid-component is present their dispatchers
        // reference every component function, so we fall back to including all.
        source.push_str("// Component Functions\n");
        let pack = self.request_pack(request)?;
        let used_types = collect_used_component_types(&request.components);
        let needs_all = used_types.contains("flow-group") || used_types.contains("grid-component");
        let wanted = |id: &str| needs_all || used_types.contains(id);

        // A pack component with a built-in id overrides that component; any
        // other id is new and is added to the dispatchers.
        let mut pack_only: Vec<&str> = pack
            .map(|p| p.components.keys().map(String::as_str).collect())
            .unwrap_or_default();
        pack_only.retain(|id| !self.components.has_component(&ComponentId::new(*id)));
        pack_only.sort_unstable();
        let pack_template_for = |id: &str| pack.and_then(|p| p.components.get(id));

        // Emit in registry insertion order — it is deliberately dependency-safe
        // (a template that calls another component's function is registered
        // after it; Typst resolves `#let`s sequentially). The order is made
        // deterministic across platforms at registration time (see registry.rs).
        // Pack-only components follow the built-ins they may call, and the
        // dispatchers come last because they call all of them.
        let (dispatchers, others): (Vec<&ComponentId>, Vec<&ComponentId>) = self
            .components
            .list_components()
            .into_iter()
            .partition(|id| is_dispatcher(&id.0));
        for component_id in others {
            if wanted(&component_id.0) {
                let template = pack_template_for(&component_id.0)
                    .or_else(|| self.components.get_template(component_id));
                if let Some(template) = template {
                    source.push_str(template);
                    source.push_str("\n\n");
                }
            }
        }
        for id in &pack_only {
            if wanted(id) {
                source.push_str(&pack.expect("pack_only implies a pack").components[*id]);
                source.push_str("\n\n");
            }
        }
        for component_id in dispatchers {
            if wanted(&component_id.0) {
                let template = match pack_template_for(&component_id.0) {
                    Some(template) => Some(template.clone()),
                    None if !pack_only.is_empty() => {
                        dispatcher_template(&component_id.0, &pack_only)
                    }
                    None => self.components.get_template(component_id).cloned(),
                };
                if let Some(template) = template {
                    source.push_str(&template);
                    source.push_str("\n\n");
                }
            }
        }

        // Pack template: wraps the whole content and renders its own title page.
        let pack_template = match pack {
            Some(p) => self
                .request_template(Some(p), request)?
                .map(|name| &p.templates[name]),
            None => None,
        };
        if let Some(template) = pack_template {
            let mut meta = serde_json::Map::new();
            meta.insert("title".into(), title_str.into());
            if let Some(subtitle) = &request.subtitle {
                meta.insert("subtitle".into(), subtitle.as_str().into());
            }
            let mut metadata: Vec<_> = request.metadata.iter().collect();
            metadata.sort_unstable();
            for (key, value) in metadata {
                meta.insert(key.clone(), value.as_str().into());
            }
            source.push_str("// Pack Template\n");
            source.push_str(template);
            source.push_str(&format!(
                "\n\n#show: body => report({}, body)\n\n",
                to_typst_dict(&serde_json::Value::Object(meta))
            ));
        }

        // Add report content
        source.push_str("// Report Content\n");
        source.push_str(&self.generate_content(request, pack_template.is_none())?);

        Ok(source)
    }

    /// Generate page setup Typst code
    fn generate_page_setup(
        &self,
        _theme: &Theme,
        page_setup: &crate::render::PageSetup,
        lang: &str,
    ) -> String {
        let paper = page_setup.paper.as_deref().unwrap_or("a4");
        let flipped = page_setup.orientation.as_deref() == Some("landscape");

        let margin_block = if let Some(m) = &page_setup.margin {
            format!("  margin: {},\n", m)
        } else {
            "  margin: (\n    top: page-margin-top,\n    bottom: page-margin-bottom,\n    left: page-margin,\n    right: page-margin,\n  ),\n".to_string()
        };

        let header_block = if page_setup.show_header {
            r#"  header: context {
    if counter(page).get().first() > 1 [
      #set text(size: font-size-xs, fill: color-text-muted)
      #grid(
        columns: (1fr, auto),
        gutter: spacing-3,
        [#report-title],
        [#report-date]
      )
      #v(4pt)
      #line(length: 100%, stroke: (paint: color-border, thickness: 0.7pt))
    ]
  },
"#
        } else {
            ""
        };

        let footer_block = if page_setup.show_footer {
            r#"  footer: context {
    if counter(page).get().first() > 1 [
      #v(1pt)
      #line(length: 100%, stroke: (paint: color-border, thickness: 0.5pt))
      #v(3pt)
      #grid(
        columns: (1fr, auto, 1fr),
        gutter: spacing-3,
        [#text(size: font-size-xs, fill: color-text-muted)[
          #if report-footer-prefix != "" { report-footer-prefix + " " }
          // Running footers are automatically tagged as PDF artifacts by
          // Typst, and PDF/UA-1 forbids links inside artifacts — so this
          // must stay plain text even when a footer link URL is configured
          // (see `report-footer-link-url`, otherwise unused here).
          #text(weight: "semibold")[#report-author]
        ]],
        [#text(size: font-size-xs, fill: color-text-muted)[#counter(page).display("1 / 1", both: true)]],
        align(right)[#text(size: font-size-xs, fill: color-text-muted)[#report-footer-tagline]]
      )
    ]
  },
"#
        } else {
            ""
        };

        format!(
            "#set page(\n  paper: \"{}\",{}\n  fill: color-background,\n{}{}{})\n\n#set document(title: [#report-title])\n\n#set text(\n  font: (font-body, \"Arial\", \"Liberation Sans\", \"Noto Sans\", \"Fira Sans\"),\n  size: font-size-base,\n  fill: color-text,\n  lang: \"{}\",\n)\n\n#set text(hyphenate: true)\n#set par(justify: false, leading: 0.75em)\n\n#set heading(numbering: none)\n#show heading: set par(justify: false)\n#show heading: set block(sticky: true)\n#show heading.where(level: 1): set text(size: font-size-2xl, weight: \"bold\", fill: color-text)\n#show heading.where(level: 2): set text(size: font-size-xl, weight: \"bold\", fill: color-text)\n#show heading.where(level: 3): set text(size: font-size-lg, weight: \"bold\", fill: color-text)\n#show heading.where(level: 4): set text(size: font-size-base, weight: \"bold\", fill: color-text-muted)\n",
            paper,
            if flipped { "\n  flipped: true," } else { "" },
            margin_block,
            header_block,
            footer_block,
            escape_for_typst_string(lang),
        )
    }

    /// Generate report content
    fn generate_content(&self, request: &RenderRequest, title_page: bool) -> Result<String> {
        let mut content = String::new();

        // Title page (a pack template renders its own)
        let has_title = title_page && request.title.as_ref().is_some_and(|t| !t.is_empty());
        if has_title {
            let title = request.title.as_deref().unwrap_or("");
            let subtitle = request.subtitle.as_deref().unwrap_or("");
            let author = request
                .metadata
                .get("author")
                .map(|s| s.as_str())
                .unwrap_or("");
            let date = request
                .metadata
                .get("date")
                .map(|s| s.as_str())
                .unwrap_or("");

            content.push_str(&format!(
                r#"#block(width: 100%, height: 100%, breakable: false)[
  #show heading: set block(above: 0pt, below: 0pt)
  #v(1fr)
  #block(width: 60pt, height: 4pt, fill: color-primary, radius: 2pt)
  #v(spacing-5)
  #heading(level: 1, outlined: false, bookmarked: true)[#block(width: 100%)[#set par(leading: 0.4em); #text(size: 36pt, weight: "bold", fill: color-text, tracking: -0.02em)[{title}]]]
  #v(spacing-3)
  #text(size: 18pt, fill: color-text-muted)[{subtitle}]
  #v(1fr)
  #line(length: 100%, stroke: 0.5pt + color-border)
  #v(spacing-3)
  #text(size: font-size-xs, fill: color-text-muted)[{author}#h(1fr){date}]
]
#pagebreak()

"#,
                title = escape_for_typst_markup(title),
                subtitle = escape_for_typst_markup(subtitle),
                author = escape_for_typst_markup(author),
                date = escape_for_typst_markup(date),
            ));
        }

        // Components
        let components = &request.components;
        let mut i = 0;
        while i < components.len() {
            let component = &components[i];
            let component_type = component
                .get("type")
                .and_then(|v| v.as_str())
                .unwrap_or("unknown");

            use crate::components::catalog::ComponentCatalog;

            let layout_hint = ComponentCatalog::get(component_type)
                .map(|d| d.layout_hint)
                .unwrap_or(LayoutHint::KeepTogether);

            // AlwaysNewPage: start the component on a new page. The break is
            // weak so it is skipped when the page is already empty — a strong
            // break here turned two adjacent `PageBreak`s into a blank page.
            if layout_hint == LayoutHint::AlwaysNewPage {
                content.push_str("#pagebreak(weak: true)\n\n");
            }

            // KeepWithNext: wrap this component and the immediately following
            // non-structural sibling in a keep-together block.
            if layout_hint == LayoutHint::KeepWithNext {
                let next = components.get(i + 1);
                let next_type = next
                    .and_then(|n| n.get("type"))
                    .and_then(|v| v.as_str())
                    .unwrap_or("");
                let next_hint = ComponentCatalog::get(next_type)
                    .map(|d| d.layout_hint)
                    .unwrap_or(LayoutHint::KeepTogether);
                // A `Breakable` next component (e.g. a long audit table) must be
                // allowed to span pages. Pairing it into a `breakable: false`
                // keep-together block traps it and makes it overflow the page
                // instead of breaking, overwriting content below (#366). So a
                // heading is only kept together with a non-breakable sibling.
                let next_is_content = !next_type.is_empty()
                    && !matches!(
                        next_hint,
                        LayoutHint::AlwaysNewPage
                            | LayoutHint::KeepWithNext
                            | LayoutHint::Breakable
                    );

                if next_is_content {
                    let next = next.expect("next_type non-empty implies next is Some");
                    let cur_data = component
                        .get("data")
                        .cloned()
                        .unwrap_or_else(|| component.clone());
                    let next_data = next.get("data").cloned().unwrap_or_else(|| next.clone());
                    let cur_fn = component_function_name(component_type);
                    let next_fn = component_function_name(next_type);
                    let cur_lit = to_typst_dict(&cur_data);
                    let next_lit = to_typst_dict(&next_data);
                    content.push_str(&format!(
                        "#block(breakable: false)[\n  #{cur_fn}({cur_lit})\n  #v(spacing-3)\n  #{next_fn}({next_lit})\n]\n\n#v(spacing-4)\n\n"
                    ));
                    i += 2;
                    continue;
                }
            }

            let data = component
                .get("data")
                .cloned()
                .unwrap_or_else(|| component.clone());

            // Generate component call
            let fn_name = component_function_name(component_type);
            let data_lit = to_typst_dict(&data);

            // Layout / structural components manage their own spacing.
            let is_structural = matches!(
                layout_hint,
                LayoutHint::AlwaysNewPage | LayoutHint::KeepWithNext
            ) || component_type == "page-break";
            if is_structural {
                content.push_str(&format!("#{}({})\n\n", fn_name, data_lit));
            } else {
                content.push_str(&format!("#{}({})\n\n#v(spacing-4)\n\n", fn_name, data_lit));
            }
            i += 1;
        }

        Ok(content)
    }

    /// Compile Typst source to PDF
    fn compile_typst(&self, source: &str, request: &RenderRequest) -> Result<Vec<u8>> {
        use crate::render::typst_compile;

        // Pack assets are reachable from Typst under their path in `assets/`.
        let pack_assets = self
            .request_pack(request)?
            .into_iter()
            .flat_map(|pack| &pack.assets)
            .map(|(name, bytes)| (name.as_str(), bytes.as_slice()));
        typst_compile::compile_with_files(source, &self.font_cache, request, pack_assets)
    }
}

/// The request with every built-in component's data completed the way its
/// Rust builder would have written it, see [`normalize_components`].
fn normalized(request: &RenderRequest) -> RenderRequest {
    let mut request = request.clone();
    normalize_components(&mut request.components);
    request
}

/// Convert a JSON value to a Typst literal expression.
///
/// - `null` → `none`
/// - booleans / numbers → their Typst equivalents
/// - strings → `"..."` with proper escape sequences
/// - arrays → `(item, ...)` with trailing comma for single-element arrays
/// - objects → `(key: val, ...)` with string-quoted keys for non-identifiers
pub fn to_typst_dict(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::Null => "none".to_string(),
        serde_json::Value::Bool(b) => b.to_string(),
        serde_json::Value::Number(n) => n.to_string(),
        serde_json::Value::String(s) => format!("\"{}\"", escape_for_typst_string(s)),
        serde_json::Value::Array(arr) => {
            let items: Vec<String> = arr.iter().map(to_typst_dict).collect();
            match items.len() {
                0 => "()".to_string(),
                // Single-element: needs trailing comma to be an array, not parenthesized value
                1 => format!("({},)", items[0]),
                _ => format!("({})", items.join(", ")),
            }
        }
        serde_json::Value::Object(obj) => {
            if obj.is_empty() {
                return "(:)".to_string();
            }
            let entries: Vec<String> = obj
                .iter()
                .map(|(k, v)| {
                    if is_typst_ident(k) {
                        format!("{}: {}", k, to_typst_dict(v))
                    } else {
                        let escaped_key = k.replace('\\', "\\\\").replace('"', "\\\"");
                        format!("\"{}\": {}", escaped_key, to_typst_dict(v))
                    }
                })
                .collect();
            format!("({})", entries.join(", "))
        }
    }
}

/// Returns true if `s` is a valid Typst identifier.
///
/// Typst keywords that cannot be used as bare dictionary keys.
const TYPST_KEYWORDS: &[&str] = &[
    "none", "auto", "true", "false", "not", "and", "or", "let", "set", "show", "context", "if",
    "else", "for", "in", "while", "break", "continue", "return", "import", "include", "as",
];

/// Returns true if `s` is a valid Typst identifier that can be used as a bare dict key.
///
/// Typst identifiers start with a letter or underscore and continue with
/// letters, digits, underscores, or hyphens — but keywords must be quoted.
fn is_typst_ident(s: &str) -> bool {
    if TYPST_KEYWORDS.contains(&s) {
        return false;
    }
    let mut chars = s.chars();
    match chars.next() {
        Some(c) if c.is_ascii_alphabetic() || c == '_' => {
            chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
        }
        _ => false,
    }
}

/// Escape a string for embedding inside a Typst string literal `"..."`.
fn escape_for_typst_string(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c => out.push(c),
        }
    }
    out
}

/// Escape a string for embedding inside a Typst content block `[...]`.
fn escape_for_typst_markup(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '#' | '[' | ']' | '\\' => {
                out.push('\\');
                out.push(ch);
            }
            c => out.push(c),
        }
    }
    out
}

/// Finds the title of the first top-level `cover-page` component, or else of
/// the first top-level `section`, if any.
///
/// Used as a document-title fallback when the caller didn't set
/// `RenderRequest.title` — see the call site in `generate_typst_source`.
fn fallback_document_title(components: &[serde_json::Value]) -> Option<String> {
    let first_title_of = |component_type: &str| {
        components.iter().find_map(|c| {
            if c.get("type").and_then(|t| t.as_str()) != Some(component_type) {
                return None;
            }
            let data = c.get("data").unwrap_or(c);
            data.get("title")
                .and_then(|t| t.as_str())
                .filter(|t| !t.is_empty())
                .map(str::to_string)
        })
    };
    first_title_of("cover-page").or_else(|| first_title_of("section"))
}

/// Collect all component type IDs referenced anywhere in a component list,
/// including deeply nested items inside flow-group and grid-component.
fn collect_used_component_types(
    components: &[serde_json::Value],
) -> std::collections::HashSet<String> {
    let mut used = std::collections::HashSet::new();
    for c in components {
        collect_types_in_value(c, &mut used);
    }
    used
}

fn collect_types_in_value(v: &serde_json::Value, used: &mut std::collections::HashSet<String>) {
    match v {
        serde_json::Value::Object(obj) => {
            if let Some(t) = obj.get("type").and_then(|t| t.as_str()) {
                used.insert(t.to_string());
            }
            for val in obj.values() {
                collect_types_in_value(val, used);
            }
        }
        serde_json::Value::Array(arr) => {
            for item in arr {
                collect_types_in_value(item, used);
            }
        }
        _ => {}
    }
}

fn component_function_name(component_type: &str) -> &str {
    use crate::components::catalog::ComponentCatalog;

    ComponentCatalog::get(component_type).map_or(component_type, |d| d.fn_name)
}

impl Default for Engine {
    fn default() -> Self {
        Self::new().expect("Failed to create default engine")
    }
}

impl std::fmt::Debug for Engine {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Engine")
            .field("config", &self.config)
            .field("packs", &self.packs.keys().collect::<Vec<_>>())
            .field("default_theme", &self.default_theme.id)
            .finish()
    }
}

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

    #[test]
    fn test_to_typst_dict_primitives() {
        assert_eq!(to_typst_dict(&json!(null)), "none");
        assert_eq!(to_typst_dict(&json!(true)), "true");
        assert_eq!(to_typst_dict(&json!(false)), "false");
        assert_eq!(to_typst_dict(&json!(42)), "42");
        assert_eq!(to_typst_dict(&json!(1.5)), "1.5");
        assert_eq!(to_typst_dict(&json!("hello")), "\"hello\"");
    }

    #[test]
    fn test_to_typst_dict_string_escaping() {
        assert_eq!(to_typst_dict(&json!("a\"b")), r#""a\"b""#);
        assert_eq!(to_typst_dict(&json!("a\nb")), "\"a\\nb\"");
        assert_eq!(to_typst_dict(&json!("a\tb")), "\"a\\tb\"");
        assert_eq!(to_typst_dict(&json!("a\\b")), "\"a\\\\b\"");
    }

    #[test]
    fn test_to_typst_dict_arrays() {
        assert_eq!(to_typst_dict(&json!([])), "()");
        assert_eq!(to_typst_dict(&json!([1])), "(1,)");
        assert_eq!(to_typst_dict(&json!([1, 2])), "(1, 2)");
    }

    #[test]
    fn test_to_typst_dict_objects() {
        assert_eq!(to_typst_dict(&json!({})), "(:)");
        // Note: serde_json preserves insertion order for objects created via json!()
        assert_eq!(to_typst_dict(&json!({"score": 85})), "(score: 85)");
    }

    #[test]
    fn test_to_typst_dict_non_ident_key() {
        assert_eq!(to_typst_dict(&json!({"2xl": "val"})), "(\"2xl\": \"val\")");
    }

    #[test]
    fn test_is_typst_ident() {
        assert!(is_typst_ident("score"));
        assert!(is_typst_ident("max_score"));
        assert!(is_typst_ident("chart-type"));
        assert!(is_typst_ident("_private"));
        assert!(!is_typst_ident("2xl"));
        assert!(!is_typst_ident(""));
        assert!(!is_typst_ident("has space"));
        // Typst keywords must not be bare keys
        assert!(!is_typst_ident("context"));
        assert!(!is_typst_ident("none"));
        assert!(!is_typst_ident("true"));
        assert!(!is_typst_ident("false"));
        assert!(!is_typst_ident("let"));
        assert!(!is_typst_ident("set"));
        assert!(!is_typst_ident("in"));
    }
}