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
//! Transformers are used to extend the behavior of `pochoir` by manipulating the HTML tree of
//! templates.
//!
//! They can be used to do various, repeated tasks like selecting nodes, inserting nodes, setting
//! attributes, setting text content or collecting data. For example, they can be used to
//! **enhance the CSS** `<style>` elements used in components by providing scoped CSS,
//! minification, autoprefixing and bundling, like what is done in the `EnhancedCss` structure
//! of the `pochoir-extra` crate. Another example is the **accessibility checker** using the
//! awesome [`axe-core`](https://github.com/dequelabs/axe-core) engine, which can have its
//! JavaScript inserted in the page *only in development*.
//!
//! ```ignore
//! use pochoir::{Context, StaticMapProvider, Transformers};
//! use pochoir_extra::{EnhancedCss, AccessibilityChecker};
//!
//! let provider = StaticMapProvider::new().with_template("index", "<main><h1>Index page</h1></main>
//! <style enhanced>
//! main {
//! padding: 4rem;
//!
//! & h1 {
//! font-size: 1.2rem;
//! }
//! }
//! </style>", None);
//! let mut context = Context::new();
//!
//! let transformers = Transformers::new()
//! .with_transformer(EnhancedCss::new())
//! .with_transformer(AccessibilityChecker::new());
//!
//! let _html = provider.transform_and_compile("index", &mut context, &mut transformers)?;
//! ```
//!
//! For more advanced uses, you can, of course, develop your own transformers. The
//! `Transformer` API is built around the main `Transformer` trait containing
//! methods taking at least a mutable reference to a `Tree`. Each method can be seen
//! as an "event" and starts with `on_`: `on_before_element`, `on_after_element` and
//! `on_tree_parsed`. For example, if you want to modify some attributes of an element, you would
//! use `on_before_element`. If you want to remove an element, you would use
//! `on_after_element` (called after all children of an element are parsed). If you
//! want to modify the full tree, you would use `on_tree_parsed`.
//!
//! For instance, if you want to set the `<title>` of a page based on the first `<h1>`
//! element of the page:
//!
//! ```
//! # fn main() -> pochoir::Result<()> {
//! use pochoir::{
//! Context, Transformer, Transformers, TransformerTreeContext, TransformerResult, StaticMapProvider,
//! parser::Tree, template_engine::Escaping,
//! };
//! use std::path::Path;
//!
//! struct TitleExtractor;
//!
//! impl Transformer for TitleExtractor {
//! fn on_tree_parsed(&mut self, ctx: &mut TransformerTreeContext) -> TransformerResult{
//! // You can use `Tree::select` or `TreeRef::select` to select elements of the tree
//! // from a CSS selector (its variant, `select_all` can also be used to select *all the
//! // elements* matching a CSS selector, otherwise just the first matching
//! // element will be returned).
//! // Regarding errors, they are just ignored here
//! let Some(title_id) = ctx.tree.select("head title").expect("failed to parse the CSS selector") else { return Ok(()) };
//! let Some(first_h1_id) = ctx.tree.select("body h1").expect("failed to parse the CSS selector") else { return Ok(()) };
//!
//! let title = format!(
//! "{} | {}",
//! ctx.tree.get(first_h1_id).text(),
//! ctx.tree.get(title_id).text(),
//! );
//! ctx.tree.get_mut(title_id).set_text(title, Escaping::default());
//!
//! Ok(())
//! }
//! }
//!
//! let mut transformers = Transformers::new()
//! .with_transformer(TitleExtractor);
//!
//! let provider = StaticMapProvider::new().with_template("index", r#"
//! <!DOCTYPE HTML>
//! <html lang="en">
//! <head>
//! <title>My Website</title>
//! </head>
//! <body>
//! <h1>Index page</h1>
//! <main>
//! <p>Some content</p>
//! </main>
//! </body>
//! </html>
//! "#, None);
//! let mut context = Context::new();
//!
//! let html = provider.transform_and_compile("index", &mut context, &mut transformers)?;
//!
//! assert_eq!(html, r#"
//! <!DOCTYPE HTML>
//! <html lang="en">
//! <head>
//! <title>Index page | My Website</title>
//! </head>
//! <body>
//! <h1>Index page</h1>
//! <main>
//! <p>Some content</p>
//! </main>
//! </body>
//! </html>
//! "#);
//! # Ok(())
//! # }
//! ```
//!
//! You can also use transformers to collect some information about the tree. For
//! example you can get a list of all the components used:
//!
//! ```
//! # fn main() -> pochoir::Result<()> {
//! use pochoir::{
//! Context, Transformer, Transformers, TransformerElementContext, TransformerResult, StaticMapProvider,
//! parser::{Tree, TreeRefId},
//! };
//!
//! struct ComponentCollector<'a> {
//! list: &'a mut Vec<String>,
//! }
//!
//! impl Transformer for ComponentCollector<'_> {
//! fn on_before_element(&mut self, ctx: &mut TransformerElementContext) -> TransformerResult {
//! let Ok(element_name) = ctx.tree.get(ctx.element_id).name() else {
//! // Not an element, ignore it
//! return Ok(())
//! };
//!
//! if pochoir::is_custom_element(&element_name) {
//! self.list.push(element_name.to_string());
//! }
//!
//! Ok(())
//! }
//! }
//!
//! let mut components = vec![];
//! let mut transformers = Transformers::new()
//! .with_transformer(ComponentCollector {
//! list: &mut components,
//! });
//!
//! let provider = StaticMapProvider::new()
//! .with_template("index", "<my-heading>Hello!</my-heading><my-button />", None)
//! .with_template("my-heading", r#"<h1 class="heading"><slot></slot></h1>"#, None)
//! .with_template("my-button", "<button>Click me!</button>", None);
//! let mut context = Context::new();
//!
//! let _html = provider.transform_and_compile("index", &mut context, &mut transformers)?;
//!
//! // Transformers need to be dropped manually to avoid referencing the components
//! // while mutably borrowing them. You can also make a scope just for compilation
//! drop(transformers);
//! assert_eq!(components, vec!["my-heading".to_string(), "my-button".to_string()]);
//! # Ok(())
//! # }
//! ```
//!
//! As you can see, using buffers is the right way to define mutable state that
//! could be used after compiling.
//!
//! Note that all transformations happen before templating, so expressions and
//! statements are not yet replaced with content.
//!
//! ### Where to go next?
//!
//! - Check out [`pochoir_parser`]'s documentation to learn how to manipulate trees in
//! transformers, especially the [`Manipulating the tree`](`pochoir_parser#manipulating-the-tree`) section.
use ;
use Context;
use ;
/// An alias to an [`EventHandlerResult`].
pub type TransformerResult = EventHandlerResult;
/// A wrapper structure containing all accessible elements usable in `on_*_element` transformer methods.
/// A wrapper structure containing all accessible elements usable in `on_*_element `transformer methods.
/// Transformers are used to extend the behavior of `pochoir` by manipulating the HTML tree of
/// templates.
///
/// See [the module documentation](self).
/// A list of transformers.
///
/// It is a helper structure used to easily insert/get/remove structures implementing the
/// [`Transformer`] trait using the builder pattern or not.