refactor(export): HtmlRender & HtmlHandler

This commit is contained in:
PoiScript 2019-02-14 13:38:48 +08:00
parent 8ba9ade62d
commit 69de17ad9b
7 changed files with 246 additions and 237 deletions

View file

@ -1,33 +0,0 @@
use std::env;
use std::fs::File;
use std::io::Cursor;
use std::io::Read;
use orgize::export::{HtmlHandler, Render};
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
println!("Usage: {} <org-file>", args[0]);
return;
}
let mut file = File::open(&args[1]).expect(&format!("file {} not found", &args[1]));
let mut contents = String::new();
file.read_to_string(&mut contents)
.expect("something went wrong reading the file");
let cursor = Cursor::new(Vec::new());
let handler = HtmlHandler;
let mut render = Render::new(handler, cursor, &contents);
render
.render()
.expect("something went wrong rendering the file");
println!(
"{}",
String::from_utf8(render.into_wirter().into_inner()).expect("invalid utf-8")
);
}

View file

@ -0,0 +1,49 @@
use std::env::args;
use std::fs::File;
use std::io::{Cursor, Read, Result, Write};
use orgize::export::*;
use orgize::headline::Headline;
use slugify::slugify;
struct CustomHtmlHandler;
impl<W: Write> HtmlHandler<W> for CustomHtmlHandler {
fn handle_headline_beg(&mut self, w: &mut W, hdl: Headline) -> Result<()> {
write!(
w,
r##"<h{0}><a class="anchor" href="#{1}">{2}</a></h{0}>"##,
if hdl.level <= 6 { hdl.level } else { 6 },
slugify!(hdl.title),
hdl.title,
)
}
}
fn main() -> Result<()> {
let args: Vec<_> = args().collect();
if args.len() < 2 {
println!("Usage: {} <org-file>", args[0]);
} else {
let mut file = File::open(&args[1])?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let cursor = Cursor::new(Vec::new());
//let mut render = DefaultHtmlRender::new(cursor, &contents);
// comment the following line and uncomment the line above to use the default handler
let mut render = HtmlRender::new(CustomHtmlHandler, cursor, &contents);
render.render()?;
println!(
"{}",
String::from_utf8(render.into_wirter().into_inner()).expect("invalid utf-8")
);
}
Ok(())
}