hypen-engine 0.4.952

A Rust implementation of the Hypen 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
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
//! Pure item-binding substitution for list iteration.
//!
//! Given an [`Element`] or [`IRNode`] and an item value from a list,
//! produce a new element/node with `@{item.x}` bindings replaced by
//! concrete values.  These functions are pure transformations — they
//! never touch the [`InstanceTree`], [`Patch`] list, or
//! [`DependencyGraph`].

use crate::ir::{ConditionalBranch, Element, IRNode, Props, Value};
use crate::reactive::Binding;

// ---------------------------------------------------------------------------
// String-level helpers
// ---------------------------------------------------------------------------

/// Navigate a nested path in a JSON value (e.g., "images.0" or "category.name")
/// Supports both object keys and array indices
pub(crate) fn navigate_item_path<'a>(
    item: &'a serde_json::Value,
    path: &str,
) -> Option<&'a serde_json::Value> {
    let mut current = item;

    for segment in path.split('.') {
        // Try to parse as array index first
        if let Ok(index) = segment.parse::<usize>() {
            current = current.get(index)?;
        } else {
            // Otherwise treat as object key
            current = current.get(segment)?;
        }
    }

    Some(current)
}

/// A replacement to be applied: (start_index, end_index, replacement_string)
#[derive(Debug)]
pub(super) struct Replacement {
    pub start: usize,
    pub end: usize,
    pub text: String,
}

/// Apply all collected replacements to a string in a single pass.
/// Builds result by copying segments between replacements - true O(n + m) complexity.
pub(super) fn apply_replacements(s: &str, mut replacements: Vec<Replacement>) -> String {
    if replacements.is_empty() {
        return s.to_string();
    }

    // Sort by start position ascending
    replacements.sort_by(|a, b| a.start.cmp(&b.start));

    // Filter invalid replacements and calculate result size
    let valid_replacements: Vec<_> = replacements
        .into_iter()
        .filter(|r| r.start <= s.len() && r.end <= s.len() && r.start <= r.end)
        .collect();

    if valid_replacements.is_empty() {
        return s.to_string();
    }

    // Calculate total size: original - removed + added
    let removed: usize = valid_replacements.iter().map(|r| r.end - r.start).sum();
    let added: usize = valid_replacements.iter().map(|r| r.text.len()).sum();
    let capacity = s.len() - removed + added;

    let mut result = String::with_capacity(capacity);
    let mut pos = 0;

    for r in valid_replacements {
        // Push the segment before this replacement
        if r.start > pos {
            result.push_str(&s[pos..r.start]);
        }
        // Push the replacement text
        result.push_str(&r.text);
        pos = r.end;
    }

    // Push remaining segment after last replacement
    if pos < s.len() {
        result.push_str(&s[pos..]);
    }

    result
}

/// Find the end of a path (valid identifier chars: alphanumeric, _, and . for nesting)
fn find_path_end(s: &str, start: usize) -> usize {
    let substring = &s[start..];
    let mut end = start;
    let mut char_iter = substring.char_indices().peekable();

    while let Some((byte_offset, ch)) = char_iter.next() {
        if ch.is_alphanumeric() || ch == '_' {
            end = start + byte_offset + ch.len_utf8();
        } else if ch == '.' {
            // Dot is valid only if followed by alphanumeric or underscore
            if let Some(&(_, next)) = char_iter.peek() {
                if next.is_alphanumeric() || next == '_' {
                    end = start + byte_offset + ch.len_utf8();
                    continue;
                }
            }
            break;
        } else {
            break;
        }
    }

    end
}

/// Format a JSON value for replacement in expressions
fn format_value_for_replacement(val: &serde_json::Value, quote_strings: bool) -> String {
    match val {
        serde_json::Value::String(s) => {
            if quote_strings {
                format!("'{}'", s)
            } else {
                s.clone()
            }
        }
        serde_json::Value::Number(n) => n.to_string(),
        serde_json::Value::Bool(b) => b.to_string(),
        serde_json::Value::Null => "null".to_string(),
        _ => serde_json::to_string(val).unwrap_or_default(),
    }
}

// ---------------------------------------------------------------------------
// Element-level item binding replacement
// ---------------------------------------------------------------------------

