atom-engine 5.0.2

A component-oriented template engine built on Tera with props, slots, and provide/inject context
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
//! Component system for Atom Engine.
//!
//! This module provides the component infrastructure including:
//! - Component registration and management
//! - Props validation
//! - Slot handling
//! - Component caching
//! - Scoped slots support

use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::Arc;

use indexmap::IndexMap;
use serde_json::Value;

use crate::error::Result;

/// Computes a hash for component props.
///
/// Used for component caching to generate cache keys.
pub fn compute_props_hash(props: &Value) -> u64 {
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    let json_str = serde_json::to_string(props).unwrap_or_default();
    json_str.hash(&mut hasher);
    hasher.finish()
}

/// Computes a cache key from component path and props hash.
pub fn compute_cache_key(path: &str, props_hash: u64) -> u64 {
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    path.hash(&mut hasher);
    props_hash.hash(&mut hasher);
    hasher.finish()
}

/// The type of a component prop.
///
/// Used for props validation to ensure type safety.
#[derive(Debug, Clone, PartialEq)]
pub enum PropType {
    String,
    Number,
    Boolean,
    Array,
    Object,
    Any,
}

impl PropType {
    /// Creates a PropType from a string representation.
    ///
    /// Supported types: "string", "number", "boolean", "array", "object", "any"
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "string" => PropType::String,
            "number" => PropType::Number,
            "boolean" => PropType::Boolean,
            "array" => PropType::Array,
            "object" => PropType::Object,
            _ => PropType::Any,
        }
    }

    /// Checks if a value matches this prop type.
    pub fn matches(&self, value: &Value) -> bool {
        match self {
            PropType::Any => true,
            PropType::String => value.is_string(),
            PropType::Number => value.is_number(),
            PropType::Boolean => value.is_boolean(),
            PropType::Array => value.is_array(),
            PropType::Object => value.is_object(),
        }
    }
}

/// Definition of a component prop.
#[derive(Debug, Clone)]
pub struct PropDef {
    pub name: String,
    pub prop_type: PropType,
    pub required: bool,
    pub default: Option<Value>,
}

impl PropDef {
    /// Validates a prop value against this definition.
    ///
    /// # Errors
    ///
    /// Returns an error if the value is null but required, or if the type doesn't match.
    pub fn validate(&self, value: &Value) -> std::result::Result<(), String> {
        if value.is_null() && self.required {
            return Err(format!("Required prop '{}' is null", self.name));
        }
        if !self.prop_type.matches(value) {
            return Err(format!(
                "Prop '{}' type mismatch: expected {:?}, got {}",
                self.name,
                self.prop_type,
                match value {
                    Value::Null => "null",
                    Value::Bool(_) => "boolean",
                    Value::Number(_) => "number",
                    Value::String(_) => "string",
                    Value::Array(_) => "array",
                    Value::Object(_) => "object",
                }
            ));
        }
        Ok(())
    }
}

/// A registered component with its template and prop definitions.
#[derive(Debug, Clone)]
pub struct Component {
    pub path: String,
    pub props: Vec<PropDef>,
    pub template: String,
    pub slots: Vec<String>,
    pub optional_slots: Vec<String>,
    pub scoped_slots: Vec<ScopedSlotDef>,
}

/// Definition of a scoped slot.
#[derive(Debug, Clone)]
pub struct ScopedSlotDef {
    pub name: String,
    pub props: Vec<String>,
}

/// Data for slot rendering.
#[derive(Debug, Clone, Default)]
pub struct SlotData {
    pub fills: IndexMap<String, String>,
    pub default: Option<String>,
    pub scoped_data: HashMap<String, Value>,
}

/// Runtime component renderer that manages slot content and stack buffers.
///
/// Used during template rendering to accumulate and manage component content.
#[derive(Clone, Default)]
pub struct ComponentRenderer {
    stack_buffers: HashMap<String, Vec<String>>,
    slot_data: HashMap<String, SlotData>,
    once_rendered: std::collections::HashSet<u64>,
}

