vertigo 0.11.2

Reactive Real-DOM library with SSR 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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
#![doc = include_str!("../README.md")]

//!
//! # Short-links to most commonly used things
//!
//! * DOM creation
//!   * [main] - Wraps function to be vertigo entry-point
//!   * [dom!] - Builds [DomNode] using RSX/rstml (HTML-like) syntax
//!   * [css!] - Builds [Css] using CSS-like syntax
//!   * [tw!] - Wraps tailwind class names
//!   * [component] - Wraps function to be used as component in RSX
//! * Data storing
//!   * [Value] - Read-write reactive value
//!   * [Computed] - Read-only (computed) reactive value
//!   * [LazyCache] - Lazy cache for fetched resources
//!   * [store] - Wraps function to be used as a store (singleton) generator
//! * Others
//!   * [bind!] - Auto-clones variables before use
//!   * [get_driver] - Access to browser facilities
//!   * [router::Router] - Hash or history routing

#![deny(rust_2018_idioms)]
#![cfg_attr(test, allow(clippy::panic_in_result_fn))]

mod computed;
mod css;
pub mod dev;
mod dom;
mod dom_macro;
mod driver_module;
mod exports;
pub mod external_api;
mod fetch;
mod future_box;
pub mod html_entities;
mod instant;
pub mod render;
pub mod router;
#[cfg(test)]
mod tests;
mod websocket;

// Exports from vertigo

pub use computed::{
    AutoMap, Computed, Dependencies, DropResource, Reactive, ToComputed, Value, context::Context,
};
pub use css::{
    css_structs::{Css, CssGroup},
    tailwind_class::TwClass,
};
pub use dom::{
    attr_value::{AttrValue, CssAttrValue},
    dom_comment::DomComment,
    dom_element::DomElement,
    dom_element_ref::DomElementRef,
    dom_id::DomId,
    dom_node::DomNode,
    dom_text::DomText,
    events::{ClickEvent, DropFileEvent, DropFileItem, KeyDownEvent},
};
pub use dom_macro::{AttrGroup, AttrGroupValue, EmbedDom};
pub use driver_module::{
    driver::{Driver, FetchMethod, FetchResult, get_driver, transaction},
    js_value::{
        JsJson, JsJsonContext, JsJsonDeserialize, JsJsonNumber, JsJsonSerialize, from_json, to_json,
    },
};
pub use exports::start_app;
pub use fetch::{
    lazy_cache::{self, LazyCache},
    request_builder::{RequestBody, RequestBuilder, RequestResponse},
    resource::Resource,
};
pub use instant::{Instant, InstantType};
pub use render::collection::CollectionKey;
pub use websocket::{WebsocketConnection, WebsocketMessage};

// Commonly used things
pub mod prelude {
    pub use crate::{Computed, Css, DomNode, ToComputed, Value, bind, component, css, dom};
}

// Re-export log module which can be used in vertigo plugins
pub use log;

/// Spawn a future - thus allowing to fire async functions in, for example, event handler. Handy when fetching resources from internet.
pub fn spawn(future: impl Future<Output = ()> + 'static) {
    get_driver().spawn(future)
}

// Re-export self for tests and macros used in vertigo crate
extern crate self as vertigo;

// Below re-exports from vertigo_macro

/// Allows to include a static file
///
/// This will place the file along with the rest of generated files. The macro returns a public path to the file with it's hash in name.
pub use vertigo_macro::include_static;

/// Allows to trace tailwind class names.
///
/// To use tailwind class name outside of literal tw attribute value, wrap it with `tw!` macro, so it gets traced by tailwind bundler.
///
/// Note that use of tailwind automatically adds tailwind base css sheet which zeroes various default rules.
///
/// ```rust
/// use vertigo::{dom, tw};
///
/// let my_class = tw!("flex");
///
/// dom! {
///     <div tw={my_class}>
///         <p>"One"</p>
///         <p>"Two"</p>
///     </div>
/// };
/// ```
pub use vertigo_macro::tw;

/// Allows to conveniently clone values into closure.
///
/// ```rust
/// use vertigo::{bind, dom, Value};
///
/// let count = Value::new(0);
///
/// let increment = bind!(count, |_| {
///     count.change(|value| {
///         *value += 1;
///     });
/// });
///
/// dom! {
///     <div>
///         <p>"Counter: " { count }</p>
///         <button on_click={increment}>"+"</button>
///     </div>
/// };
/// ```
///
/// Binding complex names results in last part being accessible inside:
///
/// ```rust
/// use vertigo::bind;
///
/// struct Point {
///     pub x: i32,
///     pub y: i32,
/// }
///
/// let point = Point { x: 1, y: 2 };
///
/// let callback = bind!(point.x, point.y, || {
///     println!("Point: ({x}, {y})");
/// });
/// ```
pub use vertigo_macro::bind;

/// Allows to create an event handler based on provided arguments which is wrapped in Rc
pub use vertigo_macro::bind_rc;

/// Allows to create an event handler based on provided arguments which launches an asynchronous action
pub use vertigo_macro::bind_spawn;

