| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| pub mod action; |
| pub mod component; |
| pub mod control; |
| pub mod css; |
| pub mod element; |
| pub mod expr; |
| pub mod layout; |
| pub mod props; |
|
|
| use vibao_ast::{App, Child, ColorFuncKind, ColorValue, Expr, Page, Program}; |
| use crate::codegen::component::ComponentRegistry; |
| use crate::codegen::css::BASE_CSS; |
| use crate::codegen::element::ElementCodegenHost; |
| use crate::codegen::expr::expr_to_js_default; |
| use std::collections::HashMap; |
|
|
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| #[derive(Debug, Clone, Copy, PartialEq)] |
| pub enum BuildMode { |
| Spa, |
| } |
|
|
| impl Default for BuildMode { |
| fn default() -> Self { |
| BuildMode::Spa |
| } |
| } |
|
|
| #[derive(Debug, Clone)] |
| pub struct CodegenOptions { |
| pub mode: BuildMode, |
| pub minify: bool, |
| pub source_map: bool, |
| pub base_url: String, |
| } |
|
|
| impl Default for CodegenOptions { |
| fn default() -> Self { |
| CodegenOptions { |
| mode: BuildMode::Spa, |
| minify: false, |
| source_map: false, |
| base_url: "/".to_string(), |
| } |
| } |
| } |
|
|
| |
| |
| |
|
|
| pub struct CodegenContext { |
| pub options: CodegenOptions, |
| id_counter: u32, |
| css_blocks: Vec<String>, |
| js_blocks: Vec<String>, |
| media_queries: Vec<String>, |
| |
| |
| |
| |
| |
| state_vars: Vec<(String, Expr)>, |
| global_vars: Vec<(String, Expr)>, |
| component_scope: Option<String>, |
| } |
|
|
| impl CodegenContext { |
| pub fn new(options: CodegenOptions) -> Self { |
| CodegenContext { |
| options, |
| id_counter: 0, |
| css_blocks: Vec::new(), |
| js_blocks: Vec::new(), |
| media_queries: Vec::new(), |
| state_vars: Vec::new(), |
| global_vars: Vec::new(), |
| component_scope: None, |
| } |
| } |
|
|
| pub fn next_id(&mut self, tag: &str) -> String { |
| self.id_counter += 1; |
| format!("vb-{}-{}", tag, self.id_counter) |
| } |
|
|
| pub fn add_css(&mut self, block: &str) { |
| if !block.trim().is_empty() { |
| self.css_blocks.push(block.to_string()); |
| } |
| } |
|
|
| pub fn add_media_query(&mut self, mq: &str) { |
| if !mq.trim().is_empty() { |
| self.media_queries.push(mq.to_string()); |
| } |
| } |
|
|
| pub fn get_css(&self) -> String { |
| self.css_blocks.iter().chain(self.media_queries.iter()).cloned().collect::<Vec<_>>().join("\n\n") |
| } |
|
|
| pub fn add_js(&mut self, block: &str) { |
| if !block.trim().is_empty() { |
| self.js_blocks.push(block.to_string()); |
| } |
| } |
|
|
| pub fn get_js(&self) -> String { |
| self.js_blocks.join("\n\n") |
| } |
|
|
| pub fn add_state_var(&mut self, name: &str, val: &Expr) { |
| self.state_vars.push((name.to_string(), val.clone())); |
| } |
|
|
| pub fn add_global_var(&mut self, name: &str, val: &Expr) { |
| self.global_vars.push((name.to_string(), val.clone())); |
| } |
|
|
| pub fn get_state_vars(&self) -> &[(String, Expr)] { |
| &self.state_vars |
| } |
|
|
| pub fn get_global_vars(&self) -> &[(String, Expr)] { |
| &self.global_vars |
| } |
|
|
| pub fn set_scope(&mut self, name: Option<String>) { |
| self.component_scope = name; |
| } |
|
|
| pub fn get_scope(&self) -> Option<&str> { |
| self.component_scope.as_deref() |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| pub fn reset_page(&mut self) { |
| self.js_blocks.clear(); |
| self.state_vars.clear(); |
| } |
| } |
|
|
| |
| |
| |
|
|
| pub struct CodegenOutput { |
| |
| pub html: String, |
| pub css: String, |
| pub js: String, |
| |
| pub pages: HashMap<String, String>, |
| |
| |
| |
| |
| pub warnings: Vec<String>, |
| } |
|
|
| |
| |
| |
|
|
| pub struct Codegen { |
| pub ctx: CodegenContext, |
| registry: ComponentRegistry, |
| } |
|
|
| impl Codegen { |
| pub fn new(options: CodegenOptions) -> Self { |
| Codegen { ctx: CodegenContext::new(options), registry: ComponentRegistry::new() } |
| } |
|
|
| |
| |
| pub fn generate(&mut self, program: &Program) -> CodegenOutput { |
| let app = &program.app; |
|
|
| for def in &app.components { |
| self.registry.register(def.clone()); |
| } |
| for v in &app.variables { |
| self.ctx.add_global_var(&v.name, &v.value); |
| } |
| self.ctx.add_css(BASE_CSS); |
|
|
| let mut pages: HashMap<String, String> = HashMap::new(); |
| for page in &app.pages { |
| self.ctx.reset_page(); |
| let html = self.gen_page(page); |
| pages.insert(page.route.clone(), html); |
| } |
|
|
| let html = pages.get("/").cloned().unwrap_or_else(|| pages.values().next().cloned().unwrap_or_default()); |
| let js = self.gen_app_js(app); |
| let warnings = self.registry.warnings.clone(); |
|
|
| CodegenOutput { html, css: self.ctx.get_css(), js, pages, warnings } |
| } |
|
|
| |
| |
| |
|
|
| fn gen_page(&mut self, page: &Page) -> String { |
| for s in &page.states { |
| self.ctx.add_state_var(&s.name, &s.value); |
| } |
| if !page.events.is_empty() { |
| let load_js = action::compile_page_load(&page.events); |
| self.ctx.add_js(&load_js); |
| } |
|
|
| let children_html = page |
| .children |
| .iter() |
| .map(|c| self.gen_child(c)) |
| .filter(|s| !s.is_empty()) |
| .collect::<Vec<_>>() |
| .join("\n"); |
|
|
| let bg_style = page |
| .mau_nen |
| .as_ref() |
| .map(|cv| format!("style=\"background-color:{}\"", resolve_page_bg_color(cv))) |
| .unwrap_or_default(); |
|
|
| format!( |
| "<div class=\"vb-page\" data-route=\"{}\" {}>\n{}\n</div>", |
| page.route, |
| bg_style, |
| css::indent2(&children_html) |
| ) |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| |
| pub fn gen_child(&mut self, child: &Child) -> String { |
| match child { |
| Child::StateDecl(s) => { |
| self.ctx.add_state_var(&s.name, &s.value); |
| String::new() |
| } |
| Child::VarDecl(v) => { |
| self.ctx.add_global_var(&v.name, &v.value); |
| String::new() |
| } |
| Child::PageEvent(pe) => { |
| let js = action::compile_page_load(std::slice::from_ref(pe)); |
| self.ctx.add_js(&js); |
| String::new() |
| } |
| Child::If(node) => control::gen_if(node, self), |
| Child::Switch(node) => control::gen_switch(node, self), |
| Child::Loop(node) => control::gen_loop(node, self), |
| Child::Element(el) => element::gen_element(el, self), |
| Child::ComponentCall(call) => { |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| let registry = std::mem::take(&mut self.registry); |
| let (html, warning) = component::gen_component_call(call, ®istry, self); |
| self.registry = registry; |
| if let Some(w) = warning { |
| self.registry.warnings.push(w); |
| } |
| html |
| } |
| } |
| } |
|
|
| fn gen_children_internal(&mut self, children: &[Child]) -> String { |
| children.iter().map(|c| self.gen_child(c)).filter(|s| !s.is_empty()).collect::<Vec<_>>().join("\n") |
| } |
|
|
| |
| |
| |
|
|
| fn gen_app_js(&self, app: &App) -> String { |
| let vars_js = self |
| .ctx |
| .get_global_vars() |
| .iter() |
| .map(|(k, v)| format!(" const {} = {};", k, expr_to_js_default(v))) |
| .collect::<Vec<_>>() |
| .join("\n"); |
|
|
| let component_defs = app |
| .components |
| .iter() |
| .map(component::gen_component_def) |
| .collect::<Vec<_>>() |
| .join("\n\n"); |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| let expr_registry = expr::take_expr_registry(); |
| let expr_registry_json = serde_json::to_string(&expr_registry) |
| .unwrap_or_else(|_| "[]".to_string()); |
|
|
| |
| |
| |
| |
| |
| let action_registry = action::take_action_registry(); |
| let action_registry_json = serde_json::to_string(&action_registry) |
| .unwrap_or_else(|_| "[]".to_string()); |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| const WASM_JS_PATH: &str = "./pkg/vibao_runtime.js"; |
|
|
| let bootstrap_js = format!( |
| r#" |
| // ── WASM Bootstrap (dynamic import — hoạt động trong classic script) ── |
| (async function __vbBoot() {{ |
| try {{ |
| const wasmModule = await import("{wasm_path}"); |
| await wasmModule.default(); // nạp file .wasm đi kèm, chờ WASM sẵn sàng |
| const optsJson = JSON.stringify({{ |
| baseURL: "{base_url}", |
| exprRegistry: {expr_registry_json}, |
| actionRegistry: {action_registry_json} |
| }}); |
| window.__vbRuntime = new wasmModule.VbRuntime(optsJson); // giữ tham chiếu để debug console |
| }} catch (err) {{ |
| console.error("[ViBao] Không khởi động được runtime:", err); |
| }} |
| }})();"#, |
| wasm_path = WASM_JS_PATH, |
| base_url = self.ctx.options.base_url, |
| expr_registry_json = expr_registry_json, |
| action_registry_json = action_registry_json, |
| ); |
|
|
| format!( |
| "// ViBao Generated JS — DO NOT EDIT\n(function() {{\n'use strict';\n\n// ── Global vars ──\n{}\n\n// ── Components ──\n{}\n\n// ── App init ──\n{}\n}})();\n{}", |
| vars_js, |
| component_defs, |
| self.ctx.get_js(), |
| bootstrap_js, |
| ) |
| } |
| } |
|
|
| |
| |
| |
| |
| |
|
|
| impl ElementCodegenHost for Codegen { |
| fn next_id(&mut self, tag: &str) -> String { |
| self.ctx.next_id(tag) |
| } |
|
|
| fn gen_children(&mut self, children: &[Child]) -> String { |
| self.gen_children_internal(children) |
| } |
|
|
| fn add_js(&mut self, code: &str) { |
| self.ctx.add_js(code); |
| } |
|
|
| fn add_css(&mut self, code: &str) { |
| self.ctx.add_css(code); |
| } |
|
|
| fn add_media_query(&mut self, code: &str) { |
| self.ctx.add_media_query(code); |
| } |
|
|
| fn compile_event_handler(&self, event: &vibao_ast::EventNode, id: &str) -> String { |
| action::compile_event_handler(event, id) |
| } |
|
|
| fn compile_hover_animation(&self, id: &str, effect: &str, duration_ms: u32) -> String { |
| action::compile_hover_animation(id, effect, duration_ms) |
| } |
|
|
| fn compile_scroll_animation(&self, id: &str, effect: &str, duration_ms: u32, delay_ms: u32) -> String { |
| action::compile_scroll_animation(id, effect, duration_ms, delay_ms) |
| } |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| pub fn resolve_page_bg_color(cv: &ColorValue) -> String { |
| match cv { |
| ColorValue::Hex(hex) => hex.clone(), |
| ColorValue::Name(name) => resolve_color_name(name), |
| ColorValue::Variable(name) => format!("var(--{})", name.replace('_', "-")), |
| ColorValue::Func { func, args } => { |
| let args_str = args |
| .iter() |
| .map(|a| expr::get_static_value(a)) |
| .collect::<Vec<_>>() |
| .join(", "); |
| format!("{}({})", color_func_name(*func), args_str) |
| } |
| } |
| } |
|
|
| fn color_func_name(func: ColorFuncKind) -> &'static str { |
| match func { |
| ColorFuncKind::TrongSuot => "trong_suot", |
| ColorFuncKind::LamSang => "lam_sang", |
| ColorFuncKind::LamToi => "lam_toi", |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| pub const COLOR_NAME_MAP: [(&str, &str); 14] = [ |
| ("trang", "#FFFFFF"), |
| ("den", "#000000"), |
| ("do", "#E53E3E"), |
| ("xanh", "#3182CE"), |
| ("xanh_la", "#38A169"), |
| ("vang", "#F59E0B"), |
| ("hong", "#D53F8C"), |
| ("tim", "#805AD5"), |
| ("cam", "#DD6B20"), |
| ("xam", "#718096"), |
| ("xam_nhat", "#F7FAFC"), |
| ("xam_dam", "#2D3748"), |
| ("luc", "#25855A"), |
| ("nau", "#7B341E"), |
| ]; |
|
|
| pub fn resolve_color_name(name: &str) -> String { |
| COLOR_NAME_MAP |
| .iter() |
| .find(|(k, _)| *k == name) |
| .map(|(_, v)| v.to_string()) |
| .unwrap_or_else(|| name.to_string()) |
| } |
|
|
| |
| |
| |
|
|
| #[cfg(test)] |
| mod tests { |
| use super::*; |
| use vibao_ast::Pos; |
|
|
| fn p() -> Pos { |
| Pos { line: 1, column: 1 } |
| } |
|
|
| #[test] |
| fn test_resolve_color_name_known() { |
| assert_eq!(resolve_color_name("do"), "#E53E3E"); |
| } |
|
|
| #[test] |
| fn test_resolve_color_name_unknown_passthrough() { |
| assert_eq!(resolve_color_name("mau_la_theo"), "mau_la_theo"); |
| } |
|
|
| #[test] |
| fn test_resolve_page_bg_color_hex() { |
| assert_eq!(resolve_page_bg_color(&ColorValue::Hex("#123456".to_string())), "#123456"); |
| } |
|
|
| #[test] |
| fn test_resolve_page_bg_color_variable() { |
| assert_eq!( |
| resolve_page_bg_color(&ColorValue::Variable("mau_chinh".to_string())), |
| "var(--mau-chinh)" |
| ); |
| } |
|
|
| #[test] |
| fn test_context_next_id_increments() { |
| let mut ctx = CodegenContext::new(CodegenOptions::default()); |
| assert_eq!(ctx.next_id("box"), "vb-box-1"); |
| assert_eq!(ctx.next_id("box"), "vb-box-2"); |
| } |
|
|
| #[test] |
| fn test_context_reset_page_clears_js_but_keeps_id_counter_global() { |
| |
| |
| |
| |
| |
| |
| let mut ctx = CodegenContext::new(CodegenOptions::default()); |
| ctx.next_id("box"); |
| ctx.add_js("some_js();"); |
| ctx.add_global_var("g", &Expr::literal_num(1.0, p())); |
| ctx.reset_page(); |
| assert_eq!(ctx.next_id("box"), "vb-box-2"); |
| assert_eq!(ctx.get_js(), ""); |
| assert_eq!(ctx.get_global_vars().len(), 1); |
| } |
|
|
| #[test] |
| fn test_multi_page_ids_never_collide() { |
| |
| |
| |
| |
| |
| |
| let mut ctx = CodegenContext::new(CodegenOptions::default()); |
| let mut all_ids = std::collections::HashSet::new(); |
|
|
| for _page in 0..3 { |
| for _el in 0..5 { |
| let id = ctx.next_id("box"); |
| assert!(all_ids.insert(id.clone()), "Id bị trùng: {}", id); |
| } |
| ctx.reset_page(); |
| } |
| assert_eq!(all_ids.len(), 15); |
| } |
|
|
| #[test] |
| fn test_generate_empty_program_has_base_css() { |
| let program = Program { |
| app: App { |
| name: "test".to_string(), |
| variables: vec![], |
| themes: vec![], |
| components: vec![], |
| pages: vec![], |
| pos: p(), |
| }, |
| }; |
| let mut codegen = Codegen::new(CodegenOptions::default()); |
| let out = codegen.generate(&program); |
| assert!(out.css.contains("ViBao Base CSS")); |
| } |
| } |
|
|