├── .gitignore ├── img ├── icon.png ├── seriously.png ├── example_imported_svg.png └── logo.svg ├── fonts ├── glyphicons-halflings-regular.eot ├── glyphicons-halflings-regular.ttf ├── glyphicons-halflings-regular.woff └── glyphicons-halflings-regular.woff2 ├── css └── main.css ├── README.md ├── js ├── filesaver.min.js ├── svg_shape_converter.js ├── colors.min.js ├── cssjson.js ├── filereader.js ├── main.js ├── bootstrap.min.js └── flatten.js ├── index.html └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/* -------------------------------------------------------------------------------- /img/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/inloop/svg2android/HEAD/img/icon.png -------------------------------------------------------------------------------- /img/seriously.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/inloop/svg2android/HEAD/img/seriously.png -------------------------------------------------------------------------------- /img/example_imported_svg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/inloop/svg2android/HEAD/img/example_imported_svg.png -------------------------------------------------------------------------------- /fonts/glyphicons-halflings-regular.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/inloop/svg2android/HEAD/fonts/glyphicons-halflings-regular.eot -------------------------------------------------------------------------------- /fonts/glyphicons-halflings-regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/inloop/svg2android/HEAD/fonts/glyphicons-halflings-regular.ttf -------------------------------------------------------------------------------- /fonts/glyphicons-halflings-regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/inloop/svg2android/HEAD/fonts/glyphicons-halflings-regular.woff -------------------------------------------------------------------------------- /fonts/glyphicons-halflings-regular.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/inloop/svg2android/HEAD/fonts/glyphicons-halflings-regular.woff2 -------------------------------------------------------------------------------- /css/main.css: -------------------------------------------------------------------------------- 1 | body { 2 | background: #f5f5f5; 3 | } 4 | 5 | footer { 6 | margin-top: 8px; 7 | margin-bottom: 8px; 8 | color: darkgray; 9 | text-align: center; 10 | } 11 | 12 | footer small a { 13 | color: #7AA7CF; 14 | } 15 | 16 | #main-container { 17 | position: relative; 18 | background: #ffffff; 19 | box-shadow: 0 1px 16px silver; 20 | 21 | } 22 | 23 | #output-code { 24 | white-space: pre-wrap; 25 | } 26 | 27 | .drag { 28 | background-color: lightblue; 29 | } 30 | 31 | .info-items td { 32 | vertical-align: top; 33 | } 34 | 35 | .info-items td:first-child { 36 | width: 90px; 37 | } 38 | 39 | #header { 40 | background: #e0f2f1; 41 | color: #7FB6B4; 42 | padding: 16px; 43 | margin-left: -15px; 44 | margin-right: -15px; 45 | margin-bottom: 15px; 46 | 47 | } 48 | 49 | #header h3 { 50 | margin: 0; 51 | } 52 | 53 | #dropzone { 54 | height: 450px; 55 | width: 100%; 56 | font-size: 1.2em; 57 | cursor: pointer; 58 | text-align: center; 59 | display: table; 60 | table-layout: fixed; 61 | } 62 | 63 | #dropzone .panel-body { 64 | display: table-cell; 65 | vertical-align: middle; 66 | } 67 | 68 | #output-box { 69 | display: none; 70 | margin-bottom: 20px; 71 | } 72 | 73 | #button-box { 74 | position: absolute; 75 | right: 40px; 76 | } 77 | 78 | #last-update { 79 | float: right; 80 | margin-top: -5px; 81 | color: #aed0cf; 82 | display: none; 83 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-svg2android-brightgreen.svg?style=flat)](https://android-arsenal.com/details/1/1061) 2 | svg2android 3 | =========== 4 | ### [Deprecated - use official [Vector Asset Studio](https://developer.android.com/studio/write/vector-asset-studio#svg) directly from Android Studio] 5 | 6 | *Convert SVG to Android VectorDrawable XML resource file.* 7 | 8 | Extracts all parameters of elements and groups that are supported in Android. 9 | 10 | **Supported:** path, line, rect, circle, ellipse, polyline and polygon elements. 11 | 12 | **Not supported:** text element (export manually to path), gradients and patterns, matrix transforms 13 | 14 | ##### Example of imported svg (random image from wikipedia): 15 | ![](https://github.com/inloop/svg2android/raw/gh-pages/img/example_imported_svg.png "Screenshot") 16 | 17 | ### License 18 | Licensed under the Apache License, Version 2.0 (the "License"); 19 | you may not use this file except in compliance with the License. 20 | You may obtain a copy of the License at 21 | 22 | http://www.apache.org/licenses/LICENSE-2.0 23 | 24 | Unless required by applicable law or agreed to in writing, software 25 | distributed under the License is distributed on an "AS IS" BASIS, 26 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 27 | See the License for the specific language governing permissions and 28 | limitations under the License. 29 | -------------------------------------------------------------------------------- /js/filesaver.min.js: -------------------------------------------------------------------------------- 1 | /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */ 2 | var saveAs=saveAs||function(view){"use strict";if(typeof navigator!=="undefined"&&/MSIE [1-9]\./.test(navigator.userAgent)){return}var doc=view.document,get_URL=function(){return view.URL||view.webkitURL||view},save_link=doc.createElementNS("http://www.w3.org/1999/xhtml","a"),can_use_save_link="download"in save_link,click=function(node){var event=new MouseEvent("click");node.dispatchEvent(event)},is_safari=/Version\/[\d\.]+.*Safari/.test(navigator.userAgent),webkit_req_fs=view.webkitRequestFileSystem,req_fs=view.requestFileSystem||webkit_req_fs||view.mozRequestFileSystem,throw_outside=function(ex){(view.setImmediate||view.setTimeout)(function(){throw ex},0)},force_saveable_type="application/octet-stream",fs_min_size=0,arbitrary_revoke_timeout=500,revoke=function(file){var revoker=function(){if(typeof file==="string"){get_URL().revokeObjectURL(file)}else{file.remove()}};if(view.chrome){revoker()}else{setTimeout(revoker,arbitrary_revoke_timeout)}},dispatch=function(filesaver,event_types,event){event_types=[].concat(event_types);var i=event_types.length;while(i--){var listener=filesaver["on"+event_types[i]];if(typeof listener==="function"){try{listener.call(filesaver,event||filesaver)}catch(ex){throw_outside(ex)}}}},auto_bom=function(blob){if(/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)){return new Blob(["\ufeff",blob],{type:blob.type})}return blob},FileSaver=function(blob,name,no_auto_bom){if(!no_auto_bom){blob=auto_bom(blob)}var filesaver=this,type=blob.type,blob_changed=false,object_url,target_view,dispatch_all=function(){dispatch(filesaver,"writestart progress write writeend".split(" "))},fs_error=function(){if(target_view&&is_safari&&typeof FileReader!=="undefined"){var reader=new FileReader;reader.onloadend=function(){var base64Data=reader.result;target_view.location.href="data:attachment/file"+base64Data.slice(base64Data.search(/[,;]/));filesaver.readyState=filesaver.DONE;dispatch_all()};reader.readAsDataURL(blob);filesaver.readyState=filesaver.INIT;return}if(blob_changed||!object_url){object_url=get_URL().createObjectURL(blob)}if(target_view){target_view.location.href=object_url}else{var new_tab=view.open(object_url,"_blank");if(new_tab==undefined&&is_safari){view.location.href=object_url}}filesaver.readyState=filesaver.DONE;dispatch_all();revoke(object_url)},abortable=function(func){return function(){if(filesaver.readyState!==filesaver.DONE){return func.apply(this,arguments)}}},create_if_not_found={create:true,exclusive:false},slice;filesaver.readyState=filesaver.INIT;if(!name){name="download"}if(can_use_save_link){object_url=get_URL().createObjectURL(blob);setTimeout(function(){save_link.href=object_url;save_link.download=name;click(save_link);dispatch_all();revoke(object_url);filesaver.readyState=filesaver.DONE});return}if(view.chrome&&type&&type!==force_saveable_type){slice=blob.slice||blob.webkitSlice;blob=slice.call(blob,0,blob.size,force_saveable_type);blob_changed=true}if(webkit_req_fs&&name!=="download"){name+=".download"}if(type===force_saveable_type||webkit_req_fs){target_view=view}if(!req_fs){fs_error();return}fs_min_size+=blob.size;req_fs(view.TEMPORARY,fs_min_size,abortable(function(fs){fs.root.getDirectory("saved",create_if_not_found,abortable(function(dir){var save=function(){dir.getFile(name,create_if_not_found,abortable(function(file){file.createWriter(abortable(function(writer){writer.onwriteend=function(event){target_view.location.href=file.toURL();filesaver.readyState=filesaver.DONE;dispatch(filesaver,"writeend",event);revoke(file)};writer.onerror=function(){var error=writer.error;if(error.code!==error.ABORT_ERR){fs_error()}};"writestart progress write abort".split(" ").forEach(function(event){writer["on"+event]=filesaver["on"+event]});writer.write(blob);filesaver.abort=function(){writer.abort();filesaver.readyState=filesaver.DONE};filesaver.readyState=filesaver.WRITING}),fs_error)}),fs_error)};dir.getFile(name,{create:false},abortable(function(file){file.remove();save()}),abortable(function(ex){if(ex.code===ex.NOT_FOUND_ERR){save()}else{fs_error()}}))}),fs_error)}),fs_error)},FS_proto=FileSaver.prototype,saveAs=function(blob,name,no_auto_bom){return new FileSaver(blob,name,no_auto_bom)};if(typeof navigator!=="undefined"&&navigator.msSaveOrOpenBlob){return function(blob,name,no_auto_bom){if(!no_auto_bom){blob=auto_bom(blob)}return navigator.msSaveOrOpenBlob(blob,name||"download")}}FS_proto.abort=function(){var filesaver=this;filesaver.readyState=filesaver.DONE;dispatch(filesaver,"abort")};FS_proto.readyState=FS_proto.INIT=0;FS_proto.WRITING=1;FS_proto.DONE=2;FS_proto.error=FS_proto.onwritestart=FS_proto.onprogress=FS_proto.onwrite=FS_proto.onabort=FS_proto.onerror=FS_proto.onwriteend=null;return saveAs}(typeof self!=="undefined"&&self||typeof window!=="undefined"&&window||this.content);if(typeof module!=="undefined"&&module.exports){module.exports.saveAs=saveAs}else if(typeof define!=="undefined"&&define!==null&&define.amd!=null){define([],function(){return saveAs})} 3 | -------------------------------------------------------------------------------- /js/svg_shape_converter.js: -------------------------------------------------------------------------------- 1 | // Based on 2 | // https://github.com/JFXtras/jfxtras-labs/blob/2.2/src/main/java/jfxtras/labs/util/ShapeConverter.java 3 | 4 | var ShapeConverter = new function () { 5 | var KAPPA = 0.5522847498307935; 6 | 7 | function s(number) { 8 | return (parseFloat(number.toPrecision(12))); 9 | } 10 | 11 | this.convertLine = function (lineTag) { 12 | var x1 = lineTag.attr("x1"); 13 | var x2 = lineTag.attr("x2"); 14 | var y1 = lineTag.attr("y1"); 15 | var y2 = lineTag.attr("y2"); 16 | 17 | return "M " + x1 + " " + y1 + " " + "L " + x2 + " " + y2; 18 | }; 19 | 20 | this.convertRect = function (rectTag) { 21 | var x = parseFloat(rectTag.attr("x") || 0); 22 | var y = parseFloat(rectTag.attr("y") || 0); 23 | var w = parseFloat(rectTag.attr("width") || 0); 24 | var h = parseFloat(rectTag.attr("height") || 0); 25 | var rx = parseFloat(rectTag.attr("rx") || 0); 26 | var ry = parseFloat(rectTag.attr("ry") || 0); 27 | var r = s(x + w); 28 | var b = s(y + h); 29 | 30 | if (ry == 0) { 31 | ry = rx; 32 | } else if (rx == 0) { 33 | rx = ry; 34 | } 35 | 36 | if (rx == 0 && ry == 0) { 37 | return "M " + x + " " + y + " H " + s(x+w) + " V " + s(y+h) + " H " + x + " V " + y + " Z"; 38 | } else { 39 | return "M " + s(x + rx) + " " + y + " " 40 | + "L " + s(r - rx) + " " + y + " " 41 | + "Q " + r + " " + y + " " + r + " " + s(y + ry) + " " 42 | + "L " + r + " " + s(y + h - ry) + " " 43 | + "Q " + r + " " + b + " " + s(r - rx) + " " + b + " " 44 | + "L " + s(x + rx) + " " + b + " " 45 | + "Q " + x + " " + b + " " + x + " " + s(b - ry) + " " 46 | + "L " + x + " " + s(y + ry) + " " 47 | + "Q " + x + " " + y + " " + s(x + rx) + " " + y + " " 48 | + "Z"; 49 | } 50 | }; 51 | 52 | this.convertCircle = function (circleTag) { 53 | var cx = parseFloat(circleTag.attr("cx") || 0); 54 | var cy = parseFloat(circleTag.attr("cy") || 0); 55 | var r = parseFloat(circleTag.attr("r") || 0); 56 | var controlDistance = r * KAPPA; 57 | 58 | // Move to first point 59 | var output = "M " + cx + " " + s(cy - r) + " "; 60 | // 1. quadrant 61 | output += "C " + s(cx + controlDistance) + " " + s(cy - r) + " " + s(cx + r) + 62 | " " + s(cy - controlDistance) + " " + s(cx + r) + " " + cy + " "; 63 | // 2. quadrant 64 | output += "C " + s(cx + r) + " " + s(cy + controlDistance) + " " + s(cx + controlDistance) + 65 | " " + s(cy + r) + " " + cx + " " + s(cy + r) + " "; 66 | // 3. quadrant 67 | output += "C " + s(cx - controlDistance) + " " + s(cy + r) + " " + s(cx - r) + " " + 68 | s(cy + controlDistance) + " " + s(cx - r) + " " + cy + " "; 69 | // 4. quadrant 70 | output += "C " + s(cx - r) + " " + s(cy - controlDistance) + " " + s(cx - controlDistance) + " " + s(cy - r) + 71 | " " + cx + " " + s(cy - r) + " "; 72 | // Close path 73 | output += "Z"; 74 | 75 | return output; 76 | }; 77 | 78 | this.convertEllipse = function (ellipseTag) { 79 | var cx = parseFloat(ellipseTag.attr("cx") || 0); 80 | var cy = parseFloat(ellipseTag.attr("cy") || 0); 81 | var rx = parseFloat(ellipseTag.attr("rx") || 0); 82 | var ry = parseFloat(ellipseTag.attr("ry") || 0); 83 | var controlDistanceX = rx * KAPPA; 84 | var controlDistanceY = ry * KAPPA; 85 | 86 | // Move to first point 87 | var output = "M " + cx + " " + s(cy - ry) + " "; 88 | // 1. quadrant 89 | output += "C " + s(cx + controlDistanceX) + " " + s(cy - ry) + " " 90 | + s(cx + rx) + " " + s(cy - controlDistanceY) + " " + s(cx + rx) + " " + cy + " "; 91 | // 2. quadrant 92 | output += "C " + s(cx + rx) + " " + s(cy + controlDistanceY) + " " 93 | + s(cx + controlDistanceX) + " " + s(cy + ry) + " " + cx + " " + s(cy + ry) + " "; 94 | // 3. quadrant 95 | output += "C " + s(cx - controlDistanceX) + " " + s(cy + ry) + " " 96 | + s(cx - rx) + " " + s(cy + controlDistanceY) + " " + s(cx - rx) + " " + cy + " "; 97 | // 4. quadrant 98 | output += "C " + s(cx - rx) + " " + s(cy - controlDistanceY) + " " 99 | + s(cx - controlDistanceX) + " " + s(cy - ry) + " " + cx + " " + s(cy - ry) + " "; 100 | // Close path 101 | output += "Z"; 102 | return output; 103 | }; 104 | 105 | this.convertPolygon = function (polylineTag, isPolyline) { 106 | var points = polylineTag.attr("points"); 107 | var pointsArrayRaw = typeof points !== "undefined" ? points.split(",") : []; 108 | var pointsArray = []; 109 | for (var i = 0; i < pointsArrayRaw.length; i++) { 110 | var splitted = pointsArrayRaw[i].split(" "); 111 | for (var j = 0; j < splitted.length; j++) { 112 | if (splitted[j].length > 0) { 113 | pointsArray.push(splitted[j]); 114 | } 115 | } 116 | } 117 | 118 | if (pointsArray.length % 2 == 0) { 119 | var output = ""; 120 | for (var i = 0 ; i < pointsArray.length ; i += 2) { 121 | output += (i == 0 ? "M " : "L "); 122 | output += pointsArray[i] + " "+ pointsArray[i+1] + " "; 123 | } 124 | if (!isPolyline) { 125 | output += "Z"; 126 | } 127 | return output; 128 | } else { 129 | return null; 130 | } 131 | }; 132 | }; -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Android SVG to VectorDrawable 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 26 | 27 | 34 | 35 |
36 |
37 | Drop file here (or multiple files) to load content or click on this box to open file dialog.
38 |
No file will be uploaded - uses only JavaScript HTML5 FileReader.

