Skip to main content

oxmpl_js/base/
state_validity_checker.rs

1// Copyright (c) 2025 Ross Gardiner, Junior Sundar
2//
3// SPDX-License-Identifier: BSD-3-Clause
4
5use crate::base::js_state_convert::*;
6use oxmpl::base::{
7    state::{CompoundState, RealVectorState, SE2State, SE3State, SO2State, SO3State, State},
8    validity::StateValidityChecker,
9};
10use wasm_bindgen::prelude::*;
11use web_sys::console;
12
13#[wasm_bindgen(js_name = StateValidityChecker)]
14#[derive(Clone)]
15pub struct JsStateValidityChecker {
16    callback: js_sys::Function,
17}
18
19#[wasm_bindgen]
20extern "C" {
21    #[wasm_bindgen(typescript_type = "(state: any) => boolean")]
22    pub type StateValidityCallback;
23}
24
25#[wasm_bindgen(js_class = StateValidityChecker)]
26impl JsStateValidityChecker {
27    #[wasm_bindgen(constructor)]
28    pub fn new(callback: StateValidityCallback) -> Self {
29        Self {
30            callback: JsValue::from(callback).into(),
31        }
32    }
33}
34
35impl JsStateValidityChecker {
36    fn call_is_valid<S: JsStateConvert + State>(&self, state: &S) -> bool {
37        let js_state = state.to_js_value();
38
39        match self.callback.call1(&JsValue::NULL, &js_state) {
40            Ok(result) => match result.as_bool() {
41                Some(is_valid) => is_valid,
42                None => {
43                    console::warn_1(&"State validity checker returned non-boolean value".into());
44                    false
45                }
46            },
47            Err(e) => {
48                console::error_2(&"State validity checker callback failed:".into(), &e);
49                false
50            }
51        }
52    }
53}
54
55impl StateValidityChecker<RealVectorState> for JsStateValidityChecker {
56    fn is_valid(&self, state: &RealVectorState) -> bool {
57        self.call_is_valid(state)
58    }
59}
60
61impl StateValidityChecker<SO2State> for JsStateValidityChecker {
62    fn is_valid(&self, state: &SO2State) -> bool {
63        self.call_is_valid(state)
64    }
65}
66
67impl StateValidityChecker<SO3State> for JsStateValidityChecker {
68    fn is_valid(&self, state: &SO3State) -> bool {
69        self.call_is_valid(state)
70    }
71}
72
73impl StateValidityChecker<SE2State> for JsStateValidityChecker {
74    fn is_valid(&self, state: &SE2State) -> bool {
75        self.call_is_valid(state)
76    }
77}
78
79impl StateValidityChecker<SE3State> for JsStateValidityChecker {
80    fn is_valid(&self, state: &SE3State) -> bool {
81        self.call_is_valid(state)
82    }
83}
84
85impl StateValidityChecker<CompoundState> for JsStateValidityChecker {
86    fn is_valid(&self, state: &CompoundState) -> bool {
87        self.call_is_valid(state)
88    }
89}