domrs 0.0.17

Document builder and serializer
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
use crate::common::{get_indentation, ToText};
use crate::{HtmlAttribute, DEFAULT_HTML_INDENT, DEFAULT_HTML_OFFSET};
use std::fmt;
use std::fmt::{Debug, Display, Write};

/// A structure representing HTML element.
#[derive(Debug, Clone)]
pub struct HtmlElement {
  /// Name of the element, will appear as a tag name in HTML document.
  name: String,
  /// Attributes of the element.
  attributes: Vec<HtmlAttribute>,
  /// Textual content of the element.
  content: Option<String>,
  /// Child elements.
  children: Vec<HtmlElement>,
  /// Flag indicating if closing tag will be serialized.
  hide_closing_tag: bool,
  /// Flag indicating if the element is serialized without indentation.
  no_indent: bool,
  /// Flag indicating if closing tag will be expanded when element is empty.
  always_expand: bool,
}

impl HtmlElement {
  /// Creates a new HTML element with specified tag name.
  pub fn new(name: &str) -> Self {
    Self {
      name: name.to_string(),
      attributes: vec![],
      content: None,
      children: vec![],
      hide_closing_tag: false,
      no_indent: false,
      always_expand: false,
    }
  }

  pub fn no_indent(mut self) -> Self {
    self.no_indent = true;
    self
  }

  pub fn hide_closing_tag(mut self) -> Self {
    self.hide_closing_tag = true;
    self
  }

  pub fn always_expand(mut self) -> Self {
    self.always_expand = true;
    self
  }

  /// Sets an attribute of the HTML element.
  pub fn attribute<N, V>(mut self, name: N, value: V) -> Self
  where
    N: ToString,
    V: ToString,
  {
    self.set_attribute(name, value);
    self
  }

  /// Sets an attribute of the HTML element.
  pub fn set_attribute<N, V>(&mut self, name: N, value: V)
  where
    N: ToString,
    V: ToString,
  {
    self.attributes.push(HtmlAttribute::new(name, value))
  }

  /// Sets a class attribute of the HTML element.
  pub fn class(mut self, class: &str) -> Self {
    self.set_class(class);
    self
  }

  /// Sets a class attribute of the HTML element.
  pub fn set_class(&mut self, class: &str) {
    self.attributes.push(HtmlAttribute::new("class", class))
  }

  /// Sets a style attribute of the HTML element.
  pub fn style(mut self, style: &str) -> Self {
    self.set_style(style);
    self
  }

  /// Sets a style attribute of the HTML element.
  pub fn set_style(&mut self, style: &str) {
    self.attributes.push(HtmlAttribute::new("style", style))
  }

  /// Adds a child element.
  pub fn child(mut self, child: impl Into<HtmlElement>) -> Self {
    self.add_child(child);
    self
  }

  /// Adds a child element.
  pub fn add_child(&mut self, child: impl Into<HtmlElement>) {
    self.children.push(child.into());
  }

  /// Adds an optional child element.
  pub fn opt_child(mut self, opt_child: Option<HtmlElement>) -> Self {
    self.add_opt_child(opt_child);
    self
  }

  /// Adds an optional child element.
  pub fn add_opt_child(&mut self, opt_child: Option<HtmlElement>) {
    if let Some(child) = opt_child {
      self.children.push(child);
    }
  }

  /// Adds multiple children elements.
  pub fn children(mut self, children: &[HtmlElement]) -> Self {
    self.add_children(children);
    self
  }

  /// Adds multiple children elements.
  pub fn add_children(&mut self, children: &[HtmlElement]) {
    for child in children {
      self.children.push(child.clone());
    }
  }

  /// Sets the content of the HTML element.
  pub fn content(mut self, content: &str) -> Self {
    self.set_content(content);
    self
  }

  /// Sets the content of the HTML element.
  pub fn set_content(&mut self, content: &str) {
    self.content = content.to_string().into();
  }

