htmlprops_to_react/
lib.rs

1#[macro_use]
2extern crate lazy_static;
3
4use std::collections::HashMap;
5
6/// convert props to react
7pub fn convert_props_react(ctx: String) -> String {    
8    let mut context = ctx.clone();
9
10    lazy_static! {
11        /// html static list of properties that convert to camel case
12        static ref HTML_PROPS: HashMap<&'static str, &'static str> = HashMap::from([
13            // special attributes
14            ("for", "htmlFor"),
15            ("class", "className"),
16            // end of special
17            ("acceptcharset", "acceptCharset"),
18            ("accesskey", "accessKey"),
19            ("allowfullscreen", "allowFullScreen"),
20            ("allowtransparency", "allowTransparency"),
21            ("autocomplete", "autoComplete"),
22            ("autofocus", "autoFocus"),
23            ("autoplay", "autoPlay"),
24            ("cellpadding", "cellPadding"),
25            ("cellspacing", "cellSpacing"),
26            ("charset", "charSet"),
27            ("classid", "classID"),
28            ("classname", "className"),
29            ("colspan", "colSpan"),
30            ("contenteditable", "contentEditable"),
31            ("contextmenu", "contextMenu"),
32            ("crossorigin", "crossOrigin"),
33            ("datetime", "dateTime"),
34            ("enctype", "encType"),
35            ("formaction", "formAction"),
36            ("formenctype", "formEncType"),
37            ("formmethod", "formMethod"),
38            ("formnovalidate", "formNoValidate"),
39            ("formtarget", "formTarget"),
40            ("frameborder", "frameBorder"),
41            ("hreflang", "hrefLang"),
42            ("htmlfor", "htmlFor"),
43            ("httpequiv", "httpEquiv"),
44            ("inputmode", "inputMode"),
45            ("keyparams", "keyParams"),
46            ("keytype", "keyType"),
47            ("marginheight", "marginHeight"),
48            ("marginwidth", "marginWidth"),
49            ("maxlength", "maxLength"),
50            ("mediagroup", "mediaGroup"),
51            ("minlength", "minLength"),
52            ("novalidate", "noValidate"),
53            ("radiogroup", "radioGroup"),
54            ("readonly", "readOnly"),
55            ("rowspan", "rowSpan"),
56            ("spellcheck", "spellCheck"),
57            ("srcdoc", "srcDoc"),
58            ("srclang", "srcLang"),
59            ("srcset", "srcSet"),
60            ("tabindex", "tabIndex"),
61            ("usemap", "useMap"),
62            // "accentheight",
63            // "alignmentbaseline",
64            // "allowreorder",
65            // "arabicform",
66            // "attributename",
67            // "attributetype",
68            // "autoreverse",
69            // "azimuth",
70            // "basefrequency",
71            // "baseprofile",
72            // "baselineshift",
73            // "calcmode",
74            // "capheight",
75            // "clippath",
76            // "clippathunits",
77            // "cliprule",
78            // "colorinterpolation",
79            // "colorinterpolationfilters",
80            // "colorprofile",
81            // "colorrendering",
82            // "contentscripttype",
83            // "contentstyletype",
84            // "diffuseconstant",
85            // "dominantbaseline",
86            // "edgemode",
87            // "enablebackground",
88            // "externalresourcesrequired",
89            // "fillopacity",
90            // "fillrule",
91            // "filterres",
92            // "filterunits",
93            // "floodcolor",
94            // "floodopacity",
95            // "focusable",
96            // "fontfamily",
97            // "fontsize",
98            // "fontsizeadjust",
99            // "fontstretch",
100            // "fontstyle",
101            // "fontvariant",
102            // "fontweight",
103            // "glyphname",
104            // "glyphorientationhorizontal",
105            // "glyphorientationvertical",
106            // "glyphref",
107            // "gradienttransform",
108            // "gradientunits",
109            // "horizadvx",
110            // "horizoriginx",
111            // "ideographic",
112            // "imagerendering",
113            // "kernelmatrix",
114            // "kernelunitlength",
115            // "keypoints",
116            // "keysplines",
117            // "keytimes",
118            // "lengthadjust",
119            // "letterspacing",
120            // "lightingcolor",
121            // "limitingconeangle",
122            // "markerend",
123            // "markerheight",
124            // "markermid",
125            // "markerstart",
126            // "markerunits",
127            // "markerwidth",
128            // "maskcontentunits",
129            // "maskunits",
130            // "mathematical",
131            // "numoctaves",
132            // "overlineposition",
133            // "overlinethickness",
134            // "paintorder",
135            // "panose1",
136            // "pathlength",
137            // "patterncontentunits",
138            // "patterntransform",
139            // "patternunits",
140            // "pointerevents",
141            // "pointsatx",
142            // "pointsaty",
143            // "pointsatz",
144            // "preservealpha",
145            // "preserveaspectratio",
146            // "primitiveunits",
147            // "refx",
148            // "refy",
149            // "renderingintent",
150            // "repeatcount",
151            // "repeatdur",
152            // "requiredextensions",
153            // "requiredfeatures",
154            // "shaperendering",
155            // "specularconstant",
156            // "specularexponent",
157            // "spreadmethod",
158            // "startoffset",
159            // "stddeviation",
160            // "stitchtiles",
161            // "stopcolor",
162            // "stopopacity",
163            // "strikethroughposition",
164            // "strikethroughthickness",
165            // "strokedasharray",
166            // "strokedashoffset",
167            // "strokelinecap",
168            // "strokelinejoin",
169            // "strokemiterlimit",
170            // "strokeopacity",
171            // "strokewidth",
172            // "surfacescale",
173            // "systemlanguage",
174            // "tablevalues",
175            // "targetx",
176            // "targety",
177            // "textanchor",
178            // "textdecoration",
179            // "textlength",
180            // "textrendering",
181            // "underlineposition",
182            // "underlinethickness",
183            // "unicodebidi",
184            // "unicoderange",
185            // "unitsperem",
186            // "valphabetic",
187            // "vhanging",
188            // "videographic",
189            // "vmathematical",
190            // "vectoreffect",
191            // "vertadvy",
192            // "vertoriginx",
193            // "vertoriginy",
194            ("viewbox", "viewBox"),
195            ("viewtarget", "viewTarget"),
196            ("wordspacing", "wordSpacing"),
197            ("writingmode", "writingMode"),
198            // "xchannelselector",
199            ("xheight", "xHeight"),
200            // "xlinkactuate",
201            // "xlinkarcrole",
202            // "xlinkhref",
203            // "xlinkrole",
204            // "xlinkshow",
205            // "xlinktitle",
206            // "xlinktype",
207            // "xmlnsxlink",
208            ("xmlbase", "xmlBase"),
209            ("xmllang", "xmlLang"),
210            ("xmlspace", "xmlSpace"),
211            ("ychannelselector", "yChannelSelector"),
212            ("zoomandpan", "zoomAndPan"),
213            ("onabort", "onAbort"),
214            ("onanimationend", "onAnimationEnd"),
215            ("onanimationiteration", "onAnimationIteration"),
216            ("onanimationstart", "onAnimationStart"),
217            ("onblur", "onBlur"),
218            ("oncanplay", "onCanPlay"),
219            ("oncanplaythrough", "onCanPlayThrough"),
220            ("onchange", "onChange"),
221            ("onclick", "onClick"),
222            ("oncompositionend", "onCompositionEnd"),
223            ("oncompositionstart", "onCompositionStart"),
224            ("oncompositionupdate", "onCompositionUpdate"),
225            ("oncontextmenu", "onContextMenu"),
226            ("oncopy", "onCopy"),
227            ("oncut", "onCut"),
228            ("ondoubleclick", "onDoubleClick"),
229            ("ondrag", "onDrag"),
230            ("ondragend", "onDragEnd"),
231            ("ondragenter", "onDragEnter"),
232            ("ondragexit", "onDragExit"),
233            ("ondragleave", "onDragLeave"),
234            ("ondragover", "onDragOver"),
235            ("ondragstart", "onDragStart"),
236            ("ondrop", "onDrop"),
237            ("ondurationchange", "onDurationChange"),
238            ("onemptied", "onEmptied"),
239            ("onencrypted", "onEncrypted"),
240            ("onended", "onEnded"),
241            ("onerror", "onError"),
242            ("onfocus", "onFocus"),
243            ("oninput", "onInput"),
244            ("onkeydown", "onKeyDown"),
245            ("onkeypress", "onKeyPress"),
246            ("onkeyup", "onKeyUp"),
247            ("onload", "onLoad"),
248            ("onloadeddata", "onLoadedData"),
249            ("onloadedmetadata", "onLoadedMetadata"),
250            ("onloadstart", "onLoadStart"),
251            ("onmousedown", "onMouseDown"),
252            ("onmouseenter", "onMouseEnter"),
253            ("onmouseleave", "onMouseLeave"),
254            ("onmousemove", "onMouseMove"),
255            ("onmouseout", "onMouseOut"),
256            ("onmouseover", "onMouseOver"),
257            ("onmouseup", "onMouseUp"),
258            ("onpaste", "onPaste"),
259            ("onpause", "onPause"),
260            ("onplay", "onPlay"),
261            ("onplaying", "onPlaying"),
262            ("onprogress", "onProgress"),
263            ("onratechange", "onRateChange"),
264            ("onscroll", "onScroll"),
265            ("onseeked", "onSeeked"),
266            ("onseeking", "onSeeking"),
267            ("onselect", "onSelect"),
268            ("onstalled", "onStalled"),
269            ("onsubmit", "onSubmit"),
270            ("onsuspend", "onSuspend"),
271            ("ontimeupdate", "onTimeUpdate"),
272            ("ontouchcancel", "onTouchCancel"),
273            ("ontouchend", "onTouchEnd"),
274            ("ontouchmove", "onTouchMove"),
275            ("ontouchstart", "onTouchStart"),
276            ("ontransitionend", "onTransitionEnd"),
277            ("onvolumechange", "onVolumeChange"),
278            ("onwaiting", "onWaiting"),
279            ("onwheel", "onWheel")
280        ]);
281    };
282
283    // TODO: parse context to get all keys split to check without full iteration
284    for (item, value) in HTML_PROPS.iter() {
285        if context.contains(&*item) {
286            let v = format!("{}=", item);
287            let rp = format!("{}=", value);
288            context = context.replace(&v, &rp);
289        };
290    };
291
292    context
293}
294
295#[test]
296fn convert_props_react_test() {
297    // convert special props class
298    let html = r#"<img class="something">"#;
299    let react_html = convert_props_react(html.to_string());
300
301    assert_eq!("<img className=\"something\">", react_html);
302
303    // convert special props class and for
304    let html = r#"<img class="something" for="mystuff">"#;
305    let react_html = convert_props_react(html.to_string());
306
307    assert_eq!("<img className=\"something\" htmlFor=\"mystuff\">", react_html);
308
309    // convert special props class, for, and other props
310    let html = r#"<img class="something" for="mystuff" tabindex="2">"#;
311    let react_html = convert_props_react(html.to_string());
312
313    assert_eq!("<img className=\"something\" htmlFor=\"mystuff\" tabIndex=\"2\">", react_html);
314}