summaryrefslogtreecommitdiff
path: root/src/lib.rs
blob: 30d6d59cecb11fc28358e7d4b8e8346ef5d42bff (plain)
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
#![recursion_limit="1024"]
extern crate wee_alloc;
extern crate console_error_panic_hook;
use std::collections::HashSet;
use name::{NameView,Name};
use address::{AddressView,Address,AddressType};
use genpdf::Element as _;
use genpdf::{elements, style, fonts};
use qrcodegen::QrCode;
use qrcodegen::QrCodeEcc;
use wasm_bindgen::prelude::*;
use yew::prelude::*;
use vcard::{VCard, VCardError};
use std::panic;

mod name;
mod address;

// Use `wee_alloc` as the global allocator.
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;

fn init() {
    panic::set_hook(Box::new(console_error_panic_hook::hook));
}

#[derive(Clone)]
pub struct Download {
    pub file_name: String,
    pub content: String,
    pub mime_type: MimeType,
}

impl Download {
    pub fn as_data_link(&self) -> String {
        let data = base64::encode(&*self.content);
        let uri_component: String = js_sys::encode_uri_component(&data).into();

        format!("data:{};base64,{}", self.mime_type.as_text(), uri_component)
    }
}

#[derive(Clone, Copy)]
pub enum MimeType {
    PDF,
    VCard,
    SVG,
}

impl MimeType {
    pub fn as_text(&self) -> &str {
        match self {
            MimeType::PDF => "application/pdf",
            MimeType::VCard => "text/vcard",
            MimeType::SVG => "image/svg+xml",
        }
    }
}

#[derive(Clone, Copy)]
pub enum DownloadOption {
    PDF,
    VCard,
    QrCode,
}

pub struct MainView {
    link: ComponentLink<Self>,
    error: Vec<String>,
    name: Name,
    work_address: Address,
    home_address: Address,
    download: Option<Download>,
    selected_option: DownloadOption,
}

pub enum Msg {
    UpdateName(Name),
    UpdateHomeAddress(Address),
    UpdateWorkAddress(Address),
    Generate(DownloadOption),
    Nope,
}

impl Component for MainView {
    type Message = Msg;
    type Properties = ();

    fn create(_props: Self::Properties, link: ComponentLink<Self>) -> Self {
        MainView { 
            link, 
            error: vec![], 
            name: Name::new(), 
            work_address: Address::new_with_type(AddressType::Work), 
            home_address: Address::new_with_type(AddressType::Home), 
            download: None, 
            selected_option: DownloadOption::VCard 
        }
    }

    fn update(&mut self, msg: Self::Message) -> ShouldRender {
        self.error.clear();
        match msg {
            Msg::UpdateName(value) => {
                self.name = value;
                self.link.send_message(Msg::Generate(self.selected_option));
            },
            Msg::UpdateHomeAddress(value) => {
                self.home_address = value;
                self.link.send_message(Msg::Generate(self.selected_option));
            },
            Msg::UpdateWorkAddress(value) => {
                self.work_address = value;
                self.link.send_message(Msg::Generate(self.selected_option));
            },
            Msg::Generate(option) => {
                self.selected_option = option;

                let vcard_content = match self.generate_vcard() {
                    Ok(vcard) => Some(vcard.to_string()),
                    Err(VCardError::FormatError(err)) => {
                        self.error.push(err.to_string());
                        None
                    }
                    Err(VCardError::EmptyFormatName) => {
                        self.error.push(String::from("At least one of the name fields should be filled out."));
                        None
                    }
                };

                match option {
                    DownloadOption::VCard => {
                        if vcard_content.is_some() {
                            self.download = Some(
                                Download { 
                                    file_name: format!("{}.vcs", self.name.formatted_name()), 
                                    content: vcard_content.unwrap().to_string(), 
                                    mime_type: MimeType::VCard,
                                }
                            )
                        }
                    }
                    DownloadOption::QrCode => {
                        if vcard_content.is_some() {
                            match QrCode::encode_text(vcard_content.as_ref().unwrap(), QrCodeEcc::Low) {
                                Ok(qr) => self.download = Some(
                                    Download {
                                        file_name: format!("QR-Code VCard {}.svg", self.name.formatted_name()),
                                        content: qr.to_svg_string(4),
                                        mime_type: MimeType::SVG,
                                    }
                                ),
                                Err(_) => self.error.push(String::from("Sorry, VCard is too long!")),
                            };
                        }
                    }
                    DownloadOption::PDF => {
                        match self.generate_pdf() {
                            Ok(pdf) => self.download = Some(
                                Download {
                                    file_name: format!("Visitenkarten {}.pdf", self.name.formatted_name()),
                                    content: pdf,
                                    mime_type: MimeType::PDF,
                                }
                            ),
                            Err(_) => self.error.push(String::from("Unexpected error while generating the PDF. Please contact me about it.")),
                        }
                    }
                }
            }
            Msg::Nope => return false,
        };
        if self.error.len() > 0 {
            self.download = None;
        }
        true
    }

