webfluent 0.4.0-alpha

The Web-First Language — compiles to HTML, CSS, JavaScript, and PDF. 50+ built-in components, reactivity, routing, i18n, SSG, and template engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
use std::collections::HashMap;
use crate::parser::ast::*;
use crate::config::ProjectConfig;

/// Renders a page to static HTML for SSG.
pub fn render_page_html(
    page: &PageDecl,
    config: &ProjectConfig,
    app_body: Option<&[Statement]>,
    translations: &HashMap<String, HashMap<String, String>>,
) -> String {
    let title = page.title.as_deref().unwrap_or(&config.name);
    let lang = if config.meta.lang.is_empty() { "en" } else { &config.meta.lang };

    let default_locale = config.i18n.as_ref()
        .map(|i| i.default_locale.as_str())
        .unwrap_or("en");

    let default_messages = translations.get(default_locale)
        .cloned()
        .unwrap_or_default();

    // Calculate relative base path from page route depth
    let route = page.path.trim_start_matches('/');
    let base_path = if route.is_empty() || route == "/" {
        ".".to_string()
    } else {
        let depth = route.split('/').filter(|s| !s.is_empty()).count();
        (0..depth).map(|_| "..").collect::<Vec<_>>().join("/")
    };

    let link_base = config.build.base_path.clone();

    let mut ctx = SsgContext {
        default_messages,
        indent: 2,
        base_path,
        link_base,
    };

    // Render app shell (navbar, etc.) if available
    let mut body_html = String::new();
    if let Some(app_stmts) = app_body {
        render_app_shell_ssg(app_stmts, &page.body, &mut ctx, &mut body_html);
    } else {
        body_html = render_statements(&page.body, &mut ctx);
    }

    let description_meta = if config.meta.description.is_empty() {
        String::new()
    } else {
        format!("    <meta name=\"description\" content=\"{}\">\n", config.meta.description)
    };

    // Calculate relative path prefix based on page route depth
    let route = page.path.trim_start_matches('/');
    let base = if route.is_empty() || route == "/" {
        ".".to_string()
    } else {
        let depth = route.split('/').filter(|s| !s.is_empty()).count();
        (0..depth).map(|_| "..").collect::<Vec<_>>().join("/")
    };

    format!(
        r#"<!DOCTYPE html>
<html lang="{}">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{}</title>
{}    <link rel="stylesheet" href="{}/styles.css">
</head>
<body>
    <div id="app">
{}    </div>
    <script src="{}/app.js"></script>
</body>
</html>"#,
        lang, title, description_meta, base, body_html, base
    )
}

struct SsgContext {
    default_messages: HashMap<String, String>,
    indent: usize,
    base_path: String, // Relative path to root for assets (e.g., ".." for /about)
    link_base: String, // Config base_path for links (e.g., "/WebFluent")
}

impl SsgContext {
    fn indent_str(&self) -> String {
        "    ".repeat(self.indent)
    }
}

/// Recursively render the App shell for SSG, handling Router nested inside layout wrappers
fn render_app_shell_ssg(
    stmts: &[Statement],
    page_body: &[Statement],
    ctx: &mut SsgContext,
    html: &mut String,
) {
    for stmt in stmts {
        if let Statement::UIElement(ui) = stmt {
            let name = match &ui.component {
                ComponentRef::BuiltIn(n) => n.as_str(),
                _ => "",
            };
            if name == "Router" {
                // Replace Router with page content
                html.push_str(&render_statements(page_body, ctx));
            } else if stmt_contains_router(stmt) {
                // This is a layout wrapper (like Row) containing the Router
                // Render the wrapper tag with children, substituting the Router
                let (tag, class) = builtin_to_html_tag(name);
                let indent = ctx.indent_str();
                html.push_str(&format!("{}<{} class=\"{}\">\n", indent, tag, class));
                ctx.indent += 1;
                render_app_shell_ssg(&ui.children, page_body, ctx, html);
                ctx.indent -= 1;
                html.push_str(&format!("{}</{}>\n", indent, tag));
            } else {
                html.push_str(&render_ui_element(ui, ctx));
            }
        }
    }
}

fn stmt_contains_router(stmt: &Statement) -> bool {
    if let Statement::UIElement(ui) = stmt {
        if matches!(&ui.component, ComponentRef::BuiltIn(n) if n == "Router") {
            return true;
        }
        for child in &ui.children {
            if stmt_contains_router(child) {
                return true;
            }
        }
    }
    false
}

