vize_fresco 0.158.0

Fresco - Vue TUI framework (Terminal User Interface)
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
//! Layout NAPI bindings.

use napi::bindgen_prelude::*;
use napi_derive::napi;
use std::cell::RefCell;

use crate::layout::{FlexStyle, LayoutEngine};

use super::types::{FlexStyleNapi, LayoutResultNapi};

thread_local! {
    // Taffy's tree is not Send, so keep the native layout state scoped to the
    // thread running the NAPI calls instead of placing it behind a shared static.
    static LAYOUT: RefCell<Option<LayoutEngine>> = const { RefCell::new(None) };
}

fn with_layout_mut<T>(f: impl FnOnce(&mut LayoutEngine) -> Result<T>) -> Result<T> {
    LAYOUT.with(|layout| {
        let mut guard = layout.try_borrow_mut().map_err(|e| {
            Error::new(
                Status::GenericFailure,
                format!("Layout borrow error: {}", e),
            )
        })?;
        let engine = guard
            .as_mut()
            .ok_or_else(|| Error::new(Status::GenericFailure, "Layout not initialized"))?;

        f(engine)
    })
}

fn with_layout<T>(f: impl FnOnce(&LayoutEngine) -> Result<T>) -> Result<T> {
    LAYOUT.with(|layout| {
        let guard = layout.try_borrow().map_err(|e| {
            Error::new(
                Status::GenericFailure,
                format!("Layout borrow error: {}", e),
            )
        })?;
        let engine = guard
            .as_ref()
            .ok_or_else(|| Error::new(Status::GenericFailure, "Layout not initialized"))?;

        f(engine)
    })
}

/// Initialize layout engine.
#[napi(js_name = "initLayout")]
#[allow(clippy::disallowed_macros)]
pub fn init_layout() -> Result<()> {
    LAYOUT.with(|layout| {
        *layout.try_borrow_mut().map_err(|e| {
            Error::new(
                Status::GenericFailure,
                format!("Layout borrow error: {}", e),
            )
        })? = Some(LayoutEngine::new());
        Ok(())
    })
}

/// Create a new layout node.
#[napi(js_name = "createLayoutNode")]
#[allow(clippy::disallowed_macros)]
pub fn create_layout_node(style: Option<FlexStyleNapi>) -> Result<i64> {
    with_layout_mut(|engine| {
        let flex_style = style.map(convert_flex_style).unwrap_or_default();
        let id = engine.new_node(&flex_style);
        Ok(id as i64)
    })
}

/// Create a new leaf layout node with measured size.
#[napi(js_name = "createLayoutLeaf")]
#[allow(clippy::disallowed_macros)]
pub fn create_layout_leaf(width: f64, height: f64, style: Option<FlexStyleNapi>) -> Result<i64> {
    with_layout_mut(|engine| {
        let flex_style = style.map(convert_flex_style).unwrap_or_default();
        let id = engine.new_leaf(&flex_style, width as f32, height as f32);
        Ok(id as i64)
    })
}

/// Set layout root node.
#[napi(js_name = "setLayoutRoot")]
#[allow(clippy::disallowed_macros)]
pub fn set_layout_root(id: i64) -> Result<()> {
    with_layout_mut(|engine| {
        engine.set_root(id as u64);
        Ok(())
    })
}

/// Add child to parent node.
#[napi(js_name = "addLayoutChild")]
#[allow(clippy::disallowed_macros)]
pub fn add_layout_child(parent: i64, child: i64) -> Result<()> {
    with_layout_mut(|engine| {
        engine.add_child(parent as u64, child as u64);
        Ok(())
    })
}

/// Remove child from parent node.
#[napi(js_name = "removeLayoutChild")]
#[allow(clippy::disallowed_macros)]
pub fn remove_layout_child(parent: i64, child: i64) -> Result<()> {
    with_layout_mut(|engine| {
        engine.remove_child(parent as u64, child as u64);
        Ok(())
    })
}

/// Update node style.
#[napi(js_name = "setLayoutStyle")]
#[allow(clippy::disallowed_macros)]
pub fn set_layout_style(id: i64, style: FlexStyleNapi) -> Result<()> {
    with_layout_mut(|engine| {
        let flex_style = convert_flex_style(style);
        engine.set_style(id as u64, &flex_style);
        Ok(())
    })
}