/// Replace item bindings (Value::Binding with is_item() or TemplateString with item bindings) with actual item values
/// OPTIMIZED: Uses single-pass replacement instead of O(n²) repeated scans
/// This is a convenience wrapper that uses "item" as the default item name.
pub fn replace_item_bindings(element: &Element, item: &serde_json::Value, index: usize) -> Element {
    replace_item_bindings_with_name(element, item, index, "item")
}

/// Replace item bindings in an Element with a configurable item name
/// This is the full implementation that supports custom iteration variable names.
///
/// Builds a fresh `Element` rather than cloning and overwriting — cloning
/// `element.ir_children` (a `Vec<IRNode>`) just to discard it is the most
/// expensive part of this hot loop, so every field here is constructed once.
pub fn replace_item_bindings_with_name(
    element: &Element,
    item: &serde_json::Value,
    index: usize,
    item_name: &str,
) -> Element {
    // Replace bindings in props using the unified Value replacement logic
    let mut new_props = Props::new();
    for (key, value) in &element.props {
        new_props.insert(
            key.clone(),
            replace_value_item_bindings(value, item, item_name),
        );
    }

    // Generate key using the item name
    let key = item
        .get("id")
        .and_then(|v| {
            v.as_str()
                .map(|s| s.to_string())
                .or_else(|| v.as_i64().map(|n| n.to_string()))
        })
        .or_else(|| {
            item.get("key")
                .and_then(|v| v.as_str().map(|s| s.to_string()))
        })
        .map(|id| format!("{}-{}", item_name, id))
        .unwrap_or_else(|| format!("{}-{}", item_name, index));

    // Recursively replace in ir_children (build directly — never materialize
    // a clone of the original Vec<IRNode>).
    let child_key = format!("{}-{}", item_name, index);
    let ir_children = element
        .ir_children
        .iter()
        .map(|child_ir| {
            replace_ir_node_item_bindings(child_ir, item, index, item_name, &child_key)
        })
        .collect();

    Element {
        element_type: element.element_type.clone(),
        props: new_props,
        ir_children,
        key: Some(key),
        module_scope: element.module_scope.clone(),
    }
}

// ---------------------------------------------------------------------------
// IRNode-level item binding replacement
// ---------------------------------------------------------------------------

/// Replace item bindings in an IRNode with actual item values
/// Supports configurable item variable names (e.g., "todo", "user" instead of "item")
pub(crate) fn replace_ir_node_item_bindings(
    node: &IRNode,
    item: &serde_json::Value,
    index: usize,
    item_name: &str,
    item_key: &str,
) -> IRNode {
    match node {
        IRNode::Element(element) => {
            let mut new_element = replace_item_bindings_with_name(element, item, index, item_name);
            // Override key with the computed item key
            new_element.key = Some(item_key.to_string());
            IRNode::Element(new_element)
        }
        IRNode::ForEach {
            source,
            item_name: inner_item_name,
            key_path,
            template,
            props,
            module_scope,
        } => {
            // Note: source binding is kept as-is; nested ForEach maintains its own iteration context
            // Replace in props
            let new_props = replace_props_item_bindings(props, item, item_name);

            // Recursively replace in template (but inner ForEach has its own item context)
            let new_template: Vec<IRNode> = template
                .iter()
                .map(|child| replace_ir_node_item_bindings(child, item, index, item_name, item_key))
                .collect();

            IRNode::ForEach {
                source: source.clone(),
                item_name: inner_item_name.clone(),
                key_path: key_path.clone(),
                template: new_template,
                props: new_props,
                module_scope: module_scope.clone(),
            }
        }
        IRNode::Conditional {
            value,
            branches,
            fallback,
            module_scope,
        } => {
            // Replace in condition value
            let new_value = replace_value_item_bindings(value, item, item_name);

            // Replace in branches
            let new_branches: Vec<ConditionalBranch> = branches
                .iter()
                .map(|branch| {
                    let new_pattern = replace_value_item_bindings(&branch.pattern, item, item_name);
                    let new_children: Vec<IRNode> = branch
                        .children
                        .iter()
                        .map(|child| {
                            replace_ir_node_item_bindings(child, item, index, item_name, item_key)
                        })
                        .collect();
                    ConditionalBranch::new(new_pattern, new_children)
                })
                .collect();

            // Replace in fallback
            let new_fallback = fallback.as_ref().map(|f| {
                f.iter()
                    .map(|child| {
                        replace_ir_node_item_bindings(child, item, index, item_name, item_key)
                    })
                    .collect()
            });

            IRNode::Conditional {
                value: new_value,
                branches: new_branches,
                fallback: new_fallback,
                module_scope: module_scope.clone(),
            }
        }
        IRNode::Router {
            location,
            routes,
            fallback,
            module_scope,
        } => {
            // Replace in location value (rare — usually state.location which has no item refs)
            let new_location = replace_value_item_bindings(location, item, item_name);

            // Replace in each route's children
            let new_routes: Vec<crate::ir::RouterRoute> = routes
                .iter()
                .map(|route| crate::ir::RouterRoute {
                    path: route.path.clone(),
                    children: route
                        .children
                        .iter()
                        .map(|child| {
                            replace_ir_node_item_bindings(child, item, index, item_name, item_key)
                        })
                        .collect(),
                })
                .collect();

            // Replace in fallback
            let new_fallback = fallback.as_ref().map(|f| {
                f.iter()
                    .map(|child| {
                        replace_ir_node_item_bindings(child, item, index, item_name, item_key)
                    })
                    .collect()
            });

            IRNode::Router {
                location: new_location,
                routes: new_routes,
                fallback: new_fallback,
                module_scope: module_scope.clone(),
            }
        }
    }
}