impl ComponentRenderer {
    /// Creates a new ComponentRenderer.
    pub fn new() -> Self {
        ComponentRenderer {
            stack_buffers: HashMap::new(),
            slot_data: HashMap::new(),
            once_rendered: std::collections::HashSet::new(),
        }
    }

    /// Pushes content onto a stack buffer.
    pub fn push(&mut self, name: &str, content: String) {
        self.stack_buffers
            .entry(name.to_string())
            .or_default()
            .push(content);
    }

    /// Prepends content to a stack buffer.
    pub fn prepend(&mut self, name: &str, content: String) {
        self.stack_buffers
            .entry(name.to_string())
            .or_default()
            .insert(0, content);
    }

    /// Drains and returns all content from a stack buffer, removing it.
    pub fn drain(&mut self, name: &str) -> String {
        self.stack_buffers
            .remove(name)
            .map(|v| v.join("\n"))
            .unwrap_or_default()
    }

    /// Peeks at the content of a stack buffer without removing it.
    pub fn peek(&self, name: &str) -> Option<String> {
        self.stack_buffers.get(name).map(|v| v.join("\n"))
    }

    /// Sets the fill content for a slot.
    pub fn set_slot_fill(&mut self, slot_name: &str, content: String) {
        let slot_name = slot_name.trim_start_matches('$').to_string();
        let slot = self.slot_data.entry(slot_name.clone()).or_default();
        if slot_name == "default" || slot_name.is_empty() {
            slot.default = Some(content);
        } else {
            slot.fills.insert(slot_name, content);
        }
    }

    /// Gets the fill content for a slot.
    pub fn get_slot(&self, name: &str) -> Option<String> {
        let name = name.trim_start_matches('$').to_string();
        if name == "default" || name.is_empty() {
            self.slot_data
                .get("default")
                .and_then(|s| s.default.clone())
        } else {
            self.slot_data
                .get(&name)
                .and_then(|s| s.fills.get(&name).cloned())
        }
    }

    /// Checks if a slot has fill content.
    pub fn has_slot(&self, name: &str) -> bool {
        let name = name.trim_start_matches('$').to_string();
        if name == "default" || name.is_empty() {
            self.slot_data
                .get("default")
                .map(|s| s.default.is_some())
                .unwrap_or(false)
        } else {
            self.slot_data
                .get(&name)
                .map(|s| s.fills.contains_key(&name))
                .unwrap_or(false)
        }
    }

    /// Sets scoped data for a slot.
    pub fn set_scoped_data(&mut self, slot_name: &str, key: &str, value: Value) {
        let slot_name = slot_name.trim_start_matches('$').to_string();
        let slot = self.slot_data.entry(slot_name).or_default();
        slot.scoped_data.insert(key.to_string(), value);
    }

    /// Gets scoped data for a slot.
    pub fn get_scoped_data(&self, slot_name: &str) -> Option<HashMap<String, Value>> {
        let name = slot_name.trim_start_matches('$').to_string();
        self.slot_data.get(&name).map(|s| s.scoped_data.clone())
    }

    /// Returns true if the key has not been rendered yet, then marks it as rendered.
    ///
    /// Used for the `once` directive to ensure content renders only once.
    pub fn once(&mut self, key: u64) -> bool {
        if self.once_rendered.contains(&key) {
            return false;
        }
        self.once_rendered.insert(key);
        true
    }

    /// Resets the renderer, clearing all buffers and slot data.
    pub fn reset(&mut self) {
        self.stack_buffers.clear();
        self.slot_data.clear();
    }
}

/// Registry for managing component templates.
#[derive(Clone, Default)]
pub struct ComponentRegistry {
    components: HashMap<String, Component>,
    cache: Arc<std::sync::RwLock<ComponentCache>>,
    cache_enabled: bool,
}

/// Cache for rendered components.
#[derive(Default)]
pub struct ComponentCache {
    entries: HashMap<u64, CachedRender>,
}

/// A cached component render.
#[derive(Clone)]
pub struct CachedRender {
    pub html: String,
    #[allow(dead_code)]
    pub props_hash: u64,
}

impl ComponentCache {
    /// Creates a new empty ComponentCache.
    pub fn new() -> Self {
        ComponentCache {
            entries: HashMap::new(),
        }
    }

