holder.js 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980
  1. /*!
  2. Holder - client side image placeholders
  3. Version 2.9.0+f2dkw
  4. © 2015 Ivan Malopinsky - http://imsky.co
  5. Site: http://holderjs.com
  6. Issues: https://github.com/imsky/holder/issues
  7. License: MIT
  8. */
  9. (function (window) {
  10. if (!window.document) return;
  11. var document = window.document;
  12. //https://github.com/inexorabletash/polyfill/blob/master/web.js
  13. if (!document.querySelectorAll) {
  14. document.querySelectorAll = function (selectors) {
  15. var style = document.createElement('style'), elements = [], element;
  16. document.documentElement.firstChild.appendChild(style);
  17. document._qsa = [];
  18. style.styleSheet.cssText = selectors + '{x-qsa:expression(document._qsa && document._qsa.push(this))}';
  19. window.scrollBy(0, 0);
  20. style.parentNode.removeChild(style);
  21. while (document._qsa.length) {
  22. element = document._qsa.shift();
  23. element.style.removeAttribute('x-qsa');
  24. elements.push(element);
  25. }
  26. document._qsa = null;
  27. return elements;
  28. };
  29. }
  30. if (!document.querySelector) {
  31. document.querySelector = function (selectors) {
  32. var elements = document.querySelectorAll(selectors);
  33. return (elements.length) ? elements[0] : null;
  34. };
  35. }
  36. if (!document.getElementsByClassName) {
  37. document.getElementsByClassName = function (classNames) {
  38. classNames = String(classNames).replace(/^|\s+/g, '.');
  39. return document.querySelectorAll(classNames);
  40. };
  41. }
  42. //https://github.com/inexorabletash/polyfill
  43. // ES5 15.2.3.14 Object.keys ( O )
  44. // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys
  45. if (!Object.keys) {
  46. Object.keys = function (o) {
  47. if (o !== Object(o)) { throw TypeError('Object.keys called on non-object'); }
  48. var ret = [], p;
  49. for (p in o) {
  50. if (Object.prototype.hasOwnProperty.call(o, p)) {
  51. ret.push(p);
  52. }
  53. }
  54. return ret;
  55. };
  56. }
  57. // ES5 15.4.4.18 Array.prototype.forEach ( callbackfn [ , thisArg ] )
  58. // From https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach
  59. if (!Array.prototype.forEach) {
  60. Array.prototype.forEach = function (fun /*, thisp */) {
  61. if (this === void 0 || this === null) { throw TypeError(); }
  62. var t = Object(this);
  63. var len = t.length >>> 0;
  64. if (typeof fun !== "function") { throw TypeError(); }
  65. var thisp = arguments[1], i;
  66. for (i = 0; i < len; i++) {
  67. if (i in t) {
  68. fun.call(thisp, t[i], i, t);
  69. }
  70. }
  71. };
  72. }
  73. //https://github.com/inexorabletash/polyfill/blob/master/web.js
  74. (function (global) {
  75. var B64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  76. global.atob = global.atob || function (input) {
  77. input = String(input);
  78. var position = 0,
  79. output = [],
  80. buffer = 0, bits = 0, n;
  81. input = input.replace(/\s/g, '');
  82. if ((input.length % 4) === 0) { input = input.replace(/=+$/, ''); }
  83. if ((input.length % 4) === 1) { throw Error('InvalidCharacterError'); }
  84. if (/[^+/0-9A-Za-z]/.test(input)) { throw Error('InvalidCharacterError'); }
  85. while (position < input.length) {
  86. n = B64_ALPHABET.indexOf(input.charAt(position));
  87. buffer = (buffer << 6) | n;
  88. bits += 6;
  89. if (bits === 24) {
  90. output.push(String.fromCharCode((buffer >> 16) & 0xFF));
  91. output.push(String.fromCharCode((buffer >> 8) & 0xFF));
  92. output.push(String.fromCharCode(buffer & 0xFF));
  93. bits = 0;
  94. buffer = 0;
  95. }
  96. position += 1;
  97. }
  98. if (bits === 12) {
  99. buffer = buffer >> 4;
  100. output.push(String.fromCharCode(buffer & 0xFF));
  101. } else if (bits === 18) {
  102. buffer = buffer >> 2;
  103. output.push(String.fromCharCode((buffer >> 8) & 0xFF));
  104. output.push(String.fromCharCode(buffer & 0xFF));
  105. }
  106. return output.join('');
  107. };
  108. global.btoa = global.btoa || function (input) {
  109. input = String(input);
  110. var position = 0,
  111. out = [],
  112. o1, o2, o3,
  113. e1, e2, e3, e4;
  114. if (/[^\x00-\xFF]/.test(input)) { throw Error('InvalidCharacterError'); }
  115. while (position < input.length) {
  116. o1 = input.charCodeAt(position++);
  117. o2 = input.charCodeAt(position++);
  118. o3 = input.charCodeAt(position++);
  119. // 111111 112222 222233 333333
  120. e1 = o1 >> 2;
  121. e2 = ((o1 & 0x3) << 4) | (o2 >> 4);
  122. e3 = ((o2 & 0xf) << 2) | (o3 >> 6);
  123. e4 = o3 & 0x3f;
  124. if (position === input.length + 2) {
  125. e3 = 64; e4 = 64;
  126. }
  127. else if (position === input.length + 1) {
  128. e4 = 64;
  129. }
  130. out.push(B64_ALPHABET.charAt(e1),
  131. B64_ALPHABET.charAt(e2),
  132. B64_ALPHABET.charAt(e3),
  133. B64_ALPHABET.charAt(e4));
  134. }
  135. return out.join('');
  136. };
  137. }(window));
  138. //https://gist.github.com/jimeh/332357
  139. if (!Object.prototype.hasOwnProperty){
  140. /*jshint -W001, -W103 */
  141. Object.prototype.hasOwnProperty = function(prop) {
  142. var proto = this.__proto__ || this.constructor.prototype;
  143. return (prop in this) && (!(prop in proto) || proto[prop] !== this[prop]);
  144. };
  145. /*jshint +W001, +W103 */
  146. }
  147. // @license http://opensource.org/licenses/MIT
  148. // copyright Paul Irish 2015
  149. // Date.now() is supported everywhere except IE8. For IE8 we use the Date.now polyfill
  150. // github.com/Financial-Times/polyfill-service/blob/master/polyfills/Date.now/polyfill.js
  151. // as Safari 6 doesn't have support for NavigationTiming, we use a Date.now() timestamp for relative values
  152. // if you want values similar to what you'd get with real perf.now, place this towards the head of the page
  153. // but in reality, you're just getting the delta between now() calls, so it's not terribly important where it's placed
  154. (function(){
  155. if ('performance' in window === false) {
  156. window.performance = {};
  157. }
  158. Date.now = (Date.now || function () { // thanks IE8
  159. return new Date().getTime();
  160. });
  161. if ('now' in window.performance === false){
  162. var nowOffset = Date.now();
  163. if (performance.timing && performance.timing.navigationStart){
  164. nowOffset = performance.timing.navigationStart;
  165. }
  166. window.performance.now = function now(){
  167. return Date.now() - nowOffset;
  168. };
  169. }
  170. })();
  171. //requestAnimationFrame polyfill for older Firefox/Chrome versions
  172. if (!window.requestAnimationFrame) {
  173. if (window.webkitRequestAnimationFrame) {
  174. //https://github.com/Financial-Times/polyfill-service/blob/master/polyfills/requestAnimationFrame/polyfill-webkit.js
  175. (function (global) {
  176. // window.requestAnimationFrame
  177. global.requestAnimationFrame = function (callback) {
  178. return webkitRequestAnimationFrame(function () {
  179. callback(global.performance.now());
  180. });
  181. };
  182. // window.cancelAnimationFrame
  183. global.cancelAnimationFrame = webkitCancelAnimationFrame;
  184. }(window));
  185. } else if (window.mozRequestAnimationFrame) {
  186. //https://github.com/Financial-Times/polyfill-service/blob/master/polyfills/requestAnimationFrame/polyfill-moz.js
  187. (function (global) {
  188. // window.requestAnimationFrame
  189. global.requestAnimationFrame = function (callback) {
  190. return mozRequestAnimationFrame(function () {
  191. callback(global.performance.now());
  192. });
  193. };
  194. // window.cancelAnimationFrame
  195. global.cancelAnimationFrame = mozCancelAnimationFrame;
  196. }(window));
  197. } else {
  198. (function (global) {
  199. global.requestAnimationFrame = function (callback) {
  200. return global.setTimeout(callback, 1000 / 60);
  201. };
  202. global.cancelAnimationFrame = global.clearTimeout;
  203. })(window);
  204. }
  205. }
  206. })(this);
  207. (function webpackUniversalModuleDefinition(root, factory) {
  208. if(typeof exports === 'object' && typeof module === 'object')
  209. module.exports = factory();
  210. else if(typeof define === 'function' && define.amd)
  211. define([], factory);
  212. else if(typeof exports === 'object')
  213. exports["Holder"] = factory();
  214. else
  215. root["Holder"] = factory();
  216. })(this, function() {
  217. return /******/ (function(modules) { // webpackBootstrap
  218. /******/ // The module cache
  219. /******/ var installedModules = {};
  220. /******/ // The require function
  221. /******/ function __webpack_require__(moduleId) {
  222. /******/ // Check if module is in cache
  223. /******/ if(installedModules[moduleId])
  224. /******/ return installedModules[moduleId].exports;
  225. /******/ // Create a new module (and put it into the cache)
  226. /******/ var module = installedModules[moduleId] = {
  227. /******/ exports: {},
  228. /******/ id: moduleId,
  229. /******/ loaded: false
  230. /******/ };
  231. /******/ // Execute the module function
  232. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  233. /******/ // Flag the module as loaded
  234. /******/ module.loaded = true;
  235. /******/ // Return the exports of the module
  236. /******/ return module.exports;
  237. /******/ }
  238. /******/ // expose the modules object (__webpack_modules__)
  239. /******/ __webpack_require__.m = modules;
  240. /******/ // expose the module cache
  241. /******/ __webpack_require__.c = installedModules;
  242. /******/ // __webpack_public_path__
  243. /******/ __webpack_require__.p = "";
  244. /******/ // Load entry module and return exports
  245. /******/ return __webpack_require__(0);
  246. /******/ })
  247. /************************************************************************/
  248. /******/ ([
  249. /* 0 */
  250. /***/ function(module, exports, __webpack_require__) {
  251. /*
  252. Holder.js - client side image placeholders
  253. (c) 2012-2015 Ivan Malopinsky - http://imsky.co
  254. */
  255. module.exports = __webpack_require__(1);
  256. /***/ },
  257. /* 1 */
  258. /***/ function(module, exports, __webpack_require__) {
  259. /* WEBPACK VAR INJECTION */(function(global) {/*
  260. Holder.js - client side image placeholders
  261. (c) 2012-2015 Ivan Malopinsky - http://imsky.co
  262. */
  263. //Libraries and functions
  264. var onDomReady = __webpack_require__(2);
  265. var querystring = __webpack_require__(3);
  266. var SceneGraph = __webpack_require__(6);
  267. var utils = __webpack_require__(7);
  268. var SVG = __webpack_require__(8);
  269. var DOM = __webpack_require__(9);
  270. var Color = __webpack_require__(10);
  271. var constants = __webpack_require__(11);
  272. var svgRenderer = __webpack_require__(12);
  273. var sgCanvasRenderer = __webpack_require__(15);
  274. var extend = utils.extend;
  275. var dimensionCheck = utils.dimensionCheck;
  276. //Constants and definitions
  277. var SVG_NS = constants.svg_ns;
  278. var Holder = {
  279. version: constants.version,
  280. /**
  281. * Adds a theme to default settings
  282. *
  283. * @param {string} name Theme name
  284. * @param {Object} theme Theme object, with foreground, background, size, font, and fontweight properties.
  285. */
  286. addTheme: function(name, theme) {
  287. name != null && theme != null && (App.settings.themes[name] = theme);
  288. delete App.vars.cache.themeKeys;
  289. return this;
  290. },
  291. /**
  292. * Appends a placeholder to an element
  293. *
  294. * @param {string} src Placeholder URL string
  295. * @param el A selector or a reference to a DOM node
  296. */
  297. addImage: function(src, el) {
  298. //todo: use jquery fallback if available for all QSA references
  299. var nodes = DOM.getNodeArray(el);
  300. nodes.forEach(function (node) {
  301. var img = DOM.newEl('img');
  302. var domProps = {};
  303. domProps[App.setup.dataAttr] = src;
  304. DOM.setAttr(img, domProps);
  305. node.appendChild(img);
  306. });
  307. return this;
  308. },
  309. /**
  310. * Sets whether or not an image is updated on resize.
  311. * If an image is set to be updated, it is immediately rendered.
  312. *
  313. * @param {Object} el Image DOM element
  314. * @param {Boolean} value Resizable update flag value
  315. */
  316. setResizeUpdate: function(el, value) {
  317. if (el.holderData) {
  318. el.holderData.resizeUpdate = !!value;
  319. if (el.holderData.resizeUpdate) {
  320. updateResizableElements(el);
  321. }
  322. }
  323. },
  324. /**
  325. * Runs Holder with options. By default runs Holder on all images with "holder.js" in their source attributes.
  326. *
  327. * @param {Object} userOptions Options object, can contain domain, themes, images, and bgnodes properties
  328. */
  329. run: function(userOptions) {
  330. //todo: split processing into separate queues
  331. userOptions = userOptions || {};
  332. var engineSettings = {};
  333. var options = extend(App.settings, userOptions);
  334. App.vars.preempted = true;
  335. App.vars.dataAttr = options.dataAttr || App.setup.dataAttr;
  336. engineSettings.renderer = options.renderer ? options.renderer : App.setup.renderer;
  337. if (App.setup.renderers.join(',').indexOf(engineSettings.renderer) === -1) {
  338. engineSettings.renderer = App.setup.supportsSVG ? 'svg' : (App.setup.supportsCanvas ? 'canvas' : 'html');
  339. }
  340. var images = DOM.getNodeArray(options.images);
  341. var bgnodes = DOM.getNodeArray(options.bgnodes);
  342. var stylenodes = DOM.getNodeArray(options.stylenodes);
  343. var objects = DOM.getNodeArray(options.objects);
  344. engineSettings.stylesheets = [];
  345. engineSettings.svgXMLStylesheet = true;
  346. engineSettings.noFontFallback = options.noFontFallback ? options.noFontFallback : false;
  347. stylenodes.forEach(function (styleNode) {
  348. if (styleNode.attributes.rel && styleNode.attributes.href && styleNode.attributes.rel.value == 'stylesheet') {
  349. var href = styleNode.attributes.href.value;
  350. //todo: write isomorphic relative-to-absolute URL function
  351. var proxyLink = DOM.newEl('a');
  352. proxyLink.href = href;
  353. var stylesheetURL = proxyLink.protocol + '//' + proxyLink.host + proxyLink.pathname + proxyLink.search;
  354. engineSettings.stylesheets.push(stylesheetURL);
  355. }
  356. });
  357. bgnodes.forEach(function (bgNode) {
  358. //Skip processing background nodes if getComputedStyle is unavailable, since only modern browsers would be able to use canvas or SVG to render to background
  359. if (!global.getComputedStyle) return;
  360. var backgroundImage = global.getComputedStyle(bgNode, null).getPropertyValue('background-image');
  361. var dataBackgroundImage = bgNode.getAttribute('data-background-src');
  362. var rawURL = dataBackgroundImage || backgroundImage;
  363. var holderURL = null;
  364. var holderString = options.domain + '/';
  365. var holderStringIndex = rawURL.indexOf(holderString);
  366. if (holderStringIndex === 0) {
  367. holderURL = rawURL;
  368. } else if (holderStringIndex === 1 && rawURL[0] === '?') {
  369. holderURL = rawURL.slice(1);
  370. } else {
  371. var fragment = rawURL.substr(holderStringIndex).match(/([^\"]*)"?\)/);
  372. if (fragment !== null) {
  373. holderURL = fragment[1];
  374. } else if (rawURL.indexOf('url(') === 0) {
  375. throw 'Holder: unable to parse background URL: ' + rawURL;
  376. }
  377. }
  378. if (holderURL != null) {
  379. var holderFlags = parseURL(holderURL, options);
  380. if (holderFlags) {
  381. prepareDOMElement({
  382. mode: 'background',
  383. el: bgNode,
  384. flags: holderFlags,
  385. engineSettings: engineSettings
  386. });
  387. }
  388. }
  389. });
  390. objects.forEach(function (object) {
  391. var objectAttr = {};
  392. try {
  393. objectAttr.data = object.getAttribute('data');
  394. objectAttr.dataSrc = object.getAttribute(App.vars.dataAttr);
  395. } catch (e) {}
  396. var objectHasSrcURL = objectAttr.data != null && objectAttr.data.indexOf(options.domain) === 0;
  397. var objectHasDataSrcURL = objectAttr.dataSrc != null && objectAttr.dataSrc.indexOf(options.domain) === 0;
  398. if (objectHasSrcURL) {
  399. prepareImageElement(options, engineSettings, objectAttr.data, object);
  400. } else if (objectHasDataSrcURL) {
  401. prepareImageElement(options, engineSettings, objectAttr.dataSrc, object);
  402. }
  403. });
  404. images.forEach(function (image) {
  405. var imageAttr = {};
  406. try {
  407. imageAttr.src = image.getAttribute('src');
  408. imageAttr.dataSrc = image.getAttribute(App.vars.dataAttr);
  409. imageAttr.rendered = image.getAttribute('data-holder-rendered');
  410. } catch (e) {}
  411. var imageHasSrc = imageAttr.src != null;
  412. var imageHasDataSrcURL = imageAttr.dataSrc != null && imageAttr.dataSrc.indexOf(options.domain) === 0;
  413. var imageRendered = imageAttr.rendered != null && imageAttr.rendered == 'true';
  414. if (imageHasSrc) {
  415. if (imageAttr.src.indexOf(options.domain) === 0) {
  416. prepareImageElement(options, engineSettings, imageAttr.src, image);
  417. } else if (imageHasDataSrcURL) {
  418. //Image has a valid data-src and an invalid src
  419. if (imageRendered) {
  420. //If the placeholder has already been render, re-render it
  421. prepareImageElement(options, engineSettings, imageAttr.dataSrc, image);
  422. } else {
  423. //If the placeholder has not been rendered, check if the image exists and render a fallback if it doesn't
  424. (function(src, options, engineSettings, dataSrc, image) {
  425. utils.imageExists(src, function(exists) {
  426. if (!exists) {
  427. prepareImageElement(options, engineSettings, dataSrc, image);
  428. }
  429. });
  430. })(imageAttr.src, options, engineSettings, imageAttr.dataSrc, image);
  431. }
  432. }
  433. } else if (imageHasDataSrcURL) {
  434. prepareImageElement(options, engineSettings, imageAttr.dataSrc, image);
  435. }
  436. });
  437. return this;
  438. }
  439. };
  440. var App = {
  441. settings: {
  442. domain: 'holder.js',
  443. images: 'img',
  444. objects: 'object',
  445. bgnodes: 'body .holderjs',
  446. stylenodes: 'head link.holderjs',
  447. themes: {
  448. 'gray': {
  449. bg: '#EEEEEE',
  450. fg: '#AAAAAA'
  451. },
  452. 'social': {
  453. bg: '#3a5a97',
  454. fg: '#FFFFFF'
  455. },
  456. 'industrial': {
  457. bg: '#434A52',
  458. fg: '#C2F200'
  459. },
  460. 'sky': {
  461. bg: '#0D8FDB',
  462. fg: '#FFFFFF'
  463. },
  464. 'vine': {
  465. bg: '#39DBAC',
  466. fg: '#1E292C'
  467. },
  468. 'lava': {
  469. bg: '#F8591A',
  470. fg: '#1C2846'
  471. }
  472. }
  473. },
  474. defaults: {
  475. size: 10,
  476. units: 'pt',
  477. scale: 1 / 16
  478. }
  479. };
  480. /**
  481. * Processes provided source attribute and sets up the appropriate rendering workflow
  482. *
  483. * @private
  484. * @param options Instance options from Holder.run
  485. * @param renderSettings Instance configuration
  486. * @param src Image URL
  487. * @param el Image DOM element
  488. */
  489. function prepareImageElement(options, engineSettings, src, el) {
  490. var holderFlags = parseURL(src.substr(src.lastIndexOf(options.domain)), options);
  491. if (holderFlags) {
  492. prepareDOMElement({
  493. mode: null,
  494. el: el,
  495. flags: holderFlags,
  496. engineSettings: engineSettings
  497. });
  498. }
  499. }
  500. /**
  501. * Processes a Holder URL and extracts configuration from query string
  502. *
  503. * @private
  504. * @param url URL
  505. * @param instanceOptions Instance options from Holder.run
  506. */
  507. function parseURL(url, instanceOptions) {
  508. var holder = {
  509. theme: extend(App.settings.themes.gray, null),
  510. stylesheets: instanceOptions.stylesheets,
  511. instanceOptions: instanceOptions
  512. };
  513. var parts = url.split('?');
  514. var basics = parts[0].split('/');
  515. holder.holderURL = url;
  516. var dimensions = basics[1];
  517. var dimensionData = dimensions.match(/([\d]+p?)x([\d]+p?)/);
  518. if (!dimensionData) return false;
  519. holder.fluid = dimensions.indexOf('p') !== -1;
  520. holder.dimensions = {
  521. width: dimensionData[1].replace('p', '%'),
  522. height: dimensionData[2].replace('p', '%')
  523. };
  524. if (parts.length === 2) {
  525. var options = querystring.parse(parts[1]);
  526. // Colors
  527. if (options.bg) {
  528. holder.theme.bg = utils.parseColor(options.bg);
  529. }
  530. if (options.fg) {
  531. holder.theme.fg = utils.parseColor(options.fg);
  532. }
  533. //todo: add automatic foreground to themes without foreground
  534. if (options.bg && !options.fg) {
  535. holder.autoFg = true;
  536. }
  537. if (options.theme && holder.instanceOptions.themes.hasOwnProperty(options.theme)) {
  538. holder.theme = extend(holder.instanceOptions.themes[options.theme], null);
  539. }
  540. // Text
  541. if (options.text) {
  542. holder.text = options.text;
  543. }
  544. if (options.textmode) {
  545. holder.textmode = options.textmode;
  546. }
  547. if (options.size) {
  548. holder.size = options.size;
  549. }
  550. if (options.font) {
  551. holder.font = options.font;
  552. }
  553. if (options.align) {
  554. holder.align = options.align;
  555. }
  556. if (options.lineWrap) {
  557. holder.lineWrap = options.lineWrap;
  558. }
  559. holder.nowrap = utils.truthy(options.nowrap);
  560. // Miscellaneous
  561. holder.auto = utils.truthy(options.auto);
  562. holder.outline = utils.truthy(options.outline);
  563. if (utils.truthy(options.random)) {
  564. App.vars.cache.themeKeys = App.vars.cache.themeKeys || Object.keys(holder.instanceOptions.themes);
  565. var _theme = App.vars.cache.themeKeys[0 | Math.random() * App.vars.cache.themeKeys.length];
  566. holder.theme = extend(holder.instanceOptions.themes[_theme], null);
  567. }
  568. }
  569. return holder;
  570. }
  571. /**
  572. * Modifies the DOM to fit placeholders and sets up resizable image callbacks (for fluid and automatically sized placeholders)
  573. *
  574. * @private
  575. * @param settings DOM prep settings
  576. */
  577. function prepareDOMElement(prepSettings) {
  578. var mode = prepSettings.mode;
  579. var el = prepSettings.el;
  580. var flags = prepSettings.flags;
  581. var _engineSettings = prepSettings.engineSettings;
  582. var dimensions = flags.dimensions,
  583. theme = flags.theme;
  584. var dimensionsCaption = dimensions.width + 'x' + dimensions.height;
  585. mode = mode == null ? (flags.fluid ? 'fluid' : 'image') : mode;
  586. var holderTemplateRe = /holder_([a-z]+)/g;
  587. var dimensionsInText = false;
  588. if (flags.text != null) {
  589. theme.text = flags.text;
  590. //<object> SVG embedding doesn't parse Unicode properly
  591. if (el.nodeName.toLowerCase() === 'object') {
  592. var textLines = theme.text.split('\\n');
  593. for (var k = 0; k < textLines.length; k++) {
  594. textLines[k] = utils.encodeHtmlEntity(textLines[k]);
  595. }
  596. theme.text = textLines.join('\\n');
  597. }
  598. }
  599. if (theme.text) {
  600. var holderTemplateMatches = theme.text.match(holderTemplateRe);
  601. if (holderTemplateMatches !== null) {
  602. //todo: optimize template replacement
  603. holderTemplateMatches.forEach(function (match) {
  604. if (match === 'holder_dimensions') {
  605. theme.text = theme.text.replace(match, dimensionsCaption);
  606. }
  607. });
  608. }
  609. }
  610. var holderURL = flags.holderURL;
  611. var engineSettings = extend(_engineSettings, null);
  612. if (flags.font) {
  613. /*
  614. If external fonts are used in a <img> placeholder rendered with SVG, Holder falls back to canvas.
  615. This is done because Firefox and Chrome disallow embedded SVGs from referencing external assets.
  616. The workaround is either to change the placeholder tag from <img> to <object> or to use the canvas renderer.
  617. */
  618. theme.font = flags.font;
  619. if (!engineSettings.noFontFallback && el.nodeName.toLowerCase() === 'img' && App.setup.supportsCanvas && engineSettings.renderer === 'svg') {
  620. engineSettings = extend(engineSettings, {
  621. renderer: 'canvas'
  622. });
  623. }
  624. }
  625. //Chrome and Opera require a quick 10ms re-render if web fonts are used with canvas
  626. if (flags.font && engineSettings.renderer == 'canvas') {
  627. engineSettings.reRender = true;
  628. }
  629. if (mode == 'background') {
  630. if (el.getAttribute('data-background-src') == null) {
  631. DOM.setAttr(el, {
  632. 'data-background-src': holderURL
  633. });
  634. }
  635. } else {
  636. var domProps = {};
  637. domProps[App.vars.dataAttr] = holderURL;
  638. DOM.setAttr(el, domProps);
  639. }
  640. flags.theme = theme;
  641. //todo consider using all renderSettings in holderData
  642. el.holderData = {
  643. flags: flags,
  644. engineSettings: engineSettings
  645. };
  646. if (mode == 'image' || mode == 'fluid') {
  647. DOM.setAttr(el, {
  648. 'alt': theme.text ? (dimensionsInText ? theme.text : theme.text + ' [' + dimensionsCaption + ']') : dimensionsCaption
  649. });
  650. }
  651. var renderSettings = {
  652. mode: mode,
  653. el: el,
  654. holderSettings: {
  655. dimensions: dimensions,
  656. theme: theme,
  657. flags: flags
  658. },
  659. engineSettings: engineSettings
  660. };
  661. if (mode == 'image') {
  662. if (!flags.auto) {
  663. el.style.width = dimensions.width + 'px';
  664. el.style.height = dimensions.height + 'px';
  665. }
  666. if (engineSettings.renderer == 'html') {
  667. el.style.backgroundColor = theme.background;
  668. } else {
  669. render(renderSettings);
  670. if (flags.textmode == 'exact') {
  671. el.holderData.resizeUpdate = true;
  672. App.vars.resizableImages.push(el);
  673. updateResizableElements(el);
  674. }
  675. }
  676. } else if (mode == 'background' && engineSettings.renderer != 'html') {
  677. render(renderSettings);
  678. } else if (mode == 'fluid') {
  679. el.holderData.resizeUpdate = true;
  680. if (dimensions.height.slice(-1) == '%') {
  681. el.style.height = dimensions.height;
  682. } else if (flags.auto == null || !flags.auto) {
  683. el.style.height = dimensions.height + 'px';
  684. }
  685. if (dimensions.width.slice(-1) == '%') {
  686. el.style.width = dimensions.width;
  687. } else if (flags.auto == null || !flags.auto) {
  688. el.style.width = dimensions.width + 'px';
  689. }
  690. if (el.style.display == 'inline' || el.style.display === '' || el.style.display == 'none') {
  691. el.style.display = 'block';
  692. }
  693. setInitialDimensions(el);
  694. if (engineSettings.renderer == 'html') {
  695. el.style.backgroundColor = theme.background;
  696. } else {
  697. App.vars.resizableImages.push(el);
  698. updateResizableElements(el);
  699. }
  700. }
  701. }
  702. /**
  703. * Core function that takes output from renderers and sets it as the source or background-image of the target element
  704. *
  705. * @private
  706. * @param renderSettings Renderer settings
  707. */
  708. function render(renderSettings) {
  709. var image = null;
  710. var mode = renderSettings.mode;
  711. var el = renderSettings.el;
  712. var holderSettings = renderSettings.holderSettings;
  713. var engineSettings = renderSettings.engineSettings;
  714. switch (engineSettings.renderer) {
  715. case 'svg':
  716. if (!App.setup.supportsSVG) return;
  717. break;
  718. case 'canvas':
  719. if (!App.setup.supportsCanvas) return;
  720. break;
  721. default:
  722. return;
  723. }
  724. //todo: move generation of scene up to flag generation to reduce extra object creation
  725. var scene = {
  726. width: holderSettings.dimensions.width,
  727. height: holderSettings.dimensions.height,
  728. theme: holderSettings.theme,
  729. flags: holderSettings.flags
  730. };
  731. var sceneGraph = buildSceneGraph(scene);
  732. function getRenderedImage() {
  733. var image = null;
  734. switch (engineSettings.renderer) {
  735. case 'canvas':
  736. image = sgCanvasRenderer(sceneGraph, renderSettings);
  737. break;
  738. case 'svg':
  739. image = svgRenderer(sceneGraph, renderSettings);
  740. break;
  741. default:
  742. throw 'Holder: invalid renderer: ' + engineSettings.renderer;
  743. }
  744. return image;
  745. }
  746. image = getRenderedImage();
  747. if (image == null) {
  748. throw 'Holder: couldn\'t render placeholder';
  749. }
  750. //todo: add <object> canvas rendering
  751. if (mode == 'background') {
  752. el.style.backgroundImage = 'url(' + image + ')';
  753. el.style.backgroundSize = scene.width + 'px ' + scene.height + 'px';
  754. } else {
  755. if (el.nodeName.toLowerCase() === 'img') {
  756. DOM.setAttr(el, {
  757. 'src': image
  758. });
  759. } else if (el.nodeName.toLowerCase() === 'object') {
  760. DOM.setAttr(el, {
  761. 'data': image,
  762. 'type': 'image/svg+xml'
  763. });
  764. }
  765. if (engineSettings.reRender) {
  766. global.setTimeout(function () {
  767. var image = getRenderedImage();
  768. if (image == null) {
  769. throw 'Holder: couldn\'t render placeholder';
  770. }
  771. //todo: refactor this code into a function
  772. if (el.nodeName.toLowerCase() === 'img') {
  773. DOM.setAttr(el, {
  774. 'src': image
  775. });
  776. } else if (el.nodeName.toLowerCase() === 'object') {
  777. DOM.setAttr(el, {
  778. 'data': image,
  779. 'type': 'image/svg+xml'
  780. });
  781. }
  782. }, 150);
  783. }
  784. }
  785. //todo: account for re-rendering
  786. DOM.setAttr(el, {
  787. 'data-holder-rendered': true
  788. });
  789. }
  790. /**
  791. * Core function that takes a Holder scene description and builds a scene graph
  792. *
  793. * @private
  794. * @param scene Holder scene object
  795. */
  796. //todo: make this function reusable
  797. //todo: merge app defaults and setup properties into the scene argument
  798. function buildSceneGraph(scene) {
  799. var fontSize = App.defaults.size;
  800. if (parseFloat(scene.theme.size)) {
  801. fontSize = scene.theme.size;
  802. } else if (parseFloat(scene.flags.size)) {
  803. fontSize = scene.flags.size;
  804. }
  805. scene.font = {
  806. family: scene.theme.font ? scene.theme.font : 'Arial, Helvetica, Open Sans, sans-serif',
  807. size: textSize(scene.width, scene.height, fontSize, App.defaults.scale),
  808. units: scene.theme.units ? scene.theme.units : App.defaults.units,
  809. weight: scene.theme.fontweight ? scene.theme.fontweight : 'bold'
  810. };
  811. scene.text = scene.theme.text || Math.floor(scene.width) + 'x' + Math.floor(scene.height);
  812. scene.noWrap = scene.theme.nowrap || scene.flags.nowrap;
  813. scene.align = scene.theme.align || scene.flags.align || 'center';
  814. switch (scene.flags.textmode) {
  815. case 'literal':
  816. scene.text = scene.flags.dimensions.width + 'x' + scene.flags.dimensions.height;
  817. break;
  818. case 'exact':
  819. if (!scene.flags.exactDimensions) break;
  820. scene.text = Math.floor(scene.flags.exactDimensions.width) + 'x' + Math.floor(scene.flags.exactDimensions.height);
  821. break;
  822. }
  823. var lineWrap = scene.flags.lineWrap || App.setup.lineWrapRatio;
  824. var sceneMargin = scene.width * lineWrap;
  825. var maxLineWidth = sceneMargin;
  826. var sceneGraph = new SceneGraph({
  827. width: scene.width,
  828. height: scene.height
  829. });
  830. var Shape = sceneGraph.Shape;
  831. var holderBg = new Shape.Rect('holderBg', {
  832. fill: scene.theme.bg
  833. });
  834. holderBg.resize(scene.width, scene.height);
  835. sceneGraph.root.add(holderBg);
  836. if (scene.flags.outline) {
  837. var outlineColor = new Color(holderBg.properties.fill);
  838. outlineColor = outlineColor.lighten(outlineColor.lighterThan('7f7f7f') ? -0.1 : 0.1);
  839. holderBg.properties.outline = {
  840. fill: outlineColor.toHex(true),
  841. width: 2
  842. };
  843. }
  844. var holderTextColor = scene.theme.fg;
  845. if (scene.flags.autoFg) {
  846. var holderBgColor = new Color(holderBg.properties.fill);
  847. var lightColor = new Color('fff');
  848. var darkColor = new Color('000', {
  849. 'alpha': 0.285714
  850. });
  851. holderTextColor = holderBgColor.blendAlpha(holderBgColor.lighterThan('7f7f7f') ? darkColor : lightColor).toHex(true);
  852. }
  853. var holderTextGroup = new Shape.Group('holderTextGroup', {
  854. text: scene.text,
  855. align: scene.align,
  856. font: scene.font,
  857. fill: holderTextColor
  858. });
  859. holderTextGroup.moveTo(null, null, 1);
  860. sceneGraph.root.add(holderTextGroup);
  861. var tpdata = holderTextGroup.textPositionData = stagingRenderer(sceneGraph);
  862. if (!tpdata) {
  863. throw 'Holder: staging fallback not supported yet.';
  864. }
  865. holderTextGroup.properties.leading = tpdata.boundingBox.height;
  866. var textNode = null;
  867. var line = null;
  868. function finalizeLine(parent, line, width, height) {
  869. line.width = width;
  870. line.height = height;
  871. parent.width = Math.max(parent.width, line.width);
  872. parent.height += line.height;
  873. }
  874. if (tpdata.lineCount > 1) {
  875. var offsetX = 0;
  876. var offsetY = 0;
  877. var lineIndex = 0;
  878. var lineKey;
  879. line = new Shape.Group('line' + lineIndex);
  880. //Double margin so that left/right-aligned next is not flush with edge of image
  881. if (scene.align === 'left' || scene.align === 'right') {
  882. maxLineWidth = scene.width * (1 - (1 - lineWrap) * 2);
  883. }
  884. for (var i = 0; i < tpdata.words.length; i++) {
  885. var word = tpdata.words[i];
  886. textNode = new Shape.Text(word.text);
  887. var newline = word.text == '\\n';
  888. if (!scene.noWrap && (offsetX + word.width >= maxLineWidth || newline === true)) {
  889. finalizeLine(holderTextGroup, line, offsetX, holderTextGroup.properties.leading);
  890. holderTextGroup.add(line);
  891. offsetX = 0;
  892. offsetY += holderTextGroup.properties.leading;
  893. lineIndex += 1;
  894. line = new Shape.Group('line' + lineIndex);
  895. line.y = offsetY;
  896. }
  897. if (newline === true) {
  898. continue;
  899. }
  900. textNode.moveTo(offsetX, 0);
  901. offsetX += tpdata.spaceWidth + word.width;
  902. line.add(textNode);
  903. }
  904. finalizeLine(holderTextGroup, line, offsetX, holderTextGroup.properties.leading);
  905. holderTextGroup.add(line);
  906. if (scene.align === 'left') {
  907. holderTextGroup.moveTo(scene.width - sceneMargin, null, null);
  908. } else if (scene.align === 'right') {
  909. for (lineKey in holderTextGroup.children) {
  910. line = holderTextGroup.children[lineKey];
  911. line.moveTo(scene.width - line.width, null, null);
  912. }
  913. holderTextGroup.moveTo(0 - (scene.width - sceneMargin), null, null);
  914. } else {
  915. for (lineKey in holderTextGroup.children) {
  916. line = holderTextGroup.children[lineKey];
  917. line.moveTo((holderTextGroup.width - line.width) / 2, null, null);
  918. }
  919. holderTextGroup.moveTo((scene.width - holderTextGroup.width) / 2, null, null);
  920. }
  921. holderTextGroup.moveTo(null, (scene.height - holderTextGroup.height) / 2, null);
  922. //If the text exceeds vertical space, move it down so the first line is visible
  923. if ((scene.height - holderTextGroup.height) / 2 < 0) {
  924. holderTextGroup.moveTo(null, 0, null);
  925. }
  926. } else {
  927. textNode = new Shape.Text(scene.text);
  928. line = new Shape.Group('line0');
  929. line.add(textNode);
  930. holderTextGroup.add(line);
  931. if (scene.align === 'left') {
  932. holderTextGroup.moveTo(scene.width - sceneMargin, null, null);
  933. } else if (scene.align === 'right') {
  934. holderTextGroup.moveTo(0 - (scene.width - sceneMargin), null, null);
  935. } else {
  936. holderTextGroup.moveTo((scene.width - tpdata.boundingBox.width) / 2, null, null);
  937. }
  938. holderTextGroup.moveTo(null, (scene.height - tpdata.boundingBox.height) / 2, null);
  939. }
  940. //todo: renderlist
  941. return sceneGraph;
  942. }
  943. /**
  944. * Adaptive text sizing function
  945. *
  946. * @private
  947. * @param width Parent width
  948. * @param height Parent height
  949. * @param fontSize Requested text size
  950. * @param scale Proportional scale of text
  951. */
  952. function textSize(width, height, fontSize, scale) {
  953. var stageWidth = parseInt(width, 10);
  954. var stageHeight = parseInt(height, 10);
  955. var bigSide = Math.max(stageWidth, stageHeight);
  956. var smallSide = Math.min(stageWidth, stageHeight);
  957. var newHeight = 0.8 * Math.min(smallSide, bigSide * scale);
  958. return Math.round(Math.max(fontSize, newHeight));
  959. }
  960. /**
  961. * Iterates over resizable (fluid or auto) placeholders and renders them
  962. *
  963. * @private
  964. * @param element Optional element selector, specified only if a specific element needs to be re-rendered
  965. */
  966. function updateResizableElements(element) {
  967. var images;
  968. if (element == null || element.nodeType == null) {
  969. images = App.vars.resizableImages;
  970. } else {
  971. images = [element];
  972. }
  973. for (var i = 0, l = images.length; i < l; i++) {
  974. var el = images[i];
  975. if (el.holderData) {
  976. var flags = el.holderData.flags;
  977. var dimensions = dimensionCheck(el);
  978. if (dimensions) {
  979. if (!el.holderData.resizeUpdate) {
  980. continue;
  981. }
  982. if (flags.fluid && flags.auto) {
  983. var fluidConfig = el.holderData.fluidConfig;
  984. switch (fluidConfig.mode) {
  985. case 'width':
  986. dimensions.height = dimensions.width / fluidConfig.ratio;
  987. break;
  988. case 'height':
  989. dimensions.width = dimensions.height * fluidConfig.ratio;
  990. break;
  991. }
  992. }
  993. var settings = {
  994. mode: 'image',
  995. holderSettings: {
  996. dimensions: dimensions,
  997. theme: flags.theme,
  998. flags: flags
  999. },
  1000. el: el,
  1001. engineSettings: el.holderData.engineSettings
  1002. };
  1003. if (flags.textmode == 'exact') {
  1004. flags.exactDimensions = dimensions;
  1005. settings.holderSettings.dimensions = flags.dimensions;
  1006. }
  1007. render(settings);
  1008. } else {
  1009. setInvisible(el);
  1010. }
  1011. }
  1012. }
  1013. }
  1014. /**
  1015. * Sets up aspect ratio metadata for fluid placeholders, in order to preserve proportions when resizing
  1016. *
  1017. * @private
  1018. * @param el Image DOM element
  1019. */
  1020. function setInitialDimensions(el) {
  1021. if (el.holderData) {
  1022. var dimensions = dimensionCheck(el);
  1023. if (dimensions) {
  1024. var flags = el.holderData.flags;
  1025. var fluidConfig = {
  1026. fluidHeight: flags.dimensions.height.slice(-1) == '%',
  1027. fluidWidth: flags.dimensions.width.slice(-1) == '%',
  1028. mode: null,
  1029. initialDimensions: dimensions
  1030. };
  1031. if (fluidConfig.fluidWidth && !fluidConfig.fluidHeight) {
  1032. fluidConfig.mode = 'width';
  1033. fluidConfig.ratio = fluidConfig.initialDimensions.width / parseFloat(flags.dimensions.height);
  1034. } else if (!fluidConfig.fluidWidth && fluidConfig.fluidHeight) {
  1035. fluidConfig.mode = 'height';
  1036. fluidConfig.ratio = parseFloat(flags.dimensions.width) / fluidConfig.initialDimensions.height;
  1037. }
  1038. el.holderData.fluidConfig = fluidConfig;
  1039. } else {
  1040. setInvisible(el);
  1041. }
  1042. }
  1043. }
  1044. /**
  1045. * Iterates through all current invisible images, and if they're visible, renders them and removes them from further checks. Runs every animation frame.
  1046. *
  1047. * @private
  1048. */
  1049. function visibilityCheck() {
  1050. var renderableImages = [];
  1051. var keys = Object.keys(App.vars.invisibleImages);
  1052. var el;
  1053. keys.forEach(function (key) {
  1054. el = App.vars.invisibleImages[key];
  1055. if (dimensionCheck(el) && el.nodeName.toLowerCase() == 'img') {
  1056. renderableImages.push(el);
  1057. delete App.vars.invisibleImages[key];
  1058. }
  1059. });
  1060. if (renderableImages.length) {
  1061. Holder.run({
  1062. images: renderableImages
  1063. });
  1064. }
  1065. // Done to prevent 100% CPU usage via aggressive calling of requestAnimationFrame
  1066. setTimeout(function () {
  1067. global.requestAnimationFrame(visibilityCheck);
  1068. }, 10);
  1069. }
  1070. /**
  1071. * Starts checking for invisible placeholders if not doing so yet. Does nothing otherwise.
  1072. *
  1073. * @private
  1074. */
  1075. function startVisibilityCheck() {
  1076. if (!App.vars.visibilityCheckStarted) {
  1077. global.requestAnimationFrame(visibilityCheck);
  1078. App.vars.visibilityCheckStarted = true;
  1079. }
  1080. }
  1081. /**
  1082. * Sets a unique ID for an image detected to be invisible and adds it to the map of invisible images checked by visibilityCheck
  1083. *
  1084. * @private
  1085. * @param el Invisible DOM element
  1086. */
  1087. function setInvisible(el) {
  1088. if (!el.holderData.invisibleId) {
  1089. App.vars.invisibleId += 1;
  1090. App.vars.invisibleImages['i' + App.vars.invisibleId] = el;
  1091. el.holderData.invisibleId = App.vars.invisibleId;
  1092. }
  1093. }
  1094. //todo: see if possible to convert stagingRenderer to use HTML only
  1095. var stagingRenderer = (function() {
  1096. var svg = null,
  1097. stagingText = null,
  1098. stagingTextNode = null;
  1099. return function(graph) {
  1100. var rootNode = graph.root;
  1101. if (App.setup.supportsSVG) {
  1102. var firstTimeSetup = false;
  1103. var tnode = function(text) {
  1104. return document.createTextNode(text);
  1105. };
  1106. if (svg == null || svg.parentNode !== document.body) {
  1107. firstTimeSetup = true;
  1108. }
  1109. svg = SVG.initSVG(svg, rootNode.properties.width, rootNode.properties.height);
  1110. //Show staging element before staging
  1111. svg.style.display = 'block';
  1112. if (firstTimeSetup) {
  1113. stagingText = DOM.newEl('text', SVG_NS);
  1114. stagingTextNode = tnode(null);
  1115. DOM.setAttr(stagingText, {
  1116. x: 0
  1117. });
  1118. stagingText.appendChild(stagingTextNode);
  1119. svg.appendChild(stagingText);
  1120. document.body.appendChild(svg);
  1121. svg.style.visibility = 'hidden';
  1122. svg.style.position = 'absolute';
  1123. svg.style.top = '-100%';
  1124. svg.style.left = '-100%';
  1125. //todo: workaround for zero-dimension <svg> tag in Opera 12
  1126. //svg.setAttribute('width', 0);
  1127. //svg.setAttribute('height', 0);
  1128. }
  1129. var holderTextGroup = rootNode.children.holderTextGroup;
  1130. var htgProps = holderTextGroup.properties;
  1131. DOM.setAttr(stagingText, {
  1132. 'y': htgProps.font.size,
  1133. 'style': utils.cssProps({
  1134. 'font-weight': htgProps.font.weight,
  1135. 'font-size': htgProps.font.size + htgProps.font.units,
  1136. 'font-family': htgProps.font.family
  1137. })
  1138. });
  1139. //Get bounding box for the whole string (total width and height)
  1140. stagingTextNode.nodeValue = htgProps.text;
  1141. var stagingTextBBox = stagingText.getBBox();
  1142. //Get line count and split the string into words
  1143. var lineCount = Math.ceil(stagingTextBBox.width / rootNode.properties.width);
  1144. var words = htgProps.text.split(' ');
  1145. var newlines = htgProps.text.match(/\\n/g);
  1146. lineCount += newlines == null ? 0 : newlines.length;
  1147. //Get bounding box for the string with spaces removed
  1148. stagingTextNode.nodeValue = htgProps.text.replace(/[ ]+/g, '');
  1149. var computedNoSpaceLength = stagingText.getComputedTextLength();
  1150. //Compute average space width
  1151. var diffLength = stagingTextBBox.width - computedNoSpaceLength;
  1152. var spaceWidth = Math.round(diffLength / Math.max(1, words.length - 1));
  1153. //Get widths for every word with space only if there is more than one line
  1154. var wordWidths = [];
  1155. if (lineCount > 1) {
  1156. stagingTextNode.nodeValue = '';
  1157. for (var i = 0; i < words.length; i++) {
  1158. if (words[i].length === 0) continue;
  1159. stagingTextNode.nodeValue = utils.decodeHtmlEntity(words[i]);
  1160. var bbox = stagingText.getBBox();
  1161. wordWidths.push({
  1162. text: words[i],
  1163. width: bbox.width
  1164. });
  1165. }
  1166. }
  1167. //Hide staging element after staging
  1168. svg.style.display = 'none';
  1169. return {
  1170. spaceWidth: spaceWidth,
  1171. lineCount: lineCount,
  1172. boundingBox: stagingTextBBox,
  1173. words: wordWidths
  1174. };
  1175. } else {
  1176. //todo: canvas fallback for measuring text on android 2.3
  1177. return false;
  1178. }
  1179. };
  1180. })();
  1181. //Helpers
  1182. /**
  1183. * Prevents a function from being called too often, waits until a timer elapses to call it again
  1184. *
  1185. * @param fn Function to call
  1186. */
  1187. function debounce(fn) {
  1188. if (!App.vars.debounceTimer) fn.call(this);
  1189. if (App.vars.debounceTimer) global.clearTimeout(App.vars.debounceTimer);
  1190. App.vars.debounceTimer = global.setTimeout(function() {
  1191. App.vars.debounceTimer = null;
  1192. fn.call(this);
  1193. }, App.setup.debounce);
  1194. }
  1195. /**
  1196. * Holder-specific resize/orientation change callback, debounced to prevent excessive execution
  1197. */
  1198. function resizeEvent() {
  1199. debounce(function() {
  1200. updateResizableElements(null);
  1201. });
  1202. }
  1203. //Set up flags
  1204. for (var flag in App.flags) {
  1205. if (!App.flags.hasOwnProperty(flag)) continue;
  1206. App.flags[flag].match = function(val) {
  1207. return val.match(this.regex);
  1208. };
  1209. }
  1210. //Properties set once on setup
  1211. App.setup = {
  1212. renderer: 'html',
  1213. debounce: 100,
  1214. ratio: 1,
  1215. supportsCanvas: false,
  1216. supportsSVG: false,
  1217. lineWrapRatio: 0.9,
  1218. dataAttr: 'data-src',
  1219. renderers: ['html', 'canvas', 'svg']
  1220. };
  1221. //Properties modified during runtime
  1222. App.vars = {
  1223. preempted: false,
  1224. resizableImages: [],
  1225. invisibleImages: {},
  1226. invisibleId: 0,
  1227. visibilityCheckStarted: false,
  1228. debounceTimer: null,
  1229. cache: {}
  1230. };
  1231. //Pre-flight
  1232. (function() {
  1233. var canvas = DOM.newEl('canvas');
  1234. if (canvas.getContext) {
  1235. if (canvas.toDataURL('image/png').indexOf('data:image/png') != -1) {
  1236. App.setup.renderer = 'canvas';
  1237. App.setup.supportsCanvas = true;
  1238. }
  1239. }
  1240. if (!!document.createElementNS && !!document.createElementNS(SVG_NS, 'svg').createSVGRect) {
  1241. App.setup.renderer = 'svg';
  1242. App.setup.supportsSVG = true;
  1243. }
  1244. })();
  1245. //Starts checking for invisible placeholders
  1246. startVisibilityCheck();
  1247. if (onDomReady) {
  1248. onDomReady(function() {
  1249. if (!App.vars.preempted) {
  1250. Holder.run();
  1251. }
  1252. if (global.addEventListener) {
  1253. global.addEventListener('resize', resizeEvent, false);
  1254. global.addEventListener('orientationchange', resizeEvent, false);
  1255. } else {
  1256. global.attachEvent('onresize', resizeEvent);
  1257. }
  1258. if (typeof global.Turbolinks == 'object') {
  1259. global.document.addEventListener('page:change', function() {
  1260. Holder.run();
  1261. });
  1262. }
  1263. });
  1264. }
  1265. module.exports = Holder;
  1266. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
  1267. /***/ },
  1268. /* 2 */
  1269. /***/ function(module, exports) {
  1270. /*!
  1271. * onDomReady.js 1.4.0 (c) 2013 Tubal Martin - MIT license
  1272. *
  1273. * Specially modified to work with Holder.js
  1274. */
  1275. function _onDomReady(win) {
  1276. //Lazy loading fix for Firefox < 3.6
  1277. //http://webreflection.blogspot.com/2009/11/195-chars-to-help-lazy-loading.html
  1278. if (document.readyState == null && document.addEventListener) {
  1279. document.addEventListener("DOMContentLoaded", function DOMContentLoaded() {
  1280. document.removeEventListener("DOMContentLoaded", DOMContentLoaded, false);
  1281. document.readyState = "complete";
  1282. }, false);
  1283. document.readyState = "loading";
  1284. }
  1285. var doc = win.document,
  1286. docElem = doc.documentElement,
  1287. LOAD = "load",
  1288. FALSE = false,
  1289. ONLOAD = "on"+LOAD,
  1290. COMPLETE = "complete",
  1291. READYSTATE = "readyState",
  1292. ATTACHEVENT = "attachEvent",
  1293. DETACHEVENT = "detachEvent",
  1294. ADDEVENTLISTENER = "addEventListener",
  1295. DOMCONTENTLOADED = "DOMContentLoaded",
  1296. ONREADYSTATECHANGE = "onreadystatechange",
  1297. REMOVEEVENTLISTENER = "removeEventListener",
  1298. // W3C Event model
  1299. w3c = ADDEVENTLISTENER in doc,
  1300. _top = FALSE,
  1301. // isReady: Is the DOM ready to be used? Set to true once it occurs.
  1302. isReady = FALSE,
  1303. // Callbacks pending execution until DOM is ready
  1304. callbacks = [];
  1305. // Handle when the DOM is ready
  1306. function ready( fn ) {
  1307. if ( !isReady ) {
  1308. // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
  1309. if ( !doc.body ) {
  1310. return defer( ready );
  1311. }
  1312. // Remember that the DOM is ready
  1313. isReady = true;
  1314. // Execute all callbacks
  1315. while ( fn = callbacks.shift() ) {
  1316. defer( fn );
  1317. }
  1318. }
  1319. }
  1320. // The ready event handler
  1321. function completed( event ) {
  1322. // readyState === "complete" is good enough for us to call the dom ready in oldIE
  1323. if ( w3c || event.type === LOAD || doc[READYSTATE] === COMPLETE ) {
  1324. detach();
  1325. ready();
  1326. }
  1327. }
  1328. // Clean-up method for dom ready events
  1329. function detach() {
  1330. if ( w3c ) {
  1331. doc[REMOVEEVENTLISTENER]( DOMCONTENTLOADED, completed, FALSE );
  1332. win[REMOVEEVENTLISTENER]( LOAD, completed, FALSE );
  1333. } else {
  1334. doc[DETACHEVENT]( ONREADYSTATECHANGE, completed );
  1335. win[DETACHEVENT]( ONLOAD, completed );
  1336. }
  1337. }
  1338. // Defers a function, scheduling it to run after the current call stack has cleared.
  1339. function defer( fn, wait ) {
  1340. // Allow 0 to be passed
  1341. setTimeout( fn, +wait >= 0 ? wait : 1 );
  1342. }
  1343. // Attach the listeners:
  1344. // Catch cases where onDomReady is called after the browser event has already occurred.
  1345. // we once tried to use readyState "interactive" here, but it caused issues like the one
  1346. // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
  1347. if ( doc[READYSTATE] === COMPLETE ) {
  1348. // Handle it asynchronously to allow scripts the opportunity to delay ready
  1349. defer( ready );
  1350. // Standards-based browsers support DOMContentLoaded
  1351. } else if ( w3c ) {
  1352. // Use the handy event callback
  1353. doc[ADDEVENTLISTENER]( DOMCONTENTLOADED, completed, FALSE );
  1354. // A fallback to window.onload, that will always work
  1355. win[ADDEVENTLISTENER]( LOAD, completed, FALSE );
  1356. // If IE event model is used
  1357. } else {
  1358. // Ensure firing before onload, maybe late but safe also for iframes
  1359. doc[ATTACHEVENT]( ONREADYSTATECHANGE, completed );
  1360. // A fallback to window.onload, that will always work
  1361. win[ATTACHEVENT]( ONLOAD, completed );
  1362. // If IE and not a frame
  1363. // continually check to see if the document is ready
  1364. try {
  1365. _top = win.frameElement == null && docElem;
  1366. } catch(e) {}
  1367. if ( _top && _top.doScroll ) {
  1368. (function doScrollCheck() {
  1369. if ( !isReady ) {
  1370. try {
  1371. // Use the trick by Diego Perini
  1372. // http://javascript.nwbox.com/IEContentLoaded/
  1373. _top.doScroll("left");
  1374. } catch(e) {
  1375. return defer( doScrollCheck, 50 );
  1376. }
  1377. // detach all dom ready events
  1378. detach();
  1379. // and execute any waiting functions
  1380. ready();
  1381. }
  1382. })();
  1383. }
  1384. }
  1385. function onDomReady( fn ) {
  1386. // If DOM is ready, execute the function (async), otherwise wait
  1387. isReady ? defer( fn ) : callbacks.push( fn );
  1388. }
  1389. // Add version
  1390. onDomReady.version = "1.4.0";
  1391. // Add method to check if DOM is ready
  1392. onDomReady.isReady = function(){
  1393. return isReady;
  1394. };
  1395. return onDomReady;
  1396. }
  1397. module.exports = typeof window !== "undefined" && _onDomReady(window);
  1398. /***/ },
  1399. /* 3 */
  1400. /***/ function(module, exports, __webpack_require__) {
  1401. //Modified version of component/querystring
  1402. //Changes: updated dependencies, dot notation parsing, JSHint fixes
  1403. //Fork at https://github.com/imsky/querystring
  1404. /**
  1405. * Module dependencies.
  1406. */
  1407. var encode = encodeURIComponent;
  1408. var decode = decodeURIComponent;
  1409. var trim = __webpack_require__(4);
  1410. var type = __webpack_require__(5);
  1411. var arrayRegex = /(\w+)\[(\d+)\]/;
  1412. var objectRegex = /\w+\.\w+/;
  1413. /**
  1414. * Parse the given query `str`.
  1415. *
  1416. * @param {String} str
  1417. * @return {Object}
  1418. * @api public
  1419. */
  1420. exports.parse = function(str){
  1421. if ('string' !== typeof str) return {};
  1422. str = trim(str);
  1423. if ('' === str) return {};
  1424. if ('?' === str.charAt(0)) str = str.slice(1);
  1425. var obj = {};
  1426. var pairs = str.split('&');
  1427. for (var i = 0; i < pairs.length; i++) {
  1428. var parts = pairs[i].split('=');
  1429. var key = decode(parts[0]);
  1430. var m, ctx, prop;
  1431. if (m = arrayRegex.exec(key)) {
  1432. obj[m[1]] = obj[m[1]] || [];
  1433. obj[m[1]][m[2]] = decode(parts[1]);
  1434. continue;
  1435. }
  1436. if (m = objectRegex.test(key)) {
  1437. m = key.split('.');
  1438. ctx = obj;
  1439. while (m.length) {
  1440. prop = m.shift();
  1441. if (!prop.length) continue;
  1442. if (!ctx[prop]) {
  1443. ctx[prop] = {};
  1444. } else if (ctx[prop] && typeof ctx[prop] !== 'object') {
  1445. break;
  1446. }
  1447. if (!m.length) {
  1448. ctx[prop] = decode(parts[1]);
  1449. }
  1450. ctx = ctx[prop];
  1451. }
  1452. continue;
  1453. }
  1454. obj[parts[0]] = null == parts[1] ? '' : decode(parts[1]);
  1455. }
  1456. return obj;
  1457. };
  1458. /**
  1459. * Stringify the given `obj`.
  1460. *
  1461. * @param {Object} obj
  1462. * @return {String}
  1463. * @api public
  1464. */
  1465. exports.stringify = function(obj){
  1466. if (!obj) return '';
  1467. var pairs = [];
  1468. for (var key in obj) {
  1469. var value = obj[key];
  1470. if ('array' == type(value)) {
  1471. for (var i = 0; i < value.length; ++i) {
  1472. pairs.push(encode(key + '[' + i + ']') + '=' + encode(value[i]));
  1473. }
  1474. continue;
  1475. }
  1476. pairs.push(encode(key) + '=' + encode(obj[key]));
  1477. }
  1478. return pairs.join('&');
  1479. };
  1480. /***/ },
  1481. /* 4 */
  1482. /***/ function(module, exports) {
  1483. exports = module.exports = trim;
  1484. function trim(str){
  1485. return str.replace(/^\s*|\s*$/g, '');
  1486. }
  1487. exports.left = function(str){
  1488. return str.replace(/^\s*/, '');
  1489. };
  1490. exports.right = function(str){
  1491. return str.replace(/\s*$/, '');
  1492. };
  1493. /***/ },
  1494. /* 5 */
  1495. /***/ function(module, exports) {
  1496. /**
  1497. * toString ref.
  1498. */
  1499. var toString = Object.prototype.toString;
  1500. /**
  1501. * Return the type of `val`.
  1502. *
  1503. * @param {Mixed} val
  1504. * @return {String}
  1505. * @api public
  1506. */
  1507. module.exports = function(val){
  1508. switch (toString.call(val)) {
  1509. case '[object Date]': return 'date';
  1510. case '[object RegExp]': return 'regexp';
  1511. case '[object Arguments]': return 'arguments';
  1512. case '[object Array]': return 'array';
  1513. case '[object Error]': return 'error';
  1514. }
  1515. if (val === null) return 'null';
  1516. if (val === undefined) return 'undefined';
  1517. if (val !== val) return 'nan';
  1518. if (val && val.nodeType === 1) return 'element';
  1519. val = val.valueOf
  1520. ? val.valueOf()
  1521. : Object.prototype.valueOf.apply(val)
  1522. return typeof val;
  1523. };
  1524. /***/ },
  1525. /* 6 */
  1526. /***/ function(module, exports) {
  1527. var SceneGraph = function(sceneProperties) {
  1528. var nodeCount = 1;
  1529. //todo: move merge to helpers section
  1530. function merge(parent, child) {
  1531. for (var prop in child) {
  1532. parent[prop] = child[prop];
  1533. }
  1534. return parent;
  1535. }
  1536. var SceneNode = function(name) {
  1537. nodeCount++;
  1538. this.parent = null;
  1539. this.children = {};
  1540. this.id = nodeCount;
  1541. this.name = 'n' + nodeCount;
  1542. if (typeof name !== 'undefined') {
  1543. this.name = name;
  1544. }
  1545. this.x = this.y = this.z = 0;
  1546. this.width = this.height = 0;
  1547. };
  1548. SceneNode.prototype.resize = function(width, height) {
  1549. if (width != null) {
  1550. this.width = width;
  1551. }
  1552. if (height != null) {
  1553. this.height = height;
  1554. }
  1555. };
  1556. SceneNode.prototype.moveTo = function(x, y, z) {
  1557. this.x = x != null ? x : this.x;
  1558. this.y = y != null ? y : this.y;
  1559. this.z = z != null ? z : this.z;
  1560. };
  1561. SceneNode.prototype.add = function(child) {
  1562. var name = child.name;
  1563. if (typeof this.children[name] === 'undefined') {
  1564. this.children[name] = child;
  1565. child.parent = this;
  1566. } else {
  1567. throw 'SceneGraph: child already exists: ' + name;
  1568. }
  1569. };
  1570. var RootNode = function() {
  1571. SceneNode.call(this, 'root');
  1572. this.properties = sceneProperties;
  1573. };
  1574. RootNode.prototype = new SceneNode();
  1575. var Shape = function(name, props) {
  1576. SceneNode.call(this, name);
  1577. this.properties = {
  1578. 'fill': '#000000'
  1579. };
  1580. if (typeof props !== 'undefined') {
  1581. merge(this.properties, props);
  1582. } else if (typeof name !== 'undefined' && typeof name !== 'string') {
  1583. throw 'SceneGraph: invalid node name';
  1584. }
  1585. };
  1586. Shape.prototype = new SceneNode();
  1587. var Group = function() {
  1588. Shape.apply(this, arguments);
  1589. this.type = 'group';
  1590. };
  1591. Group.prototype = new Shape();
  1592. var Rect = function() {
  1593. Shape.apply(this, arguments);
  1594. this.type = 'rect';
  1595. };
  1596. Rect.prototype = new Shape();
  1597. var Text = function(text) {
  1598. Shape.call(this);
  1599. this.type = 'text';
  1600. this.properties.text = text;
  1601. };
  1602. Text.prototype = new Shape();
  1603. var root = new RootNode();
  1604. this.Shape = {
  1605. 'Rect': Rect,
  1606. 'Text': Text,
  1607. 'Group': Group
  1608. };
  1609. this.root = root;
  1610. return this;
  1611. };
  1612. module.exports = SceneGraph;
  1613. /***/ },
  1614. /* 7 */
  1615. /***/ function(module, exports) {
  1616. /* WEBPACK VAR INJECTION */(function(global) {/**
  1617. * Shallow object clone and merge
  1618. *
  1619. * @param a Object A
  1620. * @param b Object B
  1621. * @returns {Object} New object with all of A's properties, and all of B's properties, overwriting A's properties
  1622. */
  1623. exports.extend = function(a, b) {
  1624. var c = {};
  1625. for (var x in a) {
  1626. if (a.hasOwnProperty(x)) {
  1627. c[x] = a[x];
  1628. }
  1629. }
  1630. if (b != null) {
  1631. for (var y in b) {
  1632. if (b.hasOwnProperty(y)) {
  1633. c[y] = b[y];
  1634. }
  1635. }
  1636. }
  1637. return c;
  1638. };
  1639. /**
  1640. * Takes a k/v list of CSS properties and returns a rule
  1641. *
  1642. * @param props CSS properties object
  1643. */
  1644. exports.cssProps = function(props) {
  1645. var ret = [];
  1646. for (var p in props) {
  1647. if (props.hasOwnProperty(p)) {
  1648. ret.push(p + ':' + props[p]);
  1649. }
  1650. }
  1651. return ret.join(';');
  1652. };
  1653. /**
  1654. * Encodes HTML entities in a string
  1655. *
  1656. * @param str Input string
  1657. */
  1658. exports.encodeHtmlEntity = function(str) {
  1659. var buf = [];
  1660. var charCode = 0;
  1661. for (var i = str.length - 1; i >= 0; i--) {
  1662. charCode = str.charCodeAt(i);
  1663. if (charCode > 128) {
  1664. buf.unshift(['&#', charCode, ';'].join(''));
  1665. } else {
  1666. buf.unshift(str[i]);
  1667. }
  1668. }
  1669. return buf.join('');
  1670. };
  1671. /**
  1672. * Checks if an image exists
  1673. *
  1674. * @param src URL of image
  1675. * @param callback Callback to call once image status has been found
  1676. */
  1677. exports.imageExists = function(src, callback) {
  1678. var image = new Image();
  1679. image.onerror = function() {
  1680. callback.call(this, false);
  1681. };
  1682. image.onload = function() {
  1683. callback.call(this, true);
  1684. };
  1685. image.src = src;
  1686. };
  1687. /**
  1688. * Decodes HTML entities in a string
  1689. *
  1690. * @param str Input string
  1691. */
  1692. exports.decodeHtmlEntity = function(str) {
  1693. return str.replace(/&#(\d+);/g, function(match, dec) {
  1694. return String.fromCharCode(dec);
  1695. });
  1696. };
  1697. /**
  1698. * Returns an element's dimensions if it's visible, `false` otherwise.
  1699. *
  1700. * @param el DOM element
  1701. */
  1702. exports.dimensionCheck = function(el) {
  1703. var dimensions = {
  1704. height: el.clientHeight,
  1705. width: el.clientWidth
  1706. };
  1707. if (dimensions.height && dimensions.width) {
  1708. return dimensions;
  1709. } else {
  1710. return false;
  1711. }
  1712. };
  1713. /**
  1714. * Returns true if value is truthy or if it is "semantically truthy"
  1715. * @param val
  1716. */
  1717. exports.truthy = function(val) {
  1718. if (typeof val === 'string') {
  1719. return val === 'true' || val === 'yes' || val === '1' || val === 'on' || val === '✓';
  1720. }
  1721. return !!val;
  1722. };
  1723. /**
  1724. * Parses input into a well-formed CSS color
  1725. * @param val
  1726. */
  1727. exports.parseColor = function(val) {
  1728. var hexre = /(^(?:#?)[0-9a-f]{6}$)|(^(?:#?)[0-9a-f]{3}$)/i;
  1729. var rgbre = /^rgb\((\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/;
  1730. var rgbare = /^rgba\((\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(0\.\d{1,}|1)\)$/;
  1731. var match = val.match(hexre);
  1732. var retval;
  1733. if (match !== null) {
  1734. retval = match[1] || match[2];
  1735. if (retval[0] !== '#') {
  1736. return '#' + retval;
  1737. } else {
  1738. return retval;
  1739. }
  1740. }
  1741. match = val.match(rgbre);
  1742. if (match !== null) {
  1743. retval = 'rgb(' + match.slice(1).join(',') + ')';
  1744. return retval;
  1745. }
  1746. match = val.match(rgbare);
  1747. if (match !== null) {
  1748. retval = 'rgba(' + match.slice(1).join(',') + ')';
  1749. return retval;
  1750. }
  1751. return null;
  1752. };
  1753. /**
  1754. * Provides the correct scaling ratio for canvas drawing operations on HiDPI screens (e.g. Retina displays)
  1755. */
  1756. exports.canvasRatio = function () {
  1757. var devicePixelRatio = 1;
  1758. var backingStoreRatio = 1;
  1759. if (global.document) {
  1760. var canvas = global.document.createElement('canvas');
  1761. if (canvas.getContext) {
  1762. var ctx = canvas.getContext('2d');
  1763. devicePixelRatio = global.devicePixelRatio || 1;
  1764. backingStoreRatio = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1;
  1765. }
  1766. }
  1767. return devicePixelRatio / backingStoreRatio;
  1768. };
  1769. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
  1770. /***/ },
  1771. /* 8 */
  1772. /***/ function(module, exports, __webpack_require__) {
  1773. /* WEBPACK VAR INJECTION */(function(global) {var DOM = __webpack_require__(9);
  1774. var SVG_NS = 'http://www.w3.org/2000/svg';
  1775. var NODE_TYPE_COMMENT = 8;
  1776. /**
  1777. * Generic SVG element creation function
  1778. *
  1779. * @param svg SVG context, set to null if new
  1780. * @param width Document width
  1781. * @param height Document height
  1782. */
  1783. exports.initSVG = function(svg, width, height) {
  1784. var defs, style, initialize = false;
  1785. if (svg && svg.querySelector) {
  1786. style = svg.querySelector('style');
  1787. if (style === null) {
  1788. initialize = true;
  1789. }
  1790. } else {
  1791. svg = DOM.newEl('svg', SVG_NS);
  1792. initialize = true;
  1793. }
  1794. if (initialize) {
  1795. defs = DOM.newEl('defs', SVG_NS);
  1796. style = DOM.newEl('style', SVG_NS);
  1797. DOM.setAttr(style, {
  1798. 'type': 'text/css'
  1799. });
  1800. defs.appendChild(style);
  1801. svg.appendChild(defs);
  1802. }
  1803. //IE throws an exception if this is set and Chrome requires it to be set
  1804. if (svg.webkitMatchesSelector) {
  1805. svg.setAttribute('xmlns', SVG_NS);
  1806. }
  1807. //Remove comment nodes
  1808. for (var i = 0; i < svg.childNodes.length; i++) {
  1809. if (svg.childNodes[i].nodeType === NODE_TYPE_COMMENT) {
  1810. svg.removeChild(svg.childNodes[i]);
  1811. }
  1812. }
  1813. //Remove CSS
  1814. while (style.childNodes.length) {
  1815. style.removeChild(style.childNodes[0]);
  1816. }
  1817. DOM.setAttr(svg, {
  1818. 'width': width,
  1819. 'height': height,
  1820. 'viewBox': '0 0 ' + width + ' ' + height,
  1821. 'preserveAspectRatio': 'none'
  1822. });
  1823. return svg;
  1824. };
  1825. /**
  1826. * Converts serialized SVG to a string suitable for data URI use
  1827. * @param svgString Serialized SVG string
  1828. * @param [base64] Use base64 encoding for data URI
  1829. */
  1830. exports.svgStringToDataURI = function() {
  1831. var rawPrefix = 'data:image/svg+xml;charset=UTF-8,';
  1832. var base64Prefix = 'data:image/svg+xml;charset=UTF-8;base64,';
  1833. return function(svgString, base64) {
  1834. if (base64) {
  1835. return base64Prefix + btoa(global.unescape(encodeURIComponent(svgString)));
  1836. } else {
  1837. return rawPrefix + encodeURIComponent(svgString);
  1838. }
  1839. };
  1840. }();
  1841. /**
  1842. * Returns serialized SVG with XML processing instructions
  1843. *
  1844. * @param svg SVG context
  1845. * @param stylesheets CSS stylesheets to include
  1846. */
  1847. exports.serializeSVG = function(svg, engineSettings) {
  1848. if (!global.XMLSerializer) return;
  1849. var serializer = new XMLSerializer();
  1850. var svgCSS = '';
  1851. var stylesheets = engineSettings.stylesheets;
  1852. //External stylesheets: Processing Instruction method
  1853. if (engineSettings.svgXMLStylesheet) {
  1854. var xml = DOM.createXML();
  1855. //Add <?xml-stylesheet ?> directives
  1856. for (var i = stylesheets.length - 1; i >= 0; i--) {
  1857. var csspi = xml.createProcessingInstruction('xml-stylesheet', 'href="' + stylesheets[i] + '" rel="stylesheet"');
  1858. xml.insertBefore(csspi, xml.firstChild);
  1859. }
  1860. xml.removeChild(xml.documentElement);
  1861. svgCSS = serializer.serializeToString(xml);
  1862. }
  1863. var svgText = serializer.serializeToString(svg);
  1864. svgText = svgText.replace(/\&amp;(\#[0-9]{2,}\;)/g, '&$1');
  1865. return svgCSS + svgText;
  1866. };
  1867. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
  1868. /***/ },
  1869. /* 9 */
  1870. /***/ function(module, exports) {
  1871. /* WEBPACK VAR INJECTION */(function(global) {/**
  1872. * Generic new DOM element function
  1873. *
  1874. * @param tag Tag to create
  1875. * @param namespace Optional namespace value
  1876. */
  1877. exports.newEl = function(tag, namespace) {
  1878. if (!global.document) return;
  1879. if (namespace == null) {
  1880. return global.document.createElement(tag);
  1881. } else {
  1882. return global.document.createElementNS(namespace, tag);
  1883. }
  1884. };
  1885. /**
  1886. * Generic setAttribute function
  1887. *
  1888. * @param el Reference to DOM element
  1889. * @param attrs Object with attribute keys and values
  1890. */
  1891. exports.setAttr = function (el, attrs) {
  1892. for (var a in attrs) {
  1893. el.setAttribute(a, attrs[a]);
  1894. }
  1895. };
  1896. /**
  1897. * Creates a XML document
  1898. * @private
  1899. */
  1900. exports.createXML = function() {
  1901. if (!global.DOMParser) return;
  1902. return new DOMParser().parseFromString('<xml />', 'application/xml');
  1903. };
  1904. /**
  1905. * Converts a value into an array of DOM nodes
  1906. *
  1907. * @param val A string, a NodeList, a Node, or an HTMLCollection
  1908. */
  1909. exports.getNodeArray = function(val) {
  1910. var retval = null;
  1911. if (typeof(val) == 'string') {
  1912. retval = document.querySelectorAll(val);
  1913. } else if (global.NodeList && val instanceof global.NodeList) {
  1914. retval = val;
  1915. } else if (global.Node && val instanceof global.Node) {
  1916. retval = [val];
  1917. } else if (global.HTMLCollection && val instanceof global.HTMLCollection) {
  1918. retval = val;
  1919. } else if (val instanceof Array) {
  1920. retval = val;
  1921. } else if (val === null) {
  1922. retval = [];
  1923. }
  1924. retval = Array.prototype.slice.call(retval);
  1925. return retval;
  1926. };
  1927. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
  1928. /***/ },
  1929. /* 10 */
  1930. /***/ function(module, exports) {
  1931. var Color = function(color, options) {
  1932. //todo: support rgba, hsla, and rrggbbaa notation
  1933. //todo: use CIELAB internally
  1934. //todo: add clamp function (with sign)
  1935. if (typeof color !== 'string') return;
  1936. this.original = color;
  1937. if (color.charAt(0) === '#') {
  1938. color = color.slice(1);
  1939. }
  1940. if (/[^a-f0-9]+/i.test(color)) return;
  1941. if (color.length === 3) {
  1942. color = color.replace(/./g, '$&$&');
  1943. }
  1944. if (color.length !== 6) return;
  1945. this.alpha = 1;
  1946. if (options && options.alpha) {
  1947. this.alpha = options.alpha;
  1948. }
  1949. this.set(parseInt(color, 16));
  1950. };
  1951. //todo: jsdocs
  1952. Color.rgb2hex = function(r, g, b) {
  1953. function format (decimal) {
  1954. var hex = (decimal | 0).toString(16);
  1955. if (decimal < 16) {
  1956. hex = '0' + hex;
  1957. }
  1958. return hex;
  1959. }
  1960. return [r, g, b].map(format).join('');
  1961. };
  1962. //todo: jsdocs
  1963. Color.hsl2rgb = function (h, s, l) {
  1964. var H = h / 60;
  1965. var C = (1 - Math.abs(2 * l - 1)) * s;
  1966. var X = C * (1 - Math.abs(parseInt(H) % 2 - 1));
  1967. var m = l - (C / 2);
  1968. var r = 0, g = 0, b = 0;
  1969. if (H >= 0 && H < 1) {
  1970. r = C;
  1971. g = X;
  1972. } else if (H >= 1 && H < 2) {
  1973. r = X;
  1974. g = C;
  1975. } else if (H >= 2 && H < 3) {
  1976. g = C;
  1977. b = X;
  1978. } else if (H >= 3 && H < 4) {
  1979. g = X;
  1980. b = C;
  1981. } else if (H >= 4 && H < 5) {
  1982. r = X;
  1983. b = C;
  1984. } else if (H >= 5 && H < 6) {
  1985. r = C;
  1986. b = X;
  1987. }
  1988. r += m;
  1989. g += m;
  1990. b += m;
  1991. r = parseInt(r * 255);
  1992. g = parseInt(g * 255);
  1993. b = parseInt(b * 255);
  1994. return [r, g, b];
  1995. };
  1996. /**
  1997. * Sets the color from a raw RGB888 integer
  1998. * @param raw RGB888 representation of color
  1999. */
  2000. //todo: refactor into a static method
  2001. //todo: factor out individual color spaces
  2002. //todo: add HSL, CIELAB, and CIELUV
  2003. Color.prototype.set = function (val) {
  2004. this.raw = val;
  2005. var r = (this.raw & 0xFF0000) >> 16;
  2006. var g = (this.raw & 0x00FF00) >> 8;
  2007. var b = (this.raw & 0x0000FF);
  2008. // BT.709
  2009. var y = 0.2126 * r + 0.7152 * g + 0.0722 * b;
  2010. var u = -0.09991 * r - 0.33609 * g + 0.436 * b;
  2011. var v = 0.615 * r - 0.55861 * g - 0.05639 * b;
  2012. this.rgb = {
  2013. r: r,
  2014. g: g,
  2015. b: b
  2016. };
  2017. this.yuv = {
  2018. y: y,
  2019. u: u,
  2020. v: v
  2021. };
  2022. return this;
  2023. };
  2024. /**
  2025. * Lighten or darken a color
  2026. * @param multiplier Amount to lighten or darken (-1 to 1)
  2027. */
  2028. Color.prototype.lighten = function(multiplier) {
  2029. var cm = Math.min(1, Math.max(0, Math.abs(multiplier))) * (multiplier < 0 ? -1 : 1);
  2030. var bm = (255 * cm) | 0;
  2031. var cr = Math.min(255, Math.max(0, this.rgb.r + bm));
  2032. var cg = Math.min(255, Math.max(0, this.rgb.g + bm));
  2033. var cb = Math.min(255, Math.max(0, this.rgb.b + bm));
  2034. var hex = Color.rgb2hex(cr, cg, cb);
  2035. return new Color(hex);
  2036. };
  2037. /**
  2038. * Output color in hex format
  2039. * @param addHash Add a hash character to the beginning of the output
  2040. */
  2041. Color.prototype.toHex = function(addHash) {
  2042. return (addHash ? '#' : '') + this.raw.toString(16);
  2043. };
  2044. /**
  2045. * Returns whether or not current color is lighter than another color
  2046. * @param color Color to compare against
  2047. */
  2048. Color.prototype.lighterThan = function(color) {
  2049. if (!(color instanceof Color)) {
  2050. color = new Color(color);
  2051. }
  2052. return this.yuv.y > color.yuv.y;
  2053. };
  2054. /**
  2055. * Returns the result of mixing current color with another color
  2056. * @param color Color to mix with
  2057. * @param multiplier How much to mix with the other color
  2058. */
  2059. /*
  2060. Color.prototype.mix = function (color, multiplier) {
  2061. if (!(color instanceof Color)) {
  2062. color = new Color(color);
  2063. }
  2064. var r = this.rgb.r;
  2065. var g = this.rgb.g;
  2066. var b = this.rgb.b;
  2067. var a = this.alpha;
  2068. var m = typeof multiplier !== 'undefined' ? multiplier : 0.5;
  2069. //todo: write a lerp function
  2070. r = r + m * (color.rgb.r - r);
  2071. g = g + m * (color.rgb.g - g);
  2072. b = b + m * (color.rgb.b - b);
  2073. a = a + m * (color.alpha - a);
  2074. return new Color(Color.rgbToHex(r, g, b), {
  2075. 'alpha': a
  2076. });
  2077. };
  2078. */
  2079. /**
  2080. * Returns the result of blending another color on top of current color with alpha
  2081. * @param color Color to blend on top of current color, i.e. "Ca"
  2082. */
  2083. //todo: see if .blendAlpha can be merged into .mix
  2084. Color.prototype.blendAlpha = function(color) {
  2085. if (!(color instanceof Color)) {
  2086. color = new Color(color);
  2087. }
  2088. var Ca = color;
  2089. var Cb = this;
  2090. //todo: write alpha blending function
  2091. var r = Ca.alpha * Ca.rgb.r + (1 - Ca.alpha) * Cb.rgb.r;
  2092. var g = Ca.alpha * Ca.rgb.g + (1 - Ca.alpha) * Cb.rgb.g;
  2093. var b = Ca.alpha * Ca.rgb.b + (1 - Ca.alpha) * Cb.rgb.b;
  2094. return new Color(Color.rgb2hex(r, g, b));
  2095. };
  2096. module.exports = Color;
  2097. /***/ },
  2098. /* 11 */
  2099. /***/ function(module, exports) {
  2100. module.exports = {
  2101. 'version': '2.9.0',
  2102. 'svg_ns': 'http://www.w3.org/2000/svg'
  2103. };
  2104. /***/ },
  2105. /* 12 */
  2106. /***/ function(module, exports, __webpack_require__) {
  2107. var shaven = __webpack_require__(13);
  2108. var SVG = __webpack_require__(8);
  2109. var constants = __webpack_require__(11);
  2110. var utils = __webpack_require__(7);
  2111. var SVG_NS = constants.svg_ns;
  2112. var templates = {
  2113. 'element': function (options) {
  2114. var tag = options.tag;
  2115. var content = options.content || '';
  2116. delete options.tag;
  2117. delete options.content;
  2118. return [tag, content, options];
  2119. }
  2120. };
  2121. //todo: deprecate tag arg, infer tag from shape object
  2122. function convertShape (shape, tag) {
  2123. return templates.element({
  2124. 'tag': tag,
  2125. 'width': shape.width,
  2126. 'height': shape.height,
  2127. 'fill': shape.properties.fill
  2128. });
  2129. }
  2130. function textCss (properties) {
  2131. return utils.cssProps({
  2132. 'fill': properties.fill,
  2133. 'font-weight': properties.font.weight,
  2134. 'font-family': properties.font.family + ', monospace',
  2135. 'font-size': properties.font.size + properties.font.units
  2136. });
  2137. }
  2138. function outlinePath (bgWidth, bgHeight, outlineWidth) {
  2139. var outlineOffsetWidth = outlineWidth / 2;
  2140. return [
  2141. 'M', outlineOffsetWidth, outlineOffsetWidth,
  2142. 'H', bgWidth - outlineOffsetWidth,
  2143. 'V', bgHeight - outlineOffsetWidth,
  2144. 'H', outlineOffsetWidth,
  2145. 'V', 0,
  2146. 'M', 0, outlineOffsetWidth,
  2147. 'L', bgWidth, bgHeight - outlineOffsetWidth,
  2148. 'M', 0, bgHeight - outlineOffsetWidth,
  2149. 'L', bgWidth, outlineOffsetWidth
  2150. ].join(' ');
  2151. }
  2152. module.exports = function (sceneGraph, renderSettings) {
  2153. var engineSettings = renderSettings.engineSettings;
  2154. var stylesheets = engineSettings.stylesheets;
  2155. var stylesheetXml = stylesheets.map(function (stylesheet) {
  2156. return '<?xml-stylesheet rel="stylesheet" href="' + stylesheet + '"?>';
  2157. }).join('\n');
  2158. var holderId = 'holder_' + Number(new Date()).toString(16);
  2159. var root = sceneGraph.root;
  2160. var textGroup = root.children.holderTextGroup;
  2161. var css = '#' + holderId + ' text { ' + textCss(textGroup.properties) + ' } ';
  2162. // push text down to be equally vertically aligned with canvas renderer
  2163. textGroup.y += textGroup.textPositionData.boundingBox.height * 0.8;
  2164. var wordTags = [];
  2165. Object.keys(textGroup.children).forEach(function (lineKey) {
  2166. var line = textGroup.children[lineKey];
  2167. Object.keys(line.children).forEach(function (wordKey) {
  2168. var word = line.children[wordKey];
  2169. var x = textGroup.x + line.x + word.x;
  2170. var y = textGroup.y + line.y + word.y;
  2171. var wordTag = templates.element({
  2172. 'tag': 'text',
  2173. 'content': word.properties.text,
  2174. 'x': x,
  2175. 'y': y
  2176. });
  2177. wordTags.push(wordTag);
  2178. });
  2179. });
  2180. var text = templates.element({
  2181. 'tag': 'g',
  2182. 'content': wordTags
  2183. });
  2184. var outline = null;
  2185. if (root.children.holderBg.properties.outline) {
  2186. var outlineProperties = root.children.holderBg.properties.outline;
  2187. outline = templates.element({
  2188. 'tag': 'path',
  2189. 'd': outlinePath(root.children.holderBg.width, root.children.holderBg.height, outlineProperties.width),
  2190. 'stroke-width': outlineProperties.width,
  2191. 'stroke': outlineProperties.fill,
  2192. 'fill': 'none'
  2193. });
  2194. }
  2195. var bg = convertShape(root.children.holderBg, 'rect');
  2196. var sceneContent = [];
  2197. sceneContent.push(bg);
  2198. if (outlineProperties) {
  2199. sceneContent.push(outline);
  2200. }
  2201. sceneContent.push(text);
  2202. var scene = templates.element({
  2203. 'tag': 'g',
  2204. 'id': holderId,
  2205. 'content': sceneContent
  2206. });
  2207. var style = templates.element({
  2208. 'tag': 'style',
  2209. //todo: figure out how to add CDATA directive
  2210. 'content': css,
  2211. 'type': 'text/css'
  2212. });
  2213. var defs = templates.element({
  2214. 'tag': 'defs',
  2215. 'content': style
  2216. });
  2217. var svg = templates.element({
  2218. 'tag': 'svg',
  2219. 'content': [defs, scene],
  2220. 'width': root.properties.width,
  2221. 'height': root.properties.height,
  2222. 'xmlns': SVG_NS,
  2223. 'viewBox': [0, 0, root.properties.width, root.properties.height].join(' '),
  2224. 'preserveAspectRatio': 'none'
  2225. });
  2226. var output = shaven(svg);
  2227. output = stylesheetXml + output[0];
  2228. var svgString = SVG.svgStringToDataURI(output, renderSettings.mode === 'background');
  2229. return svgString;
  2230. };
  2231. /***/ },
  2232. /* 13 */
  2233. /***/ function(module, exports, __webpack_require__) {
  2234. var escape = __webpack_require__(14)
  2235. // TODO: remove namespace
  2236. module.exports = function shaven (array, namespace, returnObject) {
  2237. 'use strict'
  2238. var i = 1,
  2239. doesEscape = true,
  2240. HTMLString,
  2241. attributeKey,
  2242. callback,
  2243. key
  2244. returnObject = returnObject || {}
  2245. function createElement (sugarString) {
  2246. var tags = sugarString.match(/^\w+/),
  2247. element = {
  2248. tag: tags ? tags[0] : 'div',
  2249. attr: {},
  2250. children: []
  2251. },
  2252. id = sugarString.match(/#([\w-]+)/),
  2253. reference = sugarString.match(/\$([\w-]+)/),
  2254. classNames = sugarString.match(/\.[\w-]+/g)
  2255. // Assign id if is set
  2256. if (id) {
  2257. element.attr.id = id[1]
  2258. // Add element to the return object
  2259. returnObject[id[1]] = element
  2260. }
  2261. if (reference)
  2262. returnObject[reference[1]] = element
  2263. if (classNames)
  2264. element.attr.class = classNames.join(' ').replace(/\./g, '')
  2265. if (sugarString.match(/&$/g))
  2266. doesEscape = false
  2267. return element
  2268. }
  2269. function replacer (key, value) {
  2270. if (value === null || value === false || value === undefined)
  2271. return
  2272. if (typeof value !== 'string' && typeof value !== 'object')
  2273. return String(value)
  2274. return value
  2275. }
  2276. function escapeAttribute (string) {
  2277. return String(string)
  2278. .replace(/&/g, '&amp;')
  2279. .replace(/"/g, '&quot;')
  2280. }
  2281. function escapeHTML (string) {
  2282. return String(string)
  2283. .replace(/&/g, '&amp;')
  2284. .replace(/"/g, '&quot;')
  2285. .replace(/'/g, '&apos;')
  2286. .replace(/</g, '&lt;')
  2287. .replace(/>/g, '&gt;')
  2288. }
  2289. if (typeof array[0] === 'string')
  2290. array[0] = createElement(array[0])
  2291. else if (Array.isArray(array[0]))
  2292. i = 0
  2293. else
  2294. throw new Error(
  2295. 'First element of array must be a string, ' +
  2296. 'or an array and not ' + JSON.stringify(array[0])
  2297. )
  2298. for (; i < array.length; i++) {
  2299. // Don't render element if value is false or null
  2300. if (array[i] === false || array[i] === null) {
  2301. array[0] = false
  2302. break
  2303. }
  2304. // Continue with next array value if current value is undefined or true
  2305. else if (array[i] === undefined || array[i] === true) {
  2306. continue
  2307. }
  2308. else if (typeof array[i] === 'string') {
  2309. if (doesEscape)
  2310. array[i] = escapeHTML(array[i])
  2311. array[0].children.push(array[i])
  2312. }
  2313. else if (typeof array[i] === 'number') {
  2314. array[0].children.push(array[i])
  2315. }
  2316. else if (Array.isArray(array[i])) {
  2317. if (Array.isArray(array[i][0])) {
  2318. array[i].reverse().forEach(function (subArray) {
  2319. array.splice(i + 1, 0, subArray)
  2320. })
  2321. if (i !== 0)
  2322. continue
  2323. i++
  2324. }
  2325. shaven(array[i], namespace, returnObject)
  2326. if (array[i][0])
  2327. array[0].children.push(array[i][0])
  2328. }
  2329. else if (typeof array[i] === 'function')
  2330. callback = array[i]
  2331. else if (typeof array[i] === 'object') {
  2332. for (attributeKey in array[i])
  2333. if (array[i].hasOwnProperty(attributeKey))
  2334. if (array[i][attributeKey] !== null &&
  2335. array[i][attributeKey] !== false)
  2336. if (attributeKey === 'style' &&
  2337. typeof array[i][attributeKey] === 'object')
  2338. array[0].attr[attributeKey] = JSON
  2339. .stringify(array[i][attributeKey], replacer)
  2340. .slice(2, -2)
  2341. .replace(/","/g, ';')
  2342. .replace(/":"/g, ':')
  2343. .replace(/\\"/g, '\'')
  2344. else
  2345. array[0].attr[attributeKey] = array[i][attributeKey]
  2346. }
  2347. else
  2348. throw new TypeError('"' + array[i] + '" is not allowed as a value.')
  2349. }
  2350. if (array[0] !== false) {
  2351. HTMLString = '<' + array[0].tag
  2352. for (key in array[0].attr)
  2353. if (array[0].attr.hasOwnProperty(key))
  2354. HTMLString += ' ' + key + '="' +
  2355. escapeAttribute(array[0].attr[key] || '') + '"'
  2356. HTMLString += '>'
  2357. array[0].children.forEach(function (child) {
  2358. HTMLString += child
  2359. })
  2360. HTMLString += '</' + array[0].tag + '>'
  2361. array[0] = HTMLString
  2362. }
  2363. // Return root element on index 0
  2364. returnObject[0] = array[0]
  2365. if (callback)
  2366. callback(array[0])
  2367. // returns object containing all elements with an id and the root element
  2368. return returnObject
  2369. }
  2370. /***/ },
  2371. /* 14 */
  2372. /***/ function(module, exports) {
  2373. /*!
  2374. * escape-html
  2375. * Copyright(c) 2012-2013 TJ Holowaychuk
  2376. * MIT Licensed
  2377. */
  2378. /**
  2379. * Module exports.
  2380. * @public
  2381. */
  2382. module.exports = escapeHtml;
  2383. /**
  2384. * Escape special characters in the given string of html.
  2385. *
  2386. * @param {string} str The string to escape for inserting into HTML
  2387. * @return {string}
  2388. * @public
  2389. */
  2390. function escapeHtml(html) {
  2391. return String(html)
  2392. .replace(/&/g, '&amp;')
  2393. .replace(/"/g, '&quot;')
  2394. .replace(/'/g, '&#39;')
  2395. .replace(/</g, '&lt;')
  2396. .replace(/>/g, '&gt;');
  2397. }
  2398. /***/ },
  2399. /* 15 */
  2400. /***/ function(module, exports, __webpack_require__) {
  2401. var DOM = __webpack_require__(9);
  2402. var utils = __webpack_require__(7);
  2403. module.exports = (function() {
  2404. var canvas = DOM.newEl('canvas');
  2405. var ctx = null;
  2406. return function(sceneGraph) {
  2407. if (ctx == null) {
  2408. ctx = canvas.getContext('2d');
  2409. }
  2410. var dpr = utils.canvasRatio();
  2411. var root = sceneGraph.root;
  2412. canvas.width = dpr * root.properties.width;
  2413. canvas.height = dpr * root.properties.height ;
  2414. ctx.textBaseline = 'middle';
  2415. var bg = root.children.holderBg;
  2416. var bgWidth = dpr * bg.width;
  2417. var bgHeight = dpr * bg.height;
  2418. //todo: parametrize outline width (e.g. in scene object)
  2419. var outlineWidth = 2;
  2420. var outlineOffsetWidth = outlineWidth / 2;
  2421. ctx.fillStyle = bg.properties.fill;
  2422. ctx.fillRect(0, 0, bgWidth, bgHeight);
  2423. if (bg.properties.outline) {
  2424. //todo: abstract this into a method
  2425. ctx.strokeStyle = bg.properties.outline.fill;
  2426. ctx.lineWidth = bg.properties.outline.width;
  2427. ctx.moveTo(outlineOffsetWidth, outlineOffsetWidth);
  2428. // TL, TR, BR, BL
  2429. ctx.lineTo(bgWidth - outlineOffsetWidth, outlineOffsetWidth);
  2430. ctx.lineTo(bgWidth - outlineOffsetWidth, bgHeight - outlineOffsetWidth);
  2431. ctx.lineTo(outlineOffsetWidth, bgHeight - outlineOffsetWidth);
  2432. ctx.lineTo(outlineOffsetWidth, outlineOffsetWidth);
  2433. // Diagonals
  2434. ctx.moveTo(0, outlineOffsetWidth);
  2435. ctx.lineTo(bgWidth, bgHeight - outlineOffsetWidth);
  2436. ctx.moveTo(0, bgHeight - outlineOffsetWidth);
  2437. ctx.lineTo(bgWidth, outlineOffsetWidth);
  2438. ctx.stroke();
  2439. }
  2440. var textGroup = root.children.holderTextGroup;
  2441. ctx.font = textGroup.properties.font.weight + ' ' + (dpr * textGroup.properties.font.size) + textGroup.properties.font.units + ' ' + textGroup.properties.font.family + ', monospace';
  2442. ctx.fillStyle = textGroup.properties.fill;
  2443. for (var lineKey in textGroup.children) {
  2444. var line = textGroup.children[lineKey];
  2445. for (var wordKey in line.children) {
  2446. var word = line.children[wordKey];
  2447. var x = dpr * (textGroup.x + line.x + word.x);
  2448. var y = dpr * (textGroup.y + line.y + word.y + (textGroup.properties.leading / 2));
  2449. ctx.fillText(word.properties.text, x, y);
  2450. }
  2451. }
  2452. return canvas.toDataURL('image/png');
  2453. };
  2454. })();
  2455. /***/ }
  2456. /******/ ])
  2457. });
  2458. ;
  2459. (function(ctx, isMeteorPackage) {
  2460. if (isMeteorPackage) {
  2461. Holder = ctx.Holder;
  2462. }
  2463. })(this, typeof Meteor !== 'undefined' && typeof Package !== 'undefined');