/// Replace item bindings in Props
fn replace_props_item_bindings(props: &Props, item: &serde_json::Value, item_name: &str) -> Props {
    let mut new_props = Props::new();
    for (key, value) in props {
        new_props.insert(
            key.clone(),
            replace_value_item_bindings(value, item, item_name),
        );
    }
    new_props
}

// ---------------------------------------------------------------------------
// Value-level item binding replacement
// ---------------------------------------------------------------------------

/// Replace item bindings in a Value
/// Uses optimized single-pass replacement to avoid O(n²) string operations.
/// `item_name` allows custom iteration variable names (e.g., "todo", "user" instead of "item").
fn replace_value_item_bindings(value: &Value, item: &serde_json::Value, item_name: &str) -> Value {
    match value {
        Value::Binding(binding) => {
            if binding.is_item() {
                if binding.path.is_empty() {
                    Value::Static(item.clone())
                } else {
                    let path = binding.full_path();
                    if let Some(val) = navigate_item_path(item, &path) {
                        Value::Static(val.clone())
                    } else {
                        value.clone()
                    }
                }
            } else {
                value.clone()
            }
        }
        Value::TemplateString { template, bindings } => {
            replace_template_string_item_bindings(template, bindings, item, item_name, value)
        }
        // Handle static strings containing @{item.xxx} pattern (legacy/fallback)
        Value::Static(serde_json::Value::String(s))
            if s.contains(&format!("@{{{}.", item_name))
                || s.contains(&format!("@{{{}}}", item_name)) =>
        {
            replace_static_item_bindings_with_name(s, item, item_name)
        }
        _ => value.clone(),
    }
}

/// Replace item bindings within a TemplateString value
fn replace_template_string_item_bindings(
    template: &str,
    bindings: &[Binding],
    item: &serde_json::Value,
    item_name: &str,
    original: &Value,
) -> Value {
    use crate::reactive::{build_evaluator, evaluate_template_string};

    let has_item_bindings = bindings.iter().any(|b| b.is_item());
    if !has_item_bindings {
        return original.clone();
    }

    // PHASE 1: Collect all replacements for explicit bindings (single pass)
    let mut replacements = Vec::new();
    for binding in bindings {
        if binding.is_item() {
            let pattern = format!("@{{{}}}", binding.full_path_with_source());
            if let Some(start) = template.find(&pattern) {
                let replacement = if binding.path.is_empty() {
                    format_value_for_replacement(item, false)
                } else if let Some(val) = navigate_item_path(item, &binding.full_path()) {
                    format_value_for_replacement(val, false)
                } else {
                    continue;
                };
                replacements.push(Replacement {
                    start,
                    end: start + pattern.len(),
                    text: replacement,
                });
            }
        }
    }

    // PHASE 2: Apply explicit binding replacements
    let mut result = apply_replacements(template, replacements);

    // PHASE 3: Replace item.xxx references in expressions (e.g., ternary operators)
    // Uses the configurable item_name for custom iteration variables
    let expr_replacements = collect_item_replacements_with_name(&result, item, true, item_name);
    result = apply_replacements(&result, expr_replacements);

    // Filter out resolved item bindings, keep state bindings
    let remaining_bindings: Vec<_> = bindings.iter().filter(|b| b.is_state()).cloned().collect();

    if remaining_bindings.is_empty() {
        if result.contains("@{") {
            let evaluator = build_evaluator(&serde_json::Value::Null, None, None);
            match evaluate_template_string(&result, &evaluator) {
                Ok(evaluated) => Value::Static(serde_json::Value::String(evaluated)),
                Err(_) => Value::Static(serde_json::Value::String(result)),
            }
        } else {
            Value::Static(serde_json::Value::String(result))
        }
    } else {
        Value::TemplateString {
            template: result,
            bindings: remaining_bindings,
        }
    }
}

