use typst::diag::Warned;
use typst::layout::PagedDocument;
use typst_pdf::PdfOptions;
use crate::error_mapping::map_typst_errors;
use crate::world::QuillWorld;
use quillmark_core::{Diagnostic, Quill, RenderError, Severity};
fn compile_document(world: &QuillWorld) -> Result<PagedDocument, RenderError> {
let Warned { output, warnings } = typst::compile::<PagedDocument>(world);
for warning in warnings {
eprintln!("Warning: {}", warning.message);
}
match output {
Ok(doc) => Ok(doc),
Err(errors) => {
let diagnostics = map_typst_errors(&errors, world);
Err(RenderError::CompilationFailed { diags: diagnostics })
}
}
}
pub fn compile_to_pdf(
quill: &Quill,
plated_content: &str,
json_data: &str,
) -> Result<Vec<u8>, RenderError> {
let world = QuillWorld::new_with_data(quill, plated_content, json_data).map_err(|e| {
RenderError::EngineCreation {
diag: Box::new(
Diagnostic::new(
Severity::Error,
format!("Failed to create Typst compilation environment: {}", e),
)
.with_code("typst::world_creation".to_string())
.with_source(e),
),
}
})?;
let document = compile_document(&world)?;
let pdf = typst_pdf::pdf(&document, &PdfOptions::default()).map_err(|e| {
RenderError::CompilationFailed {
diags: vec![Diagnostic::new(
Severity::Error,
format!("PDF generation failed: {:?}", e),
)
.with_code("typst::pdf_generation".to_string())],
}
})?;
Ok(pdf)
}
pub fn compile_to_svg(
quill: &Quill,
plated_content: &str,
json_data: &str,
) -> Result<Vec<Vec<u8>>, RenderError> {
let world = QuillWorld::new_with_data(quill, plated_content, json_data).map_err(|e| {
RenderError::EngineCreation {
diag: Box::new(
Diagnostic::new(
Severity::Error,
format!("Failed to create Typst compilation environment: {}", e),
)
.with_code("typst::world_creation".to_string())
.with_source(e),
),
}
})?;
let document = compile_document(&world)?;
let mut pages = Vec::new();
for page in &document.pages {
let svg = typst_svg::svg(page);
pages.push(svg.into_bytes());
}
Ok(pages)
}