39 | 40 |
41 | This tool has been deprecated. Use official Vector Asset Studio instead.
42 |
43 |
44 |
45 | 46 |
47 |
48 | 50 | 52 |
53 |

 54 |     
55 | 56 | 57 | 58 | 59 | 96 |
97 | 98 | 115 | 116 |
117 | 121 |
122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 146 | 147 | 148 | -------------------------------------------------------------------------------- /js/colors.min.js: -------------------------------------------------------------------------------- 1 | // colors.js - v2.0.0 2 | // Copyright 2012-2016 Matt Jordan 3 | // MIT License 4 | !function e(r,a,f){function n(o,d){if(!a[o]){if(!r[o]){var i="function"==typeof require&&require;if(!d&&i)return i(o,!0);if(t)return t(o,!0);var s=new Error("Cannot find module '"+o+"'");throw s.code="MODULE_NOT_FOUND",s}var u=a[o]={exports:{}};r[o][0].call(u.exports,function(e){var a=r[o][1][e];return n(a?a:e)},u,u.exports,e,r,a,f)}return a[o].exports}for(var t="function"==typeof require&&require,o=0;o1&&(i.h-=1)),[f.round(360*i.h),f.round(100*i.s),f.round(100*i.v)]};r.exports=n},{"./utils":14}],4:[function(e,r,a){var f=function(e){return e=e.replace(/^\#/,""),6===e.length?[parseInt(e.substr(0,2),16),parseInt(e.substr(2,2),16),parseInt(e.substr(4,2),16)]:parseInt(e,16)};r.exports=f},{}],5:[function(e,r,a){var f=e("./hsv2rgb"),n=function(e,r,a){var n,t,o,d,i,s,u,l,c,h,b,g;return"object"==typeof e?(n=e[0],t=e[1],o=e[2]):(n=e,t=r,o=a),u=f(n,t,o),l=u.R/255,c=u.G/255,h=u.B/255,b=Math.max(l,c,h),g=Math.min(l,c,h),s=(b+g)/2,i=0,d=0,b!=g&&(r=.5>s?(b-g)/(b+g):(b-g)/(2-b-g),e=l==b?(c-h)/(b-g):c==b?2+(h-l)/(b-g):4+(l-c)/(b-g)),s=100*s,i=100*i,d=60*d,0>d&&(d+=360),[Math.floor(e),Math.floor(r),Math.floor(a)]};r.exports=n},{"./hsv2rgb":6}],6:[function(e,r,a){var f=function(e,r,a){var f,n,t,o,d,i,s,u,l=[];switch("object"==typeof e?(f=e[0],n=e[1],t=e[2]):(f=e,n=r,t=a),n/=100,t/=100,o=Math.floor(f/60%6),d=f/60-o,i=t*(1-n),s=t*(1-d*n),u=t*(1-(1-d)*n),o){case 0:l=[t,u,i];break;case 1:l=[s,t,i];break;case 2:l=[i,t,u];break;case 3:l=[i,s,t];break;case 4:l=[u,i,t];break;case 5:l=[t,i,s]}return[Math.min(255,Math.floor(256*l[0])),Math.min(255,Math.floor(256*l[1])),Math.min(255,Math.floor(256*l[2]))]};r.exports=f},{}],7:[function(e,r,a){r.exports={complement:e("./complement"),hex2hsv:e("./hex2hsv"),hex2rgb:e("./hex2rgb"),hsv2hsl:e("./hsv2hsl"),hsv2rgb:e("./hsv2rgb"),name2hex:e("./name2hex"),name2hsv:e("./name2hsv"),name2rgb:e("./name2rgb"),rand:e("./rand"),rgb2hex:e("./rgb2hex"),rgb2hsl:e("./rgb2hsl"),utils:e("./utils")}},{"./complement":2,"./hex2hsv":3,"./hex2rgb":4,"./hsv2hsl":5,"./hsv2rgb":6,"./name2hex":8,"./name2hsv":9,"./name2rgb":10,"./rand":11,"./rgb2hex":12,"./rgb2hsl":13,"./utils":14}],8:[function(e,r,a){var f={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgrey:"#a9a9a9",darkgreen:"#006400",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",grey:"#808080",green:"#008000",greenyellow:"#adff2f",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgrey:"#d3d3d3",lightgreen:"#90ee90",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370d8",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#d87093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"},n=function(e){return e=e.toLowerCase(),f[e]?f[e]:"Invalid Color Name"};r.exports=n},{}],9:[function(e,r,a){var f=e("./name2hex"),n=e("./hex2hsv"),t=function(e){return n(f(e))};r.exports=t},{"./hex2hsv":3,"./name2hex":8}],10:[function(e,r,a){var f=e("./name2hex"),n=e("./hex2rgb"),t=function(e){return n(f(e))};r.exports=t},{"./hex2rgb":4,"./name2hex":8}],11:[function(e,r,a){var f="0123456789abcdef",n=function(e){return e?e():[Math.floor(-254*Math.random()+255),Math.floor(-254*Math.random()+255),Math.floor(-254*Math.random()+255)]};r.exports=n},{}],12:[function(e,r,a){var f=e("./utils"),n=function(e,r,a){return e=f.paddedHex(e),r=void 0!==r?f.paddedHex(r):e,a=void 0!==a?f.paddedHex(a):e,"#"+e+r+a};r.exports=n},{"./utils":14}],13:[function(e,r,a){var f=e("./utils"),n=function(e,r,a){var n,t,o,d,i,s,u,l,c;if("object"==typeof e?(n=e[0],t=e[1],o=e[2]):(n=e,t=r,o=a),n/=255,t/=255,o/=255,i=Math.max(n,t,o),d=Math.min(n,t,o),l=(i+d)/2,i==d)s=u=0;else{switch(c=i-d,u=l>.5?c/(2-i-d):c/(i+d),i){case n:s=(t-o)/c+(o>t?6:0);break;case t:s=(o-n)/c+2;break;case o:s=(n-t)/c+4}s/=6}return[Math.floor(360*s),f.round(100*u,1),f.round(100*l,1)]};r.exports=n},{"./utils":14}],14:[function(e,r,a){a.render=function(e,r){return e},a.paddedHex=function(e){var r=10>e?"0":"";return r+=e.toString(16),1===r.length?"0"+r:r},a.round=function(e,r){return r=r||10,parseFloat(e.toFixed(r))},a.hexRegexMatch=function(e){return/^\x23[a-f0-9]{3}([a-f0-9]{3})?$/i.test(e)}},{}]},{},[1]); -------------------------------------------------------------------------------- /img/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 19 | 21 | 44 | 46 | 47 | 49 | image/svg+xml 50 | 52 | 53 | 54 | 55 | 56 | 61 | 70 | 74 | 78 | 89 | 100 | 103 | 106 | 111 | 116 | 121 | 126 | 127 | 128 | 129 | 130 | 134 | 139 | 143 | 148 | 149 | 150 | 151 | -------------------------------------------------------------------------------- /js/cssjson.js: -------------------------------------------------------------------------------- 1 | /** 2 | * CSS-JSON Converter for JavaScript 3 | * Converts CSS to JSON and back. 4 | * Version 2.1 5 | * 6 | * Released under the MIT license. 7 | * 8 | * Copyright (c) 2013 Aram Kocharyan, http://aramk.com/ 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 11 | documentation files (the "Software"), to deal in the Software without restriction, including without limitation 12 | the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 13 | to permit persons to whom the Software is furnished to do so, subject to the following conditions: 14 | 15 | The above copyright notice and this permission notice shall be included in all copies or substantial portions 16 | of the Software. 17 | 18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO 19 | THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 21 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | THE SOFTWARE. 23 | */ 24 | 25 | var CSSJSON = new function () { 26 | 27 | var base = this; 28 | 29 | base.init = function () { 30 | // String functions 31 | String.prototype.trim = function () { 32 | return this.replace(/^\s+|\s+$/g, ''); 33 | }; 34 | 35 | String.prototype.repeat = function (n) { 36 | return new Array(1 + n).join(this); 37 | }; 38 | }; 39 | base.init(); 40 | 41 | var selX = /([^\s\;\{\}][^\;\{\}]*)\{/g; 42 | var endX = /\}/g; 43 | var lineX = /([^\;\{\}]*)\;/g; 44 | var commentX = /\/\*[\s\S]*?\*\//g; 45 | var lineAttrX = /([^\:]+):([^\;]*);/; 46 | 47 | // This is used, a concatenation of all above. We use alternation to 48 | // capture. 49 | var altX = /(\/\*[\s\S]*?\*\/)|([^\s\;\{\}][^\;\{\}]*(?=\{))|(\})|([^\;\{\}]+\;(?!\s*\*\/))/gmi; 50 | 51 | // Capture groups 52 | var capComment = 1; 53 | var capSelector = 2; 54 | var capEnd = 3; 55 | var capAttr = 4; 56 | 57 | var isEmpty = function (x) { 58 | return typeof x == 'undefined' || x.length == 0 || x == null; 59 | }; 60 | 61 | var isCssJson = function (node) { 62 | return !isEmpty(node) ? (node.attributes && node.children) : false; 63 | }; 64 | 65 | /** 66 | * Input is css string and current pos, returns JSON object 67 | * 68 | * @param cssString 69 | * The CSS string. 70 | * @param args 71 | * An optional argument object. ordered: Whether order of 72 | * comments and other nodes should be kept in the output. This 73 | * will return an object where all the keys are numbers and the 74 | * values are objects containing "name" and "value" keys for each 75 | * node. comments: Whether to capture comments. split: Whether to 76 | * split each comma separated list of selectors. 77 | */ 78 | base.toJSON = function (cssString, args) { 79 | var node = { 80 | children: {}, 81 | attributes: {} 82 | }; 83 | var match = null; 84 | var count = 0; 85 | 86 | if (typeof args == 'undefined') { 87 | var args = { 88 | ordered: false, 89 | comments: false, 90 | stripComments: false, 91 | split: false 92 | }; 93 | } 94 | if (args.stripComments) { 95 | args.comments = false; 96 | cssString = cssString.replace(commentX, ''); 97 | } 98 | 99 | while ((match = altX.exec(cssString)) != null) { 100 | if (!isEmpty(match[capComment]) && args.comments) { 101 | // Comment 102 | var add = match[capComment].trim(); 103 | node[count++] = add; 104 | } else if (!isEmpty(match[capSelector])) { 105 | // New node, we recurse 106 | var name = match[capSelector].trim(); 107 | // This will return when we encounter a closing brace 108 | var newNode = base.toJSON(cssString, args); 109 | if (args.ordered) { 110 | var obj = {}; 111 | obj['name'] = name; 112 | obj['value'] = newNode; 113 | // Since we must use key as index to keep order and not 114 | // name, this will differentiate between a Rule Node and an 115 | // Attribute, since both contain a name and value pair. 116 | obj['type'] = 'rule'; 117 | node[count++] = obj; 118 | } else { 119 | if (args.split) { 120 | var bits = name.split(','); 121 | } else { 122 | var bits = [name]; 123 | } 124 | for (i in bits) { 125 | var sel = bits[i].trim(); 126 | if (sel in node.children) { 127 | for (var att in newNode.attributes) { 128 | node.children[sel].attributes[att] = newNode.attributes[att]; 129 | } 130 | } else { 131 | node.children[sel] = newNode; 132 | } 133 | } 134 | } 135 | } else if (!isEmpty(match[capEnd])) { 136 | // Node has finished 137 | return node; 138 | } else if (!isEmpty(match[capAttr])) { 139 | var line = match[capAttr].trim(); 140 | var attr = lineAttrX.exec(line); 141 | if (attr) { 142 | // Attribute 143 | var name = attr[1].trim(); 144 | var value = attr[2].trim(); 145 | if (args.ordered) { 146 | var obj = {}; 147 | obj['name'] = name; 148 | obj['value'] = value; 149 | obj['type'] = 'attr'; 150 | node[count++] = obj; 151 | } else { 152 | if (name in node.attributes) { 153 | var currVal = node.attributes[name]; 154 | if (!(currVal instanceof Array)) { 155 | node.attributes[name] = [currVal]; 156 | } 157 | node.attributes[name].push(value); 158 | } else { 159 | node.attributes[name] = value; 160 | } 161 | } 162 | } else { 163 | // Semicolon terminated line 164 | node[count++] = line; 165 | } 166 | } 167 | } 168 | 169 | return node; 170 | }; 171 | 172 | /** 173 | * @param node 174 | * A JSON node. 175 | * @param depth 176 | * The depth of the current node; used for indentation and 177 | * optional. 178 | * @param breaks 179 | * Whether to add line breaks in the output. 180 | */ 181 | base.toCSS = function (node, depth, breaks) { 182 | var cssString = ''; 183 | if (typeof depth == 'undefined') { 184 | depth = 0; 185 | } 186 | if (typeof breaks == 'undefined') { 187 | breaks = false; 188 | } 189 | if (node.attributes) { 190 | for (i in node.attributes) { 191 | var att = node.attributes[i]; 192 | if (att instanceof Array) { 193 | for (var j = 0; j < att.length; j++) { 194 | cssString += strAttr(i, att[j], depth); 195 | } 196 | } else { 197 | cssString += strAttr(i, att, depth); 198 | } 199 | } 200 | } 201 | if (node.children) { 202 | var first = true; 203 | for (i in node.children) { 204 | if (breaks && !first) { 205 | cssString += '\n'; 206 | } else { 207 | first = false; 208 | } 209 | cssString += strNode(i, node.children[i], depth); 210 | } 211 | } 212 | return cssString; 213 | }; 214 | 215 | /** 216 | * @param data 217 | * You can pass css string or the CSSJS.toJSON return value. 218 | * @param id (Optional) 219 | * To identify and easy removable of the style element 220 | * @param replace (Optional. defaults to TRUE) 221 | * Whether to remove or simply do nothing 222 | * @return HTMLLinkElement 223 | */ 224 | base.toHEAD = function (data, id, replace) { 225 | var head = document.getElementsByTagName('head')[0]; 226 | var xnode = document.getElementById(id); 227 | var _xnodeTest = (xnode !== null && xnode instanceof HTMLStyleElement); 228 | 229 | if (isEmpty(data) || !(head instanceof HTMLHeadElement)) return; 230 | if (_xnodeTest) { 231 | if (replace === true || isEmpty(replace)) { 232 | xnode.removeAttribute('id'); 233 | } else return; 234 | } 235 | if (isCssJson(data)) { 236 | data = base.toCSS(data); 237 | } 238 | 239 | var node = document.createElement('style'); 240 | node.type = 'text/css'; 241 | 242 | if (!isEmpty(id)) { 243 | node.id = id; 244 | } else { 245 | node.id = 'cssjson_' + timestamp(); 246 | } 247 | if (node.styleSheet) { 248 | node.styleSheet.cssText = data; 249 | } else { 250 | node.appendChild(document.createTextNode(data)); 251 | } 252 | 253 | head.appendChild(node); 254 | 255 | if (isValidStyleNode(node)) { 256 | if (_xnodeTest) { 257 | xnode.parentNode.removeChild(xnode); 258 | } 259 | } else { 260 | node.parentNode.removeChild(node); 261 | if (_xnodeTest) { 262 | xnode.setAttribute('id', id); 263 | node = xnode; 264 | } else return; 265 | } 266 | 267 | return node; 268 | }; 269 | 270 | // Alias 271 | 272 | if (typeof window != 'undefined') { 273 | window.createCSS = base.toHEAD; 274 | } 275 | 276 | // Helpers 277 | 278 | var isValidStyleNode = function (node) { 279 | return (node instanceof HTMLStyleElement) && node.sheet.cssRules.length > 0; 280 | }; 281 | 282 | var timestamp = function () { 283 | return Date.now() || +new Date(); 284 | }; 285 | 286 | var strAttr = function (name, value, depth) { 287 | return '\t'.repeat(depth) + name + ': ' + value + ';\n'; 288 | }; 289 | 290 | var strNode = function (name, value, depth) { 291 | var cssString = '\t'.repeat(depth) + name + ' {\n'; 292 | cssString += base.toCSS(value, depth + 1); 293 | cssString += '\t'.repeat(depth) + '}\n'; 294 | return cssString; 295 | }; 296 | 297 | }; -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /js/filereader.js: -------------------------------------------------------------------------------- 1 | /*! 2 | FileReader.js - v0.99 3 | A lightweight wrapper for common FileReader usage. 4 | Copyright 2014 Brian Grinstead - MIT License. 5 | See http://github.com/bgrins/filereader.js for documentation. 6 | */ 7 | 8 | (function(window, document) { 9 | 10 | var FileReader = window.FileReader; 11 | var FileReaderSyncSupport = false; 12 | var workerScript = "self.addEventListener('message', function(e) { var data=e.data; try { var reader = new FileReaderSync; postMessage({ result: reader[data.readAs](data.file), extra: data.extra, file: data.file})} catch(e){ postMessage({ result:'error', extra:data.extra, file:data.file}); } }, false);"; 13 | var syncDetectionScript = "onmessage = function(e) { postMessage(!!FileReaderSync); };"; 14 | var fileReaderEvents = ['loadstart', 'progress', 'load', 'abort', 'error', 'loadend']; 15 | var sync = false; 16 | var FileReaderJS = window.FileReaderJS = { 17 | enabled: false, 18 | setupInput: setupInput, 19 | setupDrop: setupDrop, 20 | setupClipboard: setupClipboard, 21 | setSync: function (value) { 22 | sync = value; 23 | 24 | if (sync && !FileReaderSyncSupport) { 25 | checkFileReaderSyncSupport(); 26 | } 27 | }, 28 | getSync: function() { 29 | return sync && FileReaderSyncSupport; 30 | }, 31 | output: [], 32 | opts: { 33 | dragClass: "drag", 34 | accept: false, 35 | readAsDefault: 'DataURL', 36 | readAsMap: { 37 | }, 38 | on: { 39 | loadstart: noop, 40 | progress: noop, 41 | load: noop, 42 | abort: noop, 43 | error: noop, 44 | loadend: noop, 45 | skip: noop, 46 | groupstart: noop, 47 | groupend: noop, 48 | beforestart: noop 49 | } 50 | } 51 | }; 52 | 53 | // Setup jQuery plugin (if available) 54 | if (typeof(jQuery) !== "undefined") { 55 | jQuery.fn.fileReaderJS = function(opts) { 56 | return this.each(function() { 57 | if (jQuery(this).is("input")) { 58 | setupInput(this, opts); 59 | } 60 | else { 61 | setupDrop(this, opts); 62 | } 63 | }); 64 | }; 65 | 66 | jQuery.fn.fileClipboard = function(opts) { 67 | return this.each(function() { 68 | setupClipboard(this, opts); 69 | }); 70 | }; 71 | } 72 | 73 | // Not all browsers support the FileReader interface. Return with the enabled bit = false. 74 | if (!FileReader) { 75 | return; 76 | } 77 | 78 | 79 | // makeWorker is a little wrapper for generating web workers from strings 80 | function makeWorker(script) { 81 | var URL = window.URL || window.webkitURL; 82 | var Blob = window.Blob; 83 | var Worker = window.Worker; 84 | 85 | if (!URL || !Blob || !Worker || !script) { 86 | return null; 87 | } 88 | 89 | var blob = new Blob([script]); 90 | var worker = new Worker(URL.createObjectURL(blob)); 91 | return worker; 92 | } 93 | 94 | // setupClipboard: bind to clipboard events (intended for document.body) 95 | function setupClipboard(element, opts) { 96 | 97 | if (!FileReaderJS.enabled) { 98 | return; 99 | } 100 | var instanceOptions = extend(extend({}, FileReaderJS.opts), opts); 101 | 102 | element.addEventListener("paste", onpaste, false); 103 | 104 | function onpaste(e) { 105 | var files = []; 106 | var clipboardData = e.clipboardData || {}; 107 | var items = clipboardData.items || []; 108 | 109 | for (var i = 0; i < items.length; i++) { 110 | var file = items[i].getAsFile(); 111 | 112 | if (file) { 113 | 114 | // Create a fake file name for images from clipboard, since this data doesn't get sent 115 | var matches = new RegExp("/\(.*\)").exec(file.type); 116 | if (!file.name && matches) { 117 | var extension = matches[1]; 118 | file.name = "clipboard" + i + "." + extension; 119 | } 120 | 121 | files.push(file); 122 | } 123 | } 124 | 125 | if (files.length) { 126 | processFileList(e, files, instanceOptions); 127 | e.preventDefault(); 128 | e.stopPropagation(); 129 | } 130 | } 131 | } 132 | 133 | // setupInput: bind the 'change' event to an input[type=file] 134 | function setupInput(input, opts) { 135 | 136 | if (!FileReaderJS.enabled) { 137 | return; 138 | } 139 | var instanceOptions = extend(extend({}, FileReaderJS.opts), opts); 140 | 141 | input.addEventListener("change", inputChange, false); 142 | input.addEventListener("drop", inputDrop, false); 143 | 144 | function inputChange(e) { 145 | processFileList(e, input.files, instanceOptions); 146 | } 147 | 148 | function inputDrop(e) { 149 | e.stopPropagation(); 150 | e.preventDefault(); 151 | processFileList(e, e.dataTransfer.files, instanceOptions); 152 | } 153 | } 154 | 155 | // setupDrop: bind the 'drop' event for a DOM element 156 | function setupDrop(dropbox, opts) { 157 | 158 | if (!FileReaderJS.enabled) { 159 | return; 160 | } 161 | var instanceOptions = extend(extend({}, FileReaderJS.opts), opts); 162 | var dragClass = instanceOptions.dragClass; 163 | var initializedOnBody = false; 164 | 165 | // Bind drag events to the dropbox to add the class while dragging, and accept the drop data transfer. 166 | dropbox.addEventListener("dragenter", onlyWithFiles(dragenter), false); 167 | dropbox.addEventListener("dragleave", onlyWithFiles(dragleave), false); 168 | dropbox.addEventListener("dragover", onlyWithFiles(dragover), false); 169 | dropbox.addEventListener("drop", onlyWithFiles(drop), false); 170 | 171 | // Bind to body to prevent the dropbox events from firing when it was initialized on the page. 172 | document.body.addEventListener("dragstart", bodydragstart, true); 173 | document.body.addEventListener("dragend", bodydragend, true); 174 | document.body.addEventListener("drop", bodydrop, false); 175 | 176 | function bodydragend(e) { 177 | initializedOnBody = false; 178 | } 179 | 180 | function bodydragstart(e) { 181 | initializedOnBody = true; 182 | } 183 | 184 | function bodydrop(e) { 185 | if (e.dataTransfer.files && e.dataTransfer.files.length ){ 186 | e.stopPropagation(); 187 | e.preventDefault(); 188 | } 189 | } 190 | 191 | function onlyWithFiles(fn) { 192 | return function() { 193 | if (!initializedOnBody) { 194 | fn.apply(this, arguments); 195 | } 196 | }; 197 | } 198 | 199 | function drop(e) { 200 | e.stopPropagation(); 201 | e.preventDefault(); 202 | if (dragClass) { 203 | removeClass(dropbox, dragClass); 204 | } 205 | processFileList(e, e.dataTransfer.files, instanceOptions); 206 | } 207 | 208 | function dragenter(e) { 209 | e.stopPropagation(); 210 | e.preventDefault(); 211 | if (dragClass) { 212 | addClass(dropbox, dragClass); 213 | } 214 | } 215 | 216 | function dragleave(e) { 217 | if (dragClass) { 218 | removeClass(dropbox, dragClass); 219 | } 220 | } 221 | 222 | function dragover(e) { 223 | e.stopPropagation(); 224 | e.preventDefault(); 225 | if (dragClass) { 226 | addClass(dropbox, dragClass); 227 | } 228 | } 229 | } 230 | 231 | // setupCustomFileProperties: modify the file object with extra properties 232 | function setupCustomFileProperties(files, groupID) { 233 | for (var i = 0; i < files.length; i++) { 234 | var file = files[i]; 235 | file.extra = { 236 | nameNoExtension: file.name.substring(0, file.name.lastIndexOf('.')), 237 | extension: file.name.substring(file.name.lastIndexOf('.') + 1), 238 | fileID: i, 239 | uniqueID: getUniqueID(), 240 | groupID: groupID, 241 | prettySize: prettySize(file.size) 242 | }; 243 | } 244 | } 245 | 246 | // getReadAsMethod: return method name for 'readAs*' - http://www.w3.org/TR/FileAPI/#reading-a-file 247 | function getReadAsMethod(type, readAsMap, readAsDefault) { 248 | for (var r in readAsMap) { 249 | if (type.match(new RegExp(r))) { 250 | return 'readAs' + readAsMap[r]; 251 | } 252 | } 253 | return 'readAs' + readAsDefault; 254 | } 255 | 256 | // processFileList: read the files with FileReader, send off custom events. 257 | function processFileList(e, files, opts) { 258 | 259 | var filesLeft = files.length; 260 | var group = { 261 | groupID: getGroupID(), 262 | files: files, 263 | started: new Date() 264 | }; 265 | 266 | function groupEnd() { 267 | group.ended = new Date(); 268 | opts.on.groupend(group); 269 | } 270 | 271 | function groupFileDone() { 272 | if (--filesLeft === 0) { 273 | groupEnd(); 274 | } 275 | } 276 | 277 | FileReaderJS.output.push(group); 278 | setupCustomFileProperties(files, group.groupID); 279 | 280 | opts.on.groupstart(group); 281 | 282 | // No files in group - end immediately 283 | if (!files.length) { 284 | groupEnd(); 285 | return; 286 | } 287 | 288 | var supportsSync = sync && FileReaderSyncSupport; 289 | var syncWorker; 290 | 291 | // Only initialize the synchronous worker if the option is enabled - to prevent the overhead 292 | if (supportsSync) { 293 | syncWorker = makeWorker(workerScript); 294 | syncWorker.onmessage = function(e) { 295 | var file = e.data.file; 296 | var result = e.data.result; 297 | 298 | // Workers seem to lose the custom property on the file object. 299 | if (!file.extra) { 300 | file.extra = e.data.extra; 301 | } 302 | 303 | file.extra.ended = new Date(); 304 | 305 | // Call error or load event depending on success of the read from the worker. 306 | opts.on[result === "error" ? "error" : "load"]({ target: { result: result } }, file); 307 | groupFileDone(); 308 | }; 309 | } 310 | 311 | Array.prototype.forEach.call(files, function(file) { 312 | 313 | file.extra.started = new Date(); 314 | 315 | if (opts.accept && !file.type.match(new RegExp(opts.accept))) { 316 | opts.on.skip(file); 317 | groupFileDone(); 318 | return; 319 | } 320 | 321 | if (opts.on.beforestart(file) === false) { 322 | opts.on.skip(file); 323 | groupFileDone(); 324 | return; 325 | } 326 | 327 | var readAs = getReadAsMethod(file.type, opts.readAsMap, opts.readAsDefault); 328 | 329 | if (syncWorker) { 330 | syncWorker.postMessage({ 331 | file: file, 332 | extra: file.extra, 333 | readAs: readAs 334 | }); 335 | } 336 | else { 337 | 338 | var reader = new FileReader(); 339 | reader.originalEvent = e; 340 | 341 | fileReaderEvents.forEach(function(eventName) { 342 | reader['on' + eventName] = function(e) { 343 | if (eventName == 'load' || eventName == 'error') { 344 | file.extra.ended = new Date(); 345 | } 346 | opts.on[eventName](e, file); 347 | if (eventName == 'loadend') { 348 | groupFileDone(); 349 | } 350 | }; 351 | }); 352 | reader[readAs](file); 353 | } 354 | }); 355 | } 356 | 357 | // checkFileReaderSyncSupport: Create a temporary worker and see if FileReaderSync exists 358 | function checkFileReaderSyncSupport() { 359 | var worker = makeWorker(syncDetectionScript); 360 | if (worker) { 361 | worker.onmessage =function(e) { 362 | FileReaderSyncSupport = e.data; 363 | }; 364 | worker.postMessage({}); 365 | } 366 | } 367 | 368 | // noop: do nothing 369 | function noop() { 370 | 371 | } 372 | 373 | // extend: used to make deep copies of options object 374 | function extend(destination, source) { 375 | for (var property in source) { 376 | if (source[property] && source[property].constructor && 377 | source[property].constructor === Object) { 378 | destination[property] = destination[property] || {}; 379 | arguments.callee(destination[property], source[property]); 380 | } 381 | else { 382 | destination[property] = source[property]; 383 | } 384 | } 385 | return destination; 386 | } 387 | 388 | // hasClass: does an element have the css class? 389 | function hasClass(el, name) { 390 | return new RegExp("(?:^|\\s+)" + name + "(?:\\s+|$)").test(el.className); 391 | } 392 | 393 | // addClass: add the css class for the element. 394 | function addClass(el, name) { 395 | if (!hasClass(el, name)) { 396 | el.className = el.className ? [el.className, name].join(' ') : name; 397 | } 398 | } 399 | 400 | // removeClass: remove the css class from the element. 401 | function removeClass(el, name) { 402 | if (hasClass(el, name)) { 403 | var c = el.className; 404 | el.className = c.replace(new RegExp("(?:^|\\s+)" + name + "(?:\\s+|$)", "g"), " ").replace(/^\s\s*/, '').replace(/\s\s*$/, ''); 405 | } 406 | } 407 | 408 | // prettySize: convert bytes to a more readable string. 409 | function prettySize(bytes) { 410 | var s = ['bytes', 'kb', 'MB', 'GB', 'TB', 'PB']; 411 | var e = Math.floor(Math.log(bytes)/Math.log(1024)); 412 | return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+" "+s[e]; 413 | } 414 | 415 | // getGroupID: generate a unique int ID for groups. 416 | var getGroupID = (function(id) { 417 | return function() { 418 | return id++; 419 | }; 420 | })(0); 421 | 422 | // getUniqueID: generate a unique int ID for files 423 | var getUniqueID = (function(id) { 424 | return function() { 425 | return id++; 426 | }; 427 | })(0); 428 | 429 | // The interface is supported, bind the FileReaderJS callbacks 430 | FileReaderJS.enabled = true; 431 | 432 | })(this, document); -------------------------------------------------------------------------------- /js/main.js: -------------------------------------------------------------------------------- 1 | /* Helper methods */ 2 | String.prototype.f = function () { 3 | var s = this, 4 | i = arguments.length; 5 | 6 | while (i--) { 7 | s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]); 8 | } 9 | return s; 10 | }; 11 | 12 | String.prototype.repeat = function (num) { 13 | return new Array(num + 1).join(this); 14 | }; 15 | 16 | function pushUnique(array, item) { 17 | if (array.indexOf(item) == -1) { 18 | array.push(item); 19 | return true; 20 | } 21 | return false; 22 | } 23 | 24 | 25 | function toBool(s, defValue) { 26 | if (typeof s === "undefined") { 27 | return typeof defValue !== "undefined" ? defValue : false; 28 | } 29 | return "false" !== s; 30 | } 31 | 32 | if (typeof String.prototype.endsWith !== 'function') { 33 | String.prototype.endsWith = function (suffix) { 34 | return this.indexOf(suffix, this.length - suffix.length) !== -1; 35 | }; 36 | } 37 | 38 | if (typeof String.prototype.startsWith !== 'function') { 39 | String.prototype.startsWith = function (str) { 40 | return this.indexOf(str) == 0; 41 | }; 42 | } 43 | 44 | jQuery.fn.reverse = [].reverse; 45 | 46 | /* ------ */ 47 | 48 | var groupData = { groupSize:0, zip:null, log:[], errors:0, files:[]}; 49 | 50 | var fileReaderOpts = { 51 | dragClass: "drag", readAsDefault: "Text", on: { 52 | load: function (e, file) { 53 | if (groupData.groupSize == 1) { 54 | loadFile(e, file, false) 55 | } else { 56 | groupData.files.push({e: e, file: file}); 57 | } 58 | }, 59 | groupstart: function (g) { 60 | resetGroupData(); 61 | groupData.zip = new JSZip(); 62 | groupData.groupSize = g.files.length; 63 | }, 64 | groupend: function (g) { 65 | //Multiple files 66 | if (groupData.groupSize > 1) { 67 | groupData.groupSize = 0; 68 | var dlg = $('#dlg-files'); 69 | var btnPrimary = dlg.find(".btn-primary"); 70 | 71 | refreshSettings(); 72 | dlg.find("#files-count").text(groupData.files.length); 73 | btnPrimary.text("Export"); 74 | dlg.modal().on(); 75 | 76 | btnPrimary.removeClass("disabled"); 77 | 78 | btnPrimary.unbind("click"); 79 | btnPrimary.on("click", function () { 80 | if (btnPrimary.hasClass("disabled")) return; 81 | 82 | btnPrimary.addClass("disabled"); 83 | btnPrimary.text("Please wait ..."); 84 | 85 | //To prevent UI lag 86 | setTimeout(function () { 87 | for (var i = 0; i < groupData.files.length; i++) { 88 | var f = groupData.files[i]; 89 | loadFile(f.e, f.file, true); 90 | } 91 | 92 | groupData.log = "

