/*! holder - client side image placeholders version 2.9.6+fblyy © 2018 ivan malopinsky - http://imsky.co site: http://holderjs.com issues: https://github.com/imsky/holder/issues license: mit 演示: 占位图片 不报错(后续需更改); 占位图片 会报错 */ (function (window) { if (!window.document) return; var document = window.document; //https://github.com/inexorabletash/polyfill/blob/master/web.js if (!document.queryselectorall) { document.queryselectorall = function (selectors) { var style = document.createelement('style'), elements = [], element; document.documentelement.firstchild.appendchild(style); document._qsa = []; style.stylesheet.csstext = selectors + '{x-qsa:expression(document._qsa && document._qsa.push(this))}'; window.scrollby(0, 0); style.parentnode.removechild(style); while (document._qsa.length) { element = document._qsa.shift(); element.style.removeattribute('x-qsa'); elements.push(element); } document._qsa = null; return elements; }; } if (!document.queryselector) { document.queryselector = function (selectors) { var elements = document.queryselectorall(selectors); return (elements.length) ? elements[0] : null; }; } if (!document.getelementsbyclassname) { document.getelementsbyclassname = function (classnames) { classnames = string(classnames).replace(/^|\s+/g, '.'); return document.queryselectorall(classnames); }; } //https://github.com/inexorabletash/polyfill // es5 15.2.3.14 object.keys ( o ) // https://developer.mozilla.org/en/javascript/reference/global_objects/object/keys if (!object.keys) { object.keys = function (o) { if (o !== object(o)) { throw typeerror('object.keys called on non-object'); } var ret = [], p; for (p in o) { if (object.prototype.hasownproperty.call(o, p)) { ret.push(p); } } return ret; }; } // es5 15.4.4.18 array.prototype.foreach ( callbackfn [ , thisarg ] ) // from https://developer.mozilla.org/en/javascript/reference/global_objects/array/foreach if (!array.prototype.foreach) { array.prototype.foreach = function (fun /*, thisp */) { if (this === void 0 || this === null) { throw typeerror(); } var t = object(this); var len = t.length >>> 0; if (typeof fun !== "function") { throw typeerror(); } var thisp = arguments[1], i; for (i = 0; i < len; i++) { if (i in t) { fun.call(thisp, t[i], i, t); } } }; } //https://github.com/inexorabletash/polyfill/blob/master/web.js (function (global) { var b64_alphabet = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789+/='; global.atob = global.atob || function (input) { input = string(input); var position = 0, output = [], buffer = 0, bits = 0, n; input = input.replace(/\s/g, ''); if ((input.length % 4) === 0) { input = input.replace(/=+$/, ''); } if ((input.length % 4) === 1) { throw error('invalidcharactererror'); } if (/[^+/0-9a-za-z]/.test(input)) { throw error('invalidcharactererror'); } while (position < input.length) { n = b64_alphabet.indexof(input.charat(position)); buffer = (buffer << 6) | n; bits += 6; if (bits === 24) { output.push(string.fromcharcode((buffer >> 16) & 0xff)); output.push(string.fromcharcode((buffer >> 8) & 0xff)); output.push(string.fromcharcode(buffer & 0xff)); bits = 0; buffer = 0; } position += 1; } if (bits === 12) { buffer = buffer >> 4; output.push(string.fromcharcode(buffer & 0xff)); } else if (bits === 18) { buffer = buffer >> 2; output.push(string.fromcharcode((buffer >> 8) & 0xff)); output.push(string.fromcharcode(buffer & 0xff)); } return output.join(''); }; global.btoa = global.btoa || function (input) { input = string(input); var position = 0, out = [], o1, o2, o3, e1, e2, e3, e4; if (/[^\x00-\xff]/.test(input)) { throw error('invalidcharactererror'); } while (position < input.length) { o1 = input.charcodeat(position++); o2 = input.charcodeat(position++); o3 = input.charcodeat(position++); // 111111 112222 222233 333333 e1 = o1 >> 2; e2 = ((o1 & 0x3) << 4) | (o2 >> 4); e3 = ((o2 & 0xf) << 2) | (o3 >> 6); e4 = o3 & 0x3f; if (position === input.length + 2) { e3 = 64; e4 = 64; } else if (position === input.length + 1) { e4 = 64; } out.push(b64_alphabet.charat(e1), b64_alphabet.charat(e2), b64_alphabet.charat(e3), b64_alphabet.charat(e4)); } return out.join(''); }; }(window)); //https://gist.github.com/jimeh/332357 if (!object.prototype.hasownproperty){ /*jshint -w001, -w103 */ object.prototype.hasownproperty = function(prop) { var proto = this.__proto__ || this.constructor.prototype; return (prop in this) && (!(prop in proto) || proto[prop] !== this[prop]); }; /*jshint +w001, +w103 */ } // @license http://opensource.org/licenses/mit // copyright paul irish 2015 // date.now() is supported everywhere except ie8. for ie8 we use the date.now polyfill // github.com/financial-times/polyfill-service/blob/master/polyfills/date.now/polyfill.js // as safari 6 doesn't have support for navigationtiming, we use a date.now() timestamp for relative values // if you want values similar to what you'd get with real perf.now, place this towards the head of the page // but in reality, you're just getting the delta between now() calls, so it's not terribly important where it's placed (function(){ if ('performance' in window === false) { window.performance = {}; } date.now = (date.now || function () { // thanks ie8 return new date().gettime(); }); if ('now' in window.performance === false){ var nowoffset = date.now(); if (performance.timing && performance.timing.navigationstart){ nowoffset = performance.timing.navigationstart; } window.performance.now = function now(){ return date.now() - nowoffset; }; } })(); //requestanimationframe polyfill for older firefox/chrome versions if (!window.requestanimationframe) { if (window.webkitrequestanimationframe && window.webkitcancelanimationframe) { //https://github.com/financial-times/polyfill-service/blob/master/polyfills/requestanimationframe/polyfill-webkit.js (function (global) { global.requestanimationframe = function (callback) { return webkitrequestanimationframe(function () { callback(global.performance.now()); }); }; global.cancelanimationframe = global.webkitcancelanimationframe; }(window)); } else if (window.mozrequestanimationframe && window.mozcancelanimationframe) { //https://github.com/financial-times/polyfill-service/blob/master/polyfills/requestanimationframe/polyfill-moz.js (function (global) { global.requestanimationframe = function (callback) { return mozrequestanimationframe(function () { callback(global.performance.now()); }); }; global.cancelanimationframe = global.mozcancelanimationframe; }(window)); } else { (function (global) { global.requestanimationframe = function (callback) { return global.settimeout(callback, 1000 / 60); }; global.cancelanimationframe = global.cleartimeout; })(window); } } })(this); (function webpackuniversalmoduledefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["holder"] = factory(); else root["holder"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackbootstrap /******/ // the module cache /******/ var installedmodules = {}; /******/ // the require function /******/ function __webpack_require__(moduleid) { /******/ // check if module is in cache /******/ if(installedmodules[moduleid]) /******/ return installedmodules[moduleid].exports; /******/ // create a new module (and put it into the cache) /******/ var module = installedmodules[moduleid] = { /******/ exports: {}, /******/ id: moduleid, /******/ loaded: false /******/ }; /******/ // execute the module function /******/ modules[moduleid].call(module.exports, module, module.exports, __webpack_require__); /******/ // flag the module as loaded /******/ module.loaded = true; /******/ // return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedmodules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { /* holder.js - client side image placeholders (c) 2012-2015 ivan malopinsky - http://imsky.co */ module.exports = __webpack_require__(1); /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { /* webpack var injection */(function(global) {/* holder.js - client side image placeholders (c) 2012-2016 ivan malopinsky - http://imsky.co */ //libraries and functions var ondomready = __webpack_require__(2); var querystring = __webpack_require__(3); var scenegraph = __webpack_require__(6); var utils = __webpack_require__(7); var svg = __webpack_require__(8); var dom = __webpack_require__(9); var color = __webpack_require__(10); var constants = __webpack_require__(11); var svgrenderer = __webpack_require__(12); var sgcanvasrenderer = __webpack_require__(15); var extend = utils.extend; var dimensioncheck = utils.dimensioncheck; //constants and definitions var svg_ns = constants.svg_ns; var holder = { version: constants.version, /** * adds a theme to default settings * * @param {string} name theme name * @param {object} theme theme object, with foreground, background, size, font, and fontweight properties. */ addtheme: function(name, theme) { name != null && theme != null && (app.settings.themes[name] = theme); delete app.vars.cache.themekeys; return this; }, /** * appends a placeholder to an element * * @param {string} src placeholder url string * @param el a selector or a reference to a dom node */ addimage: function(src, el) { //todo: use jquery fallback if available for all qsa references var nodes = dom.getnodearray(el); nodes.foreach(function (node) { var img = dom.newel('img'); var domprops = {}; domprops[app.setup.dataattr] = src; dom.setattr(img, domprops); node.appendchild(img); }); return this; }, /** * sets whether or not an image is updated on resize. * if an image is set to be updated, it is immediately rendered. * * @param {object} el image dom element * @param {boolean} value resizable update flag value */ setresizeupdate: function(el, value) { if (el.holderdata) { el.holderdata.resizeupdate = !!value; if (el.holderdata.resizeupdate) { updateresizableelements(el); } } }, /** * runs holder with options. by default runs holder on all images with "holder.js" in their source attributes. * * @param {object} useroptions options object, can contain domain, themes, images, and bgnodes properties */ run: function(useroptions) { //todo: split processing into separate queues useroptions = useroptions || {}; var enginesettings = {}; var options = extend(app.settings, useroptions); app.vars.preempted = true; app.vars.dataattr = options.dataattr || app.setup.dataattr; enginesettings.renderer = options.renderer ? options.renderer : app.setup.renderer; if (app.setup.renderers.join(',').indexof(enginesettings.renderer) === -1) { enginesettings.renderer = app.setup.supportssvg ? 'svg' : (app.setup.supportscanvas ? 'canvas' : 'html'); } var images = dom.getnodearray(options.images); var bgnodes = dom.getnodearray(options.bgnodes); var stylenodes = dom.getnodearray(options.stylenodes); var objects = dom.getnodearray(options.objects); enginesettings.stylesheets = []; enginesettings.svgxmlstylesheet = true; enginesettings.nofontfallback = !!options.nofontfallback; enginesettings.nobackgroundsize = !!options.nobackgroundsize; stylenodes.foreach(function (stylenode) { if (stylenode.attributes.rel && stylenode.attributes.href && stylenode.attributes.rel.value == 'stylesheet') { var href = stylenode.attributes.href.value; //todo: write isomorphic relative-to-absolute url function var proxylink = dom.newel('a'); proxylink.href = href; var stylesheeturl = proxylink.protocol + '//' + proxylink.host + proxylink.pathname + proxylink.search; enginesettings.stylesheets.push(stylesheeturl); } }); bgnodes.foreach(function (bgnode) { //skip processing background nodes if getcomputedstyle is unavailable, since only modern browsers would be able to use canvas or svg to render to background if (!global.getcomputedstyle) return; var backgroundimage = global.getcomputedstyle(bgnode, null).getpropertyvalue('background-image'); var databackgroundimage = bgnode.getattribute('data-background-src'); var rawurl = databackgroundimage || backgroundimage; var holderurl = null; var holderstring = options.domain + '/'; var holderstringindex = rawurl.indexof(holderstring); if (holderstringindex === 0) { holderurl = rawurl; } else if (holderstringindex === 1 && rawurl[0] === '?') { holderurl = rawurl.slice(1); } else { var fragment = rawurl.substr(holderstringindex).match(/([^\"]*)"?\)/); if (fragment !== null) { holderurl = fragment[1]; } else if (rawurl.indexof('url(') === 0) { throw 'holder: unable to parse background url: ' + rawurl; } } if (holderurl) { var holderflags = parseurl(holderurl, options); if (holderflags) { preparedomelement({ mode: 'background', el: bgnode, flags: holderflags, enginesettings: enginesettings }); } } }); objects.foreach(function (object) { var objectattr = {}; try { objectattr.data = object.getattribute('data'); objectattr.datasrc = object.getattribute(app.vars.dataattr); } catch (e) {} var objecthassrcurl = objectattr.data != null && objectattr.data.indexof(options.domain) === 0; var objecthasdatasrcurl = objectattr.datasrc != null && objectattr.datasrc.indexof(options.domain) === 0; if (objecthassrcurl) { prepareimageelement(options, enginesettings, objectattr.data, object); } else if (objecthasdatasrcurl) { prepareimageelement(options, enginesettings, objectattr.datasrc, object); } }); images.foreach(function (image) { var imageattr = {}; try { imageattr.src = image.getattribute('src'); imageattr.datasrc = image.getattribute(app.vars.dataattr); imageattr.rendered = image.getattribute('data-holder-rendered'); } catch (e) {} var imagehassrc = imageattr.src != null; var imagehasdatasrcurl = imageattr.datasrc != null && imageattr.datasrc.indexof(options.domain) === 0; var imagerendered = imageattr.rendered != null && imageattr.rendered == 'true'; if (imagehassrc) { if (imageattr.src.indexof(options.domain) === 0) { prepareimageelement(options, enginesettings, imageattr.src, image); } else if (imagehasdatasrcurl) { //image has a valid data-src and an invalid src if (imagerendered) { //if the placeholder has already been render, re-render it prepareimageelement(options, enginesettings, imageattr.datasrc, image); } else { //if the placeholder has not been rendered, check if the image exists and render a fallback if it doesn't (function(src, options, enginesettings, datasrc, image) { utils.imageexists(src, function(exists) { if (!exists) { prepareimageelement(options, enginesettings, datasrc, image); } }); })(imageattr.src, options, enginesettings, imageattr.datasrc, image); } } } else if (imagehasdatasrcurl) { prepareimageelement(options, enginesettings, imageattr.datasrc, image); } }); return this; } }; var app = { settings: { domain: 'holder.js', images: 'img', objects: 'object', bgnodes: 'body .holderjs', stylenodes: 'head link.holderjs', themes: { 'gray': { bg: '#eeeeee', fg: '#aaaaaa' }, 'social': { bg: '#3a5a97', fg: '#ffffff' }, 'industrial': { bg: '#434a52', fg: '#c2f200' }, 'sky': { bg: '#0d8fdb', fg: '#ffffff' }, 'vine': { bg: '#39dbac', fg: '#1e292c' }, 'lava': { bg: '#f8591a', fg: '#1c2846' } } }, defaults: { size: 10, units: 'pt', scale: 1 / 16 } }; /** * processes provided source attribute and sets up the appropriate rendering workflow * * @private * @param options instance options from holder.run * @param rendersettings instance configuration * @param src image url * @param el image dom element */ function prepareimageelement(options, enginesettings, src, el) { var holderflags = parseurl(src.substr(src.lastindexof(options.domain)), options); if (holderflags) { preparedomelement({ mode: null, el: el, flags: holderflags, enginesettings: enginesettings }); } } /** * processes a holder url and extracts configuration from query string * * @private * @param url url * @param instanceoptions instance options from holder.run */ function parseurl(url, instanceoptions) { var holder = { theme: extend(app.settings.themes.gray, null), stylesheets: instanceoptions.stylesheets, instanceoptions: instanceoptions }; var firstquestionmark = url.indexof('?'); var parts = [url]; if (firstquestionmark !== -1) { parts = [url.slice(0, firstquestionmark), url.slice(firstquestionmark + 1)]; } var basics = parts[0].split('/'); holder.holderurl = url; var dimensions = basics[1]; var dimensiondata = dimensions.match(/([\d]+p?)x([\d]+p?)/); if (!dimensiondata) return false; holder.fluid = dimensions.indexof('p') !== -1; holder.dimensions = { width: dimensiondata[1].replace('p', '%'), height: dimensiondata[2].replace('p', '%') }; if (parts.length === 2) { var options = querystring.parse(parts[1]); // dimensions if (utils.truthy(options.ratio)) { holder.fluid = true; var ratiowidth = parsefloat(holder.dimensions.width.replace('%', '')); var ratioheight = parsefloat(holder.dimensions.height.replace('%', '')); ratioheight = math.floor(100 * (ratioheight / ratiowidth)); ratiowidth = 100; holder.dimensions.width = ratiowidth + '%'; holder.dimensions.height = ratioheight + '%'; } holder.auto = utils.truthy(options.auto); // colors if (options.bg) { holder.theme.bg = utils.parsecolor(options.bg); } if (options.fg) { holder.theme.fg = utils.parsecolor(options.fg); } //todo: add automatic foreground to themes without foreground if (options.bg && !options.fg) { holder.autofg = true; } if (options.theme && holder.instanceoptions.themes.hasownproperty(options.theme)) { holder.theme = extend(holder.instanceoptions.themes[options.theme], null); } // text if (options.text) { holder.text = options.text; } if (options.textmode) { holder.textmode = options.textmode; } if (options.size && parsefloat(options.size)) { holder.size = parsefloat(options.size); } if (options.font) { holder.font = options.font; } if (options.align) { holder.align = options.align; } if (options.linewrap) { holder.linewrap = options.linewrap; } holder.nowrap = utils.truthy(options.nowrap); // miscellaneous holder.outline = utils.truthy(options.outline); if (utils.truthy(options.random)) { app.vars.cache.themekeys = app.vars.cache.themekeys || object.keys(holder.instanceoptions.themes); var _theme = app.vars.cache.themekeys[0 | math.random() * app.vars.cache.themekeys.length]; holder.theme = extend(holder.instanceoptions.themes[_theme], null); } } return holder; } /** * modifies the dom to fit placeholders and sets up resizable image callbacks (for fluid and automatically sized placeholders) * * @private * @param settings dom prep settings */ function preparedomelement(prepsettings) { var mode = prepsettings.mode; var el = prepsettings.el; var flags = prepsettings.flags; var _enginesettings = prepsettings.enginesettings; var dimensions = flags.dimensions, theme = flags.theme; var dimensionscaption = dimensions.width + 'x' + dimensions.height; mode = mode == null ? (flags.fluid ? 'fluid' : 'image') : mode; var holdertemplatere = /holder_([a-z]+)/g; var dimensionsintext = false; if (flags.text != null) { theme.text = flags.text; // svg embedding doesn't parse unicode properly if (el.nodename.tolowercase() === 'object') { var textlines = theme.text.split('\\n'); for (var k = 0; k < textlines.length; k++) { textlines[k] = utils.encodehtmlentity(textlines[k]); } theme.text = textlines.join('\\n'); } } if (theme.text) { var holdertemplatematches = theme.text.match(holdertemplatere); if (holdertemplatematches !== null) { //todo: optimize template replacement holdertemplatematches.foreach(function (match) { if (match === 'holder_dimensions') { theme.text = theme.text.replace(match, dimensionscaption); } }); } } var holderurl = flags.holderurl; var enginesettings = extend(_enginesettings, null); if (flags.font) { /* if external fonts are used in a placeholder rendered with svg, holder falls back to canvas. this is done because firefox and chrome disallow embedded svgs from referencing external assets. the workaround is either to change the placeholder tag from to or to use the canvas renderer. */ theme.font = flags.font; if (!enginesettings.nofontfallback && el.nodename.tolowercase() === 'img' && app.setup.supportscanvas && enginesettings.renderer === 'svg') { enginesettings = extend(enginesettings, { renderer: 'canvas' }); } } //chrome and opera require a quick 10ms re-render if web fonts are used with canvas if (flags.font && enginesettings.renderer == 'canvas') { enginesettings.rerender = true; } if (mode == 'background') { if (el.getattribute('data-background-src') == null) { dom.setattr(el, { 'data-background-src': holderurl }); } } else { var domprops = {}; domprops[app.vars.dataattr] = holderurl; dom.setattr(el, domprops); } flags.theme = theme; //todo consider using all rendersettings in holderdata el.holderdata = { flags: flags, enginesettings: enginesettings }; if (mode == 'image' || mode == 'fluid') { dom.setattr(el, { 'alt': theme.text ? (dimensionsintext ? theme.text : theme.text + ' [' + dimensionscaption + ']') : dimensionscaption }); } var rendersettings = { mode: mode, el: el, holdersettings: { dimensions: dimensions, theme: theme, flags: flags }, enginesettings: enginesettings }; if (mode == 'image') { if (!flags.auto) { el.style.width = dimensions.width + 'px'; el.style.height = dimensions.height + 'px'; } if (enginesettings.renderer == 'html') { el.style.backgroundcolor = theme.bg; } else { render(rendersettings); if (flags.textmode == 'exact') { el.holderdata.resizeupdate = true; app.vars.resizableimages.push(el); updateresizableelements(el); } } } else if (mode == 'background' && enginesettings.renderer != 'html') { render(rendersettings); } else if (mode == 'fluid') { el.holderdata.resizeupdate = true; if (dimensions.height.slice(-1) == '%') { el.style.height = dimensions.height; } else if (flags.auto == null || !flags.auto) { el.style.height = dimensions.height + 'px'; } if (dimensions.width.slice(-1) == '%') { el.style.width = dimensions.width; } else if (flags.auto == null || !flags.auto) { el.style.width = dimensions.width + 'px'; } if (el.style.display == 'inline' || el.style.display === '' || el.style.display == 'none') { el.style.display = 'block'; } setinitialdimensions(el); if (enginesettings.renderer == 'html') { el.style.backgroundcolor = theme.bg; } else { app.vars.resizableimages.push(el); updateresizableelements(el); } } } /** * core function that takes output from renderers and sets it as the source or background-image of the target element * * @private * @param rendersettings renderer settings */ function render(rendersettings) { var image = null; var mode = rendersettings.mode; var el = rendersettings.el; var holdersettings = rendersettings.holdersettings; var enginesettings = rendersettings.enginesettings; switch (enginesettings.renderer) { case 'svg': if (!app.setup.supportssvg) return; break; case 'canvas': if (!app.setup.supportscanvas) return; break; default: return; } //todo: move generation of scene up to flag generation to reduce extra object creation var scene = { width: holdersettings.dimensions.width, height: holdersettings.dimensions.height, theme: holdersettings.theme, flags: holdersettings.flags }; var scenegraph = buildscenegraph(scene); function getrenderedimage() { var image = null; switch (enginesettings.renderer) { case 'canvas': image = sgcanvasrenderer(scenegraph, rendersettings); break; case 'svg': image = svgrenderer(scenegraph, rendersettings); break; default: throw 'holder: invalid renderer: ' + enginesettings.renderer; } return image; } image = getrenderedimage(); if (image == null) { throw 'holder: couldn\'t render placeholder'; } //todo: add canvas rendering if (mode == 'background') { el.style.backgroundimage = 'url(' + image + ')'; if (!enginesettings.nobackgroundsize) { el.style.backgroundsize = scene.width + 'px ' + scene.height + 'px'; } } else { if (el.nodename.tolowercase() === 'img') { dom.setattr(el, { 'src': image }); } else if (el.nodename.tolowercase() === 'object') { dom.setattr(el, { 'data': image, 'type': 'image/svg+xml' }); } if (enginesettings.rerender) { global.settimeout(function () { var image = getrenderedimage(); if (image == null) { throw 'holder: couldn\'t render placeholder'; } //todo: refactor this code into a function if (el.nodename.tolowercase() === 'img') { dom.setattr(el, { 'src': image }); } else if (el.nodename.tolowercase() === 'object') { dom.setattr(el, { 'data': image, 'type': 'image/svg+xml' }); } }, 150); } } //todo: account for re-rendering dom.setattr(el, { 'data-holder-rendered': true }); } /** * core function that takes a holder scene description and builds a scene graph * * @private * @param scene holder scene object */ //todo: make this function reusable //todo: merge app defaults and setup properties into the scene argument function buildscenegraph(scene) { var fontsize = app.defaults.size; if (parsefloat(scene.theme.size)) { fontsize = scene.theme.size; } else if (parsefloat(scene.flags.size)) { fontsize = scene.flags.size; } scene.font = { family: scene.theme.font ? scene.theme.font : 'arial, helvetica, open sans, sans-serif', size: textsize(scene.width, scene.height, fontsize, app.defaults.scale), units: scene.theme.units ? scene.theme.units : app.defaults.units, weight: scene.theme.fontweight ? scene.theme.fontweight : 'bold' }; scene.text = scene.theme.text || math.floor(scene.width) + 'x' + math.floor(scene.height); scene.nowrap = scene.theme.nowrap || scene.flags.nowrap; scene.align = scene.theme.align || scene.flags.align || 'center'; switch (scene.flags.textmode) { case 'literal': scene.text = scene.flags.dimensions.width + 'x' + scene.flags.dimensions.height; break; case 'exact': if (!scene.flags.exactdimensions) break; scene.text = math.floor(scene.flags.exactdimensions.width) + 'x' + math.floor(scene.flags.exactdimensions.height); break; } var linewrap = scene.flags.linewrap || app.setup.linewrapratio; var scenemargin = scene.width * linewrap; var maxlinewidth = scenemargin; var scenegraph = new scenegraph({ width: scene.width, height: scene.height }); var shape = scenegraph.shape; var holderbg = new shape.rect('holderbg', { fill: scene.theme.bg }); holderbg.resize(scene.width, scene.height); scenegraph.root.add(holderbg); if (scene.flags.outline) { var outlinecolor = new color(holderbg.properties.fill); outlinecolor = outlinecolor.lighten(outlinecolor.lighterthan('7f7f7f') ? -0.1 : 0.1); holderbg.properties.outline = { fill: outlinecolor.tohex(true), width: 2 }; } var holdertextcolor = scene.theme.fg; if (scene.flags.autofg) { var holderbgcolor = new color(holderbg.properties.fill); var lightcolor = new color('fff'); var darkcolor = new color('000', { 'alpha': 0.285714 }); holdertextcolor = holderbgcolor.blendalpha(holderbgcolor.lighterthan('7f7f7f') ? darkcolor : lightcolor).tohex(true); } var holdertextgroup = new shape.group('holdertextgroup', { text: scene.text, align: scene.align, font: scene.font, fill: holdertextcolor }); holdertextgroup.moveto(null, null, 1); scenegraph.root.add(holdertextgroup); var tpdata = holdertextgroup.textpositiondata = stagingrenderer(scenegraph); if (!tpdata) { throw 'holder: staging fallback not supported yet.'; } holdertextgroup.properties.leading = tpdata.boundingbox.height; var textnode = null; var line = null; function finalizeline(parent, line, width, height) { line.width = width; line.height = height; parent.width = math.max(parent.width, line.width); parent.height += line.height; } if (tpdata.linecount > 1) { var offsetx = 0; var offsety = 0; var lineindex = 0; var linekey; line = new shape.group('line' + lineindex); //double margin so that left/right-aligned next is not flush with edge of image if (scene.align === 'left' || scene.align === 'right') { maxlinewidth = scene.width * (1 - (1 - linewrap) * 2); } for (var i = 0; i < tpdata.words.length; i++) { var word = tpdata.words[i]; textnode = new shape.text(word.text); var newline = word.text == '\\n'; if (!scene.nowrap && (offsetx + word.width >= maxlinewidth || newline === true)) { finalizeline(holdertextgroup, line, offsetx, holdertextgroup.properties.leading); holdertextgroup.add(line); offsetx = 0; offsety += holdertextgroup.properties.leading; lineindex += 1; line = new shape.group('line' + lineindex); line.y = offsety; } if (newline === true) { continue; } textnode.moveto(offsetx, 0); offsetx += tpdata.spacewidth + word.width; line.add(textnode); } finalizeline(holdertextgroup, line, offsetx, holdertextgroup.properties.leading); holdertextgroup.add(line); if (scene.align === 'left') { holdertextgroup.moveto(scene.width - scenemargin, null, null); } else if (scene.align === 'right') { for (linekey in holdertextgroup.children) { line = holdertextgroup.children[linekey]; line.moveto(scene.width - line.width, null, null); } holdertextgroup.moveto(0 - (scene.width - scenemargin), null, null); } else { for (linekey in holdertextgroup.children) { line = holdertextgroup.children[linekey]; line.moveto((holdertextgroup.width - line.width) / 2, null, null); } holdertextgroup.moveto((scene.width - holdertextgroup.width) / 2, null, null); } holdertextgroup.moveto(null, (scene.height - holdertextgroup.height) / 2, null); //if the text exceeds vertical space, move it down so the first line is visible if ((scene.height - holdertextgroup.height) / 2 < 0) { holdertextgroup.moveto(null, 0, null); } } else { textnode = new shape.text(scene.text); line = new shape.group('line0'); line.add(textnode); holdertextgroup.add(line); if (scene.align === 'left') { holdertextgroup.moveto(scene.width - scenemargin, null, null); } else if (scene.align === 'right') { holdertextgroup.moveto(0 - (scene.width - scenemargin), null, null); } else { holdertextgroup.moveto((scene.width - tpdata.boundingbox.width) / 2, null, null); } holdertextgroup.moveto(null, (scene.height - tpdata.boundingbox.height) / 2, null); } //todo: renderlist return scenegraph; } /** * adaptive text sizing function * * @private * @param width parent width * @param height parent height * @param fontsize requested text size * @param scale proportional scale of text */ function textsize(width, height, fontsize, scale) { var stagewidth = parseint(width, 10); var stageheight = parseint(height, 10); var bigside = math.max(stagewidth, stageheight); var smallside = math.min(stagewidth, stageheight); var newheight = 0.8 * math.min(smallside, bigside * scale); return math.round(math.max(fontsize, newheight)); } /** * iterates over resizable (fluid or auto) placeholders and renders them * * @private * @param element optional element selector, specified only if a specific element needs to be re-rendered */ function updateresizableelements(element) { var images; if (element == null || element.nodetype == null) { images = app.vars.resizableimages; } else { images = [element]; } for (var i = 0, l = images.length; i < l; i++) { var el = images[i]; if (el.holderdata) { var flags = el.holderdata.flags; var dimensions = dimensioncheck(el); if (dimensions) { if (!el.holderdata.resizeupdate) { continue; } if (flags.fluid && flags.auto) { var fluidconfig = el.holderdata.fluidconfig; switch (fluidconfig.mode) { case 'width': dimensions.height = dimensions.width / fluidconfig.ratio; break; case 'height': dimensions.width = dimensions.height * fluidconfig.ratio; break; } } var settings = { mode: 'image', holdersettings: { dimensions: dimensions, theme: flags.theme, flags: flags }, el: el, enginesettings: el.holderdata.enginesettings }; if (flags.textmode == 'exact') { flags.exactdimensions = dimensions; settings.holdersettings.dimensions = flags.dimensions; } render(settings); } else { setinvisible(el); } } } } /** * sets up aspect ratio metadata for fluid placeholders, in order to preserve proportions when resizing * * @private * @param el image dom element */ function setinitialdimensions(el) { if (el.holderdata) { var dimensions = dimensioncheck(el); if (dimensions) { var flags = el.holderdata.flags; var fluidconfig = { fluidheight: flags.dimensions.height.slice(-1) == '%', fluidwidth: flags.dimensions.width.slice(-1) == '%', mode: null, initialdimensions: dimensions }; if (fluidconfig.fluidwidth && !fluidconfig.fluidheight) { fluidconfig.mode = 'width'; fluidconfig.ratio = fluidconfig.initialdimensions.width / parsefloat(flags.dimensions.height); } else if (!fluidconfig.fluidwidth && fluidconfig.fluidheight) { fluidconfig.mode = 'height'; fluidconfig.ratio = parsefloat(flags.dimensions.width) / fluidconfig.initialdimensions.height; } el.holderdata.fluidconfig = fluidconfig; } else { setinvisible(el); } } } /** * iterates through all current invisible images, and if they're visible, renders them and removes them from further checks. runs every animation frame. * * @private */ function visibilitycheck() { var renderableimages = []; var keys = object.keys(app.vars.invisibleimages); var el; keys.foreach(function (key) { el = app.vars.invisibleimages[key]; if (dimensioncheck(el) && el.nodename.tolowercase() == 'img') { renderableimages.push(el); delete app.vars.invisibleimages[key]; } }); if (renderableimages.length) { holder.run({ images: renderableimages }); } // done to prevent 100% cpu usage via aggressive calling of requestanimationframe settimeout(function () { global.requestanimationframe(visibilitycheck); }, 10); } /** * starts checking for invisible placeholders if not doing so yet. does nothing otherwise. * * @private */ function startvisibilitycheck() { if (!app.vars.visibilitycheckstarted) { global.requestanimationframe(visibilitycheck); app.vars.visibilitycheckstarted = true; } } /** * sets a unique id for an image detected to be invisible and adds it to the map of invisible images checked by visibilitycheck * * @private * @param el invisible dom element */ function setinvisible(el) { if (!el.holderdata.invisibleid) { app.vars.invisibleid += 1; app.vars.invisibleimages['i' + app.vars.invisibleid] = el; el.holderdata.invisibleid = app.vars.invisibleid; } } //todo: see if possible to convert stagingrenderer to use html only var stagingrenderer = (function() { var svg = null, stagingtext = null, stagingtextnode = null; return function(graph) { var rootnode = graph.root; if (app.setup.supportssvg) { var firsttimesetup = false; var tnode = function(text) { return document.createtextnode(text); }; if (svg == null || svg.parentnode !== document.body) { firsttimesetup = true; } svg = svg.initsvg(svg, rootnode.properties.width, rootnode.properties.height); //show staging element before staging svg.style.display = 'block'; if (firsttimesetup) { stagingtext = dom.newel('text', svg_ns); stagingtextnode = tnode(null); dom.setattr(stagingtext, { x: 0 }); stagingtext.appendchild(stagingtextnode); svg.appendchild(stagingtext); document.body.appendchild(svg); svg.style.visibility = 'hidden'; svg.style.position = 'absolute'; svg.style.top = '-100%'; svg.style.left = '-100%'; //todo: workaround for zero-dimension tag in opera 12 //svg.setattribute('width', 0); //svg.setattribute('height', 0); } var holdertextgroup = rootnode.children.holdertextgroup; var htgprops = holdertextgroup.properties; dom.setattr(stagingtext, { 'y': htgprops.font.size, 'style': utils.cssprops({ 'font-weight': htgprops.font.weight, 'font-size': htgprops.font.size + htgprops.font.units, 'font-family': htgprops.font.family }) }); //unescape html entities to get approximately the right width var txt = dom.newel('textarea'); txt.innerhtml = htgprops.text; stagingtextnode.nodevalue = txt.value; //get bounding box for the whole string (total width and height) var stagingtextbbox = stagingtext.getbbox(); //get line count and split the string into words var linecount = math.ceil(stagingtextbbox.width / rootnode.properties.width); var words = htgprops.text.split(' '); var newlines = htgprops.text.match(/\\n/g); linecount += newlines == null ? 0 : newlines.length; //get bounding box for the string with spaces removed stagingtextnode.nodevalue = htgprops.text.replace(/[ ]+/g, ''); var computednospacelength = stagingtext.getcomputedtextlength(); //compute average space width var difflength = stagingtextbbox.width - computednospacelength; var spacewidth = math.round(difflength / math.max(1, words.length - 1)); //get widths for every word with space only if there is more than one line var wordwidths = []; if (linecount > 1) { stagingtextnode.nodevalue = ''; for (var i = 0; i < words.length; i++) { if (words[i].length === 0) continue; stagingtextnode.nodevalue = utils.decodehtmlentity(words[i]); var bbox = stagingtext.getbbox(); wordwidths.push({ text: words[i], width: bbox.width }); } } //hide staging element after staging svg.style.display = 'none'; return { spacewidth: spacewidth, linecount: linecount, boundingbox: stagingtextbbox, words: wordwidths }; } else { //todo: canvas fallback for measuring text on android 2.3 return false; } }; })(); //helpers /** * prevents a function from being called too often, waits until a timer elapses to call it again * * @param fn function to call */ function debounce(fn) { if (!app.vars.debouncetimer) fn.call(this); if (app.vars.debouncetimer) global.cleartimeout(app.vars.debouncetimer); app.vars.debouncetimer = global.settimeout(function() { app.vars.debouncetimer = null; fn.call(this); }, app.setup.debounce); } /** * holder-specific resize/orientation change callback, debounced to prevent excessive execution */ function resizeevent() { debounce(function() { updateresizableelements(null); }); } //set up flags for (var flag in app.flags) { if (!app.flags.hasownproperty(flag)) continue; app.flags[flag].match = function(val) { return val.match(this.regex); }; } //properties set once on setup app.setup = { renderer: 'html', debounce: 100, ratio: 1, supportscanvas: false, supportssvg: false, linewrapratio: 0.9, dataattr: 'data-src', renderers: ['html', 'canvas', 'svg'] }; //properties modified during runtime app.vars = { preempted: false, resizableimages: [], invisibleimages: {}, invisibleid: 0, visibilitycheckstarted: false, debouncetimer: null, cache: {} }; //pre-flight (function() { var canvas = dom.newel('canvas'); if (canvas.getcontext) { if (canvas.todataurl('image/png').indexof('data:image/png') != -1) { app.setup.renderer = 'canvas'; app.setup.supportscanvas = true; } } if (!!document.createelementns && !!document.createelementns(svg_ns, 'svg').createsvgrect) { app.setup.renderer = 'svg'; app.setup.supportssvg = true; } })(); //starts checking for invisible placeholders startvisibilitycheck(); if (ondomready) { ondomready(function() { if (!app.vars.preempted) { holder.run(); } if (global.addeventlistener) { global.addeventlistener('resize', resizeevent, false); global.addeventlistener('orientationchange', resizeevent, false); } else { global.attachevent('onresize', resizeevent); } if (typeof global.turbolinks == 'object') { global.document.addeventlistener('page:change', function() { holder.run(); }); } }); } module.exports = holder; /* webpack var injection */}.call(exports, (function() { return this; }()))) /***/ }), /* 2 */ /***/ (function(module, exports) { /*! * ondomready.js 1.4.0 (c) 2013 tubal martin - mit license * * specially modified to work with holder.js */ function _ondomready(win) { //lazy loading fix for firefox < 3.6 //http://webreflection.blogspot.com/2009/11/195-chars-to-help-lazy-loading.html if (document.readystate == null && document.addeventlistener) { document.addeventlistener("domcontentloaded", function domcontentloaded() { document.removeeventlistener("domcontentloaded", domcontentloaded, false); document.readystate = "complete"; }, false); document.readystate = "loading"; } var doc = win.document, docelem = doc.documentelement, load = "load", false = false, onload = "on"+load, complete = "complete", readystate = "readystate", attachevent = "attachevent", detachevent = "detachevent", addeventlistener = "addeventlistener", domcontentloaded = "domcontentloaded", onreadystatechange = "onreadystatechange", removeeventlistener = "removeeventlistener", // w3c event model w3c = addeventlistener in doc, _top = false, // isready: is the dom ready to be used? set to true once it occurs. isready = false, // callbacks pending execution until dom is ready callbacks = []; // handle when the dom is ready function ready( fn ) { if ( !isready ) { // make sure body exists, at least, in case ie gets a little overzealous (ticket #5443). if ( !doc.body ) { return defer( ready ); } // remember that the dom is ready isready = true; // execute all callbacks while ( fn = callbacks.shift() ) { defer( fn ); } } } // the ready event handler function completed( event ) { // readystate === "complete" is good enough for us to call the dom ready in oldie if ( w3c || event.type === load || doc[readystate] === complete ) { detach(); ready(); } } // clean-up method for dom ready events function detach() { if ( w3c ) { doc[removeeventlistener]( domcontentloaded, completed, false ); win[removeeventlistener]( load, completed, false ); } else { doc[detachevent]( onreadystatechange, completed ); win[detachevent]( onload, completed ); } } // defers a function, scheduling it to run after the current call stack has cleared. function defer( fn, wait ) { // allow 0 to be passed settimeout( fn, +wait >= 0 ? wait : 1 ); } // attach the listeners: // catch cases where ondomready is called after the browser event has already occurred. // we once tried to use readystate "interactive" here, but it caused issues like the one // discovered by chriss here: http://bugs.jquery.com/ticket/12282#comment:15 if ( doc[readystate] === complete ) { // handle it asynchronously to allow scripts the opportunity to delay ready defer( ready ); // standards-based browsers support domcontentloaded } else if ( w3c ) { // use the handy event callback doc[addeventlistener]( domcontentloaded, completed, false ); // a fallback to window.onload, that will always work win[addeventlistener]( load, completed, false ); // if ie event model is used } else { // ensure firing before onload, maybe late but safe also for iframes doc[attachevent]( onreadystatechange, completed ); // a fallback to window.onload, that will always work win[attachevent]( onload, completed ); // if ie and not a frame // continually check to see if the document is ready try { _top = win.frameelement == null && docelem; } catch(e) {} if ( _top && _top.doscroll ) { (function doscrollcheck() { if ( !isready ) { try { // use the trick by diego perini // http://javascript.nwbox.com/iecontentloaded/ _top.doscroll("left"); } catch(e) { return defer( doscrollcheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions ready(); } })(); } } function ondomready( fn ) { // if dom is ready, execute the function (async), otherwise wait isready ? defer( fn ) : callbacks.push( fn ); } // add version ondomready.version = "1.4.0"; // add method to check if dom is ready ondomready.isready = function(){ return isready; }; return ondomready; } module.exports = typeof window !== "undefined" && _ondomready(window); /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { //modified version of component/querystring //changes: updated dependencies, dot notation parsing, jshint fixes //fork at https://github.com/imsky/querystring /** * module dependencies. */ var encode = encodeuricomponent; var decode = decodeuricomponent; var trim = __webpack_require__(4); var type = __webpack_require__(5); var arrayregex = /(\w+)\[(\d+)\]/; var objectregex = /\w+\.\w+/; /** * parse the given query `str`. * * @param {string} str * @return {object} * @api public */ exports.parse = function(str){ if ('string' !== typeof str) return {}; str = trim(str); if ('' === str) return {}; if ('?' === str.charat(0)) str = str.slice(1); var obj = {}; var pairs = str.split('&'); for (var i = 0; i < pairs.length; i++) { var parts = pairs[i].split('='); var key = decode(parts[0]); var m, ctx, prop; if (m = arrayregex.exec(key)) { obj[m[1]] = obj[m[1]] || []; obj[m[1]][m[2]] = decode(parts[1]); continue; } if (m = objectregex.test(key)) { m = key.split('.'); ctx = obj; while (m.length) { prop = m.shift(); if (!prop.length) continue; if (!ctx[prop]) { ctx[prop] = {}; } else if (ctx[prop] && typeof ctx[prop] !== 'object') { break; } if (!m.length) { ctx[prop] = decode(parts[1]); } ctx = ctx[prop]; } continue; } obj[parts[0]] = null == parts[1] ? '' : decode(parts[1]); } return obj; }; /** * stringify the given `obj`. * * @param {object} obj * @return {string} * @api public */ exports.stringify = function(obj){ if (!obj) return ''; var pairs = []; for (var key in obj) { var value = obj[key]; if ('array' == type(value)) { for (var i = 0; i < value.length; ++i) { pairs.push(encode(key + '[' + i + ']') + '=' + encode(value[i])); } continue; } pairs.push(encode(key) + '=' + encode(obj[key])); } return pairs.join('&'); }; /***/ }), /* 4 */ /***/ (function(module, exports) { exports = module.exports = trim; function trim(str){ return str.replace(/^\s*|\s*$/g, ''); } exports.left = function(str){ return str.replace(/^\s*/, ''); }; exports.right = function(str){ return str.replace(/\s*$/, ''); }; /***/ }), /* 5 */ /***/ (function(module, exports) { /** * tostring ref. */ var tostring = object.prototype.tostring; /** * return the type of `val`. * * @param {mixed} val * @return {string} * @api public */ module.exports = function(val){ switch (tostring.call(val)) { case '[object date]': return 'date'; case '[object regexp]': return 'regexp'; case '[object arguments]': return 'arguments'; case '[object array]': return 'array'; case '[object error]': return 'error'; } if (val === null) return 'null'; if (val === undefined) return 'undefined'; if (val !== val) return 'nan'; if (val && val.nodetype === 1) return 'element'; if (isbuffer(val)) return 'buffer'; val = val.valueof ? val.valueof() : object.prototype.valueof.apply(val); return typeof val; }; // code borrowed from https://github.com/feross/is-buffer/blob/master/index.js function isbuffer(obj) { return !!(obj != null && (obj._isbuffer || // for safari 5-7 (missing object.prototype.constructor) (obj.constructor && typeof obj.constructor.isbuffer === 'function' && obj.constructor.isbuffer(obj)) )) } /***/ }), /* 6 */ /***/ (function(module, exports) { var scenegraph = function(sceneproperties) { var nodecount = 1; //todo: move merge to helpers section function merge(parent, child) { for (var prop in child) { parent[prop] = child[prop]; } return parent; } var scenenode = function(name) { nodecount++; this.parent = null; this.children = {}; this.id = nodecount; this.name = 'n' + nodecount; if (typeof name !== 'undefined') { this.name = name; } this.x = this.y = this.z = 0; this.width = this.height = 0; }; scenenode.prototype.resize = function(width, height) { if (width != null) { this.width = width; } if (height != null) { this.height = height; } }; scenenode.prototype.moveto = function(x, y, z) { this.x = x != null ? x : this.x; this.y = y != null ? y : this.y; this.z = z != null ? z : this.z; }; scenenode.prototype.add = function(child) { var name = child.name; if (typeof this.children[name] === 'undefined') { this.children[name] = child; child.parent = this; } else { throw 'scenegraph: child already exists: ' + name; } }; var rootnode = function() { scenenode.call(this, 'root'); this.properties = sceneproperties; }; rootnode.prototype = new scenenode(); var shape = function(name, props) { scenenode.call(this, name); this.properties = { 'fill': '#000000' }; if (typeof props !== 'undefined') { merge(this.properties, props); } else if (typeof name !== 'undefined' && typeof name !== 'string') { throw 'scenegraph: invalid node name'; } }; shape.prototype = new scenenode(); var group = function() { shape.apply(this, arguments); this.type = 'group'; }; group.prototype = new shape(); var rect = function() { shape.apply(this, arguments); this.type = 'rect'; }; rect.prototype = new shape(); var text = function(text) { shape.call(this); this.type = 'text'; this.properties.text = text; }; text.prototype = new shape(); var root = new rootnode(); this.shape = { 'rect': rect, 'text': text, 'group': group }; this.root = root; return this; }; module.exports = scenegraph; /***/ }), /* 7 */ /***/ (function(module, exports) { /* webpack var injection */(function(global) {/** * shallow object clone and merge * * @param a object a * @param b object b * @returns {object} new object with all of a's properties, and all of b's properties, overwriting a's properties */ exports.extend = function(a, b) { var c = {}; for (var x in a) { if (a.hasownproperty(x)) { c[x] = a[x]; } } if (b != null) { for (var y in b) { if (b.hasownproperty(y)) { c[y] = b[y]; } } } return c; }; /** * takes a k/v list of css properties and returns a rule * * @param props css properties object */ exports.cssprops = function(props) { var ret = []; for (var p in props) { if (props.hasownproperty(p)) { ret.push(p + ':' + props[p]); } } return ret.join(';'); }; /** * encodes html entities in a string * * @param str input string */ exports.encodehtmlentity = function(str) { var buf = []; var charcode = 0; for (var i = str.length - 1; i >= 0; i--) { charcode = str.charcodeat(i); if (charcode > 128) { buf.unshift(['&#', charcode, ';'].join('')); } else { buf.unshift(str[i]); } } return buf.join(''); }; /** * checks if an image exists * * @param src url of image * @param callback callback to call once image status has been found */ exports.imageexists = function(src, callback) { var image = new image(); image.onerror = function() { callback.call(this, false); }; image.onload = function() { callback.call(this, true); }; image.src = src; }; /** * decodes html entities in a string * * @param str input string */ exports.decodehtmlentity = function(str) { return str.replace(/&#(\d+);/g, function(match, dec) { return string.fromcharcode(dec); }); }; /** * returns an element's dimensions if it's visible, `false` otherwise. * * @param el dom element */ exports.dimensioncheck = function(el) { var dimensions = { height: el.clientheight, width: el.clientwidth }; if (dimensions.height && dimensions.width) { return dimensions; } else { return false; } }; /** * returns true if value is truthy or if it is "semantically truthy" * @param val */ exports.truthy = function(val) { if (typeof val === 'string') { return val === 'true' || val === 'yes' || val === '1' || val === 'on' || val === '✓'; } return !!val; }; /** * parses input into a well-formed css color * @param val */ exports.parsecolor = function(val) { var hexre = /(^(?:#?)[0-9a-f]{6}$)|(^(?:#?)[0-9a-f]{3}$)/i; var rgbre = /^rgb\((\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/; var rgbare = /^rgba\((\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(0\.\d{1,}|1)\)$/; var match = val.match(hexre); var retval; if (match !== null) { retval = match[1] || match[2]; if (retval[0] !== '#') { return '#' + retval; } else { return retval; } } match = val.match(rgbre); if (match !== null) { retval = 'rgb(' + match.slice(1).join(',') + ')'; return retval; } match = val.match(rgbare); if (match !== null) { retval = 'rgba(' + match.slice(1).join(',') + ')'; return retval; } return null; }; /** * provides the correct scaling ratio for canvas drawing operations on hidpi screens (e.g. retina displays) */ exports.canvasratio = function () { var devicepixelratio = 1; var backingstoreratio = 1; if (global.document) { var canvas = global.document.createelement('canvas'); if (canvas.getcontext) { var ctx = canvas.getcontext('2d'); devicepixelratio = global.devicepixelratio || 1; backingstoreratio = ctx.webkitbackingstorepixelratio || ctx.mozbackingstorepixelratio || ctx.msbackingstorepixelratio || ctx.obackingstorepixelratio || ctx.backingstorepixelratio || 1; } } return devicepixelratio / backingstoreratio; }; /* webpack var injection */}.call(exports, (function() { return this; }()))) /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { /* webpack var injection */(function(global) {var dom = __webpack_require__(9); var svg_ns = 'http://www.w3.org/2000/svg'; var node_type_comment = 8; /** * generic svg element creation function * * @param svg svg context, set to null if new * @param width document width * @param height document height */ exports.initsvg = function(svg, width, height) { var defs, style, initialize = false; if (svg && svg.queryselector) { style = svg.queryselector('style'); if (style === null) { initialize = true; } } else { svg = dom.newel('svg', svg_ns); initialize = true; } if (initialize) { defs = dom.newel('defs', svg_ns); style = dom.newel('style', svg_ns); dom.setattr(style, { 'type': 'text/css' }); defs.appendchild(style); svg.appendchild(defs); } //ie throws an exception if this is set and chrome requires it to be set if (svg.webkitmatchesselector) { svg.setattribute('xmlns', svg_ns); } //remove comment nodes for (var i = 0; i < svg.childnodes.length; i++) { if (svg.childnodes[i].nodetype === node_type_comment) { svg.removechild(svg.childnodes[i]); } } //remove css while (style.childnodes.length) { style.removechild(style.childnodes[0]); } dom.setattr(svg, { 'width': width, 'height': height, 'viewbox': '0 0 ' + width + ' ' + height, 'preserveaspectratio': 'none' }); return svg; }; /** * converts serialized svg to a string suitable for data uri use * @param svgstring serialized svg string * @param [base64] use base64 encoding for data uri */ exports.svgstringtodatauri = function() { var rawprefix = 'data:image/svg+xml;charset=utf-8,'; var base64prefix = 'data:image/svg+xml;charset=utf-8;base64,'; return function(svgstring, base64) { if (base64) { return base64prefix + btoa(global.unescape(encodeuricomponent(svgstring))); } else { return rawprefix + encodeuricomponent(svgstring); } }; }(); /** * returns serialized svg with xml processing instructions * * @param svg svg context * @param stylesheets css stylesheets to include */ exports.serializesvg = function(svg, enginesettings) { if (!global.xmlserializer) return; var serializer = new xmlserializer(); var svgcss = ''; var stylesheets = enginesettings.stylesheets; //external stylesheets: processing instruction method if (enginesettings.svgxmlstylesheet) { var xml = dom.createxml(); //add directives for (var i = stylesheets.length - 1; i >= 0; i--) { var csspi = xml.createprocessinginstruction('xml-stylesheet', 'href="' + stylesheets[i] + '" rel="stylesheet"'); xml.insertbefore(csspi, xml.firstchild); } xml.removechild(xml.documentelement); svgcss = serializer.serializetostring(xml); } var svgtext = serializer.serializetostring(svg); svgtext = svgtext.replace(/\&(\#[0-9]{2,}\;)/g, '&$1'); return svgcss + svgtext; }; /* webpack var injection */}.call(exports, (function() { return this; }()))) /***/ }), /* 9 */ /***/ (function(module, exports) { /* webpack var injection */(function(global) {/** * generic new dom element function * * @param tag tag to create * @param namespace optional namespace value */ exports.newel = function(tag, namespace) { if (!global.document) return; if (namespace == null) { return global.document.createelement(tag); } else { return global.document.createelementns(namespace, tag); } }; /** * generic setattribute function * * @param el reference to dom element * @param attrs object with attribute keys and values */ exports.setattr = function (el, attrs) { for (var a in attrs) { el.setattribute(a, attrs[a]); } }; /** * creates a xml document * @private */ exports.createxml = function() { if (!global.domparser) return; return new domparser().parsefromstring('', 'application/xml'); }; /** * converts a value into an array of dom nodes * * @param val a string, a nodelist, a node, or an htmlcollection */ exports.getnodearray = function(val) { var retval = null; if (typeof(val) == 'string') { retval = document.queryselectorall(val); } else if (global.nodelist && val instanceof global.nodelist) { retval = val; } else if (global.node && val instanceof global.node) { retval = [val]; } else if (global.htmlcollection && val instanceof global.htmlcollection) { retval = val; } else if (val instanceof array) { retval = val; } else if (val === null) { retval = []; } retval = array.prototype.slice.call(retval); return retval; }; /* webpack var injection */}.call(exports, (function() { return this; }()))) /***/ }), /* 10 */ /***/ (function(module, exports) { var color = function(color, options) { //todo: support rgba, hsla, and rrggbbaa notation //todo: use cielab internally //todo: add clamp function (with sign) if (typeof color !== 'string') return; this.original = color; if (color.charat(0) === '#') { color = color.slice(1); } if (/[^a-f0-9]+/i.test(color)) return; if (color.length === 3) { color = color.replace(/./g, '$&$&'); } if (color.length !== 6) return; this.alpha = 1; if (options && options.alpha) { this.alpha = options.alpha; } this.set(parseint(color, 16)); }; //todo: jsdocs color.rgb2hex = function(r, g, b) { function format (decimal) { var hex = (decimal | 0).tostring(16); if (decimal < 16) { hex = '0' + hex; } return hex; } return [r, g, b].map(format).join(''); }; //todo: jsdocs color.hsl2rgb = function (h, s, l) { var h = h / 60; var c = (1 - math.abs(2 * l - 1)) * s; var x = c * (1 - math.abs(parseint(h) % 2 - 1)); var m = l - (c / 2); var r = 0, g = 0, b = 0; if (h >= 0 && h < 1) { r = c; g = x; } else if (h >= 1 && h < 2) { r = x; g = c; } else if (h >= 2 && h < 3) { g = c; b = x; } else if (h >= 3 && h < 4) { g = x; b = c; } else if (h >= 4 && h < 5) { r = x; b = c; } else if (h >= 5 && h < 6) { r = c; b = x; } r += m; g += m; b += m; r = parseint(r * 255); g = parseint(g * 255); b = parseint(b * 255); return [r, g, b]; }; /** * sets the color from a raw rgb888 integer * @param raw rgb888 representation of color */ //todo: refactor into a static method //todo: factor out individual color spaces //todo: add hsl, cielab, and cieluv color.prototype.set = function (val) { this.raw = val; var r = (this.raw & 0xff0000) >> 16; var g = (this.raw & 0x00ff00) >> 8; var b = (this.raw & 0x0000ff); // bt.709 var y = 0.2126 * r + 0.7152 * g + 0.0722 * b; var u = -0.09991 * r - 0.33609 * g + 0.436 * b; var v = 0.615 * r - 0.55861 * g - 0.05639 * b; this.rgb = { r: r, g: g, b: b }; this.yuv = { y: y, u: u, v: v }; return this; }; /** * lighten or darken a color * @param multiplier amount to lighten or darken (-1 to 1) */ color.prototype.lighten = function(multiplier) { var cm = math.min(1, math.max(0, math.abs(multiplier))) * (multiplier < 0 ? -1 : 1); var bm = (255 * cm) | 0; var cr = math.min(255, math.max(0, this.rgb.r + bm)); var cg = math.min(255, math.max(0, this.rgb.g + bm)); var cb = math.min(255, math.max(0, this.rgb.b + bm)); var hex = color.rgb2hex(cr, cg, cb); return new color(hex); }; /** * output color in hex format * @param addhash add a hash character to the beginning of the output */ color.prototype.tohex = function(addhash) { return (addhash ? '#' : '') + this.raw.tostring(16); }; /** * returns whether or not current color is lighter than another color * @param color color to compare against */ color.prototype.lighterthan = function(color) { if (!(color instanceof color)) { color = new color(color); } return this.yuv.y > color.yuv.y; }; /** * returns the result of mixing current color with another color * @param color color to mix with * @param multiplier how much to mix with the other color */ /* color.prototype.mix = function (color, multiplier) { if (!(color instanceof color)) { color = new color(color); } var r = this.rgb.r; var g = this.rgb.g; var b = this.rgb.b; var a = this.alpha; var m = typeof multiplier !== 'undefined' ? multiplier : 0.5; //todo: write a lerp function r = r + m * (color.rgb.r - r); g = g + m * (color.rgb.g - g); b = b + m * (color.rgb.b - b); a = a + m * (color.alpha - a); return new color(color.rgbtohex(r, g, b), { 'alpha': a }); }; */ /** * returns the result of blending another color on top of current color with alpha * @param color color to blend on top of current color, i.e. "ca" */ //todo: see if .blendalpha can be merged into .mix color.prototype.blendalpha = function(color) { if (!(color instanceof color)) { color = new color(color); } var ca = color; var cb = this; //todo: write alpha blending function var r = ca.alpha * ca.rgb.r + (1 - ca.alpha) * cb.rgb.r; var g = ca.alpha * ca.rgb.g + (1 - ca.alpha) * cb.rgb.g; var b = ca.alpha * ca.rgb.b + (1 - ca.alpha) * cb.rgb.b; return new color(color.rgb2hex(r, g, b)); }; module.exports = color; /***/ }), /* 11 */ /***/ (function(module, exports) { module.exports = { 'version': '2.9.6', 'svg_ns': 'http://www.w3.org/2000/svg' }; /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { var shaven = __webpack_require__(13); var svg = __webpack_require__(8); var constants = __webpack_require__(11); var utils = __webpack_require__(7); var svg_ns = constants.svg_ns; var templates = { 'element': function (options) { var tag = options.tag; var content = options.content || ''; delete options.tag; delete options.content; return [tag, content, options]; } }; //todo: deprecate tag arg, infer tag from shape object function convertshape (shape, tag) { return templates.element({ 'tag': tag, 'width': shape.width, 'height': shape.height, 'fill': shape.properties.fill }); } function textcss (properties) { return utils.cssprops({ 'fill': properties.fill, 'font-weight': properties.font.weight, 'font-family': properties.font.family + ', monospace', 'font-size': properties.font.size + properties.font.units }); } function outlinepath (bgwidth, bgheight, outlinewidth) { var outlineoffsetwidth = outlinewidth / 2; return [ 'm', outlineoffsetwidth, outlineoffsetwidth, 'h', bgwidth - outlineoffsetwidth, 'v', bgheight - outlineoffsetwidth, 'h', outlineoffsetwidth, 'v', 0, 'm', 0, outlineoffsetwidth, 'l', bgwidth, bgheight - outlineoffsetwidth, 'm', 0, bgheight - outlineoffsetwidth, 'l', bgwidth, outlineoffsetwidth ].join(' '); } module.exports = function (scenegraph, rendersettings) { var enginesettings = rendersettings.enginesettings; var stylesheets = enginesettings.stylesheets; var stylesheetxml = stylesheets.map(function (stylesheet) { return ''; }).join('\n'); var holderid = 'holder_' + number(new date()).tostring(16); var root = scenegraph.root; var textgroup = root.children.holdertextgroup; var css = '#' + holderid + ' text { ' + textcss(textgroup.properties) + ' } '; // push text down to be equally vertically aligned with canvas renderer textgroup.y += textgroup.textpositiondata.boundingbox.height * 0.8; var wordtags = []; object.keys(textgroup.children).foreach(function (linekey) { var line = textgroup.children[linekey]; object.keys(line.children).foreach(function (wordkey) { var word = line.children[wordkey]; var x = textgroup.x + line.x + word.x; var y = textgroup.y + line.y + word.y; var wordtag = templates.element({ 'tag': 'text', 'content': word.properties.text, 'x': x, 'y': y }); wordtags.push(wordtag); }); }); var text = templates.element({ 'tag': 'g', 'content': wordtags }); var outline = null; if (root.children.holderbg.properties.outline) { var outlineproperties = root.children.holderbg.properties.outline; outline = templates.element({ 'tag': 'path', 'd': outlinepath(root.children.holderbg.width, root.children.holderbg.height, outlineproperties.width), 'stroke-width': outlineproperties.width, 'stroke': outlineproperties.fill, 'fill': 'none' }); } var bg = convertshape(root.children.holderbg, 'rect'); var scenecontent = []; scenecontent.push(bg); if (outlineproperties) { scenecontent.push(outline); } scenecontent.push(text); var scene = templates.element({ 'tag': 'g', 'id': holderid, 'content': scenecontent }); var style = templates.element({ 'tag': 'style', //todo: figure out how to add cdata directive 'content': css, 'type': 'text/css' }); var defs = templates.element({ 'tag': 'defs', 'content': style }); var svg = templates.element({ 'tag': 'svg', 'content': [defs, scene], 'width': root.properties.width, 'height': root.properties.height, 'xmlns': svg_ns, 'viewbox': [0, 0, root.properties.width, root.properties.height].join(' '), 'preserveaspectratio': 'none' }); var output = shaven(svg); if (/\&(x)?#[0-9a-fa-f]/.test(output[0])) { output[0] = output[0].replace(/&#/gm, '&#'); } output = stylesheetxml + output[0]; var svgstring = svg.svgstringtodatauri(output, rendersettings.mode === 'background'); return svgstring; }; /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { var escape = __webpack_require__(14) // todo: remove namespace module.exports = function shaven (array, namespace, returnobject) { 'use strict' var i = 1 var doesescape = true var htmlstring var attributekey var callback var key returnobject = returnobject || {} function createelement (sugarstring) { var tags = sugarstring.match(/^[\w-]+/) var element = { tag: tags ? tags[0] : 'div', attr: {}, children: [] } var id = sugarstring.match(/#([\w-]+)/) var reference = sugarstring.match(/\$([\w-]+)/) var classnames = sugarstring.match(/\.[\w-]+/g) // assign id if is set if (id) { element.attr.id = id[1] // add element to the return object returnobject[id[1]] = element } if (reference) returnobject[reference[1]] = element if (classnames) element.attr.class = classnames.join(' ').replace(/\./g, '') if (sugarstring.match(/&$/g)) doesescape = false return element } function replacer (key, value) { if (value === null || value === false || value === undefined) return if (typeof value !== 'string' && typeof value !== 'object') return string(value) return value } function escapeattribute (string) { return (string || string === 0) ? string(string) .replace(/&/g, '&') .replace(/"/g, '"') : '' } function escapehtml (string) { return string(string) .replace(/&/g, '&') .replace(/"/g, '"') .replace(/'/g, ''') .replace(//g, '>') } if (typeof array[0] === 'string') array[0] = createelement(array[0]) else if (array.isarray(array[0])) i = 0 else throw new error( 'first element of array must be a string, ' + 'or an array and not ' + json.stringify(array[0]) ) for (; i < array.length; i++) { // don't render element if value is false or null if (array[i] === false || array[i] === null) { array[0] = false break } // continue with next array value if current value is undefined or true else if (array[i] === undefined || array[i] === true) { continue } else if (typeof array[i] === 'string') { if (doesescape) array[i] = escapehtml(array[i]) array[0].children.push(array[i]) } else if (typeof array[i] === 'number') { array[0].children.push(array[i]) } else if (array.isarray(array[i])) { if (array.isarray(array[i][0])) { array[i].reverse().foreach(function (subarray) { array.splice(i + 1, 0, subarray) }) if (i !== 0) continue i++ } shaven(array[i], namespace, returnobject) if (array[i][0]) array[0].children.push(array[i][0]) } else if (typeof array[i] === 'function') callback = array[i] else if (typeof array[i] === 'object') { for (attributekey in array[i]) if (array[i].hasownproperty(attributekey)) if (array[i][attributekey] !== null && array[i][attributekey] !== false) if (attributekey === 'style' && typeof array[i][attributekey] === 'object') array[0].attr[attributekey] = json .stringify(array[i][attributekey], replacer) .slice(2, -2) .replace(/","/g, ';') .replace(/":"/g, ':') .replace(/\\"/g, '\'') else array[0].attr[attributekey] = array[i][attributekey] } else throw new typeerror('"' + array[i] + '" is not allowed as a value.') } if (array[0] !== false) { htmlstring = '<' + array[0].tag for (key in array[0].attr) if (array[0].attr.hasownproperty(key)) htmlstring += ' ' + key + '="' + escapeattribute(array[0].attr[key]) + '"' htmlstring += '>' array[0].children.foreach(function (child) { htmlstring += child }) htmlstring += '' array[0] = htmlstring } // return root element on index 0 returnobject[0] = array[0] if (callback) callback(array[0]) // returns object containing all elements with an id and the root element return returnobject } /***/ }), /* 14 */ /***/ (function(module, exports) { /*! * escape-html * copyright(c) 2012-2013 tj holowaychuk * copyright(c) 2015 andreas lubbe * copyright(c) 2015 tiancheng "timothy" gu * mit licensed */ 'use strict'; /** * module variables. * @private */ var matchhtmlregexp = /["'&<>]/; /** * module exports. * @public */ module.exports = escapehtml; /** * escape special characters in the given string of html. * * @param {string} string the string to escape for inserting into html * @return {string} * @public */ function escapehtml(string) { var str = '' + string; var match = matchhtmlregexp.exec(str); if (!match) { return str; } var escape; var html = ''; var index = 0; var lastindex = 0; for (index = match.index; index < str.length; index++) { switch (str.charcodeat(index)) { case 34: // " escape = '"'; break; case 38: // & escape = '&'; break; case 39: // ' escape = '''; break; case 60: // < escape = '<'; break; case 62: // > escape = '>'; break; default: continue; } if (lastindex !== index) { html += str.substring(lastindex, index); } lastindex = index + 1; html += escape; } return lastindex !== index ? html + str.substring(lastindex, index) : html; } /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { var dom = __webpack_require__(9); var utils = __webpack_require__(7); module.exports = (function() { var canvas = dom.newel('canvas'); var ctx = null; return function(scenegraph) { if (ctx == null) { ctx = canvas.getcontext('2d'); } var dpr = utils.canvasratio(); var root = scenegraph.root; canvas.width = dpr * root.properties.width; canvas.height = dpr * root.properties.height ; ctx.textbaseline = 'middle'; var bg = root.children.holderbg; var bgwidth = dpr * bg.width; var bgheight = dpr * bg.height; //todo: parametrize outline width (e.g. in scene object) var outlinewidth = 2; var outlineoffsetwidth = outlinewidth / 2; ctx.fillstyle = bg.properties.fill; ctx.fillrect(0, 0, bgwidth, bgheight); if (bg.properties.outline) { //todo: abstract this into a method ctx.strokestyle = bg.properties.outline.fill; ctx.linewidth = bg.properties.outline.width; ctx.moveto(outlineoffsetwidth, outlineoffsetwidth); // tl, tr, br, bl ctx.lineto(bgwidth - outlineoffsetwidth, outlineoffsetwidth); ctx.lineto(bgwidth - outlineoffsetwidth, bgheight - outlineoffsetwidth); ctx.lineto(outlineoffsetwidth, bgheight - outlineoffsetwidth); ctx.lineto(outlineoffsetwidth, outlineoffsetwidth); // diagonals ctx.moveto(0, outlineoffsetwidth); ctx.lineto(bgwidth, bgheight - outlineoffsetwidth); ctx.moveto(0, bgheight - outlineoffsetwidth); ctx.lineto(bgwidth, outlineoffsetwidth); ctx.stroke(); } var textgroup = root.children.holdertextgroup; ctx.font = textgroup.properties.font.weight + ' ' + (dpr * textgroup.properties.font.size) + textgroup.properties.font.units + ' ' + textgroup.properties.font.family + ', monospace'; ctx.fillstyle = textgroup.properties.fill; for (var linekey in textgroup.children) { var line = textgroup.children[linekey]; for (var wordkey in line.children) { var word = line.children[wordkey]; var x = dpr * (textgroup.x + line.x + word.x); var y = dpr * (textgroup.y + line.y + word.y + (textgroup.properties.leading / 2)); ctx.filltext(word.properties.text, x, y); } } return canvas.todataurl('image/png'); }; })(); /***/ }) /******/ ]) }); ; (function(ctx, ismeteorpackage) { if (ismeteorpackage) { holder = ctx.holder; } })(this, typeof meteor !== 'undefined' && typeof package !== 'undefined');