/// Find all item.xxx references in a string with configurable item name.
fn collect_item_replacements_with_name(
    s: &str,
    item: &serde_json::Value,
    quote_strings: bool,
    item_name: &str,
) -> Vec<Replacement> {
    let mut replacements = Vec::new();
    let mut pos = 0;

    while pos < s.len() {
        if let Some(rel_start) = s[pos..].find(item_name) {
            let abs_start = pos + rel_start;
            let after_item = abs_start + item_name.len();

            if after_item < s.len() && s.as_bytes()[after_item] == b'.' {
                let path_start = after_item + 1;
                let path_end = find_path_end(s, path_start);

                if path_end > path_start {
                    let path = &s[path_start..path_end];
                    if let Some(val) = navigate_item_path(item, path) {
                        let replacement = format_value_for_replacement(val, quote_strings);
                        replacements.push(Replacement {
                            start: abs_start,
                            end: path_end,
                            text: replacement,
                        });
                    }
                }
                pos = path_end.max(after_item + 1);
            } else {
                pos = after_item;
            }
        } else {
            break;
        }
    }

    replacements
}

/// Replace item bindings in a static string value with configurable item name
fn replace_static_item_bindings_with_name(
    s: &str,
    item: &serde_json::Value,
    item_name: &str,
) -> Value {
    use crate::reactive::{build_evaluator, evaluate_template_string};

    let mut replacements = Vec::new();
    let mut pos = 0;

    while let Some(start) = s[pos..].find("@{") {
        let abs_start = pos + start;

        if let Some(end) = s[abs_start..].find('}') {
            let abs_end = abs_start + end;
            let content = &s[abs_start + 2..abs_end];

            if content == item_name {
                // Bare @{item}
                replacements.push(Replacement {
                    start: abs_start,
                    end: abs_end + 1,
                    text: format_value_for_replacement(item, false),
                });
                pos = abs_end + 1;
            } else if content.starts_with(&format!("{}.", item_name))
                && is_simple_path_with_name(content, item_name)
            {
                // Simple @{item.path}
                let path = &content[item_name.len() + 1..];
                if let Some(val) = navigate_item_path(item, path) {
                    replacements.push(Replacement {
                        start: abs_start,
                        end: abs_end + 1,
                        text: format_value_for_replacement(val, false),
                    });
                }
                pos = abs_end + 1;
            } else if content.contains(&format!("{}.", item_name))
                || content.contains(&format!("{} ", item_name))
            {
                // Complex expression - replace item refs within, then evaluate
                let expr_replacements =
                    collect_item_replacements_with_name(content, item, true, item_name);
                let substituted_content = apply_replacements(content, expr_replacements);
                let new_expr = format!("@{{{}}}", substituted_content);

                let evaluator = build_evaluator(&serde_json::Value::Null, None, None);
                if let Ok(evaluated) = evaluate_template_string(&new_expr, &evaluator) {
                    replacements.push(Replacement {
                        start: abs_start,
                        end: abs_end + 1,
                        text: evaluated,
                    });
                }
                pos = abs_end + 1;
            } else {
                pos = abs_end + 1;
            }
        } else {
            break;
        }
    }

    let result = apply_replacements(s, replacements);
    Value::Static(serde_json::Value::String(result))
}

/// Check if a string is a simple path with configurable item name
fn is_simple_path_with_name(s: &str, item_name: &str) -> bool {
    if !s.starts_with(item_name) {
        return false;
    }

    let after_item = &s[item_name.len()..];
    if after_item.is_empty() {
        return true;
    }

    if !after_item.starts_with('.') {
        return false;
    }

    after_item[1..]
        .chars()
        .all(|c| c.is_alphanumeric() || c == '_' || c == '.')
}