use std::path::{Path, PathBuf};
use docx_rs::Docx;
pub mod ir;
mod render;
mod styles;
pub mod typra_runtime;
pub mod typra_spec;
pub use render::RenderStats;
#[derive(Debug, thiserror::Error)]
pub enum ConvertError {
#[error("i/o error: {0}")]
Io(#[from] std::io::Error),
#[error("docx generation failed: {0}")]
Docx(String),
#[error("image error for {path}: {message}")]
Image { path: String, message: String },
}
impl From<docx_rs::DocxError> for ConvertError {
fn from(e: docx_rs::DocxError) -> Self {
ConvertError::Docx(e.to_string())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PageSize {
Letter,
A4,
Legal,
Custom { width_dxa: u32, height_dxa: u32 },
}
impl PageSize {
fn portrait_dxa(self) -> (u32, u32) {
match self {
PageSize::Letter => (12_240, 15_840), PageSize::Legal => (12_240, 20_160), PageSize::A4 => (11_906, 16_838),
PageSize::Custom {
width_dxa,
height_dxa,
} => (width_dxa, height_dxa),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Orientation {
Portrait,
Landscape,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Margins {
pub top: u32,
pub right: u32,
pub bottom: u32,
pub left: u32,
}
impl Margins {
pub fn uniform(dxa: u32) -> Self {
Margins {
top: dxa,
right: dxa,
bottom: dxa,
left: dxa,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PageSetup {
pub size: PageSize,
pub orientation: Orientation,
pub margins: Margins,
}
impl PageSetup {
pub fn dimensions_dxa(&self) -> (u32, u32) {
let (w, h) = self.size.portrait_dxa();
match self.orientation {
Orientation::Portrait => (w, h),
Orientation::Landscape => (h, w),
}
}
pub fn content_width_dxa(&self) -> usize {
let (w, _) = self.dimensions_dxa();
w.saturating_sub(self.margins.left + self.margins.right) as usize
}
}
impl Default for PageSetup {
fn default() -> Self {
PageSetup {
size: PageSize::Letter,
orientation: Orientation::Portrait,
margins: Margins::uniform(1_440),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Theme {
pub body_font: &'static str,
pub heading_font: &'static str,
pub heading_color: &'static str,
pub mono_font: &'static str,
pub link_color: &'static str,
pub code_fill: &'static str,
pub highlight_theme: &'static str,
}
impl Theme {
pub const DEFAULT: Theme = Theme {
body_font: "Aptos",
heading_font: "Aptos Display",
heading_color: "2F5496",
mono_font: "Consolas",
link_color: "0563C1",
code_fill: "F2F2F2",
highlight_theme: "InspiredGitHub",
};
pub const GITHUB: Theme = Theme {
body_font: "Aptos",
heading_font: "Aptos Display",
heading_color: "0969DA",
mono_font: "Consolas",
link_color: "0969DA",
code_fill: "F6F8FA",
highlight_theme: "InspiredGitHub",
};
pub const SOLARIZED: Theme = Theme {
body_font: "Aptos",
heading_font: "Aptos Display",
heading_color: "268BD2",
mono_font: "Consolas",
link_color: "268BD2",
code_fill: "FDF6E3",
highlight_theme: "Solarized (light)",
};
pub fn from_name(name: &str) -> Option<Theme> {
match name.trim().to_ascii_lowercase().as_str() {
"default" => Some(Theme::DEFAULT),
"github" => Some(Theme::GITHUB),
"solarized" => Some(Theme::SOLARIZED),
_ => None,
}
}
}
impl Default for Theme {
fn default() -> Self {
Theme::DEFAULT
}
}
#[derive(Debug, Clone)]
pub struct ConvertOptions {
pub image_dpi: f32,
pub embed_svg: bool,
pub svg_light_mode: bool,
pub max_image_width_px: u32,
pub base_dir: Option<PathBuf>,
pub highlight_code: bool,
pub page: PageSetup,
pub theme: Theme,
pub page_numbers: bool,
pub table_of_contents: bool,
pub language: String,
pub allow_remote_images: bool,
pub captions: bool,
}
impl Default for ConvertOptions {
fn default() -> Self {
ConvertOptions {
image_dpi: 192.0,
embed_svg: true,
svg_light_mode: true,
max_image_width_px: 600,
base_dir: None,
highlight_code: true,
page: PageSetup::default(),
theme: Theme::DEFAULT,
page_numbers: false,
table_of_contents: false,
language: "en-US".to_string(),
allow_remote_images: false,
captions: false,
}
}
}
#[derive(Debug, Clone)]
pub struct Converter {
opts: ConvertOptions,
}
impl Converter {
pub fn new(opts: ConvertOptions) -> Self {
Converter { opts }
}
pub fn options(&self) -> &ConvertOptions {
&self.opts
}
pub fn convert_str(&self, markdown: &str) -> Result<Docx, ConvertError> {
let base = self
.opts
.base_dir
.clone()
.unwrap_or_else(|| PathBuf::from("."));
let (docx, _stats, _svg, _alts, _meta, _math) =
render::build_docx(markdown, &self.opts, &base)?;
Ok(docx)
}
pub fn convert_str_with_stats(
&self,
markdown: &str,
base_dir: &Path,
) -> Result<(Docx, RenderStats), ConvertError> {
let (docx, stats, _svg, _alts, _meta, _math) =
render::build_docx(markdown, &self.opts, base_dir)?;
Ok((docx, stats))
}
pub fn convert_to_bytes(
&self,
markdown: &str,
base_dir: &Path,
) -> Result<(Vec<u8>, RenderStats), ConvertError> {
let (docx, stats, svg_embeds, image_alts, doc_meta, math_embeds) =
render::build_docx(markdown, &self.opts, base_dir)?;
let mut cursor = std::io::Cursor::new(Vec::new());
docx.build()
.pack(&mut cursor)
.map_err(|e| ConvertError::Docx(e.to_string()))?;
let bytes = render::inject_math(cursor.into_inner(), &math_embeds)?;
let bytes = render::inject_svg_layers(bytes, &svg_embeds)?;
let bytes = render::inject_image_alts(bytes, &image_alts)?;
let bytes = render::inject_table_headers(bytes)?;
let bytes = render::inject_core_props(bytes, &doc_meta)?;
let language = doc_meta
.language
.clone()
.unwrap_or_else(|| self.opts.language.clone());
let bytes = render::inject_proofing_language(bytes, &language)?;
Ok((bytes, stats))
}
pub fn convert_file(&self, input: &Path, output: &Path) -> Result<RenderStats, ConvertError> {
let markdown = std::fs::read_to_string(input)?;
let base = self.opts.base_dir.clone().unwrap_or_else(|| {
input
.parent()
.map(Path::to_path_buf)
.unwrap_or_else(|| PathBuf::from("."))
});
let (bytes, stats) = self.convert_to_bytes(&markdown, &base)?;
std::fs::write(output, bytes)?;
Ok(stats)
}
}
pub fn convert_str(markdown: &str) -> Result<Docx, ConvertError> {
Converter::new(ConvertOptions::default()).convert_str(markdown)
}