telegram-webapp-sdk 0.13.0

Telegram WebApp SDK for Rust
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
// SPDX-FileCopyrightText: 2025-2026 RAprogramm <andrey.rozanov.vl@gmail.com>
// SPDX-License-Identifier: MIT

use wasm_bindgen::{JsCast, JsValue, closure::Closure};
use web_sys::{Element, EventTarget, Node};

/// Ergonomic extension methods for [`web_sys::Element`].
///
/// Provides concise helpers for common DOM manipulations (attributes, classes,
/// text/HTML content, event listeners, and child insertion/removal) on top of
/// the lower-level `web-sys` API.
pub trait ElementExt {
    /// Sets the `class` attribute, replacing any existing class list.
    fn set_class(&self, class: &str);
    /// Sets the `id` attribute.
    fn set_id(&self, id: &str);
    /// Replaces the element's text content with `text`.
    fn set_text(&self, text: &str);
    /// Replaces the element's inner HTML with `html`.
    ///
    /// # Errors
    /// This helper never fails: `set_inner_html` is infallible in `web-sys`, so
    /// the returned `Result` is always `Ok`. It exists to keep the trait
    /// uniform.
    fn set_html(&self, html: &str) -> Result<(), JsValue>;
    /// Sets attribute `attr` to `value`.
    ///
    /// # Errors
    /// Returns an error when `attr` is not a valid attribute name and the
    /// browser rejects it.
    fn set_attr(&self, attr: &str, value: &str) -> Result<(), JsValue>;
    /// Returns the value of attribute `attr`, or `None` if it is absent.
    fn get_attr(&self, attr: &str) -> Option<String>;
    /// Removes attribute `attr`.
    ///
    /// # Errors
    /// Returns an error when `attr` is not a valid attribute name and the
    /// browser rejects it.
    fn remove_attr(&self, attr: &str) -> Result<(), JsValue>;
    /// Adds `class` to the `class` attribute if it is not already present.
    ///
    /// # Errors
    /// Returns an error when the `class` attribute cannot be written, which
    /// happens only if the browser rejects the attribute update.
    fn add_class(&self, class: &str) -> Result<(), JsValue>;
    /// Removes `class` from the `class` attribute, dropping the attribute
    /// entirely when no classes remain.
    ///
    /// # Errors
    /// Returns an error when the `class` attribute cannot be written or
    /// removed, which happens only if the browser rejects the attribute
    /// update.
    fn remove_class(&self, class: &str) -> Result<(), JsValue>;
    /// Adds `class` if absent, or removes it if present.
    ///
    /// # Errors
    /// Returns an error when the `class` attribute cannot be written or
    /// removed, which happens only if the browser rejects the attribute
    /// update.
    fn toggle_class(&self, class: &str) -> Result<(), JsValue>;
    /// Returns `true` if the `class` attribute contains `class` as a whole
    /// token.
    fn has_class(&self, class: &str) -> bool;
    /// Attaches `handler` as a listener for `event`.
    ///
    /// The underlying closure is leaked so the listener remains valid for the
    /// lifetime of the element.
    ///
    /// # Errors
    /// Returns an error when the browser rejects
    /// `add_event_listener_with_callback`, for example when `event` is
    /// empty.
    fn on<F>(&self, event: &str, handler: F) -> Result<(), JsValue>
    where
        F: FnMut(web_sys::Event) + 'static;
    /// Appends `child` as the last child of this element.
    ///
    /// # Errors
    /// Returns an error when the browser refuses the insertion, for example
    /// when `child` is `self` or comes from a different document.
    fn append(&self, child: &Element) -> Result<(), JsValue>;
    /// Inserts `child` as the first child of this element, or appends it when
    /// the element has no children.
    ///
    /// # Errors
    /// Returns an error when the browser refuses the insertion, for example
    /// when `child` is `self` or comes from a different document.
    fn prepend(&self, child: &Element) -> Result<(), JsValue>;
    /// Detaches this element from its parent; a no-op when it has no parent.
    ///
    /// # Errors
    /// Returns an error when the parent node refuses the removal, which cannot
    /// happen for an element obtained from the live document tree.
    fn remove(&self) -> Result<(), JsValue>;
    /// Removes all child nodes of this element.
    fn clear(&self);
}

impl ElementExt for Element {
    fn set_class(&self, class: &str) {
        self.set_attribute("class", class).ok();
    }

    fn set_id(&self, id: &str) {
        self.set_attribute("id", id).ok();
    }

    fn set_text(&self, text: &str) {
        self.set_text_content(Some(text));
    }

    fn set_html(&self, html: &str) -> Result<(), JsValue> {
        self.set_inner_html(html);
        Ok(())
    }

