sidoc-html5

Check-in Differences
Login

Check-in Differences

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Difference From sidoc-html5-0.1.0 To sidoc-html5-0.1.1

2024-11-07
14:58
Change log. Leaf check-in: 85777bcf71 user: jan tags: trunk
14:45
Fix test. check-in: c89299ba90 user: jan tags: sidoc-html5-0.1.1, trunk
14:09
Happy pedantic clippy. Add map_opt(). check-in: 550f0e8901 user: jan tags: trunk
2022-10-26
03:42
Start working on adding some extra (optional) validation. check-in: c6bd771b40 user: jan tags: trunk
2022-10-21
00:22
Reformat. check-in: a29cded2b3 user: jan tags: sidoc-html5-0.1.0, trunk
00:21
Add rustfmt. check-in: 510ce9565b user: jan tags: trunk

Changes to .efiles.

1



2

Cargo.toml



src/lib.rs


>
>
>

>
1
2
3
4
5
6
Cargo.toml
README.md
www/index.md
www/changelog.md
src/lib.rs
tests/gentests.rs

Changes to Cargo.toml.

1
2
3
4
5

6
7
8
9
10
11
12
13

14
15
16







17
18

19






20
[package]
name = "sidoc-html5"
version = "0.1.0"
edition = "2021"
license = "0BSD"

categories = [ "web-programming" ]
keywords = [ "sidoc", "html" ]
repository = "https://repos.qrnch.tech/pub/sidoc-html5"
description = "Helper functions for generating HTML5 documents for sidoc."
exclude = [
  ".efiles",
  ".fossil-settings",
  ".fslckout",

  "rustfmt.toml"
]








[dependencies]
html-escape = { version = "0.2.11" }

sidoc = { version = "0.1.0" }









|


>
|







>



>
>
>
>
>
>
>

|
>
|
>
>
>
>
>
>

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
[package]
name = "sidoc-html5"
version = "0.1.1"
edition = "2021"
license = "0BSD"
# https://crates.io/category_slugs
categories = [ "template-engine", "web-programming" ]
keywords = [ "sidoc", "html" ]
repository = "https://repos.qrnch.tech/pub/sidoc-html5"
description = "Helper functions for generating HTML5 documents for sidoc."
exclude = [
  ".efiles",
  ".fossil-settings",
  ".fslckout",
  "bacon.toml",
  "rustfmt.toml"
]

# https://doc.rust-lang.org/cargo/reference/manifest.html#the-badges-section
[badges]
maintenance = { status = "passively-maintained" }

[features]
extra-validation = [ "lazy_static" ]

[dependencies]
html-escape = { version = "0.2.13" }
lazy_static = { version = "1.5.0", optional = true }
sidoc = { version = "0.1.1" }

[lints.clippy]
all = { level = "warn", priority = -1 }
pedantic = { level = "warn", priority = -1 }
nursery = { level = "warn", priority = -1 }
cargo = { level = "warn", priority = -1 }

Added README.md.









>
>
>
>
1
2
3
4
# sidoc-html5

HTML5 generation wrapper for sidoc.

Added bacon.toml.





























































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
# This is a configuration file for the bacon tool
#
# Complete help on configuration: https://dystroy.org/bacon/config/
# 
# You may check the current default at
#   https://github.com/Canop/bacon/blob/main/defaults/default-bacon.toml

default_job = "clippy-all"

[jobs.check]
command = ["cargo", "check", "--color", "always"]
need_stdout = false

[jobs.check-all]
command = ["cargo", "check", "--all-targets", "--color", "always"]
need_stdout = false

# Run clippy on the default target
[jobs.clippy]
command = [
    "cargo", "clippy",
    "--color", "always",
]
need_stdout = false

# Run clippy on all targets
# To disable some lints, you may change the job this way:
#    [jobs.clippy-all]
#    command = [
#        "cargo", "clippy",
#        "--all-targets",
#        "--color", "always",
#    	 "--",
#    	 "-A", "clippy::bool_to_int_with_if",
#    	 "-A", "clippy::collapsible_if",
#    	 "-A", "clippy::derive_partial_eq_without_eq",
#    ]
# need_stdout = false
[jobs.clippy-all]
command = [
    "cargo", "clippy",
    "--all-targets",
    "--color", "always",
]
need_stdout = false

# This job lets you run
# - all tests: bacon test
# - a specific test: bacon test -- config::test_default_files
# - the tests of a package: bacon test -- -- -p config
[jobs.test]
command = [
    "cargo", "test", "--color", "always",
    "--", "--color", "always", # see https://github.com/Canop/bacon/issues/124
]
need_stdout = true

[jobs.nextest]
command = [
    "cargo", "nextest", "run",
    "--color", "always",
    "--hide-progress-bar", "--failure-output", "final"
]
need_stdout = true
analyzer = "nextest"