    /// Gets a cached render by key.
    pub fn get(&self, key: &u64) -> Option<String> {
        self.entries.get(key).map(|c| c.html.clone())
    }

    /// Inserts a cached render.
    pub fn insert(&mut self, key: u64, html: String, props_hash: u64) {
        self.entries.insert(key, CachedRender { html, props_hash });
    }

    /// Clears all cached entries.
    pub fn clear(&mut self) {
        self.entries.clear();
    }

    /// Returns the number of cached entries.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns true if the cache is empty.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

impl ComponentRegistry {
    /// Creates a new ComponentRegistry.
    pub fn new() -> Self {
        ComponentRegistry {
            components: HashMap::new(),
            cache: Arc::new(std::sync::RwLock::new(ComponentCache::new())),
            cache_enabled: false,
        }
    }

    /// Registers a component with its template.
    pub fn register(&mut self, path: &str, template: &str) -> Result<()> {
        let props = Self::parse_props(template);
        let (slots, optional_slots) = Self::parse_slots(template);
        let scoped_slots = Self::parse_scoped_slots(template);

        self.components.insert(
            path.to_string(),
            Component {
                path: path.to_string(),
                props,
                template: template.to_string(),
                slots,
                optional_slots,
                scoped_slots,
            },
        );

        Ok(())
    }

    /// Gets a component by path.
    pub fn get(&self, path: &str) -> Option<&Component> {
        self.components.get(path)
    }

    /// Resolves a tag name to a component path.
    ///
    /// Tries multiple variations: exact match, with "components/" prefix,
    /// with ".html" extension, and nested paths.
    pub fn resolve_tag(&self, tag: &str) -> Option<String> {
        if self.components.contains_key(tag) {
            return Some(tag.to_string());
        }

        let with_prefix = format!("components/{}", tag);
        if self.components.contains_key(&with_prefix) {
            return Some(with_prefix);
        }

        let with_ext = format!("{}.html", tag);
        if self.components.contains_key(&with_ext) {
            return Some(with_ext);
        }

        let parts: Vec<&str> = tag.split('.').collect();
        if parts.len() >= 2 {
            let nested = format!("components/{}.html", parts.join("/"));
            if self.components.contains_key(&nested) {
                return Some(nested);
            }
        }

        None
    }

    /// Lists all registered component paths.
    pub fn list_components(&self) -> Vec<String> {
        self.components.keys().cloned().collect()
    }

    /// Validates props against a component's prop definitions.
    ///
    /// # Errors
    ///
    /// Returns an error if a required prop is missing or a prop has an invalid type.
    pub fn validate_props(
        &self,
        path: &str,
        provided: &Value,
    ) -> std::result::Result<HashMap<String, Value>, String> {
        let component = self
            .components
            .get(path)
            .ok_or_else(|| format!("Component '{}' not found", path))?;

        let mut result = HashMap::new();
        let provided_obj = provided.as_object().ok_or("Props must be an object")?;

        for prop_def in &component.props {
            if let Some(value) = provided_obj.get(&prop_def.name) {
                prop_def.validate(value)?;
                result.insert(prop_def.name.clone(), value.clone());
            } else if let Some(default) = &prop_def.default {
                result.insert(prop_def.name.clone(), default.clone());
            } else if prop_def.required {
                return Err(format!("Required prop '{}' not provided", prop_def.name));
            }
        }

        Ok(result)
    }

    /// Enables or disables component caching.
    pub fn enable_cache(&mut self, enabled: bool) {
        self.cache_enabled = enabled;
    }

    /// Returns whether caching is enabled.
    pub fn is_cache_enabled(&self) -> bool {
        self.cache_enabled
    }

    /// Gets a cached render.
    pub fn get_cached(&self, key: u64) -> Option<String> {
        if !self.cache_enabled {
            return None;
        }
        self.cache.read().ok()?.get(&key)
    }

    /// Stores a render in the cache.
    pub fn set_cached(&self, key: u64, html: String, props_hash: u64) {
        if !self.cache_enabled {
            return;
        }
        if let Ok(mut cache) = self.cache.write() {
            cache.insert(key, html, props_hash);
        }
    }