    fn change(&mut self, _props: Self::Properties) -> ShouldRender {
        false
    }

    fn view(&self) -> Html {

        let download_options = self.link.callback(|e: ChangeData|
            match e {
                ChangeData::Select(v) => match v.value().as_str() {
                    "vcard" => Msg::Generate(DownloadOption::VCard),
                    "pdf" => Msg::Generate(DownloadOption::PDF),
                    "qrcode" => Msg::Generate(DownloadOption::QrCode),
                    _ => Msg::Nope,
                },
                _ => Msg::Nope,
            }
        );

        html!{
            <>
                <main>
                    <section class="hero">
                        <div class="hero-body">
                            <div class="container is-max-widescreen">
                                <h1 class="title">{ "A Generator for vCards" }</h1>
                                <h2 class="subtitle">{ "Supports generating vCards (.vcf), print-ready PDF business cards and QR Codes" }</h2>
                            </div>
                        </div>
                    </section>

                    <section class="section">
                        <div class="container is-max-widescreen">

                            { self.render_errors() }

                            <NameView oninput=self.link.callback(|n: Name| Msg::UpdateName(n)) />

                            <AddressView address_type=AddressType::Home oninput=self.link.callback(|a: Address| Msg::UpdateHomeAddress(a)) />

                            <AddressView address_type=AddressType::Work oninput=self.link.callback(|a: Address| Msg::UpdateWorkAddress(a)) />

                            <div class="block level-left">
                                <div class="select level-item">
                                    <select id="download_options" onchange=download_options>
                                        <option value="vcard">{ "VCard (.vcf)" }</option>
                                        <option value="pdf">{ "Print-ready PDF" }</option>
                                        <option value="qrcode">{ "QR Code" }</option>
                                    </select>
                                </div>
                                
                                { self.render_download() }
                            </div>

                            <div class="block">
                                { self.render_preview() }
                            </div>

                        </div>
                    </section>
                </main>

                <footer class="footer">
                    <div class="content has-text-centered">
                        <p>
                            <strong>{ "VCard Generator" }</strong> { " by " } <a href="https://jelemux.dev">{ "Jeremias Weber" }</a>{ ". "}
                            { "The source code is licenced " } <a href="http://opensource.org/licenses/mit-license.php">{ "MIT" }</a>{"."}
                        </p>
                    </div>
                </footer>
            </>
        }
    }
}