/// Macro for creating `JsJson` from structures and structures from `JsJson`.
///
/// Used for fetching and sending objects over the network.
///
/// Enums representation is compatible with serde's "external tagging" which is the default.
///
/// # Options
///
/// ## Container Options
///
/// * `rename_all = "..."`: Rename all fields according to the given case convention.
///   Supported values: `PascalCase`, `camelCase`, `snake_case`, `kebab-case`, `SHOUTY_SNAKE_CASE`, `UPPERCASE`, `lowercase`.
///
/// ## Field Options
///
/// * `default`: Default value for the field if it is missing in the JSON.
///   If no value is provided, `Default::default()` is used.
/// * `rename = "..."`: Rename the field to the given string.
/// * `stringify`: Serialize the field using `Display` and deserialize using `FromStr`. Useful for foreign structs.
///
/// # Example
///
/// ```rust
/// use vertigo::AutoJsJson;
///
/// #[derive(AutoJsJson)]
/// #[js_json(rename_all = "camelCase")]
/// pub struct Post {
///     pub id: i64,
///     pub name: String,
///     #[js_json(default)]
///     pub visible: bool,
///     #[js_json(stringify)]
///     pub status: Status,
/// }
///
/// #[derive(Clone)]
/// pub enum Status {
///     Active,
///     Inactive,
/// }
///
/// impl std::fmt::Display for Status {
///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
///         match self {
///             Status::Active => write!(f, "active"),
///             Status::Inactive => write!(f, "inactive"),
///         }
///     }
/// }
///
/// impl std::str::FromStr for Status {
///     type Err = String;
///
///     fn from_str(s: &str) -> Result<Self, Self::Err> {
///         match s {
///             "active" => Ok(Status::Active),
///             "inactive" => Ok(Status::Inactive),
///             _ => Err("Invalid status".to_string()),
///         }
///     }
/// }
///
/// let post = Post {
///     id: 1,
///     name: "Hello".to_string(),
///     visible: true,
///     status: Status::Active,
/// };
///
/// let js_json = vertigo::to_json(post);
///
/// let post2 = vertigo::from_json::<Post>(js_json);
/// ```
///
/// # Creating newtypes for foreign types
///
/// Option `stringify` can be used for newtypes to serialize them using `Display` and deserialize using `FromStr`.
///
/// ```rust
/// use vertigo::AutoJsJson;
///
/// // Let's say we have a type that implements `Display` and `FromStr`
/// // but doesn't support JsJson serialization
/// struct ForeignType(i64);
///
/// # impl std::fmt::Display for ForeignType {
/// #     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
/// #         write!(f, "{}", self.0)
/// #     }
/// # }
/// # impl std::str::FromStr for ForeignType {
/// #     type Err = String;
/// #
/// #     fn from_str(s: &str) -> Result<Self, Self::Err> {
/// #         Ok(ForeignType(s.parse().map_err(|_| "Invalid value".to_string())?))
/// #     }
/// # }
///
/// // We can use `stringify` option to serialize it
/// // using `Display` and deserialize using `FromStr`
/// #[derive(AutoJsJson)]
/// struct MyType(#[js_json(stringify)] ForeignType);
pub use vertigo_macro::AutoJsJson;

/// Macro which transforms a provided function into a component that can be used in [dom!] macro
///
/// ```rust
/// use vertigo::prelude::*;
///
/// #[component]
/// pub fn Header(name: Value<String>) {
///     dom! {
///         <div>"Hello" {name}</div>
///     }
/// }
///
/// let name = Value::new("world".to_string());
///
/// dom! {
///     <div>
///        <Header name={name} />
///     </div>
/// };
/// ```
///
/// ```rust
/// use vertigo::{bind, component, dom, AttrGroup, Value};
///
/// #[component]
/// pub fn Input<'a>(label: &'a str, value: Value<String>, input: AttrGroup) {
///     let on_input = bind!(value, |new_value: String| {
///         value.set(new_value);
///     });
///
///     dom! {
///         <div>
///             {label}
///             <input {value} {on_input} {..input} />
///         </div>
///     }
/// }
///
/// let value = Value::new("world".to_string());
///
/// dom! {
///     <div>
///        <Input label="Hello" {value} input:name="hello_value" />
///     </div>
/// };
/// ```
///
/// Note: [AttrGroup] allows to dynamically pass arguments to some child node.
pub use vertigo_macro::component;