    fn set_attr(&self, attr: &str, value: &str) -> Result<(), JsValue> {
        self.set_attribute(attr, value)
    }

    fn get_attr(&self, attr: &str) -> Option<String> {
        self.get_attribute(attr)
    }

    fn remove_attr(&self, attr: &str) -> Result<(), JsValue> {
        self.remove_attribute(attr)
    }

    fn add_class(&self, class: &str) -> Result<(), JsValue> {
        let current = self.get_attribute("class").unwrap_or_default();
        if !current.split_whitespace().any(|c| c == class) {
            let new_class = if current.is_empty() {
                class.to_string()
            } else {
                format!("{current} {class}")
            };
            self.set_attribute("class", &new_class)?;
        }
        Ok(())
    }

    fn remove_class(&self, class: &str) -> Result<(), JsValue> {
        let current = self.get_attribute("class").unwrap_or_default();
        let new_class: String = current
            .split_whitespace()
            .filter(|c| *c != class)
            .collect::<Vec<_>>()
            .join(" ");
        if new_class.is_empty() {
            self.remove_attribute("class")?;
        } else {
            self.set_attribute("class", &new_class)?;
        }
        Ok(())
    }

    fn toggle_class(&self, class: &str) -> Result<(), JsValue> {
        if self.has_class(class) {
            self.remove_class(class)?;
        } else {
            self.add_class(class)?;
        }
        Ok(())
    }

    fn has_class(&self, class: &str) -> bool {
        self.get_attribute("class")
            .is_some_and(|c| c.split_whitespace().any(|x| x == class))
    }

    fn on<F>(&self, event: &str, mut handler: F) -> Result<(), JsValue>
    where
        F: FnMut(web_sys::Event) + 'static
    {
        let target: EventTarget = self.clone().unchecked_into();
        let closure = Closure::wrap(Box::new(move |e: web_sys::Event| {
            handler(e);
        }) as Box<dyn FnMut(_)>);

        target.add_event_listener_with_callback(event, closure.as_ref().unchecked_ref())?;
        closure.forget();

        Ok(())
    }

    fn append(&self, child: &Element) -> Result<(), JsValue> {
        Node::append_child(self, child)
            .map(|_| ())
            .map_err(JsCast::unchecked_into)
    }

    fn prepend(&self, child: &Element) -> Result<(), JsValue> {
        self.first_child().map_or_else(
            || self.append(child),
            |first| {
                Node::insert_before(self, child, Some(&first))
                    .map(|_| ())
                    .map_err(JsCast::unchecked_into)
            }
        )
    }

    fn remove(&self) -> Result<(), JsValue> {
        self.parent_element().map_or_else(
            || Ok(()),
            |parent| {
                Node::remove_child(&parent, self)
                    .map(|_| ())
                    .map_err(JsCast::unchecked_into)
            }
        )
    }

    fn clear(&self) {
        while let Some(child) = self.first_child() {
            let _ = Node::remove_child(self, &child);
        }
    }
}

#[cfg(test)]
mod tests {
    use std::{cell::Cell, rc::Rc};

    use wasm_bindgen_test::{wasm_bindgen_test, wasm_bindgen_test_configure};
    use web_sys::Element;

    use super::*;
    use crate::dom::Document;

    wasm_bindgen_test_configure!(run_in_browser);

    fn make(tag: &str) -> Element {
        Document.create_element(tag).expect("create")
    }

    #[wasm_bindgen_test]
    #[allow(dead_code, clippy::unused_unit)]
    fn set_class_sets_attribute() {
        let el = make("div");
        el.set_class("a b");
        assert_eq!(el.get_attribute("class").as_deref(), Some("a b"));
    }

    #[wasm_bindgen_test]
    #[allow(dead_code, clippy::unused_unit)]
    fn set_id_sets_attribute() {
        let el = make("div");
        el.set_id("x");
        assert_eq!(el.get_attribute("id").as_deref(), Some("x"));
    }

    #[wasm_bindgen_test]
    #[allow(dead_code, clippy::unused_unit)]
    fn set_text_sets_text_content() {
        let el = make("p");
        el.set_text("hello");
        assert_eq!(el.text_content().as_deref(), Some("hello"));
    }

    #[wasm_bindgen_test]
    #[allow(dead_code, clippy::unused_unit)]
    fn set_html_sets_inner_html() {
        let el = make("div");
        el.set_html("<b>bold</b>").expect("ok");
        assert!(el.inner_html().contains("<b>"));
    }

    #[wasm_bindgen_test]
    #[allow(dead_code, clippy::unused_unit)]
    fn set_and_get_attr() {
        let el = make("div");
        el.set_attr("data-x", "42").expect("ok");
        assert_eq!(el.get_attr("data-x").as_deref(), Some("42"));
    }

