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
#![doc = include_str!("../README.md")]
#![allow(clippy::multiple_crate_versions)]

use std::cell::RefCell;
use std::rc::Rc;

use dioxus::dioxus_core::Element;
use dioxus::hooks::UnboundedSender;
use futures_channel::oneshot;
use wasm_bindgen::prelude::*;
use web_sys::HtmlElement;

use crate::rust_component::RustComponent;
pub use dioxus_web_component_macro::web_component;

mod event;
pub use self::event::*;

mod style;
pub use self::style::*;

mod rust_component;

pub use futures_util::StreamExt;

/// Message from web component to dioxus
#[derive(Debug)]
#[non_exhaustive]
pub enum Message {
    /// Set attribute
    SetAttribute {
        /// Attribute name
        name: String,
        /// Attribute value
        value: Option<String>,
    },
    /// Get property
    Get {
        /// Property name
        name: String,
        /// reply channel
        tx: oneshot::Sender<JsValue>,
    },
    /// Set property
    Set {
        /// Property name
        name: String,
        /// Property value
        value: JsValue,
    },
}

/// A context provided by the web component
#[derive(Clone)]
pub struct Shared {
    attributes: Vec<String>,
    event_target: web_sys::HtmlElement,
    tx: Rc<RefCell<Option<UnboundedSender<Message>>>>,
}

impl Shared {
    /// The web component event target use to dispatch custom event
    #[must_use]
    pub fn event_target(&self) -> HtmlElement {
        self.event_target.clone()
    }

    /// Set the receiver
    pub fn set_tx(&mut self, tx: UnboundedSender<Message>) {
        // initial state
        for attr in &self.attributes {
            let Some(value) = self.event_target.get_attribute(attr) else {
                continue;
            };
            let _ = tx.unbounded_send(Message::SetAttribute {
                name: attr.to_string(),
                value: Some(value),
            });
        }
        // Keep sender
        let mut cell = self.tx.borrow_mut();
        *cell = Some(tx);
    }
}

/// Dioxus web component
pub trait DioxusWebComponent {
    /// Set an HTML attribute
    fn set_attribute(&mut self, attribute: &str, value: Option<String>) {
        let _ = value;
        let _ = attribute;
    }

    /// Set a property
    fn set_property(&mut self, property: &str, value: JsValue) {
        let _ = value;
        let _ = property;
    }

    /// Get a property
    fn get_property(&mut self, property: &str) -> JsValue {
        let _ = property;
        JsValue::undefined()
    }

    /// Handle a message
    fn handle_message(&mut self, msg: Message) {
        match msg {
            Message::SetAttribute { name, value } => self.set_attribute(&name, value),
            Message::Get { name, tx } => {
                let value = self.get_property(&name);
                let _ = tx.send(value);
            }
            Message::Set { name, value } => self.set_property(&name, value),
        }
    }
}

/// Property
#[wasm_bindgen(skip_typescript)]
#[derive(Debug, Clone)]
pub struct Property {
    /// Name
    name: String,
    /// Readonly
    readonly: bool,
}

impl Property {
    /// Create a property
    pub fn new(name: impl Into<String>, readonly: bool) -> Self {
        let name = name.into();
        Self { name, readonly }
    }
}

#[wasm_bindgen]
impl Property {
    /// Get name
    #[wasm_bindgen(getter)]
    #[must_use]
    pub fn name(&self) -> String {
        self.name.clone()
    }

    /// Is property readonly
    #[wasm_bindgen(getter)]
    #[must_use]
    pub fn readonly(&self) -> bool {
        self.readonly
    }
}

/// Register a Dioxus web component
pub fn register_dioxus_web_component(
    custom_tag: &str,
    attributes: Vec<String>,
    properties: Vec<Property>,
    style: InjectedStyle,
    dx_el_builder: fn() -> Element,
) {
    let rust_component = RustComponent {
        attributes,
        properties,
        style,
        dx_el_builder,
    };
    register_web_component(custom_tag, rust_component);
}

#[wasm_bindgen(module = "/src/shim.js")]
extern "C" {
    #[allow(unsafe_code)]
    fn register_web_component(custom_tag: &str, rust_component: RustComponent);
}