html-streaming-editor 0.8.0

UNIX-tool like streaming editor for HTML content
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
#[cfg(test)]
mod tests;

use html_escape::{encode_double_quoted_attribute, encode_text};
use log::trace;
use snafu::ResultExt;
use std::fmt::Debug;
use std::ops::Add;

use super::pipeline::ElementProcessingPipeline;
use crate::element_creating::ElementCreatingPipeline;
use crate::html::HtmlContent;
use crate::{CommandError, CssSelectorList, SubpipelineFailedSnafu, ValueSource};

#[derive(Debug, PartialEq, Clone)]
pub(crate) enum ElementProcessingCommand<'a> {
    /// Find all nodes, beginning at the input, that match the given CSS selector and detach them
    /// and return only those
    ExtractElement(CssSelectorList<'a>),
    /// Find all nodes, beginning at the input, that match the given CSS selector
    /// and remove them from their parent nodes.
    /// Returns the input as result.
    RemoveElement(CssSelectorList<'a>),
    /// runs a sub-pipeline on each element matching the given CSS selector
    /// Returns the input as result.
    ForEach(CssSelectorList<'a>, ElementProcessingPipeline<'a>),
    /// runs a sub-pipeline and replaces each element matching the given CSS selector with the result of the pipeline
    /// Returns the input as result.
    ReplaceElement(CssSelectorList<'a>, ElementCreatingPipeline<'a>),
    /// Remove the given attribute from all currently selected nodes
    /// Returns the input as result.
    ClearAttribute(&'a str),
    /// Remove all children of the currently selected nodes
    /// Returns the input as result
    ClearContent,
    /// Add or Reset a given attribute with a new value
    /// Returns the input as result.
    SetAttribute(&'a str, ValueSource<'a>),
    /// Remove all children of the currently selected nodes and add a new text as child instead
    /// Returns the input as result.
    SetTextContent(ValueSource<'a>),
    /// adds a new text as last child
    /// Returns the input as result.
    AppendTextContent(ValueSource<'a>),
    /// adds a new comment as last child
    /// Returns the input as result.
    AppendComment(ValueSource<'a>),
    /// runs a sub-pipeline and adds the result as last child
    /// Returns the input as result.
    AppendElement(ElementCreatingPipeline<'a>),
    /// adds a new text as first child
    /// Returns the input as result.
    PrependTextContent(ValueSource<'a>),
    /// adds a new comment as first child
    /// Returns the input as result.
    PrependComment(ValueSource<'a>),
    /// runs a sub-pipeline and adds the result as first child
    /// Returns the input as result.
    PrependElement(ElementCreatingPipeline<'a>),
}

impl<'a> ElementProcessingCommand<'a> {
    /// perform the action defined by the command on the set of nodes
    /// and return the calculated results.
    /// For some command the output can be equal to the input,
    /// others change the result-set
    pub(crate) fn execute(
        &self,
        input: &Vec<rctree::Node<HtmlContent>>,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        match self {
            ElementProcessingCommand::ForEach(selector, pipeline) => {
                Self::for_each(input, selector, pipeline)
            }
            ElementProcessingCommand::ReplaceElement(selector, pipeline) => {
                Self::replace_element(input, selector, pipeline)
            }
            ElementProcessingCommand::ExtractElement(selector) => {
                Self::extract_element(input, selector)
            }
            ElementProcessingCommand::RemoveElement(selector) => {
                Self::remove_element(input, selector)
            }
            ElementProcessingCommand::ClearAttribute(attribute) => {
                Self::clear_attr(input, attribute)
            }
            ElementProcessingCommand::SetAttribute(attribute, value_source) => {
                Self::set_attr(input, attribute, value_source)
            }
            ElementProcessingCommand::ClearContent => Self::clear_content(input),
            ElementProcessingCommand::SetTextContent(value_source) => {
                Self::set_text_content(input, value_source)
            }
            ElementProcessingCommand::AppendTextContent(value_source) => {
                Self::append_text_content(input, value_source)
            }
            ElementProcessingCommand::AppendComment(value_source) => {
                Self::append_comment(input, value_source)
            }
            ElementProcessingCommand::AppendElement(pipeline) => {
                Self::append_element(input, pipeline)
            }
            ElementProcessingCommand::PrependTextContent(value_source) => {
                Self::prepend_text_content(input, value_source)
            }
            ElementProcessingCommand::PrependComment(value_source) => {
                Self::prepend_comment(input, value_source)
            }
            ElementProcessingCommand::PrependElement(pipeline) => {
                Self::prepend_element(input, pipeline)
            }
        }
    }

    fn for_each(
        input: &[rctree::Node<HtmlContent>],
        selector: &CssSelectorList<'a>,
        pipeline: &ElementProcessingPipeline,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        let queried_elements = selector.query(input);
        let _ = pipeline.run_on(queried_elements);

        Ok(input.to_owned())
    }

    fn extract_element(
        input: &[rctree::Node<HtmlContent>],
        selector: &CssSelectorList<'a>,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        trace!(
            "Running EXTRACT-ELEMENT command using selector: {:#?}",
            selector
        );

        Ok(selector
            .query(input)
            .iter()
            .map(|e| rctree::Node::clone(e).make_deep_copy())
            .collect::<Vec<_>>())
    }

    fn remove_element(
        input: &[rctree::Node<HtmlContent>],
        selector: &CssSelectorList<'a>,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        trace!("Running WITHOUT command using selector: {:#?}", selector);

        let findings = selector.query(input);

        for node in findings {
            node.detach();
        }

        Ok(input.to_owned())
    }

    fn replace_element(
        input: &[rctree::Node<HtmlContent>],
        selector: &CssSelectorList<'a>,
        pipeline: &ElementCreatingPipeline,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        trace!("Running REPLACE command using selector: {:#?}", selector);

        let queried_elements = selector.query(input);

        for element_for_replacement in queried_elements {
            let mut created_elements = pipeline
                .run_on(vec![rctree::Node::clone(&element_for_replacement)])
                .context(SubpipelineFailedSnafu)?;
            for new_element in &mut created_elements {
                let copy = new_element.make_deep_copy();
                element_for_replacement.insert_before(copy);
            }
            element_for_replacement.detach();
        }

        Ok(input.to_owned())
    }

    fn clear_attr(
        input: &Vec<rctree::Node<HtmlContent>>,
        attr_name: &str,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        trace!("Running CLEAR-ATTR command for attr: {:#?}", attr_name);
        let attribute = String::from(attr_name);

        for node in input {
            let working_copy = rctree::Node::clone(node);
            let mut data = working_copy.borrow_mut();
            data.clear_attribute(&attribute);
        }

        Ok(input.clone())
    }

    fn clear_content(
        input: &Vec<rctree::Node<HtmlContent>>,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        trace!("Running CLEAR-CONTENT command");

        for node in input {
            for child in node.children() {
                child.detach()
            }
        }

        Ok(input.clone())
    }

    fn set_attr(
        input: &Vec<rctree::Node<HtmlContent>>,
        attribute: &str,
        value_source: &ValueSource,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        trace!(
            "Running SET-ATTR command for attr: {:#?} with value: {:#?}",
            attribute,
            value_source
        );

        for node in input {
            let rendered_value = value_source.render(node).context(SubpipelineFailedSnafu)?;
            let rendered_value = rendered_value.join("");
            let rendered_value = String::from(encode_double_quoted_attribute(&rendered_value));
            let rendered_value = rendered_value.replace('\n', "\\n");

            let working_copy = rctree::Node::clone(node);
            let mut data = working_copy.borrow_mut();
            data.set_attribute(attribute, rendered_value);
        }

        Ok(input.clone())
    }

    fn set_text_content(
        input: &Vec<rctree::Node<HtmlContent>>,
        value_source: &ValueSource,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        trace!(
            "Running SET-TEXT-CONTENT command with value: {:#?}",
            value_source
        );

        for node in input {
            let rendered_value = value_source.render(node).context(SubpipelineFailedSnafu)?;
            let rendered_value = rendered_value.join("");
            let rendered_value = String::from(encode_text(&rendered_value));

            let working_copy = rctree::Node::clone(node);
            // first clear everything that was there before
            for child in node.children() {
                child.detach()
            }

            working_copy.append(rctree::Node::new(HtmlContent::Text(rendered_value)));
        }

        Ok(input.clone())
    }

    fn append_text_content(
        input: &Vec<rctree::Node<HtmlContent>>,
        value_source: &ValueSource,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        trace!(
            "Running APPEND-TEXT-CONTENT command with value: {:#?}",
            value_source
        );

        for node in input {
            let rendered_value = value_source.render(node).context(SubpipelineFailedSnafu)?;
            let rendered_value = rendered_value.join("");
            let rendered_value = String::from(encode_text(&rendered_value));

            let working_copy = rctree::Node::clone(node);
            working_copy.append(rctree::Node::new(HtmlContent::Text(rendered_value)));
        }

        Ok(input.clone())
    }

    fn append_comment(
        input: &Vec<rctree::Node<HtmlContent>>,
        value_source: &ValueSource,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        trace!(
            "Running APPEND-COMMENT command with value: {:#?}",
            value_source
        );

        for node in input {
            let rendered_value = value_source.render(node).context(SubpipelineFailedSnafu)?;
            let rendered_value = rendered_value.join("");
            let rendered_value = rendered_value.replace("--", "\\x2D\\x2D");

            let working_copy = rctree::Node::clone(node);
            working_copy.append(rctree::Node::new(HtmlContent::Comment(rendered_value)));
        }

        Ok(input.clone())
    }

    fn append_element(
        input: &Vec<rctree::Node<HtmlContent>>,
        pipeline: &ElementCreatingPipeline,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        trace!("Running APPEND-ELEMENT command");

        for node in input {
            if let Some(new_element) = pipeline
                .run_on(vec![])
                .context(SubpipelineFailedSnafu)?
                .pop()
            {
                let working_copy = rctree::Node::clone(node);
                working_copy.append(new_element);
            }
        }

        Ok(input.clone())
    }

    fn prepend_text_content(
        input: &Vec<rctree::Node<HtmlContent>>,
        value_source: &ValueSource,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        trace!(
            "Running APPEND-TEXT-CONTENT command with value: {:#?}",
            value_source
        );

        for node in input {
            let rendered_value = value_source.render(node).context(SubpipelineFailedSnafu)?;
            let rendered_value = rendered_value.join("");
            let rendered_value = String::from(encode_text(&rendered_value));

            let working_copy = rctree::Node::clone(node);
            working_copy.prepend(rctree::Node::new(HtmlContent::Text(rendered_value)));
        }

        Ok(input.clone())
    }

    fn prepend_comment(
        input: &Vec<rctree::Node<HtmlContent>>,
        value_source: &ValueSource,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        trace!(
            "Running APPEND-COMMENT command with value: {:#?}",
            value_source
        );

        for node in input {
            let rendered_value = value_source.render(node).context(SubpipelineFailedSnafu)?;
            let rendered_value = rendered_value.join("");
            let rendered_value = rendered_value.replace("--", "\\x2D\\x2D");

            let working_copy = rctree::Node::clone(node);
            working_copy.prepend(rctree::Node::new(HtmlContent::Comment(rendered_value)));
        }

        Ok(input.clone())
    }

    fn prepend_element(
        input: &Vec<rctree::Node<HtmlContent>>,
        pipeline: &ElementCreatingPipeline,
    ) -> Result<Vec<rctree::Node<HtmlContent>>, CommandError> {
        trace!("Running APPEND-ELEMENT command");

        for node in input {
            if let Some(new_element) = pipeline
                .run_on(vec![])
                .context(SubpipelineFailedSnafu)?
                .pop()
            {
                let working_copy = rctree::Node::clone(node);
                working_copy.prepend(new_element);
            }
        }

        Ok(input.clone())
    }
}

impl<'a> Add<ElementProcessingCommand<'a>> for ElementProcessingCommand<'a> {
    type Output = Vec<ElementProcessingCommand<'a>>;

    fn add(self, rhs: ElementProcessingCommand<'a>) -> Self::Output {
        vec![self, rhs]
    }
}

impl<'a> Add<Option<Vec<ElementProcessingCommand<'a>>>> for ElementProcessingCommand<'a> {
    type Output = Vec<ElementProcessingCommand<'a>>;

    fn add(self, rhs: Option<Vec<ElementProcessingCommand<'a>>>) -> Self::Output {
        if let Some(mut vec) = rhs {
            vec.insert(0, self);
            return vec;
        }

        vec![self]
    }
}