[jobs.doc]
command = ["cargo", "doc", "--color", "always", "--no-deps"]
need_stdout = false

# If the doc compiles, then it opens in your browser and bacon switches
# to the previous job
[jobs.doc-open]
command = ["cargo", "doc", "--color", "always", "--no-deps", "--open"]
need_stdout = false
on_success = "back" # so that we don't open the browser at each change

# You can run your application and have the result displayed in bacon,
# if it makes sense for this crate.
# Don't forget the `--color always` part or the errors won't be
# properly parsed.
[jobs.run]
command = [
    "cargo", "run",
    "--color", "always",
    # put launch parameters for your program behind a `--` separator
]
need_stdout = true
allow_warnings = true
background = true

# Run your long-running application (eg server) and have the result displayed in bacon.
# For programs that never stop (eg a server), `background` is set to false
# to have the cargo run output immediately displayed instead of waiting for
# program's end.
# 'on_change_strategy' is set to `kill_then_restart` to have your program restart
# on every change (an alternative would be to use the 'F5' key manually in bacon).
# If you often use this job, it makes sense to override the 'r' key by adding
# a binding `r = job:run-long` at the end of this file .
[jobs.run-long]
command = [
    "cargo", "run",
    "--color", "always",
    # put launch parameters for your program behind a `--` separator
]
need_stdout = true
allow_warnings = true
background = false
on_change_strategy = "kill_then_restart"

# This parameterized job runs the example of your choice, as soon
# as the code compiles.
# Call it as
#    bacon ex -- my-example
[jobs.ex]
command = ["cargo", "run", "--color", "always", "--example"]
need_stdout = true
allow_warnings = true

# You may define here keybindings that would be specific to
# a project, for example a shortcut to launch a specific job.
# Shortcuts to internal functions (scrolling, toggling, etc.)
# should go in your personal global prefs.toml file instead.
[keybindings]
# alt-m = "job:my-job"
c = "job:clippy-all" # comment this to have 'c' run clippy on only the default target

Changes to src/lib.rs.

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
use std::borrow::Cow;