Files converted: " + (groupData.files.length - groupData.errors) + " / " + groupData.files.length + "

" + groupData.log; 93 | groupData.zip.file("log.html", groupData.log); 94 | 95 | saveAs(groupData.zip.generate({type: "blob"}), "export.zip"); 96 | dlg.modal("hide"); 97 | }, 250); 98 | }); 99 | 100 | dlg.unbind("hidden.bs.modal"); 101 | dlg.on("hidden.bs.modal", function () { 102 | resetGroupData(); 103 | }) 104 | } 105 | } 106 | } 107 | }; 108 | 109 | if (typeof FileReader === "undefined") { 110 | $('#dropzone, #dropzone-dialog').hide(); 111 | $('#compat-error').show(); 112 | } else { 113 | $('#dropzone, #dropzone-dialog').fileReaderJS(fileReaderOpts); 114 | } 115 | 116 | if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1){ 117 | localStorage.bakeTransforms = false; 118 | $(".bake-transforms").prop("disabled", true); 119 | alert("Sorry but svg2android doesn't work well on Firefox, please use Google Chrome or other browser for now."); 120 | } 121 | 122 | //Copy settings to dialog 123 | var dlg = $('#dlg-files'); 124 | dlg.find('.modal-body').html($("#settings-area").clone()); 125 | 126 | //Clipboard paste event 127 | $("body").bind("paste", function(e) { 128 | var pastedData = e.originalEvent.clipboardData.getData('text'); 129 | if (pastedData.length > 0) { 130 | groupData.groupSize = 1; 131 | refreshSettings(); 132 | parseSingleFile(pastedData); 133 | } 134 | }); 135 | 136 | $("#deprecation-text").on("click", function (ev) { 137 | ev.stopPropagation(); 138 | }); 139 | 140 | showLastUpdate("svg2android"); 141 | 142 | /* ------ */ 143 | 144 | var DRAW_LINE = "l"; //used as default parameter when no found in path 145 | var START_PATH = "M"; 146 | var END_PATH = "Z"; 147 | var INDENT = " "; 148 | 149 | var pathsParsedCount = 0; 150 | var generatedOutput = ""; 151 | var lastFileName = ""; 152 | var lastFileData; 153 | var warnings = []; 154 | var svgStyles = {}; 155 | var globalSvg; 156 | 157 | var clipPathEnabled = false; 158 | var clipPathItemsCount = 0; 159 | var clipPathMerged = []; 160 | 161 | function loadFile(e, file, multipleFiles) { 162 | lastFileName = file.name; 163 | refreshSettings(); 164 | 165 | if (multipleFiles) { 166 | parseMultipleFiles(e.target.result) 167 | } else { 168 | parseSingleFile(e.target.result); 169 | } 170 | } 171 | 172 | function resetGroupData() { 173 | groupData.zip = new JSZip(); 174 | groupData.log = []; 175 | groupData.files = []; 176 | groupData.errors = 0; 177 | groupData.groupSize = 0; 178 | } 179 | 180 | function refreshSettings() { 181 | $(".opt-id-as-name").prop("checked", toBool(localStorage.useIdAsName)); 182 | $(".bake-transforms").prop("checked", toBool(localStorage.bakeTransforms)); 183 | $(".clear-groups").prop("checked", toBool(localStorage.clearGroups, true)); 184 | $(".wordwrap-pathdata").prop("checked", toBool(localStorage.wordWrapPathData, false)); 185 | } 186 | 187 | function extractFileNameWithoutExt(filename) { 188 | var dotIndex = filename.lastIndexOf("."); 189 | if (dotIndex > -1) { 190 | filename = filename.substr(0, dotIndex); 191 | } 192 | filename = filename.toLowerCase(); 193 | filename = filename.replace(/[^a-z0-9]/gi, '_'); 194 | 195 | return filename; 196 | } 197 | 198 | //Main parse & convert logic 199 | function recursiveTreeWalk(parent, groupLevel, clipPath) { 200 | parent.children().each(function () { 201 | var current = $(this); 202 | if (current.is("a") && current.children().length > 0) { 203 | recursiveTreeWalk(current, groupLevel, clipPath); 204 | } else if (current.is("g") && current.children().length > 0) { //Group tag, ignore empty groups 205 | var group = parseGroup(current); 206 | var ignoreGroup = !(toBool(localStorage.clearGroups, true) && !group.isSet); 207 | if (ignoreGroup) printGroupStart(group, groupLevel); 208 | 209 | if (ignoreGroup) groupLevel++; 210 | recursiveTreeWalk(current, groupLevel, clipPath); 211 | if (ignoreGroup) groupLevel--; 212 | 213 | if (ignoreGroup) printGroupEnd(groupLevel); 214 | } else if (current.is("path")) { 215 | var pathD = parsePathD(current); 216 | if (pathD != null) { 217 | printPath(pathD, getStyles(current), groupLevel, clipPath); 218 | } else { 219 | pushUnique(warnings, "found path(s) without data (empty or invalid parameter d)"); 220 | } 221 | } else if (current.is("line")) { 222 | printPath(ShapeConverter.convertLine(current), getStyles(current), groupLevel, clipPath); 223 | } else if (current.is("rect")) { 224 | printPath(ShapeConverter.convertRect(current), getStyles(current), groupLevel, clipPath); 225 | } else if (current.is("circle")) { 226 | printPath(ShapeConverter.convertCircle(current), getStyles(current), groupLevel, clipPath); 227 | } else if (current.is("ellipse")) { 228 | printPath(ShapeConverter.convertEllipse(current), getStyles(current), groupLevel, clipPath); 229 | } else if (current.is("polyline")) { 230 | printPath(ShapeConverter.convertPolygon(current, true), getStyles(current), groupLevel, clipPath); 231 | } else if (current.is("polygon")) { 232 | printPath(ShapeConverter.convertPolygon(current, false), getStyles(current), groupLevel, clipPath); 233 | } else if (current.is("text")) { 234 | pushUnique(warnings, "text element is not supported, export all text into path"); 235 | } else if (current.is("image")) { 236 | pushUnique(warnings, "image element is not supported, you must vectorize raster image"); 237 | } 238 | }); 239 | } 240 | 241 | function preprocessReferences(svg) { 242 | svg.find("use").each(function () { 243 | var current = $(this); 244 | substituteUseRef(svg, current); 245 | }); 246 | } 247 | 248 | function getStyles(el) { 249 | var styles = parseStyles(el); 250 | 251 | var parentStyles = null; 252 | 253 | //Inherit all parent group styles in reversed order (to override them correctly) 254 | el.parents("g").reverse().each(function () { 255 | var current = $(this); 256 | if (parentStyles == null) { 257 | parentStyles = []; 258 | } 259 | jQuery.extend(parentStyles, parseStyles(current)); 260 | }); 261 | 262 | //Do not propagate id from group to childrens 263 | if (parentStyles != null && typeof parentStyles["id"] !== "undefined") { 264 | parentStyles["id"] = undefined; 265 | } 266 | 267 | return [styles, parentStyles]; 268 | } 269 | 270 | function substituteUseRef(parent, current) { 271 | var href = current.attr("xlink:href"); 272 | if (typeof href !== "undefined") { 273 | href = href.trim(); 274 | //Check if valid href 275 | if (href.length > 1 && href.startsWith("#")) { 276 | //Find definition in svg 277 | var defs = $(parent).find("[id='" + href.substr(1) + "']"); 278 | if (defs.length) { 279 | defs = defs.clone(); 280 | 281 | //Copy overriding attributes into children 282 | $.each(current.prop("attributes"), function () { 283 | defs.attr(this.name, this.value); 284 | }); 285 | 286 | current.replaceWith(defs); 287 | } else { 288 | console.warn("Found tag but did not found appropriate block in for id " + href); 289 | } 290 | } 291 | } 292 | } 293 | 294 | function parseGroup(groupTag) { 295 | var transform = groupTag.attr("transform"); 296 | var id = groupTag.attr("id"); 297 | var groupTransform = {transformX: 0, transformY: 0, scaleX: 1, scaleY: 1, 298 | rotate:0, rotatePivotX:-1, rotatePivotY:-1, id:"", isSet:false, clipPathId:null}; 299 | if (typeof transform !== "undefined") { 300 | var regex = /((\w|\s)+)\(([^)]+)/mg; 301 | var result; 302 | while (result = regex.exec(transform)) { 303 | var split = result[3].split(/[,\s]+/); 304 | var transformName = result[1].trim(); 305 | if (transformName == "translate") { 306 | groupTransform.transformX = split[0]; 307 | groupTransform.transformY = split[1] || 0; 308 | groupTransform.isSet = true; 309 | } else if (transformName == "scale") { 310 | groupTransform.scaleX = split[0]; 311 | groupTransform.scaleY = split[1] || 0; 312 | groupTransform.isSet = true; 313 | } else if (transformName == "rotate") { 314 | groupTransform.rotate = split[0]; 315 | groupTransform.rotatePivotX = split[1] || -1; 316 | groupTransform.rotatePivotY = split[2] || -1; 317 | groupTransform.isSet = true; 318 | } else { 319 | pushUnique(warnings, "group transform '" + transformName + "' is not supported, use option Bake transforms into path") 320 | } 321 | } 322 | } 323 | if (typeof id !== "undefined") { 324 | groupTransform.id = id; 325 | } 326 | 327 | var styles = getStyles(groupTag)[0]; 328 | if (typeof styles["clip-path"] !== "undefined") { 329 | groupTransform.isSet = true; 330 | groupTransform.clipPathId = styles["clip-path"]; 331 | } 332 | 333 | return groupTransform; 334 | } 335 | 336 | function parsePathD(pathData) { 337 | var path = pathData.attr("d"); 338 | 339 | if (typeof path === "undefined") { 340 | return null; 341 | } 342 | 343 | path = path.replace(/\s{2,}/g, " "); //replace extra spaces 344 | 345 | if (path.match(/-?\d*\.?\d+e[+-]?\d+/g)) { 346 | pushUnique(warnings, "found some numbers with scientific E notation in pathData which Android probably does not support. " + 347 | "Please fix It manually by editing your editor precision or manually by editing pathData"); 348 | } 349 | 350 | //Check path If contains draw otherwise use default l 351 | var pathStart = false, bigM = false, skipMove = false, stop = false; 352 | var pathRebuild = ""; 353 | path.split(" ").forEach(function (t) { 354 | if (stop) { 355 | pathRebuild += t + " "; 356 | return; 357 | } 358 | 359 | if (t.toUpperCase() == START_PATH) { 360 | pathStart = true; 361 | bigM = t == START_PATH; 362 | } else if (skipMove && pathStart) { 363 | if (!(t.indexOf(",") == -1 && isNaN(t))) { 364 | //t = (bigM ? DRAW_LINE.toUpperCase() : DRAW_LINE) + " " + t; 365 | //TODO: check If this condition was needed 366 | } 367 | stop = true; 368 | } else if (pathStart) { 369 | skipMove = true; 370 | } 371 | 372 | pathRebuild += t + " "; 373 | }); 374 | 375 | path = fixPathPositioning(pathRebuild); 376 | path = fixNumberFormatting(path); 377 | 378 | if (!path.endsWith(" ")) { 379 | path += " "; 380 | } 381 | 382 | if (toBool(localStorage.wordWrapPathData)) { 383 | return wordwrap(path.trim(), 80, "\n"); 384 | } else { 385 | return path.trim(); 386 | } 387 | } 388 | 389 | 390 | function parseStyles(path) { 391 | //Convert attributes to style 392 | var attributes = path[0].attributes; 393 | var stylesArray = {}; 394 | for (var n = 0; n < attributes.length; n++) { 395 | var name = attributes[n].name; 396 | var value = attributes[n].value; 397 | if (name == "style") { 398 | //Fix CSSJSON bug 399 | if (!value.endsWith(";")) { 400 | value += ";" 401 | } 402 | var cssAttributes = CSSJSON.toJSON(value).attributes; 403 | parseCssAttributes(stylesArray, cssAttributes); 404 | } else if (name == "class") { 405 | var val = "." + value.trim(); 406 | if (typeof svgStyles.children !== "undefined" && typeof svgStyles.children[val] !== "undefined") { 407 | parseCssAttributes(stylesArray, svgStyles.children[val].attributes); 408 | } 409 | } else { 410 | stylesArray[name] = value; 411 | checkAttribute(name, value); 412 | } 413 | } 414 | 415 | return stylesArray; 416 | } 417 | 418 | function parseCssAttributes(stylesArray, cssAttributes) { 419 | for (var key in cssAttributes) { 420 | if (cssAttributes.hasOwnProperty(key)) { 421 | stylesArray[key] = cssAttributes[key]; 422 | 423 | checkAttribute(key, cssAttributes[key]); 424 | } 425 | } 426 | } 427 | 428 | function checkAttribute(key, val) { 429 | if ((key == "fill" || key == "stroke") && val.startsWith("url")) { 430 | pushUnique(warnings, "found fill(s) or stroke(s) which uses url() (gradients and patterns are not supported in Android)"); 431 | } else if ((key == "fill-rule") && val == "evenodd") { 432 | pushUnique(warnings, "found attribute 'fill-rule:evenodd' which is supported only on Android API 24 and higher - (more info)"); 433 | } 434 | } 435 | 436 | function printGroupStart(groupTransform, groupLevel) { 437 | generatedOutput += INDENT.repeat(groupLevel + 1) + '\n'; 453 | } 454 | 455 | function printClipPath(pathData, groupLevel) { 456 | generatedOutput += INDENT.repeat(groupLevel + 1) + ' 0) { 469 | clipPathMerged = []; 470 | clipPathItemsCount = defCount; 471 | recursiveTreeWalk(clipDefs, groupLevel, true); 472 | } 473 | } 474 | } 475 | 476 | function printPath(pathData, stylesArray, groupLevel, clipPath) { 477 | var styles = stylesArray[0]; 478 | var parentGroupStyles = stylesArray[1]; 479 | 480 | if (pathData == null) { 481 | return; 482 | } 483 | 484 | if (styles.hasOwnProperty("transform")) { 485 | pushUnique(warnings, "transforms on path are not supported, use option Bake transforms into path") 486 | } 487 | 488 | //Check for clip-path (before inheriting styles from group) 489 | checkForClipPath(styles["clip-path"], groupLevel); 490 | 491 | if (parentGroupStyles != null) { 492 | //Inherit styles from group first 493 | for (var styleName in parentGroupStyles) { 494 | if (typeof styles[styleName] === "undefined") { 495 | styles[styleName] = parentGroupStyles[styleName]; 496 | } 497 | } 498 | } 499 | //Parent opacity setting - multiply fill-opacity and stroke-opacity 500 | var opacity = styles["opacity"]; 501 | if (typeof opacity !== "undefined") { 502 | if (typeof styles["fill-opacity"] !== "undefined") { 503 | styles["fill-opacity"] *= opacity; 504 | } else { 505 | styles["fill-opacity"] = opacity; 506 | } 507 | if (typeof styles["stroke-opacity"] !== "undefined") { 508 | styles["stroke-opacity"] *= opacity; 509 | } else { 510 | styles["stroke-opacity"] = opacity; 511 | } 512 | } 513 | 514 | //If fill is omitted use default black 515 | if (typeof styles["fill"] === "undefined") { 516 | styles["fill"] = "#000000"; 517 | } 518 | 519 | //Handle fill-rule 520 | if (typeof styles["fill-rule"] !== "undefined" && styles["fill-rule"].toLowerCase() == "evenodd") { 521 | styles["fill-rule"] = "evenOdd"; 522 | } else { 523 | styles["fill-rule"] = "nonZero"; 524 | } 525 | 526 | //If strokeWidth is needed but omitted, default to 1 527 | var needsStrokeWidth = (typeof styles["stroke"] !== "undefined") || 528 | (typeof styles["stroke-opacity"] !== "undefined") || 529 | (typeof styles["stroke-alpha"] !== "undefined") || 530 | (typeof styles["stroke-linejoin"] !== "undefined") || 531 | (typeof styles["stroke-miterlimit"] !== "undefined") || 532 | (typeof styles["stroke-linecap"] !== "undefined"); 533 | if (needsStrokeWidth && (typeof styles["stroke-width"] === "undefined")) { 534 | styles["stroke-width"] = "1"; 535 | pushUnique(warnings, "stroke-width not found on path one or more times. Defaulting all instances to 1."); 536 | } 537 | 538 | if (!clipPath) { 539 | generatedOutput += INDENT.repeat(groupLevel + 1) + '= clipPathItemsCount) { 557 | printClipPath(clipPathMerged.join(" "), groupLevel); 558 | } 559 | } 560 | } 561 | 562 | function generateCode(inputXml) { 563 | var resultData = { error:null, warnings:null, code:null }; 564 | 565 | var xml; 566 | try { 567 | xml = $($.parseXML(inputXml)); 568 | } catch (e) { 569 | resultData.error = "Error: not valid SVG file."; 570 | return resultData; 571 | } 572 | 573 | //Reset previous 574 | pathsParsedCount = 0; 575 | warnings = []; 576 | svgStyles = {}; 577 | 578 | var svg = xml.find("svg"); 579 | globalSvg = svg; 580 | preprocessReferences(svg); 581 | 582 | if (toBool(localStorage.bakeTransforms)) { 583 | try { 584 | flatten(svg[0], false, true); 585 | } catch (e) { 586 | console.error(e); 587 | resultData.error = "Error: problem during parsing svg (flatten failed)."; 588 | return resultData; 589 | } 590 | } 591 | 592 | var cssStyle = svg.find("style"); 593 | if (cssStyle.length) { 594 | svgStyles = CSSJSON.toJSON(cssStyle.text().trim(), {split:true}); 595 | } 596 | 597 | //Parse dimensions 598 | var dimensions = getDimensions(svg); 599 | var width = dimensions.width; 600 | var height = dimensions.height; 601 | 602 | //XML Vector start 603 | generatedOutput = '\n'; 604 | generatedOutput += ' 1) { 624 | var warnText = ""; 625 | warnings.forEach(function (w, i) { 626 | warnText += "Warning #" + (i + 1) + ":" + w + ""; 627 | }); 628 | resultData.warnings = "" + warnText + "
"; 629 | } 630 | 631 | //SVG must contain path(s) 632 | if (pathsParsedCount == 0) { 633 | resultData.error = "No shape elements found in svg."; 634 | return resultData; 635 | } 636 | 637 | resultData.code = generatedOutput; 638 | 639 | return resultData; 640 | } 641 | 642 | function parseSingleFile(inputXml) { 643 | lastFileData = inputXml; 644 | 645 | $(".alert").hide(); 646 | 647 | var data = generateCode(inputXml); 648 | 649 | if (data.warnings !== null) { 650 | setMessage(data.warnings, "alert-warning"); 651 | } 652 | 653 | if (data.error !== null) { 654 | setMessage(data.error, "alert-danger"); 655 | $("#output-box").hide(); 656 | } else { 657 | $("#output-code").text(data.code).animate({scrollTop: 0}, "fast"); 658 | $("#output-box").fadeIn(); 659 | $(".nouploadinfo").hide(); 660 | $("#dropzone").animate({height: 50}, 500); 661 | $("#success-box").show(); 662 | } 663 | } 664 | 665 | function parseMultipleFiles(inputXml) { 666 | var data = generateCode(inputXml); 667 | 668 | groupData.log += "