  /// Converts the element to its textual representation and saves in provided string buffer.
  pub(crate) fn write(&self, mut offset: usize, indent: usize, buffer: &mut String) {
    if self.no_indent && offset >= indent {
      offset -= indent;
    }
    let _ = write!(buffer, "{}<{}", get_indentation(self.no_indent, offset), self.name);
    for attribute in &self.attributes {
      let _ = write!(buffer, "{}", attribute);
    }
    if self.children.is_empty() {
      if let Some(content) = &self.content {
        let line_count = content.lines().count();
        if line_count > 1 {
          let _ = write!(buffer, ">");
          for line in content.lines() {
            let _ = write!(buffer, "\n{}{}", get_indentation(false, offset + indent), line);
          }
          let _ = write!(buffer, "\n{}</{}>", get_indentation(false, offset), self.name);
        } else {
          let _ = write!(buffer, ">{}</{}>", content, self.name);
        }
      } else {
        let _ = write!(
          buffer,
          "{}",
          if self.always_expand {
            format!("></{}>", self.name)
          } else if self.hide_closing_tag {
            ">".to_string()
          } else {
            "/>".to_string()
          }
        );
      }
    } else {
      let _ = writeln!(buffer, ">");
      for (i, child) in self.children.iter().enumerate() {
        if i > 0 {
          let _ = writeln!(buffer);
        }
        child.write(offset + indent, indent, buffer);
      }
      let _ = write!(buffer, "\n{}</{}>", get_indentation(self.no_indent, offset), self.name);
    }
  }
}

impl ToText for HtmlElement {
  /// Converts [HtmlElement] into text with specified offset and indent.
  fn to_text(&self, offset: usize, indent: usize) -> String {
    let mut buffer = String::new();
    self.write(offset, indent, &mut buffer);
    buffer
  }
}

impl Display for HtmlElement {
  /// Implements [Display] for [HtmlElement].
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(f, "{}", self.to_text(DEFAULT_HTML_OFFSET, DEFAULT_HTML_INDENT))
  }
}

/// Implementation of commonly used HTML elements.
impl HtmlElement {
  /// Creates `<h1>` HTML element. The [section heading] level 1 element.
  ///
  /// [section heading]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements
  ///
  /// # Example
  ///
  /// ```
  /// # use domrs::HtmlElement;
  /// let h = HtmlElement::h1("Heading level 1");
  /// assert_eq!("<h1>Heading level 1</h1>", h.to_string());
  /// ```
  pub fn h1(content: &str) -> Self {
    Self::new("h1").content(content)
  }

  /// Creates `<h2>` HTML element. The [section heading] level 2 element.
  ///
  /// [section heading]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements
  ///
  /// # Example
  ///
  /// ```
  /// # use domrs::HtmlElement;
  /// let h = HtmlElement::h2("Heading level 2");
  /// assert_eq!("<h2>Heading level 2</h2>", h.to_string());
  /// ```
  pub fn h2(content: &str) -> Self {
    Self::new("h2").content(content)
  }

  /// Creates `<h3>` HTML element. The [section heading] level 3 element.
  ///
  /// [section heading]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements
  ///
  /// # Example
  ///
  /// ```
  /// # use domrs::HtmlElement;
  /// let h = HtmlElement::h3("Heading level 3");
  /// assert_eq!("<h3>Heading level 3</h3>", h.to_string());
  /// ```
  pub fn h3(content: &str) -> Self {
    Self::new("h3").content(content)
  }

  /// Creates `<h4>` HTML element. The [section heading] level 4 element.
  ///
  /// [section heading]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements
  ///
  /// # Example
  ///
  /// ```
  /// # use domrs::HtmlElement;
  /// let h = HtmlElement::h4("Heading level 4");
  /// assert_eq!("<h4>Heading level 4</h4>", h.to_string());
  /// ```
  pub fn h4(content: &str) -> Self {
    Self::new("h4").content(content)
  }

  /// Creates `<h5>` HTML element. The [section heading] level 5 element.
  ///
  /// [section heading]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements
  ///
  /// # Example
  ///
  /// ```
  /// # use domrs::HtmlElement;
  /// let h = HtmlElement::h5("Heading level 5");
  /// assert_eq!("<h5>Heading level 5</h5>", h.to_string());
  /// ```
  pub fn h5(content: &str) -> Self {
    Self::new("h5").content(content)
  }

  /// Creates `<h6>` HTML element. The [section heading] level 6 element.
  ///
  /// [section heading]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements
  ///
  /// # Example
  ///
  /// ```
  /// # use domrs::HtmlElement;
  /// let h = HtmlElement::h6("Heading level 6");
  /// assert_eq!("<h6>Heading level 6</h6>", h.to_string());
  /// ```
  pub fn h6(content: &str) -> Self {
    Self::new("h6").content(content)
  }