fn render_statements(stmts: &[Statement], ctx: &mut SsgContext) -> String {
    let mut html = String::new();
    for stmt in stmts {
        match stmt {
            Statement::UIElement(ui) => html.push_str(&render_ui_element(ui, ctx)),
            Statement::If(_) => {
                // Dynamic — emit placeholder comment
                html.push_str(&format!("{}<!--wf-if-->\n", ctx.indent_str()));
            }
            Statement::For(_) => {
                html.push_str(&format!("{}<!--wf-for-->\n", ctx.indent_str()));
            }
            Statement::Show(show) => {
                // Render content but hidden
                let inner = render_statements(&show.body, ctx);
                html.push_str(&format!(
                    "{}<div style=\"display:none\">\n{}{}</div>\n",
                    ctx.indent_str(), inner, ctx.indent_str()
                ));
            }
            Statement::Fetch(fetch) => {
                // Render loading block if present
                if let Some(loading) = &fetch.loading_block {
                    html.push_str(&render_statements(loading, ctx));
                } else {
                    html.push_str(&format!("{}<!--wf-fetch-->\n", ctx.indent_str()));
                }
            }
            // Skip state, derived, effect, action, use, events, navigate, log, animate
            _ => {}
        }
    }
    html
}

fn render_ui_element(ui: &UIElement, ctx: &mut SsgContext) -> String {
    match &ui.component {
        ComponentRef::BuiltIn(name) => render_builtin(name, ui, ctx),
        ComponentRef::SubComponent(parent, sub) => {
            let class = format!("wf-{}__{}",
                parent.to_lowercase(),
                camel_to_kebab(sub)
            );
            let tag = match sub.as_str() {
                "Item" => "li",
                _ => "div",
            };
            render_tag(tag, &class, ui, ctx)
        }
        ComponentRef::UserDefined(_name) => {
            // Can't pre-render user components without expanding them
            // Emit a placeholder div
            let indent = ctx.indent_str();
            format!("{}<!--wf-component-->\n", indent)
        }
    }
}

fn render_builtin(name: &str, ui: &UIElement, ctx: &mut SsgContext) -> String {
    let (tag, base_class) = builtin_to_html_tag(name);

    // Build class string
    let mut classes = vec![base_class.to_string()];
    for m in &ui.modifiers {
        let mc = modifier_to_css_class(base_class, m);
        if !mc.is_empty() {
            classes.push(mc);
        }
    }
    let class_str = classes.iter().filter(|c| !c.is_empty()).cloned().collect::<Vec<_>>().join(" ");

    // Special handling for certain components
    match name {
        "Spacer" => {
            return format!("{}<div class=\"{}\"></div>\n", ctx.indent_str(), class_str);
        }
        "Divider" => {
            return format!("{}<hr class=\"{}\">\n", ctx.indent_str(), class_str);
        }
        "Spinner" => {
            return format!("{}<div class=\"{}\"></div>\n", ctx.indent_str(), class_str);
        }
        "Children" | "_StyleBlock" | "Router" | "Route" => {
            return String::new();
        }
        "Toast" => return String::new(), // Imperative, no SSG output
        _ => {}
    }

    // Extract attributes and text content
    let mut attrs = Vec::new();
    let mut text_content: Option<String> = None;

    if !class_str.is_empty() {
        attrs.push(format!("class=\"{}\"", class_str));
    }

    for arg in &ui.args {
        match arg {
            Arg::Named(key, val) => {
                match key.as_str() {
                    "src" | "alt" | "href" | "placeholder" | "type" | "min" | "max" |
                    "step" | "accept" | "role" | "value" => {
                        if let Some(s) = expr_to_static_string(val) {
                            attrs.push(format!("{}=\"{}\"", key, html_escape(&s)));
                        }
                    }
                    "to" => {
                        if let Some(s) = expr_to_static_string(val) {
                            // Use config base_path for absolute links
                            let href = if ctx.link_base.is_empty() {
                                s.clone()
                            } else {
                                format!("{}{}", ctx.link_base, s)
                            };
                            attrs.push(format!("href=\"{}\"", html_escape(&href)));
                        }
                    }
                    "required" => attrs.push("required".to_string()),
                    "disabled" => attrs.push("disabled".to_string()),
                    "controls" => attrs.push("controls".to_string()),
                    "title" => {
                        if let Some(s) = expr_to_static_string(val) {
                            attrs.push(format!("title=\"{}\"", html_escape(&s)));
                        }
                    }
                    "label" => {
                        // For checkbox/radio/switch/slider, the label is visible text
                        if let Some(s) = expr_to_static_string(val) {
                            text_content = Some(s);
                        }
                    }
                    "columns" => {
                        if let Expr::NumberLiteral(n) = val {
                            attrs.push(format!("style=\"grid-template-columns: repeat({}, 1fr)\"", *n as i32));
                        }
                    }
                    "visible" | "bind" | "checked" | "icon" | "span" |
                    "gap" | "align" | "justify" => {} // Skip runtime-only attrs
                    _ => {}
                }
            }
            Arg::Positional(expr) => {
                if text_content.is_none() {
                    text_content = resolve_text(expr, &ctx.default_messages);
                }
            }
        }
    }

    // Handle input type from modifiers
    for m in &ui.modifiers {
        match m.as_str() {
            "text" | "email" | "password" | "number" | "search" | "tel" | "url" |
            "date" | "time" | "color" => {
                let t = if m == "datetime" { "datetime-local" } else { m.as_str() };
                attrs.push(format!("type=\"{}\"", t));
            }
            "submit" | "reset" => attrs.push(format!("type=\"{}\"", m)),
            _ => {}
        }
    }

    // Heading tag override based on modifier
    let actual_tag = if name == "Heading" {
        heading_tag(&ui.modifiers)
    } else {
        tag
    };

    let indent = ctx.indent_str();
    let attrs_str = if attrs.is_empty() {
        String::new()
    } else {
        format!(" {}", attrs.join(" "))
    };

    // Self-closing tags
    if matches!(actual_tag, "input" | "img" | "hr" | "br") {
        return format!("{}<{}{}>\n", indent, actual_tag, attrs_str);
    }

    // Has children?
    let has_children = !ui.children.is_empty();
    let has_text = text_content.is_some();

    if !has_children && !has_text {
        return format!("{}<{}{}></{}>​\n", indent, actual_tag, attrs_str, actual_tag);
    }

    let mut result = format!("{}<{}{}>\n", indent, actual_tag, attrs_str);

    if let Some(text) = &text_content {
        // Inline text
        if !has_children {
            return format!("{}<{}{}>{}</{}>​\n", indent, actual_tag, attrs_str, html_escape(text), actual_tag);
        }
        result.push_str(&format!("{}    {}\n", indent, html_escape(text)));
    }

    ctx.indent += 1;
    result.push_str(&render_statements(&ui.children, ctx));
    ctx.indent -= 1;

    result.push_str(&format!("{}</{}>​\n", indent, actual_tag));
    result
}

