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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
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
#![warn(missing_docs)]

//! HTML to react transformer
//!
//! html-to-react is a fast html to react
//! transformer that uses btrees to search and replace
//! html properties to the react equivalent.
//!
//! # How to use html-to-react
//!
//! There are two ways to use html-to-react:
//!
//! - **Convert props React** transform html string to a react string.
//!   - [`convert_props_react`] is used to transform :blocking.
//! - **Convert to React**  Lets you transform the html to a react component.
//!   - [`convert_to_react`] is used to transform :blocking.
//!
//! [`convert_props_react`]: html_to_react/fn.convert_props_react.html
//! [`convert_to_react`]: html_to_react/fn.convert_to_react.html
//! 
//! # Basic usage
//!
//! First, you will need to add `html-to-react` to your `Cargo.toml`.
//!
//! Next, add your html to one of the transform methods to get your react,
//! output.

#[macro_use]
extern crate lazy_static;

extern crate convert_case;

use convert_case::{Case, Casing};
use std::collections::BTreeMap;

/// convert props to react
pub fn convert_props_react(ctx: String) -> String {
    let mut context = ctx.clone();

    lazy_static! {
        /// html static list of properties that convert to camel-case [https://reactjs.org/docs/dom-elements.html]
        static ref HTML_PROPS: BTreeMap<&'static str, &'static str> = BTreeMap::from([
            ("acceptcharset", "acceptCharset"),
            ("accesskey", "accessKey"),
            ("allowfullscreen", "allowFullScreen"),
            ("allowtransparency", "allowTransparency"),
            ("autocomplete", "autoComplete"),
            ("autofocus", "autoFocus"),
            ("autoplay", "autoPlay"),
            ("cellpadding", "cellPadding"),
            ("cellspacing", "cellSpacing"),
            ("charset", "charSet"),
            ("class", "className"), // special html
            ("classid", "classID"),
            ("classname", "className"),
            ("colspan", "colSpan"),
            ("contenteditable", "contentEditable"),
            ("contextmenu", "contextMenu"),
            ("crossorigin", "crossOrigin"),
            ("datetime", "dateTime"),
            ("enctype", "encType"),
            ("for", "htmlFor"), // special html
            ("formaction", "formAction"),
            ("formenctype", "formEncType"),
            ("formmethod", "formMethod"),
            ("formnovalidate", "formNoValidate"),
            ("formtarget", "formTarget"),
            ("frameborder", "frameBorder"),
            ("hreflang", "hrefLang"),
            ("htmlfor", "htmlFor"),
            ("httpequiv", "httpEquiv"),
            ("inputmode", "inputMode"),
            ("keyparams", "keyParams"),
            ("keytype", "keyType"),
            ("marginheight", "marginHeight"),
            ("marginwidth", "marginWidth"),
            ("maxlength", "maxLength"),
            ("mediagroup", "mediaGroup"),
            ("minlength", "minLength"),
            ("novalidate", "noValidate"),
            ("radiogroup", "radioGroup"),
            ("readonly", "readOnly"),
            ("rowspan", "rowSpan"),
            ("spellcheck", "spellCheck"),
            ("srcdoc", "srcDoc"),
            ("srclang", "srcLang"),
            ("srcset", "srcSet"),
            ("tabindex", "tabIndex"),
            ("usemap", "useMap"),
            // svg
            ("accentheight", "accentHeight"),
            ("alignmentbaseline", "alignmentBaseline"),
            ("allowreorder", "allowReorder"),
            ("arabicform", "arabicForm"),
            ("attributename", "attributeName"),
            ("attributetype", "attributeType"),
            ("autoreverse", "autoReverse"),
            ("basefrequency", "baseFrequency"),
            ("baseprofile", "baseProfile"),
            ("baselineshift", "baselineShift"),
            ("calcmode", "calcMode"),
            ("capheight", "capHeight"),
            ("clippath", "clipPath"),
            ("clippathunits", "clipPathUnits"),
            ("cliprule", "clipRule"),
            ("colorinterpolation", "colorInterpolation"),
            ("colorinterpolationfilters", "colorInterpolationFilters"),
            ("colorprofile", "colorProfile"),
            ("colorrendering", "colorRendering"),
            ("contentscripttype", "contentScriptType"),
            ("contentstyletype", "contentStyleType"),
            ("diffuseconstant", "diffuseConstant"),
            ("dominantbaseline", "dominantBaseline"),
            ("edgemode", "edgeMode"),
            ("enablebackground", "enableBackground"),
            ("externalresourcesrequired", "externalResourcesRequired"),
            ("fillopacity", "fillOpacity"),
            ("fillrule", "fillRule"),
            ("filterres", "filterRes"),
            ("filterunits", "filterUnits"),
            ("floodcolor", "floodColor"),
            ("floodopacity", "floodOpacity"),
            ("fontfamily", "fontFamily"),
            ("fontsize", "fontSize"),
            ("fontsizeadjust", "fontSizeAdjust"),
            ("fontstretch", "fontStretch"),
            ("fontstyle", "fontStyle"),
            ("fontvariant", "fontVariant"),
            ("fontweight", "fontWeight"),
            ("glyphname", "glyphName"),
            ("glyphorientationhorizontal", "glyphOrientationHorizontal"),
            ("glyphorientationvertical", "glyphOrientationVertical"),
            ("glyphref", "glyphRef"),
            ("gradienttransform", "gradientTransform"),
            ("gradientunits", "gradientUnits"),
            ("horizadvx", "horizAdvX"),
            ("horizoriginx", "horizOriginX"),
            ("imagerendering", "imageRendering"),
            ("kernelmatrix", "kernelMatrix"),
            ("kernelunitlength", "kernelUnitLength"),
            ("keypoints", "keyPoints"),
            ("keysplines", "keySplines"),
            ("keytimes", "keyTimes"),
            ("lengthadjust", "lengthAdjust"),
            ("letterspacing", "letterSpacing"),
            ("lightingcolor", "lightingColor"),
            ("limitingconeangle", "limitingConeAngle"),
            ("markerend", "markerEnd"),
            ("markerheight", "markerHeight"),
            ("markermid", "markerMid"),
            ("markerstart", "markerStart"),
            ("markerunits", "markerUnits"),
            ("markerwidth", "markerWidth"),
            ("maskcontentunits", "maskContentUnits"),
            ("maskunits", "maskUnits"),
            ("numoctaves", "numOctaves"),
            ("overlineposition", "overlinePosition"),
            ("overlinethickness", "overlineThickness"),
            ("paintorder", "paintOrder"),
            ("pathlength", "pathLength"),
            ("patterncontentunits", "patternContentUnits"),
            ("patterntransform", "patternTransform"),
            ("patternunits", "patternUnits"),
            ("pointerevents", "pointerEvents"),
            ("pointsatx", "pointsAtX"),
            ("pointsaty", "pointsAtY"),
            ("pointsatz", "pointsAtZ"),
            ("preservealpha", "preserveAlpha"),
            ("preserveaspectratio", "preserveAspectRatio"),
            ("primitiveunits", "primitiveUnits"),
            ("refx", "refX"),
            ("refy", "refY"),
            ("renderingintent", "renderingIntent"),
            ("repeatcount", "repeatCount"),
            ("repeatdur", "repeatDur"),
            ("requiredextensions", "requiredExtensions"),
            ("requiredfeatures", "requiredFeatures"),
            ("shaperendering", "shapeRendering"),
            ("specularconstant", "specularConstant"),
            ("specularexponent", "specularExponent"),
            ("spreadmethod", "spreadMethod"),
            ("startoffset", "startOffset"),
            ("stddeviation", "stdDeviation"),
            ("stitchtiles", "stitchTiles"),
            ("stopcolor", "stopColor"),
            ("stopopacity", "stopOpacity"),
            ("strikethroughposition", "strikethroughPosition"),
            ("strikethroughthickness", "strikethroughThickness"),
            ("strokedasharray", "strokeDasharray"),
            ("strokedashoffset", "strokeDashoffset"),
            ("strokelinecap", "strokeLinecap"),
            ("strokelinejoin", "strokeLinejoin"),
            ("strokemiterlimit", "strokeMiterlimit"),
            ("strokeopacity", "strokeOpacity"),
            ("strokewidth", "strokeWidth"),
            ("surfacescale", "surfaceScale"),
            ("systemlanguage", "systemLanguage"),
            ("tablevalues", "tableValues"),
            ("targetx", "targetX"),
            ("targety", "targetY"),
            ("textanchor", "textAnchor"),
            ("textdecoration", "textDecoration"),
            ("textlength", "textLength"),
            ("textrendering", "textRendering"),
            ("underlineposition", "underlinePosition"),
            ("underlinethickness", "underlineThickness"),
            ("unicodebidi", "unicodeBidi"),
            ("unicoderange", "unicodeRange"),
            ("unitsperem", "unitsPerEm"),
            ("valphabetic", "vAlphabetic"),
            ("vhanging", "vHanging"),
            ("videographic", "vIdeographic"),
            ("vmathematical", "vMathematical"),
            ("vectoreffect", "vectorEffect"),
            ("vertadvy", "vertAdvY"),
            ("vertoriginx", "vertOriginX"),
            ("vertoriginy", "vertOriginY"),
            ("viewbox", "viewBox"),
            ("viewtarget", "viewTarget"),
            ("wordspacing", "wordSpacing"),
            ("writingmode", "writingMode"),
            ("xchannelselector", "xChannelSelector"),
            ("xheight", "xHeight"),
            ("xlinkactuate", "xlinkActuate"),
            ("xlinkarcrole", "xlinkArcrole"),
            ("xlinkhref", "xlinkHref"),
            ("xlinkrole", "xlinkRole"),
            ("xlinkshow", "xlinkShow"),
            ("xlinktitle", "xlinkTitle"),
            ("xlinktype", "xlinkType"),
            ("xmlnsxlink", "xmlnsXlink"),
            ("xmlbase", "xmlBase"),
            ("xmllang", "xmlLang"),
            ("xmlspace", "xmlSpace"),
            ("ychannelselector", "yChannelSelector"),
            ("zoomandpan", "zoomAndPan"),
            // events
            ("onabort", "onAbort"),
            ("onanimationend", "onAnimationEnd"),
            ("onanimationiteration", "onAnimationIteration"),
            ("onanimationstart", "onAnimationStart"),
            ("onblur", "onBlur"),
            ("oncanplay", "onCanPlay"),
            ("oncanplaythrough", "onCanPlayThrough"),
            ("onchange", "onChange"),
            ("onclick", "onClick"),
            ("oncompositionend", "onCompositionEnd"),
            ("oncompositionstart", "onCompositionStart"),
            ("oncompositionupdate", "onCompositionUpdate"),
            ("oncontextmenu", "onContextMenu"),
            ("oncopy", "onCopy"),
            ("oncut", "onCut"),
            ("ondoubleclick", "onDoubleClick"),
            ("ondrag", "onDrag"),
            ("ondragend", "onDragEnd"),
            ("ondragenter", "onDragEnter"),
            ("ondragexit", "onDragExit"),
            ("ondragleave", "onDragLeave"),
            ("ondragover", "onDragOver"),
            ("ondragstart", "onDragStart"),
            ("ondrop", "onDrop"),
            ("ondurationchange", "onDurationChange"),
            ("onemptied", "onEmptied"),
            ("onencrypted", "onEncrypted"),
            ("onended", "onEnded"),
            ("onerror", "onError"),
            ("onfocus", "onFocus"),
            ("oninput", "onInput"),
            ("onkeydown", "onKeyDown"),
            ("onkeypress", "onKeyPress"),
            ("onkeyup", "onKeyUp"),
            ("onload", "onLoad"),
            ("onloadeddata", "onLoadedData"),
            ("onloadedmetadata", "onLoadedMetadata"),
            ("onloadstart", "onLoadStart"),
            ("onmousedown", "onMouseDown"),
            ("onmouseenter", "onMouseEnter"),
            ("onmouseleave", "onMouseLeave"),
            ("onmousemove", "onMouseMove"),
            ("onmouseout", "onMouseOut"),
            ("onmouseover", "onMouseOver"),
            ("onmouseup", "onMouseUp"),
            ("onpaste", "onPaste"),
            ("onpause", "onPause"),
            ("onplay", "onPlay"),
            ("onplaying", "onPlaying"),
            ("onprogress", "onProgress"),
            ("onratechange", "onRateChange"),
            ("onscroll", "onScroll"),
            ("onseeked", "onSeeked"),
            ("onseeking", "onSeeking"),
            ("onselect", "onSelect"),
            ("onstalled", "onStalled"),
            ("onsubmit", "onSubmit"),
            ("onsuspend", "onSuspend"),
            ("ontimeupdate", "onTimeUpdate"),
            ("ontouchcancel", "onTouchCancel"),
            ("ontouchend", "onTouchEnd"),
            ("ontouchmove", "onTouchMove"),
            ("ontouchstart", "onTouchStart"),
            ("ontransitionend", "onTransitionEnd"),
            ("onvolumechange", "onVolumeChange"),
            ("onwaiting", "onWaiting"),
            ("onwheel", "onWheel")
        ]);
    };

    let props: Vec<String> = extract_html_props(&context);

    for item in props.iter() {
        if item == "style" {
            context = create_style_object(&mut context);
        } else {
            let value = HTML_PROPS.get(&*item.to_owned()).unwrap_or(&"");

            if !value.is_empty() {
                let v = format!("{}=", item);
                let rp = format!("{}=", value);
                context = context.replace(&v, &rp);
            }
        }
    }

    context
}