/// Remove a node.
#[napi(js_name = "removeLayoutNode")]
#[allow(clippy::disallowed_macros)]
pub fn remove_layout_node(id: i64) -> Result<()> {
    with_layout_mut(|engine| {
        engine.remove(id as u64);
        Ok(())
    })
}

/// Compute layout.
#[napi(js_name = "computeLayout")]
#[allow(clippy::disallowed_macros)]
pub fn compute_layout(width: i32, height: i32) -> Result<()> {
    with_layout_mut(|engine| {
        engine.compute(width as f32, height as f32);
        Ok(())
    })
}

/// Get layout result for a node.
#[napi(js_name = "getLayout")]
#[allow(clippy::disallowed_macros)]
pub fn get_layout(id: i64) -> Result<Option<LayoutResultNapi>> {
    with_layout(|engine| {
        Ok(engine.layout(id as u64).map(|rect| LayoutResultNapi {
            id,
            x: rect.x as i32,
            y: rect.y as i32,
            width: rect.width as i32,
            height: rect.height as i32,
        }))
    })
}

/// Get all layout results.
#[napi(js_name = "getAllLayouts")]
#[allow(clippy::disallowed_macros)]
pub fn get_all_layouts() -> Result<Vec<LayoutResultNapi>> {
    with_layout(|engine| {
        let results: Vec<_> = engine
            .layouts()
            .iter()
            .map(|(&id, &rect)| LayoutResultNapi {
                id: id as i64,
                x: rect.x as i32,
                y: rect.y as i32,
                width: rect.width as i32,
                height: rect.height as i32,
            })
            .collect();

        Ok(results)
    })
}

/// Clear layout engine.
#[napi(js_name = "clearLayout")]
#[allow(clippy::disallowed_macros)]
pub fn clear_layout() -> Result<()> {
    LAYOUT.with(|layout| {
        if let Some(ref mut engine) = *layout.try_borrow_mut().map_err(|e| {
            Error::new(
                Status::GenericFailure,
                format!("Layout borrow error: {}", e),
            )
        })? {
            engine.clear();
        }

        Ok(())
    })
}