fn render_tag(tag: &str, class: &str, ui: &UIElement, ctx: &mut SsgContext) -> String {
    let indent = ctx.indent_str();
    let mut result = format!("{}<{} class=\"{}\">\n", indent, tag, class);
    ctx.indent += 1;
    result.push_str(&render_statements(&ui.children, ctx));
    ctx.indent -= 1;
    result.push_str(&format!("{}</{}>​\n", indent, tag));
    result
}

/// Try to resolve an expression to a static string.
fn expr_to_static_string(expr: &Expr) -> Option<String> {
    match expr {
        Expr::StringLiteral(s) => Some(s.clone()),
        Expr::NumberLiteral(n) => Some(format!("{}", n)),
        Expr::BoolLiteral(b) => Some(format!("{}", b)),
        _ => None, // Dynamic — can't resolve
    }
}

/// Resolve text content, including i18n t() calls.
fn resolve_text(expr: &Expr, messages: &HashMap<String, String>) -> Option<String> {
    match expr {
        Expr::StringLiteral(s) => Some(s.clone()),
        Expr::NumberLiteral(n) => {
            if *n == (*n as i64) as f64 {
                Some(format!("{}", *n as i64))
            } else {
                Some(format!("{}", n))
            }
        }
        Expr::BoolLiteral(b) => Some(format!("{}", b)),
        Expr::FunctionCall(name, args) if name == "t" => {
            // i18n: resolve from default locale
            if let Some(Expr::StringLiteral(key)) = args.first() {
                messages.get(key).cloned().or_else(|| Some(key.clone()))
            } else {
                None
            }
        }
        _ => None, // Dynamic expression — leave empty for client
    }
}

fn heading_tag(modifiers: &[String]) -> &'static str {
    for m in modifiers {
        match m.as_str() {
            "h1" => return "h1",
            "h2" => return "h2",
            "h3" => return "h3",
            "h4" => return "h4",
            "h5" => return "h5",
            "h6" => return "h6",
            _ => {}
        }
    }
    "h2"
}

fn html_escape(s: &str) -> String {
    s.replace('&', "&amp;")
     .replace('<', "&lt;")
     .replace('>', "&gt;")
     .replace('"', "&quot;")
     .replace('\u{FFFE}', "{")
     .replace('\u{FFFF}', "}")
}