    /// Clears the component cache.
    pub fn clear_cache(&self) {
        if let Ok(mut cache) = self.cache.write() {
            cache.clear();
        }
    }

    /// Returns the number of cached entries.
    pub fn cache_len(&self) -> usize {
        self.cache.read().map(|c| c.len()).unwrap_or(0)
    }

    fn parse_scoped_slots(template: &str) -> Vec<ScopedSlotDef> {
        let mut scoped_slots = Vec::new();

        if let Some(start) = template.find("{%-- atom:") {
            if let Some(end) = template[start..].find("--%}") {
                let atom_block = &template[start + 11..start + end];
                if let Some(slots_start) = atom_block.find("@scoped_slots(") {
                    let slots_end = atom_block[slots_start..]
                        .find(')')
                        .map(|i| slots_start + i + 1);
                    if let Some(end_idx) = slots_end {
                        let slots_str = &atom_block[slots_start + 14..end_idx];
                        for part in slots_str.split(',') {
                            let part = part.trim();
                            if part.is_empty() {
                                continue;
                            }
                            let parts: Vec<&str> = part.split(':').collect();
                            let name = parts[0].trim().to_string();
                            let props = if parts.len() > 1 {
                                parts[1]
                                    .trim()
                                    .split(',')
                                    .map(|s| s.trim().to_string())
                                    .collect()
                            } else {
                                vec![]
                            };
                            scoped_slots.push(ScopedSlotDef { name, props });
                        }
                    }
                }
            }
        }

        scoped_slots
    }

    fn parse_props(template: &str) -> Vec<PropDef> {
        let mut props = Vec::new();

        if let Some(start) = template.find("{%-- atom:") {
            if let Some(end) = template[start..].find("--%}") {
                let atom_block = &template[start + 11..start + end];
                if let Some(props_start) = atom_block.find("@props(") {
                    let props_end = atom_block[props_start..]
                        .find(')')
                        .map(|i| props_start + i + 1);
                    if let Some(end_idx) = props_end {
                        let props_str = &atom_block[props_start + 7..end_idx];
                        props = Self::parse_props_string(props_str);
                    }
                }
            }
        }

        props
    }

    fn parse_props_string(s: &str) -> Vec<PropDef> {
        let mut props = Vec::new();
        let s = s.trim();
        let s = s.trim_start_matches('{').trim_end_matches('}');

        for part in s.split(',') {
            let part = part.trim();
            if part.is_empty() {
                continue;
            }

            let parts: Vec<&str> = part.split(':').collect();
            if parts.is_empty() {
                continue;
            }

            let mut name = parts[0].trim().to_string();
            let prop_type = if parts.len() > 1 {
                PropType::from_str(parts[1].trim())
            } else {
                PropType::Any
            };

            let optional = name.ends_with('?');
            if optional {
                name = name.trim_end_matches('?').to_string();
            }

            let (required, default) = if let Some(eq_pos) = name.find('=') {
                let default_str = &name[eq_pos + 1..];
                let default = serde_json::Value::from(default_str.trim());
                (false, Some(default))
            } else {
                (true, None)
            };

            name = name.split('=').next().unwrap_or(&name).trim().to_string();

            let required = required && !optional;

            props.push(PropDef {
                name,
                prop_type,
                required,
                default,
            });
        }

        props
    }

    fn parse_slots(template: &str) -> (Vec<String>, Vec<String>) {
        let mut slots = Vec::new();
        let mut optional_slots = Vec::new();

        let mut search = template;
        while let Some(start) = search.find("slot_") {
            search = &search[start + 5..];
            if let Some(end) = search.find("()") {
                let raw_name = &search[..end];
                if raw_name.is_empty() {
                    continue;
                }
                let is_optional = raw_name.ends_with('?');
                let name = if is_optional {
                    raw_name.trim_end_matches('?').to_string()
                } else {
                    raw_name.to_string()
                };

                if is_optional {
                    if !optional_slots.contains(&name) {
                        optional_slots.push(name);
                    }
                } else if !slots.contains(&name) {
                    slots.push(name);
                }
            }
        }

        (slots, optional_slots)
    }
}