/// extract all html props into a vector
fn extract_html_props(context: &String) -> Vec<String> {
    let mut props: Vec<String> = vec![];
    let mut current_prop = String::from("");
    let mut space_before_text = false;
    let mut inside_tag = false;

    // get all html props into a vec
    for c in context.chars() {
        if inside_tag {
            if c == '=' {
                space_before_text = false;
                props.push((*current_prop).to_string());
                current_prop.clear();
            }
            if space_before_text {
                current_prop.push(c);
            }
            if c == ' ' {
                space_before_text = true;
            }
        }
        if c == '<' {
            inside_tag = true;
        }
        if c == '>' {
            inside_tag = false;
        }
    }

    // sort the vec for btree linear lookup performance
    props.sort();

    props
}

/// manipulate the style properties to react
pub fn create_style_object(ctx: &mut String) -> String {
    let style_matcher = if ctx.contains("style='") {
        r#"'"#
    } else {
        r#"""#
    };

    let style_start = format!(r#"style={}"#, style_matcher);
    let (style_string, start_idx, end_idx) = text_between(&ctx, &style_start, style_matcher);

    let mut current_prop = String::from("");
    let mut space_before_text = false;

    let mut style_replacer = style_string.clone();

    // get all html props into a vec
    for c in style_string.chars() {
        if space_before_text {
            current_prop.push(c);
        }
        if c == ';' {
            space_before_text = true;
            style_replacer = style_replacer.replace(";", ",");
            current_prop.clear();
        }
        if c == ':' {
            let clp = &current_prop.trim();
            let camel_style = &clp.to_case(Case::Camel);

            style_replacer = style_replacer.replace(&*clp, &camel_style);
            space_before_text = false;
            current_prop.clear();
        }
    }

    let mut space_before_text = false;
    let mut current_prop = String::from("");

    let mut style_clone = style_replacer.clone().to_owned();

    // add double quotes to react props style values
    for (i, c) in style_replacer.chars().enumerate() {
        if space_before_text && c != ',' {
            current_prop.push(c);
        }

        if space_before_text && c == ',' {
            let current = current_prop.trim();
            style_clone = style_clone.replace(&current, &format!(r#""{}""#, current).to_string());
            space_before_text = false;
        }

        if c == ':' {
            space_before_text = true;
            current_prop.clear();
        }

        if i + 1 == style_replacer.len() {
            let current = current_prop.trim();
            style_clone = style_clone.replace(&current, &format!(r#""{}""#, current).to_string());
            space_before_text = false;
        }
    }

    let style_replacer = format!("{}{}{}", "style={{", style_clone, "}}");

    ctx.replace_range(start_idx - 7..start_idx + end_idx + 1, &style_replacer);

    ctx.to_owned()
}

/// get the text between two strings
fn text_between(search_str: &String, start_str: &String, end_str: &str) -> (String, usize, usize) {
    let start_idx = {
        let start_point = search_str.find(start_str);
        start_point.unwrap() + start_str.len()
    };

    let remaining = &search_str[start_idx..];
    let end_idx = remaining.find(&end_str).unwrap_or(remaining.len());

    (remaining[..end_idx].to_string(), start_idx, end_idx)
}

/// convert props to a react component
pub fn convert_to_react(ctx: String, component_name: String) -> String {
    let react_html = convert_props_react(ctx);
    let mut react_html = react_html.trim().to_owned();
    
    // remove html tags
    if react_html.starts_with("<!DOCTYPE html>") {
        react_html = react_html.replace("<!DOCTYPE html>", "");
    }
    if react_html.starts_with("<html>") {
        react_html = react_html.replace("<html>", "");
        react_html = react_html.replace("</html>", "");
    }

    let component_name = format!(" {}", component_name.trim());

    let component = format!(
        r#"import React from "react"
    
function{}() {{
    return (
        {}
    )
}}"#,
        component_name, react_html
    );

    component
}

#[test]
fn convert_props_react_test() {
    // convert special props class
    let html = r#"<img class="something">"#;
    let react_html = convert_props_react(html.to_string());

    assert_eq!("<img className=\"something\">", react_html);

    // convert special props class and for
    let html = r#"<img class="something" for="mystuff">"#;
    let react_html = convert_props_react(html.to_string());

    assert_eq!(
        "<img className=\"something\" htmlFor=\"mystuff\">",
        react_html
    );

    // convert special props class, for, and other props
    let html = r#"<img class="something" for="mystuff" tabindex="2">"#;
    let react_html = convert_props_react(html.to_string());

    assert_eq!(
        "<img className=\"something\" htmlFor=\"mystuff\" tabIndex=\"2\">",
        react_html
    );
}

#[test]
fn extract_html_props_test() {
    let html = r#"<img class="something" for="mystuff" tabindex="2">"#;
    let props = extract_html_props(&html.to_string());

    assert_eq!(props, vec!["class", "for", "tabindex"]);
}

#[test]
fn convert_props_react_styles_test() {
    let html = r#"<img style="color: white; background-color: black">"#;
    let props = convert_props_react(html.to_string());

    assert_eq!(
        r#"<img style={{color: "white", backgroundColor: "black"}}>"#,
        props
    );
}

#[test]
fn convert_props_react_children_test() {
    let html = r#"<div class="something" for="mystuff" tabindex="2" style="color: white; background-color: black">
    <div class="child" for="mychildstuff" tabindex="2" style="color: white; background-color: black">
        child
    </div>
</div>"#;
    let props = convert_props_react(html.to_string());

    assert_eq!(
        r###"<div className="something" htmlFor="mystuff" tabIndex="2" style={{color: "white", backgroundColor: "black"}}>
    <div className="child" htmlFor="mychildstuff" tabIndex="2" style={{color: "white", backgroundColor: "black"}}>
        child
    </div>
</div>"###,
        props
    );
}

#[test]
fn convert_react_component_test() {
    let html = r#"<div class="something" for="mystuff" tabindex="2" style="color: white; background-color: black">
            <div class="child" for="mychildstuff" tabindex="2" style="color: white; background-color: black">
                child
            </div>
        </div>"#;

    let props = convert_to_react(html.trim().to_string(), "Something".to_string());

    let style_object = r#"style={{color: "white", backgroundColor: "black"}}"#;

    assert_eq!(
        format!(
            r###"import React from "react"
    
function Something() {{
    return (
        <div className="something" htmlFor="mystuff" tabIndex="2" {}>
            <div className="child" htmlFor="mychildstuff" tabIndex="2" {}>
                child
            </div>
        </div>
    )
}}"###,
            style_object, style_object
        ),
        props
    );
}