fn builtin_to_html_tag(name: &str) -> (&'static str, &'static str) {
    match name {
        "Container" => ("div", "wf-container"),
        "Row" => ("div", "wf-row"),
        "Column" => ("div", "wf-col"),
        "Grid" => ("div", "wf-grid"),
        "Stack" => ("div", "wf-stack"),
        "Spacer" => ("div", "wf-spacer"),
        "Divider" => ("hr", "wf-divider"),
        "Navbar" => ("nav", "wf-navbar"),
        "Sidebar" => ("aside", "wf-sidebar"),
        "Breadcrumb" => ("nav", "wf-breadcrumb"),
        "Link" => ("a", "wf-link"),
        "Menu" => ("div", "wf-menu"),
        "Tabs" => ("div", "wf-tabs"),
        "TabPage" => ("div", "wf-tab-page"),
        "Card" => ("div", "wf-card"),
        "Table" => ("table", "wf-table"),
        "Thead" => ("thead", ""),
        "Tbody" => ("tbody", ""),
        "Trow" => ("tr", ""),
        "Tcell" => ("td", ""),
        "List" => ("ul", "wf-list"),
        "Badge" => ("span", "wf-badge"),
        "Avatar" => ("div", "wf-avatar"),
        "Tooltip" => ("div", "wf-tooltip"),
        "Tag" => ("span", "wf-tag"),
        "Input" => ("input", "wf-input"),
        "Select" => ("select", "wf-select"),
        "Option" => ("option", ""),
        "Checkbox" => ("label", "wf-checkbox"),
        "Radio" => ("label", "wf-radio"),
        "Switch" => ("label", "wf-switch"),
        "Slider" => ("input", "wf-slider"),
        "DatePicker" => ("input", "wf-datepicker"),
        "FileUpload" => ("input", "wf-file-upload"),
        "Form" => ("form", "wf-form"),
        "Alert" => ("div", "wf-alert"),
        "Toast" => ("div", "wf-toast"),
        "Modal" => ("div", "wf-modal"),
        "Dialog" => ("div", "wf-dialog"),
        "Spinner" => ("div", "wf-spinner"),
        "Progress" => ("progress", "wf-progress"),
        "Skeleton" => ("div", "wf-skeleton"),
        "Button" => ("button", "wf-btn"),
        "IconButton" => ("button", "wf-icon-btn"),
        "ButtonGroup" => ("div", "wf-btn-group"),
        "Dropdown" => ("div", "wf-dropdown"),
        "Image" => ("img", "wf-image"),
        "Video" => ("video", "wf-video"),
        "Icon" => ("i", "wf-icon"),
        "Carousel" => ("div", "wf-carousel"),
        "Text" => ("p", "wf-text"),
        "Heading" => ("h2", "wf-heading"),
        "Code" => ("code", "wf-code"),
        "Blockquote" => ("blockquote", "wf-blockquote"),
        _ => ("div", ""),
    }
}

fn modifier_to_css_class(base_class: &str, modifier: &str) -> String {
    match modifier {
        "small" => format!("{}--small", base_class),
        "medium" => String::new(),
        "large" => format!("{}--large", base_class),
        "primary" => format!("{}--primary", base_class),
        "secondary" => format!("{}--secondary", base_class),
        "success" => format!("{}--success", base_class),
        "danger" => format!("{}--danger", base_class),
        "warning" => format!("{}--warning", base_class),
        "info" => format!("{}--info", base_class),
        "rounded" => format!("{}--rounded", base_class),
        "pill" => format!("{}--pill", base_class),
        "flat" => format!("{}--flat", base_class),
        "elevated" => format!("{}--elevated", base_class),
        "outlined" => format!("{}--outlined", base_class),
        "full" => format!("{}--full", base_class),
        "bold" => "wf-text--bold".to_string(),
        "italic" => "wf-text--italic".to_string(),
        "center" => "wf-text--center".to_string(),
        "heading" => "wf-text--heading".to_string(),
        "subtitle" => "wf-text--subtitle".to_string(),
        "muted" => "wf-text--muted".to_string(),
        "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => format!("wf-heading--{}", modifier),
        "dismissible" => format!("{}--dismissible", base_class),
        "fluid" => format!("{}--fluid", base_class),
        "fadeIn" | "fadeOut" | "slideUp" | "slideDown" | "slideLeft" | "slideRight" |
        "scaleIn" | "scaleOut" | "bounce" | "shake" | "pulse" | "spin" => {
            format!("wf-animate-{}", modifier)
        }
        "fast" => "wf-animate--fast".to_string(),
        "slow" => "wf-animate--slow".to_string(),
        _ => String::new(),
    }
}

fn camel_to_kebab(s: &str) -> String {
    let mut result = String::new();
    for (i, ch) in s.chars().enumerate() {
        if ch.is_uppercase() && i > 0 {
            result.push('-');
        }
        result.push(ch.to_lowercase().next().unwrap());
    }
    result
}