    #[wasm_bindgen_test]
    #[allow(dead_code, clippy::unused_unit)]
    fn remove_attr_clears_value() {
        let el = make("div");
        el.set_attr("data-x", "42").expect("ok");
        el.remove_attr("data-x").expect("ok");
        assert!(el.get_attr("data-x").is_none());
    }

    #[wasm_bindgen_test]
    #[allow(dead_code, clippy::unused_unit)]
    fn add_class_appends_and_dedupes() {
        let el = make("div");
        el.add_class("a").expect("ok");
        el.add_class("b").expect("ok");
        el.add_class("a").expect("ok");
        assert_eq!(el.get_attribute("class").as_deref(), Some("a b"));
    }

    #[wasm_bindgen_test]
    #[allow(dead_code, clippy::unused_unit)]
    fn remove_class_filters_and_clears_when_empty() {
        let el = make("div");
        el.set_class("a b");
        el.remove_class("a").expect("ok");
        assert_eq!(el.get_attribute("class").as_deref(), Some("b"));
        el.remove_class("b").expect("ok");
        assert!(el.get_attribute("class").is_none());
    }

    #[wasm_bindgen_test]
    #[allow(dead_code, clippy::unused_unit)]
    fn toggle_class_round_trip() {
        let el = make("div");
        el.toggle_class("on").expect("ok");
        assert!(el.has_class("on"));
        el.toggle_class("on").expect("ok");
        assert!(!el.has_class("on"));
    }

    #[wasm_bindgen_test]
    #[allow(dead_code, clippy::unused_unit)]
    fn has_class_finds_only_whole_tokens() {
        let el = make("div");
        el.set_class("alpha beta");
        assert!(el.has_class("alpha"));
        assert!(el.has_class("beta"));
        assert!(!el.has_class("alph"));
        assert!(!el.has_class("gamma"));
    }

    #[wasm_bindgen_test]
    #[allow(dead_code, clippy::unused_unit)]
    fn on_event_fires_handler() {
        let body = Document.body().expect("body");
        let el = make("button");
        body.append_child(&el).expect("attach");

        let hits = Rc::new(Cell::new(0u32));
        let hits_cb = hits.clone();
        el.on("click", move |_| hits_cb.set(hits_cb.get() + 1))
            .expect("ok");

        let evt = web_sys::Event::new("click").expect("event");
        el.dispatch_event(&evt).expect("dispatch");

        assert_eq!(hits.get(), 1);
        el.remove();
    }

    #[wasm_bindgen_test]
    #[allow(dead_code, clippy::unused_unit)]
    fn append_places_child_at_end() {
        let parent = make("ul");
        let a = make("li");
        a.set_id("a");
        let b = make("li");
        b.set_id("b");
        parent.append(&a).expect("ok");
        parent.append(&b).expect("ok");

        let last = parent.last_element_child().expect("last");
        assert_eq!(last.id(), "b");
    }

    #[wasm_bindgen_test]
    #[allow(dead_code, clippy::unused_unit)]
    fn prepend_inserts_at_start_or_appends_when_empty() {
        let parent = make("ul");
        let a = make("li");
        a.set_id("a");
        parent.prepend(&a).expect("ok");
        assert_eq!(parent.first_element_child().expect("first").id(), "a");

        let b = make("li");
        b.set_id("b");
        parent.prepend(&b).expect("ok");
        assert_eq!(parent.first_element_child().expect("first").id(), "b");
    }

    #[wasm_bindgen_test]
    #[allow(dead_code, clippy::unused_unit)]
    fn remove_detaches_and_is_noop_without_parent() {
        let parent = make("div");
        let child = make("span");
        parent.append(&child).expect("ok");
        assert!(parent.first_element_child().is_some());
        // UFCS because `web_sys::Element::remove` also exists and shadows the
        // trait method.
        ElementExt::remove(&child).expect("detach");
        assert!(parent.first_element_child().is_none());

        let orphan = make("div");
        ElementExt::remove(&orphan).expect("noop");
    }

    fn element_child_count(parent: &Element) -> usize {
        let mut count = 0usize;
        let mut next = parent.first_element_child();
        while let Some(el) = next {
            count += 1;
            next = el.next_element_sibling();
        }
        count
    }

    #[wasm_bindgen_test]
    #[allow(dead_code, clippy::unused_unit)]
    fn clear_removes_all_children() {
        let parent = make("div");
        for _ in 0..3 {
            parent.append(&make("span")).expect("ok");
        }
        assert_eq!(element_child_count(&parent), 3);
        parent.clear();
        assert_eq!(element_child_count(&parent), 0);
    }
}