impl MainView {
    fn render_errors(&self) -> Html {
        html!{
            <>
                {
                    for self.error.iter().map(|err| 
                        html!{
                            <div class="notification is-danger is-light">
                                { err }
                            </div>
                        }
                    ) 
                }
            </>
        }
    }
    fn render_download(&self) -> Html {
        if self.download.is_some() {
            let download = self.download.as_ref().unwrap();

            html!{
                <a href=download.as_data_link() download=download.file_name class="button is-primary level-item" >
                    { "Download" }
                </a>
            }
        } else {
            html!{}
        }
    }
    fn render_preview(&self) -> Html {
        if self.download.is_some() {
            let download = self.download.as_ref().unwrap();

            match download.mime_type {
                MimeType::PDF => html!{
                    <iframe src=download.as_data_link() alt="PDF Preview" width="400" height="550"/>
                },
                MimeType::VCard => {
                    html!{
                        <pre>
                            <code> { download.content.clone() } </code>
                        </pre>
                    }
                }
                MimeType::SVG => html!{
                    <img src=download.as_data_link() alt="Image Preview" class="image is-square" width="300" height="300"/>
                },
            }
        } else {
            html!{}
        }
    }
    fn generate_vcard(&self) -> Result<VCard, VCardError> {
        match VCard::from_formatted_name_str(&self.name.formatted_name()) {
            Ok(vcard) => {
                let mut vcard = vcard;

                let names = {
                    let mut names = HashSet::new();
                    names.insert(self.name.to_vcard_name());

                    names
                };

                let addresses = {
                    let mut addresses = HashSet::new();
                    addresses.insert(self.home_address.to_vcard_address());
                    addresses.insert(self.work_address.to_vcard_address());

                    addresses
                };

                vcard.names = Some(vcard::Set::from_hash_set(names).unwrap());
                vcard.addresses = Some(vcard::Set::from_hash_set(addresses).unwrap());

                Ok(vcard)
            }
            Err(err) => Err(err),
        }
    }
    fn generate_pdf(&self) -> Result<String, ()>{
        let regular_bytes = include_bytes!("/usr/share/fonts/liberation/LiberationSans-Regular.ttf");
        let regular_font_data = fonts::FontData::new(regular_bytes.to_vec(), Some(printpdf::BuiltinFont::Helvetica)).expect("font data should be correct");

        let bold_bytes = include_bytes!("/usr/share/fonts/liberation/LiberationSans-Bold.ttf");
        let bold_font_data = fonts::FontData::new(bold_bytes.to_vec(), Some(printpdf::BuiltinFont::HelveticaBold)).expect("font data should be correct");

        let italic_bytes = include_bytes!("/usr/share/fonts/liberation/LiberationSans-Italic.ttf");
        let italic_font_data = fonts::FontData::new(italic_bytes.to_vec(), Some(printpdf::BuiltinFont::HelveticaOblique)).expect("font data should be correct");

        let bold_italic_bytes = include_bytes!("/usr/share/fonts/liberation/LiberationSans-BoldItalic.ttf");
        let bold_italic_font_data = fonts::FontData::new(bold_italic_bytes.to_vec(), Some(printpdf::BuiltinFont::HelveticaBoldOblique)).expect("font data should be correct");

        let font_family = fonts::FontFamily{ 
            regular: regular_font_data, 
            bold: bold_font_data, 
            italic: italic_font_data, 
            bold_italic: bold_italic_font_data 
        };

        let mut doc = genpdf::Document::new(font_family);

        doc.set_title("BCard test");
        doc.set_minimal_conformance();
        doc.set_margins(10);
        doc.set_line_spacing(1.25);

        doc.push(
            elements::Paragraph::new("genpdf Demo Document")
                .aligned(elements::Alignment::Center)
                .styled(style::Style::new().bold().with_font_size(20)),
        );

        // TODO fill doc with real data

        let mut buf: Vec<u8> = Vec::new();
        match doc.render(&mut buf) {
            Ok(_) => Ok(match String::from_utf8(buf) {
                Ok(s) => s,
                Err(_) => return Err(()),
            }),
            Err(_) => Err(()),
        }
    }
}


#[wasm_bindgen(start)]
pub fn run_app() {
    init();
    App::<MainView>::new().mount_to_body();
}