report-builder 0.1.1

A simple html report builder 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
//! # Report Builder
//!
//! This crate provides tools for generating HTML reports with interactive elements such as tables,
//! plots, and other visualizations. It's designed to be used as a library within other Rust projects.
//!
//! ## Features
//!
//! - Create multi-section reports
//! - Add interactive tables with sorting, searching, and CSV export
//! - Include responsive Plotly charts
//! - Customizable styling and layout
//!
//! ## Usage
//!
//! Add `report-builder` to your `Cargo.toml` dependencies:
//!
//! ```rust,ignore
//! [dependencies]
//! report-builder = "0.1.0"  # Replace with the latest version
//! ```
//!
//! Then, use the provided structs and methods to construct your report:
//!
//! ```rust,ignore
//! use report_builder::{Report, ReportSection};
//! use maud::html;
//! use plotly::Plot;
//!
//! fn main() {
//!     let mut report = Report::new("MySoftware", "1.0", Some("logo.png"), "Analysis Report");
//!     
//!     let mut section = ReportSection::new("Results");
//!     section.add_content(html! { p { "This is a paragraph in the results section." } });
//!     
//!     // Add a plot (assuming you have a Plot object)
//!     let plot = Plot::new(); // Create and customize your plot
//!     section.add_plot(plot);
//!     
//!     report.add_section(section);
//!     report.save_to_file("report.html").unwrap();
//! }
//! ```

pub mod plots;

use chrono::Local;
use maud::{html, Markup, PreEscaped};
use plotly::Plot;
use rand::{distributions::Alphanumeric, Rng};
use std::io::Write;

/// Represents a section of the report, containing a title and multiple content blocks.
pub struct ReportSection {
    title: String,
    content_blocks: Vec<Markup>, // Multiple content blocks (text or plots)
}

impl ReportSection {
    /// Creates a new section with the given title.
    ///
    /// # Arguments
    ///
    /// * `title` - A string slice that holds the title of the section.
    pub fn new(title: &str) -> Self {
        ReportSection {
            title: title.to_string(),
            content_blocks: Vec::new(),
        }
    }

    /// Adds a block of content (text, HTML, etc.) to the section.
    ///
    /// # Arguments
    ///
    /// * `content` - A Markup object representing the content to be added.
    pub fn add_content(&mut self, content: Markup) {
        self.content_blocks.push(content);
    }