" + lastFileName + "

"; 669 | if (data.warnings !== null) { 670 | groupData.log += data.warnings + "
"; 671 | } 672 | 673 | if (data.error !== null) { 674 | groupData.log += data.error + "
"; 675 | groupData.errors++; 676 | } else { 677 | if (data.warnings === null) { 678 | groupData.log += "OK
"; 679 | } 680 | groupData.zip.file(extractFileNameWithoutExt(lastFileName) + ".xml", data.code); 681 | } 682 | } 683 | 684 | function fixPathPositioning(path) { 685 | return path.replace(/^\s*m/, START_PATH).replace(/^\s*z/, END_PATH); 686 | } 687 | 688 | function fixNumberFormatting(path) { 689 | //Fix spacing between numbers 690 | var result = path.replace(/(\.\d+)(\.\d+)\s?/g, "\$1 \$2 "); 691 | //Fix decimal numbers which does not start with 0 692 | result = result.replace(/([^\d])\./g, "\$10."); 693 | return result; 694 | } 695 | 696 | function getDimensions(svg) { 697 | var widthAttr = svg.attr("width"); 698 | var heightAttr = svg.attr("height"); 699 | var viewBoxAttr = svg.attr("viewBox"); 700 | 701 | if (typeof viewBoxAttr === "undefined") { 702 | if (typeof widthAttr === "undefined" || typeof heightAttr === "undefined") { 703 | pushUnique(warnings, "width or height not set for svg (set -1)"); 704 | return {width: -1, height: -1}; 705 | } else { 706 | return {width: convertDimensionToPx(widthAttr), height: convertDimensionToPx(heightAttr)}; 707 | } 708 | } else { 709 | var viewBoxAttrParts = viewBoxAttr.split(/[,\s]+/); 710 | if (viewBoxAttrParts[0] > 0 || viewBoxAttrParts[1] > 0) { 711 | pushUnique(warnings, "viewbox minx/miny is other than 0 (not supported)"); 712 | } 713 | return {width: viewBoxAttrParts[2], height: viewBoxAttrParts[3]}; 714 | } 715 | 716 | } 717 | 718 | function removeNonNumeric(input) { 719 | if (typeof input === "undefined") return input; 720 | return input.replace(/[^0-9.]/g, ""); 721 | } 722 | 723 | 724 | function generateAttr(name, val, groupLevel, def, end) { 725 | if (typeof val === "undefined" || val == def || val == "null") return ""; 726 | 727 | var result = INDENT.repeat(groupLevel + 2) + 'android:{0}="{1}"'.f(name, val); 728 | 729 | if (end) { 730 | result += ' />'; 731 | } 732 | result += '\n'; 733 | return result; 734 | } 735 | 736 | function selectAll() { 737 | var el = $("#output-code")[0]; 738 | if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") { 739 | var range = document.createRange(); 740 | range.selectNodeContents(el); 741 | var sel = window.getSelection(); 742 | sel.removeAllRanges(); 743 | sel.addRange(range); 744 | } else if (typeof document.selection != "undefined" && typeof document.body.createTextRange != "undefined") { 745 | var textRange = document.body.createTextRange(); 746 | textRange.moveToElementText(el); 747 | textRange.select(); 748 | } 749 | } 750 | 751 | function download() { 752 | var blob = new Blob([$("#output-code").text()], {type: "text/xml;charset=utf-8"}); 753 | var filename = extractFileNameWithoutExt(lastFileName) || ""; 754 | saveAs(blob, filename.length > 0 ? (filename + ".xml") : "vector.xml", true); 755 | } 756 | 757 | function dropzoneClick() { 758 | $("#dropzone-dialog").click(); 759 | } 760 | 761 | function setMessage(text, type) { 762 | var info = $("." + type + ".box"); 763 | info.html(text); 764 | info.removeClass(); 765 | info.addClass("alert"); 766 | info.addClass("box"); 767 | info.addClass(type); 768 | info.show(); 769 | } 770 | 771 | function useIdAsName(el) { 772 | localStorage.useIdAsName = el.checked; 773 | if (groupData.groupSize == 1) parseSingleFile(lastFileData); 774 | } 775 | 776 | function bakeTransforms(el) { 777 | localStorage.bakeTransforms = el.checked; 778 | if (groupData.groupSize == 1) parseSingleFile(lastFileData); 779 | } 780 | 781 | function clearGroups(el) { 782 | localStorage.clearGroups = el.checked; 783 | if (groupData.groupSize == 1) parseSingleFile(lastFileData); 784 | } 785 | 786 | function enableClipPaths(el) { 787 | clipPathEnabled = el.checked; 788 | if (groupData.groupSize == 1) parseSingleFile(lastFileData); 789 | } 790 | 791 | function wordwrap(str, width, brk, cut) { 792 | brk = brk || '\n'; 793 | width = width || 75; 794 | cut = cut || false; 795 | 796 | if (!str) { 797 | return str; 798 | } 799 | 800 | var regex = '.{1,' + width + '}(\\s|$)' + (cut ? '|.{' + width + '}|.+$' : '|\\S+?(\\s|$)'); 801 | 802 | var matches = str.match(new RegExp(regex, 'g')); 803 | // trim off leading/trailing spaces from the matched strings 804 | for (i = 0; i < matches.length; i++) { 805 | matches[i] = matches[i].trim(); 806 | } 807 | 808 | return matches.join(brk); 809 | } 810 | 811 | function enableWordWrapPathData(el) { 812 | localStorage.wordWrapPathData = el.checked; 813 | if (groupData.groupSize == 1) parseSingleFile(lastFileData); 814 | } 815 | 816 | function parseRgb(color) { 817 | var parts = color.replace(/(rgb)|\(|\)/g, "").split(","); 818 | if (parts.length == 3) { //is a valid rgb 819 | var rgb = []; 820 | for (var i = 0; i < parts.length; i++) { 821 | var part = parts[i].trim(); 822 | var val = Math.max(0, parseFloat(part)); 823 | rgb[i] = part.endsWith("%") ? Math.round(((Math.min(100, val) / 100) * 255)) : val; 824 | } 825 | return rgb; 826 | } else { 827 | return null; 828 | } 829 | 830 | } 831 | 832 | //Parse rgb, named colors to hex 833 | function parseColorToHex(color) { 834 | if (typeof color === "undefined") return color; 835 | color = color.replace(/\s/g, ""); 836 | 837 | //Is hex already 838 | if (color.substr(0, 1) === "#") { 839 | return color; 840 | } else { 841 | if (color.startsWith("rgb(")) { 842 | var rgb = parseRgb(color); 843 | if (rgb != null) { 844 | return $c.rgb2hex(rgb[0], rgb[1], rgb[2]); 845 | } else { 846 | return color; 847 | } 848 | } else { 849 | var hexClr = $c.name2hex(color); 850 | return !hexClr.startsWith("Invalid") ? hexClr : color; 851 | } 852 | } 853 | } 854 | 855 | function convertDimensionToPx(dimen) { 856 | var val = removeNonNumeric(dimen); 857 | var METER_TO_PX = 3543.30709; 858 | var INCH_TO_PX = 90; 859 | var PT_TO_PX = 1.25; 860 | var PC_TO_PX = 15; 861 | var FT_TO_PX = 1080; 862 | 863 | if (dimen.endsWith("mm")) { 864 | return val * (METER_TO_PX / 1000); 865 | } else if (dimen.endsWith("cm")) { 866 | return val * (METER_TO_PX / 100); 867 | } else if (dimen.endsWith("m")) { 868 | return val * METER_TO_PX; 869 | } else if (dimen.endsWith("in")) { 870 | return val * INCH_TO_PX; 871 | } else if (dimen.endsWith("pt")) { 872 | return val * PT_TO_PX; 873 | } else if (dimen.endsWith("pc")) { 874 | return val * PC_TO_PX; 875 | } else if (dimen.endsWith("ft")) { 876 | return val * FT_TO_PX; 877 | } else { 878 | return val; 879 | } 880 | } 881 | 882 | function showLastUpdate(repo) { 883 | $.get("https://api.github.com/repos/inloop/" + repo + "/git/refs/heads/gh-pages") 884 | .done(function (data) { 885 | $.get(data.object.url) 886 | .done(function (data) { 887 | var date = data.author.date; 888 | if (date) { 889 | var lastUpdateArea = $("#last-update"); 890 | lastUpdateArea.children("span").text(new Date(date).toLocaleDateString()); 891 | lastUpdateArea.prop("title", "Last change: " + data.message); 892 | lastUpdateArea.tooltip(); 893 | lastUpdateArea.fadeIn(); 894 | } 895 | }); 896 | }); 897 | } -------------------------------------------------------------------------------- /js/bootstrap.min.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * Bootstrap v3.3.7 (http://getbootstrap.com) 3 | * Copyright 2011-2016 Twitter, Inc. 4 | * Licensed under the MIT license 5 | */ 6 | if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1||b[0]>3)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){if(a(b.target).is(this))return b.handleObj.handler.apply(this,arguments)}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.7",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a("#"===f?[]:f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.7",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c).prop(c,!0)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c).prop(c,!1))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")?(c.prop("checked")&&(a=!1),b.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==c.prop("type")&&(c.prop("checked")!==this.$element.hasClass("active")&&(a=!1),this.$element.toggleClass("active")),c.prop("checked",this.$element.hasClass("active")),a&&c.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target).closest(".btn");b.call(d,"toggle"),a(c.target).is('input[type="radio"], input[type="checkbox"]')||(c.preventDefault(),d.is("input,button")?d.trigger("focus"):d.find("input:visible,button:visible").first().trigger("focus"))}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.7",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));if(!(a>this.$items.length-1||a<0))return this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){if(!this.sliding)return this.slide("next")},c.prototype.prev=function(){if(!this.sliding)return this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.7",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function c(c){c&&3===c.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=b(d),f={relatedTarget:this};e.hasClass("open")&&(c&&"click"==c.type&&/input|textarea/i.test(c.target.tagName)&&a.contains(e[0],c.target)||(e.trigger(c=a.Event("hide.bs.dropdown",f)),c.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger(a.Event("hidden.bs.dropdown",f)))))}))}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.7",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=b(e),g=f.hasClass("open");if(c(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",c);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger(a.Event("shown.bs.dropdown",h))}return!1}},g.prototype.keydown=function(c){if(/(38|40|27|32)/.test(c.which)&&!/input|textarea/i.test(c.target.tagName)){var d=a(this);if(c.preventDefault(),c.stopPropagation(),!d.is(".disabled, :disabled")){var e=b(d),g=e.hasClass("open");if(!g&&27!=c.which||g&&27==c.which)return 27==c.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find(".dropdown-menu"+h);if(i.length){var j=i.index(c.target);38==c.which&&j>0&&j--,40==c.which&&jdocument.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth
',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusin"==b.type?"focus":"hover"]=!0),c.tip().hasClass("in")||"in"==c.hoverState?void(c.hoverState="in"):(clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);if(c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusout"==b.type?"focus":"hover"]=!1),!c.isInStateTrue())return clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide()},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h="bottom"==h&&k.bottom+m>o.bottom?"top":"top"==h&&k.top-mo.width?"left":"left"==h&&k.left-lg.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;jg.right&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){if(!this.$tip&&(this.$tip=a(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),b?(c.inState.click=!c.inState.click,c.isInStateTrue()?c.enter(c):c.leave(c)):c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type),a.$tip&&a.$tip.detach(),a.$tip=null,a.$arrow=null,a.$viewport=null,a.$element=null})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;!e&&/destroy|hide/.test(b)||(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.7",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:''}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.7",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b=e[a]&&(void 0===e[a+1]||b .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.7",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return e=a-d&&"bottom"},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery); -------------------------------------------------------------------------------- /js/flatten.js: -------------------------------------------------------------------------------- 1 | /* 2 | Random path and shape generator, flattener test base: http://jsfiddle.net/xqq5w/embedded/result/ 3 | Basic usage example: http://jsfiddle.net/Nv78L/3/embedded/result/ 4 | 5 | Basic usage: flatten(document.getElementById('svg')); 6 | 7 | What it does: Flattens elements (converts elements to paths and flattens transformations). 8 | If the argument element (whose id is above 'svg') has children, or it's descendants has children, 9 | these children elements are flattened also. 10 | 11 | If you want to modify path coordinates using non-affine methods (eg. perspective distort), 12 | you can convert all segments to cubic curves using: 13 | 14 | flatten(document.getElementById('svg'), true); 15 | 16 | There are also arguments 'toAbsolute' (convert coordinates to absolute) and 'dec', 17 | number of digits after decimal separator. 18 | */ 19 | /* 20 | The MIT License (MIT) 21 | 22 | Copyright (c) 2014 Timo (https://github.com/timo22345) 23 | 24 | Permission is hereby granted, free of charge, to any person obtaining a copy 25 | of this software and associated documentation files (the "Software"), to deal 26 | in the Software without restriction, including without limitation the rights 27 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 28 | copies of the Software, and to permit persons to whom the Software is 29 | furnished to do so, subject to the following conditions: 30 | 31 | The above copyright notice and this permission notice shall be included in 32 | all copies or substantial portions of the Software. 33 | 34 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 35 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 36 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 37 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 38 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 39 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 40 | THE SOFTWARE. 41 | */ 42 | 43 | (function () { 44 | 45 | SVGElement.prototype.getTransformToElement = SVGElement.prototype.getTransformToElement || function(elem) { 46 | return elem.getScreenCTM().inverse().multiply(this.getScreenCTM());}; 47 | 48 | var p2s = /,?([achlmqrstvxz]),?/gi; 49 | var convertToString = function (arr) { 50 | return arr.join(',').replace(p2s, ' $1'); 51 | }; 52 | 53 | var decPrecision = 6; 54 | var s = function (num) { 55 | if (decPrecision !== false) return parseFloat(num.toPrecision(decPrecision)); 56 | else return num; 57 | }; 58 | 59 | // Flattens transformations of element or it's children and sub-children 60 | // elem: DOM element 61 | // toCubics: converts all segments to cubics 62 | // toAbsolute: converts all segments to Absolute 63 | // dec: number of digits after decimal separator 64 | // Returns: no return value 65 | function flatten(elem, toCubics, toAbsolute, dec) { 66 | if (!elem) return; 67 | if (typeof (rectAsArgs) == 'undefined') rectAsArgs = false; 68 | if (typeof (toCubics) == 'undefined') toCubics = false; 69 | if (typeof (toAbsolute) == 'undefined') toAbsolute = false; 70 | if (typeof (dec) == 'undefined') dec = false; 71 | 72 | if (elem && elem.children && elem.children.length) { 73 | for (var i = 0, ilen = elem.children.length; i < ilen; i++) { 74 | flatten(elem.children[i], toCubics, toAbsolute, dec); 75 | } 76 | elem.removeAttribute('transform'); 77 | return; 78 | } 79 | if (!(elem instanceof SVGCircleElement || 80 | elem instanceof SVGRectElement || 81 | elem instanceof SVGEllipseElement || 82 | elem instanceof SVGLineElement || 83 | elem instanceof SVGPolygonElement || 84 | elem instanceof SVGPolylineElement || 85 | elem instanceof SVGPathElement)) return; 86 | 87 | path_elem = convertToPath(elem); 88 | 89 | if (!path_elem || path_elem.getAttribute(d) == '') return 'M 0 0'; 90 | 91 | // Rounding coordinates to dec decimals 92 | if (dec || dec === 0) { 93 | if (dec > 15) decPrecision = 15; 94 | else if (dec < 0) decPrecision = 0; 95 | } 96 | 97 | 98 | var arr; 99 | //var pathDOM = path_elem.node; 100 | var pathDOM = path_elem; 101 | var d = pathDOM.getAttribute('d').trim(); 102 | 103 | // If you want to retain current path commans, set toCubics to false 104 | if (!toCubics) { // Set to false to prevent possible re-normalization. 105 | arr = parsePathString(d); // str to array 106 | var arr_orig = arr; 107 | arr = pathToAbsolute(arr); // mahvstcsqz -> uppercase 108 | } 109 | // If you want to modify path data using nonAffine methods, 110 | // set toCubics to true 111 | else { 112 | arr = path2curve(d); // mahvstcsqz -> MC 113 | var arr_orig = arr; 114 | } 115 | var svgDOM = pathDOM.ownerSVGElement; 116 | 117 | // Get the relation matrix that converts path coordinates 118 | // to SVGroot's coordinate space 119 | var matrix = pathDOM.getTransformToElement(svgDOM); 120 | 121 | // The following code can bake transformations 122 | // both normalized and non-normalized data 123 | // Coordinates have to be Absolute in the following 124 | var i = 0, 125 | j, m = arr.length, 126 | letter = '', 127 | letter_orig = '', 128 | x = 0, 129 | y = 0, 130 | point, newcoords = [], 131 | newcoords_orig = [], 132 | pt = svgDOM.createSVGPoint(), 133 | subpath_start = {}, prevX = 0, 134 | prevY = 0; 135 | subpath_start.x = null; 136 | subpath_start.y = null; 137 | for (; i < m; i++) { 138 | letter = arr[i][0].toUpperCase(); 139 | letter_orig = arr_orig[i][0]; 140 | newcoords[i] = []; 141 | newcoords[i][0] = arr[i][0]; 142 | 143 | if (letter == 'A') { 144 | x = arr[i][6]; 145 | y = arr[i][7]; 146 | 147 | pt.x = arr[i][6]; 148 | pt.y = arr[i][7]; 149 | newcoords[i] = arc_transform(arr[i][1], arr[i][2], arr[i][3], arr[i][4], arr[i][5], pt, matrix); 150 | // rounding arc parameters 151 | // x,y are rounded normally 152 | // other parameters at least to 5 decimals 153 | // because they affect more than x,y rounding 154 | newcoords[i][1] = newcoords[i][1]; //rx 155 | newcoords[i][2] = newcoords[i][2]; //ry 156 | newcoords[i][3] = newcoords[i][3]; //x-axis-rotation 157 | newcoords[i][6] = newcoords[i][6]; //x 158 | newcoords[i][7] = newcoords[i][7]; //y 159 | } 160 | else if (letter != 'Z') { 161 | // parse other segs than Z and A 162 | for (j = 1; j < arr[i].length; j = j + 2) { 163 | if (letter == 'V') y = arr[i][j]; 164 | else if (letter == 'H') x = arr[i][j]; 165 | else { 166 | x = arr[i][j]; 167 | y = arr[i][j + 1]; 168 | } 169 | pt.x = x; 170 | pt.y = y; 171 | point = pt.matrixTransform(matrix); 172 | 173 | if (letter == 'V' || letter == 'H') { 174 | newcoords[i][0] = 'L'; 175 | newcoords[i][j] = s(point.x); 176 | newcoords[i][j + 1] = s(point.y); 177 | } 178 | else { 179 | newcoords[i][j] = s(point.x); 180 | newcoords[i][j + 1] = s(point.y); 181 | } 182 | } 183 | } 184 | if ((letter != 'Z' && subpath_start.x === null) || letter == 'M') { 185 | subpath_start.x = x; 186 | subpath_start.y = y; 187 | } 188 | if (letter == 'Z') { 189 | x = subpath_start.x; 190 | y = subpath_start.y; 191 | } 192 | } 193 | // Convert all that was relative back to relative 194 | // This could be combined to above, but to make code more readable 195 | // this is made separately. 196 | var prevXtmp = 0; 197 | var prevYtmp = 0; 198 | subpath_start.x = ''; 199 | for (i = 0; i < newcoords.length; i++) { 200 | letter_orig = arr_orig[i][0]; 201 | if (letter_orig == 'A' || letter_orig == 'M' || letter_orig == 'L' || letter_orig == 'C' || letter_orig == 'S' || letter_orig == 'Q' || letter_orig == 'T' || letter_orig == 'H' || letter_orig == 'V') { 202 | var len = newcoords[i].length; 203 | var lentmp = len; 204 | if (letter_orig == 'A') { 205 | newcoords[i][6] = s(newcoords[i][6]); 206 | newcoords[i][7] = s(newcoords[i][7]); 207 | } 208 | else { 209 | lentmp--; 210 | while (--lentmp) newcoords[i][lentmp] = s(newcoords[i][lentmp]); 211 | } 212 | prevX = newcoords[i][len - 2]; 213 | prevY = newcoords[i][len - 1]; 214 | } 215 | else if (letter_orig == 'a') { 216 | prevXtmp = newcoords[i][6]; 217 | prevYtmp = newcoords[i][7]; 218 | newcoords[i][0] = letter_orig; 219 | newcoords[i][6] = s(newcoords[i][6] - prevX); 220 | newcoords[i][7] = s(newcoords[i][7] - prevY); 221 | prevX = prevXtmp; 222 | prevY = prevYtmp; 223 | } 224 | else if (letter_orig == 'm' || letter_orig == 'l' || letter_orig == 'c' || letter_orig == 's' || letter_orig == 'q' || letter_orig == 't' || letter_orig == 'h' || letter_orig == 'v') { 225 | var len = newcoords[i].length; 226 | prevXtmp = newcoords[i][len - 2]; 227 | prevYtmp = newcoords[i][len - 1]; 228 | for (j = 1; j < len; j = j + 2) { 229 | if (letter_orig == 'h' || letter_orig == 'v') 230 | newcoords[i][0] = 'l'; 231 | else newcoords[i][0] = letter_orig; 232 | newcoords[i][j] = s(newcoords[i][j] - prevX); 233 | newcoords[i][j + 1] = s(newcoords[i][j + 1] - prevY); 234 | } 235 | prevX = prevXtmp; 236 | prevY = prevYtmp; 237 | } 238 | if ((letter_orig.toLowerCase() != 'z' && subpath_start.x == '') || letter_orig.toLowerCase() == 'm') { 239 | subpath_start.x = prevX; 240 | subpath_start.y = prevY; 241 | } 242 | if (letter_orig.toLowerCase() == 'z') { 243 | prevX = subpath_start.x; 244 | prevY = subpath_start.y; 245 | } 246 | } 247 | 248 | if (toAbsolute) newcoords = pathToAbsolute(newcoords); 249 | path_elem.setAttribute('d', convertToString(newcoords)); 250 | path_elem.removeAttribute('transform'); 251 | } 252 | 253 | // Converts all shapes to path retaining attributes. 254 | // oldElem - DOM element to be replaced by path. Can be one of the following: 255 | // ellipse, circle, path, line, polyline, polygon and rect. 256 | // rectAsArgs - Boolean. If true, rect roundings will be as arcs. Otherwise as cubics. 257 | // Source: https://github.com/duopixel/Method-Draw/blob/master/editor/src/svgcanvas.js 258 | // Modifications: Timo (https://github.com/timo22345) 259 | function convertToPath(oldElem) { 260 | if (!oldElem) return; 261 | // Create new path element 262 | var path = document.createElementNS(oldElem.ownerSVGElement.namespaceURI, 'path'); 263 | 264 | // All attributes that path element can have 265 | var attrs = ['requiredFeatures', 'requiredExtensions', 'systemLanguage', 'id', 'xml:base', 'xml:lang', 'xml:space', 'onfocusin', 'onfocusout', 'onactivate', 'onclick', 'onmousedown', 'onmouseup', 'onmouseover', 'onmousemove', 'onmouseout', 'onload', 'alignment-baseline', 'baseline-shift', 'clip', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cursor', 'direction', 'display', 'dominant-baseline', 'enable-background', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'image-rendering', 'kerning', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'opacity', 'overflow', 'pointer-events', 'shape-rendering', 'stop-color', 'stop-opacity', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'unicode-bidi', 'visibility', 'word-spacing', 'writing-mode', 'class', 'style', 'externalResourcesRequired', 'transform', 'd', 'pathLength']; 266 | 267 | // Copy attributes of oldElem to path 268 | for (var i = 0, ilen = attrs.length; i < ilen; i++) { 269 | var attrName = attrs[i]; 270 | var attrValue = oldElem.getAttribute(attrName); 271 | if (attrValue) path.setAttribute(attrName, attrValue); 272 | } 273 | 274 | var d = ''; 275 | var tag = oldElem.tagName; 276 | switch (tag) { 277 | case 'ellipse': 278 | d += ShapeConverter.convertEllipse($(oldElem)); 279 | break; 280 | case 'circle': 281 | d += ShapeConverter.convertCircle($(oldElem)); 282 | break; 283 | case 'path': 284 | d = oldElem.getAttribute('d'); 285 | break; 286 | case 'line': 287 | d += ShapeConverter.convertLine($(oldElem)); 288 | break; 289 | case 'polyline': 290 | d += ShapeConverter.convertPolygon($(oldElem), true); 291 | break; 292 | case 'polygon': 293 | d += ShapeConverter.convertPolygon($(oldElem), false); 294 | break; 295 | case 'rect': 296 | d += ShapeConverter.convertRect($(oldElem)); 297 | break; 298 | default: 299 | //path.parentNode.removeChild(path); 300 | break; 301 | } 302 | 303 | if (d) path.setAttribute('d', d); 304 | 305 | // Replace the current element with the converted one 306 | oldElem.parentNode.replaceChild(path, oldElem); 307 | return path; 308 | } 309 | 310 | // This is needed to flatten transformations of elliptical arcs 311 | // Note! This is not needed if Raphael.path2curve is used 312 | function arc_transform(a_rh, a_rv, a_offsetrot, large_arc_flag, sweep_flag, endpoint, matrix, svgDOM) { 313 | function NEARZERO(B) { 314 | if (Math.abs(B) < 0.0000000000000001) return true; 315 | else return false; 316 | } 317 | 318 | var rh, rv, rot; 319 | 320 | var m = []; // matrix representation of transformed ellipse 321 | var s, c; // sin and cos helpers (the former offset rotation) 322 | var A, B, C; // ellipse implicit equation: 323 | var ac, A2, C2; // helpers for angle and halfaxis-extraction. 324 | rh = a_rh; 325 | rv = a_rv; 326 | 327 | a_offsetrot = a_offsetrot * (Math.PI / 180); // deg->rad 328 | rot = a_offsetrot; 329 | 330 | s = parseFloat(Math.sin(rot)); 331 | c = parseFloat(Math.cos(rot)); 332 | 333 | // build ellipse representation matrix (unit circle transformation). 334 | // the 2x2 matrix multiplication with the upper 2x2 of a_mat is inlined. 335 | m[0] = matrix.a * +rh * c + matrix.c * rh * s; 336 | m[1] = matrix.b * +rh * c + matrix.d * rh * s; 337 | m[2] = matrix.a * -rv * s + matrix.c * rv * c; 338 | m[3] = matrix.b * -rv * s + matrix.d * rv * c; 339 | 340 | // to implict equation (centered) 341 | A = (m[0] * m[0]) + (m[2] * m[2]); 342 | C = (m[1] * m[1]) + (m[3] * m[3]); 343 | B = (m[0] * m[1] + m[2] * m[3]) * 2.0; 344 | 345 | // precalculate distance A to C 346 | ac = A - C; 347 | 348 | // convert implicit equation to angle and halfaxis: 349 | if (NEARZERO(B)) { 350 | a_offsetrot = 0; 351 | A2 = A; 352 | C2 = C; 353 | } 354 | else { 355 | if (NEARZERO(ac)) { 356 | A2 = A + B * 0.5; 357 | C2 = A - B * 0.5; 358 | a_offsetrot = Math.PI / 4.0; 359 | } 360 | else { 361 | // Precalculate radical: 362 | var K = 1 + B * B / (ac * ac); 363 | 364 | // Clamp (precision issues might need this.. not likely, but better save than sorry) 365 | if (K < 0) K = 0; 366 | else K = Math.sqrt(K); 367 | 368 | A2 = 0.5 * (A + C + K * ac); 369 | C2 = 0.5 * (A + C - K * ac); 370 | a_offsetrot = 0.5 * Math.atan2(B, ac); 371 | } 372 | } 373 | 374 | // This can get slightly below zero due to rounding issues. 375 | // it's save to clamp to zero in this case (this yields a zero length halfaxis) 376 | if (A2 < 0) A2 = 0; 377 | else A2 = Math.sqrt(A2); 378 | if (C2 < 0) C2 = 0; 379 | else C2 = Math.sqrt(C2); 380 | 381 | // now A2 and C2 are half-axis: 382 | if (ac <= 0) { 383 | a_rv = A2; 384 | a_rh = C2; 385 | } 386 | else { 387 | a_rv = C2; 388 | a_rh = A2; 389 | } 390 | 391 | // If the transformation matrix contain a mirror-component 392 | // winding order of the ellise needs to be changed. 393 | if ((matrix.a * matrix.d) - (matrix.b * matrix.c) < 0) { 394 | if (!sweep_flag) sweep_flag = 1; 395 | else sweep_flag = 0; 396 | } 397 | 398 | // Finally, transform arc endpoint. This takes care about the 399 | // translational part which we ignored at the whole math-showdown above. 400 | endpoint = endpoint.matrixTransform(matrix); 401 | 402 | // Radians back to degrees 403 | a_offsetrot = a_offsetrot * 180 / Math.PI; 404 | 405 | var r = ['A', a_rh, a_rv, a_offsetrot, large_arc_flag, sweep_flag, endpoint.x, endpoint.y]; 406 | return r; 407 | } 408 | 409 | // Parts of Raphaël 2.1.0 (MIT licence: http://raphaeljs.com/license.html) 410 | // Contains eg. bugfixed path2curve() function 411 | 412 | var R = {}; 413 | var has = 'hasOwnProperty'; 414 | var Str = String; 415 | var array = 'array'; 416 | var isnan = { 417 | 'NaN': 1, 418 | 'Infinity': 1, 419 | '-Infinity': 1 420 | }; 421 | var lowerCase = Str.prototype.toLowerCase; 422 | var upperCase = Str.prototype.toUpperCase; 423 | var objectToString = Object.prototype.toString; 424 | var concat = 'concat'; 425 | var split = 'split'; 426 | var apply = 'apply'; 427 | var math = Math, 428 | mmax = math.max, 429 | mmin = math.min, 430 | abs = math.abs, 431 | pow = math.pow, 432 | PI = math.PI, 433 | round = math.round, 434 | toFloat = parseFloat, 435 | toInt = parseInt; 436 | var p2s = /,?([achlmqrstvxz]),?/gi; 437 | var pathCommand = /([achlmrqstvz])[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*)+)/ig; 438 | var pathValues = /(-?\d*\.?\d*(?:e[\-+]?\d+)?)[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*/ig; 439 | R.is = function (o, type) { 440 | type = lowerCase.call(type); 441 | if (type == 'finite') { 442 | return !isnan[has](+o); 443 | } 444 | if (type == 'array') { 445 | return o instanceof Array; 446 | } 447 | return type == 'null' && o === null || type == typeof o && o !== null || type == 'object' && o === Object(o) || type == 'array' && Array.isArray && Array.isArray(o) || objectToString.call(o).slice(8, -1).toLowerCase() == type 448 | }; 449 | 450 | function clone(obj) { 451 | if (Object(obj) !== obj) { 452 | return obj; 453 | } 454 | var res = new obj.constructor; 455 | for (var key in obj) { 456 | if (obj[has](key)) { 457 | res[key] = clone(obj[key]); 458 | } 459 | } 460 | return res; 461 | } 462 | 463 | R._path2string = function () { 464 | return this.join(',').replace(p2s, '$1'); 465 | }; 466 | 467 | function repush(array, item) { 468 | for (var i = 0, ii = array.length; i < ii; i++) 469 | if (array[i] === item) { 470 | return array.push(array.splice(i, 1)[0]); 471 | } 472 | } 473 | 474 | var pathClone = function (pathArray) { 475 | var res = clone(pathArray); 476 | res.toString = R._path2string; 477 | return res; 478 | }; 479 | var paths = function (ps) { 480 | var p = paths.ps = paths.ps || 481 | {}; 482 | if (p[ps]) p[ps].sleep = 100; 483 | else p[ps] = { 484 | sleep: 100 485 | }; 486 | setTimeout(function () { 487 | for (var key in p) { 488 | if (p[has](key) && key != ps) { 489 | p[key].sleep--; 490 | !p[key].sleep && delete p[key]; 491 | } 492 | } 493 | }); 494 | return p[ps]; 495 | }; 496 | 497 | function catmullRom2bezier(crp, z) { 498 | var d = []; 499 | for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) { 500 | var p = [ 501 | { 502 | x: +crp[i - 2], 503 | y: +crp[i - 1] 504 | }, 505 | { 506 | x: +crp[i], 507 | y: +crp[i + 1] 508 | }, 509 | { 510 | x: +crp[i + 2], 511 | y: +crp[i + 3] 512 | }, 513 | { 514 | x: +crp[i + 4], 515 | y: +crp[i + 5] 516 | }]; 517 | if (z) { 518 | if (!i) { 519 | p[0] = { 520 | x: +crp[iLen - 2], 521 | y: +crp[iLen - 1] 522 | }; 523 | } 524 | else { 525 | if (iLen - 4 == i) { 526 | p[3] = { 527 | x: +crp[0], 528 | y: +crp[1] 529 | }; 530 | } 531 | else { 532 | if (iLen - 2 == i) { 533 | p[2] = { 534 | x: +crp[0], 535 | y: +crp[1] 536 | }; 537 | p[3] = { 538 | x: +crp[2], 539 | y: +crp[3] 540 | }; 541 | } 542 | } 543 | } 544 | } 545 | else { 546 | if (iLen - 4 == i) { 547 | p[3] = p[2]; 548 | } 549 | else { 550 | if (!i) { 551 | p[0] = { 552 | x: +crp[i], 553 | y: +crp[i + 1] 554 | }; 555 | } 556 | } 557 | } 558 | d.push(['C', (-p[0].x + 6 * p[1].x + p[2].x) / 6, (-p[0].y + 6 * p[1].y + p[2].y) / 6, (p[1].x + 6 * p[2].x - p[3].x) / 6, (p[1].y + 6 * p[2].y - p[3].y) / 6, p[2].x, p[2].y]) 559 | } 560 | return d 561 | }; 562 | var parsePathString = function (pathString) { 563 | if (!pathString) return null; 564 | var pth = paths(pathString); 565 | if (pth.arr) return pathClone(pth.arr); 566 | var paramCounts = { 567 | a: 7, 568 | c: 6, 569 | h: 1, 570 | l: 2, 571 | m: 2, 572 | r: 4, 573 | q: 4, 574 | s: 4, 575 | t: 2, 576 | v: 1, 577 | z: 0 578 | }, data = []; 579 | if (R.is(pathString, array) && R.is(pathString[0], array)) data = pathClone(pathString); 580 | if (!data.length) { 581 | Str(pathString).replace(pathCommand, function (a, b, c) { 582 | var params = [], 583 | name = b.toLowerCase(); 584 | c.replace(pathValues, function (a, b) { 585 | b && params.push(+b); 586 | }); 587 | if (name == 'm' && params.length > 2) { 588 | data.push([b][concat](params.splice(0, 2))); 589 | name = 'l'; 590 | b = b == 'm' ? 'l' : 'L' 591 | } 592 | if (name == 'r') data.push([b][concat](params)); 593 | else { 594 | while (params.length >= paramCounts[name]) { 595 | data.push([b][concat](params.splice(0, paramCounts[name]))); 596 | if (!paramCounts[name]) break; 597 | } 598 | } 599 | }) 600 | } 601 | data.toString = R._path2string; 602 | pth.arr = pathClone(data); 603 | return data; 604 | }; 605 | 606 | function repush(array, item) { 607 | for (var i = 0, ii = array.length; i < ii; i++) 608 | if (array[i] === item) { 609 | return array.push(array.splice(i, 1)[0]); 610 | } 611 | } 612 | 613 | var pathToAbsolute = cacher(function (pathArray) { 614 | //var pth = paths(pathArray); // Timo: commented to prevent multiple caching 615 | // for some reason only FF proceed correctly 616 | // when not cached using cacher() around 617 | // this function. 618 | //if (pth.abs) return pathClone(pth.abs) 619 | if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) 620 | pathArray = parsePathString(pathArray); 621 | if (!pathArray || !pathArray.length) return [['M', 0, 0]]; 622 | var res = [], 623 | x = 0, 624 | y = 0, 625 | mx = 0, 626 | my = 0, 627 | start = 0; 628 | if (pathArray[0][0] == 'M') { 629 | x = +pathArray[0][1]; 630 | y = +pathArray[0][2]; 631 | mx = x; 632 | my = y; 633 | start++; 634 | res[0] = ['M', x, y]; 635 | } 636 | var crz = pathArray.length == 3 && pathArray[0][0] == 'M' && pathArray[1][0].toUpperCase() == 'R' && pathArray[2][0].toUpperCase() == 'Z'; 637 | for (var r, pa, i = start, ii = pathArray.length; i < ii; i++) { 638 | res.push(r = []); 639 | pa = pathArray[i]; 640 | if (pa[0] != upperCase.call(pa[0])) { 641 | r[0] = upperCase.call(pa[0]); 642 | switch (r[0]) { 643 | case 'A': 644 | r[1] = pa[1]; 645 | r[2] = pa[2]; 646 | r[3] = pa[3]; 647 | r[4] = pa[4]; 648 | r[5] = pa[5]; 649 | r[6] = s(pa[6] + x); 650 | r[7] = s(pa[7] + y); 651 | break; 652 | case 'V': 653 | r[1] = s(pa[1] + y); 654 | break; 655 | case 'H': 656 | r[1] = s(pa[1] + x); 657 | break; 658 | case 'R': 659 | var dots = [x, y][concat](pa.slice(1)); 660 | for (var j = 2, jj = dots.length; j < jj; j++) { 661 | dots[j] = s(dots[j] + x); 662 | dots[++j] = s(dots[j] + y); 663 | } 664 | res.pop(); 665 | res = res[concat](catmullRom2bezier(dots, crz)); 666 | break; 667 | case 'M': 668 | mx = s(pa[1] + x); 669 | my = s(pa[2] + y); 670 | default: 671 | for (j = 1, jj = pa.length; j < jj; j++) 672 | r[j] = s(pa[j] + (j % 2 ? x : y)) 673 | } 674 | } 675 | else { 676 | if (pa[0] == 'R') { 677 | dots = [x, y][concat](pa.slice(1)); 678 | res.pop(); 679 | res = res[concat](catmullRom2bezier(dots, crz)); 680 | r = ['R'][concat](pa.slice(-2)); 681 | } 682 | else { 683 | for (var k = 0, kk = pa.length; k < kk; k++) 684 | r[k] = pa[k] 685 | } 686 | } 687 | switch (r[0]) { 688 | case 'Z': 689 | x = mx; 690 | y = my; 691 | break; 692 | case 'H': 693 | x = r[1]; 694 | break; 695 | case 'V': 696 | y = r[1]; 697 | break; 698 | case 'M': 699 | mx = r[r.length - 2]; 700 | my = r[r.length - 1]; 701 | default: 702 | x = r[r.length - 2]; 703 | y = r[r.length - 1]; 704 | } 705 | } 706 | res.toString = R._path2string; 707 | //pth.abs = pathClone(res); 708 | return res; 709 | }); 710 | 711 | function cacher(f, scope, postprocessor) { 712 | function newf() { 713 | var arg = Array.prototype.slice.call(arguments, 0), 714 | args = arg.join('\u2400'), 715 | cache = newf.cache = newf.cache || 716 | {}, count = newf.count = newf.count || []; 717 | if (cache.hasOwnProperty(args)) { 718 | for (var i = 0, ii = count.length; i < ii; i++) 719 | if (count[i] === args) { 720 | count.push(count.splice(i, 1)[0]); 721 | } 722 | return postprocessor ? postprocessor(cache[args]) : cache[args]; 723 | } 724 | count.length >= 1E3 && delete cache[count.shift()]; 725 | count.push(args); 726 | cache[args] = f.apply(scope, arg); 727 | return postprocessor ? postprocessor(cache[args]) : cache[args]; 728 | } 729 | 730 | return newf; 731 | } 732 | 733 | var l2c = function (x1, y1, x2, y2) { 734 | return [x1, y1, x2, y2, x2, y2]; 735 | }, 736 | q2c = function (x1, y1, ax, ay, x2, y2) { 737 | var _13 = 1 / 3, 738 | _23 = 2 / 3; 739 | return [_13 * x1 + _23 * ax, _13 * y1 + _23 * ay, _13 * x2 + _23 * ax, _13 * y2 + _23 * ay, x2, y2] 740 | }, 741 | a2c = cacher(function (x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) { 742 | var _120 = PI * 120 / 180, 743 | rad = PI / 180 * (+angle || 0), 744 | res = [], 745 | xy, 746 | rotate = cacher(function (x, y, rad) { 747 | var X = x * Math.cos(rad) - y * Math.sin(rad), 748 | Y = x * Math.sin(rad) + y * Math.cos(rad); 749 | return { 750 | x: X, 751 | y: Y 752 | }; 753 | }); 754 | if (!recursive) { 755 | xy = rotate(x1, y1, -rad); 756 | x1 = xy.x; 757 | y1 = xy.y; 758 | xy = rotate(x2, y2, -rad); 759 | x2 = xy.x; 760 | y2 = xy.y; 761 | var cos = Math.cos(PI / 180 * angle), 762 | sin = Math.sin(PI / 180 * angle), 763 | x = (x1 - x2) / 2, 764 | y = (y1 - y2) / 2; 765 | var h = x * x / (rx * rx) + y * y / (ry * ry); 766 | if (h > 1) { 767 | h = Math.sqrt(h); 768 | rx = h * rx; 769 | ry = h * ry; 770 | } 771 | var rx2 = rx * rx, 772 | ry2 = ry * ry, 773 | k = (large_arc_flag == sweep_flag ? -1 : 1) * Math.sqrt(Math.abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))), 774 | cx = k * rx * y / ry + (x1 + x2) / 2, 775 | cy = k * -ry * x / rx + (y1 + y2) / 2, 776 | f1 = Math.asin(((y1 - cy) / ry).toFixed(9)), 777 | f2 = Math.asin(((y2 - cy) / ry).toFixed(9)); 778 | f1 = x1 < cx ? PI - f1 : f1; 779 | f2 = x2 < cx ? PI - f2 : f2; 780 | f1 < 0 && (f1 = PI * 2 + f1); 781 | f2 < 0 && (f2 = PI * 2 + f2); 782 | if (sweep_flag && f1 > f2) { 783 | f1 = f1 - PI * 2; 784 | } 785 | if (!sweep_flag && f2 > f1) { 786 | f2 = f2 - PI * 2; 787 | } 788 | } 789 | else { 790 | f1 = recursive[0]; 791 | f2 = recursive[1]; 792 | cx = recursive[2]; 793 | cy = recursive[3]; 794 | } 795 | var df = f2 - f1; 796 | if (Math.abs(df) > _120) { 797 | var f2old = f2, 798 | x2old = x2, 799 | y2old = y2; 800 | f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1); 801 | x2 = cx + rx * Math.cos(f2); 802 | y2 = cy + ry * Math.sin(f2); 803 | res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]) 804 | } 805 | df = f2 - f1; 806 | var c1 = Math.cos(f1), 807 | s1 = Math.sin(f1), 808 | c2 = Math.cos(f2), 809 | s2 = Math.sin(f2), 810 | t = Math.tan(df / 4), 811 | hx = 4 / 3 * rx * t, 812 | hy = 4 / 3 * ry * t, 813 | m1 = [x1, y1], 814 | m2 = [x1 + hx * s1, y1 - hy * c1], 815 | m3 = [x2 + hx * s2, y2 - hy * c2], 816 | m4 = [x2, y2]; 817 | m2[0] = 2 * m1[0] - m2[0]; 818 | m2[1] = 2 * m1[1] - m2[1]; 819 | if (recursive) return [m2, m3, m4].concat(res); 820 | else { 821 | res = [m2, m3, m4].concat(res).join().split(','); 822 | var newres = []; 823 | for (var i = 0, ii = res.length; i < ii; i++) 824 | newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x 825 | return newres 826 | } 827 | }); 828 | 829 | var path2curve = cacher(function (path, path2) { 830 | var pth = !path2 && paths(path); 831 | if (!path2 && pth.curve) return pathClone(pth.curve); 832 | var p = pathToAbsolute(path), 833 | p2 = path2 && pathToAbsolute(path2), 834 | attrs = { 835 | x: 0, 836 | y: 0, 837 | bx: 0, 838 | by: 0, 839 | X: 0, 840 | Y: 0, 841 | qx: null, 842 | qy: null 843 | }, 844 | attrs2 = { 845 | x: 0, 846 | y: 0, 847 | bx: 0, 848 | by: 0, 849 | X: 0, 850 | Y: 0, 851 | qx: null, 852 | qy: null 853 | }, 854 | processPath = function (path, d, pcom) { 855 | var nx, ny; 856 | if (!path) { 857 | return ['C', d.x, d.y, d.x, d.y, d.x, d.y]; 858 | } 859 | !(path[0] in 860 | { 861 | T: 1, 862 | Q: 1 863 | }) && (d.qx = d.qy = null); 864 | switch (path[0]) { 865 | case 'M': 866 | d.X = path[1]; 867 | d.Y = path[2]; 868 | break; 869 | case 'A': 870 | path = ['C'][concat](a2c[apply](0, [d.x, d.y][concat](path.slice(1)))); 871 | break; 872 | case 'S': 873 | if (pcom == 'C' || pcom == 'S') { 874 | nx = d.x * 2 - d.bx; 875 | ny = d.y * 2 - d.by; 876 | } 877 | else { 878 | nx = d.x; 879 | ny = d.y; 880 | } 881 | path = ['C', nx, ny][concat](path.slice(1)); 882 | break; 883 | case 'T': 884 | if (pcom == 'Q' || pcom == 'T') { 885 | d.qx = d.x * 2 - d.qx; 886 | d.qy = d.y * 2 - d.qy; 887 | } 888 | else { 889 | d.qx = d.x; 890 | d.qy = d.y; 891 | } 892 | path = ['C'][concat](q2c(d.x, d.y, d.qx, d.qy, path[1], path[2])); 893 | break; 894 | case 'Q': 895 | d.qx = path[1]; 896 | d.qy = path[2]; 897 | path = ['C'][concat](q2c(d.x, d.y, path[1], path[2], path[3], path[4])); 898 | break; 899 | case 'L': 900 | path = ['C'][concat](l2c(d.x, d.y, path[1], path[2])); 901 | break; 902 | case 'H': 903 | path = ['C'][concat](l2c(d.x, d.y, path[1], d.y)); 904 | break; 905 | case 'V': 906 | path = ['C'][concat](l2c(d.x, d.y, d.x, path[1])); 907 | break; 908 | case 'Z': 909 | path = ['C'][concat](l2c(d.x, d.y, d.X, d.Y)); 910 | break 911 | } 912 | return path 913 | }, 914 | fixArc = function (pp, i) { 915 | if (pp[i].length > 7) { 916 | pp[i].shift(); 917 | var pi = pp[i]; 918 | while (pi.length) { 919 | pcoms1[i] = 'A'; 920 | p2 && (pcoms2[i] = 'A'); 921 | pp.splice(i++, 0, ['C'][concat](pi.splice(0, 6))); 922 | } 923 | pp.splice(i, 1); 924 | ii = mmax(p.length, p2 && p2.length || 0); 925 | } 926 | }, 927 | fixM = function (path1, path2, a1, a2, i) { 928 | if (path1 && path2 && path1[i][0] == 'M' && path2[i][0] != 'M') { 929 | path2.splice(i, 0, ['M', a2.x, a2.y]); 930 | a1.bx = 0; 931 | a1.by = 0; 932 | a1.x = path1[i][1]; 933 | a1.y = path1[i][2]; 934 | ii = mmax(p.length, p2 && p2.length || 0); 935 | } 936 | }, 937 | pcoms1 = [], 938 | pcoms2 = [], 939 | pfirst = '', 940 | pcom = ''; 941 | for (var i = 0, ii = mmax(p.length, p2 && p2.length || 0); i < ii; i++) { 942 | p[i] && (pfirst = p[i][0]); 943 | if (pfirst != 'C') { 944 | pcoms1[i] = pfirst; 945 | i && (pcom = pcoms1[i - 1]); 946 | } 947 | p[i] = processPath(p[i], attrs, pcom); 948 | if (pcoms1[i] != 'A' && pfirst == 'C') pcoms1[i] = 'C'; 949 | fixArc(p, i); 950 | if (p2) { 951 | p2[i] && (pfirst = p2[i][0]); 952 | if (pfirst != 'C') { 953 | pcoms2[i] = pfirst; 954 | i && (pcom = pcoms2[i - 1]); 955 | } 956 | p2[i] = processPath(p2[i], attrs2, pcom); 957 | if (pcoms2[i] != 'A' && pfirst == 'C') pcoms2[i] = 'C'; 958 | fixArc(p2, i); 959 | } 960 | fixM(p, p2, attrs, attrs2, i); 961 | fixM(p2, p, attrs2, attrs, i); 962 | var seg = p[i], 963 | seg2 = p2 && p2[i], 964 | seglen = seg.length, 965 | seg2len = p2 && seg2.length; 966 | attrs.x = seg[seglen - 2]; 967 | attrs.y = seg[seglen - 1]; 968 | attrs.bx = toFloat(seg[seglen - 4]) || attrs.x; 969 | attrs.by = toFloat(seg[seglen - 3]) || attrs.y; 970 | attrs2.bx = p2 && (toFloat(seg2[seg2len - 4]) || attrs2.x); 971 | attrs2.by = p2 && (toFloat(seg2[seg2len - 3]) || attrs2.y); 972 | attrs2.x = p2 && seg2[seg2len - 2]; 973 | attrs2.y = p2 && seg2[seg2len - 1]; 974 | } 975 | if (!p2) pth.curve = pathClone(p); 976 | return p2 ? [p, p2] : p 977 | }, null, pathClone); 978 | 979 | // Export function 980 | window.flatten = flatten; 981 | 982 | })(); --------------------------------------------------------------------------------