jsbind/
url.rs

1use crate::error::TypeError;
2use crate::utils::*;
3use alloc::string::String;
4
5#[derive(Clone, Debug, PartialEq, PartialOrd)]
6#[repr(transparent)]
7pub struct URL {
8    inner: emlite::Val,
9}
10bind!(URL);
11impl_dyn_cast!(URL);
12
13impl URL {
14    /// Creates a new URL object with error handling.
15    ///
16    /// # Arguments
17    /// * `input` - URL string to parse
18    /// * `base` - Optional base URL string
19    ///
20    /// # Returns
21    /// Result containing the URL object or a TypeError if the URL is malformed
22    ///
23    /// # Examples
24    /// ```rust
25    /// use jsbind::prelude::*;
26    ///
27    /// let url = URL::new("https://example.com", None).unwrap();
28    /// let relative = URL::new("/path", Some("https://example.com")).unwrap();
29    /// assert!(URL::new("invalid-url", None).is_err());
30    /// ```
31    pub fn new(input: &str, base: Option<String>) -> Result<Self, TypeError> {
32        let ctor = emlite::Val::global("URL");
33        let result = match base {
34            Some(b) => ctor.new(&[input.into(), b.into()]),
35            None => ctor.new(&[input.into()]),
36        };
37        result.as_::<Result<Self, TypeError>>()
38    }
39
40    pub fn href(&self) -> Option<String> {
41        self.inner.get("href").as_::<Option<String>>()
42    }
43    pub fn set_href(&mut self, v: &str) {
44        self.inner.set("href", v);
45    }
46
47    pub fn protocol(&self) -> Option<String> {
48        self.inner.get("protocol").as_::<Option<String>>()
49    }
50    pub fn set_protocol(&mut self, v: &str) {
51        self.inner.set("protocol", v);
52    }
53
54    pub fn pathname(&self) -> Option<String> {
55        self.inner.get("pathname").as_::<Option<String>>()
56    }
57    pub fn set_pathname(&mut self, v: &str) {
58        self.inner.set("pathname", v);
59    }
60
61    pub fn search_params(&self) -> URLSearchParams {
62        self.inner.get("searchParams").as_::<URLSearchParams>()
63    }
64}
65
66/// `URLSearchParams` – minimal wrapper. There is a URLSearchParams in webbind as well
67#[derive(Clone, Debug, PartialEq, PartialOrd)]
68#[repr(transparent)]
69pub struct URLSearchParams {
70    inner: emlite::Val,
71}
72bind!(URLSearchParams);
73impl_dyn_cast!(URLSearchParams);
74
75impl URLSearchParams {
76    pub fn get(&self, key: &str) -> Option<String> {
77        let v = self.inner.call("get", &[key.into()]);
78        if v.is_null() {
79            None
80        } else {
81            v.as_::<Option<String>>()
82        }
83    }
84
85    pub fn append(&mut self, key: &str, value: &str) {
86        self.inner.call("append", &[key.into(), value.into()]);
87    }
88}