enum AttrType<'a> {
  KV(&'a str, String),
  Bool(&'a str),
  Data(&'a str, String),
  BoolData(&'a str)
}

pub struct Element<'a> {
  tag: &'a str,
  classes: Vec<&'a str>,
  alst: Vec<AttrType<'a>>
}

impl<'a> Element<'a> {

  pub fn new(tag: &'a str) -> Self {
    Element {
      tag,
      classes: Vec::new(),
      alst: Vec::new()
    }
  }

  /// Assign a class to this element.
  ///
  /// ```
  /// use sidoc_html5::Element;
  /// let element = Element::new("p")
  ///   .class("warning");
  /// ```
  #[inline]

  pub fn class(mut self, cls: &'a str) -> Self {
    self.classes.push(cls);
    self
  }














  /// Assign a "flag attribute" to the element.
  ///
  /// Flag attributes do not have (explicit) values, and are used to mark
  /// elements as `selected` or `checked` and such.
  ///
  /// ```
  /// use sidoc_html5::Element;
  /// let element = Element::new("input")
  ///   .raw_attr("type", "checkbox")
  ///   .flag("checked");
  /// ```
  #[inline]

  pub fn flag(mut self, key: &'a str) -> Self {
    self.alst.push(AttrType::Bool(key));
    self
  }







  /// Conditionally add a flag attribute.
  ///
  /// Flag attributes do not have (explicit) values, and are used to mark
  /// elements as `selected` or `checked` and such.
  ///
  /// ```
  /// use sidoc_html5::Element;
  /// for id in &[1, 2, 3] {
  ///   let element = Element::new("option")
  ///     .flag_if(*id == 3, "selected");
  /// }
  /// ```
  #[inline]




  pub fn flag_if(mut self, f: bool, key: &'a str) -> Self {
    if f {
      self.alst.push(AttrType::Bool(key));
    }
    self
  }

  /// Add an attribute.
  ///
  /// The attribute value is escaped as needed.
  ///
  /// Note: If the value is guaranteed not to require escaping then prefer the
  /// [`Element::raw_attr()`] method instead.
  ///
  /// ```
  /// use sidoc_html5::Element;
  /// let elem = Element::new("input")
  ///   .attr("name", "foo");
  /// ```
  #[inline]

  pub fn attr(mut self, key: &'a str, value: impl AsRef<str>) -> Self {
    debug_assert!(
      key != "class",
      "Use the dedicated .class() method to add classes to elements"
    );
    self.alst.push(AttrType::KV(
      key,
      html_escape::encode_double_quoted_attribute(value.as_ref()).to_string()
    ));
    self
  }

  /// Conditionally add an attribute.
  ///
  /// The value is escaped as needed.
  #[inline]




  pub fn attr_if<V>(self, flag: bool, key: &'a str, value: V) -> Self
  where
    V: AsRef<str>
  {
    debug_assert!(
      key != "class",
      "Use the dedicated .class() method to add classes to elements"

>
>
>
>
>
>
>
>
>
>
>
>
>















>
|















>




>
>
>
>
>
>
>
>
>
>
>
>
>













>




>
>
>
>
>
>














>
>
>
>




















>
















>
>
>
>







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
use std::borrow::Cow;

#[cfg(feature = "extra-validation")]
use std::collections::HashSet;

#[cfg(feature = "extra-validation")]
lazy_static::lazy_static! {
  static ref VOID_ELEMENTS: HashSet<&'static str> = {
    HashSet::from([
      "area", "base", "br", "col", "embed", "hr", "img", "input", "link",
      "meta", "param", "source", "track", "wbr"
    ])
  };
}

enum AttrType<'a> {
  KV(&'a str, String),
  Bool(&'a str),
  Data(&'a str, String),
  BoolData(&'a str)
}

pub struct Element<'a> {
  tag: &'a str,
  classes: Vec<&'a str>,
  alst: Vec<AttrType<'a>>
}

impl<'a> Element<'a> {
  #[must_use]
  pub const fn new(tag: &'a str) -> Self {
    Element {
      tag,
      classes: Vec::new(),
      alst: Vec::new()
    }
  }

  /// Assign a class to this element.
  ///
  /// ```
  /// use sidoc_html5::Element;
  /// let element = Element::new("p")
  ///   .class("warning");
  /// ```
  #[inline]
  #[must_use]
  pub fn class(mut self, cls: &'a str) -> Self {
    self.classes.push(cls);
    self
  }

  /// Assign a class to this element in-place.
  ///
  /// ```
  /// use sidoc_html5::Element;
  /// let mut element = Element::new("p");
  /// element.class_r("warning");
  /// ```
  #[inline]
  pub fn class_r(&mut self, cls: &'a str) -> &mut Self {
    self.classes.push(cls);
    self
  }

  /// Assign a "flag attribute" to the element.
  ///
  /// Flag attributes do not have (explicit) values, and are used to mark
  /// elements as `selected` or `checked` and such.
  ///
  /// ```
  /// use sidoc_html5::Element;
  /// let element = Element::new("input")
  ///   .raw_attr("type", "checkbox")
  ///   .flag("checked");
  /// ```
  #[inline]
  #[must_use]
  pub fn flag(mut self, key: &'a str) -> Self {
    self.alst.push(AttrType::Bool(key));
    self
  }

  #[inline]
  pub fn flag_r(&mut self, key: &'a str) -> &mut Self {
    self.alst.push(AttrType::Bool(key));
    self
  }

  /// Conditionally add a flag attribute.
  ///
  /// Flag attributes do not have (explicit) values, and are used to mark
  /// elements as `selected` or `checked` and such.
  ///
  /// ```
  /// use sidoc_html5::Element;
  /// for id in &[1, 2, 3] {
  ///   let element = Element::new("option")
  ///     .flag_if(*id == 3, "selected");
  /// }
  /// ```
  #[inline]
  /*
  #[deprecated(since = "0.1.2", note = "Use .mod_if() with .flag() instead.")]
  */
  #[must_use]
  pub fn flag_if(mut self, f: bool, key: &'a str) -> Self {
    if f {
      self.alst.push(AttrType::Bool(key));
    }
    self
  }

  /// Add an attribute.
  ///
  /// The attribute value is escaped as needed.
  ///
  /// Note: If the value is guaranteed not to require escaping then prefer the
  /// [`Element::raw_attr()`] method instead.
  ///
  /// ```
  /// use sidoc_html5::Element;
  /// let elem = Element::new("input")
  ///   .attr("name", "foo");
  /// ```
  #[inline]
  #[must_use]
  pub fn attr(mut self, key: &'a str, value: impl AsRef<str>) -> Self {
    debug_assert!(
      key != "class",
      "Use the dedicated .class() method to add classes to elements"
    );
    self.alst.push(AttrType::KV(
      key,
      html_escape::encode_double_quoted_attribute(value.as_ref()).to_string()
    ));
    self
  }

  /// Conditionally add an attribute.
  ///
  /// The value is escaped as needed.
  #[inline]
  /*
  #[deprecated(since = "0.1.2", note = "Use .mod_if() with .attr() instead.")]
  */
  #[must_use]
  pub fn attr_if<V>(self, flag: bool, key: &'a str, value: V) -> Self
  where
    V: AsRef<str>
  {
    debug_assert!(
      key != "class",
      "Use the dedicated .class() method to add classes to elements"
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
  ///
  /// ```
  /// use sidoc_html5::Element;
  /// let elem = Element::new("tr")
  ///   .data_attr("name", "foo");
  /// ```
  #[inline]

  pub fn data_attr(mut self, key: &'a str, value: impl AsRef<str>) -> Self {
    debug_assert!(
      key != "class",
      "Use the dedicated .class() method to add classes to elements"
    );
    self.alst.push(AttrType::Data(
      key,
      html_escape::encode_double_quoted_attribute(value.as_ref()).to_string()
    ));
    self
  }


























  /// Conditionally add a boolean `data-` attribute.
  ///
  /// Add a `data-foo=true` attribute to an element:
  /// ```
  /// use sidoc_html5::Element;
  /// let val = 7;
  /// let elem = Element::new("p")
  ///   .data_flag_if(val > 5, "foo");
  /// ```
  #[inline]







  pub fn data_flag_if(mut self, flag: bool, key: &'a str) -> Self {
    if flag {
      self.alst.push(AttrType::BoolData(key));
    }
    self
  }








>











>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>











>
>
>
>
>
>
>







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
  ///
  /// ```
  /// use sidoc_html5::Element;
  /// let elem = Element::new("tr")
  ///   .data_attr("name", "foo");
  /// ```
  #[inline]
  #[must_use]
  pub fn data_attr(mut self, key: &'a str, value: impl AsRef<str>) -> Self {
    debug_assert!(
      key != "class",
      "Use the dedicated .class() method to add classes to elements"
    );
    self.alst.push(AttrType::Data(
      key,
      html_escape::encode_double_quoted_attribute(value.as_ref()).to_string()
    ));
    self
  }

  #[inline]
  pub fn data_attr_r(
    &mut self,
    key: &'a str,
    value: impl AsRef<str>
  ) -> &mut Self {
    debug_assert!(
      key != "class",
      "Use the dedicated .class() method to add classes to elements"
    );
    self.alst.push(AttrType::Data(
      key,
      html_escape::encode_double_quoted_attribute(value.as_ref()).to_string()
    ));
    self
  }


  #[inline]
  #[must_use]
  pub fn data_flag(mut self, key: &'a str) -> Self {
    self.alst.push(AttrType::BoolData(key));
    self
  }

  /// Conditionally add a boolean `data-` attribute.
  ///
  /// Add a `data-foo=true` attribute to an element:
  /// ```
  /// use sidoc_html5::Element;
  /// let val = 7;
  /// let elem = Element::new("p")
  ///   .data_flag_if(val > 5, "foo");
  /// ```
  #[inline]
  /*
  #[deprecated(
    since = "0.1.2",
    note = "Use .mod_if() with .data_flag() instead."
  )]
  */
  #[must_use]
  pub fn data_flag_if(mut self, flag: bool, key: &'a str) -> Self {
    if flag {
      self.alst.push(AttrType::BoolData(key));
    }
    self
  }

164
165
166
167
168
169
170


171
172
173
174
175
176
177
  /// let something = Some("something");
  /// let nothing: Option<&str> = None;
  /// let elem = Element::new("form")
  ///   .optattr("id", something)
  ///   .optattr("name", nothing);
  /// ```
  #[inline]


  pub fn optattr<T>(mut self, key: &'a str, value: Option<T>) -> Self
  where
    T: AsRef<str>
  {
    if let Some(v) = value.as_ref() {
      self.alst.push(AttrType::KV(
        key,







>
>







241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
  /// let something = Some("something");
  /// let nothing: Option<&str> = None;
  /// let elem = Element::new("form")
  ///   .optattr("id", something)
  ///   .optattr("name", nothing);
  /// ```
  #[inline]
  #[must_use]
  #[allow(clippy::needless_pass_by_value)]
  pub fn optattr<T>(mut self, key: &'a str, value: Option<T>) -> Self
  where
    T: AsRef<str>
  {
    if let Some(v) = value.as_ref() {
      self.alst.push(AttrType::KV(
        key,
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
  /// let elem = Element::new("p")
  ///   .optattr_map("id", something, |v| {
  ///     // Have a value -- format it and append "-aboo" to it.
  ///     format!("{}-aboo", v)
  ///   });
  /// ```
  #[inline]





  pub fn optattr_map<T, F>(
    mut self,
    key: &'a str,

    value: Option<T>,

    f: F



  ) -> Self
  where
    F: Fn(&T) -> String
  {
    if let Some(v) = value.as_ref() {
      let s = f(v);
      self.alst.push(AttrType::KV(
        key,
        html_escape::encode_double_quoted_attribute(&s).to_string()
      ));
    }
    self
  }

  /// If an an optional input value is set, apply a function on the contained
  /// value.
  #[inline]




  pub fn opt_map<T, F>(self, value: Option<&'_ T>, f: F) -> Self
  where
    F: Fn(Self, &T) -> Self
  {








    if let Some(v) = value.as_ref() {
      f(self, v)
    } else {
      self
    }
  }
























  /// Conditionally call a function to add an attribute with a generated value.
  ///
  /// ```
  /// use sidoc_html5::Element;
  /// let sv = vec!["foo".to_string(), "bar".to_string()];
  /// Element::new("body")
  ///   .map_attr_if(!sv.is_empty(), "data-mylist", &sv, |v: &Vec<String>| {
  ///     v.join(",")
  ///   });
  /// ```
  #[inline]

  pub fn map_attr_if<T, F>(
    self,
    flag: bool,
    key: &'a str,
    data: &T,
    f: F
  ) -> Self
  where
    F: Fn(&T) -> String
  {
    if flag {
      self.attr(key, f(data))
    } else {
      self
    }
  }












































}

/// Methods that don't transform the input.
impl<'a> Element<'a> {
  /// Add an attribute.
  ///
  /// The attribute value is not escaped.
  ///
  /// ```
  /// use sidoc_html5::Element;
  /// let elem = Element::new("form")
  ///   .raw_attr("id", "foo");
  /// ```
  #[inline]


  pub fn raw_attr(mut self, key: &'a str, value: impl ToString) -> Self {
    debug_assert!(
      key != "class",
      "Use the dedicated .class() method to add classes to elements"
    );
    self.alst.push(AttrType::KV(key, value.to_string()));
    self







>
>
>
>
>
|
|
|
>
|
>
|
>
>
>
|
















>
>
>
>




>
>
>
>
>
>
>
>






>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>












>
















>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>














>
>







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
  /// let elem = Element::new("p")
  ///   .optattr_map("id", something, |v| {
  ///     // Have a value -- format it and append "-aboo" to it.
  ///     format!("{}-aboo", v)
  ///   });
  /// ```
  #[inline]
  /*
  #[deprecated(since = "0.1.2", note = "Use .map_attr() instead.")]
  */
  #[must_use]
  #[allow(clippy::needless_pass_by_value)]
  pub fn optattr_map<T, F>(self, key: &'a str, value: Option<T>, f: F) -> Self
  where
    F: Fn(&T) -> String
  {
    self.map_attr(key, value, f)
  }

  #[inline]
  #[must_use]
  #[allow(clippy::needless_pass_by_value)]
  pub fn map_attr<T, F>(mut self, key: &'a str, value: Option<T>, f: F) -> Self
  where
    F: Fn(&T) -> String
  {
    if let Some(v) = value.as_ref() {
      let s = f(v);
      self.alst.push(AttrType::KV(
        key,
        html_escape::encode_double_quoted_attribute(&s).to_string()
      ));
    }
    self
  }

  /// If an an optional input value is set, apply a function on the contained
  /// value.
  #[inline]
  /*
  #[deprecated(since = "0.1.2", note = "Use .map() instead.")]
  */
  #[must_use]
  pub fn opt_map<T, F>(self, value: Option<&'_ T>, f: F) -> Self
  where
    F: Fn(Self, &T) -> Self
  {
    self.map(value, f)
  }

  #[must_use]
  pub fn map<T, F>(self, value: Option<&'_ T>, f: F) -> Self
  where
    F: Fn(Self, &T) -> Self
  {
    if let Some(v) = value.as_ref() {
      f(self, v)
    } else {
      self
    }
  }

  /// If an an optional input value is set, apply a function on the contained
  /// value.
  ///
  /// ```
  /// use sidoc_html5::Element;
  /// let opt_str = Some("enabled");
  /// Element::new("body")
  ///   .map_opt(opt_str, |this, s| {
  ///     this.flag(s)
  ///   });
  /// ```
  #[inline]
  #[must_use]
  pub fn map_opt<T, F>(self, o: Option<T>, f: F) -> Self
  where
    F: FnOnce(Self, T) -> Self
  {
    match o {
      Some(t) => f(self, t),
      None => self
    }
  }

  /// Conditionally call a function to add an attribute with a generated value.
  ///
  /// ```
  /// use sidoc_html5::Element;
  /// let sv = vec!["foo".to_string(), "bar".to_string()];
  /// Element::new("body")
  ///   .map_attr_if(!sv.is_empty(), "data-mylist", &sv, |v: &Vec<String>| {
  ///     v.join(",")
  ///   });
  /// ```
  #[inline]
  #[must_use]
  pub fn map_attr_if<T, F>(
    self,
    flag: bool,
    key: &'a str,
    data: &T,
    f: F
  ) -> Self
  where
    F: Fn(&T) -> String
  {
    if flag {
      self.attr(key, f(data))
    } else {
      self
    }
  }


  /// Conditionally call a closure to modify `self` if a predicate is true.
  ///
  /// ```
  /// use sidoc_html5::Element;
  /// let someval = 42;
  /// Element::new("body")
  ///   .map_if(someval == 42, |obj| obj.flag("selected"));
  /// ```
  #[inline]
  #[must_use]
  pub fn map_if<F>(self, flag: bool, f: F) -> Self
  where
    F: FnOnce(Self) -> Self
  {
    if flag {
      f(self)
    } else {
      self
    }
  }

  /// Conditionally call a closure to modify `self`, in-place, if a predicate
  /// is true.
  ///
  /// ```
  /// use sidoc_html5::Element;
  /// let someval = 42;
  /// let mut e = Element::new("body");
  /// e.mod_if(someval == 42, |obj| {
  ///   obj.flag_r("selected");
  /// });
  /// ```
  #[inline]
  pub fn mod_if<F>(&mut self, flag: bool, f: F) -> &mut Self
  where
    F: FnOnce(&mut Self)
  {
    if flag {
      f(self);
    }
    self
  }
}

/// Methods that don't transform the input.
impl<'a> Element<'a> {
  /// Add an attribute.
  ///
  /// The attribute value is not escaped.
  ///
  /// ```
  /// use sidoc_html5::Element;
  /// let elem = Element::new("form")
  ///   .raw_attr("id", "foo");
  /// ```
  #[inline]
  #[must_use]
  #[allow(clippy::needless_pass_by_value)]
  pub fn raw_attr(mut self, key: &'a str, value: impl ToString) -> Self {
    debug_assert!(
      key != "class",
      "Use the dedicated .class() method to add classes to elements"
    );
    self.alst.push(AttrType::KV(key, value.to_string()));
    self
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
  /// let something = Some(&ss);
  /// let nothing = None::<&String>;
  /// let elem = Element::new("form")
  ///   .raw_optattr("id", something)
  ///   .raw_optattr("name", nothing);
  /// ```
  #[inline]

  pub fn raw_optattr<T>(mut self, key: &'a str, value: Option<&T>) -> Self
  where
    T: ToString
  {
    if let Some(v) = value.as_ref() {
      self.alst.push(AttrType::KV(key, v.to_string()));
    }
    self
  }

  /// Add an attribute if a condition is true.
  ///
  /// The attribute value is not escaped.
  #[inline]


  pub fn raw_attr_if(
    self,
    flag: bool,
    key: &'a str,
    value: impl ToString
  ) -> Self {
    debug_assert!(







>














>
>







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
  /// let something = Some(&ss);
  /// let nothing = None::<&String>;
  /// let elem = Element::new("form")
  ///   .raw_optattr("id", something)
  ///   .raw_optattr("name", nothing);
  /// ```
  #[inline]
  #[must_use]
  pub fn raw_optattr<T>(mut self, key: &'a str, value: Option<&T>) -> Self
  where
    T: ToString
  {
    if let Some(v) = value.as_ref() {
      self.alst.push(AttrType::KV(key, v.to_string()));
    }
    self
  }

  /// Add an attribute if a condition is true.
  ///
  /// The attribute value is not escaped.
  #[inline]
  #[allow(clippy::needless_pass_by_value)]
  #[must_use]
  pub fn raw_attr_if(
    self,
    flag: bool,
    key: &'a str,
    value: impl ToString
  ) -> Self {
    debug_assert!(
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353

      if !self.classes.is_empty() {
        ret.push(format!(r#"class="{}""#, self.classes.join(" ")));
      }

      let it = self.alst.iter().map(|a| match a {
        AttrType::KV(k, v) => {
          format!(r#"{}="{}""#, k, v)
        }
        AttrType::Bool(a) => a.to_string(),
        AttrType::Data(k, v) => {
          format!(r#"data-{}="{}""#, k, v)
        }
        AttrType::BoolData(a) => {
          format!("data-{}=true", a)
        }
      });

      ret.extend(it);

      Some(ret)
    }







|

|

|


|







506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527

      if !self.classes.is_empty() {
        ret.push(format!(r#"class="{}""#, self.classes.join(" ")));
      }

      let it = self.alst.iter().map(|a| match a {
        AttrType::KV(k, v) => {
          format!(r#"{k}="{v}""#)
        }
        AttrType::Bool(a) => (*a).to_string(),
        AttrType::Data(k, v) => {
          format!(r#"data-{k}="{v}""#)
        }
        AttrType::BoolData(a) => {
          format!("data-{a}")
        }
      });

      ret.extend(it);

      Some(ret)
    }
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
  /// let mut bldr = sidoc::Builder::new();
  /// Element::new("div")
  ///   .sub(&mut bldr, |bldr| {
  ///     Element::new("br")
  ///       .add_empty(bldr);
  /// });
  /// ```




  pub fn sub<F>(self, bldr: &mut sidoc::Builder, mut f: F)
  where
    F: FnMut(&mut sidoc::Builder)
  {



    if let Some(lst) = self.gen_attr_list() {
      bldr.scope(
        format!("<{} {}>", self.tag, lst.join(" ")),
        Some(format!("</{}>", self.tag))
      );
    } else {
      let stag = format!("<{}>", self.tag);
      let etag = format!("</{}>", self.tag);
      bldr.scope(stag, Some(etag));
    }

    f(bldr);

    bldr.exit();
  }
}


/// Methods inserting element into a sidoc context.
impl<'a> Element<'a> {
  /// Consume `self` and add a empty tag representation of element to a sidoc
  /// builder.
  ///
  /// An empty/void tag comes is one which does not have a closing tag:
  /// `<tagname foo="bar">`.




  #[inline]
  pub fn add_empty(self, bldr: &mut sidoc::Builder) {



    let line = if let Some(alst) = self.gen_attr_list() {
      format!("<{} {}>", self.tag, alst.join(" "))
    } else {
      format!("<{}>", self.tag)
    };

    bldr.line(line);







>
>
>
>




>
>
>
















>








>
>
>
>


>
>
>







536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
  /// let mut bldr = sidoc::Builder::new();
  /// Element::new("div")
  ///   .sub(&mut bldr, |bldr| {
  ///     Element::new("br")
  ///       .add_empty(bldr);
  /// });
  /// ```
  ///
  /// # Panics
  /// If the `extra-validation` feature is enabled, panic if the tag name is
  /// not a known "void" element.
  pub fn sub<F>(self, bldr: &mut sidoc::Builder, mut f: F)
  where
    F: FnMut(&mut sidoc::Builder)
  {
    #[cfg(feature = "extra-validation")]
    assert!(!VOID_ELEMENTS.contains(self.tag));

    if let Some(lst) = self.gen_attr_list() {
      bldr.scope(
        format!("<{} {}>", self.tag, lst.join(" ")),
        Some(format!("</{}>", self.tag))
      );
    } else {
      let stag = format!("<{}>", self.tag);
      let etag = format!("</{}>", self.tag);
      bldr.scope(stag, Some(etag));
    }

    f(bldr);

    bldr.exit();
  }
}


/// Methods inserting element into a sidoc context.
impl<'a> Element<'a> {
  /// Consume `self` and add a empty tag representation of element to a sidoc
  /// builder.
  ///
  /// An empty/void tag comes is one which does not have a closing tag:
  /// `<tagname foo="bar">`.
  ///
  /// # Panics
  /// If the `extra-validation` feature is enabled, panic if the tag name is
  /// not a known "void" element.
  #[inline]
  pub fn add_empty(self, bldr: &mut sidoc::Builder) {
    #[cfg(feature = "extra-validation")]
    assert!(VOID_ELEMENTS.contains(self.tag));

    let line = if let Some(alst) = self.gen_attr_list() {
      format!("<{} {}>", self.tag, alst.join(" "))
    } else {
      format!("<{}>", self.tag)
    };

    bldr.line(line);
417
418
419
420
421
422
423




424
425



426
427
428
429
430
431
432
  ///   .raw_attr("rows", 8)
  ///   .raw_attr("cols", 32)
  ///   .add_content("This is the text content", &mut bldr);
  /// ```
  ///
  /// The example above should generate:
  /// `<textarea rows="8" cols="32">This is the text content</textarea>`




  #[inline]
  pub fn add_content(self, text: &str, bldr: &mut sidoc::Builder) {



    let line = if let Some(alst) = self.gen_attr_list() {
      format!(
        "<{} {}>{}</{}>",
        self.tag,
        alst.join(" "),
        html_escape::encode_text(text),
        self.tag







>
>
>
>


>
>
>







606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
  ///   .raw_attr("rows", 8)
  ///   .raw_attr("cols", 32)
  ///   .add_content("This is the text content", &mut bldr);
  /// ```
  ///
  /// The example above should generate:
  /// `<textarea rows="8" cols="32">This is the text content</textarea>`
  ///
  /// # Panics
  /// If the `extra-validation` feature is enabled, panic if the tag name is
  /// not a known "void" element.
  #[inline]
  pub fn add_content(self, text: &str, bldr: &mut sidoc::Builder) {
    #[cfg(feature = "extra-validation")]
    assert!(!VOID_ELEMENTS.contains(self.tag));

    let line = if let Some(alst) = self.gen_attr_list() {
      format!(
        "<{} {}>{}</{}>",
        self.tag,
        alst.join(" "),
        html_escape::encode_text(text),
        self.tag
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
  /// let mut bldr = sidoc::Builder::new();
  /// let elem = Element::new("button")
  ///   .add_raw_content("Do Stuff", &mut bldr);
  /// ```
  ///
  /// The example above should generate:
  /// `<button>Do Stuff</button>`




  #[inline]
  pub fn add_raw_content(self, text: &str, bldr: &mut sidoc::Builder) {



    let line = if let Some(alst) = self.gen_attr_list() {
      format!("<{} {}>{}</{}>", self.tag, alst.join(" "), text, self.tag)
    } else {
      format!("<{}>{}</{}>", self.tag, text, self.tag)
    };
    bldr.line(line);
  }




  pub fn add_opt_content<T>(self, text: &Option<T>, bldr: &mut sidoc::Builder)
  where
    T: AsRef<str>
  {



    let t = if let Some(t) = text {

      html_escape::encode_text(t)
    } else {
      Cow::from("")
    };
    let line = if let Some(alst) = self.gen_attr_list() {
      format!("<{} {}>{}</{}>", self.tag, alst.join(" "), t, self.tag)
    } else {
      format!("<{}>{}</{}>", self.tag, t, self.tag)
    };
    bldr.line(line);
  }





  pub fn add_scope(self, bldr: &mut sidoc::Builder) {



    let line = if let Some(alst) = self.gen_attr_list() {
      format!("<{} {}>", self.tag, alst.join(" "))
    } else {
      format!("<{}>", self.tag)
    };
    bldr.scope(line, Some(format!("</{}>", self.tag)));
  }
}

// vim: set ft=rust et sw=2 ts=2 sts=2 cinoptions=2 tw=79 :







>
>
>
>


>
>
>








>
>
>




>
>
>
|
>
|
<
<
<








>
>
>
>

>
>
>










648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684



685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
  /// let mut bldr = sidoc::Builder::new();
  /// let elem = Element::new("button")
  ///   .add_raw_content("Do Stuff", &mut bldr);
  /// ```
  ///
  /// The example above should generate:
  /// `<button>Do Stuff</button>`
  ///
  /// # Panics
  /// If the `extra-validation` feature is enabled, panic if the tag name is
  /// not a known "void" element.
  #[inline]
  pub fn add_raw_content(self, text: &str, bldr: &mut sidoc::Builder) {
    #[cfg(feature = "extra-validation")]
    assert!(!VOID_ELEMENTS.contains(self.tag));

    let line = if let Some(alst) = self.gen_attr_list() {
      format!("<{} {}>{}</{}>", self.tag, alst.join(" "), text, self.tag)
    } else {
      format!("<{}>{}</{}>", self.tag, text, self.tag)
    };
    bldr.line(line);
  }

  /// # Panics
  /// If the `extra-validation` feature is enabled, panic if the tag name is
  /// not a known "void" element.
  pub fn add_opt_content<T>(self, text: &Option<T>, bldr: &mut sidoc::Builder)
  where
    T: AsRef<str>
  {
    #[cfg(feature = "extra-validation")]
    assert!(!VOID_ELEMENTS.contains(self.tag));

    let t = text
      .as_ref()
      .map_or_else(|| Cow::from(""), |t| html_escape::encode_text(t));



    let line = if let Some(alst) = self.gen_attr_list() {
      format!("<{} {}>{}</{}>", self.tag, alst.join(" "), t, self.tag)
    } else {
      format!("<{}>{}</{}>", self.tag, t, self.tag)
    };
    bldr.line(line);
  }


  /// # Panics
  /// If the `extra-validation` feature is enabled, panic if the tag name is
  /// not a known "void" element.
  pub fn add_scope(self, bldr: &mut sidoc::Builder) {
    #[cfg(feature = "extra-validation")]
    assert!(!VOID_ELEMENTS.contains(self.tag));

    let line = if let Some(alst) = self.gen_attr_list() {
      format!("<{} {}>", self.tag, alst.join(" "))
    } else {
      format!("<{}>", self.tag)
    };
    bldr.scope(line, Some(format!("</{}>", self.tag)));
  }
}

// vim: set ft=rust et sw=2 ts=2 sts=2 cinoptions=2 tw=79 :

Added tests/gentests.rs.













































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
use std::sync::Arc;

use sidoc::{Builder, RenderContext};

use sidoc_html5::Element;

#[test]
fn data_attr() {
  let mut bldr = Builder::new();

  let e = Element::new("br").data_attr("hello", "world");
  e.add_empty(&mut bldr);

  let mut r = RenderContext::new();
  let doc = bldr.build().unwrap();
  r.doc("root", Arc::new(doc));
  let buf = r.render("root").unwrap();

  assert_eq!(buf, "<br data-hello=\"world\">\n");
}

// vim: set ft=rust et sw=2 ts=2 sts=2 cinoptions=2 tw=79 :

Added www/changelog.md.













































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Change Log

⚠️  indicates a breaking change.

## [Unreleased]

[Details](/vdiff?from=sidoc-html5-0.1.0&to=trunk)

### Added

- Add `Element::map_opt()`.

### Changed

### Removed

---

## [0.1.0] - 2020-09-12

Initial release

Added www/index.md.



































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# sidoc-html5

HTML5 generation wrapper for sidoc.


## Change log

The details of changes can always be found in the timeline, but for a
high-level view of changes between released versions there's a manually
maintained [Change Log](./changelog.md).


## Project Status

sidoc-html5 is passively maintained.  It will receive updates and fixes and
needed, but is currently considered to be feature complete.