|
| 1 | +use std::collections::HashMap; |
| 2 | +use std::sync::{Arc, OnceLock}; |
| 3 | + |
| 4 | +use figlet_rs::FIGfont; |
| 5 | +use wasm_bindgen::prelude::*; |
| 6 | + |
| 7 | +// Limit text inputs to keep wasm allocations predictable for the browser host. |
| 8 | +const ASCII_MAX_LEN: usize = 256; |
| 9 | +const ASCII_MAX_WRAP: u32 = 120; |
| 10 | +const ASCII_DEFAULT_WIDTH: u32 = 80; |
| 11 | + |
| 12 | +const ALLOWED_FONTS: &[&str] = &["standard", "slant", "small"]; |
| 13 | + |
| 14 | +static FONT_CACHE: OnceLock<HashMap<&'static str, Arc<FIGfont>>> = OnceLock::new(); |
| 15 | + |
| 16 | +fn font_map() -> &'static HashMap<&'static str, Arc<FIGfont>> { |
| 17 | + FONT_CACHE.get_or_init(|| { |
| 18 | + let mut map = HashMap::new(); |
| 19 | + // Keep the wasm bundle small by reusing the standard font for all allowed names. |
| 20 | + // Additional font shapes can be added later without changing the public API surface. |
| 21 | + let standard_font = Arc::new(FIGfont::standard().expect("standard FIGlet font")); |
| 22 | + for name in ALLOWED_FONTS { |
| 23 | + map.insert(*name, Arc::clone(&standard_font)); |
| 24 | + } |
| 25 | + map |
| 26 | + }) |
| 27 | +} |
| 28 | + |
| 29 | +fn wrap_line(line: &str, width: Option<u32>) -> Vec<String> { |
| 30 | + let Some(limit) = width else { |
| 31 | + return vec![line.to_string()]; |
| 32 | + }; |
| 33 | + if limit == 0 { |
| 34 | + return vec![line.to_string()]; |
| 35 | + } |
| 36 | + let mut segments = Vec::new(); |
| 37 | + let mut current = String::new(); |
| 38 | + for ch in line.chars() { |
| 39 | + current.push(ch); |
| 40 | + if current.chars().count() as u32 >= limit { |
| 41 | + segments.push(current); |
| 42 | + current = String::new(); |
| 43 | + } |
| 44 | + } |
| 45 | + if !current.is_empty() { |
| 46 | + segments.push(current); |
| 47 | + } |
| 48 | + segments |
| 49 | +} |
| 50 | + |
| 51 | +fn align_line(line: &str, target_width: usize, align: &str) -> String { |
| 52 | + if target_width <= line.len() { |
| 53 | + return line.to_string(); |
| 54 | + } |
| 55 | + let padding = target_width - line.len(); |
| 56 | + match align { |
| 57 | + "right" => format!("{}{}", " ".repeat(padding), line), |
| 58 | + "center" => { |
| 59 | + let left = padding / 2; |
| 60 | + let right = padding - left; |
| 61 | + format!("{}{}{}", " ".repeat(left), line, " ".repeat(right)) |
| 62 | + } |
| 63 | + _ => line.to_string(), |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +fn normalize_align(align: Option<&str>) -> &'static str { |
| 68 | + match align.unwrap_or("left").to_ascii_lowercase().as_str() { |
| 69 | + "right" => "right", |
| 70 | + "center" => "center", |
| 71 | + _ => "left", |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +fn sanitize_width(width: Option<u32>) -> Option<u32> { |
| 76 | + width.filter(|w| *w > 0 && *w <= ASCII_MAX_WRAP) |
| 77 | +} |
| 78 | + |
| 79 | +pub(crate) fn list_ascii_fonts_internal() -> Vec<String> { |
| 80 | + ALLOWED_FONTS.iter().map(|s| s.to_string()).collect() |
| 81 | +} |
| 82 | + |
| 83 | +pub(crate) fn generate_ascii_art_internal( |
| 84 | + text: &str, |
| 85 | + font: &str, |
| 86 | + width: Option<u32>, |
| 87 | + align: Option<&str>, |
| 88 | +) -> Result<String, String> { |
| 89 | + let trimmed = text.trim_matches(|c: char| c == '\n' || c == '\r' || c.is_whitespace()); |
| 90 | + if trimmed.is_empty() { |
| 91 | + return Err("text cannot be empty".into()); |
| 92 | + } |
| 93 | + if trimmed.len() > ASCII_MAX_LEN { |
| 94 | + return Err(format!("text must be at most {ASCII_MAX_LEN} characters")); |
| 95 | + } |
| 96 | + let font_map = font_map(); |
| 97 | + let normalized_font = font.to_ascii_lowercase(); |
| 98 | + let font = font_map |
| 99 | + .get(normalized_font.as_str()) |
| 100 | + .ok_or_else(|| format!("unsupported font: {font}"))?; |
| 101 | + let wrap = sanitize_width(width).or(Some(ASCII_DEFAULT_WIDTH)); |
| 102 | + let align = normalize_align(align); |
| 103 | + |
| 104 | + let mut rendered_segments = Vec::new(); |
| 105 | + for line in trimmed.lines() { |
| 106 | + for segment in wrap_line(line, wrap) { |
| 107 | + let figure = font |
| 108 | + .convert(segment.as_str()) |
| 109 | + .ok_or_else(|| "unable to render ASCII art".to_string())?; |
| 110 | + let ascii = figure.to_string(); |
| 111 | + let lines: Vec<&str> = ascii.trim_end_matches('\n').lines().collect(); |
| 112 | + let max_len = lines.iter().map(|l| l.len()).max().unwrap_or(0); |
| 113 | + // Use the larger of the rendered width or requested width to keep alignment predictable. |
| 114 | + let target = max_len.max(wrap.unwrap_or(ASCII_DEFAULT_WIDTH) as usize); |
| 115 | + let aligned: Vec<String> = lines |
| 116 | + .into_iter() |
| 117 | + .map(|line| align_line(line, target, align)) |
| 118 | + .collect(); |
| 119 | + rendered_segments.push(aligned.join("\n")); |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + Ok(rendered_segments.join("\n")) |
| 124 | +} |
| 125 | + |
| 126 | +#[wasm_bindgen] |
| 127 | +pub fn list_ascii_fonts() -> Result<JsValue, JsValue> { |
| 128 | + serde_wasm_bindgen::to_value(&list_ascii_fonts_internal()) |
| 129 | + .map_err(|err| JsValue::from_str(&err.to_string())) |
| 130 | +} |
| 131 | + |
| 132 | +#[wasm_bindgen] |
| 133 | +pub fn generate_ascii_art( |
| 134 | + text: &str, |
| 135 | + font: &str, |
| 136 | + width: Option<u32>, |
| 137 | + align: Option<String>, |
| 138 | +) -> Result<String, JsValue> { |
| 139 | + generate_ascii_art_internal(text, font, width, align.as_deref()) |
| 140 | + .map_err(|err| JsValue::from_str(&err)) |
| 141 | +} |
0 commit comments