rust_rectangle_dividing/
wasm_binding.rs1use crate::axis_aligned_rectangle::AxisAlignedRectangle;
2use crate::component::Component;
3use crate::dividing::Dividing;
4use crate::point::Point;
5use crate::rectangle::{Rectangle, RectangleSize};
6use serde::{Deserialize, Serialize};
7use serde_wasm_bindgen;
8use wasm_bindgen::prelude::*;
9
10#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
11pub struct JSRect {
12 pub x: f32,
13 pub y: f32,
14 pub w: f32,
15 pub h: f32,
16}
17
18#[wasm_bindgen]
19pub fn dividing(
20 rect: JsValue,
21 weights: &[f32],
22 aspect_ratio: f32,
23 vertical_first: bool,
24 boustrophedron: bool,
25) -> Result<JsValue, JsValue> {
26 let Ok(rect) = serde_wasm_bindgen::from_value::<JSRect>(rect) else {
27 return Err(JsValue::from_str("failed to parse rect"));
28 };
29 let rect =
30 AxisAlignedRectangle::new(&Point::new(rect.x, rect.y), &Rectangle::new(rect.w, rect.h));
31 let rects = match vertical_first {
32 true => {
33 rect.divide_vertical_then_horizontal_with_weights(weights, aspect_ratio, boustrophedron)
34 }
35 false => {
36 rect.divide_horizontal_then_vertical_with_weights(weights, aspect_ratio, boustrophedron)
37 }
38 };
39
40 let js_rects = rects
41 .iter()
42 .map(|rect| JSRect {
43 x: rect.x(),
44 y: rect.y(),
45 w: rect.width(),
46 h: rect.height(),
47 })
48 .collect::<Vec<_>>();
49
50 serde_wasm_bindgen::to_value(&js_rects).map_err(|e| e.into())
51}
52
53#[cfg(test)]
54mod tests {
55 use wasm_bindgen_test::wasm_bindgen_test;
56
57 use super::*;
58
59 #[wasm_bindgen_test]
60 fn test_basis() {
61 let result = dividing(
62 serde_wasm_bindgen::to_value(&JSRect {
63 x: 0.0,
64 y: 0.0,
65 w: 100.0,
66 h: 100.0,
67 })
68 .unwrap(),
69 &[1.0, 1.0],
70 1.0,
71 true,
72 false,
73 )
74 .unwrap();
75 let result: Vec<JSRect> = serde_wasm_bindgen::from_value(result).unwrap();
76 assert_eq!(
77 result,
78 vec![
79 JSRect {
80 x: 0.0,
81 y: 0.0,
82 w: 100.0,
83 h: 50.0
84 },
85 JSRect {
86 x: 0.0,
87 y: 50.0,
88 w: 100.0,
89 h: 50.0
90 }
91 ]
92 );
93 }
94}