Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ minify-html = "0.15.0"
notify = "6.1.1"
num_cpus = "1.16.0"
once_cell = "1.20.2"
rayon = "1.10"
rouille = "3.6.2"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0.120"
Expand Down
29 changes: 0 additions & 29 deletions generate.sh

This file was deleted.

78 changes: 51 additions & 27 deletions src/dev/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ use std::sync::mpsc::Receiver;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use WithItem::None;

pub static WS_PORT: OnceCell<u16> = OnceCell::new();
pub const SCRIPT: &str = include_str!("./inline_script.html");
Expand All @@ -30,7 +29,7 @@ fn dev_rebuild(res: Result<notify::Event, notify::Error>) -> Result<(), Vec<Proc
}
Err(e) => Err(vec![ProcessError {
error_type: ErrorType::Other,
item: None,
item: WithItem::None,
path: PathBuf::from("Watcher"),
message: Some(format!("{e} (internal watcher error)")),
}]),
Expand All @@ -39,14 +38,25 @@ fn dev_rebuild(res: Result<notify::Event, notify::Error>) -> Result<(), Vec<Proc

fn spawn_websocket_handler(receiver: Receiver<String>, src: PathBuf, ws_port: u16) {
let clients: Arc<Mutex<HashMap<u64, Responder>>> = Arc::new(Mutex::new(HashMap::new()));
let event_hub = simple_websockets::launch(ws_port)
.unwrap_or_else(|_| panic!("failed to listen on port {}", ws_port));
let event_hub = match simple_websockets::launch(ws_port) {
Ok(hub) => hub,
Err(e) => {
eprintln!("Failed to launch websocket server on port {}: {:?}", ws_port, e);
return;
}
};

// Spawn thread to handle messages from receiver
let clients_clone = Arc::clone(&clients);
thread::spawn(move || loop {
let message = receiver.recv().unwrap();
let locked_clients = clients_clone.lock().unwrap();
let message = match receiver.recv() {
Ok(msg) => msg,
Err(_) => return, // Channel closed, exit thread
};
let locked_clients = match clients_clone.lock() {
Ok(c) => c,
Err(_) => return, // Mutex poisoned, exit thread
};

let json = serde_json::json!({
"message": if message == "reload" { "reload" } else { &message }
Expand All @@ -62,13 +72,15 @@ fn spawn_websocket_handler(receiver: Receiver<String>, src: PathBuf, ws_port: u1
loop {
match event_hub.poll_event() {
Event::Connect(client_id, responder) => {
let mut locked_clients = clients.lock().unwrap();
locked_clients.insert(client_id, responder);
if let Ok(mut locked_clients) = clients.lock() {
locked_clients.insert(client_id, responder);
}
}

Event::Disconnect(client_id) => {
let mut locked_clients = clients.lock().unwrap();
locked_clients.remove(&client_id);
if let Ok(mut locked_clients) = clients.lock() {
locked_clients.remove(&client_id);
}
}

Event::Message(_, msg) => {
Expand All @@ -84,8 +96,14 @@ fn spawn_websocket_handler(receiver: Receiver<String>, src: PathBuf, ws_port: u1

fn handle_markdown_update(json: &serde_json::Value, src: &PathBuf) {
if json["type"] == "markdown_update" {
let content = json["content"].as_str().unwrap().trim();
let original = json["originalContent"].as_str().unwrap().trim();
let content = match json["content"].as_str() {
Some(s) => s.trim(),
None => return,
};
let original = match json["originalContent"].as_str() {
Some(s) => s.trim(),
None => return,
};
if let Ok(files) = utils::walk_dir(src) {
for path in files {
if let Ok(file_content) = fs::read_to_string(&path) {
Expand Down Expand Up @@ -143,38 +161,44 @@ pub fn spawn_watcher(args: Vec<String>) {
.with_compare_contents(true)
.with_poll_interval(Duration::from_millis(200));

let mut watcher = notify::PollWatcher::new(
let mut watcher = match notify::PollWatcher::new(
move |res| {
let result = dev_rebuild(res);
if result.is_ok() {
let send = sender.send("reload".to_string());
if send.is_err() {
let e = send.unwrap_err();
if let Err(e) = sender.send("reload".to_string()) {
cprintln!("<s><y>Warning: failed to send reload signal: </></>: {e}");
}
} else {
let e = result.unwrap_err();
} else if let Err(e) = result {
let _ = sender.send(utils::format_errs(&e));
utils::print_vec_errs(&e);
}
},
config,
)
.unwrap();
) {
Ok(w) => w,
Err(e) => {
eprintln!("Failed to create watcher: {}", e);
return;
}
};

watcher
.watch(&src, RecursiveMode::Recursive)
.expect("watch failed");
if let Err(e) = watcher.watch(&src, RecursiveMode::Recursive) {
eprintln!("Failed to watch directory: {}", e);
return;
}

let preview_addr = format!("0.0.0.0:{}", preview_port);

rouille::start_server(preview_addr, move |request| {
{
let mut response = rouille::match_assets(request, dist.to_str().unwrap());
let dist_str = match dist.to_str() {
Some(s) => s,
None => return Response::html("500 Internal Server Error").with_status_code(500),
};
let mut response = rouille::match_assets(request, dist_str);
if request.url() == "/" {
let f = fs::File::open(dist.join("index").with_extension("html"));
if f.is_ok() {
response = Response::from_file("text/html", f.unwrap());
if let Ok(f) = fs::File::open(dist.join("index").with_extension("html")) {
response = Response::from_file("text/html", f);
}
}
if response.is_success() {
Expand Down
11 changes: 3 additions & 8 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,10 @@ impl fmt::Display for ProcessError {
Some(msg) => cformat!("<strong>{msg}</>"),
None => String::new(),
};
let path = &self
let path = self
.path
.to_str()
.to_owned()
.expect("Couldn't turn PathBuf into string whilst formatting error message.");
.unwrap_or("<invalid-utf8-path>");
let err_msg = match self.error_type {
ErrorType::Io => {
cformat!("The {item} <r>{path}</> encountered an IO error. {msg_fmt}")
Expand Down Expand Up @@ -98,11 +97,7 @@ impl<T, E: std::fmt::Display> MapProcErr<T, E> for Result<T, E> {
message: Option<String>,
) -> Result<T, ProcessError> {
self.map_err(|e| {
let msg = if message.is_some() {
message.unwrap()
} else {
format!("{}", e)
};
let msg = message.unwrap_or_else(|| format!("{}", e));
ProcessError {
error_type,
item,
Expand Down
10 changes: 8 additions & 2 deletions src/handlers/components.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,12 @@ pub fn process_component(

let mut errors: Vec<ProcessError> = Vec::new();
let mut output = input;

// Early return if no matches
if !regex.is_match(&output).unwrap_or(false) {
return ProcessResult { output, errors };
}

let mut replacements = Vec::new();

for f in regex.find_iter(&output) {
Expand All @@ -180,7 +186,7 @@ pub fn process_component(
ComponentTypes::SelfClosing => {
let result = get_component_self(src, name, targets, hist.clone());
errors.extend(result.errors);
replacements.push((found_str.to_string(), result.output));
replacements.push((found_str.to_owned(), result.output));
}
ComponentTypes::Wrapping => {
let end = format!("</{}>", name);
Expand All @@ -193,7 +199,7 @@ pub fn process_component(
replacements.push((content, String::new()));
}
replacements.push((end, String::new()));
replacements.push((found_str.to_string(), result.output));
replacements.push((found_str.to_owned(), result.output));
}
}
}
Expand Down
27 changes: 19 additions & 8 deletions src/handlers/entries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub fn process_entry(
kv: Vec<(&str, &str)>,
) -> Vec<ProcessError> {
let mut errors: Vec<ProcessError> = Vec::new();
let is_dev = *IS_DEV.get().unwrap();
let is_dev = *IS_DEV.get().unwrap_or(&false);

// Reset KaTeX usage flag for this page
katex_assets::reset_katex_flag();
Expand All @@ -37,9 +37,21 @@ pub fn process_entry(
.join("templates")
.join(name.replace(":", "/"))
.with_extension("frame.html");
let result_path = src
.parent()
.unwrap()

let src_parent = match src.parent() {
Some(p) => p,
None => {
errors.push(ProcessError {
error_type: ErrorType::Io,
item: WithItem::File,
path: src.clone(),
message: Some("Source directory has no parent".to_string()),
});
return errors;
}
};

let result_path = src_parent
.join(if is_dev { "dev" } else { "dist" })
.join(result_path.trim_start_matches("/"));

Expand Down Expand Up @@ -121,10 +133,9 @@ pub fn process_entry(

if is_dev && !s.contains("// * SCRIPT INCLUDED IN DEV MODE") {
s = s.replace("<head>", &format!("<head>{}", SCRIPT));
s = s.replace(
"__SIMPLE_WS_PORT_PLACEHOLDER__",
&WS_PORT.get().unwrap().to_string(),
);
if let Some(ws_port) = WS_PORT.get() {
s = s.replace("__SIMPLE_WS_PORT_PLACEHOLDER__", &ws_port.to_string());
}
}

let output = minify(&s.into_bytes(), &minify_html::Cfg::spec_compliant());
Expand Down
23 changes: 19 additions & 4 deletions src/handlers/markdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,25 @@ fn render_katex(html: &str) -> Result<String, String> {

for captures in MATH_SPAN_REGEX.captures_iter(html) {
if let Ok(cap) = captures {
let mat = cap.get(0).unwrap();
let mat = match cap.get(0) {
Some(m) => m,
None => continue,
};
let start = mat.start();
let end = mat.end();

// Add everything before this match
result.push_str(&html[last_end..start]);

// Extract math style and content
let style = cap.get(1).unwrap().as_str();
let latex = cap.get(2).unwrap().as_str();
let style = match cap.get(1) {
Some(m) => m.as_str(),
None => continue,
};
let latex = match cap.get(2) {
Some(m) => m.as_str(),
None => continue,
};

// Configure KaTeX options
let opts = Opts::builder()
Expand Down Expand Up @@ -90,6 +99,11 @@ fn render_katex(html: &str) -> Result<String, String> {
}

pub fn render_markdown(input: String) -> String {
// Early return if no markdown
if !input.contains("</markdown>") {
return input;
}

let mut plugins = Plugins::default();
plugins.render.codefence_syntax_highlighter = Some(&*SYNTAX_HIGHLIGHTER);
let options = create_markdown_options();
Expand All @@ -114,7 +128,8 @@ pub fn render_markdown(input: String) -> String {
Ok(html) => html,
Err(e) => {
eprintln!("KaTeX rendering error: {}", e);
std::process::exit(1);
// Return the rendered HTML without KaTeX processing on error
rendered
}
};

Expand Down
Loading