/// Convert FlexStyleNapi to FlexStyle.
fn convert_flex_style(style: FlexStyleNapi) -> FlexStyle {
    use crate::layout::*;

    let mut result = FlexStyle::default();

    if let Some(display) = style.display {
        result.display = match display.as_str() {
            "none" => Display::None,
            _ => Display::Flex,
        };
    }

    if let Some(position) = style.position {
        result.position = match position.as_str() {
            "absolute" => Position::Absolute,
            _ => Position::Relative,
        };
    }

    if let Some(top) = style.top {
        result.inset.top = parse_length_percentage_auto(&top);
    }

    if let Some(right) = style.right {
        result.inset.right = parse_length_percentage_auto(&right);
    }

    if let Some(bottom) = style.bottom {
        result.inset.bottom = parse_length_percentage_auto(&bottom);
    }

    if let Some(left) = style.left {
        result.inset.left = parse_length_percentage_auto(&left);
    }

    if let Some(overflow) = style.overflow.or(style.overflow_x).or(style.overflow_y) {
        result.overflow = match overflow.as_str() {
            "hidden" => Overflow::Hidden,
            "scroll" => Overflow::Scroll,
            _ => Overflow::Visible,
        };
    }

    if let Some(dir) = style.flex_direction {
        result.flex_direction = match dir.as_str() {
            "column" => FlexDirection::Column,
            "row-reverse" => FlexDirection::RowReverse,
            "column-reverse" => FlexDirection::ColumnReverse,
            _ => FlexDirection::Row,
        };
    }

    if let Some(wrap) = style.flex_wrap {
        result.flex_wrap = match wrap.as_str() {
            "wrap" => FlexWrap::Wrap,
            "wrap-reverse" => FlexWrap::WrapReverse,
            _ => FlexWrap::NoWrap,
        };
    }

    if let Some(jc) = style.justify_content {
        result.justify_content = match jc.as_str() {
            "flex-end" | "end" => JustifyContent::FlexEnd,
            "center" => JustifyContent::Center,
            "space-between" => JustifyContent::SpaceBetween,
            "space-around" => JustifyContent::SpaceAround,
            "space-evenly" => JustifyContent::SpaceEvenly,
            _ => JustifyContent::FlexStart,
        };
    }

    if let Some(ai) = style.align_items {
        result.align_items = match ai.as_str() {
            "flex-start" | "start" => AlignItems::FlexStart,
            "flex-end" | "end" => AlignItems::FlexEnd,
            "center" => AlignItems::Center,
            "baseline" => AlignItems::Baseline,
            _ => AlignItems::Stretch,
        };
    }

    if let Some(ai) = style.align_self {
        result.align_self = match ai.as_str() {
            "flex-start" | "start" => AlignSelf::FlexStart,
            "flex-end" | "end" => AlignSelf::FlexEnd,
            "center" => AlignSelf::Center,
            "stretch" => AlignSelf::Stretch,
            "baseline" => AlignSelf::Baseline,
            _ => AlignSelf::Auto,
        };
    }

    if let Some(ac) = style.align_content {
        result.align_content = match ac.as_str() {
            "flex-end" | "end" => AlignContent::FlexEnd,
            "center" => AlignContent::Center,
            "stretch" => AlignContent::Stretch,
            "space-between" => AlignContent::SpaceBetween,
            "space-around" => AlignContent::SpaceAround,
            _ => AlignContent::FlexStart,
        };
    }

    if let Some(grow) = style.flex_grow {
        result.flex_grow = grow as f32;
    }

    if let Some(shrink) = style.flex_shrink {
        result.flex_shrink = shrink as f32;
    }

    if let Some(basis) = style.flex_basis {
        result.flex_basis = parse_dimension(&basis);
    }

    if let Some(width) = style.width {
        result.width = parse_dimension(&width);
    }

    if let Some(height) = style.height {
        result.height = parse_dimension(&height);
    }

    if let Some(width) = style.min_width {
        result.min_width = parse_dimension(&width);
    }

    if let Some(height) = style.min_height {
        result.min_height = parse_dimension(&height);
    }

    if let Some(width) = style.max_width {
        result.max_width = parse_dimension(&width);
    }

    if let Some(height) = style.max_height {
        result.max_height = parse_dimension(&height);
    }

    if let Some(aspect_ratio) = style.aspect_ratio {
        result.aspect_ratio = Some(aspect_ratio as f32);
    }

    if let Some(p) = style.padding {
        result.padding = Edges::all(p as f32);
    }

    if let Some(p) = style.padding_top {
        result.padding.top = LengthPercentageAuto::Points(p as f32);
    }

    if let Some(p) = style.padding_right {
        result.padding.right = LengthPercentageAuto::Points(p as f32);
    }

    if let Some(p) = style.padding_bottom {
        result.padding.bottom = LengthPercentageAuto::Points(p as f32);
    }

    if let Some(p) = style.padding_left {
        result.padding.left = LengthPercentageAuto::Points(p as f32);
    }

    if let Some(m) = style.margin {
        result.margin = Edges::all(m as f32);
    }

    if let Some(m) = style.margin_top {
        result.margin.top = LengthPercentageAuto::Points(m as f32);
    }

    if let Some(m) = style.margin_right {
        result.margin.right = LengthPercentageAuto::Points(m as f32);
    }

    if let Some(m) = style.margin_bottom {
        result.margin.bottom = LengthPercentageAuto::Points(m as f32);
    }

    if let Some(m) = style.margin_left {
        result.margin.left = LengthPercentageAuto::Points(m as f32);
    }

    if let Some(g) = style.gap {
        result.gap = Gap::all(g as f32);
    }

    if let Some(g) = style.row_gap {
        result.gap.row = g as f32;
    }

    if let Some(g) = style.column_gap {
        result.gap.column = g as f32;
    }

    result
}

/// Parse dimension string.
fn parse_dimension(s: &str) -> crate::layout::Dimension {
    use crate::layout::Dimension;

    if s == "auto" {
        return Dimension::Auto;
    }

    if let Some(pct) = s.strip_suffix('%')
        && let Ok(v) = pct.parse::<f32>()
    {
        return Dimension::Percent(v);
    }

    if let Ok(v) = s.parse::<f32>() {
        return Dimension::Points(v);
    }

    Dimension::Auto
}

/// Parse length/percentage/auto string.
fn parse_length_percentage_auto(s: &str) -> crate::layout::LengthPercentageAuto {
    use crate::layout::LengthPercentageAuto;

    if s == "auto" {
        return LengthPercentageAuto::Auto;
    }

    if let Some(pct) = s.strip_suffix('%')
        && let Ok(v) = pct.parse::<f32>()
    {
        return LengthPercentageAuto::Percent(v);
    }

    if let Ok(v) = s.parse::<f32>() {
        return LengthPercentageAuto::Points(v);
    }

    LengthPercentageAuto::Auto
}