/// Macro that allows to evaluate pseudo-JavaScript expressions.
///
/// Example 1:
///
/// ```rust
/// use vertigo::js;
///
/// let referrer = js!{ document.referrer };
/// ```
///
/// Example 2:
///
/// ```rust
/// # use vertigo::js;
/// let max_y = js!{ window.scrollMaxY };
/// js! { window.scrollTo(0, max_y) };
/// ```
///
/// Can be used with [DomElementRef]:
///
/// ```rust
/// use vertigo::{js, dom_element};
///
/// let node = dom_element! { <input /> };
/// let node_ref = node.get_ref();
/// js! { #node_ref.focus() };
/// ```
///
/// Passing an object as an argument is a little more complicated, but possible:
///
/// ```rust
/// # use vertigo::js;
/// js! {
///     window.scrollTo(
///         vec![
///             ("top", 100000.into()),
///             ("behavior", "smooth".into()),
///         ]
///     )
/// };
/// ```
#[macro_export]
macro_rules! js {
    // Convert `#ref_node.anything` into `#[ref_node] anything` which can be handled by js_inner macro.
    ( #$ident:ident.$expr:expr ) => {
        $crate::js_inner! { #[$ident] $expr }
    };
    // Otherwise be transparent.
    ( $expr:expr ) => {
        $crate::js_inner! { $expr }
    };
}

/// Used internally by [js!] macro.
pub use vertigo_macro::js_inner;

/// Marco that marks an entry point of the app
///
/// Note: Html, head and body tags are required by vertigo to properly take over the DOM
///
/// Note 2: When using external tailwind, make sure the source `tailwind.css` file is in the same directory as usage of this macro.
///
/// ```rust
/// use vertigo::prelude::*;
///
/// #[vertigo::main]
/// fn app() -> DomNode {
///     dom! {
///         <html>
///             <head/>
///             <body>
///                 <div>"Hello world"</div>
///             </body>
///         </html>
///     }
/// }
/// ```
pub use vertigo_macro::main;

/// Allows to create [DomNode] using RSX/rstml (HTML-like) syntax.
///
/// Simple DOM with a param embedded:
///
/// ```rust
/// use vertigo::dom;
///
/// let value = "world";
///
/// dom! {
///     <div>
///         <h3>"Hello " {value} "!"</h3>
///         <p>"Good morning!"</p>
///     </div>
/// };
/// ```
///
/// Mapping and embedding an `Option`:
///
/// ```rust
/// use vertigo::dom;
///
/// let name = "John";
/// let occupation = Some("Lumberjack");
///
/// dom! {
///     <div>
///         <h3>"Hello " {name} "!"</h3>
///         {..occupation.map(|occupation| dom! { <p>"Occupation: " {occupation}</p> })}
///     </div>
/// };
/// ```
///
/// Note the spread operator which utilizes the fact that `Option` is iterable in Rust.
pub use vertigo_macro::dom;

/// Allows to create [DomElement] using HTML tags.
///
/// Unlike [DomNode] generated by the [dom!] macro, it can't generate multiple nodes at top level,
/// but allows to mangle with the outcome a little more, for example using [DomElement::add_child].
pub use vertigo_macro::dom_element;

/// Version of [dom!] macro that additionally emits compiler warning with generated code.
pub use vertigo_macro::dom_debug;

/// Allows to create [Css] styles for usage in [dom!] macro.
///
/// ```rust
/// use vertigo::{css, dom};
///
/// let green_on_red = css! {"
///     color: green;
///     background-color: red;
/// "};
///
/// dom! {
///    <div css={green_on_red}>"Tomato stem"</div>
/// };
/// ```
///
/// ```rust
/// use vertigo::{css, Css, dom};
///
/// fn css_menu_item(active: bool) -> Css {
///     let bg_color = if active { "lightblue" } else { "lightgreen" };
///
///     css! {"
///         cursor: pointer;
///         background-color: {bg_color};
///
///         :hover {
///             text-decoration: underline;
///         }
///     "}
/// }
///
/// dom! {
///     <a css={css_menu_item(true)}>"Active item"</a>
///     <a css={css_menu_item(false)}>"Inactive item"</a>
/// };
/// ```
///
/// See [tooltip demo](https://github.com/vertigo-web/vertigo/blob/master/demo/app/src/app/styling/tooltip.rs) for more complex example.
pub use vertigo_macro::css;

/// Constructs a CSS block that can be manually pushed into existing [Css] styles instance.
///
/// ```rust
/// use vertigo::{css, css_block};
///
/// let mut green_style = css! {"
///     color: green;
/// "};
///
/// green_style.push_str(
///     css_block! {"
///         font-style: italic;
///    "}
/// );
/// ```
pub use vertigo_macro::css_block;

/// Wraps a function generating a resource out of parameters, and creates a store.
///
/// Accessing the store from different locations uses always the same store
/// as data is kept using [LocalKey](std::thread::LocalKey).
///
/// ```rust
/// use vertigo::{AutoJsJson, LazyCache, RequestBuilder, store};
///
/// #[derive(AutoJsJson, PartialEq)]
/// struct CommentModel {
///     id: i32,
///     name: String,
/// }
///
/// #[store]
/// fn get_post(post_id: &String) -> LazyCache<Vec<CommentModel>> {
///     RequestBuilder
///         ::get(format!("https://jsonplaceholder.typicode.com/posts/{post_id}/comments"))
///         .ttl_minutes(10)
///         .lazy_cache(|status, body| {
///             if status == 200 {
///                 Some(body.into::<Vec<CommentModel>>())
///             } else {
///                 None
///             }
///         })
/// }
pub use vertigo_macro::store;