Skip to main content

vibe/web_runtime/
layout_virtual.rs

1//! Layout, Viewport Virtualization, Splitters, Collision-Aware Anchoring & Hit-Testing
2//! (`layout.*` and `ui.*`) for VibeScript v0.02.
3
4use std::collections::BTreeMap;
5
6use crate::error::{DiagCode, Diagnostic};
7use crate::span::Span;
8use crate::value::Value;
9
10use super::ui_controls::{
11    extract_f64, extract_i64, extract_list, extract_str, opt_f64, opt_i64, opt_str,
12};
13
14/// Dispatch a `layout.*` or layout-related `ui.*` function call.
15pub fn call_layout_virtual(
16    path: &str,
17    args: &[Value],
18    span: Span,
19) -> Result<Option<Value>, Diagnostic> {
20    match path {
21        "layout.virtual_slice" => {
22            let total_items = extract_i64(args, 0, "layout.virtual_slice", span)?.max(0);
23            let row_height = extract_f64(args, 1, "layout.virtual_slice", span)?;
24            if row_height <= 0.0 {
25                return Err(Diagnostic::new(
26                    DiagCode::E100,
27                    span,
28                    "layout.virtual_slice: row_height must be > 0",
29                ));
30            }
31            let scroll_top = extract_f64(args, 2, "layout.virtual_slice", span)?.max(0.0);
32            let viewport_h = extract_f64(args, 3, "layout.virtual_slice", span)?.max(0.0);
33            let overscan = opt_i64(args, 4, 2).max(0);
34
35            let total_height = (total_items as f64) * row_height;
36            let (start_idx, end_idx, visible_count, offset_y) = if total_items == 0 {
37                (0, 0, 0, 0.0)
38            } else {
39                let first_vis = ((scroll_top / row_height).floor() as i64).clamp(0, total_items);
40                let vis_rows = ((viewport_h / row_height).ceil() as i64).max(0);
41                let s = (first_vis - overscan).clamp(0, total_items);
42                let e = (first_vis + vis_rows + overscan).clamp(s, total_items);
43                (s, e, e - s, (s as f64) * row_height)
44            };
45
46            let mut rec = BTreeMap::new();
47            rec.insert("start_idx".into(), Value::I64(start_idx));
48            rec.insert("end_idx".into(), Value::I64(end_idx));
49            rec.insert("visible_count".into(), Value::I64(visible_count));
50            rec.insert("offset_y".into(), Value::F64(offset_y));
51            rec.insert("total_height".into(), Value::F64(total_height));
52            Ok(Some(Value::Record(rec)))
53        }
54        "layout.solve_flex" => {
55            let items = extract_list(args, 0, "layout.solve_flex", span)?;
56            let viewport_w = extract_f64(args, 1, "layout.solve_flex", span)?.max(0.0);
57            let viewport_h = extract_f64(args, 2, "layout.solve_flex", span)?.max(0.0);
58            let direction = opt_str(args, 3, "row");
59            let gap = opt_f64(args, 4, 0.0).max(0.0);
60            let is_col = matches!(direction.as_str(), "column" | "col" | "vertical");
61            if !is_col && !matches!(direction.as_str(), "row" | "horizontal") {
62                return Err(Diagnostic::new(
63                    DiagCode::E100,
64                    span,
65                    format!("layout.solve_flex: unsupported direction '{direction}'"),
66                ));
67            }
68
69            let n = items.len();
70            let total_gap = if n > 1 { gap * (n - 1) as f64 } else { 0.0 };
71            let main_cap = if is_col { viewport_h } else { viewport_w };
72            let cross_cap = if is_col { viewport_w } else { viewport_h };
73
74            let mut fixed_sum = 0.0;
75            let mut flex_sum = 0.0;
76            for item in &items {
77                if let Value::Record(m) = item {
78                    let main_sz = item_dim(m, if is_col { "h" } else { "w" });
79                    if main_sz > 0.0 {
80                        fixed_sum += main_sz;
81                    } else {
82                        let fl = m
83                            .get("flex")
84                            .and_then(Value::as_f64)
85                            .unwrap_or(1.0)
86                            .max(0.0);
87                        flex_sum += if fl > 0.0 { fl } else { 1.0 };
88                    }
89                }
90            }
91            let remaining = (main_cap - fixed_sum - total_gap).max(0.0);
92            let mut cursor = 0.0;
93            let mut out = Vec::with_capacity(n);
94            for item in items {
95                if let Value::Record(mut m) = item {
96                    let raw_w = item_dim(&m, "w");
97                    let raw_h = item_dim(&m, "h");
98                    let fl = m
99                        .get("flex")
100                        .and_then(Value::as_f64)
101                        .unwrap_or(1.0)
102                        .max(1.0);
103                    let (x, y, w, h) = if is_col {
104                        let h = if raw_h > 0.0 {
105                            raw_h
106                        } else if flex_sum > 0.0 {
107                            remaining * (fl / flex_sum)
108                        } else {
109                            0.0
110                        };
111                        let w = if raw_w > 0.0 { raw_w } else { cross_cap };
112                        let y = cursor;
113                        cursor += h + gap;
114                        (0.0, y, w, h)
115                    } else {
116                        let w = if raw_w > 0.0 {
117                            raw_w
118                        } else if flex_sum > 0.0 {
119                            remaining * (fl / flex_sum)
120                        } else {
121                            0.0
122                        };
123                        let h = if raw_h > 0.0 { raw_h } else { cross_cap };
124                        let x = cursor;
125                        cursor += w + gap;
126                        (x, 0.0, w, h)
127                    };
128                    m.insert("x".into(), Value::F64(x));
129                    m.insert("y".into(), Value::F64(y));
130                    m.insert("w".into(), Value::F64(w));
131                    m.insert("h".into(), Value::F64(h));
132                    out.push(Value::Record(m));
133                }
134            }
135            Ok(Some(Value::List(out)))
136        }
137        "ui.splitter" => {
138            let id = extract_str(args, 0, "ui.splitter", span)?;
139            let orientation = extract_str(args, 1, "ui.splitter", span)?;
140            if !matches!(
141                orientation.as_str(),
142                "horizontal" | "vertical" | "row" | "column"
143            ) {
144                return Err(Diagnostic::new(
145                    DiagCode::E100,
146                    span,
147                    format!("ui.splitter: invalid orientation '{orientation}'"),
148                ));
149            }
150            let ratio = extract_f64(args, 2, "ui.splitter", span)?.clamp(0.0, 1.0);
151            let min_px = extract_f64(args, 3, "ui.splitter", span)?.max(0.0);
152            let max_px = extract_f64(args, 4, "ui.splitter", span)?.max(min_px);
153            let total_px = opt_f64(args, 5, 1000.0_f64.max(max_px)).max(min_px);
154
155            let primary_px = (ratio * total_px).clamp(min_px, max_px.min(total_px).max(min_px));
156            let secondary_px = (total_px - primary_px).max(0.0);
157            let clamped_ratio = if total_px > 0.0 {
158                primary_px / total_px
159            } else {
160                0.0
161            };
162
163            let mut rec = BTreeMap::new();
164            rec.insert("id".into(), Value::String(id));
165            rec.insert("kind".into(), Value::String("splitter".into()));
166            rec.insert("orientation".into(), Value::String(orientation));
167            rec.insert("ratio".into(), Value::F64(clamped_ratio));
168            rec.insert("primary_px".into(), Value::F64(primary_px));
169            rec.insert("secondary_px".into(), Value::F64(secondary_px));
170            Ok(Some(Value::Record(rec)))
171        }
172        "ui.anchor_position" => eval_anchor_position(args, span),
173        "ui.hit_test" => {
174            let items = match args.first() {
175                Some(Value::List(xs)) => xs.clone(),
176                Some(Value::Record(doc)) => match doc.get("items") {
177                    Some(Value::List(xs)) => xs.clone(),
178                    _ => Vec::new(),
179                },
180                _ => return Err(Diagnostic::new(
181                    DiagCode::E100,
182                    span,
183                    "ui.hit_test(items, x, y): argument #0 must be a List or document Record",
184                )),
185            };
186            let x = extract_f64(args, 1, "ui.hit_test", span)?;
187            let y = extract_f64(args, 2, "ui.hit_test", span)?;
188
189            for item in items.iter().rev() {
190                if let Value::Record(m) = item {
191                    let disabled = m.get("disabled") == Some(&Value::Bool(true))
192                        || m.get("hidden") == Some(&Value::Bool(true))
193                        || m.get("inert") == Some(&Value::Bool(true));
194                    if disabled {
195                        continue;
196                    }
197                    let ix = m.get("x").and_then(Value::as_f64).unwrap_or(0.0);
198                    let iy = m.get("y").and_then(Value::as_f64).unwrap_or(0.0);
199                    let iw = item_dim(m, "w");
200                    let ih = item_dim(m, "h");
201                    if iw > 0.0 && ih > 0.0 && x >= ix && x <= ix + iw && y >= iy && y <= iy + ih {
202                        if let Some(Value::String(id)) = m.get("id") {
203                            return Ok(Some(Value::String(id.clone())));
204                        }
205                    }
206                }
207            }
208            Ok(Some(Value::String(String::new())))
209        }
210        _ => Ok(None),
211    }
212}
213
214fn eval_anchor_position(args: &[Value], span: Span) -> Result<Option<Value>, Diagnostic> {
215    let (ax, ay, aw, ah, ow, oh, vw, vh, preferred_side) =
216        if let Some(Value::Record(r)) = args.first() {
217            let ax = r.get("x").and_then(Value::as_f64).unwrap_or(0.0);
218            let ay = r.get("y").and_then(Value::as_f64).unwrap_or(0.0);
219            let aw = item_dim(r, "w");
220            let ah = item_dim(r, "h");
221            let ow = extract_f64(args, 1, "ui.anchor_position", span)?.max(0.0);
222            let oh = extract_f64(args, 2, "ui.anchor_position", span)?.max(0.0);
223            let vw = extract_f64(args, 3, "ui.anchor_position", span)?.max(0.0);
224            let vh = extract_f64(args, 4, "ui.anchor_position", span)?.max(0.0);
225            let side = opt_str(args, 5, "bottom");
226            (ax, ay, aw, ah, ow, oh, vw, vh, side)
227        } else {
228            let ax = extract_f64(args, 0, "ui.anchor_position", span)?;
229            let ay = extract_f64(args, 1, "ui.anchor_position", span)?;
230            let aw = extract_f64(args, 2, "ui.anchor_position", span)?.max(0.0);
231            let ah = extract_f64(args, 3, "ui.anchor_position", span)?.max(0.0);
232            let ow = extract_f64(args, 4, "ui.anchor_position", span)?.max(0.0);
233            let oh = extract_f64(args, 5, "ui.anchor_position", span)?.max(0.0);
234            let vw = extract_f64(args, 6, "ui.anchor_position", span)?.max(0.0);
235            let vh = extract_f64(args, 7, "ui.anchor_position", span)?.max(0.0);
236            let side = opt_str(args, 8, "bottom");
237            (ax, ay, aw, ah, ow, oh, vw, vh, side)
238        };
239
240    let (mut x, mut y, resolved_side, flipped) = match preferred_side.as_str() {
241        "bottom" => {
242            if ay + ah + oh > vh && ay - oh >= 0.0 {
243                (ax, ay - oh, "top", true)
244            } else {
245                (ax, ay + ah, "bottom", false)
246            }
247        }
248        "top" => {
249            if ay - oh < 0.0 && ay + ah + oh <= vh {
250                (ax, ay + ah, "bottom", true)
251            } else {
252                (ax, ay - oh, "top", false)
253            }
254        }
255        "right" => {
256            if ax + aw + ow > vw && ax - ow >= 0.0 {
257                (ax - ow, ay, "left", true)
258            } else {
259                (ax + aw, ay, "right", false)
260            }
261        }
262        "left" => {
263            if ax - ow < 0.0 && ax + aw + ow <= vw {
264                (ax + aw, ay, "right", true)
265            } else {
266                (ax - ow, ay, "left", false)
267            }
268        }
269        _ => {
270            return Err(Diagnostic::new(
271                DiagCode::E100,
272                span,
273                format!("ui.anchor_position: invalid preferred_side '{preferred_side}'"),
274            ))
275        }
276    };
277
278    x = x.clamp(0.0, (vw - ow).max(0.0));
279    y = y.clamp(0.0, (vh - oh).max(0.0));
280
281    let mut rec = BTreeMap::new();
282    rec.insert("x".into(), Value::F64(x));
283    rec.insert("y".into(), Value::F64(y));
284    rec.insert("resolved_side".into(), Value::String(resolved_side.into()));
285    rec.insert("flipped".into(), Value::Bool(flipped));
286    Ok(Some(Value::Record(rec)))
287}
288
289fn item_dim(m: &BTreeMap<String, Value>, key: &str) -> f64 {
290    let alt = if key == "w" { "width" } else { "height" };
291    m.get(key)
292        .or_else(|| m.get(alt))
293        .and_then(Value::as_f64)
294        .unwrap_or(0.0)
295}