  /// Creates `<br>` HTML element. The [line break] element.
  ///
  /// [line break]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/br
  ///
  /// # Example
  ///
  /// ```
  /// # use domrs::HtmlElement;
  /// let br = HtmlElement::br();
  /// assert_eq!("<br/>", br.to_string());
  /// ```
  pub fn br() -> Self {
    Self::new("br")
  }

  /// Creates `<div>` HTML element. The [content division] element.
  ///
  /// [content division]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div
  ///
  /// # Example
  ///
  /// ```
  /// # use domrs::HtmlElement;
  /// let div = HtmlElement::div();
  /// assert_eq!("<div></div>", div.to_string());
  /// ```
  pub fn div() -> Self {
    Self::new("div").always_expand()
  }

  /// Creates `<span>` HTML element. The [content span] element.
  ///
  /// [content span]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span
  ///
  /// # Example
  ///
  /// ```
  /// # use domrs::HtmlElement;
  /// let span = HtmlElement::span();
  /// assert_eq!("<span></span>", span.to_string());
  /// ```
  pub fn span() -> Self {
    Self::new("span").always_expand()
  }
}

/// Creates `<h1>` HTML element. The section heading level 1 element.
///
/// # Example
///
/// ```
/// # use domrs::h1;
/// # use domrs::HtmlElement;
/// let h = h1!("Heading level 1");
/// assert_eq!("<h1>Heading level 1</h1>", h.to_string());
/// ```
#[macro_export]
macro_rules! h1 {
  ($content:expr) => {
    HtmlElement::h1($content)
  };
}

/// Creates `<h2>` HTML element. The section heading level 2 element.
///
/// # Example
///
/// ```
/// # use domrs::h2;
/// # use domrs::HtmlElement;
/// let h = h2!("Heading level 2");
/// assert_eq!("<h2>Heading level 2</h2>", h.to_string());
/// ```
#[macro_export]
macro_rules! h2 {
  ($content:expr) => {
    HtmlElement::h2($content)
  };
}

/// Creates `<h3>` HTML element. The section heading level 3 element.
///
/// # Example
///
/// ```
/// # use domrs::h3;
/// # use domrs::HtmlElement;
/// let h = h3!("Heading level 3");
/// assert_eq!("<h3>Heading level 3</h3>", h.to_string());
/// ```
#[macro_export]
macro_rules! h3 {
  ($content:expr) => {
    HtmlElement::h3($content)
  };
}

/// Creates `<h4>` HTML element. The section heading level 4 element.
///
/// # Example
///
/// ```
/// # use domrs::h4;
/// # use domrs::HtmlElement;
/// let h = h4!("Heading level 4");
/// assert_eq!("<h4>Heading level 4</h4>", h.to_string());
/// ```
#[macro_export]
macro_rules! h4 {
  ($content:expr) => {
    HtmlElement::h4($content)
  };
}

/// Creates `<h5>` HTML element. The section heading level 5 element.
///
/// # Example
///
/// ```
/// # use domrs::h5;
/// # use domrs::HtmlElement;
/// let h = h5!("Heading level 5");
/// assert_eq!("<h5>Heading level 5</h5>", h.to_string());
/// ```
#[macro_export]
macro_rules! h5 {
  ($content:expr) => {
    HtmlElement::h5($content)
  };
}

/// Creates `<h6>` HTML element. The section heading level 6 element.
///
/// # Example
///
/// ```
/// # use domrs::h6;
/// # use domrs::HtmlElement;
/// let h = h6!("Heading level 6");
/// assert_eq!("<h6>Heading level 6</h6>", h.to_string());
/// ```
#[macro_export]
macro_rules! h6 {
  ($content:expr) => {
    HtmlElement::h6($content)
  };
}

#[macro_export]
macro_rules! div {
  ($class:expr, $content:expr) => {
    HtmlElement::div().class($class).content($content)
  };
  ($content:expr) => {
    HtmlElement::div().content($content)
  };
  () => {
    HtmlElement::div()
  };
}

#[macro_export]
macro_rules! span {
  ($class:expr, $content:expr) => {
    HtmlElement::span().class($class).content($content)
  };
  ($content:expr) => {
    HtmlElement::span().content($content)
  };
  () => {
    HtmlElement::span()
  };
}