    /// Adds a Plotly plot to the section, with responsive sizing.
    ///
    /// # Arguments
    ///
    /// * `plot` - A Plot object to be added to the section.
    pub fn add_plot(&mut self, plot: Plot) {
        let plot_id: String = rand::thread_rng()
            .sample_iter(&Alphanumeric)
            .take(10)
            .map(char::from)
            .collect();

        self.content_blocks.push(html! {
            div class="plot-wrapper" {
                div id=(plot_id.clone()) class="plot-container" {
                    (PreEscaped(plot.to_inline_html(Some(&plot_id))))
                }
            }
            script {
                (PreEscaped(format!(r#"
                    function resizePlot() {{
                        let plotDiv = document.getElementById('{plot_id}');
                        if (plotDiv) {{
                            let width = window.innerWidth * 0.8;
                            Plotly.relayout(plotDiv, {{ width: width }});
                        }}
                    }}
                    window.addEventListener('resize', resizePlot);
                    resizePlot(); // Call initially
                "#)))
            }
        });
    }

    /// Render the section as HTML
    fn render(&self) -> Markup {
        html! {
            div {
                h2 { (self.title) }
                @for block in &self.content_blocks {
                    (block)
                }
            }
        }
    }
}

/// Represents the entire report, containing multiple sections and metadata.
pub struct Report {
    software_name: String,
    version: String,
    software_logo: Option<String>,
    title: String,
    sections: Vec<ReportSection>,
}

impl Report {
    /// Creates a new report with the given metadata.
    ///
    /// # Arguments
    ///
    /// * `software_name` - The name of the software generating the report.
    /// * `version` - The version of the software.
    /// * `software_logo` - An optional path to the software's logo image.
    /// * `title` - The title of the report.
    pub fn new(
        software_name: &str,
        version: &str,
        software_logo: Option<&str>,
        title: &str,
    ) -> Self {
        Report {
            software_name: software_name.to_string(),
            version: version.to_string(),
            software_logo: software_logo.map(|s| s.to_string()),
            title: title.to_string(),
            sections: Vec::new(),
        }
    }

    /// Adds a section to the report.
    ///
    /// # Arguments
    ///
    /// * `section` - A ReportSection to be added to the report.
    pub fn add_section(&mut self, section: ReportSection) {
        self.sections.push(section);
    }

    /// Render the entire report as HTML
    fn render(&self) -> Markup {
        let current_date = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();

        html! {
            (maud::DOCTYPE)
            html {
                head {
                    title { (self.title) }
                    script src="https://cdn.plot.ly/plotly-latest.min.js" {}
                    script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js" {}
                    script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js" {}
                    link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" {}
                    script src="https://cdn.datatables.net/colresize/1.0.0/dataTables.colResize.min.js" {}
                    link rel="stylesheet" href="https://cdn.datatables.net/colResize/1.0.0/css/colResize.dataTables.min.css" {}
                    script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js" {}

                    // JavaScript for DataTables and CSV export
                    script {
                        (PreEscaped(r#"
                            $(document).ready(function() {
                                let table = $('#dataTable').DataTable({
                                    paging: true,
                                    searching: true,
                                    ordering: true,
                                    scrollX: true,
                                    autoWidth: false,  // Ensures DataTables doesn't override widths
                                    colResize: {
                                        enable: true,  // Enable column resizing
                                        resizeTable: true
                                    }
                                });

                                $('#downloadCsv').on('click', function() {
                                    let csv = [];
                                    let headers = [];
                                    $('#dataTable thead th').each(function() {
                                        headers.push($(this).text());
                                    });
                                    csv.push(headers.join(','));

                                    $('#dataTable tbody tr').each(function() {
                                        let row = [];
                                        $(this).find('td').each(function() {
                                            row.push('"' + $(this).text() + '"');
                                        });
                                        csv.push(row.join(','));
                                    });

                                    let csvContent = csv.join('\n');
                                    let blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
                                    saveAs(blob, 'table_data.csv');
                                });
                            });
                        "#))
                    }

                    // JavaScript for tabs
                    script {
                        (PreEscaped(r#"
                            function showTab(tabId) {
                                document.querySelectorAll('.tab-content').forEach(function(tab) {
                                    tab.classList.remove('active');
                                });
                    
                                document.querySelectorAll('.tab').forEach(function(tab) {
                                    tab.classList.remove('active');
                                });
                    
                                document.getElementById(tabId).classList.add('active');
                                document.querySelector(`[data-tab='${tabId}']`).classList.add('active');
                            }
                        "#))
                    }


                    // CSS styles
                    // CSS for the table container
                    style {
                        (PreEscaped("
                            .table-container {
                                width: 100%;
                                overflow-x: auto; /* Enable horizontal scrolling */
                                white-space: nowrap; /* Prevent line breaks in cells */
                                border: 1px solid #ddd; /* Optional: Add a border */
                                padding: 10px;
                            }
                            table {
                                width: 100%;
                                border-collapse: collapse;
                            }
                            table.display {
                                width: 100% 
                                table-layout: fixed;
                                border-collapse: collapse;
                            }

                            .dataTables_scrollHeadInner {
                                width: 100% !important;
                            }
                        "))
                    }

                    // CSS for the plot container
                    style {
                        (PreEscaped("
                            .plot-wrapper {
                                width: 100%;
                                display: flex;
                                justify-content: center;
                                align-items: center;
                                position: relative;
                            }

                            .plot-container {
                                width: 100%;
                                // max-width: 1200px; /* Prevents it from getting too large */
                                height: 600px; /* Adjust as needed */
                                position: relative;
                                overflow: hidden; /* Prevents content from spilling */
                                // border: 1px solid #ccc; /* Optional: Helps visualize layout */
                            }
                        "))
                    }

                    // CSS for the report
                    style {
                        (PreEscaped("
                            body {
                                font-family: Arial, sans-serif;
                            }
                            .banner {
                                display: flex;
                                align-items: center;
                                justify-content: space-between;
                                padding: 15px;
                                background: linear-gradient(135deg, #4a90e2, #145da0);
                                border-radius: 12px;
                                box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
                                color: white;
                                margin-bottom: 20px;
                                max-width: 100%;
                                overflow: hidden;
                            }
                            .banner img {
                                max-height: 100px;
                                width: auto;
                                height: auto;
                                margin-right: 15px;
                            }
                            .banner-text h2 {
                                font-size: 36px;
                                margin: 0;
                                white-space: nowrap;
                            }
                            .banner-text p {
                                font-size: 16px;
                                margin: 0;
                                opacity: 0.8;
                            }
                            .tabs {
                                display: flex;
                                border-bottom: 2px solid #ddd;
                            }
                            .tab {
                                padding: 10px 20px;
                                cursor: pointer;
                                font-size: 16px;
                                font-weight: bold;
                                color: #444;
                                transition: 0.3s;
                            }
                            .tab:hover {
                                color: #000;
                            }
                            .tab.active {
                                border-bottom: 3px solid #007bff;
                                color: #007bff;
                            }
                            .tab-content {
                                display: none;
                                padding: 20px;
                            }
                            .tab-content.active {
                                display: block;
                            }
                        "))
                    }
                }

                body {
                    div class="banner" {
                        @if let Some(ref logo) = self.software_logo {
                            img src=(logo) alt="Software Logo";
                        }
                        div class="banner-text" {
                            h2 { (self.software_name) " v" (self.version) }
                            p class="timestamp" { "Generated on: " (current_date) }
                        }
                    }

                    div class="tabs" {
                        @for (i, section) in self.sections.iter().enumerate() {
                            button class="tab" data-tab=(format!("tab{}", i)) onclick=(format!("showTab('tab{}')", i)) {
                                (section.title.clone())
                            }
                        }
                    }

                    @for (i, section) in self.sections.iter().enumerate() {
                        div id=(format!("tab{}", i)) class={@if i == 0 { "tab-content active" } @else { "tab-content" }} {
                            (section.render())
                        }
                    }
                }
            }
        }
    }

    /// Saves the report to an HTML file.
    ///
    /// # Arguments
    ///
    /// * `filename` - The name of the file to save the report to.
    ///
    /// # Returns
    ///
    /// A Result indicating success or an IO error.
    pub fn save_to_file(&self, filename: &str) -> std::io::Result<()> {
        let mut file = std::fs::File::create(filename)?;
        file.write_all(self.render().into_string().as_bytes())?;
        Ok(())
    }
}

impl ToString for Report {
    fn to_string(&self) -> String {
        self.render().into_string()
    }
}

#[cfg(test)]

mod tests {
    use super::*;
    use crate::plots::plot_scatter;
    use maud::html;

    #[test]
    fn test_report() {
        let mut report = Report::new("Redeem", "1.0", Some("logo.png"), "My Report");

        let mut section1 = ReportSection::new("Section 1");
        section1.add_content(html! {
            p { "This is the first section of the report." }
        });

        // create table
        let table = html! {
            table class="display" id="dataTable" {
                thead {
                    tr {
                        th { "Name" }
                        th { "Age" }
                        th { "City" }
                        th { "Country" }
                        th { "Occupation" }
                        th { "Salary" }
                        th { "Join Date" }
                        th { "Active" }
                        th { "Actions" }
                        th { "Actions" }
                        th { "Actions" }
                    }
                }
                tbody {
                    tr {
                        td { "JohnMichaelbrunovalentinemark Beckham" }
                        td { "30" }
                        td { "New York" }
                        td { "USA" }
                        td { "Engineer" }
                        td { "100,000" }
                        td { "2022-01-01" }
                        td { "Yes" }
                        td { "Edit | Delete" }
                        td { "Edit | Delete" }
                        td { "Edit | Delete" }
                    }
                    tr {
                        td { "Jane Smith" }
                        td { "25" }
                        td { "Los Angeles" }
                        td { "USA" }
                        td { "Designer" }
                        td { "80,000" }
                        td { "2022-02-15" }
                        td { "No" }
                        td { "Edit | Delete" }
                        td { "Edit | Delete" }
                        td { "Edit | Delete" }
                    }
                }
            }
        };
        section1.add_content(table.clone());

        report.add_section(section1);

        // Add a scatter plot
        let x = vec![
            vec![1.0, 2.0, 3.0, 4.0, 5.0],
            vec![2.0, 7.0, 3.0, 9.0, 10.0],
            vec![1.0, 12.0, 13.0, 14.0, 15.0],
        ];
        let y = vec![
            vec![1.0, 2.0, 3.0, 4.0, 5.0],
            vec![6.0, 7.0, 8.0, 9.0, 10.0],
            vec![11.0, 12.0, 13.0, 14.0, 15.0],
        ];
        let labels = vec![
            "file1".to_string(),
            "file2".to_string(),
            "file3".to_string(),
        ];
        let title = "Scatter Plot";
        let x_title = "X";
        let y_title = "Y";

        let plot = plot_scatter(&x, &y, labels, title, x_title, y_title).unwrap();

        let mut section2 = ReportSection::new("Section 2");
        section2.add_plot(plot.clone());

        // add some content latin
        section2.add_content(html! {
            p { "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ac nisl..." }
        });

        section2.add_content(table);

        // add another plot (the same one)
        section2.add_plot(plot);

        report.add_section(section2);

        report.save_to_file("report.html").unwrap();
    }
}