code
stringlengths
2
1.05M
/* YUI 3.17.2 (build 9c3c78e) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add("lang/datatype-date-format_nl",function(e){e.Intl.add("datatype-date-format","nl",{a:["zo","ma","di","wo","do","vr","za"],A:["zondag","maandag","dinsdag","woensdag","donderdag","vrijdag","zaterdag"],b:["jan.","feb.","mrt.","apr.","mei","jun.","jul.","aug.","sep.","okt.","nov.","dec."],B:["januari","februari","maart","april","mei","juni","juli","augustus","september","oktober","november","december"],c:"%a %d %b %Y %H:%M:%S %Z",p:["AM","PM"],P:["am","pm"],x:"%d-%m-%y",X:"%H:%M:%S"})},"3.17.2");
/* mousetrap v1.5.3 craig.is/killing/mice */ (function(C,r,g){function t(a,b,h){a.addEventListener?a.addEventListener(b,h,!1):a.attachEvent("on"+b,h)}function x(a){if("keypress"==a.type){var b=String.fromCharCode(a.which);a.shiftKey||(b=b.toLowerCase());return b}return l[a.which]?l[a.which]:p[a.which]?p[a.which]:String.fromCharCode(a.which).toLowerCase()}function D(a){var b=[];a.shiftKey&&b.push("shift");a.altKey&&b.push("alt");a.ctrlKey&&b.push("ctrl");a.metaKey&&b.push("meta");return b}function u(a){return"shift"==a||"ctrl"==a||"alt"==a|| "meta"==a}function y(a,b){var h,c,e,g=[];h=a;"+"===h?h=["+"]:(h=h.replace(/\+{2}/g,"+plus"),h=h.split("+"));for(e=0;e<h.length;++e)c=h[e],z[c]&&(c=z[c]),b&&"keypress"!=b&&A[c]&&(c=A[c],g.push("shift")),u(c)&&g.push(c);h=c;e=b;if(!e){if(!k){k={};for(var m in l)95<m&&112>m||l.hasOwnProperty(m)&&(k[l[m]]=m)}e=k[h]?"keydown":"keypress"}"keypress"==e&&g.length&&(e="keydown");return{key:c,modifiers:g,action:e}}function B(a,b){return null===a||a===r?!1:a===b?!0:B(a.parentNode,b)}function c(a){function b(a){a= a||{};var b=!1,n;for(n in q)a[n]?b=!0:q[n]=0;b||(v=!1)}function h(a,b,n,f,c,h){var g,e,l=[],m=n.type;if(!d._callbacks[a])return[];"keyup"==m&&u(a)&&(b=[a]);for(g=0;g<d._callbacks[a].length;++g)if(e=d._callbacks[a][g],(f||!e.seq||q[e.seq]==e.level)&&m==e.action){var k;(k="keypress"==m&&!n.metaKey&&!n.ctrlKey)||(k=e.modifiers,k=b.sort().join(",")===k.sort().join(","));k&&(k=f&&e.seq==f&&e.level==h,(!f&&e.combo==c||k)&&d._callbacks[a].splice(g,1),l.push(e))}return l}function g(a,b,n,f){d.stopCallback(b, b.target||b.srcElement,n,f)||!1!==a(b,n)||(b.preventDefault?b.preventDefault():b.returnValue=!1,b.stopPropagation?b.stopPropagation():b.cancelBubble=!0)}function e(a){"number"!==typeof a.which&&(a.which=a.keyCode);var b=x(a);b&&("keyup"==a.type&&w===b?w=!1:d.handleKey(b,D(a),a))}function l(a,c,n,f){function e(c){return function(){v=c;++q[a];clearTimeout(k);k=setTimeout(b,1E3)}}function h(c){g(n,c,a);"keyup"!==f&&(w=x(c));setTimeout(b,10)}for(var d=q[a]=0;d<c.length;++d){var p=d+1===c.length?h:e(f|| y(c[d+1]).action);m(c[d],p,f,a,d)}}function m(a,b,c,f,e){d._directMap[a+":"+c]=b;a=a.replace(/\s+/g," ");var g=a.split(" ");1<g.length?l(a,g,b,c):(c=y(a,c),d._callbacks[c.key]=d._callbacks[c.key]||[],h(c.key,c.modifiers,{type:c.action},f,a,e),d._callbacks[c.key][f?"unshift":"push"]({callback:b,modifiers:c.modifiers,action:c.action,seq:f,level:e,combo:a}))}var d=this;a=a||r;if(!(d instanceof c))return new c(a);d.target=a;d._callbacks={};d._directMap={};var q={},k,w=!1,p=!1,v=!1;d._handleKey=function(a, c,e){var f=h(a,c,e),d;c={};var k=0,l=!1;for(d=0;d<f.length;++d)f[d].seq&&(k=Math.max(k,f[d].level));for(d=0;d<f.length;++d)f[d].seq?f[d].level==k&&(l=!0,c[f[d].seq]=1,g(f[d].callback,e,f[d].combo,f[d].seq)):l||g(f[d].callback,e,f[d].combo);f="keypress"==e.type&&p;e.type!=v||u(a)||f||b(c);p=l&&"keydown"==e.type};d._bindMultiple=function(a,b,c){for(var d=0;d<a.length;++d)m(a[d],b,c)};t(a,"keypress",e);t(a,"keydown",e);t(a,"keyup",e)}var l={8:"backspace",9:"tab",13:"enter",16:"shift",17:"ctrl",18:"alt", 20:"capslock",27:"esc",32:"space",33:"pageup",34:"pagedown",35:"end",36:"home",37:"left",38:"up",39:"right",40:"down",45:"ins",46:"del",91:"meta",93:"meta",224:"meta"},p={106:"*",107:"+",109:"-",110:".",111:"/",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},A={"~":"`","!":"1","@":"2","#":"3",$:"4","%":"5","^":"6","&":"7","*":"8","(":"9",")":"0",_:"-","+":"=",":":";",'"':"'","<":",",">":".","?":"/","|":"\\"},z={option:"alt",command:"meta","return":"enter", escape:"esc",plus:"+",mod:/Mac|iPod|iPhone|iPad/.test(navigator.platform)?"meta":"ctrl"},k;for(g=1;20>g;++g)l[111+g]="f"+g;for(g=0;9>=g;++g)l[g+96]=g;c.prototype.bind=function(a,b,c){a=a instanceof Array?a:[a];this._bindMultiple.call(this,a,b,c);return this};c.prototype.unbind=function(a,b){return this.bind.call(this,a,function(){},b)};c.prototype.trigger=function(a,b){if(this._directMap[a+":"+b])this._directMap[a+":"+b]({},a);return this};c.prototype.reset=function(){this._callbacks={};this._directMap= {};return this};c.prototype.stopCallback=function(a,b){return-1<(" "+b.className+" ").indexOf(" mousetrap ")||B(b,this.target)?!1:"INPUT"==b.tagName||"SELECT"==b.tagName||"TEXTAREA"==b.tagName||b.isContentEditable};c.prototype.handleKey=function(){return this._handleKey.apply(this,arguments)};c.init=function(){var a=c(r),b;for(b in a)"_"!==b.charAt(0)&&(c[b]=function(b){return function(){return a[b].apply(a,arguments)}}(b))};c.init();C.Mousetrap=c;"undefined"!==typeof module&&module.exports&&(module.exports= c);"function"===typeof define&&define.amd&&define(function(){return c})})(window,document);
version https://git-lfs.github.com/spec/v1 oid sha256:a3f03afcc6974e394a97aab72837e73c3df4a856e0908debbcf04204ea006311 size 4789
module.exports = function(req, res) { req.list.model.findById(req.params.id, function(err, item) { if (err) return res.status(500).json({ err: 'database error', detail: err }); if (!item) return res.status(404).json({ err: 'not found', id: req.params.id }); req.list.updateItem(item, { data: req.body, files: req.files }, function(err) { if (err) return res.status(500).json({ err: 'database error', detail: err }); res.json(req.list.getData(item)); }); }); };
/** * DragDrop.js * * A JavaScript micro-framework for adding drag-and-drop functionality * to elements for advanced UI development. * * @author James Brumond * @version 0.3.0 * @copyright Copyright 2011 James Brumond * @license Dual licensed under MIT and GPL */ /*jshint browser: true, bitwise: false, camelcase: false, eqnull: true, latedef: false, plusplus: false, jquery: true, shadow: true, smarttabs: true, loopfunc: true */ (function() { var // Is this a touch device? touchEvents = ('ontouchstart' in window), // A class to add when an element is being dragged dragClass = 'drag', /** * The DragDrop namespace * * Example: * * DragDrop.bind ( element[, options ]); * DragDrop.unbind ( reference ); * * @access public */ DragDrop = (function() { var self = { }, // Determine the events to bind to events = (touchEvents ? { start: 'touchstart', move: 'touchmove', end: 'touchend' } : { start: 'mousedown', move: 'mousemove', end: 'mouseup' } ), // Elements already bound bindings = [ ], // Check if a given binding (element/anchor pair) already exists bindingExists = function(element, anchor) { for (var i = 0, c = bindings.length; i < c; i++) { if (bindings[i] && bindings[i].element === element && bindings[i].anchor === anchor) { return true; } } return false; }, // Do something with a given binding's given event stack withBindingEvent = function(reference, event, func) { if (bindings[reference._id] && bindings[reference._id].events[event]) { func(bindings[reference._id].events[event]); } }, // Parse the arguments of DragDrop.bind parseOptions = function(element, options) { options = options || { }; options.element = element; options.anchor = options.anchor || element; options.boundingBox = options.boundingBox || null; return options; }, // The next binding ID to use nextBinding = 1, // ------------------------------------------------------------------ // A constructor for a resource type used in referencing bindings BindingReference = function() { this._id = nextBinding++; }; BindingReference.prototype.unbind = function() { return DragDrop.unbind(this); }; BindingReference.prototype.bindEvent = function(event, func) { return DragDrop.bindEvent(this, event, func); }; BindingReference.prototype.unbindEvent = function(event, func) { return DragDrop.unbindEvent(this, event, func); }; BindingReference.prototype.invokeEvent = function(event, source) { return DragDrop.invokeEvent(this, event, source); }; BindingReference.prototype.setBoundingBox = function(box) { bindings[this._id].boundingBox = box; }; // ---------------------------------------------------------------------------- // Public Functions // Make an element draggable self.bind = function(element, options) { options = parseOptions(element, options); if (! isObject(options.element)) { throw new Error('Must give an element to drag'); } if (getStyle(options.anchor, 'position') === 'static') { throw new Error('Cannot drag-drop an element with position:static'); } // Check to make sure the elements aren't already bound if (! bindingExists(options.element, options.anchor)) { // Initialize the binding object var reference = new BindingReference(); var binding = { element: options.element, anchor: options.anchor, dragging: false, event: null, shouldUnbind: false, boundingBox: options.boundingBox, events: { beforedrag: Callstack(options.beforedrag), dragstart: Callstack(options.dragstart), dragend: Callstack(options.dragend), drag: Callstack(options.drag), unbind: Callstack(options.unbind) } }; // Bind the first event binding.event = Events.bind(binding.anchor, events.start, function(e) { // Make sure it's a left click or touch event if ((window.event && e.button === 1) || e.button === 0 || touchEvents) { stopEvent(e); // Call any "beforedrag" events before calculations begin binding.events.beforedrag.call( binding.element, new DragEvent('beforedrag', e, binding) ); // Make sure everyone knows the element is being dragged binding.dragging = true; addClass(binding.element, dragClass); // Start calculating movement var startX = getPos(binding.element, 'left'); var startY = getPos(binding.element, 'top'); var tempEvents = [ ]; // The target for the move and end events is dependent on the input type var target = (touchEvents ? binding.anchor : document); // Bind the movement event tempEvents.push(Events.bind(target, events.move, function(e2) { // Find all needed offsets var offsetX = e2.clientX - e.clientX; var offsetY = e2.clientY - e.clientY; var offsetWidth = binding.element.offsetWidth; var offsetHeight = binding.element.offsetHeight; // Find the new positions var posX = startX + offsetX; var posY = startY + offsetY; // Enforce any bounding box if (binding.boundingBox) { var box = binding.boundingBox; var minX, maxX, minY, maxY; // Bound inside offset parent if (box === 'offsetParent') { var parent = binding.element.offsetParent; minX = minY = 0; maxX = parent.offsetWidth; maxY = parent.offsetHeight; } // Bound to the dimensions of the window else if (box === 'windowSize') { var dimensions = getWindowSize(); minX = minY = 0; maxX = dimensions.x; maxY = dimensions.y; } // Manual bounding box else { minX = box.x.min; maxX = box.x.max; minY = box.y.min; maxY = box.y.max; } posX = Math.max(minX, Math.min(maxX - offsetWidth, posX)); posY = Math.max(minY, Math.min(maxY - offsetHeight, posY)); } // Move the element binding.element.style.left = posX + 'px'; binding.element.style.top = posY + 'px'; // Call any "drag" events binding.events.drag.call( binding.element, new DragEvent('drag', e2, binding) ); return stopEvent(e2); })); // Bind the release event tempEvents.push(Events.bind(target, events.end, function(e2) { // Unbind move and end events for (var i = 0, c = tempEvents.length; i < c; i++) { Events.unbind(tempEvents[i]); } // Clean up... binding.dragging = false; removeClass(binding.element, dragClass); if (binding.shouldUnbind) { DragDrop.unbind(binding.element, binding.anchor); } // Call any "dragend" events binding.events.dragend.call( binding.element, new DragEvent('dragend', e2, binding) ); return stopEvent(e2); })); // Avoid text selection problems document.body.focus(); tempEvents.push(Events.bind(document, 'selectstart', false)); tempEvents.push(Events.bind(binding.anchor, 'dragstart', false)); // Call any "dragstart" events binding.events.dragstart.call( binding.element, new DragEvent('dragstart', e, binding) ); return false; } }); // Add the binding to the list bindings[reference._id] = binding; return reference; } }; // Remove an element's draggableness self.unbind = function(reference) { if (reference instanceof BindingReference) { var id = reference._id; if (bindings[id]) { if (bindings[id].dragging) { bindings[id].shouldUnbind = true; } else { Events.unbind(bindings[id].event); bindings[id] = null; } // Call any "unbind" events binding.events.unbind.call( binding.element, new DragEvent('unbind', e, binding) ); } } }; // Bind a drag event self.bindEvent = function(reference, event, func) { withBindingEvent(reference, event, function(stack) { stack.push(func); }); }; // Unbind a drag event self.unbindEvent = function(reference, event, func) { withBindingEvent(reference, event, function(stack) { stack.remove(func); }); }; // Manually invoke a drag event self.invokeEvent = function(reference, event, source) { withBindingEvent(reference, event, function(stack) { stack.call( bindings[reference._id].element, new DragEvent(event, source, reference) ); }); }; return self; }()), // ---------------------------------------------------------------------------- // Helper Functions // Array Remove - By John Resig (MIT Licensed) arrayRemove = function(array, from, to) { var rest = array.slice((to || from) + 1 || array.length); array.length = from < 0 ? array.length + from : from; return array.push.apply(array, rest); }, // Get the position of an element getPos = function(elem, from) { var pos = parseFloat(getStyle(elem, from)); return (isNaN(pos) ? 0 : pos); }, // Get a style property from an element getStyle = function(elem, prop) { if (elem.currentStyle) { return elem.currentStyle[prop]; } else if (window.getComputedStyle) { return document.defaultView.getComputedStyle(elem, null).getPropertyValue(prop); } else if (elem.style) { return elem.style[prop]; } }, // Get the dimensions of the window getWindowSize = function() { return { x: window.innerWidth || document.documentElement.clientWidth || body().clientWidth, y: window.innerHeight || document.documentElement.clientHeight || body().clientHeight }; }, // Stop an event stopEvent = function(evt) { if (evt.preventDefault) { evt.preventDefault(); } if (evt.stopPropagation) { evt.stopPropagation(); } evt.returnValue = false; return false; }, // Regular expressions for matching classnames cnRegexes = { }, // Remove a class from an element removeClass = function(elem, cn) { if (! cnRegexes[cn]) { cnRegexes[cn] = new RegExp('(^|\\s)+' + cn + '(\\s|$)+'); } elem.className = elem.className.replace(cnRegexes[cn], ' '); }, // Add a class to an element addClass = function(elem, cn) { removeClass(elem, cn); elem.className += ' ' + cn; }, // Check for a non-null object isObject = function(value) { return !! (value && typeof value === 'object'); }, /** * A stackable function * * @access private * @param function an initial function * @return function */ Callstack = function(func) { var stack = [ ]; var result = function() { var ret; for (var i = 0, c = stack.length; i < c; i++) { ret = stack[i].apply(this, arguments); } return ret; }; result.push = function() { stack.push.apply(stack, arguments); }; result.remove = function() { var args = Array.prototype.slice.call(arguments); var result = [ ]; OUTER: for (var i = 0, c1 = stack.length; i < c1; i++) { for (var j = 0, c2 = args.length; j < c2; j++) { if (stack[i] === args[j]) { continue OUTER; } } result.push(stack[i]); } stack = result; }; if (typeof func === 'function') { stack.push(func); } return result; }, /** * Custom event constructor * * @access private * @param string type * @param object original event object */ DragEvent = function DragEvent(type, original, binding) { this.type = type; this.originalEvent = original; this.altKey = original.altKey || false; this.ctrlKey = original.ctrlKey || false; this.shiftKey = original.shiftKey || false; this.timestamp = original.timestamp || (+new Date()); this.pos = getPosition(original); this.binding = binding; }, /** * A namespace with functions for event binding * * Example: * * Bind * var evt = Events.bind(obj, 'event', function() { ... }); * * Unbind * Events.unbind(evt); * -OR- * evt.unbind(); * * @access private */ Events = (function() { var // Bind an event bindEvent = (function() { if (document.addEventListener) { return function(obj, event, func) { obj.addEventListener(event, func, false); }; } else if (document.attachEvent) { return function(obj, event, func) { obj.attachEvent('on' + event, func); }; } else { return function() { }; } }()), // Unbind an event unbindEvent = (function() { if (document.removeEventListener) { return function(obj, event, func) { obj.removeEventListener(event, func, false); }; } else if (document.detachEvent) { return function(obj, event, func) { obj.detachEvent('on' + event, func); }; } else { return function() { }; } }()); // Build the return value return { bind: function(obj, event, func) { var oldFunc = (func === false) ? function(e) { return stopEvent(e); } : func; func = function(e) { return oldFunc.call(obj, e || window.event); }; bindEvent(obj, event, func); var ret = function() { unbindEvent(obj, event, func); }; ret.unbind = function() {ret();}; return ret; }, unbind: function(unbinder) { unbinder(); } }; }()); function getPosition(evt) { var posX = 0; var posY = 0; if (evt.targetTouches) { posX = evt.targetTouches[0].pageX; posY = evt.targetTouches[0].pageY; } else if (evt.pageX || evt.pageY) { posX = evt.pageX; posY = evt.pageY; } else if (evt.clientX || evt.clientY) { posX = evt.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; posY = evt.clientY + document.body.scrollTop + document.documentElement.scrollTop; } return {x: posX, y: posY}; } // ---------------------------------------------------------------------------- // Expose window.DragDrop = DragDrop; }());
const dog = { @readonly @nonenumerable @doubledValue legs: 4 };
/** * Interaction for the groups module * * @author Jeroen Van den Bossche <jeroenvandenbossche@netlash.com> * @author Dieter Vanden Eynde <dieter@netlash.com> * @author Thomas Deceuninck <thomas@fronto.be> */ jsBackend.groups = { // init, constructor-alike init: function() { // variables $hide = $('.hide'); $container = $('.container'); $containerLabel = $('.container span label'); $moduleDataGridBody = $('.module .datagridHolder .dataGrid tbody'); $groupHolderDataGridBody = $('.groupHolder .dataGrid tbody'); $dataGridTd = $('.dataGrid tbody tr td'); $selectAll = $('.selectAll'); $hide.each(jsBackend.groups.hide); $container.click(jsBackend.groups.clickHandler); $containerLabel.each(jsBackend.groups.mouseHandler); $moduleDataGridBody.each(jsBackend.groups.selectionPermissions); $groupHolderDataGridBody.each(jsBackend.groups.selectionWidgets); $dataGridTd.click(jsBackend.groups.selectHandler); $selectAll.click(jsBackend.groups.selectAll); }, // hide an item hide: function() { // variables $this = $(this); // hide them $this.hide(); }, // clickhandler clickHandler: function(e) { // prevent default e.preventDefault(); // init vars $this = $(this); // the action is currently closed, open it if($this.hasClass('iconCollapsed')) { // slidedown $this.next('.datagridHolder').show(); // change title $this.attr('title', 'close'); // change css $this.addClass('iconExpanded'); $this.removeClass('iconCollapsed'); } // the action is currently open, close it else { // close this thing $this.next('.datagridHolder').hide(); // change title $this.attr('title', 'open'); // change css $this.addClass('iconCollapsed'); $this.removeClass('iconExpanded'); } }, // selectHandler selectHandler: function() { // init vars $this = $(this); // editing permissions? check permissions if($this.parent('tr').parent('tbody').parent('.dataGrid').parent('.datagridHolder').parent('.module').html() !== null) $this.parent('tr').parent('tbody').each(jsBackend.groups.selectionPermissions); // editing widgets? check widgets else $this.parent('tr').parent('tbody').each(jsBackend.groups.selectionWidgets); }, // selection selectionPermissions: function() { // init vars var allChecked = true; var noneChecked = true; $this = $(this); // loop all actions and check if they're checked $this.find('tr td input').each(function() { // if not checked set false if(!$(this).prop('checked')) allChecked = false; // is checked? else noneChecked = false; }); // some are checked? indeterminate! if(!allChecked && !noneChecked) { // unset checked and set indeterminate $this.parent('table').parent('div').parent('li').find('input').get(0).checked = false; $this.parent('table').parent('div').parent('li').find('input').get(0).indeterminate = true; } // if all actions are checked, check massaction checkbox if(allChecked) { // unset indeterminate and set checked $this.parent('table').parent('div').parent('li').find('input').get(0).indeterminate = false; $this.parent('table').parent('div').parent('li').find('input').get(0).checked = true; } // nothing is checked? if(noneChecked) { // unset indeterminate and checked $this.parent('table').parent('div').parent('li').find('input').get(0).indeterminate = false; $this.parent('table').parent('div').parent('li').find('input').get(0).checked = false; } }, // selection widgets selectionWidgets : function() { // init vars var allChecked = true; $this = $(this); // loop all actions and check if they're checked $this.find('tr td input').each(function() { // if not checked set false if(!$(this).attr('checked')) allChecked = false; }); // set checked if all is checked if(allChecked) $this.parent('table').find('thead tr th span span input').attr('checked', 'checked'); // uncheck if not all items are checked else $this.parent('table').find('thead tr th span span input').removeAttr('checked'); }, // mousehandler mouseHandler: function() { // variables $this = $(this); // assign mouseovers $this.mouseover(function() { // change cursors $this.css('cursor', 'pointer'); $this.css('cursor', 'hand'); }); }, // select all selectAll : function() { // init vars $this = $(this); // check all? if($this.prop('checked')) { // loop through rows $this.next('a').next('div').find('table tbody tr td input').each(function() { // check boxes $(this).attr('checked', 'checked').parents('tr').addClass('selected'); }); } // uncheck all? else { // loop through rows $this.next('a').next('div').find('table tbody tr td input').each(function() { // uncheck boxes $(this).removeAttr('checked').parents('tr').removeClass('selected'); }); } } }; $(jsBackend.groups.init);
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The Physics Body is typically linked to a single Sprite and defines properties that determine how the physics body is simulated. * These properties affect how the body reacts to forces, what forces it generates on itself (to simulate friction), and how it reacts to collisions in the scene. * In most cases, the properties are used to simulate physical effects. Each body also has its own property values that determine exactly how it reacts to forces and collisions in the scene. * By default a single Rectangle shape is added to the Body that matches the dimensions of the parent Sprite. See addShape, removeShape, clearShapes to add extra shapes around the Body. * Note: When bound to a Sprite to avoid single-pixel jitters on mobile devices we strongly recommend using Sprite sizes that are even on both axis, i.e. 128x128 not 127x127. * Note: When a game object is given a P2 body it has its anchor x/y set to 0.5, so it becomes centered. * * @class Phaser.Physics.P2.Body * @classdesc Physics Body Constructor * @constructor * @param {Phaser.Game} game - Game reference to the currently running game. * @param {Phaser.Sprite} [sprite] - The Sprite object this physics body belongs to. * @param {number} [x=0] - The x coordinate of this Body. * @param {number} [y=0] - The y coordinate of this Body. * @param {number} [mass=1] - The default mass of this Body (0 = static). */ Phaser.Physics.P2.Body = function (game, sprite, x, y, mass) { sprite = sprite || null; x = x || 0; y = y || 0; if (typeof mass === 'undefined') { mass = 1; } /** * @property {Phaser.Game} game - Local reference to game. */ this.game = game; /** * @property {Phaser.Physics.P2} world - Local reference to the P2 World. */ this.world = game.physics.p2; /** * @property {Phaser.Sprite} sprite - Reference to the parent Sprite. */ this.sprite = sprite; /** * @property {number} type - The type of physics system this body belongs to. */ this.type = Phaser.Physics.P2JS; /** * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position. */ this.offset = new Phaser.Point(); /** * @property {p2.Body} data - The p2 Body data. * @protected */ this.data = new p2.Body({ position: [ this.world.pxmi(x), this.world.pxmi(y) ], mass: mass }); this.data.parent = this; /** * @property {Phaser.InversePointProxy} velocity - The velocity of the body. Set velocity.x to a negative value to move to the left, position to the right. velocity.y negative values move up, positive move down. */ this.velocity = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.velocity); /** * @property {Phaser.InversePointProxy} force - The force applied to the body. */ this.force = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.force); /** * @property {Phaser.Point} gravity - A locally applied gravity force to the Body. Applied directly before the world step. NOTE: Not currently implemented. */ this.gravity = new Phaser.Point(); /** * Dispatched when a first contact is created between shapes in two bodies. This event is fired during the step, so collision has already taken place. * The event will be sent 4 parameters: The body it is in contact with, the shape from this body that caused the contact, the shape from the contact body and the contact equation data array. * @property {Phaser.Signal} onBeginContact */ this.onBeginContact = new Phaser.Signal(); /** * Dispatched when contact ends between shapes in two bodies. This event is fired during the step, so collision has already taken place. * The event will be sent 3 parameters: The body it is in contact with, the shape from this body that caused the contact and the shape from the contact body. * @property {Phaser.Signal} onEndContact */ this.onEndContact = new Phaser.Signal(); /** * @property {array} collidesWith - Array of CollisionGroups that this Bodies shapes collide with. */ this.collidesWith = []; /** * @property {boolean} removeNextStep - To avoid deleting this body during a physics step, and causing all kinds of problems, set removeNextStep to true to have it removed in the next preUpdate. */ this.removeNextStep = false; /** * @property {Phaser.Physics.P2.BodyDebug} debugBody - Reference to the debug body. */ this.debugBody = null; /** * @property {boolean} _collideWorldBounds - Internal var that determines if this Body collides with the world bounds or not. * @private */ this._collideWorldBounds = true; /** * @property {object} _bodyCallbacks - Array of Body callbacks. * @private */ this._bodyCallbacks = {}; /** * @property {object} _bodyCallbackContext - Array of Body callback contexts. * @private */ this._bodyCallbackContext = {}; /** * @property {object} _groupCallbacks - Array of Group callbacks. * @private */ this._groupCallbacks = {}; /** * @property {object} _bodyCallbackContext - Array of Grouo callback contexts. * @private */ this._groupCallbackContext = {}; // Set-up the default shape if (sprite) { this.setRectangleFromSprite(sprite); if (sprite.exists) { this.game.physics.p2.addBody(this); } } }; Phaser.Physics.P2.Body.prototype = { /** * Sets a callback to be fired any time a shape in this Body impacts with a shape in the given Body. The impact test is performed against body.id values. * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. * * @method Phaser.Physics.P2.Body#createBodyCallback * @param {Phaser.Sprite|Phaser.TileSprite|Phaser.Physics.P2.Body|p2.Body} object - The object to send impact events for. * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback. * @param {object} callbackContext - The context under which the callback will fire. */ createBodyCallback: function (object, callback, callbackContext) { var id = -1; if (object['id']) { id = object.id; } else if (object['body']) { id = object.body.id; } if (id > -1) { if (callback === null) { delete (this._bodyCallbacks[id]); delete (this._bodyCallbackContext[id]); } else { this._bodyCallbacks[id] = callback; this._bodyCallbackContext[id] = callbackContext; } } }, /** * Sets a callback to be fired any time this Body impacts with the given Group. The impact test is performed against shape.collisionGroup values. * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. * This callback will only fire if this Body has been assigned a collision group. * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. * * @method Phaser.Physics.P2.Body#createGroupCallback * @param {Phaser.Physics.CollisionGroup} group - The Group to send impact events for. * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback. * @param {object} callbackContext - The context under which the callback will fire. */ createGroupCallback: function (group, callback, callbackContext) { if (callback === null) { delete (this._groupCallbacks[group.mask]); delete (this._groupCallbacksContext[group.mask]); } else { this._groupCallbacks[group.mask] = callback; this._groupCallbackContext[group.mask] = callbackContext; } }, /** * Gets the collision bitmask from the groups this body collides with. * * @method Phaser.Physics.P2.Body#getCollisionMask * @return {number} The bitmask. */ getCollisionMask: function () { var mask = 0; if (this._collideWorldBounds) { mask = this.game.physics.p2.boundsCollisionGroup.mask; } for (var i = 0; i < this.collidesWith.length; i++) { mask = mask | this.collidesWith[i].mask; } return mask; }, /** * Updates the collisionMask. * * @method Phaser.Physics.P2.Body#updateCollisionMask * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body. */ updateCollisionMask: function (shape) { var mask = this.getCollisionMask(); if (typeof shape === 'undefined') { for (var i = this.data.shapes.length - 1; i >= 0; i--) { this.data.shapes[i].collisionMask = mask; } } else { shape.collisionMask = mask; } }, /** * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified. * This also resets the collisionMask. * * @method Phaser.Physics.P2.Body#setCollisionGroup * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use. * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body. */ setCollisionGroup: function (group, shape) { var mask = this.getCollisionMask(); if (typeof shape === 'undefined') { for (var i = this.data.shapes.length - 1; i >= 0; i--) { this.data.shapes[i].collisionGroup = group.mask; this.data.shapes[i].collisionMask = mask; } } else { shape.collisionGroup = group.mask; shape.collisionMask = mask; } }, /** * Clears the collision data from the shapes in this Body. Optionally clears Group and/or Mask. * * @method Phaser.Physics.P2.Body#clearCollision * @param {boolean} [clearGroup=true] - Clear the collisionGroup value from the shape/s? * @param {boolean} [clearMask=true] - Clear the collisionMask value from the shape/s? * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision data will be cleared from all Shapes in this Body. */ clearCollision: function (clearGroup, clearMask, shape) { if (typeof shape === 'undefined') { for (var i = this.data.shapes.length - 1; i >= 0; i--) { if (clearGroup) { this.data.shapes[i].collisionGroup = null; } if (clearMask) { this.data.shapes[i].collisionMask = null; } } } else { if (clearGroup) { shape.collisionGroup = null; } if (clearMask) { shape.collisionMask = null; } } if (clearGroup) { this.collidesWith.length = 0; } }, /** * Adds the given CollisionGroup, or array of CollisionGroups, to the list of groups that this body will collide with and updates the collision masks. * * @method Phaser.Physics.P2.Body#collides * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes will collide with. * @param {function} [callback] - Optional callback that will be triggered when this Body impacts with the given Group. * @param {object} [callbackContext] - The context under which the callback will be called. * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision mask will be added to all Shapes in this Body. */ collides: function (group, callback, callbackContext, shape) { if (Array.isArray(group)) { for (var i = 0; i < group.length; i++) { if (this.collidesWith.indexOf(group[i]) === -1) { this.collidesWith.push(group[i]); if (callback) { this.createGroupCallback(group[i], callback, callbackContext); } } } } else { if (this.collidesWith.indexOf(group) === -1) { this.collidesWith.push(group); if (callback) { this.createGroupCallback(group, callback, callbackContext); } } } var mask = this.getCollisionMask(); if (typeof shape === 'undefined') { for (var i = this.data.shapes.length - 1; i >= 0; i--) { this.data.shapes[i].collisionMask = mask; } } else { shape.collisionMask = mask; } }, /** * Moves the shape offsets so their center of mass becomes the body center of mass. * * @method Phaser.Physics.P2.Body#adjustCenterOfMass */ adjustCenterOfMass: function () { this.data.adjustCenterOfMass(); }, /** * Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details. * * @method Phaser.Physics.P2.Body#applyDamping * @param {number} dt - Current time step. */ applyDamping: function (dt) { this.data.applyDamping(dt); }, /** * Apply force to a world point. This could for example be a point on the RigidBody surface. Applying force this way will add to Body.force and Body.angularForce. * * @method Phaser.Physics.P2.Body#applyForce * @param {Float32Array|Array} force - The force vector to add. * @param {number} worldX - The world x point to apply the force on. * @param {number} worldY - The world y point to apply the force on. */ applyForce: function (force, worldX, worldY) { this.data.applyForce(force, [this.world.pxmi(worldX), this.world.pxmi(worldY)]); }, /** * Sets the force on the body to zero. * * @method Phaser.Physics.P2.Body#setZeroForce */ setZeroForce: function () { this.data.setZeroForce(); }, /** * If this Body is dynamic then this will zero its angular velocity. * * @method Phaser.Physics.P2.Body#setZeroRotation */ setZeroRotation: function () { this.data.angularVelocity = 0; }, /** * If this Body is dynamic then this will zero its velocity on both axis. * * @method Phaser.Physics.P2.Body#setZeroVelocity */ setZeroVelocity: function () { this.data.velocity[0] = 0; this.data.velocity[1] = 0; }, /** * Sets the Body damping and angularDamping to zero. * * @method Phaser.Physics.P2.Body#setZeroDamping */ setZeroDamping: function () { this.data.damping = 0; this.data.angularDamping = 0; }, /** * Transform a world point to local body frame. * * @method Phaser.Physics.P2.Body#toLocalFrame * @param {Float32Array|Array} out - The vector to store the result in. * @param {Float32Array|Array} worldPoint - The input world vector. */ toLocalFrame: function (out, worldPoint) { return this.data.toLocalFrame(out, worldPoint); }, /** * Transform a local point to world frame. * * @method Phaser.Physics.P2.Body#toWorldFrame * @param {Array} out - The vector to store the result in. * @param {Array} localPoint - The input local vector. */ toWorldFrame: function (out, localPoint) { return this.data.toWorldFrame(out, localPoint); }, /** * This will rotate the Body by the given speed to the left (counter-clockwise). * * @method Phaser.Physics.P2.Body#rotateLeft * @param {number} speed - The speed at which it should rotate. */ rotateLeft: function (speed) { this.data.angularVelocity = this.world.pxm(-speed); }, /** * This will rotate the Body by the given speed to the left (clockwise). * * @method Phaser.Physics.P2.Body#rotateRight * @param {number} speed - The speed at which it should rotate. */ rotateRight: function (speed) { this.data.angularVelocity = this.world.pxm(speed); }, /** * Moves the Body forwards based on its current angle and the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveForward * @param {number} speed - The speed at which it should move forwards. */ moveForward: function (speed) { var magnitude = this.world.pxmi(-speed); var angle = this.data.angle + Math.PI / 2; this.data.velocity[0] = magnitude * Math.cos(angle); this.data.velocity[1] = magnitude * Math.sin(angle); }, /** * Moves the Body backwards based on its current angle and the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveBackward * @param {number} speed - The speed at which it should move backwards. */ moveBackward: function (speed) { var magnitude = this.world.pxmi(-speed); var angle = this.data.angle + Math.PI / 2; this.data.velocity[0] = -(magnitude * Math.cos(angle)); this.data.velocity[1] = -(magnitude * Math.sin(angle)); }, /** * Applies a force to the Body that causes it to 'thrust' forwards, based on its current angle and the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#thrust * @param {number} speed - The speed at which it should thrust. */ thrust: function (speed) { var magnitude = this.world.pxmi(-speed); var angle = this.data.angle + Math.PI / 2; this.data.force[0] += magnitude * Math.cos(angle); this.data.force[1] += magnitude * Math.sin(angle); }, /** * Applies a force to the Body that causes it to 'thrust' backwards (in reverse), based on its current angle and the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#reverse * @param {number} speed - The speed at which it should reverse. */ reverse: function (speed) { var magnitude = this.world.pxmi(-speed); var angle = this.data.angle + Math.PI / 2; this.data.force[0] -= magnitude * Math.cos(angle); this.data.force[1] -= magnitude * Math.sin(angle); }, /** * If this Body is dynamic then this will move it to the left by setting its x velocity to the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveLeft * @param {number} speed - The speed at which it should move to the left, in pixels per second. */ moveLeft: function (speed) { this.data.velocity[0] = this.world.pxmi(-speed); }, /** * If this Body is dynamic then this will move it to the right by setting its x velocity to the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveRight * @param {number} speed - The speed at which it should move to the right, in pixels per second. */ moveRight: function (speed) { this.data.velocity[0] = this.world.pxmi(speed); }, /** * If this Body is dynamic then this will move it up by setting its y velocity to the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveUp * @param {number} speed - The speed at which it should move up, in pixels per second. */ moveUp: function (speed) { this.data.velocity[1] = this.world.pxmi(-speed); }, /** * If this Body is dynamic then this will move it down by setting its y velocity to the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveDown * @param {number} speed - The speed at which it should move down, in pixels per second. */ moveDown: function (speed) { this.data.velocity[1] = this.world.pxmi(speed); }, /** * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. * * @method Phaser.Physics.P2.Body#preUpdate * @protected */ preUpdate: function () { if (this.removeNextStep) { this.removeFromWorld(); this.removeNextStep = false; } }, /** * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. * * @method Phaser.Physics.P2.Body#postUpdate * @protected */ postUpdate: function () { this.sprite.x = this.world.mpxi(this.data.position[0]); this.sprite.y = this.world.mpxi(this.data.position[1]); if (!this.fixedRotation) { this.sprite.rotation = this.data.angle; } }, /** * Resets the Body force, velocity (linear and angular) and rotation. Optionally resets damping and mass. * * @method Phaser.Physics.P2.Body#reset * @param {number} x - The new x position of the Body. * @param {number} y - The new x position of the Body. * @param {boolean} [resetDamping=false] - Resets the linear and angular damping. * @param {boolean} [resetMass=false] - Sets the Body mass back to 1. */ reset: function (x, y, resetDamping, resetMass) { if (typeof resetDamping === 'undefined') { resetDamping = false; } if (typeof resetMass === 'undefined') { resetMass = false; } this.setZeroForce(); this.setZeroVelocity(); this.setZeroRotation(); if (resetDamping) { this.setZeroDamping(); } if (resetMass) { this.mass = 1; } this.x = x; this.y = y; }, /** * Adds this physics body to the world. * * @method Phaser.Physics.P2.Body#addToWorld */ addToWorld: function () { if (this.game.physics.p2._toRemove) { for (var i = 0; i < this.game.physics.p2._toRemove.length; i++) { if (this.game.physics.p2._toRemove[i] === this) { this.game.physics.p2._toRemove.splice(i, 1); } } } if (this.data.world !== this.game.physics.p2.world) { this.game.physics.p2.addBody(this); } }, /** * Removes this physics body from the world. * * @method Phaser.Physics.P2.Body#removeFromWorld */ removeFromWorld: function () { if (this.data.world === this.game.physics.p2.world) { this.game.physics.p2.removeBodyNextStep(this); } }, /** * Destroys this Body and all references it holds to other objects. * * @method Phaser.Physics.P2.Body#destroy */ destroy: function () { this.removeFromWorld(); this.clearShapes(); this._bodyCallbacks = {}; this._bodyCallbackContext = {}; this._groupCallbacks = {}; this._groupCallbackContext = {}; if (this.debugBody) { this.debugBody.destroy(); } this.debugBody = null; this.sprite = null; }, /** * Removes all Shapes from this Body. * * @method Phaser.Physics.P2.Body#clearShapes */ clearShapes: function () { var i = this.data.shapes.length; while (i--) { this.data.removeShape(this.data.shapes[i]); } this.shapeChanged(); }, /** * Add a shape to the body. You can pass a local transform when adding a shape, so that the shape gets an offset and an angle relative to the body center of mass. * Will automatically update the mass properties and bounding radius. * * @method Phaser.Physics.P2.Body#addShape * @param {p2.Shape} shape - The shape to add to the body. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Shape} The shape that was added to the body. */ addShape: function (shape, offsetX, offsetY, rotation) { if (typeof offsetX === 'undefined') { offsetX = 0; } if (typeof offsetY === 'undefined') { offsetY = 0; } if (typeof rotation === 'undefined') { rotation = 0; } this.data.addShape(shape, [this.world.pxmi(offsetX), this.world.pxmi(offsetY)], rotation); this.shapeChanged(); return shape; }, /** * Adds a Circle shape to this Body. You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addCircle * @param {number} radius - The radius of this circle (in pixels) * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Circle} The Circle shape that was added to the Body. */ addCircle: function (radius, offsetX, offsetY, rotation) { var shape = new p2.Circle(this.world.pxm(radius)); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Adds a Rectangle shape to this Body. You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addRectangle * @param {number} width - The width of the rectangle in pixels. * @param {number} height - The height of the rectangle in pixels. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Rectangle} The Rectangle shape that was added to the Body. */ addRectangle: function (width, height, offsetX, offsetY, rotation) { var shape = new p2.Rectangle(this.world.pxm(width), this.world.pxm(height)); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Adds a Plane shape to this Body. The plane is facing in the Y direction. You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addPlane * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Plane} The Plane shape that was added to the Body. */ addPlane: function (offsetX, offsetY, rotation) { var shape = new p2.Plane(); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Adds a Particle shape to this Body. You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addParticle * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Particle} The Particle shape that was added to the Body. */ addParticle: function (offsetX, offsetY, rotation) { var shape = new p2.Particle(); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Adds a Line shape to this Body. * The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0]. * You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addLine * @param {number} length - The length of this line (in pixels) * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Line} The Line shape that was added to the Body. */ addLine: function (length, offsetX, offsetY, rotation) { var shape = new p2.Line(this.world.pxm(length)); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Adds a Capsule shape to this Body. * You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addCapsule * @param {number} length - The distance between the end points in pixels. * @param {number} radius - Radius of the capsule in radians. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Capsule} The Capsule shape that was added to the Body. */ addCapsule: function (length, radius, offsetX, offsetY, rotation) { var shape = new p2.Capsule(this.world.pxm(length), radius); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. The shape must be simple and without holes. * This function expects the x.y values to be given in pixels. If you want to provide them at p2 world scales then call Body.data.fromPolygon directly. * * @method Phaser.Physics.P2.Body#addPolygon * @param {object} options - An object containing the build options: * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. * @return {boolean} True on success, else false. */ addPolygon: function (options, points) { options = options || {}; if (!Array.isArray(points)) { points = Array.prototype.slice.call(arguments, 1); } var path = []; // Did they pass in a single array of points? if (points.length === 1 && Array.isArray(points[0])) { path = points[0].slice(0); } else if (Array.isArray(points[0])) { path = points[0].slice(0); } else if (typeof points[0] === 'number') { // We've a list of numbers for (var i = 0, len = points.length; i < len; i += 2) { path.push([points[i], points[i + 1]]); } } // top and tail var idx = path.length - 1; if (path[idx][0] === path[0][0] && path[idx][1] === path[0][1]) { path.pop(); } // Now process them into p2 values for (var p = 0; p < path.length; p++) { path[p][0] = this.world.pxmi(path[p][0]); path[p][1] = this.world.pxmi(path[p][1]); } var result = this.data.fromPolygon(path, options); this.shapeChanged(); return result; }, /** * Remove a shape from the body. Will automatically update the mass properties and bounding radius. * * @method Phaser.Physics.P2.Body#removeShape * @param {p2.Circle|p2.Rectangle|p2.Plane|p2.Line|p2.Particle} shape - The shape to remove from the body. * @return {boolean} True if the shape was found and removed, else false. */ removeShape: function (shape) { var result = this.data.removeShape(shape); this.shapeChanged(); return result; }, /** * Clears any previously set shapes. Then creates a new Circle shape and adds it to this Body. * * @method Phaser.Physics.P2.Body#setCircle * @param {number} radius - The radius of this circle (in pixels) * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. */ setCircle: function (radius, offsetX, offsetY, rotation) { this.clearShapes(); return this.addCircle(radius, offsetX, offsetY, rotation); }, /** * Clears any previously set shapes. The creates a new Rectangle shape at the given size and offset, and adds it to this Body. * If you wish to create a Rectangle to match the size of a Sprite or Image see Body.setRectangleFromSprite. * * @method Phaser.Physics.P2.Body#setRectangle * @param {number} [width=16] - The width of the rectangle in pixels. * @param {number} [height=16] - The height of the rectangle in pixels. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Rectangle} The Rectangle shape that was added to the Body. */ setRectangle: function (width, height, offsetX, offsetY, rotation) { if (typeof width === 'undefined') { width = 16; } if (typeof height === 'undefined') { height = 16; } this.clearShapes(); return this.addRectangle(width, height, offsetX, offsetY, rotation); }, /** * Clears any previously set shapes. * Then creates a Rectangle shape sized to match the dimensions and orientation of the Sprite given. * If no Sprite is given it defaults to using the parent of this Body. * * @method Phaser.Physics.P2.Body#setRectangleFromSprite * @param {Phaser.Sprite|Phaser.Image} [sprite] - The Sprite on which the Rectangle will get its dimensions. * @return {p2.Rectangle} The Rectangle shape that was added to the Body. */ setRectangleFromSprite: function (sprite) { if (typeof sprite === 'undefined') { sprite = this.sprite; } this.clearShapes(); return this.addRectangle(sprite.width, sprite.height, 0, 0, sprite.rotation); }, /** * Adds the given Material to all Shapes that belong to this Body. * If you only wish to apply it to a specific Shape in this Body then provide that as the 2nd parameter. * * @method Phaser.Physics.P2.Body#setMaterial * @param {Phaser.Physics.P2.Material} material - The Material that will be applied. * @param {p2.Shape} [shape] - An optional Shape. If not provided the Material will be added to all Shapes in this Body. */ setMaterial: function (material, shape) { if (typeof shape === 'undefined') { for (var i = this.data.shapes.length - 1; i >= 0; i--) { this.data.shapes[i].material = material; } } else { shape.material = material; } }, /** * Updates the debug draw if any body shapes change. * * @method Phaser.Physics.P2.Body#shapeChanged */ shapeChanged: function() { if (this.debugBody) { this.debugBody.draw(); } }, /** * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. * The shape data format is based on the custom phaser export in. * * @method Phaser.Physics.P2.Body#addPhaserPolygon * @param {string} key - The key of the Physics Data file as stored in Game.Cache. * @param {string} object - The key of the object within the Physics data file that you wish to load the shape data from. */ addPhaserPolygon: function (key, object) { var data = this.game.cache.getPhysicsData(key, object); var createdFixtures = []; // Cycle through the fixtures for (var i = 0; i < data.length; i++) { var fixtureData = data[i]; var shapesOfFixture = this.addFixture(fixtureData); // Always add to a group createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group] || []; createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group].concat(shapesOfFixture); // if (unique) fixture key is provided if (fixtureData.fixtureKey) { createdFixtures[fixtureData.fixtureKey] = shapesOfFixture; } } this.data.aabbNeedsUpdate = true; this.shapeChanged(); return createdFixtures; }, /** * Add a polygon fixture. This is used during #loadPolygon. * * @method Phaser.Physics.P2.Body#addFixture * @param {string} fixtureData - The data for the fixture. It contains: isSensor, filter (collision) and the actual polygon shapes. * @return {array} An array containing the generated shapes for the given polygon. */ addFixture: function (fixtureData) { var generatedShapes = []; if (fixtureData.circle) { var shape = new p2.Circle(this.world.pxm(fixtureData.circle.radius)); shape.collisionGroup = fixtureData.filter.categoryBits; shape.collisionMask = fixtureData.filter.maskBits; shape.sensor = fixtureData.isSensor; var offset = p2.vec2.create(); offset[0] = this.world.pxmi(fixtureData.circle.position[0] - this.sprite.width/2); offset[1] = this.world.pxmi(fixtureData.circle.position[1] - this.sprite.height/2); this.data.addShape(shape, offset); generatedShapes.push(shape); } else { var polygons = fixtureData.polygons; var cm = p2.vec2.create(); for (var i = 0; i < polygons.length; i++) { var shapes = polygons[i]; var vertices = []; for (var s = 0; s < shapes.length; s += 2) { vertices.push([ this.world.pxmi(shapes[s]), this.world.pxmi(shapes[s + 1]) ]); } var shape = new p2.Convex(vertices); // Move all vertices so its center of mass is in the local center of the convex for (var j = 0; j !== shape.vertices.length; j++) { var v = shape.vertices[j]; p2.vec2.sub(v, v, shape.centerOfMass); } p2.vec2.scale(cm, shape.centerOfMass, 1); cm[0] -= this.world.pxmi(this.sprite.width / 2); cm[1] -= this.world.pxmi(this.sprite.height / 2); shape.updateTriangles(); shape.updateCenterOfMass(); shape.updateBoundingRadius(); shape.collisionGroup = fixtureData.filter.categoryBits; shape.collisionMask = fixtureData.filter.maskBits; shape.sensor = fixtureData.isSensor; this.data.addShape(shape, cm); generatedShapes.push(shape); } } return generatedShapes; }, /** * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. * * @method Phaser.Physics.P2.Body#loadPolygon * @param {string} key - The key of the Physics Data file as stored in Game.Cache. * @param {string} object - The key of the object within the Physics data file that you wish to load the shape data from. * @return {boolean} True on success, else false. */ loadPolygon: function (key, object) { var data = this.game.cache.getPhysicsData(key, object); // We've multiple Convex shapes, they should be CCW automatically var cm = p2.vec2.create(); for (var i = 0; i < data.length; i++) { var vertices = []; for (var s = 0; s < data[i].shape.length; s += 2) { vertices.push([ this.world.pxmi(data[i].shape[s]), this.world.pxmi(data[i].shape[s + 1]) ]); } var c = new p2.Convex(vertices); // Move all vertices so its center of mass is in the local center of the convex for (var j = 0; j !== c.vertices.length; j++) { var v = c.vertices[j]; p2.vec2.sub(v, v, c.centerOfMass); } p2.vec2.scale(cm, c.centerOfMass, 1); cm[0] -= this.world.pxmi(this.sprite.width / 2); cm[1] -= this.world.pxmi(this.sprite.height / 2); c.updateTriangles(); c.updateCenterOfMass(); c.updateBoundingRadius(); this.data.addShape(c, cm); } this.data.aabbNeedsUpdate = true; this.shapeChanged(); return true; }, /** * DEPRECATED: This method will soon be removed from the API. Please avoid using. * Reads the physics data from a physics data file stored in the Game.Cache. * It will add the shape data to this Body, as well as set the density (mass). * * @method Phaser.Physics.P2.Body#loadData * @param {string} key - The key of the Physics Data file as stored in Game.Cache. * @param {string} object - The key of the object within the Physics data file that you wish to load the shape data from. * @return {boolean} True on success, else false. */ loadData: function (key, object) { var data = this.game.cache.getPhysicsData(key, object); if (data && data.shape) { this.mass = data.density; return this.loadPolygon(key, object); } } }; Phaser.Physics.P2.Body.prototype.constructor = Phaser.Physics.P2.Body; /** * Dynamic body. * @property DYNAMIC * @type {Number} * @static */ Phaser.Physics.P2.Body.DYNAMIC = 1; /** * Static body. * @property STATIC * @type {Number} * @static */ Phaser.Physics.P2.Body.STATIC = 2; /** * Kinematic body. * @property KINEMATIC * @type {Number} * @static */ Phaser.Physics.P2.Body.KINEMATIC = 4; /** * @name Phaser.Physics.P2.Body#static * @property {boolean} static - Returns true if the Body is static. Setting Body.static to 'false' will make it dynamic. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "static", { get: function () { return (this.data.motionState === Phaser.Physics.P2.Body.STATIC); }, set: function (value) { if (value && this.data.motionState !== Phaser.Physics.P2.Body.STATIC) { this.data.motionState = Phaser.Physics.P2.Body.STATIC; this.mass = 0; } else if (!value && this.data.motionState === Phaser.Physics.P2.Body.STATIC) { this.data.motionState = Phaser.Physics.P2.Body.DYNAMIC; if (this.mass === 0) { this.mass = 1; } } } }); /** * @name Phaser.Physics.P2.Body#dynamic * @property {boolean} dynamic - Returns true if the Body is dynamic. Setting Body.dynamic to 'false' will make it static. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "dynamic", { get: function () { return (this.data.motionState === Phaser.Physics.P2.Body.DYNAMIC); }, set: function (value) { if (value && this.data.motionState !== Phaser.Physics.P2.Body.DYNAMIC) { this.data.motionState = Phaser.Physics.P2.Body.DYNAMIC; if (this.mass === 0) { this.mass = 1; } } else if (!value && this.data.motionState === Phaser.Physics.P2.Body.DYNAMIC) { this.data.motionState = Phaser.Physics.P2.Body.STATIC; this.mass = 0; } } }); /** * @name Phaser.Physics.P2.Body#kinematic * @property {boolean} kinematic - Returns true if the Body is kinematic. Setting Body.kinematic to 'false' will make it static. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "kinematic", { get: function () { return (this.data.motionState === Phaser.Physics.P2.Body.KINEMATIC); }, set: function (value) { if (value && this.data.motionState !== Phaser.Physics.P2.Body.KINEMATIC) { this.data.motionState = Phaser.Physics.P2.Body.KINEMATIC; this.mass = 4; } else if (!value && this.data.motionState === Phaser.Physics.P2.Body.KINEMATIC) { this.data.motionState = Phaser.Physics.P2.Body.STATIC; this.mass = 0; } } }); /** * @name Phaser.Physics.P2.Body#allowSleep * @property {boolean} allowSleep - */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "allowSleep", { get: function () { return this.data.allowSleep; }, set: function (value) { if (value !== this.data.allowSleep) { this.data.allowSleep = value; } } }); /** * The angle of the Body in degrees from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. * Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement Body.angle = 450 is the same as Body.angle = 90. * If you wish to work in radians instead of degrees use the property Body.rotation instead. Working in radians is faster as it doesn't have to convert values. * * @name Phaser.Physics.P2.Body#angle * @property {number} angle - The angle of this Body in degrees. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angle", { get: function() { return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.data.angle)); }, set: function(value) { this.data.angle = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value)); } }); /** * Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. * @name Phaser.Physics.P2.Body#angularDamping * @property {number} angularDamping - The angular damping acting acting on the body. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularDamping", { get: function () { return this.data.angularDamping; }, set: function (value) { this.data.angularDamping = value; } }); /** * @name Phaser.Physics.P2.Body#angularForce * @property {number} angularForce - The angular force acting on the body. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularForce", { get: function () { return this.data.angularForce; }, set: function (value) { this.data.angularForce = value; } }); /** * @name Phaser.Physics.P2.Body#angularVelocity * @property {number} angularVelocity - The angular velocity of the body. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularVelocity", { get: function () { return this.data.angularVelocity; }, set: function (value) { this.data.angularVelocity = value; } }); /** * Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. * @name Phaser.Physics.P2.Body#damping * @property {number} damping - The linear damping acting on the body in the velocity direction. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "damping", { get: function () { return this.data.damping; }, set: function (value) { this.data.damping = value; } }); /** * @name Phaser.Physics.P2.Body#fixedRotation * @property {boolean} fixedRotation - */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "fixedRotation", { get: function () { return this.data.fixedRotation; }, set: function (value) { if (value !== this.data.fixedRotation) { this.data.fixedRotation = value; } } }); /** * @name Phaser.Physics.P2.Body#inertia * @property {number} inertia - The inertia of the body around the Z axis.. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "inertia", { get: function () { return this.data.inertia; }, set: function (value) { this.data.inertia = value; } }); /** * @name Phaser.Physics.P2.Body#mass * @property {number} mass - */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "mass", { get: function () { return this.data.mass; }, set: function (value) { if (value !== this.data.mass) { this.data.mass = value; this.data.updateMassProperties(); } } }); /** * @name Phaser.Physics.P2.Body#motionState * @property {number} motionState - The type of motion this body has. Should be one of: Body.STATIC (the body does not move), Body.DYNAMIC (body can move and respond to collisions) and Body.KINEMATIC (only moves according to its .velocity). */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "motionState", { get: function () { return this.data.motionState; }, set: function (value) { if (value !== this.data.motionState) { this.data.motionState = value; } } }); /** * The angle of the Body in radians. * If you wish to work in degrees instead of radians use the Body.angle property instead. Working in radians is faster as it doesn't have to convert values. * * @name Phaser.Physics.P2.Body#rotation * @property {number} rotation - The angle of this Body in radians. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "rotation", { get: function() { return this.data.angle; }, set: function(value) { this.data.angle = value; } }); /** * @name Phaser.Physics.P2.Body#sleepSpeedLimit * @property {number} sleepSpeedLimit - . */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "sleepSpeedLimit", { get: function () { return this.data.sleepSpeedLimit; }, set: function (value) { this.data.sleepSpeedLimit = value; } }); /** * @name Phaser.Physics.P2.Body#x * @property {number} x - The x coordinate of this Body. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "x", { get: function () { return this.world.mpxi(this.data.position[0]); }, set: function (value) { this.data.position[0] = this.world.pxmi(value); } }); /** * @name Phaser.Physics.P2.Body#y * @property {number} y - The y coordinate of this Body. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "y", { get: function () { return this.world.mpxi(this.data.position[1]); }, set: function (value) { this.data.position[1] = this.world.pxmi(value); } }); /** * @name Phaser.Physics.P2.Body#id * @property {number} id - The Body ID. Each Body that has been added to the World has a unique ID. * @readonly */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "id", { get: function () { return this.data.id; } }); /** * @name Phaser.Physics.P2.Body#debug * @property {boolean} debug - Enable or disable debug drawing of this body */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "debug", { get: function () { return (this.debugBody !== null); }, set: function (value) { if (value && !this.debugBody) { // This will be added to the global space this.debugBody = new Phaser.Physics.P2.BodyDebug(this.game, this.data); } else if (!value && this.debugBody) { this.debugBody.destroy(); this.debugBody = null; } } }); /** * A Body can be set to collide against the World bounds automatically if this is set to true. Otherwise it will leave the World. * Note that this only applies if your World has bounds! The response to the collision should be managed via CollisionMaterials. * * @name Phaser.Physics.P2.Body#collideWorldBounds * @property {boolean} collideWorldBounds - Should the Body collide with the World bounds? */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "collideWorldBounds", { get: function () { return this._collideWorldBounds; }, set: function (value) { if (value && !this._collideWorldBounds) { this._collideWorldBounds = true; this.updateCollisionMask(); } else if (!value && this._collideWorldBounds) { this._collideWorldBounds = false; this.updateCollisionMask(); } } });
var panelInstance = ( <Panel> 这是一个基本的面板组件。 </Panel> ); React.render(panelInstance, mountNode);
/* * written with Mocha Framework */ should = require('should') BigNumber = require('../').n describe('BigNumber.js', function () { describe('#initialization', function () { it('should create a big number from a number', function () { BigNumber(517).val().should.equal("517"); BigNumber(-517).val().should.equal("-517"); BigNumber(BigNumber(517)).val().should.equal("517"); }), it('should create a big number from an array', function () { BigNumber([5,1,7]).val().should.equal("517"); BigNumber(["+",5,1,7]).val().should.equal("517"); BigNumber(["-",5,1,7]).val().should.equal("-517"); }), it('should create positive or negative numbers from string', function () { BigNumber(517).sign.should.equal(1); BigNumber(-517).sign.should.equal(-1); }), it('should create positive or negative numbers from array', function () { BigNumber(["+",5,1,7]).sign.should.equal(1); BigNumber(["-",5,1,7]).sign.should.equal(-1); }), it('should throw error at object creation', function () { BigNumber("51s7").val().should.equal("Invalid Number"); BigNumber([5, 14, 7, 9]).val().should.equal("Invalid Number"); BigNumber([5, 2, "s", 9]).val().should.equal("Invalid Number"); BigNumber("5s17").val().should.equal("Invalid Number"); BigNumber([5,"s",1,7]).val().should.equal("Invalid Number"); }) }), describe('#compare()', function () { it('should compare 2 numbers', function () { BigNumber(517)._compare().should.equal(0); BigNumber(517)._compare(5170).should.equal(-1); BigNumber(517)._compare(65).should.equal(1); BigNumber(517)._compare(925).should.equal(-1); BigNumber(29100517)._compare(-32500000).should.equal(1); BigNumber(["-",5,3,7,9,4,6])._compare(985).should.equal(-1); BigNumber(9773)._compare(9773).should.equal(0); BigNumber(199773)._compare(199774).should.equal(-1); BigNumber(199773)._compare(199772).should.equal(1); BigNumber(1)._compare(-2).should.equal(1); BigNumber(-24)._compare(-24).should.equal(0); BigNumber(-5)._compare(-4).should.equal(-1); BigNumber(-97)._compare(-12).should.equal(-1); BigNumber(-97)._compare(-102).should.equal(1); }), it('should test lt (less than)', function () { BigNumber(517).lt(518).should.equal(true); BigNumber(517).lt(517).should.equal(false); BigNumber(517).lt(516).should.equal(false); BigNumber(517).lt(516).should.equal(false); BigNumber(517).lt(518).should.equal(true); BigNumber(5).lt(33).should.equal(true); BigNumber(-5).lt(3).should.equal(true); BigNumber(-5).lt(-3).should.equal(true); BigNumber(-5).lt(3).should.equal(true); BigNumber(-5).lt(-7).should.equal(false); BigNumber(-5).lt(-5).should.equal(false); }), it('should test lte (less or equal than)', function () { BigNumber(517).lte(-517).should.equal(false); BigNumber(517).lte(517).should.equal(true); BigNumber(517).lte(518).should.equal(true); BigNumber(-5).lte(5).should.equal(true); BigNumber(-5).lte(-5).should.equal(true); BigNumber(2).lte(-5).should.equal(false); }), it('should test equals', function () { BigNumber(517).equals(516).should.equal(false); BigNumber(-9).equals(-9).should.equal(true); BigNumber(-9).equals(-91).should.equal(false); BigNumber(517).equals(517).should.equal(true); }), it('should test gt (greater than)', function () { BigNumber(517).gt(517).should.equal(false); BigNumber(518).gt(517).should.equal(true); BigNumber(516).gt(517).should.equal(false); BigNumber(-1).gt(9).should.equal(false); BigNumber(-7).gt(-9).should.equal(true); BigNumber(0).gt(-9).should.equal(true); BigNumber(-1).gt(-1).should.equal(false); BigNumber(0).gt(0).should.equal(false); }), it('should test gte (greater or equal than)', function () { BigNumber(-517).gte(517).should.equal(false); BigNumber(517).gte(517).should.equal(true); BigNumber(-517).gte(517).should.equal(false); BigNumber(-517).gte(-517).should.equal(true); BigNumber(32).gte(17).should.equal(true); BigNumber(32).gte(33).should.equal(false); }) }), describe('#plus()', function () { it('should add 2 positive numbers', function () { BigNumber(1).plus(0).val().should.equal("1"); BigNumber(1).plus(1).val().should.equal("2"); BigNumber(8).plus(8).val().should.equal("16"); BigNumber(27).plus(73).val().should.equal("100"); BigNumber(99).plus(10001).val().should.equal("10100"); BigNumber(517).plus().val().should.equal("517"); BigNumber(2).plus(BigNumber(5999)).val().should.equal("6001"); BigNumber(517).plus(0).val().should.equal("517"); BigNumber(517).plus(5).val().should.equal("522"); BigNumber(517).plus(925).val().should.equal("1442"); BigNumber(29100517).plus(925).val().should.equal("29101442"); BigNumber([5,3,7,9,4,6]).plus(985).val().should.equal("538931"); BigNumber(9773).plus(227).val().should.equal("10000"); BigNumber(199773).plus(227).val().should.equal("200000"); }), it('should add 2 numbers', function () { BigNumber(1).plus(-1).val().should.equal("0"); BigNumber(1).plus(-7).val().should.equal("-6"); BigNumber(1).plus(-100).val().should.equal("-99"); BigNumber(-121).plus(-1).val().should.equal("-122"); BigNumber(-121).plus(22).val().should.equal("-99"); BigNumber(-121).plus(1105).val().should.equal("984"); BigNumber(-5).plus(-99).val().should.equal("-104"); }) }), describe('#minus()', function () { it('should subtract 2 positive numbers obtaining a positive number', function () { BigNumber(5).minus().val().should.equal("5"); BigNumber(5).minus(3).val().should.equal("2"); BigNumber(19).minus(17).val().should.equal("2"); BigNumber(57).minus(55).val().should.equal("2"); BigNumber(10000).minus(9999).val().should.equal("1"); BigNumber(10000).minus(10000).val().should.equal("0"); BigNumber(10000).minus(-10000).val().should.equal("20000"); BigNumber(10000).minus(999).val().should.equal("9001"); BigNumber(10000).minus(1).val().should.equal("9999"); BigNumber(2934).minus(999).val().should.equal("1935"); BigNumber(19).minus(0).val().should.equal("19"); BigNumber(10000).minus(227).val().should.equal("9773"); BigNumber(200000).minus(227).val().should.equal("199773"); }), it('should subtract 2 positive numbers obtaining a negative number', function () { BigNumber(5).minus(33).val().should.equal("-28"); BigNumber(5).minus(104).val().should.equal("-99"); BigNumber(0).minus(101).val().should.equal("-101"); }), it('should subtract 2 numbers', function () { BigNumber(55).minus(57).val().should.equal("-2"); BigNumber(5).minus(-33).val().should.equal("38"); BigNumber(-5).minus(98).val().should.equal("-103"); BigNumber(-33).minus(-5).val().should.equal("-28"); BigNumber(-33).minus(-33).val().should.equal("0"); BigNumber(-33).minus(-32).val().should.equal("-1"); BigNumber(-33).minus(-34).val().should.equal("1"); BigNumber(-5).minus(-33).val().should.equal("28"); BigNumber(-5).minus(-3).val().should.equal("-2"); BigNumber(-101).minus(-1010).val().should.equal("909"); BigNumber(-5).minus(99).val().should.equal("-104"); BigNumber(-5).minus(-15).val().should.equal("10"); }) }), describe('#multiply()', function () { it('should multiply 2 positive numbers', function () { BigNumber(5).multiply(0).val().should.equal("0"); BigNumber(0).multiply(5).val().should.equal("0"); BigNumber(243).multiply(1).val().should.equal("243"); BigNumber(243).multiply(2).val().should.equal("486"); BigNumber(5).multiply(2).val().should.equal("10"); BigNumber(5).multiply(100).val().should.equal("500"); BigNumber(100).multiply(5).val().should.equal("500"); BigNumber(54325).multiply(543).val().should.equal("29498475"); BigNumber(1).multiply(100000).val().should.equal("100000"); }), it('should multiply 2 positive numbers', function () { BigNumber(-5).multiply(0).val().should.equal("0"); BigNumber(-1).multiply(-1).val().should.equal("1"); BigNumber(5).multiply(-1).val().should.equal("-5"); BigNumber(-5).multiply(20).val().should.equal("-100"); BigNumber(17).multiply(-12).val().should.equal("-204"); }) }), describe('#divide()', function () { it('should divide 2 positive numbers', function () { BigNumber(5).divide(0).val().should.equal("Invalid Number - Division By Zero"); BigNumber(5).divide(1).val().should.equal("5"); BigNumber(99).divide(5).val().should.equal("19"); BigNumber(7321).divide(153).val().should.equal("47"); BigNumber(919).divide(153).val().should.equal("6"); }), it('should divide 2 numbers', function () { BigNumber(-5).divide(1).val().should.equal("-5"); BigNumber(-5).divide(-1).val().should.equal("5"); BigNumber(5).divide(-1).val().should.equal("-5"); BigNumber(9).divide(2).val().should.equal("4"); BigNumber(17).divide(5).val().should.equal("3"); BigNumber(10).divide(2).val().should.equal("5"); BigNumber(-50).divide(-10).val().should.equal("5"); BigNumber(-50).divide(39).val().should.equal("-1"); BigNumber(99).divide(5).val().should.equal("19"); BigNumber(100).divide(5).val().should.equal("20"); BigNumber(101).divide(5).val().should.equal("20"); BigNumber(104).divide(5).val().should.equal("20"); BigNumber(-17).divide(-9).val().should.equal("1"); BigNumber(-17).divide(3).val().should.equal("-5"); BigNumber(99).divide(-17).val().should.equal("-5"); }), it('should return the division rest', function () { BigNumber(7321).divide(153).rest.val().should.equal("130"); BigNumber(3).divide(2).rest.val().should.equal("1"); BigNumber(9).divide(3).rest.val().should.equal("0"); BigNumber(93).divide(21).rest.val().should.equal("9"); BigNumber(100).divide(53).rest.val().should.equal("47"); }) }), describe('#mod()', function () { it('should return the remainder of 2 numbers division', function () { BigNumber(7321).mod(153).val().should.equal("130"); BigNumber(3).mod(2).val().should.equal("1"); BigNumber(9).mod(3).val().should.equal("0"); BigNumber(93).mod(21).val().should.equal("9"); BigNumber(100).mod(53).val().should.equal("47"); }) }), describe('#pow()', function () { it('should raise a a number to a positive integer power', function () { BigNumber(5).pow(0).val().should.equal("1"); BigNumber(5).pow(1).val().should.equal("5"); BigNumber(5).pow(4).val().should.equal("625"); BigNumber(1).pow(200).val().should.equal("1"); BigNumber(2).pow(2).val().should.equal("4"); BigNumber(2).pow(3).val().should.equal("8"); BigNumber(2).pow(4).val().should.equal("16"); BigNumber(2).pow(5).val().should.equal("32"); BigNumber(2).pow(6).val().should.equal("64"); BigNumber(2).pow(10).val().should.equal("1024"); BigNumber(2).pow(32).val().should.equal("4294967296"); BigNumber(4).pow(3).val().should.equal("64"); BigNumber(999999).pow(30).val().should.equal("999970000434995940027404857494593772964205852910692880044960372786493105240295422519882625422555240236493170372730045000692855852922964200593774857494027404995940000434999970000001"); }) }), describe('#isZero()', function () { it('should test if the big number is zero', function () { BigNumber(517).isZero().should.equal(false); BigNumber(0).isZero().should.equal(true); BigNumber([0]).isZero().should.equal(true); }) }), describe('#abs()', function () { it('should return absolute value of number', function () { BigNumber(517).abs().val().should.equal("517"); BigNumber(-517).abs().val().should.equal("517"); }) }), describe('chainable tests', function () { it('should test random chainable operations', function () { var a = 1970485694, b = 153487287; BigNumber(a).add(1).multiply(BigNumber(b).add(1)).multiply(BigNumber(a).add(2).add(BigNumber(b))).divide(2).val().should.equal("321191979129581791629406140"); BigNumber(5).plus(97).minus(53).plus(434).multiply(5435423).add(321453).multiply(21).div(2).val().should.equal("27569123001"); }) }) })
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _event = require('./event.js'); var _event2 = _interopRequireDefault(_event); var _util = require('./util.js'); var _util2 = _interopRequireDefault(_util); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Props = { check: function check(t, val) { switch (t) { case String: return typeof val === 'string'; case Number: return typeof val === 'number'; case Boolean: return typeof val === 'boolean'; case Function: return typeof val === 'function'; case Object: return (typeof val === 'undefined' ? 'undefined' : _typeof(val)) === 'object'; case Array: return toString.call(val) === '[object Array]'; default: return val instanceof t; } }, build: function build(props) { var rst = {}; if (typeof props === 'string') { rst[props] = {}; } else if (toString.call(props) === '[object Array]') { props.forEach(function (p) { rst[p] = {}; }); } else { Object.keys(props).forEach(function (p) { if (typeof props[p] === 'function') { rst[p] = { type: [props[p]] }; } else if (toString.call(props[p]) === '[object Array]') { rst[p] = { type: props[p] }; } else rst[p] = props[p]; if (rst[p].type && toString.call(rst[p].type) !== '[object Array]') rst[p].type = [rst[p].type]; }); } return rst; }, valid: function valid(props, key, val) { var _this = this; var valid = false; if (props[key]) { if (!props[key].type) { valid = true; } else { return props[key].type.some(function (t) { return _this.check(t, val); }); } } return valid; }, getValue: function getValue(props, key, value) { var rst; if (value !== undefined && this.valid(props, key, value)) { rst = value; } else if (typeof props[key].default === 'function') { rst = props[key].default(); } else rst = props[key].default; return props[key].coerce ? props[key].coerce(rst) : rst; } }; var _class = function () { function _class() { _classCallCheck(this, _class); this.$com = {}; this.$mixins = []; this.$isComponent = true; this.$prefix = ''; this.$mappingProps = {}; this.data = {}; this.methods = {}; } _createClass(_class, [{ key: '$init', value: function $init($wxpage, $root, $parent) { var _this2 = this; var self = this; this.$wxpage = $wxpage; if (this.$isComponent) { this.$root = $root || this.$root; this.$parent = $parent || this.$parent; this.$wxapp = this.$root.$parent.$wxapp; } if (this.props) { this.props = Props.build(this.props); } var k = void 0, defaultData = {}; var props = this.props; var key = void 0, val = void 0, binded = void 0; var inRepeat = false, repeatKey = void 0; if (this.$initData === undefined) { this.$initData = _util2.default.$copy(this.data, true); } else { this.data = _util2.default.$copy(this.$initData, true); } if (this.$props) { for (key in this.$props) { for (binded in this.$props[key]) { if (/\.sync$/.test(binded)) { if (!this.$mappingProps[this.$props[key][binded]]) this.$mappingProps[this.$props[key][binded]] = {}; this.$mappingProps[this.$props[key][binded]][key] = binded.substring(7, binded.length - 5); } } } } if (props) { for (key in props) { val = undefined; if ($parent && $parent.$props && $parent.$props[this.$name]) { val = $parent.$props[this.$name][key]; binded = $parent.$props[this.$name]['v-bind:' + key + '.once'] || $parent.$props[this.$name]['v-bind:' + key + '.sync']; if (binded) { if ((typeof binded === 'undefined' ? 'undefined' : _typeof(binded)) === 'object') { (function () { props[key].repeat = binded.for; inRepeat = true; var bindfor = binded.for, binddata = $parent; bindfor.split('.').forEach(function (t) { binddata = binddata[t]; }); repeatKey = Object.keys(binddata)[0]; if (!_this2.$mappingProps[key]) _this2.$mappingProps[key] = {}; _this2.$mappingProps[key]['parent'] = { mapping: binded.for, from: key }; })(); } else { val = $parent[binded]; if (props[key].twoWay) { if (!this.$mappingProps[key]) this.$mappingProps[key] = {}; this.$mappingProps[key]['parent'] = binded; } } } } if (!this.data[key] && !props[key].repeat) { val = Props.getValue(props, key, val); this.data[key] = val; } } } for (k in this.data) { defaultData['' + this.$prefix + k] = this.data[k]; this[k] = this.data[k]; } this.$data = _util2.default.$copy(this.data, true); if (inRepeat) this.$setIndex(repeatKey); if (this.computed) { for (k in this.computed) { var fn = this.computed[k]; defaultData['' + this.$prefix + k] = fn.call(this); this[k] = _util2.default.$copy(defaultData['' + this.$prefix + k], true); } } this.setData(defaultData); var coms = Object.getOwnPropertyNames(this.$com); if (coms.length) { coms.forEach(function (name) { _this2.$com[name].$init(_this2.getWxPage(), $root, _this2); _this2.$com[name].onLoad && _this2.$com[name].onLoad(); _this2.$com[name].$mixins.forEach(function (mix) { mix['onLoad'] && mix['onLoad'].call(_this2.$com[name]); }); _this2.$com[name].$apply(); }); } } }, { key: '$initMixins', value: function $initMixins() { var _this3 = this; if (this.mixins) { if (typeof this.mixins === 'function') { this.mixins = [this.mixins]; } } else { this.mixins = []; } this.mixins.forEach(function (mix) { var inst = new mix(); inst.$init(_this3); _this3.$mixins.push(inst); }); } }, { key: 'onLoad', value: function onLoad() {} }, { key: 'setData', value: function setData(k, v) { if (typeof k === 'string') { if (v) { var tmp = {}; tmp[k] = v; k = tmp; } else { var _tmp = {}; _tmp[k] = this.data['' + k]; k = _tmp; } return this.$wxpage.setData(k); } var t = null, reg = new RegExp('^' + this.$prefix.replace(/\$/g, '\\$'), 'ig'); for (t in k) { var noPrefix = t.replace(reg, ''); this.$data[noPrefix] = _util2.default.$copy(k[t], true); } return this.$wxpage.setData(k); } }, { key: 'getWxPage', value: function getWxPage() { return this.$wxpage; } }, { key: 'getCurrentPages', value: function getCurrentPages() { return this.$wxpage.getCurrentPages(); } }, { key: '$setIndex', value: function $setIndex(index) { var _this4 = this; if (this.$index === index) return; this.$index = index; var props = this.props, $parent = this.$parent; var key = void 0, val = void 0, binded = void 0; if (props) { for (key in props) { val = undefined; if ($parent && $parent.$props && $parent.$props[this.$name]) { val = $parent.$props[this.$name][key]; binded = $parent.$props[this.$name]['v-bind:' + key + '.once'] || $parent.$props[this.$name]['v-bind:' + key + '.sync']; if (binded) { if ((typeof binded === 'undefined' ? 'undefined' : _typeof(binded)) === 'object') { (function () { var bindfor = binded.for, binddata = $parent; bindfor.split('.').forEach(function (t) { binddata = binddata[t]; }); val = binddata[index]; _this4.$index = index; _this4.data[key] = val; _this4[key] = val; _this4.$data[key] = _util2.default.$copy(_this4[key], true); })(); } } } } for (key in this.$com) { this.$com[key].$index = undefined; } } } }, { key: '$getComponent', value: function $getComponent(com) { var _this5 = this; if (typeof com === 'string') { if (com.indexOf('/') === -1) { return this.$com[com]; } else if (com === '/') { return this.$parent; } else { var path = com.split('/'); path.forEach(function (s, i) { if (i === 0) { if (s === '') { com = _this5.$root; } else if (s === '.') { com = _this5; } else if (s === '..') { com = _this5.$parent; } else { com = _this5.$getComponent(s); } } else if (s) { com = com.$com[s]; } }); } } return (typeof com === 'undefined' ? 'undefined' : _typeof(com)) !== 'object' ? null : com; } }, { key: '$invoke', value: function $invoke(com, method) { com = this.$getComponent(com); if (!com) { throw new Error('Invalid path: ' + com); } var fn = com.methods ? com.methods[method] : ''; for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } if (typeof fn === 'function') { var $evt = new _event2.default('', this, 'invoke'); var rst = fn.apply(com, args.concat($evt)); com.$apply(); return rst; } else { fn = com[method]; } if (typeof fn === 'function') { return fn.apply(com, args); } else { throw new Error('Invalid method: ' + method); } } }, { key: '$broadcast', value: function $broadcast(evtName) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } var com = this; var $evt = typeof evtName === 'string' ? new _event2.default(evtName, this, 'broadcast') : $evt; var queue = [com]; while (queue.length && $evt.active) { var current = queue.shift(); var _loop = function _loop(_c) { _c = current.$com[_c]; queue.push(_c); var fn = getEventsFn(_c, evtName); if (fn) { _c.$apply(function () { fn.apply(_c, args.concat($evt)); }); } if (!$evt.active) return 'break'; c = _c; }; for (var c in current.$com) { var _ret3 = _loop(c); if (_ret3 === 'break') break; } } } }, { key: '$emit', value: function $emit(evtName) { var _this6 = this; for (var _len3 = arguments.length, args = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { args[_key3 - 1] = arguments[_key3]; } var com = this; var source = this; var $evt = new _event2.default(evtName, source, 'emit'); if (this.$parent.$events && this.$parent.$events[this.$name]) { var method = this.$parent.$events[this.$name]['v-on:' + evtName]; if (method && this.$parent.methods) { var _fn = this.$parent.methods[method]; if (typeof _fn === 'function') { this.$parent.$apply(function () { _fn.apply(_this6.$parent, args.concat($evt)); }); return; } else { throw new Error('Invalid method from emit, component is ' + this.$parent.$name + ', method is ' + method + '. Make sure you defined it already.\n'); } } } var _loop2 = function _loop2() { var comContext = com; var fn = getEventsFn(comContext, evtName); fn && comContext.$apply(function () { fn.apply(comContext, args.concat($evt)); }); com = comContext.$parent; }; while (com && com.$isComponent !== undefined && $evt.active) { _loop2(); } } }, { key: '$apply', value: function $apply(fn) { if (typeof fn === 'function') { fn.call(this); this.$apply(); } else { if (this.$$phase) { this.$$phase = '$apply'; } else { this.$digest(); } } } }, { key: '$digest', value: function $digest() { var _this7 = this; var k = void 0; var originData = this.$data; this.$$phase = '$digest'; while (this.$$phase) { var readyToSet = {}; for (k in originData) { if (!_util2.default.$isEqual(this[k], originData[k])) { if (this.watch) { if (this.watch[k]) { if (typeof this.watch[k] === 'function') { this.watch[k].call(this, this[k], originData[k]); } else if (typeof this.watch[k] === 'string' && typeof this.methods[k] === 'function') { this.methods[k].call(this, this[k], originData[k]); } } } readyToSet[this.$prefix + k] = this[k]; this.data[k] = this[k]; originData[k] = _util2.default.$copy(this[k], true); if (this.$mappingProps[k]) { Object.keys(this.$mappingProps[k]).forEach(function (changed) { var mapping = _this7.$mappingProps[k][changed]; if ((typeof mapping === 'undefined' ? 'undefined' : _typeof(mapping)) === 'object') { _this7.$parent.$apply(); } else if (changed === 'parent' && !_util2.default.$isEqual(_this7.$parent.$data[mapping], _this7[k])) { _this7.$parent[mapping] = _this7[k]; _this7.$parent.data[mapping] = _this7[k]; _this7.$parent.$apply(); } else if (changed !== 'parent' && !_util2.default.$isEqual(_this7.$com[changed].$data[mapping], _this7[k])) { _this7.$com[changed][mapping] = _this7[k]; _this7.$com[changed].data[mapping] = _this7[k]; _this7.$com[changed].$apply(); } }); } } } if (Object.keys(readyToSet).length) { if (this.computed) { for (k in this.computed) { var _fn2 = this.computed[k], val = _fn2.call(this); if (!_util2.default.$isEqual(this[k], val)) { readyToSet[this.$prefix + k] = val; this[k] = _util2.default.$copy(val, true); } } } this.setData(readyToSet); } this.$$phase = this.$$phase === '$apply' ? '$digest' : false; } } }]); return _class; }(); exports.default = _class; function getEventsFn(comContext, evtName) { var fn = comContext.events ? comContext.events[evtName] : undefined; var typeFn = typeof fn === 'undefined' ? 'undefined' : _typeof(fn); var fnFn = void 0; if (typeFn === 'string') { var method = comContext.methods && comContext.methods[fn]; if (typeof method === 'function') { fnFn = method; } } else if (typeFn === 'function') { fnFn = fn; } return fnFn; } //# sourceMappingURL=component.js.map
… i0.ɵɵproperty("event", ctx.$event);
htmx.defineExtension("morphdom-swap",{isInlineSwap:function(o){return"morphdom"===o},handleSwap:function(o,n,e){if("morphdom"===o)return e.nodeType===Node.DOCUMENT_FRAGMENT_NODE?morphdom(n,e.firstElementChild):morphdom(n,e.outerHTML),[n]}});
var _createMaxMinBy = require('./internal/_createMaxMinBy'); var _curry2 = require('./internal/_curry2'); var _lt = require('./internal/_lt'); /** * Determines the smallest of a list of items as determined by pairwise comparisons from the supplied comparator * Note that this will return undefined if supplied an empty list. * * @func * @memberOf R * @category Math * @sig (a -> Number) -> [a] -> a * @param {Function} keyFn A comparator function for elements in the list * @param {Array} list A list of comparable elements * @see R.min * @return {*} The greatest element in the list. `undefined` if the list is empty. * @example * * function cmp(obj) { return obj.x; } * var a = {x: 1}, b = {x: 2}, c = {x: 3}; * R.minBy(cmp, [a, b, c]); //=> {x: 1} */ module.exports = _curry2(_createMaxMinBy(_lt));
var _ = require('lodash'); var assert = require('chai').assert; var sinon = require('sinon'); var React = require('react/addons'); var Typeahead = require('../src/typeahead'); var TypeaheadOption = require('../src/typeahead/option'); var TypeaheadSelector = require('../src/typeahead/selector'); var Keyevent = require('../src/keyevent'); var TestUtils = React.addons.TestUtils; function simulateTextInput(component, value) { var node = component.refs.entry.getDOMNode(); node.value = value; TestUtils.Simulate.change(node); return TestUtils.scryRenderedComponentsWithType(component, TypeaheadOption); } var BEATLES = ['John', 'Paul', 'George', 'Ringo']; var BEATLES_COMPLEX = [ { firstName: 'John', lastName: 'Lennon', nameWithTitle: 'John Winston Ono Lennon MBE' }, { firstName: 'Paul', lastName: 'McCartney', nameWithTitle: 'Sir James Paul McCartney MBE' }, { firstName: 'George', lastName: 'Harrison', nameWithTitle: 'George Harrison MBE' }, { firstName: 'Ringo', lastName: 'Starr', nameWithTitle: 'Richard Starkey Jr. MBE' } ]; describe('Typeahead Component', function() { describe('sanity', function() { beforeEach(function() { this.component = TestUtils.renderIntoDocument(<Typeahead options={ BEATLES } />); }); it('should fuzzy search and render matching results', function() { // input value: num of expected results var testplan = { 'o': 3, 'pa': 1, 'Grg': 1, 'Ringo': 1, 'xxx': 0 }; _.each(testplan, function(expected, value) { var results = simulateTextInput(this.component, value); assert.equal(results.length, expected, 'Text input: ' + value); }, this); }); it('does not change the url hash when clicking on options', function() { var results = simulateTextInput(this.component, 'o'); var firstResult = results[0]; var anchor = TestUtils.findRenderedDOMComponentWithTag(firstResult, 'a'); var href = anchor.getDOMNode().getAttribute('href'); assert.notEqual(href, '#'); }); describe('keyboard controls', function() { it('down arrow + return selects an option', function() { var results = simulateTextInput(this.component, 'o'); var secondItem = results[1].getDOMNode().innerText; var node = this.component.refs.entry.getDOMNode(); TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_DOWN }); TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_DOWN }); TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_RETURN }); assert.equal(node.value, secondItem); // Poor Ringo }); it('up arrow + return navigates and selects an option', function() { var results = simulateTextInput(this.component, 'o'); var firstItem = results[0].getDOMNode().innerText; var node = this.component.refs.entry.getDOMNode(); TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_DOWN }); TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_DOWN }); TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_UP }); TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_RETURN }); assert.equal(node.value, firstItem); }); it('escape clears selection', function() { var results = simulateTextInput(this.component, 'o'); var firstItem = results[0].getDOMNode(); var node = this.component.refs.entry.getDOMNode(); TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_DOWN }); assert.ok(firstItem.classList.contains('hover')); TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_ESCAPE }); assert.notOk(firstItem.classList.contains('hover')); }); it('tab to choose first item', function() { var results = simulateTextInput(this.component, 'o'); var itemText = results[0].getDOMNode().innerText; var node = this.component.refs.entry.getDOMNode(); TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_TAB }); assert.equal(node.value, itemText); }); it('tab to selected current item', function() { var results = simulateTextInput(this.component, 'o'); var itemText = results[1].getDOMNode().innerText; var node = this.component.refs.entry.getDOMNode(); TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_DOWN }); TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_DOWN }); TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_TAB }); assert.equal(node.value, itemText); }); it('tab on no selection should not be undefined', function() { var results = simulateTextInput(this.component, 'oz'); assert(results.length == 0); var node = this.component.refs.entry.getDOMNode(); TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_TAB }); assert.equal("oz", node.value); }); it('should set hover', function() { var results = simulateTextInput(this.component, 'o'); var node = this.component.refs.entry.getDOMNode(); TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_DOWN }); TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_DOWN }); assert.equal(true, results[1].props.hover); }); }); describe('component functions', function() { beforeEach(function() { this.sinon = sinon.sandbox.create(); }); afterEach(function() { this.sinon.restore(); }); it('focuses the typeahead', function() { var node = React.findDOMNode(this.component.refs.entry); this.sinon.spy(node, 'focus'); this.component.focus(); assert.equal(node.focus.calledOnce, true); }); }); }); describe('props', function() { context('maxVisible', function() { it('limits the result set based on the maxVisible option', function() { var component = TestUtils.renderIntoDocument(<Typeahead options={ BEATLES } maxVisible={ 1 } ></Typeahead>); var results = simulateTextInput(component, 'o'); assert.equal(results.length, 1); }); }); context('displayOption', function() { it('renders simple options verbatim when not specified', function() { var component = TestUtils.renderIntoDocument(<Typeahead options={ BEATLES } />); var results = simulateTextInput(component, 'john'); assert.equal(results[0].getDOMNode().textContent, 'John'); }); it('renders custom options when specified as a string', function() { var component = TestUtils.renderIntoDocument(<Typeahead options={ BEATLES_COMPLEX } filterOption='firstName' displayOption='nameWithTitle' />); var results = simulateTextInput(component, 'john'); assert.equal(results[0].getDOMNode().textContent, 'John Winston Ono Lennon MBE'); }); it('renders custom options when specified as a function', function() { var component = TestUtils.renderIntoDocument(<Typeahead options={ BEATLES_COMPLEX } filterOption='firstName' displayOption={ function(o, i) { return i + ' ' + o.firstName + ' ' + o.lastName; } } />); var results = simulateTextInput(component, 'john'); assert.equal(results[0].getDOMNode().textContent, '0 John Lennon'); }); }); context('allowCustomValues', function() { beforeEach(function() { this.sinon = sinon.sandbox.create() this.selectSpy = this.sinon.spy(); this.component = TestUtils.renderIntoDocument(<Typeahead options={BEATLES} allowCustomValues={3} onOptionSelected={this.selectSpy} ></Typeahead>); }); afterEach(function() { this.sinon.restore(); }) it('should not display custom value if input length is less than entered', function() { var input = this.component.refs.entry.getDOMNode(); input.value = "zz"; TestUtils.Simulate.change(input); var results = TestUtils.scryRenderedComponentsWithType(this.component, TypeaheadOption); assert.equal(0, results.length); assert.equal(false, this.selectSpy.called); }); it('should display custom value if input exceeds props.allowCustomValues', function() { var input = this.component.refs.entry.getDOMNode(); input.value = "ZZZ"; TestUtils.Simulate.change(input); var results = TestUtils.scryRenderedComponentsWithType(this.component, TypeaheadOption); assert.equal(1, results.length); assert.equal(false, this.selectSpy.called); }); it('should call onOptionSelected when selecting from options', function() { var results = simulateTextInput(this.component, 'o'); var firstItem = results[0].getDOMNode().innerText; var node = this.component.refs.entry.getDOMNode(); TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_DOWN }); TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_DOWN }); TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_UP }); TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_RETURN }); assert.equal(true, this.selectSpy.called); assert(this.selectSpy.calledWith(firstItem)); }) it('should call onOptionSelected when custom value is selected', function() { var input = this.component.refs.entry.getDOMNode(); input.value = "ZZZ"; TestUtils.Simulate.change(input); TestUtils.Simulate.keyDown(input, { keyCode: Keyevent.DOM_VK_DOWN }); TestUtils.Simulate.keyDown(input, { keyCode: Keyevent.DOM_VK_RETURN }); assert.equal(true, this.selectSpy.called); assert(this.selectSpy.calledWith(input.value)); }) it('should add hover prop to customValue', function() { var input = this.component.refs.entry.getDOMNode(); input.value = "ZZZ"; TestUtils.Simulate.change(input); var results = TestUtils.scryRenderedComponentsWithType(this.component, TypeaheadOption); TestUtils.Simulate.keyDown(input, { keyCode: Keyevent.DOM_VK_DOWN }); assert.equal(true, results[0].props.hover) }) }); context('customClasses', function() { before(function() { var customClasses = { input: 'topcoat-text-input', results: 'topcoat-list__container', listItem: 'topcoat-list__item', listAnchor: 'topcoat-list__link', hover: 'topcoat-list__item-active' }; this.component = TestUtils.renderIntoDocument(<Typeahead options={ BEATLES } customClasses={ customClasses } ></Typeahead>); simulateTextInput(this.component, 'o'); }); it('adds a custom class to the typeahead input', function() { var input = this.component.refs.entry.getDOMNode(); assert.isTrue(input.classList.contains('topcoat-text-input')); }); it('adds a custom class to the results component', function() { var results = TestUtils.findRenderedComponentWithType(this.component, TypeaheadSelector).getDOMNode(); assert.isTrue(results.classList.contains('topcoat-list__container')); }); it('adds a custom class to the list items', function() { var typeaheadOptions = TestUtils.scryRenderedComponentsWithType(this.component, TypeaheadOption); var listItem = typeaheadOptions[1].getDOMNode(); assert.isTrue(listItem.classList.contains('topcoat-list__item')); }); it('adds a custom class to the option anchor tags', function() { var typeaheadOptions = TestUtils.scryRenderedComponentsWithType(this.component, TypeaheadOption); var listAnchor = typeaheadOptions[1].refs.anchor.getDOMNode(); assert.isTrue(listAnchor.classList.contains('topcoat-list__link')); }); it('adds a custom class to the list items when active', function() { var typeaheadOptions = TestUtils.scryRenderedComponentsWithType(this.component, TypeaheadOption); var node = this.component.refs.entry.getDOMNode(); TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_DOWN }); var listItem = typeaheadOptions[0]; var domListItem = listItem.getDOMNode(); assert.isTrue(domListItem.classList.contains('topcoat-list__item-active')); }); }); context('defaultValue', function() { it('should perform an initial search if a default value is provided', function() { var component = TestUtils.renderIntoDocument(<Typeahead options={ BEATLES } defaultValue={ 'o' } />); var results = TestUtils.scryRenderedComponentsWithType(component, TypeaheadOption); assert.equal(results.length, 3); }); }); context('value', function() { it('should set input value', function() { var component = TestUtils.renderIntoDocument(<Typeahead options={ BEATLES } value={ 'John' } />); var input = component.refs.entry.getDOMNode(); assert.equal(input.value, 'John'); }); }); context('onKeyDown', function() { it('should bind to key events on the input', function() { var component = TestUtils.renderIntoDocument(<Typeahead options={ BEATLES } onKeyDown={ function(e) { assert.equal(e.keyCode, 87); } } />); var input = component.refs.entry.getDOMNode(); TestUtils.Simulate.keyDown(input, { keyCode: 87 }); }); }); context('onKeyUp', function() { it('should bind to key events on the input', function() { var component = TestUtils.renderIntoDocument(<Typeahead options={ BEATLES } onKeyUp={ function(e) { assert.equal(e.keyCode, 87); } } />); var input = component.refs.entry.getDOMNode(); TestUtils.Simulate.keyUp(input, { keyCode: 87 }); }); }); context('inputProps', function() { it('should forward props to the input element', function() { var component = TestUtils.renderIntoDocument(<Typeahead options={ BEATLES } inputProps={{ autoCorrect: 'off' }} />); var input = component.refs.entry; assert.equal(input.props.autoCorrect, 'off'); }); }); context('defaultClassNames', function() { it('should remove default classNames when this prop is specified and false', function() { var component = TestUtils.renderIntoDocument(<Typeahead options={ BEATLES } defaultClassNames={false} />); simulateTextInput(component, 'o'); assert.notOk(component.getDOMNode().classList.contains("typeahead")); assert.notOk(component.refs.sel.getDOMNode().classList.contains("typeahead-selector")); }); }); context('filterOption', function() { var FN_TEST_PLANS = [ { name: 'accepts everything', fn: function() { return true; }, input: 'xxx', output: 4 }, { name: 'rejects everything', fn: function() { return false; }, input: 'o', output: 0 } ]; _.each(FN_TEST_PLANS, function(testplan) { it('should filter with a custom function that ' + testplan.name, function() { var component = TestUtils.renderIntoDocument(<Typeahead options={ BEATLES } filterOption={ testplan.fn } />); var results = simulateTextInput(component, testplan.input); assert.equal(results.length, testplan.output); }); }); var STRING_TEST_PLANS = { 'o': 3, 'pa': 1, 'Grg': 1, 'Ringo': 1, 'xxx': 0 }; it('should filter using fuzzy matching on the provided field name', function() { var component = TestUtils.renderIntoDocument(<Typeahead options={ BEATLES_COMPLEX } filterOption='firstName' displayOption='firstName' />); _.each(STRING_TEST_PLANS, function(expected, value) { var results = simulateTextInput(component, value); assert.equal(results.length, expected, 'Text input: ' + value); }, this); }); }); context('formInputOption', function() { var FORM_INPUT_TEST_PLANS = [ { name: 'uses simple options verbatim when not specified', props: { options: BEATLES }, output: 'John' }, { name: 'defaults to the display string when not specified', props: { options: BEATLES_COMPLEX, filterOption: 'firstName', displayOption: 'nameWithTitle' }, output: 'John Winston Ono Lennon MBE' }, { name: 'uses custom options when specified as a string', props: { options: BEATLES_COMPLEX, filterOption: 'firstName', displayOption: 'nameWithTitle', formInputOption: 'lastName' }, output: 'Lennon' }, { name: 'uses custom optinos when specified as a function', props: { options: BEATLES_COMPLEX, filterOption: 'firstName', displayOption: 'nameWithTitle', formInputOption: function(o, i) { return o.firstName + ' ' + o.lastName; } }, output: 'John Lennon' } ]; _.each(FORM_INPUT_TEST_PLANS, function(testplan) { it(testplan.name, function() { var component = TestUtils.renderIntoDocument(<Typeahead {...testplan.props} name='beatles' />); var results = simulateTextInput(component, 'john'); var node = component.refs.entry.getDOMNode(); TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_DOWN }); TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_RETURN }); assert.equal(component.state.selection, testplan.output); }); }); }); context('customListComponent', function() { before(function() { ListComponent = React.createClass({ render: function() { return <div></div>; } }); this.ListComponent = ListComponent; }) beforeEach(function() { this.component = TestUtils.renderIntoDocument( <Typeahead options={ BEATLES } customListComponent={this.ListComponent}/> ); }); it('should not show the customListComponent when the input is empty', function() { var results = TestUtils.scryRenderedComponentsWithType(this.component, this.ListComponent); assert.equal(0, results.length); }); it('should show the customListComponent when the input is not empty', function() { var input = this.component.refs.entry.getDOMNode(); input.value = "o"; TestUtils.Simulate.change(input); var results = TestUtils.scryRenderedComponentsWithType(this.component, this.ListComponent); assert.equal(1, results.length); }); it('should no longer show the customListComponent after an option has been selected', function() { var input = this.component.refs.entry.getDOMNode(); input.value = "o"; TestUtils.Simulate.change(input); TestUtils.Simulate.keyDown(input, { keyCode: Keyevent.DOM_VK_TAB }); var results = TestUtils.scryRenderedComponentsWithType(this.component, this.ListComponent); assert.equal(0, results.length); }); }); context('textarea', function() { it('should render a <textarea> input', function() { var component = TestUtils.renderIntoDocument(<Typeahead options={ BEATLES } textarea={ true } />); var input = component.refs.entry.getDOMNode(); assert.equal(input.tagName.toLowerCase(), 'textarea'); }); it('should render a <input> input', function() { var component = TestUtils.renderIntoDocument(<Typeahead options={ BEATLES } />); var input = component.refs.entry.getDOMNode(); assert.equal(input.tagName.toLowerCase(), 'input'); }); }) }); });
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'image', 'sr', { alertUrl: 'Унесите УРЛ слике', alt: 'Алтернативни текст', border: 'Оквир', btnUpload: 'Пошаљи на сервер', button2Img: 'Да ли желите да промените одабрану слику дугмета као једноставну слику?', hSpace: 'HSpace', img2Button: 'Да ли желите да промените одабрану слику у слику дугмета?', infoTab: 'Инфо слике', linkTab: 'Линк', lockRatio: 'Закључај однос', menu: 'Особине слика', resetSize: 'Ресетуј величину', title: 'Особине слика', titleButton: 'Особине дугмета са сликом', upload: 'Пошаљи', urlMissing: 'Недостаје УРЛ слике.', vSpace: 'VSpace', validateBorder: 'Ивица треба да буде цифра.', validateHSpace: 'HSpace треба да буде цифра.', validateVSpace: 'VSpace треба да буде цифра.' } );
/* This file is part of Ext JS 4 Copyright (c) 2011 Sencha Inc Contact: http://www.sencha.com/contact GNU General Public License Usage This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file. Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact. */ Ext.require([ 'Ext.form.field.ComboBox', 'Ext.form.FieldSet', 'Ext.tip.QuickTipManager', 'Ext.data.*' ]); Ext.onReady(function() { Ext.tip.QuickTipManager.init(); // Define the model for a State Ext.define('State', { extend: 'Ext.data.Model', fields: [ {type: 'string', name: 'abbr'}, {type: 'string', name: 'name'}, {type: 'string', name: 'slogan'} ] }); // The data for all states var states = [ {"abbr":"AL","name":"Alabama","slogan":"The Heart of Dixie"}, {"abbr":"AK","name":"Alaska","slogan":"The Land of the Midnight Sun"}, {"abbr":"AZ","name":"Arizona","slogan":"The Grand Canyon State"}, {"abbr":"AR","name":"Arkansas","slogan":"The Natural State"}, {"abbr":"CA","name":"California","slogan":"The Golden State"}, {"abbr":"CO","name":"Colorado","slogan":"The Mountain State"}, {"abbr":"CT","name":"Connecticut","slogan":"The Constitution State"}, {"abbr":"DE","name":"Delaware","slogan":"The First State"}, {"abbr":"DC","name":"District of Columbia","slogan":"The Nation's Capital"}, {"abbr":"FL","name":"Florida","slogan":"The Sunshine State"}, {"abbr":"GA","name":"Georgia","slogan":"The Peach State"}, {"abbr":"HI","name":"Hawaii","slogan":"The Aloha State"}, {"abbr":"ID","name":"Idaho","slogan":"Famous Potatoes"}, {"abbr":"IL","name":"Illinois","slogan":"The Prairie State"}, {"abbr":"IN","name":"Indiana","slogan":"The Hospitality State"}, {"abbr":"IA","name":"Iowa","slogan":"The Corn State"}, {"abbr":"KS","name":"Kansas","slogan":"The Sunflower State"}, {"abbr":"KY","name":"Kentucky","slogan":"The Bluegrass State"}, {"abbr":"LA","name":"Louisiana","slogan":"The Bayou State"}, {"abbr":"ME","name":"Maine","slogan":"The Pine Tree State"}, {"abbr":"MD","name":"Maryland","slogan":"Chesapeake State"}, {"abbr":"MA","name":"Massachusetts","slogan":"The Spirit of America"}, {"abbr":"MI","name":"Michigan","slogan":"Great Lakes State"}, {"abbr":"MN","name":"Minnesota","slogan":"North Star State"}, {"abbr":"MS","name":"Mississippi","slogan":"Magnolia State"}, {"abbr":"MO","name":"Missouri","slogan":"Show Me State"}, {"abbr":"MT","name":"Montana","slogan":"Big Sky Country"}, {"abbr":"NE","name":"Nebraska","slogan":"Beef State"}, {"abbr":"NV","name":"Nevada","slogan":"Silver State"}, {"abbr":"NH","name":"New Hampshire","slogan":"Granite State"}, {"abbr":"NJ","name":"New Jersey","slogan":"Garden State"}, {"abbr":"NM","name":"New Mexico","slogan":"Land of Enchantment"}, {"abbr":"NY","name":"New York","slogan":"Empire State"}, {"abbr":"NC","name":"North Carolina","slogan":"First in Freedom"}, {"abbr":"ND","name":"North Dakota","slogan":"Peace Garden State"}, {"abbr":"OH","name":"Ohio","slogan":"The Heart of it All"}, {"abbr":"OK","name":"Oklahoma","slogan":"Oklahoma is OK"}, {"abbr":"OR","name":"Oregon","slogan":"Pacific Wonderland"}, {"abbr":"PA","name":"Pennsylvania","slogan":"Keystone State"}, {"abbr":"RI","name":"Rhode Island","slogan":"Ocean State"}, {"abbr":"SC","name":"South Carolina","slogan":"Nothing Could be Finer"}, {"abbr":"SD","name":"South Dakota","slogan":"Great Faces, Great Places"}, {"abbr":"TN","name":"Tennessee","slogan":"Volunteer State"}, {"abbr":"TX","name":"Texas","slogan":"Lone Star State"}, {"abbr":"UT","name":"Utah","slogan":"Salt Lake State"}, {"abbr":"VT","name":"Vermont","slogan":"Green Mountain State"}, {"abbr":"VA","name":"Virginia","slogan":"Mother of States"}, {"abbr":"WA","name":"Washington","slogan":"Green Tree State"}, {"abbr":"WV","name":"West Virginia","slogan":"Mountain State"}, {"abbr":"WI","name":"Wisconsin","slogan":"America's Dairyland"}, {"abbr":"WY","name":"Wyoming","slogan":"Like No Place on Earth"} ]; // The data store holding the states; shared by each of the ComboBox examples below var store = Ext.create('Ext.data.Store', { model: 'State', data: states }); // Simple ComboBox using the data store var simpleCombo = Ext.create('Ext.form.field.ComboBox', { fieldLabel: 'Select a single state', renderTo: 'simpleCombo', displayField: 'name', width: 320, labelWidth: 130, store: store, queryMode: 'local', typeAhead: true }); // ComboBox with a custom item template var customTplCombo = Ext.create('Ext.form.field.ComboBox', { fieldLabel: 'Select a single state', renderTo: 'customTplCombo', displayField: 'name', width: 320, labelWidth: 130, store: store, queryMode: 'local', listConfig: { getInnerTpl: function() { return '<div data-qtip="{name}. {slogan}">{name} ({abbr})</div>'; } } }); // ComboBox with multiple selection enabled var multiCombo = Ext.create('Ext.form.field.ComboBox', { fieldLabel: 'Select multiple states', renderTo: 'multiSelectCombo', multiSelect: true, displayField: 'name', width: 320, labelWidth: 130, store: store, queryMode: 'local' }); // ComboBox transformed from HTML select var transformed = Ext.create('Ext.form.field.ComboBox', { typeAhead: true, transform: 'stateSelect', width: 135, forceSelection: true }); ////// Collapsible code panels; ignore: ///// Ext.select('pre.code').each(function(pre) { Ext.create('Ext.form.FieldSet', { contentEl: pre, renderTo: pre.parent(), title: 'View code for this example', collapsible: true, collapsed: true }) }); });
var models = require('../../models') var mongoose = require('mongoose') var express = require('express') var jobRunner = require('../../runner'); exports.unauthorized = function (app, template) { template([ 'view' ], { prefix: 'task' }); } exports.httpRouter = function (app) { } exports.router = function (app) { var task = express.Router(); task.get('/', view) .delete('/', remove) app.param('task_id', get) app.use('/playbook/:playbook_id/job/:job_id/task/:task_id', task); } function get (req, res, next, id) { models.Task.findOne({ _id: id }).exec(function (err, task) { if (err || !task) { return res.send(404); } req.task = task; next(); }); } function view (req, res) { res.send(req.task); } function remove (req, res) { if (req.task.status == 'Running') { return res.send(400, 'Job is Running.'); } jobRunner.queue.pause(); for (var i = 0; i < jobRunner.queue.tasks.length; i++) { if (jobRunner.queue.tasks[i].data._id.toString() == req.task._id.toString()) { // This is our task jobRunner.queue.tasks.splice(i, 1); break; } } jobRunner.queue.resume(); req.task.remove(function (err) { res.send(201); }) }
/** * Module for working with file. Shall implement * IEmmetFile interface. * * Since implementation of this module depends * greatly on current runtime, this module must be * initialized with actual implementation first * before use. E.g. * require('./plugin/file')({ * read: function() {...} * }) * * By default, this module provides Node.JS implementation */ if (typeof module === 'object' && typeof define !== 'function') { var define = function (factory) { module.exports = factory(require, exports, module); }; } define(function(require, exports, module) { var utils = require('../utils/common'); // hide it from Require.JS parser (function(r) { if (typeof define === 'undefined' || !define.amd) { try { fs = r('fs'); path = r('path'); } catch(e) {} } })(require); // module is a function that can extend itself module.exports = function(obj) { if (obj) { utils.extend(module.exports, obj); } }; function bts(bytes) { var out = []; for (var i = 0, il = bytes.length; i < il; i++) { out.push(String.fromCharCode(bytes[i])); } return out.join(''); } function isURL(path) { var re = /^https?:\/\//; return re.test(path); } return utils.extend(module.exports, { _parseParams: function(args) { var params = { path: args[0], size: 0 }; args = utils.toArray(args, 1); params.callback = args[args.length - 1]; args = args.slice(0, args.length - 1); if (args.length) { params.size = args[0]; } return params; }, _read: function(params, callback) { if (isURL(params.path)) { var req = require(/^https:/.test(params.path) ? 'https' : 'http').get(params.path, function(res) { var bufs = []; var totalLength = 0; var finished = false; res .on('data', function(chunk) { totalLength += chunk.length; bufs.push(chunk); if (params.size && totalLength >= params.size) { finished = true; callback(null, Buffer.concat(bufs)); req.abort(); } }) .on('end', function() { if (!finished) { finished = true; callback(null, Buffer.concat(bufs)); } }); }).on('error', callback); } else { if (params.size) { var fd = fs.openSync(params.path, 'r'); var buf = new Buffer(params.size); fs.read(fd, buf, 0, params.size, null, function(err, bytesRead) { callback(err, buf) }); } else { callback(null, fs.readFileSync(params.path)); } } }, /** * Reads binary file content and return it * @param {String} path File's relative or absolute path * @return {String} */ read: function(path, size, callback) { var params = this._parseParams(arguments); this._read(params, function(err, buf) { params.callback(err, err ? '' : bts(buf)); }); }, /** * Read file content and return it * @param {String} path File's relative or absolute path * @return {String} */ readText: function(path, size, callback) { var params = this._parseParams(arguments); this._read(params, function(err, buf) { params.callback(err, err ? '' : buf.toString()); }); }, /** * Locate <code>file_name</code> file that relates to <code>editor_file</code>. * File name may be absolute or relative path * * <b>Dealing with absolute path.</b> * Many modern editors have a "project" support as information unit, but you * should not rely on project path to find file with absolute path. First, * it requires user to create a project before using this method (and this * is not very convenient). Second, project path doesn't always points to * to website's document root folder: it may point, for example, to an * upper folder which contains server-side scripts. * * For better result, you should use the following algorithm in locating * absolute resources: * 1) Get parent folder for <code>editorFile</code> as a start point * 2) Append required <code>fileName</code> to start point and test if * file exists * 3) If it doesn't exists, move start point one level up (to parent folder) * and repeat step 2. * * @param {String} editorFile * @param {String} fileName * @return {String} Returns null if <code>fileName</code> cannot be located */ locateFile: function(editorFile, fileName) { if (isURL(fileName)) { return fileName; } var dirname = editorFile, f; fileName = fileName.replace(/^\/+/, ''); while (dirname && dirname !== path.dirname(dirname)) { dirname = path.dirname(dirname); f = path.join(dirname, fileName); if (fs.existsSync(f)) return f; } return ''; }, /** * Creates absolute path by concatenating <code>parent</code> and <code>fileName</code>. * If <code>parent</code> points to file, its parent directory is used * @param {String} parent * @param {String} fileName * @return {String} */ createPath: function(parent, fileName, callback) { var stat = fs.statSync(parent); if (stat && !stat.isDirectory()) { parent = path.dirname(parent); } return callback(path.resolve(parent, fileName)); }, /** * Saves <code>content</code> as <code>file</code> * @param {String} file File's absolute path * @param {String} content File content */ save: function(file, content) { fs.writeFileSync(file, content, 'ascii'); }, /** * Returns file extension in lower case * @param {String} file * @return {String} */ getExt: function(file) { var m = (file || '').match(/\.([\w\-]+)$/); return m ? m[1].toLowerCase() : ''; } }); });
/* Copyright 2014 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* jshint globalstrict: false */ /* umdutils ignore */ (function (root, factory) { 'use strict'; if (typeof define === 'function' && define.amd) { define('pdfjs-dist/web/pdf.components', ['exports', 'pdfjs-dist/build/pdf'], factory); } else if (typeof exports !== 'undefined') { factory(exports, require('../build/pdf.js')); } else { factory((root.pdfjsDistWebPDFComponents = {}), root.pdfjsDistBuildPdf); } }(this, function (exports, pdfjsLib) { 'use strict'; var pdfViewerLibs = { pdfjsWebPDFJS: pdfjsLib }; (function () { (function (root, factory) { { factory((root.pdfjsWebPDFRenderingQueue = {})); } }(this, function (exports) { var CLEANUP_TIMEOUT = 30000; var RenderingStates = { INITIAL: 0, RUNNING: 1, PAUSED: 2, FINISHED: 3 }; /** * Controls rendering of the views for pages and thumbnails. * @class */ var PDFRenderingQueue = (function PDFRenderingQueueClosure() { /** * @constructs */ function PDFRenderingQueue() { this.pdfViewer = null; this.pdfThumbnailViewer = null; this.onIdle = null; this.highestPriorityPage = null; this.idleTimeout = null; this.printing = false; this.isThumbnailViewEnabled = false; } PDFRenderingQueue.prototype = /** @lends PDFRenderingQueue.prototype */ { /** * @param {PDFViewer} pdfViewer */ setViewer: function PDFRenderingQueue_setViewer(pdfViewer) { this.pdfViewer = pdfViewer; }, /** * @param {PDFThumbnailViewer} pdfThumbnailViewer */ setThumbnailViewer: function PDFRenderingQueue_setThumbnailViewer(pdfThumbnailViewer) { this.pdfThumbnailViewer = pdfThumbnailViewer; }, /** * @param {IRenderableView} view * @returns {boolean} */ isHighestPriority: function PDFRenderingQueue_isHighestPriority(view) { return this.highestPriorityPage === view.renderingId; }, renderHighestPriority: function PDFRenderingQueue_renderHighestPriority(currentlyVisiblePages) { if (this.idleTimeout) { clearTimeout(this.idleTimeout); this.idleTimeout = null; } // Pages have a higher priority than thumbnails, so check them first. if (this.pdfViewer.forceRendering(currentlyVisiblePages)) { return; } // No pages needed rendering so check thumbnails. if (this.pdfThumbnailViewer && this.isThumbnailViewEnabled) { if (this.pdfThumbnailViewer.forceRendering()) { return; } } if (this.printing) { // If printing is currently ongoing do not reschedule cleanup. return; } if (this.onIdle) { this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT); } }, getHighestPriority: function PDFRenderingQueue_getHighestPriority(visible, views, scrolledDown) { // The state has changed figure out which page has the highest priority to // render next (if any). // Priority: // 1 visible pages // 2 if last scrolled down page after the visible pages // 2 if last scrolled up page before the visible pages var visibleViews = visible.views; var numVisible = visibleViews.length; if (numVisible === 0) { return false; } for (var i = 0; i < numVisible; ++i) { var view = visibleViews[i].view; if (!this.isViewFinished(view)) { return view; } } // All the visible views have rendered, try to render next/previous pages. if (scrolledDown) { var nextPageIndex = visible.last.id; // ID's start at 1 so no need to add 1. if (views[nextPageIndex] && !this.isViewFinished(views[nextPageIndex])) { return views[nextPageIndex]; } } else { var previousPageIndex = visible.first.id - 2; if (views[previousPageIndex] && !this.isViewFinished(views[previousPageIndex])) { return views[previousPageIndex]; } } // Everything that needs to be rendered has been. return null; }, /** * @param {IRenderableView} view * @returns {boolean} */ isViewFinished: function PDFRenderingQueue_isViewFinished(view) { return view.renderingState === RenderingStates.FINISHED; }, /** * Render a page or thumbnail view. This calls the appropriate function * based on the views state. If the view is already rendered it will return * false. * @param {IRenderableView} view */ renderView: function PDFRenderingQueue_renderView(view) { var state = view.renderingState; switch (state) { case RenderingStates.FINISHED: return false; case RenderingStates.PAUSED: this.highestPriorityPage = view.renderingId; view.resume(); break; case RenderingStates.RUNNING: this.highestPriorityPage = view.renderingId; break; case RenderingStates.INITIAL: this.highestPriorityPage = view.renderingId; var continueRendering = function () { this.renderHighestPriority(); }.bind(this); view.draw().then(continueRendering, continueRendering); break; } return true; }, }; return PDFRenderingQueue; })(); exports.RenderingStates = RenderingStates; exports.PDFRenderingQueue = PDFRenderingQueue; })); (function (root, factory) { { factory((root.pdfjsWebDownloadManager = {}), root.pdfjsWebPDFJS); } }(this, function (exports, pdfjsLib) { function download(blobUrl, filename) { var a = document.createElement('a'); if (a.click) { // Use a.click() if available. Otherwise, Chrome might show // "Unsafe JavaScript attempt to initiate a navigation change // for frame with URL" and not open the PDF at all. // Supported by (not mentioned = untested): // - Firefox 6 - 19 (4- does not support a.click, 5 ignores a.click) // - Chrome 19 - 26 (18- does not support a.click) // - Opera 9 - 12.15 // - Internet Explorer 6 - 10 // - Safari 6 (5.1- does not support a.click) a.href = blobUrl; a.target = '_parent'; // Use a.download if available. This increases the likelihood that // the file is downloaded instead of opened by another PDF plugin. if ('download' in a) { a.download = filename; } // <a> must be in the document for IE and recent Firefox versions. // (otherwise .click() is ignored) (document.body || document.documentElement).appendChild(a); a.click(); a.parentNode.removeChild(a); } else { if (window.top === window && blobUrl.split('#')[0] === window.location.href.split('#')[0]) { // If _parent == self, then opening an identical URL with different // location hash will only cause a navigation, not a download. var padCharacter = blobUrl.indexOf('?') === -1 ? '?' : '&'; blobUrl = blobUrl.replace(/#|$/, padCharacter + '$&'); } window.open(blobUrl, '_parent'); } } function DownloadManager() {} DownloadManager.prototype = { downloadUrl: function DownloadManager_downloadUrl(url, filename) { if (!pdfjsLib.isValidUrl(url, true)) { return; // restricted/invalid URL } download(url + '#pdfjs.action=download', filename); }, downloadData: function DownloadManager_downloadData(data, filename, contentType) { if (navigator.msSaveBlob) { // IE10 and above return navigator.msSaveBlob(new Blob([data], { type: contentType }), filename); } var blobUrl = pdfjsLib.createObjectURL(data, contentType, pdfjsLib.PDFJS.disableCreateObjectURL); download(blobUrl, filename); }, download: function DownloadManager_download(blob, url, filename) { if (!URL) { // URL.createObjectURL is not supported this.downloadUrl(url, filename); return; } if (navigator.msSaveBlob) { // IE10 / IE11 if (!navigator.msSaveBlob(blob, filename)) { this.downloadUrl(url, filename); } return; } var blobUrl = URL.createObjectURL(blob); download(blobUrl, filename); } }; exports.DownloadManager = DownloadManager; })); (function (root, factory) { { factory((root.pdfjsWebUIUtils = {}), root.pdfjsWebPDFJS); } }(this, function (exports, pdfjsLib) { var CSS_UNITS = 96.0 / 72.0; var DEFAULT_SCALE_VALUE = 'auto'; var DEFAULT_SCALE = 1.0; var UNKNOWN_SCALE = 0; var MAX_AUTO_SCALE = 1.25; var SCROLLBAR_PADDING = 40; var VERTICAL_PADDING = 5; var mozL10n = document.mozL10n || document.webL10n; var PDFJS = pdfjsLib.PDFJS; /** * Disables fullscreen support, and by extension Presentation Mode, * in browsers which support the fullscreen API. * @var {boolean} */ PDFJS.disableFullscreen = (PDFJS.disableFullscreen === undefined ? false : PDFJS.disableFullscreen); /** * Enables CSS only zooming. * @var {boolean} */ PDFJS.useOnlyCssZoom = (PDFJS.useOnlyCssZoom === undefined ? false : PDFJS.useOnlyCssZoom); /** * The maximum supported canvas size in total pixels e.g. width * height. * The default value is 4096 * 4096. Use -1 for no limit. * @var {number} */ PDFJS.maxCanvasPixels = (PDFJS.maxCanvasPixels === undefined ? 16777216 : PDFJS.maxCanvasPixels); /** * Disables saving of the last position of the viewed PDF. * @var {boolean} */ PDFJS.disableHistory = (PDFJS.disableHistory === undefined ? false : PDFJS.disableHistory); /** * Disables creation of the text layer that used for text selection and search. * @var {boolean} */ PDFJS.disableTextLayer = (PDFJS.disableTextLayer === undefined ? false : PDFJS.disableTextLayer); /** * Disables maintaining the current position in the document when zooming. */ PDFJS.ignoreCurrentPositionOnZoom = (PDFJS.ignoreCurrentPositionOnZoom === undefined ? false : PDFJS.ignoreCurrentPositionOnZoom); /** * Interface locale settings. * @var {string} */ PDFJS.locale = (PDFJS.locale === undefined ? navigator.language : PDFJS.locale); /** * Returns scale factor for the canvas. It makes sense for the HiDPI displays. * @return {Object} The object with horizontal (sx) and vertical (sy) scales. The scaled property is set to false if scaling is not required, true otherwise. */ function getOutputScale(ctx) { var devicePixelRatio = window.devicePixelRatio || 1; var backingStoreRatio = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1; var pixelRatio = devicePixelRatio / backingStoreRatio; return { sx: pixelRatio, sy: pixelRatio, scaled: pixelRatio !== 1 }; } /** * Scrolls specified element into view of its parent. * @param {Object} element - The element to be visible. * @param {Object} spot - An object with optional top and left properties, * specifying the offset from the top left edge. * @param {boolean} skipOverflowHiddenElements - Ignore elements that have * the CSS rule `overflow: hidden;` set. The default is false. */ function scrollIntoView(element, spot, skipOverflowHiddenElements) { // Assuming offsetParent is available (it's not available when viewer is in // hidden iframe or object). We have to scroll: if the offsetParent is not set // producing the error. See also animationStartedClosure. var parent = element.offsetParent; if (!parent) { console.error('offsetParent is not set -- cannot scroll'); return; } var checkOverflow = skipOverflowHiddenElements || false; var offsetY = element.offsetTop + element.clientTop; var offsetX = element.offsetLeft + element.clientLeft; while (parent.clientHeight === parent.scrollHeight || (checkOverflow && getComputedStyle(parent).overflow === 'hidden')) { if (parent.dataset._scaleY) { offsetY /= parent.dataset._scaleY; offsetX /= parent.dataset._scaleX; } offsetY += parent.offsetTop; offsetX += parent.offsetLeft; parent = parent.offsetParent; if (!parent) { return; // no need to scroll } } if (spot) { if (spot.top !== undefined) { offsetY += spot.top; } if (spot.left !== undefined) { offsetX += spot.left; parent.scrollLeft = offsetX; } } parent.scrollTop = offsetY; } /** * Helper function to start monitoring the scroll event and converting them into * PDF.js friendly one: with scroll debounce and scroll direction. */ function watchScroll(viewAreaElement, callback) { var debounceScroll = function debounceScroll(evt) { if (rAF) { return; } // schedule an invocation of scroll for next animation frame. rAF = window.requestAnimationFrame(function viewAreaElementScrolled() { rAF = null; var currentY = viewAreaElement.scrollTop; var lastY = state.lastY; if (currentY !== lastY) { state.down = currentY > lastY; } state.lastY = currentY; callback(state); }); }; var state = { down: true, lastY: viewAreaElement.scrollTop, _eventHandler: debounceScroll }; var rAF = null; viewAreaElement.addEventListener('scroll', debounceScroll, true); return state; } /** * Helper function to parse query string (e.g. ?param1=value&parm2=...). */ function parseQueryString(query) { var parts = query.split('&'); var params = {}; for (var i = 0, ii = parts.length; i < ii; ++i) { var param = parts[i].split('='); var key = param[0].toLowerCase(); var value = param.length > 1 ? param[1] : null; params[decodeURIComponent(key)] = decodeURIComponent(value); } return params; } /** * Use binary search to find the index of the first item in a given array which * passes a given condition. The items are expected to be sorted in the sense * that if the condition is true for one item in the array, then it is also true * for all following items. * * @returns {Number} Index of the first array element to pass the test, * or |items.length| if no such element exists. */ function binarySearchFirstItem(items, condition) { var minIndex = 0; var maxIndex = items.length - 1; if (items.length === 0 || !condition(items[maxIndex])) { return items.length; } if (condition(items[minIndex])) { return minIndex; } while (minIndex < maxIndex) { var currentIndex = (minIndex + maxIndex) >> 1; var currentItem = items[currentIndex]; if (condition(currentItem)) { maxIndex = currentIndex; } else { minIndex = currentIndex + 1; } } return minIndex; /* === maxIndex */ } /** * Approximates float number as a fraction using Farey sequence (max order * of 8). * @param {number} x - Positive float number. * @returns {Array} Estimated fraction: the first array item is a numerator, * the second one is a denominator. */ function approximateFraction(x) { // Fast paths for int numbers or their inversions. if (Math.floor(x) === x) { return [x, 1]; } var xinv = 1 / x; var limit = 8; if (xinv > limit) { return [1, limit]; } else if (Math.floor(xinv) === xinv) { return [1, xinv]; } var x_ = x > 1 ? xinv : x; // a/b and c/d are neighbours in Farey sequence. var a = 0, b = 1, c = 1, d = 1; // Limiting search to order 8. while (true) { // Generating next term in sequence (order of q). var p = a + c, q = b + d; if (q > limit) { break; } if (x_ <= p / q) { c = p; d = q; } else { a = p; b = q; } } // Select closest of the neighbours to x. if (x_ - a / b < c / d - x_) { return x_ === x ? [a, b] : [b, a]; } else { return x_ === x ? [c, d] : [d, c]; } } function roundToDivide(x, div) { var r = x % div; return r === 0 ? x : Math.round(x - r + div); } /** * Generic helper to find out what elements are visible within a scroll pane. */ function getVisibleElements(scrollEl, views, sortByVisibility) { var top = scrollEl.scrollTop, bottom = top + scrollEl.clientHeight; var left = scrollEl.scrollLeft, right = left + scrollEl.clientWidth; function isElementBottomBelowViewTop(view) { var element = view.div; var elementBottom = element.offsetTop + element.clientTop + element.clientHeight; return elementBottom > top; } var visible = [], view, element; var currentHeight, viewHeight, hiddenHeight, percentHeight; var currentWidth, viewWidth; var firstVisibleElementInd = (views.length === 0) ? 0 : binarySearchFirstItem(views, isElementBottomBelowViewTop); for (var i = firstVisibleElementInd, ii = views.length; i < ii; i++) { view = views[i]; element = view.div; currentHeight = element.offsetTop + element.clientTop; viewHeight = element.clientHeight; if (currentHeight > bottom) { break; } currentWidth = element.offsetLeft + element.clientLeft; viewWidth = element.clientWidth; if (currentWidth + viewWidth < left || currentWidth > right) { continue; } hiddenHeight = Math.max(0, top - currentHeight) + Math.max(0, currentHeight + viewHeight - bottom); percentHeight = ((viewHeight - hiddenHeight) * 100 / viewHeight) | 0; visible.push({ id: view.id, x: currentWidth, y: currentHeight, view: view, percent: percentHeight }); } var first = visible[0]; var last = visible[visible.length - 1]; if (sortByVisibility) { visible.sort(function(a, b) { var pc = a.percent - b.percent; if (Math.abs(pc) > 0.001) { return -pc; } return a.id - b.id; // ensure stability }); } return {first: first, last: last, views: visible}; } /** * Event handler to suppress context menu. */ function noContextMenuHandler(e) { e.preventDefault(); } /** * Returns the filename or guessed filename from the url (see issue 3455). * url {String} The original PDF location. * @return {String} Guessed PDF file name. */ function getPDFFileNameFromURL(url) { var reURI = /^(?:([^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/; // SCHEME HOST 1.PATH 2.QUERY 3.REF // Pattern to get last matching NAME.pdf var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i; var splitURI = reURI.exec(url); var suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]); if (suggestedFilename) { suggestedFilename = suggestedFilename[0]; if (suggestedFilename.indexOf('%') !== -1) { // URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf try { suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0]; } catch(e) { // Possible (extremely rare) errors: // URIError "Malformed URI", e.g. for "%AA.pdf" // TypeError "null has no properties", e.g. for "%2F.pdf" } } } return suggestedFilename || 'document.pdf'; } /** * Simple event bus for an application. Listeners are attached using the * `on` and `off` methods. To raise an event, the `dispatch` method shall be * used. */ var EventBus = (function EventBusClosure() { function EventBus() { this._listeners = Object.create(null); } EventBus.prototype = { on: function EventBus_on(eventName, listener) { var eventListeners = this._listeners[eventName]; if (!eventListeners) { eventListeners = []; this._listeners[eventName] = eventListeners; } eventListeners.push(listener); }, off: function EventBus_on(eventName, listener) { var eventListeners = this._listeners[eventName]; var i; if (!eventListeners || ((i = eventListeners.indexOf(listener)) < 0)) { return; } eventListeners.splice(i, 1); }, dispatch: function EventBus_dispath(eventName) { var eventListeners = this._listeners[eventName]; if (!eventListeners || eventListeners.length === 0) { return; } // Passing all arguments after the eventName to the listeners. var args = Array.prototype.slice.call(arguments, 1); // Making copy of the listeners array in case if it will be modified // during dispatch. eventListeners.slice(0).forEach(function (listener) { listener.apply(null, args); }); } }; return EventBus; })(); var ProgressBar = (function ProgressBarClosure() { function clamp(v, min, max) { return Math.min(Math.max(v, min), max); } function ProgressBar(id, opts) { this.visible = true; // Fetch the sub-elements for later. this.div = document.querySelector(id + ' .progress'); // Get the loading bar element, so it can be resized to fit the viewer. this.bar = this.div.parentNode; // Get options, with sensible defaults. this.height = opts.height || 100; this.width = opts.width || 100; this.units = opts.units || '%'; // Initialize heights. this.div.style.height = this.height + this.units; this.percent = 0; } ProgressBar.prototype = { updateBar: function ProgressBar_updateBar() { if (this._indeterminate) { this.div.classList.add('indeterminate'); this.div.style.width = this.width + this.units; return; } this.div.classList.remove('indeterminate'); var progressSize = this.width * this._percent / 100; this.div.style.width = progressSize + this.units; }, get percent() { return this._percent; }, set percent(val) { this._indeterminate = isNaN(val); this._percent = clamp(val, 0, 100); this.updateBar(); }, setWidth: function ProgressBar_setWidth(viewer) { if (viewer) { var container = viewer.parentNode; var scrollbarWidth = container.offsetWidth - viewer.offsetWidth; if (scrollbarWidth > 0) { this.bar.setAttribute('style', 'width: calc(100% - ' + scrollbarWidth + 'px);'); } } }, hide: function ProgressBar_hide() { if (!this.visible) { return; } this.visible = false; this.bar.classList.add('hidden'); document.body.classList.remove('loadingInProgress'); }, show: function ProgressBar_show() { if (this.visible) { return; } this.visible = true; document.body.classList.add('loadingInProgress'); this.bar.classList.remove('hidden'); } }; return ProgressBar; })(); exports.CSS_UNITS = CSS_UNITS; exports.DEFAULT_SCALE_VALUE = DEFAULT_SCALE_VALUE; exports.DEFAULT_SCALE = DEFAULT_SCALE; exports.UNKNOWN_SCALE = UNKNOWN_SCALE; exports.MAX_AUTO_SCALE = MAX_AUTO_SCALE; exports.SCROLLBAR_PADDING = SCROLLBAR_PADDING; exports.VERTICAL_PADDING = VERTICAL_PADDING; exports.mozL10n = mozL10n; exports.EventBus = EventBus; exports.ProgressBar = ProgressBar; exports.getPDFFileNameFromURL = getPDFFileNameFromURL; exports.noContextMenuHandler = noContextMenuHandler; exports.parseQueryString = parseQueryString; exports.getVisibleElements = getVisibleElements; exports.roundToDivide = roundToDivide; exports.approximateFraction = approximateFraction; exports.getOutputScale = getOutputScale; exports.scrollIntoView = scrollIntoView; exports.watchScroll = watchScroll; exports.binarySearchFirstItem = binarySearchFirstItem; })); (function (root, factory) { { factory((root.pdfjsWebDOMEvents = {}), root.pdfjsWebUIUtils); } }(this, function (exports, uiUtils) { var EventBus = uiUtils.EventBus; // Attaching to the application event bus to dispatch events to the DOM for // backwards viewer API compatibility. function attachDOMEventsToEventBus(eventBus) { eventBus.on('documentload', function () { var event = document.createEvent('CustomEvent'); event.initCustomEvent('documentload', true, true, {}); window.dispatchEvent(event); }); eventBus.on('pagerendered', function (e) { var event = document.createEvent('CustomEvent'); event.initCustomEvent('pagerendered', true, true, { pageNumber: e.pageNumber, cssTransform: e.cssTransform, }); e.source.div.dispatchEvent(event); }); eventBus.on('textlayerrendered', function (e) { var event = document.createEvent('CustomEvent'); event.initCustomEvent('textlayerrendered', true, true, { pageNumber: e.pageNumber }); e.source.textLayerDiv.dispatchEvent(event); }); eventBus.on('pagechange', function (e) { var event = document.createEvent('UIEvents'); event.initUIEvent('pagechange', true, true, window, 0); event.updateInProgress = e.updateInProgress; event.pageNumber = e.pageNumber; event.previousPageNumber = e.previousPageNumber; e.source.container.dispatchEvent(event); }); eventBus.on('pagesinit', function (e) { var event = document.createEvent('CustomEvent'); event.initCustomEvent('pagesinit', true, true, null); e.source.container.dispatchEvent(event); }); eventBus.on('pagesloaded', function (e) { var event = document.createEvent('CustomEvent'); event.initCustomEvent('pagesloaded', true, true, { pagesCount: e.pagesCount }); e.source.container.dispatchEvent(event); }); eventBus.on('scalechange', function (e) { var event = document.createEvent('UIEvents'); event.initUIEvent('scalechange', true, true, window, 0); event.scale = e.scale; event.presetValue = e.presetValue; e.source.container.dispatchEvent(event); }); eventBus.on('updateviewarea', function (e) { var event = document.createEvent('UIEvents'); event.initUIEvent('updateviewarea', true, true, window, 0); event.location = e.location; e.source.container.dispatchEvent(event); }); eventBus.on('find', function (e) { if (e.source === window) { return; // event comes from FirefoxCom, no need to replicate } var event = document.createEvent('CustomEvent'); event.initCustomEvent('find' + e.type, true, true, { query: e.query, caseSensitive: e.caseSensitive, highlightAll: e.highlightAll, findPrevious: e.findPrevious }); window.dispatchEvent(event); }); eventBus.on('attachmentsloaded', function (e) { var event = document.createEvent('CustomEvent'); event.initCustomEvent('attachmentsloaded', true, true, { attachmentsCount: e.attachmentsCount }); e.source.container.dispatchEvent(event); }); eventBus.on('sidebarviewchanged', function (e) { var event = document.createEvent('CustomEvent'); event.initCustomEvent('sidebarviewchanged', true, true, { view: e.view, }); e.source.outerContainer.dispatchEvent(event); }); eventBus.on('pagemode', function (e) { var event = document.createEvent('CustomEvent'); event.initCustomEvent('pagemode', true, true, { mode: e.mode, }); e.source.pdfViewer.container.dispatchEvent(event); }); eventBus.on('namedaction', function (e) { var event = document.createEvent('CustomEvent'); event.initCustomEvent('namedaction', true, true, { action: e.action }); e.source.pdfViewer.container.dispatchEvent(event); }); eventBus.on('presentationmodechanged', function (e) { var event = document.createEvent('CustomEvent'); event.initCustomEvent('presentationmodechanged', true, true, { active: e.active, switchInProgress: e.switchInProgress }); window.dispatchEvent(event); }); eventBus.on('outlineloaded', function (e) { var event = document.createEvent('CustomEvent'); event.initCustomEvent('outlineloaded', true, true, { outlineCount: e.outlineCount }); e.source.container.dispatchEvent(event); }); } var globalEventBus = null; function getGlobalEventBus() { if (globalEventBus) { return globalEventBus; } globalEventBus = new EventBus(); attachDOMEventsToEventBus(globalEventBus); return globalEventBus; } exports.attachDOMEventsToEventBus = attachDOMEventsToEventBus; exports.getGlobalEventBus = getGlobalEventBus; })); (function (root, factory) { { factory((root.pdfjsWebPDFFindController = {}), root.pdfjsWebUIUtils); } }(this, function (exports, uiUtils, firefoxCom) { var scrollIntoView = uiUtils.scrollIntoView; var FindStates = { FIND_FOUND: 0, FIND_NOTFOUND: 1, FIND_WRAPPED: 2, FIND_PENDING: 3 }; var FIND_SCROLL_OFFSET_TOP = -50; var FIND_SCROLL_OFFSET_LEFT = -400; var CHARACTERS_TO_NORMALIZE = { '\u2018': '\'', // Left single quotation mark '\u2019': '\'', // Right single quotation mark '\u201A': '\'', // Single low-9 quotation mark '\u201B': '\'', // Single high-reversed-9 quotation mark '\u201C': '"', // Left double quotation mark '\u201D': '"', // Right double quotation mark '\u201E': '"', // Double low-9 quotation mark '\u201F': '"', // Double high-reversed-9 quotation mark '\u00BC': '1/4', // Vulgar fraction one quarter '\u00BD': '1/2', // Vulgar fraction one half '\u00BE': '3/4', // Vulgar fraction three quarters }; /** * Provides "search" or "find" functionality for the PDF. * This object actually performs the search for a given string. */ var PDFFindController = (function PDFFindControllerClosure() { function PDFFindController(options) { this.pdfViewer = options.pdfViewer || null; this.onUpdateResultsCount = null; this.onUpdateState = null; this.reset(); // Compile the regular expression for text normalization once. var replace = Object.keys(CHARACTERS_TO_NORMALIZE).join(''); this.normalizationRegex = new RegExp('[' + replace + ']', 'g'); } PDFFindController.prototype = { reset: function PDFFindController_reset() { this.startedTextExtraction = false; this.extractTextPromises = []; this.pendingFindMatches = Object.create(null); this.active = false; // If active, find results will be highlighted. this.pageContents = []; // Stores the text for each page. this.pageMatches = []; this.matchCount = 0; this.selected = { // Currently selected match. pageIdx: -1, matchIdx: -1 }; this.offset = { // Where the find algorithm currently is in the document. pageIdx: null, matchIdx: null }; this.pagesToSearch = null; this.resumePageIdx = null; this.state = null; this.dirtyMatch = false; this.findTimeout = null; this.firstPagePromise = new Promise(function (resolve) { this.resolveFirstPage = resolve; }.bind(this)); }, normalize: function PDFFindController_normalize(text) { return text.replace(this.normalizationRegex, function (ch) { return CHARACTERS_TO_NORMALIZE[ch]; }); }, calcFindMatch: function PDFFindController_calcFindMatch(pageIndex) { var pageContent = this.normalize(this.pageContents[pageIndex]); var query = this.normalize(this.state.query); var caseSensitive = this.state.caseSensitive; var queryLen = query.length; if (queryLen === 0) { // Do nothing: the matches should be wiped out already. return; } if (!caseSensitive) { pageContent = pageContent.toLowerCase(); query = query.toLowerCase(); } var matches = []; var matchIdx = -queryLen; while (true) { matchIdx = pageContent.indexOf(query, matchIdx + queryLen); if (matchIdx === -1) { break; } matches.push(matchIdx); } this.pageMatches[pageIndex] = matches; this.updatePage(pageIndex); if (this.resumePageIdx === pageIndex) { this.resumePageIdx = null; this.nextPageMatch(); } // Update the matches count if (matches.length > 0) { this.matchCount += matches.length; this.updateUIResultsCount(); } }, extractText: function PDFFindController_extractText() { if (this.startedTextExtraction) { return; } this.startedTextExtraction = true; this.pageContents = []; var extractTextPromisesResolves = []; var numPages = this.pdfViewer.pagesCount; for (var i = 0; i < numPages; i++) { this.extractTextPromises.push(new Promise(function (resolve) { extractTextPromisesResolves.push(resolve); })); } var self = this; function extractPageText(pageIndex) { self.pdfViewer.getPageTextContent(pageIndex).then( function textContentResolved(textContent) { var textItems = textContent.items; var str = []; for (var i = 0, len = textItems.length; i < len; i++) { str.push(textItems[i].str); } // Store the pageContent as a string. self.pageContents.push(str.join('')); extractTextPromisesResolves[pageIndex](pageIndex); if ((pageIndex + 1) < self.pdfViewer.pagesCount) { extractPageText(pageIndex + 1); } } ); } extractPageText(0); }, executeCommand: function PDFFindController_executeCommand(cmd, state) { if (this.state === null || cmd !== 'findagain') { this.dirtyMatch = true; } this.state = state; this.updateUIState(FindStates.FIND_PENDING); this.firstPagePromise.then(function() { this.extractText(); clearTimeout(this.findTimeout); if (cmd === 'find') { // Only trigger the find action after 250ms of silence. this.findTimeout = setTimeout(this.nextMatch.bind(this), 250); } else { this.nextMatch(); } }.bind(this)); }, updatePage: function PDFFindController_updatePage(index) { if (this.selected.pageIdx === index) { // If the page is selected, scroll the page into view, which triggers // rendering the page, which adds the textLayer. Once the textLayer is // build, it will scroll onto the selected match. this.pdfViewer.scrollPageIntoView(index + 1); } var page = this.pdfViewer.getPageView(index); if (page.textLayer) { page.textLayer.updateMatches(); } }, nextMatch: function PDFFindController_nextMatch() { var previous = this.state.findPrevious; var currentPageIndex = this.pdfViewer.currentPageNumber - 1; var numPages = this.pdfViewer.pagesCount; this.active = true; if (this.dirtyMatch) { // Need to recalculate the matches, reset everything. this.dirtyMatch = false; this.selected.pageIdx = this.selected.matchIdx = -1; this.offset.pageIdx = currentPageIndex; this.offset.matchIdx = null; this.hadMatch = false; this.resumePageIdx = null; this.pageMatches = []; this.matchCount = 0; var self = this; for (var i = 0; i < numPages; i++) { // Wipe out any previous highlighted matches. this.updatePage(i); // As soon as the text is extracted start finding the matches. if (!(i in this.pendingFindMatches)) { this.pendingFindMatches[i] = true; this.extractTextPromises[i].then(function(pageIdx) { delete self.pendingFindMatches[pageIdx]; self.calcFindMatch(pageIdx); }); } } } // If there's no query there's no point in searching. if (this.state.query === '') { this.updateUIState(FindStates.FIND_FOUND); return; } // If we're waiting on a page, we return since we can't do anything else. if (this.resumePageIdx) { return; } var offset = this.offset; // Keep track of how many pages we should maximally iterate through. this.pagesToSearch = numPages; // If there's already a matchIdx that means we are iterating through a // page's matches. if (offset.matchIdx !== null) { var numPageMatches = this.pageMatches[offset.pageIdx].length; if ((!previous && offset.matchIdx + 1 < numPageMatches) || (previous && offset.matchIdx > 0)) { // The simple case; we just have advance the matchIdx to select // the next match on the page. this.hadMatch = true; offset.matchIdx = (previous ? offset.matchIdx - 1 : offset.matchIdx + 1); this.updateMatch(true); return; } // We went beyond the current page's matches, so we advance to // the next page. this.advanceOffsetPage(previous); } // Start searching through the page. this.nextPageMatch(); }, matchesReady: function PDFFindController_matchesReady(matches) { var offset = this.offset; var numMatches = matches.length; var previous = this.state.findPrevious; if (numMatches) { // There were matches for the page, so initialize the matchIdx. this.hadMatch = true; offset.matchIdx = (previous ? numMatches - 1 : 0); this.updateMatch(true); return true; } else { // No matches, so attempt to search the next page. this.advanceOffsetPage(previous); if (offset.wrapped) { offset.matchIdx = null; if (this.pagesToSearch < 0) { // No point in wrapping again, there were no matches. this.updateMatch(false); // while matches were not found, searching for a page // with matches should nevertheless halt. return true; } } // Matches were not found (and searching is not done). return false; } }, /** * The method is called back from the text layer when match presentation * is updated. * @param {number} pageIndex - page index. * @param {number} index - match index. * @param {Array} elements - text layer div elements array. * @param {number} beginIdx - start index of the div array for the match. * @param {number} endIdx - end index of the div array for the match. */ updateMatchPosition: function PDFFindController_updateMatchPosition( pageIndex, index, elements, beginIdx, endIdx) { if (this.selected.matchIdx === index && this.selected.pageIdx === pageIndex) { var spot = { top: FIND_SCROLL_OFFSET_TOP, left: FIND_SCROLL_OFFSET_LEFT }; scrollIntoView(elements[beginIdx], spot, /* skipOverflowHiddenElements = */ true); } }, nextPageMatch: function PDFFindController_nextPageMatch() { if (this.resumePageIdx !== null) { console.error('There can only be one pending page.'); } do { var pageIdx = this.offset.pageIdx; var matches = this.pageMatches[pageIdx]; if (!matches) { // The matches don't exist yet for processing by "matchesReady", // so set a resume point for when they do exist. this.resumePageIdx = pageIdx; break; } } while (!this.matchesReady(matches)); }, advanceOffsetPage: function PDFFindController_advanceOffsetPage(previous) { var offset = this.offset; var numPages = this.extractTextPromises.length; offset.pageIdx = (previous ? offset.pageIdx - 1 : offset.pageIdx + 1); offset.matchIdx = null; this.pagesToSearch--; if (offset.pageIdx >= numPages || offset.pageIdx < 0) { offset.pageIdx = (previous ? numPages - 1 : 0); offset.wrapped = true; } }, updateMatch: function PDFFindController_updateMatch(found) { var state = FindStates.FIND_NOTFOUND; var wrapped = this.offset.wrapped; this.offset.wrapped = false; if (found) { var previousPage = this.selected.pageIdx; this.selected.pageIdx = this.offset.pageIdx; this.selected.matchIdx = this.offset.matchIdx; state = (wrapped ? FindStates.FIND_WRAPPED : FindStates.FIND_FOUND); // Update the currently selected page to wipe out any selected matches. if (previousPage !== -1 && previousPage !== this.selected.pageIdx) { this.updatePage(previousPage); } } this.updateUIState(state, this.state.findPrevious); if (this.selected.pageIdx !== -1) { this.updatePage(this.selected.pageIdx); } }, updateUIResultsCount: function PDFFindController_updateUIResultsCount() { if (this.onUpdateResultsCount) { this.onUpdateResultsCount(this.matchCount); } }, updateUIState: function PDFFindController_updateUIState(state, previous) { if (this.onUpdateState) { this.onUpdateState(state, previous, this.matchCount); } } }; return PDFFindController; })(); exports.FindStates = FindStates; exports.PDFFindController = PDFFindController; })); (function (root, factory) { { factory((root.pdfjsWebPDFHistory = {}), root.pdfjsWebDOMEvents); } }(this, function (exports, domEvents) { function PDFHistory(options) { this.linkService = options.linkService; this.eventBus = options.eventBus || domEvents.getGlobalEventBus(); this.initialized = false; this.initialDestination = null; this.initialBookmark = null; } PDFHistory.prototype = { /** * @param {string} fingerprint */ initialize: function pdfHistoryInitialize(fingerprint) { this.initialized = true; this.reInitialized = false; this.allowHashChange = true; this.historyUnlocked = true; this.isViewerInPresentationMode = false; this.previousHash = window.location.hash.substring(1); this.currentBookmark = ''; this.currentPage = 0; this.updatePreviousBookmark = false; this.previousBookmark = ''; this.previousPage = 0; this.nextHashParam = ''; this.fingerprint = fingerprint; this.currentUid = this.uid = 0; this.current = {}; var state = window.history.state; if (this._isStateObjectDefined(state)) { // This corresponds to navigating back to the document // from another page in the browser history. if (state.target.dest) { this.initialDestination = state.target.dest; } else { this.initialBookmark = state.target.hash; } this.currentUid = state.uid; this.uid = state.uid + 1; this.current = state.target; } else { // This corresponds to the loading of a new document. if (state && state.fingerprint && this.fingerprint !== state.fingerprint) { // Reinitialize the browsing history when a new document // is opened in the web viewer. this.reInitialized = true; } this._pushOrReplaceState({fingerprint: this.fingerprint}, true); } var self = this; window.addEventListener('popstate', function pdfHistoryPopstate(evt) { if (!self.historyUnlocked) { return; } if (evt.state) { // Move back/forward in the history. self._goTo(evt.state); return; } // If the state is not set, then the user tried to navigate to a // different hash by manually editing the URL and pressing Enter, or by // clicking on an in-page link (e.g. the "current view" link). // Save the current view state to the browser history. // Note: In Firefox, history.null could also be null after an in-page // navigation to the same URL, and without dispatching the popstate // event: https://bugzilla.mozilla.org/show_bug.cgi?id=1183881 if (self.uid === 0) { // Replace the previous state if it was not explicitly set. var previousParams = (self.previousHash && self.currentBookmark && self.previousHash !== self.currentBookmark) ? {hash: self.currentBookmark, page: self.currentPage} : {page: 1}; replacePreviousHistoryState(previousParams, function() { updateHistoryWithCurrentHash(); }); } else { updateHistoryWithCurrentHash(); } }, false); function updateHistoryWithCurrentHash() { self.previousHash = window.location.hash.slice(1); self._pushToHistory({hash: self.previousHash}, false, true); self._updatePreviousBookmark(); } function replacePreviousHistoryState(params, callback) { // To modify the previous history entry, the following happens: // 1. history.back() // 2. _pushToHistory, which calls history.replaceState( ... ) // 3. history.forward() // Because a navigation via the history API does not immediately update // the history state, the popstate event is used for synchronization. self.historyUnlocked = false; // Suppress the hashchange event to avoid side effects caused by // navigating back and forward. self.allowHashChange = false; window.addEventListener('popstate', rewriteHistoryAfterBack); history.back(); function rewriteHistoryAfterBack() { window.removeEventListener('popstate', rewriteHistoryAfterBack); window.addEventListener('popstate', rewriteHistoryAfterForward); self._pushToHistory(params, false, true); history.forward(); } function rewriteHistoryAfterForward() { window.removeEventListener('popstate', rewriteHistoryAfterForward); self.allowHashChange = true; self.historyUnlocked = true; callback(); } } function pdfHistoryBeforeUnload() { var previousParams = self._getPreviousParams(null, true); if (previousParams) { var replacePrevious = (!self.current.dest && self.current.hash !== self.previousHash); self._pushToHistory(previousParams, false, replacePrevious); self._updatePreviousBookmark(); } // Remove the event listener when navigating away from the document, // since 'beforeunload' prevents Firefox from caching the document. window.removeEventListener('beforeunload', pdfHistoryBeforeUnload, false); } window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false); window.addEventListener('pageshow', function pdfHistoryPageShow(evt) { // If the entire viewer (including the PDF file) is cached in // the browser, we need to reattach the 'beforeunload' event listener // since the 'DOMContentLoaded' event is not fired on 'pageshow'. window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false); }, false); self.eventBus.on('presentationmodechanged', function(e) { self.isViewerInPresentationMode = e.active; }); }, clearHistoryState: function pdfHistory_clearHistoryState() { this._pushOrReplaceState(null, true); }, _isStateObjectDefined: function pdfHistory_isStateObjectDefined(state) { return (state && state.uid >= 0 && state.fingerprint && this.fingerprint === state.fingerprint && state.target && state.target.hash) ? true : false; }, _pushOrReplaceState: function pdfHistory_pushOrReplaceState(stateObj, replace) { if (replace) { window.history.replaceState(stateObj, '', document.URL); } else { window.history.pushState(stateObj, '', document.URL); } }, get isHashChangeUnlocked() { if (!this.initialized) { return true; } return this.allowHashChange; }, _updatePreviousBookmark: function pdfHistory_updatePreviousBookmark() { if (this.updatePreviousBookmark && this.currentBookmark && this.currentPage) { this.previousBookmark = this.currentBookmark; this.previousPage = this.currentPage; this.updatePreviousBookmark = false; } }, updateCurrentBookmark: function pdfHistoryUpdateCurrentBookmark(bookmark, pageNum) { if (this.initialized) { this.currentBookmark = bookmark.substring(1); this.currentPage = pageNum | 0; this._updatePreviousBookmark(); } }, updateNextHashParam: function pdfHistoryUpdateNextHashParam(param) { if (this.initialized) { this.nextHashParam = param; } }, push: function pdfHistoryPush(params, isInitialBookmark) { if (!(this.initialized && this.historyUnlocked)) { return; } if (params.dest && !params.hash) { params.hash = (this.current.hash && this.current.dest && this.current.dest === params.dest) ? this.current.hash : this.linkService.getDestinationHash(params.dest).split('#')[1]; } if (params.page) { params.page |= 0; } if (isInitialBookmark) { var target = window.history.state.target; if (!target) { // Invoked when the user specifies an initial bookmark, // thus setting initialBookmark, when the document is loaded. this._pushToHistory(params, false); this.previousHash = window.location.hash.substring(1); } this.updatePreviousBookmark = this.nextHashParam ? false : true; if (target) { // If the current document is reloaded, // avoid creating duplicate entries in the history. this._updatePreviousBookmark(); } return; } if (this.nextHashParam) { if (this.nextHashParam === params.hash) { this.nextHashParam = null; this.updatePreviousBookmark = true; return; } else { this.nextHashParam = null; } } if (params.hash) { if (this.current.hash) { if (this.current.hash !== params.hash) { this._pushToHistory(params, true); } else { if (!this.current.page && params.page) { this._pushToHistory(params, false, true); } this.updatePreviousBookmark = true; } } else { this._pushToHistory(params, true); } } else if (this.current.page && params.page && this.current.page !== params.page) { this._pushToHistory(params, true); } }, _getPreviousParams: function pdfHistory_getPreviousParams(onlyCheckPage, beforeUnload) { if (!(this.currentBookmark && this.currentPage)) { return null; } else if (this.updatePreviousBookmark) { this.updatePreviousBookmark = false; } if (this.uid > 0 && !(this.previousBookmark && this.previousPage)) { // Prevent the history from getting stuck in the current state, // effectively preventing the user from going back/forward in // the history. // // This happens if the current position in the document didn't change // when the history was previously updated. The reasons for this are // either: // 1. The current zoom value is such that the document does not need to, // or cannot, be scrolled to display the destination. // 2. The previous destination is broken, and doesn't actally point to a // position within the document. // (This is either due to a bad PDF generator, or the user making a // mistake when entering a destination in the hash parameters.) return null; } if ((!this.current.dest && !onlyCheckPage) || beforeUnload) { if (this.previousBookmark === this.currentBookmark) { return null; } } else if (this.current.page || onlyCheckPage) { if (this.previousPage === this.currentPage) { return null; } } else { return null; } var params = {hash: this.currentBookmark, page: this.currentPage}; if (this.isViewerInPresentationMode) { params.hash = null; } return params; }, _stateObj: function pdfHistory_stateObj(params) { return {fingerprint: this.fingerprint, uid: this.uid, target: params}; }, _pushToHistory: function pdfHistory_pushToHistory(params, addPrevious, overwrite) { if (!this.initialized) { return; } if (!params.hash && params.page) { params.hash = ('page=' + params.page); } if (addPrevious && !overwrite) { var previousParams = this._getPreviousParams(); if (previousParams) { var replacePrevious = (!this.current.dest && this.current.hash !== this.previousHash); this._pushToHistory(previousParams, false, replacePrevious); } } this._pushOrReplaceState(this._stateObj(params), (overwrite || this.uid === 0)); this.currentUid = this.uid++; this.current = params; this.updatePreviousBookmark = true; }, _goTo: function pdfHistory_goTo(state) { if (!(this.initialized && this.historyUnlocked && this._isStateObjectDefined(state))) { return; } if (!this.reInitialized && state.uid < this.currentUid) { var previousParams = this._getPreviousParams(true); if (previousParams) { this._pushToHistory(this.current, false); this._pushToHistory(previousParams, false); this.currentUid = state.uid; window.history.back(); return; } } this.historyUnlocked = false; if (state.target.dest) { this.linkService.navigateTo(state.target.dest); } else { this.linkService.setHash(state.target.hash); } this.currentUid = state.uid; if (state.uid > this.uid) { this.uid = state.uid; } this.current = state.target; this.updatePreviousBookmark = true; var currentHash = window.location.hash.substring(1); if (this.previousHash !== currentHash) { this.allowHashChange = false; } this.previousHash = currentHash; this.historyUnlocked = true; }, back: function pdfHistoryBack() { this.go(-1); }, forward: function pdfHistoryForward() { this.go(1); }, go: function pdfHistoryGo(direction) { if (this.initialized && this.historyUnlocked) { var state = window.history.state; if (direction === -1 && state && state.uid > 0) { window.history.back(); } else if (direction === 1 && state && state.uid < (this.uid - 1)) { window.history.forward(); } } } }; exports.PDFHistory = PDFHistory; })); (function (root, factory) { { factory((root.pdfjsWebPDFLinkService = {}), root.pdfjsWebUIUtils, root.pdfjsWebDOMEvents); } }(this, function (exports, uiUtils, domEvents) { var parseQueryString = uiUtils.parseQueryString; /** * @typedef {Object} PDFLinkServiceOptions * @property {EventBus} eventBus - The application event bus. */ /** * Performs navigation functions inside PDF, such as opening specified page, * or destination. * @class * @implements {IPDFLinkService} */ var PDFLinkService = (function () { /** * @constructs PDFLinkService * @param {PDFLinkServiceOptions} options */ function PDFLinkService(options) { options = options || {}; this.eventBus = options.eventBus || domEvents.getGlobalEventBus(); this.baseUrl = null; this.pdfDocument = null; this.pdfViewer = null; this.pdfHistory = null; this._pagesRefCache = null; } PDFLinkService.prototype = { setDocument: function PDFLinkService_setDocument(pdfDocument, baseUrl) { this.baseUrl = baseUrl; this.pdfDocument = pdfDocument; this._pagesRefCache = Object.create(null); }, setViewer: function PDFLinkService_setViewer(pdfViewer) { this.pdfViewer = pdfViewer; }, setHistory: function PDFLinkService_setHistory(pdfHistory) { this.pdfHistory = pdfHistory; }, /** * @returns {number} */ get pagesCount() { return this.pdfDocument.numPages; }, /** * @returns {number} */ get page() { return this.pdfViewer.currentPageNumber; }, /** * @param {number} value */ set page(value) { this.pdfViewer.currentPageNumber = value; }, /** * @param dest - The PDF destination object. */ navigateTo: function PDFLinkService_navigateTo(dest) { var destString = ''; var self = this; var goToDestination = function(destRef) { // dest array looks like that: <page-ref> </XYZ|FitXXX> <args..> var pageNumber = destRef instanceof Object ? self._pagesRefCache[destRef.num + ' ' + destRef.gen + ' R'] : (destRef + 1); if (pageNumber) { if (pageNumber > self.pagesCount) { pageNumber = self.pagesCount; } self.pdfViewer.scrollPageIntoView(pageNumber, dest); if (self.pdfHistory) { // Update the browsing history. self.pdfHistory.push({ dest: dest, hash: destString, page: pageNumber }); } } else { self.pdfDocument.getPageIndex(destRef).then(function (pageIndex) { var pageNum = pageIndex + 1; var cacheKey = destRef.num + ' ' + destRef.gen + ' R'; self._pagesRefCache[cacheKey] = pageNum; goToDestination(destRef); }); } }; var destinationPromise; if (typeof dest === 'string') { destString = dest; destinationPromise = this.pdfDocument.getDestination(dest); } else { destinationPromise = Promise.resolve(dest); } destinationPromise.then(function(destination) { dest = destination; if (!(destination instanceof Array)) { return; // invalid destination } goToDestination(destination[0]); }); }, /** * @param dest - The PDF destination object. * @returns {string} The hyperlink to the PDF object. */ getDestinationHash: function PDFLinkService_getDestinationHash(dest) { if (typeof dest === 'string') { return this.getAnchorUrl('#' + escape(dest)); } if (dest instanceof Array) { var destRef = dest[0]; // see navigateTo method for dest format var pageNumber = destRef instanceof Object ? this._pagesRefCache[destRef.num + ' ' + destRef.gen + ' R'] : (destRef + 1); if (pageNumber) { var pdfOpenParams = this.getAnchorUrl('#page=' + pageNumber); var destKind = dest[1]; if (typeof destKind === 'object' && 'name' in destKind && destKind.name === 'XYZ') { var scale = (dest[4] || this.pdfViewer.currentScaleValue); var scaleNumber = parseFloat(scale); if (scaleNumber) { scale = scaleNumber * 100; } pdfOpenParams += '&zoom=' + scale; if (dest[2] || dest[3]) { pdfOpenParams += ',' + (dest[2] || 0) + ',' + (dest[3] || 0); } } return pdfOpenParams; } } return this.getAnchorUrl(''); }, /** * Prefix the full url on anchor links to make sure that links are resolved * relative to the current URL instead of the one defined in <base href>. * @param {String} anchor The anchor hash, including the #. * @returns {string} The hyperlink to the PDF object. */ getAnchorUrl: function PDFLinkService_getAnchorUrl(anchor) { return (this.baseUrl || '') + anchor; }, /** * @param {string} hash */ setHash: function PDFLinkService_setHash(hash) { if (hash.indexOf('=') >= 0) { var params = parseQueryString(hash); // borrowing syntax from "Parameters for Opening PDF Files" if ('nameddest' in params) { if (this.pdfHistory) { this.pdfHistory.updateNextHashParam(params.nameddest); } this.navigateTo(params.nameddest); return; } var pageNumber, dest; if ('page' in params) { pageNumber = (params.page | 0) || 1; } if ('zoom' in params) { // Build the destination array. var zoomArgs = params.zoom.split(','); // scale,left,top var zoomArg = zoomArgs[0]; var zoomArgNumber = parseFloat(zoomArg); if (zoomArg.indexOf('Fit') === -1) { // If the zoomArg is a number, it has to get divided by 100. If it's // a string, it should stay as it is. dest = [null, { name: 'XYZ' }, zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null, zoomArgs.length > 2 ? (zoomArgs[2] | 0) : null, (zoomArgNumber ? zoomArgNumber / 100 : zoomArg)]; } else { if (zoomArg === 'Fit' || zoomArg === 'FitB') { dest = [null, { name: zoomArg }]; } else if ((zoomArg === 'FitH' || zoomArg === 'FitBH') || (zoomArg === 'FitV' || zoomArg === 'FitBV')) { dest = [null, { name: zoomArg }, zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null]; } else if (zoomArg === 'FitR') { if (zoomArgs.length !== 5) { console.error('PDFLinkService_setHash: ' + 'Not enough parameters for \'FitR\'.'); } else { dest = [null, { name: zoomArg }, (zoomArgs[1] | 0), (zoomArgs[2] | 0), (zoomArgs[3] | 0), (zoomArgs[4] | 0)]; } } else { console.error('PDFLinkService_setHash: \'' + zoomArg + '\' is not a valid zoom value.'); } } } if (dest) { this.pdfViewer.scrollPageIntoView(pageNumber || this.page, dest); } else if (pageNumber) { this.page = pageNumber; // simple page } if ('pagemode' in params) { this.eventBus.dispatch('pagemode', { source: this, mode: params.pagemode }); } } else if (/^\d+$/.test(hash)) { // page number this.page = hash; } else { // named destination if (this.pdfHistory) { this.pdfHistory.updateNextHashParam(unescape(hash)); } this.navigateTo(unescape(hash)); } }, /** * @param {string} action */ executeNamedAction: function PDFLinkService_executeNamedAction(action) { // See PDF reference, table 8.45 - Named action switch (action) { case 'GoBack': if (this.pdfHistory) { this.pdfHistory.back(); } break; case 'GoForward': if (this.pdfHistory) { this.pdfHistory.forward(); } break; case 'NextPage': this.page++; break; case 'PrevPage': this.page--; break; case 'LastPage': this.page = this.pagesCount; break; case 'FirstPage': this.page = 1; break; default: break; // No action according to spec } this.eventBus.dispatch('namedaction', { source: this, action: action }); }, /** * @param {number} pageNum - page number. * @param {Object} pageRef - reference to the page. */ cachePageRef: function PDFLinkService_cachePageRef(pageNum, pageRef) { var refStr = pageRef.num + ' ' + pageRef.gen + ' R'; this._pagesRefCache[refStr] = pageNum; } }; return PDFLinkService; })(); var SimpleLinkService = (function SimpleLinkServiceClosure() { function SimpleLinkService() {} SimpleLinkService.prototype = { /** * @returns {number} */ get page() { return 0; }, /** * @param {number} value */ set page(value) {}, /** * @param dest - The PDF destination object. */ navigateTo: function (dest) {}, /** * @param dest - The PDF destination object. * @returns {string} The hyperlink to the PDF object. */ getDestinationHash: function (dest) { return '#'; }, /** * @param hash - The PDF parameters/hash. * @returns {string} The hyperlink to the PDF object. */ getAnchorUrl: function (hash) { return '#'; }, /** * @param {string} hash */ setHash: function (hash) {}, /** * @param {string} action */ executeNamedAction: function (action) {}, /** * @param {number} pageNum - page number. * @param {Object} pageRef - reference to the page. */ cachePageRef: function (pageNum, pageRef) {} }; return SimpleLinkService; })(); exports.PDFLinkService = PDFLinkService; exports.SimpleLinkService = SimpleLinkService; })); (function (root, factory) { { factory((root.pdfjsWebPDFPageView = {}), root.pdfjsWebUIUtils, root.pdfjsWebPDFRenderingQueue, root.pdfjsWebDOMEvents, root.pdfjsWebPDFJS); } }(this, function (exports, uiUtils, pdfRenderingQueue, domEvents, pdfjsLib) { var CSS_UNITS = uiUtils.CSS_UNITS; var DEFAULT_SCALE = uiUtils.DEFAULT_SCALE; var getOutputScale = uiUtils.getOutputScale; var approximateFraction = uiUtils.approximateFraction; var roundToDivide = uiUtils.roundToDivide; var RenderingStates = pdfRenderingQueue.RenderingStates; var TEXT_LAYER_RENDER_DELAY = 200; // ms /** * @typedef {Object} PDFPageViewOptions * @property {HTMLDivElement} container - The viewer element. * @property {EventBus} eventBus - The application event bus. * @property {number} id - The page unique ID (normally its number). * @property {number} scale - The page scale display. * @property {PageViewport} defaultViewport - The page viewport. * @property {PDFRenderingQueue} renderingQueue - The rendering queue object. * @property {IPDFTextLayerFactory} textLayerFactory * @property {IPDFAnnotationLayerFactory} annotationLayerFactory */ /** * @class * @implements {IRenderableView} */ var PDFPageView = (function PDFPageViewClosure() { /** * @constructs PDFPageView * @param {PDFPageViewOptions} options */ function PDFPageView(options) { var container = options.container; var id = options.id; var scale = options.scale; var defaultViewport = options.defaultViewport; var renderingQueue = options.renderingQueue; var textLayerFactory = options.textLayerFactory; var annotationLayerFactory = options.annotationLayerFactory; this.id = id; this.renderingId = 'page' + id; this.rotation = 0; this.scale = scale || DEFAULT_SCALE; this.viewport = defaultViewport; this.pdfPageRotate = defaultViewport.rotation; this.hasRestrictedScaling = false; this.eventBus = options.eventBus || domEvents.getGlobalEventBus(); this.renderingQueue = renderingQueue; this.textLayerFactory = textLayerFactory; this.annotationLayerFactory = annotationLayerFactory; this.renderingState = RenderingStates.INITIAL; this.resume = null; this.onBeforeDraw = null; this.onAfterDraw = null; this.textLayer = null; this.zoomLayer = null; this.annotationLayer = null; var div = document.createElement('div'); div.id = 'pageContainer' + this.id; div.className = 'page'; div.style.width = Math.floor(this.viewport.width) + 'px'; div.style.height = Math.floor(this.viewport.height) + 'px'; div.setAttribute('data-page-number', this.id); this.div = div; container.appendChild(div); } PDFPageView.prototype = { setPdfPage: function PDFPageView_setPdfPage(pdfPage) { this.pdfPage = pdfPage; this.pdfPageRotate = pdfPage.rotate; var totalRotation = (this.rotation + this.pdfPageRotate) % 360; this.viewport = pdfPage.getViewport(this.scale * CSS_UNITS, totalRotation); this.stats = pdfPage.stats; this.reset(); }, destroy: function PDFPageView_destroy() { this.zoomLayer = null; this.reset(); if (this.pdfPage) { this.pdfPage.cleanup(); } }, reset: function PDFPageView_reset(keepZoomLayer, keepAnnotations) { if (this.renderTask) { this.renderTask.cancel(); } this.resume = null; this.renderingState = RenderingStates.INITIAL; var div = this.div; div.style.width = Math.floor(this.viewport.width) + 'px'; div.style.height = Math.floor(this.viewport.height) + 'px'; var childNodes = div.childNodes; var currentZoomLayerNode = (keepZoomLayer && this.zoomLayer) || null; var currentAnnotationNode = (keepAnnotations && this.annotationLayer && this.annotationLayer.div) || null; for (var i = childNodes.length - 1; i >= 0; i--) { var node = childNodes[i]; if (currentZoomLayerNode === node || currentAnnotationNode === node) { continue; } div.removeChild(node); } div.removeAttribute('data-loaded'); if (currentAnnotationNode) { // Hide annotationLayer until all elements are resized // so they are not displayed on the already-resized page this.annotationLayer.hide(); } else { this.annotationLayer = null; } if (this.canvas && !currentZoomLayerNode) { // Zeroing the width and height causes Firefox to release graphics // resources immediately, which can greatly reduce memory consumption. this.canvas.width = 0; this.canvas.height = 0; delete this.canvas; } this.loadingIconDiv = document.createElement('div'); this.loadingIconDiv.className = 'loadingIcon'; div.appendChild(this.loadingIconDiv); }, update: function PDFPageView_update(scale, rotation) { this.scale = scale || this.scale; if (typeof rotation !== 'undefined') { this.rotation = rotation; } var totalRotation = (this.rotation + this.pdfPageRotate) % 360; this.viewport = this.viewport.clone({ scale: this.scale * CSS_UNITS, rotation: totalRotation }); var isScalingRestricted = false; if (this.canvas && pdfjsLib.PDFJS.maxCanvasPixels > 0) { var outputScale = this.outputScale; var pixelsInViewport = this.viewport.width * this.viewport.height; if (((Math.floor(this.viewport.width) * outputScale.sx) | 0) * ((Math.floor(this.viewport.height) * outputScale.sy) | 0) > pdfjsLib.PDFJS.maxCanvasPixels) { isScalingRestricted = true; } } if (this.canvas) { if (pdfjsLib.PDFJS.useOnlyCssZoom || (this.hasRestrictedScaling && isScalingRestricted)) { this.cssTransform(this.canvas, true); this.eventBus.dispatch('pagerendered', { source: this, pageNumber: this.id, cssTransform: true, }); return; } if (!this.zoomLayer) { this.zoomLayer = this.canvas.parentNode; this.zoomLayer.style.position = 'absolute'; } } if (this.zoomLayer) { this.cssTransform(this.zoomLayer.firstChild); } this.reset(/* keepZoomLayer = */ true, /* keepAnnotations = */ true); }, /** * Called when moved in the parent's container. */ updatePosition: function PDFPageView_updatePosition() { if (this.textLayer) { this.textLayer.render(TEXT_LAYER_RENDER_DELAY); } }, cssTransform: function PDFPageView_transform(canvas, redrawAnnotations) { var CustomStyle = pdfjsLib.CustomStyle; // Scale canvas, canvas wrapper, and page container. var width = this.viewport.width; var height = this.viewport.height; var div = this.div; canvas.style.width = canvas.parentNode.style.width = div.style.width = Math.floor(width) + 'px'; canvas.style.height = canvas.parentNode.style.height = div.style.height = Math.floor(height) + 'px'; // The canvas may have been originally rotated, rotate relative to that. var relativeRotation = this.viewport.rotation - canvas._viewport.rotation; var absRotation = Math.abs(relativeRotation); var scaleX = 1, scaleY = 1; if (absRotation === 90 || absRotation === 270) { // Scale x and y because of the rotation. scaleX = height / width; scaleY = width / height; } var cssTransform = 'rotate(' + relativeRotation + 'deg) ' + 'scale(' + scaleX + ',' + scaleY + ')'; CustomStyle.setProp('transform', canvas, cssTransform); if (this.textLayer) { // Rotating the text layer is more complicated since the divs inside the // the text layer are rotated. // TODO: This could probably be simplified by drawing the text layer in // one orientation then rotating overall. var textLayerViewport = this.textLayer.viewport; var textRelativeRotation = this.viewport.rotation - textLayerViewport.rotation; var textAbsRotation = Math.abs(textRelativeRotation); var scale = width / textLayerViewport.width; if (textAbsRotation === 90 || textAbsRotation === 270) { scale = width / textLayerViewport.height; } var textLayerDiv = this.textLayer.textLayerDiv; var transX, transY; switch (textAbsRotation) { case 0: transX = transY = 0; break; case 90: transX = 0; transY = '-' + textLayerDiv.style.height; break; case 180: transX = '-' + textLayerDiv.style.width; transY = '-' + textLayerDiv.style.height; break; case 270: transX = '-' + textLayerDiv.style.width; transY = 0; break; default: console.error('Bad rotation value.'); break; } CustomStyle.setProp('transform', textLayerDiv, 'rotate(' + textAbsRotation + 'deg) ' + 'scale(' + scale + ', ' + scale + ') ' + 'translate(' + transX + ', ' + transY + ')'); CustomStyle.setProp('transformOrigin', textLayerDiv, '0% 0%'); } if (redrawAnnotations && this.annotationLayer) { this.annotationLayer.render(this.viewport, 'display'); } }, get width() { return this.viewport.width; }, get height() { return this.viewport.height; }, getPagePoint: function PDFPageView_getPagePoint(x, y) { return this.viewport.convertToPdfPoint(x, y); }, draw: function PDFPageView_draw() { if (this.renderingState !== RenderingStates.INITIAL) { console.error('Must be in new state before drawing'); } this.renderingState = RenderingStates.RUNNING; var pdfPage = this.pdfPage; var viewport = this.viewport; var div = this.div; // Wrap the canvas so if it has a css transform for highdpi the overflow // will be hidden in FF. var canvasWrapper = document.createElement('div'); canvasWrapper.style.width = div.style.width; canvasWrapper.style.height = div.style.height; canvasWrapper.classList.add('canvasWrapper'); var canvas = document.createElement('canvas'); canvas.id = 'page' + this.id; // Keep the canvas hidden until the first draw callback, or until drawing // is complete when `!this.renderingQueue`, to prevent black flickering. canvas.setAttribute('hidden', 'hidden'); var isCanvasHidden = true; canvasWrapper.appendChild(canvas); if (this.annotationLayer && this.annotationLayer.div) { // annotationLayer needs to stay on top div.insertBefore(canvasWrapper, this.annotationLayer.div); } else { div.appendChild(canvasWrapper); } this.canvas = canvas; canvas.mozOpaque = true; var ctx = canvas.getContext('2d', {alpha: false}); var outputScale = getOutputScale(ctx); this.outputScale = outputScale; if (pdfjsLib.PDFJS.useOnlyCssZoom) { var actualSizeViewport = viewport.clone({scale: CSS_UNITS}); // Use a scale that will make the canvas be the original intended size // of the page. outputScale.sx *= actualSizeViewport.width / viewport.width; outputScale.sy *= actualSizeViewport.height / viewport.height; outputScale.scaled = true; } if (pdfjsLib.PDFJS.maxCanvasPixels > 0) { var pixelsInViewport = viewport.width * viewport.height; var maxScale = Math.sqrt(pdfjsLib.PDFJS.maxCanvasPixels / pixelsInViewport); if (outputScale.sx > maxScale || outputScale.sy > maxScale) { outputScale.sx = maxScale; outputScale.sy = maxScale; outputScale.scaled = true; this.hasRestrictedScaling = true; } else { this.hasRestrictedScaling = false; } } var sfx = approximateFraction(outputScale.sx); var sfy = approximateFraction(outputScale.sy); canvas.width = roundToDivide(viewport.width * outputScale.sx, sfx[0]); canvas.height = roundToDivide(viewport.height * outputScale.sy, sfy[0]); canvas.style.width = roundToDivide(viewport.width, sfx[1]) + 'px'; canvas.style.height = roundToDivide(viewport.height, sfy[1]) + 'px'; // Add the viewport so it's known what it was originally drawn with. canvas._viewport = viewport; var textLayerDiv = null; var textLayer = null; if (this.textLayerFactory) { textLayerDiv = document.createElement('div'); textLayerDiv.className = 'textLayer'; textLayerDiv.style.width = canvasWrapper.style.width; textLayerDiv.style.height = canvasWrapper.style.height; if (this.annotationLayer && this.annotationLayer.div) { // annotationLayer needs to stay on top div.insertBefore(textLayerDiv, this.annotationLayer.div); } else { div.appendChild(textLayerDiv); } textLayer = this.textLayerFactory.createTextLayerBuilder(textLayerDiv, this.id - 1, this.viewport); } this.textLayer = textLayer; var resolveRenderPromise, rejectRenderPromise; var promise = new Promise(function (resolve, reject) { resolveRenderPromise = resolve; rejectRenderPromise = reject; }); // Rendering area var self = this; function pageViewDrawCallback(error) { // The renderTask may have been replaced by a new one, so only remove // the reference to the renderTask if it matches the one that is // triggering this callback. if (renderTask === self.renderTask) { self.renderTask = null; } if (error === 'cancelled') { rejectRenderPromise(error); return; } self.renderingState = RenderingStates.FINISHED; if (isCanvasHidden) { self.canvas.removeAttribute('hidden'); isCanvasHidden = false; } if (self.loadingIconDiv) { div.removeChild(self.loadingIconDiv); delete self.loadingIconDiv; } if (self.zoomLayer) { // Zeroing the width and height causes Firefox to release graphics // resources immediately, which can greatly reduce memory consumption. var zoomLayerCanvas = self.zoomLayer.firstChild; zoomLayerCanvas.width = 0; zoomLayerCanvas.height = 0; div.removeChild(self.zoomLayer); self.zoomLayer = null; } self.error = error; self.stats = pdfPage.stats; if (self.onAfterDraw) { self.onAfterDraw(); } self.eventBus.dispatch('pagerendered', { source: self, pageNumber: self.id, cssTransform: false, }); if (!error) { resolveRenderPromise(undefined); } else { rejectRenderPromise(error); } } var renderContinueCallback = null; if (this.renderingQueue) { renderContinueCallback = function renderContinueCallback(cont) { if (!self.renderingQueue.isHighestPriority(self)) { self.renderingState = RenderingStates.PAUSED; self.resume = function resumeCallback() { self.renderingState = RenderingStates.RUNNING; cont(); }; return; } if (isCanvasHidden) { self.canvas.removeAttribute('hidden'); isCanvasHidden = false; } cont(); }; } var transform = !outputScale.scaled ? null : [outputScale.sx, 0, 0, outputScale.sy, 0, 0]; var renderContext = { canvasContext: ctx, transform: transform, viewport: this.viewport, // intent: 'default', // === 'display' }; var renderTask = this.renderTask = this.pdfPage.render(renderContext); renderTask.onContinue = renderContinueCallback; this.renderTask.promise.then( function pdfPageRenderCallback() { pageViewDrawCallback(null); if (textLayer) { self.pdfPage.getTextContent({ normalizeWhitespace: true }).then( function textContentResolved(textContent) { textLayer.setTextContent(textContent); textLayer.render(TEXT_LAYER_RENDER_DELAY); } ); } }, function pdfPageRenderError(error) { pageViewDrawCallback(error); } ); if (this.annotationLayerFactory) { if (!this.annotationLayer) { this.annotationLayer = this.annotationLayerFactory. createAnnotationLayerBuilder(div, this.pdfPage); } this.annotationLayer.render(this.viewport, 'display'); } div.setAttribute('data-loaded', true); if (self.onBeforeDraw) { self.onBeforeDraw(); } return promise; }, beforePrint: function PDFPageView_beforePrint(printContainer) { var CustomStyle = pdfjsLib.CustomStyle; var pdfPage = this.pdfPage; var viewport = pdfPage.getViewport(1); // Use the same hack we use for high dpi displays for printing to get // better output until bug 811002 is fixed in FF. var PRINT_OUTPUT_SCALE = 2; var canvas = document.createElement('canvas'); // The logical size of the canvas. canvas.width = Math.floor(viewport.width) * PRINT_OUTPUT_SCALE; canvas.height = Math.floor(viewport.height) * PRINT_OUTPUT_SCALE; // The rendered size of the canvas, relative to the size of canvasWrapper. canvas.style.width = (PRINT_OUTPUT_SCALE * 100) + '%'; var cssScale = 'scale(' + (1 / PRINT_OUTPUT_SCALE) + ', ' + (1 / PRINT_OUTPUT_SCALE) + ')'; CustomStyle.setProp('transform' , canvas, cssScale); CustomStyle.setProp('transformOrigin' , canvas, '0% 0%'); var canvasWrapper = document.createElement('div'); canvasWrapper.appendChild(canvas); printContainer.appendChild(canvasWrapper); canvas.mozPrintCallback = function(obj) { var ctx = obj.context; ctx.save(); ctx.fillStyle = 'rgb(255, 255, 255)'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.restore(); // Used by the mozCurrentTransform polyfill in src/display/canvas.js. ctx._transformMatrix = [PRINT_OUTPUT_SCALE, 0, 0, PRINT_OUTPUT_SCALE, 0, 0]; ctx.scale(PRINT_OUTPUT_SCALE, PRINT_OUTPUT_SCALE); var renderContext = { canvasContext: ctx, viewport: viewport, intent: 'print' }; pdfPage.render(renderContext).promise.then(function() { // Tell the printEngine that rendering this canvas/page has finished. obj.done(); }, function(error) { console.error(error); // Tell the printEngine that rendering this canvas/page has failed. // This will make the print proces stop. if ('abort' in obj) { obj.abort(); } else { obj.done(); } }); }; }, }; return PDFPageView; })(); exports.PDFPageView = PDFPageView; })); (function (root, factory) { { factory((root.pdfjsWebTextLayerBuilder = {}), root.pdfjsWebDOMEvents, root.pdfjsWebPDFJS); } }(this, function (exports, domEvents, pdfjsLib) { /** * @typedef {Object} TextLayerBuilderOptions * @property {HTMLDivElement} textLayerDiv - The text layer container. * @property {EventBus} eventBus - The application event bus. * @property {number} pageIndex - The page index. * @property {PageViewport} viewport - The viewport of the text layer. * @property {PDFFindController} findController */ /** * TextLayerBuilder provides text-selection functionality for the PDF. * It does this by creating overlay divs over the PDF text. These divs * contain text that matches the PDF text they are overlaying. This object * also provides a way to highlight text that is being searched for. * @class */ var TextLayerBuilder = (function TextLayerBuilderClosure() { function TextLayerBuilder(options) { this.textLayerDiv = options.textLayerDiv; this.eventBus = options.eventBus || domEvents.getGlobalEventBus(); this.renderingDone = false; this.divContentDone = false; this.pageIdx = options.pageIndex; this.pageNumber = this.pageIdx + 1; this.matches = []; this.viewport = options.viewport; this.textDivs = []; this.findController = options.findController || null; this.textLayerRenderTask = null; this._bindMouse(); } TextLayerBuilder.prototype = { _finishRendering: function TextLayerBuilder_finishRendering() { this.renderingDone = true; var endOfContent = document.createElement('div'); endOfContent.className = 'endOfContent'; this.textLayerDiv.appendChild(endOfContent); this.eventBus.dispatch('textlayerrendered', { source: this, pageNumber: this.pageNumber }); }, /** * Renders the text layer. * @param {number} timeout (optional) if specified, the rendering waits * for specified amount of ms. */ render: function TextLayerBuilder_render(timeout) { if (!this.divContentDone || this.renderingDone) { return; } if (this.textLayerRenderTask) { this.textLayerRenderTask.cancel(); this.textLayerRenderTask = null; } this.textDivs = []; var textLayerFrag = document.createDocumentFragment(); this.textLayerRenderTask = pdfjsLib.renderTextLayer({ textContent: this.textContent, container: textLayerFrag, viewport: this.viewport, textDivs: this.textDivs, timeout: timeout }); this.textLayerRenderTask.promise.then(function () { this.textLayerDiv.appendChild(textLayerFrag); this._finishRendering(); this.updateMatches(); }.bind(this), function (reason) { // canceled or failed to render text layer -- skipping errors }); }, setTextContent: function TextLayerBuilder_setTextContent(textContent) { if (this.textLayerRenderTask) { this.textLayerRenderTask.cancel(); this.textLayerRenderTask = null; } this.textContent = textContent; this.divContentDone = true; }, convertMatches: function TextLayerBuilder_convertMatches(matches) { var i = 0; var iIndex = 0; var bidiTexts = this.textContent.items; var end = bidiTexts.length - 1; var queryLen = (this.findController === null ? 0 : this.findController.state.query.length); var ret = []; for (var m = 0, len = matches.length; m < len; m++) { // Calculate the start position. var matchIdx = matches[m]; // Loop over the divIdxs. while (i !== end && matchIdx >= (iIndex + bidiTexts[i].str.length)) { iIndex += bidiTexts[i].str.length; i++; } if (i === bidiTexts.length) { console.error('Could not find a matching mapping'); } var match = { begin: { divIdx: i, offset: matchIdx - iIndex } }; // Calculate the end position. matchIdx += queryLen; // Somewhat the same array as above, but use > instead of >= to get // the end position right. while (i !== end && matchIdx > (iIndex + bidiTexts[i].str.length)) { iIndex += bidiTexts[i].str.length; i++; } match.end = { divIdx: i, offset: matchIdx - iIndex }; ret.push(match); } return ret; }, renderMatches: function TextLayerBuilder_renderMatches(matches) { // Early exit if there is nothing to render. if (matches.length === 0) { return; } var bidiTexts = this.textContent.items; var textDivs = this.textDivs; var prevEnd = null; var pageIdx = this.pageIdx; var isSelectedPage = (this.findController === null ? false : (pageIdx === this.findController.selected.pageIdx)); var selectedMatchIdx = (this.findController === null ? -1 : this.findController.selected.matchIdx); var highlightAll = (this.findController === null ? false : this.findController.state.highlightAll); var infinity = { divIdx: -1, offset: undefined }; function beginText(begin, className) { var divIdx = begin.divIdx; textDivs[divIdx].textContent = ''; appendTextToDiv(divIdx, 0, begin.offset, className); } function appendTextToDiv(divIdx, fromOffset, toOffset, className) { var div = textDivs[divIdx]; var content = bidiTexts[divIdx].str.substring(fromOffset, toOffset); var node = document.createTextNode(content); if (className) { var span = document.createElement('span'); span.className = className; span.appendChild(node); div.appendChild(span); return; } div.appendChild(node); } var i0 = selectedMatchIdx, i1 = i0 + 1; if (highlightAll) { i0 = 0; i1 = matches.length; } else if (!isSelectedPage) { // Not highlighting all and this isn't the selected page, so do nothing. return; } for (var i = i0; i < i1; i++) { var match = matches[i]; var begin = match.begin; var end = match.end; var isSelected = (isSelectedPage && i === selectedMatchIdx); var highlightSuffix = (isSelected ? ' selected' : ''); if (this.findController) { this.findController.updateMatchPosition(pageIdx, i, textDivs, begin.divIdx, end.divIdx); } // Match inside new div. if (!prevEnd || begin.divIdx !== prevEnd.divIdx) { // If there was a previous div, then add the text at the end. if (prevEnd !== null) { appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset); } // Clear the divs and set the content until the starting point. beginText(begin); } else { appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset); } if (begin.divIdx === end.divIdx) { appendTextToDiv(begin.divIdx, begin.offset, end.offset, 'highlight' + highlightSuffix); } else { appendTextToDiv(begin.divIdx, begin.offset, infinity.offset, 'highlight begin' + highlightSuffix); for (var n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) { textDivs[n0].className = 'highlight middle' + highlightSuffix; } beginText(end, 'highlight end' + highlightSuffix); } prevEnd = end; } if (prevEnd) { appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset); } }, updateMatches: function TextLayerBuilder_updateMatches() { // Only show matches when all rendering is done. if (!this.renderingDone) { return; } // Clear all matches. var matches = this.matches; var textDivs = this.textDivs; var bidiTexts = this.textContent.items; var clearedUntilDivIdx = -1; // Clear all current matches. for (var i = 0, len = matches.length; i < len; i++) { var match = matches[i]; var begin = Math.max(clearedUntilDivIdx, match.begin.divIdx); for (var n = begin, end = match.end.divIdx; n <= end; n++) { var div = textDivs[n]; div.textContent = bidiTexts[n].str; div.className = ''; } clearedUntilDivIdx = match.end.divIdx + 1; } if (this.findController === null || !this.findController.active) { return; } // Convert the matches on the page controller into the match format // used for the textLayer. this.matches = this.convertMatches(this.findController === null ? [] : (this.findController.pageMatches[this.pageIdx] || [])); this.renderMatches(this.matches); }, /** * Fixes text selection: adds additional div where mouse was clicked. * This reduces flickering of the content if mouse slowly dragged down/up. * @private */ _bindMouse: function TextLayerBuilder_bindMouse() { var div = this.textLayerDiv; div.addEventListener('mousedown', function (e) { var end = div.querySelector('.endOfContent'); if (!end) { return; } // On non-Firefox browsers, the selection will feel better if the height // of the endOfContent div will be adjusted to start at mouse click // location -- this will avoid flickering when selections moves up. // However it does not work when selection started on empty space. var adjustTop = e.target !== div; adjustTop = adjustTop && window.getComputedStyle(end). getPropertyValue('-moz-user-select') !== 'none'; if (adjustTop) { var divBounds = div.getBoundingClientRect(); var r = Math.max(0, (e.pageY - divBounds.top) / divBounds.height); end.style.top = (r * 100).toFixed(2) + '%'; } end.classList.add('active'); }); div.addEventListener('mouseup', function (e) { var end = div.querySelector('.endOfContent'); if (!end) { return; } end.style.top = ''; end.classList.remove('active'); }); }, }; return TextLayerBuilder; })(); /** * @constructor * @implements IPDFTextLayerFactory */ function DefaultTextLayerFactory() {} DefaultTextLayerFactory.prototype = { /** * @param {HTMLDivElement} textLayerDiv * @param {number} pageIndex * @param {PageViewport} viewport * @returns {TextLayerBuilder} */ createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) { return new TextLayerBuilder({ textLayerDiv: textLayerDiv, pageIndex: pageIndex, viewport: viewport }); } }; exports.TextLayerBuilder = TextLayerBuilder; exports.DefaultTextLayerFactory = DefaultTextLayerFactory; })); (function (root, factory) { { factory((root.pdfjsWebAnnotationLayerBuilder = {}), root.pdfjsWebUIUtils, root.pdfjsWebPDFLinkService, root.pdfjsWebPDFJS); } }(this, function (exports, uiUtils, pdfLinkService, pdfjsLib) { var mozL10n = uiUtils.mozL10n; var SimpleLinkService = pdfLinkService.SimpleLinkService; /** * @typedef {Object} AnnotationLayerBuilderOptions * @property {HTMLDivElement} pageDiv * @property {PDFPage} pdfPage * @property {IPDFLinkService} linkService * @property {DownloadManager} downloadManager */ /** * @class */ var AnnotationLayerBuilder = (function AnnotationLayerBuilderClosure() { /** * @param {AnnotationLayerBuilderOptions} options * @constructs AnnotationLayerBuilder */ function AnnotationLayerBuilder(options) { this.pageDiv = options.pageDiv; this.pdfPage = options.pdfPage; this.linkService = options.linkService; this.downloadManager = options.downloadManager; this.div = null; } AnnotationLayerBuilder.prototype = /** @lends AnnotationLayerBuilder.prototype */ { /** * @param {PageViewport} viewport * @param {string} intent (default value is 'display') */ render: function AnnotationLayerBuilder_render(viewport, intent) { var self = this; var parameters = { intent: (intent === undefined ? 'display' : intent), }; this.pdfPage.getAnnotations(parameters).then(function (annotations) { viewport = viewport.clone({ dontFlip: true }); parameters = { viewport: viewport, div: self.div, annotations: annotations, page: self.pdfPage, linkService: self.linkService, downloadManager: self.downloadManager }; if (self.div) { // If an annotationLayer already exists, refresh its children's // transformation matrices. pdfjsLib.AnnotationLayer.update(parameters); } else { // Create an annotation layer div and render the annotations // if there is at least one annotation. if (annotations.length === 0) { return; } self.div = document.createElement('div'); self.div.className = 'annotationLayer'; self.pageDiv.appendChild(self.div); parameters.div = self.div; pdfjsLib.AnnotationLayer.render(parameters); if (typeof mozL10n !== 'undefined') { mozL10n.translate(self.div); } } }); }, hide: function AnnotationLayerBuilder_hide() { if (!this.div) { return; } this.div.setAttribute('hidden', 'true'); } }; return AnnotationLayerBuilder; })(); /** * @constructor * @implements IPDFAnnotationLayerFactory */ function DefaultAnnotationLayerFactory() {} DefaultAnnotationLayerFactory.prototype = { /** * @param {HTMLDivElement} pageDiv * @param {PDFPage} pdfPage * @returns {AnnotationLayerBuilder} */ createAnnotationLayerBuilder: function (pageDiv, pdfPage) { return new AnnotationLayerBuilder({ pageDiv: pageDiv, pdfPage: pdfPage, linkService: new SimpleLinkService(), }); } }; exports.AnnotationLayerBuilder = AnnotationLayerBuilder; exports.DefaultAnnotationLayerFactory = DefaultAnnotationLayerFactory; })); (function (root, factory) { { factory((root.pdfjsWebPDFViewer = {}), root.pdfjsWebUIUtils, root.pdfjsWebPDFPageView, root.pdfjsWebPDFRenderingQueue, root.pdfjsWebTextLayerBuilder, root.pdfjsWebAnnotationLayerBuilder, root.pdfjsWebPDFLinkService, root.pdfjsWebDOMEvents, root.pdfjsWebPDFJS); } }(this, function (exports, uiUtils, pdfPageView, pdfRenderingQueue, textLayerBuilder, annotationLayerBuilder, pdfLinkService, domEvents, pdfjsLib) { var UNKNOWN_SCALE = uiUtils.UNKNOWN_SCALE; var SCROLLBAR_PADDING = uiUtils.SCROLLBAR_PADDING; var VERTICAL_PADDING = uiUtils.VERTICAL_PADDING; var MAX_AUTO_SCALE = uiUtils.MAX_AUTO_SCALE; var CSS_UNITS = uiUtils.CSS_UNITS; var DEFAULT_SCALE = uiUtils.DEFAULT_SCALE; var DEFAULT_SCALE_VALUE = uiUtils.DEFAULT_SCALE_VALUE; var scrollIntoView = uiUtils.scrollIntoView; var watchScroll = uiUtils.watchScroll; var getVisibleElements = uiUtils.getVisibleElements; var PDFPageView = pdfPageView.PDFPageView; var RenderingStates = pdfRenderingQueue.RenderingStates; var PDFRenderingQueue = pdfRenderingQueue.PDFRenderingQueue; var TextLayerBuilder = textLayerBuilder.TextLayerBuilder; var AnnotationLayerBuilder = annotationLayerBuilder.AnnotationLayerBuilder; var SimpleLinkService = pdfLinkService.SimpleLinkService; var PresentationModeState = { UNKNOWN: 0, NORMAL: 1, CHANGING: 2, FULLSCREEN: 3, }; var DEFAULT_CACHE_SIZE = 10; /** * @typedef {Object} PDFViewerOptions * @property {HTMLDivElement} container - The container for the viewer element. * @property {HTMLDivElement} viewer - (optional) The viewer element. * @property {EventBus} eventBus - The application event bus. * @property {IPDFLinkService} linkService - The navigation/linking service. * @property {DownloadManager} downloadManager - (optional) The download * manager component. * @property {PDFRenderingQueue} renderingQueue - (optional) The rendering * queue object. * @property {boolean} removePageBorders - (optional) Removes the border shadow * around the pages. The default is false. */ /** * Simple viewer control to display PDF content/pages. * @class * @implements {IRenderableView} */ var PDFViewer = (function pdfViewer() { function PDFPageViewBuffer(size) { var data = []; this.push = function cachePush(view) { var i = data.indexOf(view); if (i >= 0) { data.splice(i, 1); } data.push(view); if (data.length > size) { data.shift().destroy(); } }; this.resize = function (newSize) { size = newSize; while (data.length > size) { data.shift().destroy(); } }; } function isSameScale(oldScale, newScale) { if (newScale === oldScale) { return true; } if (Math.abs(newScale - oldScale) < 1e-15) { // Prevent unnecessary re-rendering of all pages when the scale // changes only because of limited numerical precision. return true; } return false; } /** * @constructs PDFViewer * @param {PDFViewerOptions} options */ function PDFViewer(options) { this.container = options.container; this.viewer = options.viewer || options.container.firstElementChild; this.eventBus = options.eventBus || domEvents.getGlobalEventBus(); this.linkService = options.linkService || new SimpleLinkService(); this.downloadManager = options.downloadManager || null; this.removePageBorders = options.removePageBorders || false; this.defaultRenderingQueue = !options.renderingQueue; if (this.defaultRenderingQueue) { // Custom rendering queue is not specified, using default one this.renderingQueue = new PDFRenderingQueue(); this.renderingQueue.setViewer(this); } else { this.renderingQueue = options.renderingQueue; } this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this)); this.updateInProgress = false; this.presentationModeState = PresentationModeState.UNKNOWN; this._resetView(); if (this.removePageBorders) { this.viewer.classList.add('removePageBorders'); } } PDFViewer.prototype = /** @lends PDFViewer.prototype */{ get pagesCount() { return this._pages.length; }, getPageView: function (index) { return this._pages[index]; }, get currentPageNumber() { return this._currentPageNumber; }, set currentPageNumber(val) { if (!this.pdfDocument) { this._currentPageNumber = val; return; } var arg; if (!(0 < val && val <= this.pagesCount)) { arg = { source: this, updateInProgress: this.updateInProgress, pageNumber: this._currentPageNumber, previousPageNumber: val }; this.eventBus.dispatch('pagechanging', arg); this.eventBus.dispatch('pagechange', arg); return; } arg = { source: this, updateInProgress: this.updateInProgress, pageNumber: val, previousPageNumber: this._currentPageNumber }; this.eventBus.dispatch('pagechanging', arg); this._currentPageNumber = val; this.eventBus.dispatch('pagechange', arg); // Check if the caller is `PDFViewer_update`, to avoid breaking scrolling. if (this.updateInProgress) { return; } this.scrollPageIntoView(val); }, /** * @returns {number} */ get currentScale() { return this._currentScale !== UNKNOWN_SCALE ? this._currentScale : DEFAULT_SCALE; }, /** * @param {number} val - Scale of the pages in percents. */ set currentScale(val) { if (isNaN(val)) { throw new Error('Invalid numeric scale'); } if (!this.pdfDocument) { this._currentScale = val; this._currentScaleValue = val !== UNKNOWN_SCALE ? val.toString() : null; return; } this._setScale(val, false); }, /** * @returns {string} */ get currentScaleValue() { return this._currentScaleValue; }, /** * @param val - The scale of the pages (in percent or predefined value). */ set currentScaleValue(val) { if (!this.pdfDocument) { this._currentScale = isNaN(val) ? UNKNOWN_SCALE : val; this._currentScaleValue = val; return; } this._setScale(val, false); }, /** * @returns {number} */ get pagesRotation() { return this._pagesRotation; }, /** * @param {number} rotation - The rotation of the pages (0, 90, 180, 270). */ set pagesRotation(rotation) { this._pagesRotation = rotation; for (var i = 0, l = this._pages.length; i < l; i++) { var pageView = this._pages[i]; pageView.update(pageView.scale, rotation); } this._setScale(this._currentScaleValue, true); if (this.defaultRenderingQueue) { this.update(); } }, /** * @param pdfDocument {PDFDocument} */ setDocument: function (pdfDocument) { if (this.pdfDocument) { this._resetView(); } this.pdfDocument = pdfDocument; if (!pdfDocument) { return; } var pagesCount = pdfDocument.numPages; var self = this; var resolvePagesPromise; var pagesPromise = new Promise(function (resolve) { resolvePagesPromise = resolve; }); this.pagesPromise = pagesPromise; pagesPromise.then(function () { self.eventBus.dispatch('pagesloaded', { source: self, pagesCount: pagesCount }); }); var isOnePageRenderedResolved = false; var resolveOnePageRendered = null; var onePageRendered = new Promise(function (resolve) { resolveOnePageRendered = resolve; }); this.onePageRendered = onePageRendered; var bindOnAfterAndBeforeDraw = function (pageView) { pageView.onBeforeDraw = function pdfViewLoadOnBeforeDraw() { // Add the page to the buffer at the start of drawing. That way it can // be evicted from the buffer and destroyed even if we pause its // rendering. self._buffer.push(this); }; // when page is painted, using the image as thumbnail base pageView.onAfterDraw = function pdfViewLoadOnAfterDraw() { if (!isOnePageRenderedResolved) { isOnePageRenderedResolved = true; resolveOnePageRendered(); } }; }; var firstPagePromise = pdfDocument.getPage(1); this.firstPagePromise = firstPagePromise; // Fetch a single page so we can get a viewport that will be the default // viewport for all pages return firstPagePromise.then(function(pdfPage) { var scale = this.currentScale; var viewport = pdfPage.getViewport(scale * CSS_UNITS); for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) { var textLayerFactory = null; if (!pdfjsLib.PDFJS.disableTextLayer) { textLayerFactory = this; } var pageView = new PDFPageView({ container: this.viewer, eventBus: this.eventBus, id: pageNum, scale: scale, defaultViewport: viewport.clone(), renderingQueue: this.renderingQueue, textLayerFactory: textLayerFactory, annotationLayerFactory: this }); bindOnAfterAndBeforeDraw(pageView); this._pages.push(pageView); } var linkService = this.linkService; // Fetch all the pages since the viewport is needed before printing // starts to create the correct size canvas. Wait until one page is // rendered so we don't tie up too many resources early on. onePageRendered.then(function () { if (!pdfjsLib.PDFJS.disableAutoFetch) { var getPagesLeft = pagesCount; for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) { pdfDocument.getPage(pageNum).then(function (pageNum, pdfPage) { var pageView = self._pages[pageNum - 1]; if (!pageView.pdfPage) { pageView.setPdfPage(pdfPage); } linkService.cachePageRef(pageNum, pdfPage.ref); getPagesLeft--; if (!getPagesLeft) { resolvePagesPromise(); } }.bind(null, pageNum)); } } else { // XXX: Printing is semi-broken with auto fetch disabled. resolvePagesPromise(); } }); self.eventBus.dispatch('pagesinit', {source: self}); if (this.defaultRenderingQueue) { this.update(); } if (this.findController) { this.findController.resolveFirstPage(); } }.bind(this)); }, _resetView: function () { this._pages = []; this._currentPageNumber = 1; this._currentScale = UNKNOWN_SCALE; this._currentScaleValue = null; this._buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE); this._location = null; this._pagesRotation = 0; this._pagesRequests = []; var container = this.viewer; while (container.hasChildNodes()) { container.removeChild(container.lastChild); } }, _scrollUpdate: function PDFViewer_scrollUpdate() { if (this.pagesCount === 0) { return; } this.update(); for (var i = 0, ii = this._pages.length; i < ii; i++) { this._pages[i].updatePosition(); } }, _setScaleDispatchEvent: function pdfViewer_setScaleDispatchEvent( newScale, newValue, preset) { var arg = { source: this, scale: newScale, presetValue: preset ? newValue : undefined }; this.eventBus.dispatch('scalechanging', arg); this.eventBus.dispatch('scalechange', arg); }, _setScaleUpdatePages: function pdfViewer_setScaleUpdatePages( newScale, newValue, noScroll, preset) { this._currentScaleValue = newValue; if (isSameScale(this._currentScale, newScale)) { if (preset) { this._setScaleDispatchEvent(newScale, newValue, true); } return; } for (var i = 0, ii = this._pages.length; i < ii; i++) { this._pages[i].update(newScale); } this._currentScale = newScale; if (!noScroll) { var page = this._currentPageNumber, dest; if (this._location && !pdfjsLib.PDFJS.ignoreCurrentPositionOnZoom && !(this.isInPresentationMode || this.isChangingPresentationMode)) { page = this._location.pageNumber; dest = [null, { name: 'XYZ' }, this._location.left, this._location.top, null]; } this.scrollPageIntoView(page, dest); } this._setScaleDispatchEvent(newScale, newValue, preset); if (this.defaultRenderingQueue) { this.update(); } }, _setScale: function pdfViewer_setScale(value, noScroll) { var scale = parseFloat(value); if (scale > 0) { this._setScaleUpdatePages(scale, value, noScroll, false); } else { var currentPage = this._pages[this._currentPageNumber - 1]; if (!currentPage) { return; } var hPadding = (this.isInPresentationMode || this.removePageBorders) ? 0 : SCROLLBAR_PADDING; var vPadding = (this.isInPresentationMode || this.removePageBorders) ? 0 : VERTICAL_PADDING; var pageWidthScale = (this.container.clientWidth - hPadding) / currentPage.width * currentPage.scale; var pageHeightScale = (this.container.clientHeight - vPadding) / currentPage.height * currentPage.scale; switch (value) { case 'page-actual': scale = 1; break; case 'page-width': scale = pageWidthScale; break; case 'page-height': scale = pageHeightScale; break; case 'page-fit': scale = Math.min(pageWidthScale, pageHeightScale); break; case 'auto': var isLandscape = (currentPage.width > currentPage.height); // For pages in landscape mode, fit the page height to the viewer // *unless* the page would thus become too wide to fit horizontally. var horizontalScale = isLandscape ? Math.min(pageHeightScale, pageWidthScale) : pageWidthScale; scale = Math.min(MAX_AUTO_SCALE, horizontalScale); break; default: console.error('pdfViewSetScale: \'' + value + '\' is an unknown zoom value.'); return; } this._setScaleUpdatePages(scale, value, noScroll, true); } }, /** * Scrolls page into view. * @param {number} pageNumber * @param {Array} dest - (optional) original PDF destination array: * <page-ref> </XYZ|FitXXX> <args..> */ scrollPageIntoView: function PDFViewer_scrollPageIntoView(pageNumber, dest) { if (!this.pdfDocument) { return; } var pageView = this._pages[pageNumber - 1]; if (this.isInPresentationMode) { if (this._currentPageNumber !== pageView.id) { // Avoid breaking getVisiblePages in presentation mode. this.currentPageNumber = pageView.id; return; } dest = null; // Fixes the case when PDF has different page sizes. this._setScale(this._currentScaleValue, true); } if (!dest) { scrollIntoView(pageView.div); return; } var x = 0, y = 0; var width = 0, height = 0, widthScale, heightScale; var changeOrientation = (pageView.rotation % 180 === 0 ? false : true); var pageWidth = (changeOrientation ? pageView.height : pageView.width) / pageView.scale / CSS_UNITS; var pageHeight = (changeOrientation ? pageView.width : pageView.height) / pageView.scale / CSS_UNITS; var scale = 0; switch (dest[1].name) { case 'XYZ': x = dest[2]; y = dest[3]; scale = dest[4]; // If x and/or y coordinates are not supplied, default to // _top_ left of the page (not the obvious bottom left, // since aligning the bottom of the intended page with the // top of the window is rarely helpful). x = x !== null ? x : 0; y = y !== null ? y : pageHeight; break; case 'Fit': case 'FitB': scale = 'page-fit'; break; case 'FitH': case 'FitBH': y = dest[2]; scale = 'page-width'; // According to the PDF spec, section 12.3.2.2, a `null` value in the // parameter should maintain the position relative to the new page. if (y === null && this._location) { x = this._location.left; y = this._location.top; } break; case 'FitV': case 'FitBV': x = dest[2]; width = pageWidth; height = pageHeight; scale = 'page-height'; break; case 'FitR': x = dest[2]; y = dest[3]; width = dest[4] - x; height = dest[5] - y; var hPadding = this.removePageBorders ? 0 : SCROLLBAR_PADDING; var vPadding = this.removePageBorders ? 0 : VERTICAL_PADDING; widthScale = (this.container.clientWidth - hPadding) / width / CSS_UNITS; heightScale = (this.container.clientHeight - vPadding) / height / CSS_UNITS; scale = Math.min(Math.abs(widthScale), Math.abs(heightScale)); break; default: return; } if (scale && scale !== this._currentScale) { this.currentScaleValue = scale; } else if (this._currentScale === UNKNOWN_SCALE) { this.currentScaleValue = DEFAULT_SCALE_VALUE; } if (scale === 'page-fit' && !dest[4]) { scrollIntoView(pageView.div); return; } var boundingRect = [ pageView.viewport.convertToViewportPoint(x, y), pageView.viewport.convertToViewportPoint(x + width, y + height) ]; var left = Math.min(boundingRect[0][0], boundingRect[1][0]); var top = Math.min(boundingRect[0][1], boundingRect[1][1]); scrollIntoView(pageView.div, { left: left, top: top }); }, _updateLocation: function (firstPage) { var currentScale = this._currentScale; var currentScaleValue = this._currentScaleValue; var normalizedScaleValue = parseFloat(currentScaleValue) === currentScale ? Math.round(currentScale * 10000) / 100 : currentScaleValue; var pageNumber = firstPage.id; var pdfOpenParams = '#page=' + pageNumber; pdfOpenParams += '&zoom=' + normalizedScaleValue; var currentPageView = this._pages[pageNumber - 1]; var container = this.container; var topLeft = currentPageView.getPagePoint( (container.scrollLeft - firstPage.x), (container.scrollTop - firstPage.y)); var intLeft = Math.round(topLeft[0]); var intTop = Math.round(topLeft[1]); pdfOpenParams += ',' + intLeft + ',' + intTop; this._location = { pageNumber: pageNumber, scale: normalizedScaleValue, top: intTop, left: intLeft, pdfOpenParams: pdfOpenParams }; }, update: function PDFViewer_update() { var visible = this._getVisiblePages(); var visiblePages = visible.views; if (visiblePages.length === 0) { return; } this.updateInProgress = true; var suggestedCacheSize = Math.max(DEFAULT_CACHE_SIZE, 2 * visiblePages.length + 1); this._buffer.resize(suggestedCacheSize); this.renderingQueue.renderHighestPriority(visible); var currentId = this._currentPageNumber; var firstPage = visible.first; for (var i = 0, ii = visiblePages.length, stillFullyVisible = false; i < ii; ++i) { var page = visiblePages[i]; if (page.percent < 100) { break; } if (page.id === currentId) { stillFullyVisible = true; break; } } if (!stillFullyVisible) { currentId = visiblePages[0].id; } if (!this.isInPresentationMode) { this.currentPageNumber = currentId; } this._updateLocation(firstPage); this.updateInProgress = false; this.eventBus.dispatch('updateviewarea', { source: this, location: this._location }); }, containsElement: function (element) { return this.container.contains(element); }, focus: function () { this.container.focus(); }, get isInPresentationMode() { return this.presentationModeState === PresentationModeState.FULLSCREEN; }, get isChangingPresentationMode() { return this.presentationModeState === PresentationModeState.CHANGING; }, get isHorizontalScrollbarEnabled() { return (this.isInPresentationMode ? false : (this.container.scrollWidth > this.container.clientWidth)); }, _getVisiblePages: function () { if (!this.isInPresentationMode) { return getVisibleElements(this.container, this._pages, true); } else { // The algorithm in getVisibleElements doesn't work in all browsers and // configurations when presentation mode is active. var visible = []; var currentPage = this._pages[this._currentPageNumber - 1]; visible.push({ id: currentPage.id, view: currentPage }); return { first: currentPage, last: currentPage, views: visible }; } }, cleanup: function () { for (var i = 0, ii = this._pages.length; i < ii; i++) { if (this._pages[i] && this._pages[i].renderingState !== RenderingStates.FINISHED) { this._pages[i].reset(); } } }, /** * @param {PDFPageView} pageView * @returns {PDFPage} * @private */ _ensurePdfPageLoaded: function (pageView) { if (pageView.pdfPage) { return Promise.resolve(pageView.pdfPage); } var pageNumber = pageView.id; if (this._pagesRequests[pageNumber]) { return this._pagesRequests[pageNumber]; } var promise = this.pdfDocument.getPage(pageNumber).then( function (pdfPage) { pageView.setPdfPage(pdfPage); this._pagesRequests[pageNumber] = null; return pdfPage; }.bind(this)); this._pagesRequests[pageNumber] = promise; return promise; }, forceRendering: function (currentlyVisiblePages) { var visiblePages = currentlyVisiblePages || this._getVisiblePages(); var pageView = this.renderingQueue.getHighestPriority(visiblePages, this._pages, this.scroll.down); if (pageView) { this._ensurePdfPageLoaded(pageView).then(function () { this.renderingQueue.renderView(pageView); }.bind(this)); return true; } return false; }, getPageTextContent: function (pageIndex) { return this.pdfDocument.getPage(pageIndex + 1).then(function (page) { return page.getTextContent({ normalizeWhitespace: true }); }); }, /** * @param {HTMLDivElement} textLayerDiv * @param {number} pageIndex * @param {PageViewport} viewport * @returns {TextLayerBuilder} */ createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) { return new TextLayerBuilder({ textLayerDiv: textLayerDiv, eventBus: this.eventBus, pageIndex: pageIndex, viewport: viewport, findController: this.isInPresentationMode ? null : this.findController }); }, /** * @param {HTMLDivElement} pageDiv * @param {PDFPage} pdfPage * @returns {AnnotationLayerBuilder} */ createAnnotationLayerBuilder: function (pageDiv, pdfPage) { return new AnnotationLayerBuilder({ pageDiv: pageDiv, pdfPage: pdfPage, linkService: this.linkService, downloadManager: this.downloadManager }); }, setFindController: function (findController) { this.findController = findController; }, }; return PDFViewer; })(); exports.PresentationModeState = PresentationModeState; exports.PDFViewer = PDFViewer; })); }).call(pdfViewerLibs); var PDFJS = pdfjsLib.PDFJS; PDFJS.PDFViewer = pdfViewerLibs.pdfjsWebPDFViewer.PDFViewer; PDFJS.PDFPageView = pdfViewerLibs.pdfjsWebPDFPageView.PDFPageView; PDFJS.PDFLinkService = pdfViewerLibs.pdfjsWebPDFLinkService.PDFLinkService; PDFJS.TextLayerBuilder = pdfViewerLibs.pdfjsWebTextLayerBuilder.TextLayerBuilder; PDFJS.DefaultTextLayerFactory = pdfViewerLibs.pdfjsWebTextLayerBuilder.DefaultTextLayerFactory; PDFJS.AnnotationLayerBuilder = pdfViewerLibs.pdfjsWebAnnotationLayerBuilder.AnnotationLayerBuilder; PDFJS.DefaultAnnotationLayerFactory = pdfViewerLibs.pdfjsWebAnnotationLayerBuilder.DefaultAnnotationLayerFactory; PDFJS.PDFHistory = pdfViewerLibs.pdfjsWebPDFHistory.PDFHistory; PDFJS.PDFFindController = pdfViewerLibs.pdfjsWebPDFFindController.PDFFindController; PDFJS.EventBus = pdfViewerLibs.pdfjsWebUIUtils.EventBus; PDFJS.DownloadManager = pdfViewerLibs.pdfjsWebDownloadManager.DownloadManager; PDFJS.ProgressBar = pdfViewerLibs.pdfjsWebUIUtils.ProgressBar; exports.PDFJS = PDFJS; }));
/** * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'magicline', 'it', { title: 'Inserisci paragrafo qui' } );
UI.registerHelper("removeTrailingSpaces", function(content){ return content ? content.replace(/ \n/g, "\n") : ''; });
// Copyright 2006 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Known Issues: // // * Patterns only support repeat. // * Radial gradient are not implemented. The VML version of these look very // different from the canvas one. // * Clipping paths are not implemented. // * Coordsize. The width and height attribute have higher priority than the // width and height style values which isn't correct. // * Painting mode isn't implemented. // * Canvas width/height should is using content-box by default. IE in // Quirks mode will draw the canvas using border-box. Either change your // doctype to HTML5 // (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype) // or use Box Sizing Behavior from WebFX // (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html) // * Non uniform scaling does not correctly scale strokes. // * Optimize. There is always room for speed improvements. // AMD by kener.linfeng@gmail.com define('zrender/lib/excanvas',['require'],function(require) { // Only add this code if we do not already have a canvas implementation if (!document.createElement('canvas').getContext) { (function() { // alias some functions to make (compiled) code shorter var m = Math; var mr = m.round; var ms = m.sin; var mc = m.cos; var abs = m.abs; var sqrt = m.sqrt; // this is used for sub pixel precision var Z = 10; var Z2 = Z / 2; var IE_VERSION = +navigator.userAgent.match(/MSIE ([\d.]+)?/)[1]; /** * This funtion is assigned to the <canvas> elements as element.getContext(). * @this {HTMLElement} * @return {CanvasRenderingContext2D_} */ function getContext() { return this.context_ || (this.context_ = new CanvasRenderingContext2D_(this)); } var slice = Array.prototype.slice; /** * Binds a function to an object. The returned function will always use the * passed in {@code obj} as {@code this}. * * Example: * * g = bind(f, obj, a, b) * g(c, d) // will do f.call(obj, a, b, c, d) * * @param {Function} f The function to bind the object to * @param {Object} obj The object that should act as this when the function * is called * @param {*} var_args Rest arguments that will be used as the initial * arguments when the function is called * @return {Function} A new function that has bound this */ function bind(f, obj, var_args) { var a = slice.call(arguments, 2); return function() { return f.apply(obj, a.concat(slice.call(arguments))); }; } function encodeHtmlAttribute(s) { return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;'); } function addNamespace(doc, prefix, urn) { if (!doc.namespaces[prefix]) { doc.namespaces.add(prefix, urn, '#default#VML'); } } function addNamespacesAndStylesheet(doc) { addNamespace(doc, 'g_vml_', 'urn:schemas-microsoft-com:vml'); addNamespace(doc, 'g_o_', 'urn:schemas-microsoft-com:office:office'); // Setup default CSS. Only add one style sheet per document if (!doc.styleSheets['ex_canvas_']) { var ss = doc.createStyleSheet(); ss.owningElement.id = 'ex_canvas_'; ss.cssText = 'canvas{display:inline-block;overflow:hidden;' + // default size is 300x150 in Gecko and Opera 'text-align:left;width:300px;height:150px}'; } } // Add namespaces and stylesheet at startup. addNamespacesAndStylesheet(document); var G_vmlCanvasManager_ = { init: function(opt_doc) { var doc = opt_doc || document; // Create a dummy element so that IE will allow canvas elements to be // recognized. doc.createElement('canvas'); doc.attachEvent('onreadystatechange', bind(this.init_, this, doc)); }, init_: function(doc) { // find all canvas elements var els = doc.getElementsByTagName('canvas'); for (var i = 0; i < els.length; i++) { this.initElement(els[i]); } }, /** * Public initializes a canvas element so that it can be used as canvas * element from now on. This is called automatically before the page is * loaded but if you are creating elements using createElement you need to * make sure this is called on the element. * @param {HTMLElement} el The canvas element to initialize. * @return {HTMLElement} the element that was created. */ initElement: function(el) { if (!el.getContext) { el.getContext = getContext; // Add namespaces and stylesheet to document of the element. addNamespacesAndStylesheet(el.ownerDocument); // Remove fallback content. There is no way to hide text nodes so we // just remove all childNodes. We could hide all elements and remove // text nodes but who really cares about the fallback content. el.innerHTML = ''; // do not use inline function because that will leak memory el.attachEvent('onpropertychange', onPropertyChange); el.attachEvent('onresize', onResize); var attrs = el.attributes; if (attrs.width && attrs.width.specified) { // TODO: use runtimeStyle and coordsize // el.getContext().setWidth_(attrs.width.nodeValue); el.style.width = attrs.width.nodeValue + 'px'; } else { el.width = el.clientWidth; } if (attrs.height && attrs.height.specified) { // TODO: use runtimeStyle and coordsize // el.getContext().setHeight_(attrs.height.nodeValue); el.style.height = attrs.height.nodeValue + 'px'; } else { el.height = el.clientHeight; } //el.getContext().setCoordsize_() } return el; } }; function onPropertyChange(e) { var el = e.srcElement; switch (e.propertyName) { case 'width': el.getContext().clearRect(); el.style.width = el.attributes.width.nodeValue + 'px'; // In IE8 this does not trigger onresize. el.firstChild.style.width = el.clientWidth + 'px'; break; case 'height': el.getContext().clearRect(); el.style.height = el.attributes.height.nodeValue + 'px'; el.firstChild.style.height = el.clientHeight + 'px'; break; } } function onResize(e) { var el = e.srcElement; if (el.firstChild) { el.firstChild.style.width = el.clientWidth + 'px'; el.firstChild.style.height = el.clientHeight + 'px'; } } G_vmlCanvasManager_.init(); // precompute "00" to "FF" var decToHex = []; for (var i = 0; i < 16; i++) { for (var j = 0; j < 16; j++) { decToHex[i * 16 + j] = i.toString(16) + j.toString(16); } } function createMatrixIdentity() { return [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ]; } function matrixMultiply(m1, m2) { var result = createMatrixIdentity(); for (var x = 0; x < 3; x++) { for (var y = 0; y < 3; y++) { var sum = 0; for (var z = 0; z < 3; z++) { sum += m1[x][z] * m2[z][y]; } result[x][y] = sum; } } return result; } function copyState(o1, o2) { o2.fillStyle = o1.fillStyle; o2.lineCap = o1.lineCap; o2.lineJoin = o1.lineJoin; o2.lineWidth = o1.lineWidth; o2.miterLimit = o1.miterLimit; o2.shadowBlur = o1.shadowBlur; o2.shadowColor = o1.shadowColor; o2.shadowOffsetX = o1.shadowOffsetX; o2.shadowOffsetY = o1.shadowOffsetY; o2.strokeStyle = o1.strokeStyle; o2.globalAlpha = o1.globalAlpha; o2.font = o1.font; o2.textAlign = o1.textAlign; o2.textBaseline = o1.textBaseline; o2.arcScaleX_ = o1.arcScaleX_; o2.arcScaleY_ = o1.arcScaleY_; o2.lineScale_ = o1.lineScale_; } var colorData = { aliceblue: '#F0F8FF', antiquewhite: '#FAEBD7', aquamarine: '#7FFFD4', azure: '#F0FFFF', beige: '#F5F5DC', bisque: '#FFE4C4', black: '#000000', blanchedalmond: '#FFEBCD', blueviolet: '#8A2BE2', brown: '#A52A2A', burlywood: '#DEB887', cadetblue: '#5F9EA0', chartreuse: '#7FFF00', chocolate: '#D2691E', coral: '#FF7F50', cornflowerblue: '#6495ED', cornsilk: '#FFF8DC', crimson: '#DC143C', cyan: '#00FFFF', darkblue: '#00008B', darkcyan: '#008B8B', darkgoldenrod: '#B8860B', darkgray: '#A9A9A9', darkgreen: '#006400', darkgrey: '#A9A9A9', darkkhaki: '#BDB76B', darkmagenta: '#8B008B', darkolivegreen: '#556B2F', darkorange: '#FF8C00', darkorchid: '#9932CC', darkred: '#8B0000', darksalmon: '#E9967A', darkseagreen: '#8FBC8F', darkslateblue: '#483D8B', darkslategray: '#2F4F4F', darkslategrey: '#2F4F4F', darkturquoise: '#00CED1', darkviolet: '#9400D3', deeppink: '#FF1493', deepskyblue: '#00BFFF', dimgray: '#696969', dimgrey: '#696969', dodgerblue: '#1E90FF', firebrick: '#B22222', floralwhite: '#FFFAF0', forestgreen: '#228B22', gainsboro: '#DCDCDC', ghostwhite: '#F8F8FF', gold: '#FFD700', goldenrod: '#DAA520', grey: '#808080', greenyellow: '#ADFF2F', honeydew: '#F0FFF0', hotpink: '#FF69B4', indianred: '#CD5C5C', indigo: '#4B0082', ivory: '#FFFFF0', khaki: '#F0E68C', lavender: '#E6E6FA', lavenderblush: '#FFF0F5', lawngreen: '#7CFC00', lemonchiffon: '#FFFACD', lightblue: '#ADD8E6', lightcoral: '#F08080', lightcyan: '#E0FFFF', lightgoldenrodyellow: '#FAFAD2', lightgreen: '#90EE90', lightgrey: '#D3D3D3', lightpink: '#FFB6C1', lightsalmon: '#FFA07A', lightseagreen: '#20B2AA', lightskyblue: '#87CEFA', lightslategray: '#778899', lightslategrey: '#778899', lightsteelblue: '#B0C4DE', lightyellow: '#FFFFE0', limegreen: '#32CD32', linen: '#FAF0E6', magenta: '#FF00FF', mediumaquamarine: '#66CDAA', mediumblue: '#0000CD', mediumorchid: '#BA55D3', mediumpurple: '#9370DB', mediumseagreen: '#3CB371', mediumslateblue: '#7B68EE', mediumspringgreen: '#00FA9A', mediumturquoise: '#48D1CC', mediumvioletred: '#C71585', midnightblue: '#191970', mintcream: '#F5FFFA', mistyrose: '#FFE4E1', moccasin: '#FFE4B5', navajowhite: '#FFDEAD', oldlace: '#FDF5E6', olivedrab: '#6B8E23', orange: '#FFA500', orangered: '#FF4500', orchid: '#DA70D6', palegoldenrod: '#EEE8AA', palegreen: '#98FB98', paleturquoise: '#AFEEEE', palevioletred: '#DB7093', papayawhip: '#FFEFD5', peachpuff: '#FFDAB9', peru: '#CD853F', pink: '#FFC0CB', plum: '#DDA0DD', powderblue: '#B0E0E6', rosybrown: '#BC8F8F', royalblue: '#4169E1', saddlebrown: '#8B4513', salmon: '#FA8072', sandybrown: '#F4A460', seagreen: '#2E8B57', seashell: '#FFF5EE', sienna: '#A0522D', skyblue: '#87CEEB', slateblue: '#6A5ACD', slategray: '#708090', slategrey: '#708090', snow: '#FFFAFA', springgreen: '#00FF7F', steelblue: '#4682B4', tan: '#D2B48C', thistle: '#D8BFD8', tomato: '#FF6347', turquoise: '#40E0D0', violet: '#EE82EE', wheat: '#F5DEB3', whitesmoke: '#F5F5F5', yellowgreen: '#9ACD32' }; function getRgbHslContent(styleString) { var start = styleString.indexOf('(', 3); var end = styleString.indexOf(')', start + 1); var parts = styleString.substring(start + 1, end).split(','); // add alpha if needed if (parts.length != 4 || styleString.charAt(3) != 'a') { parts[3] = 1; } return parts; } function percent(s) { return parseFloat(s) / 100; } function clamp(v, min, max) { return Math.min(max, Math.max(min, v)); } function hslToRgb(parts){ var r, g, b, h, s, l; h = parseFloat(parts[0]) / 360 % 360; if (h < 0) h++; s = clamp(percent(parts[1]), 0, 1); l = clamp(percent(parts[2]), 0, 1); if (s == 0) { r = g = b = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hueToRgb(p, q, h + 1 / 3); g = hueToRgb(p, q, h); b = hueToRgb(p, q, h - 1 / 3); } return '#' + decToHex[Math.floor(r * 255)] + decToHex[Math.floor(g * 255)] + decToHex[Math.floor(b * 255)]; } function hueToRgb(m1, m2, h) { if (h < 0) h++; if (h > 1) h--; if (6 * h < 1) return m1 + (m2 - m1) * 6 * h; else if (2 * h < 1) return m2; else if (3 * h < 2) return m1 + (m2 - m1) * (2 / 3 - h) * 6; else return m1; } var processStyleCache = {}; function processStyle(styleString) { if (styleString in processStyleCache) { return processStyleCache[styleString]; } var str, alpha = 1; styleString = String(styleString); if (styleString.charAt(0) == '#') { str = styleString; } else if (/^rgb/.test(styleString)) { var parts = getRgbHslContent(styleString); var str = '#', n; for (var i = 0; i < 3; i++) { if (parts[i].indexOf('%') != -1) { n = Math.floor(percent(parts[i]) * 255); } else { n = +parts[i]; } str += decToHex[clamp(n, 0, 255)]; } alpha = +parts[3]; } else if (/^hsl/.test(styleString)) { var parts = getRgbHslContent(styleString); str = hslToRgb(parts); alpha = parts[3]; } else { str = colorData[styleString] || styleString; } return processStyleCache[styleString] = {color: str, alpha: alpha}; } var DEFAULT_STYLE = { style: 'normal', variant: 'normal', weight: 'normal', size: 10, family: 'sans-serif' }; // Internal text style cache var fontStyleCache = {}; function processFontStyle(styleString) { if (fontStyleCache[styleString]) { return fontStyleCache[styleString]; } var el = document.createElement('div'); var style = el.style; try { style.font = styleString; } catch (ex) { // Ignore failures to set to invalid font. } return fontStyleCache[styleString] = { style: style.fontStyle || DEFAULT_STYLE.style, variant: style.fontVariant || DEFAULT_STYLE.variant, weight: style.fontWeight || DEFAULT_STYLE.weight, size: style.fontSize || DEFAULT_STYLE.size, family: style.fontFamily || DEFAULT_STYLE.family }; } function getComputedStyle(style, element) { var computedStyle = {}; for (var p in style) { computedStyle[p] = style[p]; } // Compute the size var canvasFontSize = parseFloat(element.currentStyle.fontSize), fontSize = parseFloat(style.size); if (typeof style.size == 'number') { computedStyle.size = style.size; } else if (style.size.indexOf('px') != -1) { computedStyle.size = fontSize; } else if (style.size.indexOf('em') != -1) { computedStyle.size = canvasFontSize * fontSize; } else if(style.size.indexOf('%') != -1) { computedStyle.size = (canvasFontSize / 100) * fontSize; } else if (style.size.indexOf('pt') != -1) { computedStyle.size = fontSize / .75; } else { computedStyle.size = canvasFontSize; } // Different scaling between normal text and VML text. This was found using // trial and error to get the same size as non VML text. computedStyle.size *= 0.981; return computedStyle; } function buildStyle(style) { return style.style + ' ' + style.variant + ' ' + style.weight + ' ' + style.size + 'px ' + style.family; } var lineCapMap = { 'butt': 'flat', 'round': 'round' }; function processLineCap(lineCap) { return lineCapMap[lineCap] || 'square'; } /** * This class implements CanvasRenderingContext2D interface as described by * the WHATWG. * @param {HTMLElement} canvasElement The element that the 2D context should * be associated with */ function CanvasRenderingContext2D_(canvasElement) { this.m_ = createMatrixIdentity(); this.mStack_ = []; this.aStack_ = []; this.currentPath_ = []; // Canvas context properties this.strokeStyle = '#000'; this.fillStyle = '#000'; this.lineWidth = 1; this.lineJoin = 'miter'; this.lineCap = 'butt'; this.miterLimit = Z * 1; this.globalAlpha = 1; this.font = '10px sans-serif'; this.textAlign = 'left'; this.textBaseline = 'alphabetic'; this.canvas = canvasElement; var cssText = 'width:' + canvasElement.clientWidth + 'px;height:' + canvasElement.clientHeight + 'px;overflow:hidden;position:absolute'; var el = canvasElement.ownerDocument.createElement('div'); el.style.cssText = cssText; canvasElement.appendChild(el); var overlayEl = el.cloneNode(false); // Use a non transparent background. overlayEl.style.backgroundColor = 'red'; overlayEl.style.filter = 'alpha(opacity=0)'; canvasElement.appendChild(overlayEl); this.element_ = el; this.arcScaleX_ = 1; this.arcScaleY_ = 1; this.lineScale_ = 1; } var contextPrototype = CanvasRenderingContext2D_.prototype; contextPrototype.clearRect = function() { if (this.textMeasureEl_) { this.textMeasureEl_.removeNode(true); this.textMeasureEl_ = null; } this.element_.innerHTML = ''; }; contextPrototype.beginPath = function() { // TODO: Branch current matrix so that save/restore has no effect // as per safari docs. this.currentPath_ = []; }; contextPrototype.moveTo = function(aX, aY) { var p = getCoords(this, aX, aY); this.currentPath_.push({type: 'moveTo', x: p.x, y: p.y}); this.currentX_ = p.x; this.currentY_ = p.y; }; contextPrototype.lineTo = function(aX, aY) { var p = getCoords(this, aX, aY); this.currentPath_.push({type: 'lineTo', x: p.x, y: p.y}); this.currentX_ = p.x; this.currentY_ = p.y; }; contextPrototype.bezierCurveTo = function(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { var p = getCoords(this, aX, aY); var cp1 = getCoords(this, aCP1x, aCP1y); var cp2 = getCoords(this, aCP2x, aCP2y); bezierCurveTo(this, cp1, cp2, p); }; // Helper function that takes the already fixed cordinates. function bezierCurveTo(self, cp1, cp2, p) { self.currentPath_.push({ type: 'bezierCurveTo', cp1x: cp1.x, cp1y: cp1.y, cp2x: cp2.x, cp2y: cp2.y, x: p.x, y: p.y }); self.currentX_ = p.x; self.currentY_ = p.y; } contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) { // the following is lifted almost directly from // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes var cp = getCoords(this, aCPx, aCPy); var p = getCoords(this, aX, aY); var cp1 = { x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_), y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_) }; var cp2 = { x: cp1.x + (p.x - this.currentX_) / 3.0, y: cp1.y + (p.y - this.currentY_) / 3.0 }; bezierCurveTo(this, cp1, cp2, p); }; contextPrototype.arc = function(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { aRadius *= Z; var arcType = aClockwise ? 'at' : 'wa'; var xStart = aX + mc(aStartAngle) * aRadius - Z2; var yStart = aY + ms(aStartAngle) * aRadius - Z2; var xEnd = aX + mc(aEndAngle) * aRadius - Z2; var yEnd = aY + ms(aEndAngle) * aRadius - Z2; // IE won't render arches drawn counter clockwise if xStart == xEnd. if (xStart == xEnd && !aClockwise) { xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something // that can be represented in binary } var p = getCoords(this, aX, aY); var pStart = getCoords(this, xStart, yStart); var pEnd = getCoords(this, xEnd, yEnd); this.currentPath_.push({type: arcType, x: p.x, y: p.y, radius: aRadius, xStart: pStart.x, yStart: pStart.y, xEnd: pEnd.x, yEnd: pEnd.y}); }; contextPrototype.rect = function(aX, aY, aWidth, aHeight) { this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); }; contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) { var oldPath = this.currentPath_; this.beginPath(); this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); this.stroke(); this.currentPath_ = oldPath; }; contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) { var oldPath = this.currentPath_; this.beginPath(); this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); this.fill(); this.currentPath_ = oldPath; }; contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) { var gradient = new CanvasGradient_('gradient'); gradient.x0_ = aX0; gradient.y0_ = aY0; gradient.x1_ = aX1; gradient.y1_ = aY1; return gradient; }; contextPrototype.createRadialGradient = function(aX0, aY0, aR0, aX1, aY1, aR1) { var gradient = new CanvasGradient_('gradientradial'); gradient.x0_ = aX0; gradient.y0_ = aY0; gradient.r0_ = aR0; gradient.x1_ = aX1; gradient.y1_ = aY1; gradient.r1_ = aR1; return gradient; }; contextPrototype.drawImage = function(image, var_args) { var dx, dy, dw, dh, sx, sy, sw, sh; // to find the original width we overide the width and height var oldRuntimeWidth = image.runtimeStyle.width; var oldRuntimeHeight = image.runtimeStyle.height; image.runtimeStyle.width = 'auto'; image.runtimeStyle.height = 'auto'; // get the original size var w = image.width; var h = image.height; // and remove overides image.runtimeStyle.width = oldRuntimeWidth; image.runtimeStyle.height = oldRuntimeHeight; if (arguments.length == 3) { dx = arguments[1]; dy = arguments[2]; sx = sy = 0; sw = dw = w; sh = dh = h; } else if (arguments.length == 5) { dx = arguments[1]; dy = arguments[2]; dw = arguments[3]; dh = arguments[4]; sx = sy = 0; sw = w; sh = h; } else if (arguments.length == 9) { sx = arguments[1]; sy = arguments[2]; sw = arguments[3]; sh = arguments[4]; dx = arguments[5]; dy = arguments[6]; dw = arguments[7]; dh = arguments[8]; } else { throw Error('Invalid number of arguments'); } var d = getCoords(this, dx, dy); var w2 = sw / 2; var h2 = sh / 2; var vmlStr = []; var W = 10; var H = 10; // For some reason that I've now forgotten, using divs didn't work vmlStr.push(' <g_vml_:group', ' coordsize="', Z * W, ',', Z * H, '"', ' coordorigin="0,0"' , ' style="width:', W, 'px;height:', H, 'px;position:absolute;'); // If filters are necessary (rotation exists), create them // filters are bog-slow, so only create them if abbsolutely necessary // The following check doesn't account for skews (which don't exist // in the canvas spec (yet) anyway. if (this.m_[0][0] != 1 || this.m_[0][1] || this.m_[1][1] != 1 || this.m_[1][0]) { var filter = []; // Note the 12/21 reversal filter.push('M11=', this.m_[0][0], ',', 'M12=', this.m_[1][0], ',', 'M21=', this.m_[0][1], ',', 'M22=', this.m_[1][1], ',', 'Dx=', mr(d.x / Z), ',', 'Dy=', mr(d.y / Z), ''); // Bounding box calculation (need to minimize displayed area so that // filters don't waste time on unused pixels. var max = d; var c2 = getCoords(this, dx + dw, dy); var c3 = getCoords(this, dx, dy + dh); var c4 = getCoords(this, dx + dw, dy + dh); max.x = m.max(max.x, c2.x, c3.x, c4.x); max.y = m.max(max.y, c2.y, c3.y, c4.y); vmlStr.push('padding:0 ', mr(max.x / Z), 'px ', mr(max.y / Z), 'px 0;filter:progid:DXImageTransform.Microsoft.Matrix(', filter.join(''), ", sizingmethod='clip');"); } else { vmlStr.push('top:', mr(d.y / Z), 'px;left:', mr(d.x / Z), 'px;'); } vmlStr.push(' ">' , '<g_vml_:image src="', image.src, '"', ' style="width:', Z * dw, 'px;', ' height:', Z * dh, 'px"', ' cropleft="', sx / w, '"', ' croptop="', sy / h, '"', ' cropright="', (w - sx - sw) / w, '"', ' cropbottom="', (h - sy - sh) / h, '"', ' />', '</g_vml_:group>'); this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join('')); }; contextPrototype.stroke = function(aFill) { var lineStr = []; var lineOpen = false; var W = 10; var H = 10; lineStr.push('<g_vml_:shape', ' filled="', !!aFill, '"', ' style="position:absolute;width:', W, 'px;height:', H, 'px;"', ' coordorigin="0,0"', ' coordsize="', Z * W, ',', Z * H, '"', ' stroked="', !aFill, '"', ' path="'); var newSeq = false; var min = {x: null, y: null}; var max = {x: null, y: null}; for (var i = 0; i < this.currentPath_.length; i++) { var p = this.currentPath_[i]; var c; switch (p.type) { case 'moveTo': c = p; lineStr.push(' m ', mr(p.x), ',', mr(p.y)); break; case 'lineTo': lineStr.push(' l ', mr(p.x), ',', mr(p.y)); break; case 'close': lineStr.push(' x '); p = null; break; case 'bezierCurveTo': lineStr.push(' c ', mr(p.cp1x), ',', mr(p.cp1y), ',', mr(p.cp2x), ',', mr(p.cp2y), ',', mr(p.x), ',', mr(p.y)); break; case 'at': case 'wa': lineStr.push(' ', p.type, ' ', mr(p.x - this.arcScaleX_ * p.radius), ',', mr(p.y - this.arcScaleY_ * p.radius), ' ', mr(p.x + this.arcScaleX_ * p.radius), ',', mr(p.y + this.arcScaleY_ * p.radius), ' ', mr(p.xStart), ',', mr(p.yStart), ' ', mr(p.xEnd), ',', mr(p.yEnd)); break; } // TODO: Following is broken for curves due to // move to proper paths. // Figure out dimensions so we can do gradient fills // properly if (p) { if (min.x == null || p.x < min.x) { min.x = p.x; } if (max.x == null || p.x > max.x) { max.x = p.x; } if (min.y == null || p.y < min.y) { min.y = p.y; } if (max.y == null || p.y > max.y) { max.y = p.y; } } } lineStr.push(' ">'); if (!aFill) { appendStroke(this, lineStr); } else { appendFill(this, lineStr, min, max); } lineStr.push('</g_vml_:shape>'); this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); }; function appendStroke(ctx, lineStr) { var a = processStyle(ctx.strokeStyle); var color = a.color; var opacity = a.alpha * ctx.globalAlpha; var lineWidth = ctx.lineScale_ * ctx.lineWidth; // VML cannot correctly render a line if the width is less than 1px. // In that case, we dilute the color to make the line look thinner. if (lineWidth < 1) { opacity *= lineWidth; } lineStr.push( '<g_vml_:stroke', ' opacity="', opacity, '"', ' joinstyle="', ctx.lineJoin, '"', ' miterlimit="', ctx.miterLimit, '"', ' endcap="', processLineCap(ctx.lineCap), '"', ' weight="', lineWidth, 'px"', ' color="', color, '" />' ); } function appendFill(ctx, lineStr, min, max) { var fillStyle = ctx.fillStyle; var arcScaleX = ctx.arcScaleX_; var arcScaleY = ctx.arcScaleY_; var width = max.x - min.x; var height = max.y - min.y; if (fillStyle instanceof CanvasGradient_) { // TODO: Gradients transformed with the transformation matrix. var angle = 0; var focus = {x: 0, y: 0}; // additional offset var shift = 0; // scale factor for offset var expansion = 1; if (fillStyle.type_ == 'gradient') { var x0 = fillStyle.x0_ / arcScaleX; var y0 = fillStyle.y0_ / arcScaleY; var x1 = fillStyle.x1_ / arcScaleX; var y1 = fillStyle.y1_ / arcScaleY; var p0 = getCoords(ctx, x0, y0); var p1 = getCoords(ctx, x1, y1); var dx = p1.x - p0.x; var dy = p1.y - p0.y; angle = Math.atan2(dx, dy) * 180 / Math.PI; // The angle should be a non-negative number. if (angle < 0) { angle += 360; } // Very small angles produce an unexpected result because they are // converted to a scientific notation string. if (angle < 1e-6) { angle = 0; } } else { var p0 = getCoords(ctx, fillStyle.x0_, fillStyle.y0_); focus = { x: (p0.x - min.x) / width, y: (p0.y - min.y) / height }; width /= arcScaleX * Z; height /= arcScaleY * Z; var dimension = m.max(width, height); shift = 2 * fillStyle.r0_ / dimension; expansion = 2 * fillStyle.r1_ / dimension - shift; } // We need to sort the color stops in ascending order by offset, // otherwise IE won't interpret it correctly. var stops = fillStyle.colors_; stops.sort(function(cs1, cs2) { return cs1.offset - cs2.offset; }); var length = stops.length; var color1 = stops[0].color; var color2 = stops[length - 1].color; var opacity1 = stops[0].alpha * ctx.globalAlpha; var opacity2 = stops[length - 1].alpha * ctx.globalAlpha; var colors = []; for (var i = 0; i < length; i++) { var stop = stops[i]; colors.push(stop.offset * expansion + shift + ' ' + stop.color); } // When colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. lineStr.push('<g_vml_:fill type="', fillStyle.type_, '"', ' method="none" focus="100%"', ' color="', color1, '"', ' color2="', color2, '"', ' colors="', colors.join(','), '"', ' opacity="', opacity2, '"', ' g_o_:opacity2="', opacity1, '"', ' angle="', angle, '"', ' focusposition="', focus.x, ',', focus.y, '" />'); } else if (fillStyle instanceof CanvasPattern_) { if (width && height) { var deltaLeft = -min.x; var deltaTop = -min.y; lineStr.push('<g_vml_:fill', ' position="', deltaLeft / width * arcScaleX * arcScaleX, ',', deltaTop / height * arcScaleY * arcScaleY, '"', ' type="tile"', // TODO: Figure out the correct size to fit the scale. //' size="', w, 'px ', h, 'px"', ' src="', fillStyle.src_, '" />'); } } else { var a = processStyle(ctx.fillStyle); var color = a.color; var opacity = a.alpha * ctx.globalAlpha; lineStr.push('<g_vml_:fill color="', color, '" opacity="', opacity, '" />'); } } contextPrototype.fill = function() { this.stroke(true); }; contextPrototype.closePath = function() { this.currentPath_.push({type: 'close'}); }; function getCoords(ctx, aX, aY) { var m = ctx.m_; return { x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2, y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2 }; }; contextPrototype.save = function() { var o = {}; copyState(this, o); this.aStack_.push(o); this.mStack_.push(this.m_); this.m_ = matrixMultiply(createMatrixIdentity(), this.m_); }; contextPrototype.restore = function() { if (this.aStack_.length) { copyState(this.aStack_.pop(), this); this.m_ = this.mStack_.pop(); } }; function matrixIsFinite(m) { return isFinite(m[0][0]) && isFinite(m[0][1]) && isFinite(m[1][0]) && isFinite(m[1][1]) && isFinite(m[2][0]) && isFinite(m[2][1]); } function setM(ctx, m, updateLineScale) { if (!matrixIsFinite(m)) { return; } ctx.m_ = m; if (updateLineScale) { // Get the line scale. // Determinant of this.m_ means how much the area is enlarged by the // transformation. So its square root can be used as a scale factor // for width. var det = m[0][0] * m[1][1] - m[0][1] * m[1][0]; ctx.lineScale_ = sqrt(abs(det)); } } contextPrototype.translate = function(aX, aY) { var m1 = [ [1, 0, 0], [0, 1, 0], [aX, aY, 1] ]; setM(this, matrixMultiply(m1, this.m_), false); }; contextPrototype.rotate = function(aRot) { var c = mc(aRot); var s = ms(aRot); var m1 = [ [c, s, 0], [-s, c, 0], [0, 0, 1] ]; setM(this, matrixMultiply(m1, this.m_), false); }; contextPrototype.scale = function(aX, aY) { this.arcScaleX_ *= aX; this.arcScaleY_ *= aY; var m1 = [ [aX, 0, 0], [0, aY, 0], [0, 0, 1] ]; setM(this, matrixMultiply(m1, this.m_), true); }; contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) { var m1 = [ [m11, m12, 0], [m21, m22, 0], [dx, dy, 1] ]; setM(this, matrixMultiply(m1, this.m_), true); }; contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) { var m = [ [m11, m12, 0], [m21, m22, 0], [dx, dy, 1] ]; setM(this, m, true); }; /** * The text drawing function. * The maxWidth argument isn't taken in account, since no browser supports * it yet. */ contextPrototype.drawText_ = function(text, x, y, maxWidth, stroke) { var m = this.m_, delta = 1000, left = 0, right = delta, offset = {x: 0, y: 0}, lineStr = []; var fontStyle = getComputedStyle(processFontStyle(this.font), this.element_); var fontStyleString = buildStyle(fontStyle); var elementStyle = this.element_.currentStyle; var textAlign = this.textAlign.toLowerCase(); switch (textAlign) { case 'left': case 'center': case 'right': break; case 'end': textAlign = elementStyle.direction == 'ltr' ? 'right' : 'left'; break; case 'start': textAlign = elementStyle.direction == 'rtl' ? 'right' : 'left'; break; default: textAlign = 'left'; } // 1.75 is an arbitrary number, as there is no info about the text baseline switch (this.textBaseline) { case 'hanging': case 'top': offset.y = fontStyle.size / 1.75; break; case 'middle': break; default: case null: case 'alphabetic': case 'ideographic': case 'bottom': offset.y = -fontStyle.size / 2.25; break; } switch(textAlign) { case 'right': left = delta; right = 0.05; break; case 'center': left = right = delta / 2; break; } var d = getCoords(this, x + offset.x, y + offset.y); lineStr.push('<g_vml_:line from="', -left ,' 0" to="', right ,' 0.05" ', ' coordsize="100 100" coordorigin="0 0"', ' filled="', !stroke, '" stroked="', !!stroke, '" style="position:absolute;width:1px;height:1px;">'); if (stroke) { appendStroke(this, lineStr); } else { // TODO: Fix the min and max params. appendFill(this, lineStr, {x: -left, y: 0}, {x: right, y: fontStyle.size}); } var skewM = m[0][0].toFixed(3) + ',' + m[1][0].toFixed(3) + ',' + m[0][1].toFixed(3) + ',' + m[1][1].toFixed(3) + ',0,0'; var skewOffset = mr(d.x / Z) + ',' + mr(d.y / Z); lineStr.push('<g_vml_:skew on="t" matrix="', skewM ,'" ', ' offset="', skewOffset, '" origin="', left ,' 0" />', '<g_vml_:path textpathok="true" />', '<g_vml_:textpath on="true" string="', encodeHtmlAttribute(text), '" style="v-text-align:', textAlign, ';font:', encodeHtmlAttribute(fontStyleString), '" /></g_vml_:line>'); this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); }; contextPrototype.fillText = function(text, x, y, maxWidth) { this.drawText_(text, x, y, maxWidth, false); }; contextPrototype.strokeText = function(text, x, y, maxWidth) { this.drawText_(text, x, y, maxWidth, true); }; contextPrototype.measureText = function(text) { if (!this.textMeasureEl_) { var s = '<span style="position:absolute;' + 'top:-20000px;left:0;padding:0;margin:0;border:none;' + 'white-space:pre;"></span>'; this.element_.insertAdjacentHTML('beforeEnd', s); this.textMeasureEl_ = this.element_.lastChild; } var doc = this.element_.ownerDocument; this.textMeasureEl_.innerHTML = ''; this.textMeasureEl_.style.font = this.font; // Don't use innerHTML or innerText because they allow markup/whitespace. this.textMeasureEl_.appendChild(doc.createTextNode(text)); return {width: this.textMeasureEl_.offsetWidth}; }; /******** STUBS ********/ contextPrototype.clip = function() { // TODO: Implement }; contextPrototype.arcTo = function() { // TODO: Implement }; contextPrototype.createPattern = function(image, repetition) { return new CanvasPattern_(image, repetition); }; // Gradient / Pattern Stubs function CanvasGradient_(aType) { this.type_ = aType; this.x0_ = 0; this.y0_ = 0; this.r0_ = 0; this.x1_ = 0; this.y1_ = 0; this.r1_ = 0; this.colors_ = []; } CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) { aColor = processStyle(aColor); this.colors_.push({offset: aOffset, color: aColor.color, alpha: aColor.alpha}); }; function CanvasPattern_(image, repetition) { assertImageIsValid(image); switch (repetition) { case 'repeat': case null: case '': this.repetition_ = 'repeat'; break case 'repeat-x': case 'repeat-y': case 'no-repeat': this.repetition_ = repetition; break; default: throwException('SYNTAX_ERR'); } this.src_ = image.src; this.width_ = image.width; this.height_ = image.height; } function throwException(s) { throw new DOMException_(s); } function assertImageIsValid(img) { if (!img || img.nodeType != 1 || img.tagName != 'IMG') { throwException('TYPE_MISMATCH_ERR'); } if (img.readyState != 'complete') { throwException('INVALID_STATE_ERR'); } } function DOMException_(s) { this.code = this[s]; this.message = s +': DOM Exception ' + this.code; } var p = DOMException_.prototype = new Error; p.INDEX_SIZE_ERR = 1; p.DOMSTRING_SIZE_ERR = 2; p.HIERARCHY_REQUEST_ERR = 3; p.WRONG_DOCUMENT_ERR = 4; p.INVALID_CHARACTER_ERR = 5; p.NO_DATA_ALLOWED_ERR = 6; p.NO_MODIFICATION_ALLOWED_ERR = 7; p.NOT_FOUND_ERR = 8; p.NOT_SUPPORTED_ERR = 9; p.INUSE_ATTRIBUTE_ERR = 10; p.INVALID_STATE_ERR = 11; p.SYNTAX_ERR = 12; p.INVALID_MODIFICATION_ERR = 13; p.NAMESPACE_ERR = 14; p.INVALID_ACCESS_ERR = 15; p.VALIDATION_ERR = 16; p.TYPE_MISMATCH_ERR = 17; // set up externs G_vmlCanvasManager = G_vmlCanvasManager_; CanvasRenderingContext2D = CanvasRenderingContext2D_; CanvasGradient = CanvasGradient_; CanvasPattern = CanvasPattern_; DOMException = DOMException_; })(); } // if else { // make the canvas test simple by kener.linfeng@gmail.com G_vmlCanvasManager = false; } return G_vmlCanvasManager; }); // define; /** * zrender: shape仓库 * * @desc zrender是一个轻量级的Canvas类库,MVC封装,数据驱动,提供类Dom事件模型。 * @author Kener (@Kener-林峰, linzhifeng@baidu.com) * */ define( 'zrender/shape',[],function(/*require*/) { var self = {}; var _shapeLibrary = {}; //shape库 /** * 定义图形实现 * @param {Object} name * @param {Object} clazz 图形实现 */ self.define = function(name, clazz) { _shapeLibrary[name] = clazz; return self; }; /** * 获取图形实现 * @param {Object} name */ self.get = function(name) { return _shapeLibrary[name]; }; return self; } ); /** * zrender: 向量操作类 * * author : lang(shenyi01@baidu.com) * code from vec2 in http://glmatrix.net/ */ define( 'zrender/tool/vector',[],function() { var vector = { add : function(out, v1, v2) { out[0] = v1[0]+v2[0]; out[1] = v1[1]+v2[1]; return out; }, sub : function(out, v1, v2) { out[0] = v1[0]-v2[0]; out[1] = v1[1]-v2[1]; return out; }, length : function(v) { return Math.sqrt( this.lengthSquare(v) ); }, lengthSquare : function(v) { return v[0]*v[0]+v[1]*v[1]; }, mul : function(out, v1, v2) { out[0] = v1[0]*v2[0]; out[1] = v1[1]*v2[1]; return out; }, dot : function(v1, v2) { return v1[0]*v2[0]+v1[1]*v2[1]; }, scale : function(out, v, s) { out[0] = v[0]*s; out[1] = v[1]*s; return out; }, normalize : function(out, v) { var d = vector.length(v); if(d === 0){ out[0] = 0; out[1] = 0; }else{ out[0] = v[0]/d; out[1] = v[1]/d; } return out; }, distance : function( v1, v2 ) { var out = []; return vector.length( vector.sub(out, v1, v2) ); }, middle : function(out, v1, v2) { out[0] = (v1[0]+v2[0])/2; out[1] = (v1[1]+v2[1])/2; return out; } }; return vector; } ); /** * zrender: 公共辅助函数 * * @author Kener (@Kener-林峰, linzhifeng@baidu.com) * * clone:深度克隆 * merge:合并源对象的属性到目标对象 * getContext:获取一个自由使用的canvas 2D context,使用原生方法,如isPointInPath,measureText等 */ define( 'zrender/tool/util',['require','./vector','../lib/excanvas'],function(require) { var vec2 = require('./vector'); /** * 对一个object进行深度拷贝 * * @param {Any} source 需要进行拷贝的对象 * @return {Any} 拷贝后的新对象 */ function clone(source) { // buildInObject, 用于处理无法遍历Date等对象的问题 var buildInObject = { '[object Function]': 1, '[object RegExp]': 1, '[object Date]': 1, '[object Error]': 1, '[object CanvasGradient]': 1 }; var result = source; var i; var len; if (!source || source instanceof Number || source instanceof String || source instanceof Boolean ) { return result; } else if (source instanceof Array) { result = []; var resultLen = 0; for (i = 0, len = source.length; i < len; i++) { result[resultLen++] = this.clone(source[i]); } } else if ('object' == typeof source) { if(buildInObject[Object.prototype.toString.call(source)] || source.__nonRecursion ) { return result; } result = {}; for (i in source) { if (source.hasOwnProperty(i)) { result[i] = this.clone(source[i]); } } } return result; } /** * 合并源对象的属性到目标对象 * modify from Tangram * @param {*} target 目标对象 * @param {*} source 源对象 * @param {Object} optOptions 选项 * @param {boolean} optOptions.overwrite 是否覆盖 * @param {boolean} optOptions.recursive 是否递归 * @param {boolean} optOptions.whiteList 白名单,如果定义,则仅处理白名单属性 */ var merge = (function() { // buildInObject, 用于处理无法遍历Date等对象的问题 var buildInObject = { '[object Function]': 1, '[object RegExp]': 1, '[object Date]': 1, '[object Error]': 1, '[object CanvasGradient]': 1 }; function mergeItem(target, source, index, overwrite, recursive) { if (source.hasOwnProperty(index)) { if (recursive && typeof target[index] == 'object' && buildInObject[ Object.prototype.toString.call(target[index]) ] != 1 ) { // 如果需要递归覆盖,就递归调用merge merge( target[index], source[index], { 'overwrite': overwrite, 'recursive': recursive } ); } else if (overwrite || !(index in target)) { // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况 target[index] = source[index]; } } } return function(target, source, optOptions){ var i = 0; var options = optOptions || {}; var overwrite = options['overwrite']; var whiteList = options['whiteList']; var recursive = options['recursive']; var len; // 只处理在白名单中的属性 if (whiteList && whiteList.length) { len = whiteList.length; for (; i < len; ++i) { mergeItem( target, source, whiteList[i], overwrite, recursive ); } } else { for (i in source) { mergeItem(target, source, i, overwrite, recursive); } } return target; }; })(); var _ctx; function getContext() { if (!_ctx) { require('../lib/excanvas'); if (G_vmlCanvasManager) { var _div = document.createElement('div'); _div.style.position = 'absolute'; _div.style.top = '-1000px'; document.body.appendChild(_div); _ctx = G_vmlCanvasManager.initElement(_div) .getContext('2d'); } else { _ctx = document.createElement('canvas').getContext('2d'); } } return _ctx; } var _canvas; var _pixelCtx; var _width; var _height; var _offsetX = 0; var _offsetY = 0; /** * 获取像素拾取专用的上下文 * @return {Object} 上下文 */ function getPixelContext() { if (!_pixelCtx) { _canvas = document.createElement('canvas'); _width = _canvas.width; _height = _canvas.height; _pixelCtx = _canvas.getContext('2d'); } return _pixelCtx; } /** * 如果坐标处在_canvas外部,改变_canvas的大小 * @param {number} x : 横坐标 * @param {number} y : 纵坐标 * 注意 修改canvas的大小 需要重新设置translate */ function adjustCanvasSize(x, y) { // 每次加的长度 var _v = 100; var _flag = false; if (x + _offsetX > _width) { _width = x + _offsetX + _v; _canvas.width = _width; _flag = true; } if (y + _offsetY > _height) { _height = y + _offsetY + _v; _canvas.height = _height; _flag = true; } if (x < -_offsetX) { _offsetX = Math.ceil(-x / _v) * _v; _width += _offsetX; _canvas.width = _width; _flag = true; } if (y < -_offsetY) { _offsetY = Math.ceil(-y / _v) * _v; _height += _offsetY; _canvas.height = _height; _flag = true; } if (_flag) { _pixelCtx.translate(_offsetX, _offsetY); } } /** * 获取像素canvas的偏移量 * @return {Object} 偏移量 */ function getPixelOffset() { return { x : _offsetX, y : _offsetY }; } /** * 查询数组中元素的index */ function indexOf(array, value){ if (array.indexOf) { return array.indexOf(value); } for(var i = 0, len=array.length; i<len; i++) { if (array[i] === value) { return i; } } return -1; } /** * 计算包围盒 */ function computeBoundingBox(points, min, max) { if (points.length === 0) { return; } var left = points[0][0]; var right = points[0][0]; var top = points[0][1]; var bottom = points[0][1]; for (var i = 1; i < points.length; i++) { var p = points[i]; if (p[0] < left) { left = p[0]; } if (p[0] > right) { right = p[0]; } if (p[1] < top) { top = p[1]; } if (p[1] > bottom) { bottom = p[1]; } } min[0] = left; min[1] = top; max[0] = right; max[1] = bottom; } /** * 计算三阶贝塞尔曲线的包围盒 * http://pissang.net/blog/?p=91 */ function computeCubeBezierBoundingBox(p0, p1, p2, p3, min, max) { var xDim = _computeCubeBezierExtremitiesDim( p0[0], p1[0], p2[0], p3[0] ); var yDim = _computeCubeBezierExtremitiesDim( p0[1], p1[1], p2[1], p3[1] ); xDim.push(p0[0], p3[0]); yDim.push(p0[1], p3[1]); var left = Math.min.apply(null, xDim); var right = Math.max.apply(null, xDim); var top = Math.min.apply(null, yDim); var bottom = Math.max.apply(null, yDim); min[0] = left; min[1] = top; max[0] = right; max[1] = bottom; } function _computeCubeBezierExtremitiesDim(p0, p1, p2, p3) { var extremities = []; var b = 6 * p2 - 12 * p1 + 6 * p0; var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2; var c = 3 * p1 - 3 * p0; var tmp = b * b - 4 * a * c; if (tmp > 0){ var tmpSqrt = Math.sqrt(tmp); var t1 = (-b + tmpSqrt) / (2 * a); var t2 = (-b - tmpSqrt) / (2 * a); extremities.push(t1, t2); } else if (tmp === 0) { extremities.push(-b / (2 * a)); } var result = []; for (var i = 0; i < extremities.length; i++) { var t = extremities[i]; if (Math.abs(2 * a * t + b) > 0.0001 && t < 1 && t > 0) { var ct = 1 - t; var val = ct * ct * ct * p0 + 3 * ct * ct * t * p1 + 3 * ct * t * t * p2 + t * t *t * p3; result.push(val); } } return result; } /** * 计算二阶贝塞尔曲线的包围盒 * http://pissang.net/blog/?p=91 */ function computeQuadraticBezierBoundingBox(p0, p1, p2, min, max) { // Find extremities, where derivative in x dim or y dim is zero var tmp = (p0[0] + p2[0] - 2 * p1[0]); // p1 is center of p0 and p2 in x dim var t1; if (tmp === 0) { t1 = 0.5; } else { t1 = (p0[0] - p1[0]) / tmp; } tmp = (p0[1] + p2[1] - 2 * p1[1]); // p1 is center of p0 and p2 in y dim var t2; if (tmp === 0) { t2 = 0.5; } else { t2 = (p0[1] - p1[1]) / tmp; } t1 = Math.max(Math.min(t1, 1), 0); t2 = Math.max(Math.min(t2, 1), 0); var ct1 = 1-t1; var ct2 = 1-t2; var x1 = ct1 * ct1 * p0[0] + 2 * ct1 * t1 * p1[0] + t1 * t1 * p2[0]; var y1 = ct1 * ct1 * p0[1] + 2 * ct1 * t1 * p1[1] + t1 * t1 * p2[1]; var x2 = ct2 * ct2 * p0[0] + 2 * ct2 * t2 * p1[0] + t2 * t2 * p2[0]; var y2 = ct2 * ct2 * p0[1] + 2 * ct2 * t2 * p1[1] + t2 * t2 * p2[1]; return computeBoundingBox( [p0.slice(), p2.slice(), [x1, y1], [x2, y2]], min, max ); } /** * 计算圆弧的包围盒 * http://pissang.net/blog/?p=91 */ var computeArcBoundingBox = (function(){ var start = []; var end = []; // At most 4 extremities var extremities = [[], [], [], []]; return function( center, radius, startAngle, endAngle, clockwise, min, max ) { clockwise = clockwise ? 1 : -1; start[0] = Math.cos(startAngle); start[1] = Math.sin(startAngle) * clockwise; vec2.scale(start, start, radius); vec2.add(start, start, center); end[0] = Math.cos(endAngle); end[1] = Math.sin(endAngle) * clockwise; vec2.scale(end, end, radius); vec2.add(end, end, center); startAngle = startAngle % (Math.PI * 2); if (startAngle < 0) { startAngle = startAngle + Math.PI * 2; } endAngle = endAngle % (Math.PI * 2); if (endAngle < 0) { endAngle = endAngle + Math.PI * 2; } if (startAngle > endAngle) { endAngle += Math.PI * 2; } var number = 0; for (var angle = 0; angle < endAngle; angle += Math.PI / 2) { if (angle > startAngle) { var extremity = extremities[number++]; extremity[0] = Math.cos(angle); extremity[1] = Math.sin(angle) * clockwise; vec2.scale(extremity, extremity, radius); vec2.add(extremity, extremity, center); } } var points = extremities.slice(0, number); points.push(start, end); computeBoundingBox(points, min, max); }; })(); return { clone : clone, merge : merge, getContext : getContext, getPixelContext : getPixelContext, getPixelOffset : getPixelOffset, adjustCanvasSize : adjustCanvasSize, computeBoundingBox : computeBoundingBox, computeCubeBezierBoundingBox : computeCubeBezierBoundingBox, computeQuadraticBezierBoundingBox : computeQuadraticBezierBoundingBox, computeArcBoundingBox : computeArcBoundingBox, indexOf : indexOf }; } ); /** * zrender: 图形空间辅助类 * * @author Kener (@Kener-林峰, linzhifeng@baidu.com) * * isInside:是否在区域内部 * isOutside:是否在区域外部 * getTextWidth:测算单行文本宽度 */ define( 'zrender/tool/area',['require','../tool/util'],function(require) { var util = require('../tool/util'); var _ctx; /** * 包含判断 * @param {string} shapeClazz : 图形类 * @param {Object} area : 目标区域 * @param {number} x : 横坐标 * @param {number} y : 纵坐标 */ function isInside(shapeClazz, area, x, y) { if (!area || !shapeClazz) { // 无参数或不支持类型 return false; } var zoneType = shapeClazz.type; if (!_ctx) { _ctx = util.getContext(); } if (!_isInsideRectangle( area.__rect || shapeClazz.getRect(area), x, y ) ) { // 不在矩形区域内直接返回false return false; } // 未实现或不可用时(excanvas不支持)则数学运算,主要是line,brokenLine,ring var _mathReturn = _mathMethod(zoneType, area, x, y); if (typeof _mathReturn != 'undefined') { return _mathReturn; } if (zoneType != 'beziercurve' && shapeClazz.buildPath && _ctx.isPointInPath ) { return _buildPathMethod(shapeClazz, _ctx, area, x, y); } else if (_ctx.getImageData) { return _pixelMethod(shapeClazz, area, x, y); } // 上面的方法都行不通时 switch (zoneType) { //心形----------------------10 case 'heart': return true; // Todo,不精确 //水滴----------------------11 case 'droplet': return true; // Todo,不精确 case 'ellipse': return true; // Todo,不精确 // 旋轮曲线 不准确 case 'trochoid': var _r = area.location == 'out' ? area.r1 + area.r2 + area.d : area.r1 - area.r2 + area.d; return _isInsideCircle(area, x, y, _r); // 玫瑰线 不准确 case 'rose' : return _isInsideCircle(area, x, y, area.maxr); //路径,椭圆,曲线等-----------------13 default: return false; // Todo,暂不支持 } } /** * 用数学方法判断,三个方法中最快,但是支持的shape少 * * @param {string} zoneType : 图形类型 * @param {Object} area :目标区域 * @param {number} x : 横坐标 * @param {number} y : 纵坐标 * @return {boolean=} true表示坐标处在图形中 */ function _mathMethod(zoneType, area, x, y) { // 在矩形内则部分图形需要进一步判断 switch (zoneType) { //线-----------------------1 case 'line': return _isInsideLine(area, x, y); //折线----------------------2 case 'brokenLine': return _isInsideBrokenLine(area, x, y); //文本----------------------3 case 'text': return true; //圆环----------------------4 case 'ring': return _isInsideRing(area, x, y); //矩形----------------------5 case 'rectangle': return true; //圆形----------------------6 case 'circle': return _isInsideCircle(area, x, y, area.r); //扇形----------------------7 case 'sector': return _isInsideSector(area, x, y); //多边形---------------------8 case 'path': return _isInsidePath(area, x, y); case 'polygon': case 'star': case 'isogon': return _isInsidePolygon(area, x, y); //图片----------------------9 case 'image': return true; } } /** * 通过buildPath方法来判断,三个方法中较快,但是不支持线条类型的shape, * 而且excanvas不支持isPointInPath方法 * * @param {Object} shapeClazz : shape类 * @param {Object} context : 上下文 * @param {Object} area :目标区域 * @param {number} x : 横坐标 * @param {number} y : 纵坐标 * @return {boolean} true表示坐标处在图形中 */ function _buildPathMethod(shapeClazz, context, area, x, y) { // 图形类实现路径创建了则用类的path context.beginPath(); shapeClazz.buildPath(context, area); context.closePath(); return context.isPointInPath(x, y); } /** * 通过像素值来判断,三个方法中最慢,但是支持广,不足之处是excanvas不支持像素处理 * * @param {Object} shapeClazz : shape类 * @param {Object} area :目标区域 * @param {number} x : 横坐标 * @param {number} y : 纵坐标 * @return {boolean} true表示坐标处在图形中 */ function _pixelMethod(shapeClazz, area, x, y) { var _rect = area.__rect || shapeClazz.getRect(area); var _context = util.getPixelContext(); var _offset = util.getPixelOffset(); util.adjustCanvasSize(x, y); _context.clearRect(_rect.x, _rect.y, _rect.width, _rect.height); _context.beginPath(); shapeClazz.brush(_context, {style : area}); _context.closePath(); return _isPainted(_context, x + _offset.x, y + _offset.y); } /** * 坐标像素值,判断坐标是否被作色 * * @param {Object} context : 上下文 * @param {number} x : 横坐标 * @param {number} y : 纵坐标 * @param {number=} unit : 触发的精度,越大越容易触发,可选,缺省是为1 * @return {boolean} 已经被画过返回true */ function _isPainted(context, x, y, unit) { var pixelsData; if (typeof unit != 'undefined') { unit = Math.floor((unit || 1 )/ 2); pixelsData = context.getImageData( x - unit, y - unit, unit + unit, unit + unit ).data; } else { pixelsData = context.getImageData(x, y, 1, 1).data; } var len = pixelsData.length; while (len--) { if (pixelsData[len] !== 0) { return true; } } return false; } /** * !isInside */ function isOutside(shapeClazz, area, x, y) { return !isInside(shapeClazz, area, x, y); } /** * 线段包含判断 */ function _isInsideLine(area, x, y) { var _x1 = area.xStart; var _y1 = area.yStart; var _x2 = area.xEnd; var _y2 = area.yEnd; var _l = area.lineWidth; var _a = 0; var _b = _x1; if (_x1 !== _x2) { _a = (_y1 - _y2) / (_x1 - _x2); _b = (_x1 * _y2 - _x2 * _y1) / (_x1 - _x2) ; } else { return Math.abs(x - _x1) <= _l / 2; } var _s = (_a * x - y + _b) * (_a * x - y + _b) / (_a * _a + 1); return _s <= _l / 2 * _l / 2; } function _isInsideBrokenLine(area, x, y) { var pointList = area.pointList; var lineArea; var insideCatch = false; for (var i = 0, l = pointList.length - 1; i < l; i++) { lineArea = { xStart : pointList[i][0], yStart : pointList[i][1], xEnd : pointList[i + 1][0], yEnd : pointList[i + 1][1], lineWidth : area.lineWidth }; if (!_isInsideRectangle( { x : Math.min(lineArea.xStart, lineArea.xEnd) - lineArea.lineWidth, y : Math.min(lineArea.yStart, lineArea.yEnd) - lineArea.lineWidth, width : Math.abs(lineArea.xStart - lineArea.xEnd) + lineArea.lineWidth, height : Math.abs(lineArea.yStart - lineArea.yEnd) + lineArea.lineWidth }, x,y ) ) { // 不在矩形区内跳过 continue; } insideCatch = _isInsideLine(lineArea, x, y); if (insideCatch) { break; } } return insideCatch; } function _isInsideRing(area, x, y) { if (_isInsideCircle(area, x, y, area.r) && !_isInsideCircle( { x : area.x, y : area.y }, x, y, area.r0 || 0 ) ){ // 大圆内,小圆外 return true; } return false; } /** * 矩形包含判断 */ function _isInsideRectangle(area, x, y) { if (x >= area.x && x <= (area.x + area.width) && y >= area.y && y <= (area.y + area.height) ) { return true; } return false; } /** * 圆形包含判断 */ function _isInsideCircle(area, x, y, r) { return (x - area.x) * (x - area.x) + (y - area.y) * (y - area.y) < r * r; } /** * 扇形包含判断 */ function _isInsideSector(area, x, y) { if (!_isInsideCircle(area, x, y, area.r) || (area.r0 > 0 && _isInsideCircle( { x : area.x, y : area.y }, x, y, area.r0 ) ) ){ // 大圆外或者小圆内直接false return false; } else { // 判断夹角 var angle = (360 - Math.atan2(y - area.y, x - area.x) / Math.PI * 180) % 360; var endA = (360 + area.endAngle) % 360; var startA = (360 + area.startAngle) % 360; if (endA > startA) { return (angle >= startA && angle <= endA); } else { return !(angle >= endA && angle <= startA); } } } /** * 多边形包含判断 * 警告:下面这段代码会很难看,建议跳过~ */ function _isInsidePolygon(area, x, y) { /** * 射线判别法 * 如果一个点在多边形内部,任意角度做射线肯定会与多边形要么有一个交点,要么有与多边形边界线重叠 * 如果一个点在多边形外部,任意角度做射线要么与多边形有一个交点, * 要么有两个交点,要么没有交点,要么有与多边形边界线重叠。 */ var i; var j; var polygon = area.pointList; var N = polygon.length; var inside = false; var redo = true; var v; for (i = 0; i < N; ++i) { // 是否在顶点上 if (polygon[i][0] == x && polygon[i][1] == y ) { redo = false; inside = true; break; } } if (redo) { redo = false; inside = false; for (i = 0,j = N - 1;i < N;j = i++) { if ((polygon[i][1] < y && y < polygon[j][1]) || (polygon[j][1] < y && y < polygon[i][1]) ) { if (x <= polygon[i][0] || x <= polygon[j][0]) { v = (y - polygon[i][1]) * (polygon[j][0] - polygon[i][0]) / (polygon[j][1] - polygon[i][1]) + polygon[i][0]; if (x < v) { // 在线的左侧 inside = !inside; } else if (x == v) { // 在线上 inside = true; break; } } } else if (y == polygon[i][1]) { if (x < polygon[i][0]) { // 交点在顶点上 polygon[i][1] > polygon[j][1] ? --y : ++y; //redo = true; break; } } else if (polygon[i][1] == polygon[j][1] // 在水平的边界线上 && y == polygon[i][1] && ((polygon[i][0] < x && x < polygon[j][0]) || (polygon[j][0] < x && x < polygon[i][0])) ) { inside = true; break; } } } return inside; } /** * 路径包含判断,依赖多边形判断 */ function _isInsidePath(area, x, y) { var pointList = area.pointList; var insideCatch = false; for (var i = 0, l = pointList.length; i < l; i++) { insideCatch = _isInsidePolygon( { pointList : pointList[i] }, x, y ); if (insideCatch) { break; } } return insideCatch; } /** * 测算单行文本欢度 * @param {Object} text * @param {Object} textFont */ function getTextWidth(text, textFont) { if (!_ctx) { _ctx = util.getContext(); } _ctx.save(); if (textFont) { _ctx.font = textFont; } var width = _ctx.measureText(text).width; _ctx.restore(); return width; } return { isInside : isInside, isOutside : isOutside, getTextWidth : getTextWidth }; } ); /** * zrender: 3x2矩阵操作类 * * author: lang(shenyi01@baidu.com) * code from mat2d in http://glmatrix.net/ */ define( 'zrender/tool/matrix',[],function() { var matrix = { create : function() { return [1, 0, 0, 1, 0, 0]; }, identity : function(out) { out[0] = 1; out[1] = 0; out[2] = 0; out[3] = 1; out[4] = 0; out[5] = 0; }, mul : function(out, m1, m2) { out[0] = m1[0] * m2[0] + m1[2] * m2[1]; out[1] = m1[1] * m2[0] + m1[3] * m2[1]; out[2] = m1[0] * m2[2] + m1[2] * m2[3]; out[3] = m1[1] * m2[2] + m1[3] * m2[3]; out[4] = m1[0] * m2[4] + m1[2] * m2[5] + m1[4]; out[5] = m1[1] * m2[4] + m1[3] * m2[5] + m1[5]; return out; }, translate : function(out, a, v) { out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3]; out[4] = a[4] + v[0]; out[5] = a[5] + v[1]; return out; }, rotate : function(out, a, rad) { var aa = a[0], ac = a[2], atx = a[4]; var ab = a[1], ad = a[3], aty = a[5]; var st = Math.sin(rad); var ct = Math.cos(rad); out[0] = aa*ct + ab*st; out[1] = -aa*st + ab*ct; out[2] = ac*ct + ad*st; out[3] = -ac*st + ct*ad; out[4] = ct*atx + st*aty; out[5] = ct*aty - st*atx; return out; }, scale : function(out, a, v) { var vx = v[0], vy = v[1]; out[0] = a[0] * vx; out[1] = a[1] * vy; out[2] = a[2] * vx; out[3] = a[3] * vy; out[4] = a[4] * vx; out[5] = a[5] * vy; return out; }, /** * 求逆矩阵 */ invert : function(out, a) { var aa = a[0], ac = a[2], atx = a[4]; var ab = a[1], ad = a[3], aty = a[5]; var det = aa * ad - ab * ac; if(!det){ return null; } det = 1.0 / det; out[0] = ad * det; out[1] = -ab * det; out[2] = -ac * det; out[3] = aa * det; out[4] = (ac * aty - ad * atx) * det; out[5] = (ab * atx - aa * aty) * det; return out; }, /** * 矩阵左乘向量 */ mulVector : function(out, a, v) { var aa = a[0], ac = a[2], atx = a[4]; var ab = a[1], ad = a[3], aty = a[5]; out[0] = v[0] * aa + v[1] * ac + atx; out[1] = v[0] * ab + v[1] * ad + aty; return out; } }; return matrix; } ); /** * zrender : 颜色辅助类 * * author: CrossDo (chenhuaimu@baidu.com) * * getColor:获取色板颜色 * customPalette : 自定义调色板 * resetPalette : 重置调色板 * * getHighlightColor : 获取默认高亮颜色 * customHighlight : 自定义默认高亮颜色 * resetHighlight : 重置默认高亮颜色 * * getRadialGradient : 径向渐变 * getLinearGradient : 线性渐变 * getGradientColors : 获取颜色之间渐变颜色数组 * getStepColors : 获取两种颜色之间渐变颜色数组 * reverse : 颜色翻转 * mix : 颜色混合 * lift : 颜色升降 * trim : 清除空格 * random : 随机颜色 * toRGB : 转为RGB格式 * toRGBA : 转为RGBA格式 * toHex : 转为#RRGGBB格式 * toHSL : 转为HSL格式 * toHSLA : 转为HSLA格式 * toHSB : 转为HSB格式 * toHSBA : 转为HSBA格式 * toHSV : 转为HSV格式 * toHSVA : 转为HSVA格式 * toName : 转为颜色名字 * toColor: 颜色值数组转为指定格式颜色 * toArray: 返回颜色值数组 * alpha : 设置颜色的透明度 **/ define( 'zrender/tool/color',['require','../tool/util'],function(require) { var util = require('../tool/util'); var _ctx; // Color palette is an array containing the default colors for the chart's // series. // When all colors are used, new colors are selected from the start again. // Defaults to: // 默认色板 var palette = [ '#ff9277', ' #dddd00', ' #ffc877', ' #bbe3ff', ' #d5ffbb', '#bbbbff', ' #ddb000', ' #b0dd00', ' #e2bbff', ' #ffbbe3', '#ff7777', ' #ff9900', ' #83dd00', ' #77e3ff', ' #778fff', '#c877ff', ' #ff77ab', ' #ff6600', ' #aa8800', ' #77c7ff', '#ad77ff', ' #ff77ff', ' #dd0083', ' #777700', ' #00aa00', '#0088aa', ' #8400dd', ' #aa0088', ' #dd0000', ' #772e00' ]; var _palette = palette; var highlightColor = 'rgba(255,255,0,0.5)'; var _highlightColor = highlightColor; // 颜色格式 /*jshint maxlen: 330 */ var colorRegExp = /^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+%?(?:\s*,\s*[\d\.]+%?)?)\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+%?(?:\s*,\s*[\d\.]+)?)%?\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+%?(?:\s*,\s*[\d\.]+)?)%?\s*\))\s*$/i; var _nameColors = { aliceblue : '#f0f8ff', antiquewhite : '#faebd7', aqua : '#0ff', aquamarine : '#7fffd4', azure : '#f0ffff', beige : '#f5f5dc', bisque : '#ffe4c4', black : '#000', blanchedalmond : '#ffebcd', blue : '#00f', blueviolet : '#8a2be2', brown : '#a52a2a', burlywood : '#deb887', cadetblue : '#5f9ea0', chartreuse : '#7fff00', chocolate : '#d2691e', coral : '#ff7f50', cornflowerblue : '#6495ed', cornsilk : '#fff8dc', crimson : '#dc143c', cyan : '#0ff', darkblue : '#00008b', darkcyan : '#008b8b', darkgoldenrod : '#b8860b', darkgray : '#a9a9a9', darkgrey : '#a9a9a9', darkgreen : '#006400', darkkhaki : '#bdb76b', darkmagenta : '#8b008b', darkolivegreen : '#556b2f', darkorange : '#ff8c00', darkorchid : '#9932cc', darkred : '#8b0000', darksalmon : '#e9967a', darkseagreen : '#8fbc8f', darkslateblue : '#483d8b', darkslategray : '#2f4f4f', darkslategrey : '#2f4f4f', darkturquoise : '#00ced1', darkviolet : '#9400d3', deeppink : '#ff1493', deepskyblue : '#00bfff', dimgray : '#696969', dimgrey : '#696969', dodgerblue : '#1e90ff', firebrick : '#b22222', floralwhite : '#fffaf0', forestgreen : '#228b22', fuchsia : '#f0f', gainsboro : '#dcdcdc', ghostwhite : '#f8f8ff', gold : '#ffd700', goldenrod : '#daa520', gray : '#808080', grey : '#808080', green : '#008000', greenyellow : '#adff2f', honeydew : '#f0fff0', hotpink : '#ff69b4', indianred : '#cd5c5c', indigo : '#4b0082', ivory : '#fffff0', khaki : '#f0e68c', lavender : '#e6e6fa', lavenderblush : '#fff0f5', lawngreen : '#7cfc00', lemonchiffon : '#fffacd', lightblue : '#add8e6', lightcoral : '#f08080', lightcyan : '#e0ffff', lightgoldenrodyellow : '#fafad2', lightgray : '#d3d3d3', lightgrey : '#d3d3d3', lightgreen : '#90ee90', lightpink : '#ffb6c1', lightsalmon : '#ffa07a', lightseagreen : '#20b2aa', lightskyblue : '#87cefa', lightslategray : '#789', lightslategrey : '#789', lightsteelblue : '#b0c4de', lightyellow : '#ffffe0', lime : '#0f0', limegreen : '#32cd32', linen : '#faf0e6', magenta : '#f0f', maroon : '#800000', mediumaquamarine : '#66cdaa', mediumblue : '#0000cd', mediumorchid : '#ba55d3', mediumpurple : '#9370d8', mediumseagreen : '#3cb371', mediumslateblue : '#7b68ee', mediumspringgreen : '#00fa9a', mediumturquoise : '#48d1cc', mediumvioletred : '#c71585', midnightblue : '#191970', mintcream : '#f5fffa', mistyrose : '#ffe4e1', moccasin : '#ffe4b5', navajowhite : '#ffdead', navy : '#000080', oldlace : '#fdf5e6', olive : '#808000', olivedrab : '#6b8e23', orange : '#ffa500', orangered : '#ff4500', orchid : '#da70d6', palegoldenrod : '#eee8aa', palegreen : '#98fb98', paleturquoise : '#afeeee', palevioletred : '#d87093', papayawhip : '#ffefd5', peachpuff : '#ffdab9', peru : '#cd853f', pink : '#ffc0cb', plum : '#dda0dd', powderblue : '#b0e0e6', purple : '#800080', red : '#f00', rosybrown : '#bc8f8f', royalblue : '#4169e1', saddlebrown : '#8b4513', salmon : '#fa8072', sandybrown : '#f4a460', seagreen : '#2e8b57', seashell : '#fff5ee', sienna : '#a0522d', silver : '#c0c0c0', skyblue : '#87ceeb', slateblue : '#6a5acd', slategray : '#708090', slategrey : '#708090', snow : '#fffafa', springgreen : '#00ff7f', steelblue : '#4682b4', tan : '#d2b48c', teal : '#008080', thistle : '#d8bfd8', tomato : '#ff6347', turquoise : '#40e0d0', violet : '#ee82ee', wheat : '#f5deb3', white : '#fff', whitesmoke : '#f5f5f5', yellow : '#ff0', yellowgreen : '#9acd32' }; /** * 自定义调色板 */ function customPalette(userPalete) { palette = userPalete; } /** * 复位默认色板 */ function resetPalette() { palette = _palette; } /** * 获取色板颜色 * @param {number} idx : 色板位置 * @param {array} [userPalete] : 自定义色板 * * @return {color} 颜色#000000~#ffffff */ function getColor(idx, userPalete) { idx = +idx || 0; userPalete = userPalete || palette; return userPalete[idx % userPalete.length]; } /** * 自定义默认高亮颜色 */ function customHighlight(userHighlightColor) { highlightColor = userHighlightColor; } /** * 重置默认高亮颜色 */ function resetHighlight() { _highlightColor = highlightColor; } /** * 获取默认高亮颜色 */ function getHighlightColor() { return highlightColor; } /** * 径向渐变 * @param {number} x0 渐变起点 * @param {number} y0 * @param {number} r0 * @param {number} x1 渐变终点 * @param {number} y1 * @param {number} r1 * @param {Array} colorList 颜色列表 */ function getRadialGradient(x0, y0, r0, x1, y1, r1, colorList) { if (!_ctx) { _ctx = util.getContext(); } var gradient = _ctx.createRadialGradient(x0, y0, r0, x1, y1, r1); for ( var i = 0, l = colorList.length; i < l; i++) { gradient.addColorStop(colorList[i][0], colorList[i][1]); } gradient.__nonRecursion = true; return gradient; } /** * 线性渐变 * @param {Object} x0 渐变起点 * @param {Object} y0 * @param {Object} x1 渐变终点 * @param {Object} y1 * @param {Array} colorList 颜色列表 */ function getLinearGradient(x0, y0, x1, y1, colorList) { if (!_ctx) { _ctx = util.getContext(); } var gradient = _ctx.createLinearGradient(x0, y0, x1, y1); for ( var i = 0, l = colorList.length; i < l; i++) { gradient.addColorStop(colorList[i][0], colorList[i][1]); } gradient.__nonRecursion = true; return gradient; } /** * 获取两种颜色之间渐变颜色数组 * @param {color} start 起始颜色 * @param {color} end 结束颜色 * @param {number} step 渐变级数 * @return {Array} 颜色数组 */ function getStepColors(start, end, step) { start = toRGBA(start); end = toRGBA(end); start = getData(start); end = getData(end); var colors = []; var stepR = (end[0] - start[0]) / step; var stepG = (end[1] - start[1]) / step; var stepB = (end[2] - start[2]) / step; // 生成颜色集合 // fix by linfeng 颜色堆积 for (var i = 0, r = start[0], g = start[1], b = start[2]; i < step; i++ ) { colors[i] = toColor([ adjust(Math.floor(r), [ 0, 255 ]), adjust(Math.floor(g), [ 0, 255 ]), adjust(Math.floor(b), [ 0, 255 ]) ]); r += stepR; g += stepG; b += stepB; } r = end[0]; g = end[1]; b = end[2]; colors[i] = toColor( [ r, g, b ]); return colors; } /** * 获取指定级数的渐变颜色数组 * @param {Array} colors 颜色组 * @param {number=20} step 渐变级数 * @return {Array} 颜色数组 */ function getGradientColors(colors, step) { var ret = []; var len = colors.length; if (step === undefined) { step = 20; } if (len === 1) { ret = getStepColors(colors[0], colors[0], step); } else if (len > 1) { for ( var i = 0, n = len - 1; i < n; i++) { var steps = getStepColors(colors[i], colors[i + 1], step); if (i < n - 1) { steps.pop(); } ret = ret.concat(steps); } } return ret; } /** * 颜色值数组转为指定格式颜色,例如:<br/> * data = [60,20,20,0.1] format = 'rgba' * 返回:rgba(60,20,20,0.1) * @param {Array} data 颜色值数组 * @param {string} format 格式,默认rgb * @return {string} 颜色 */ function toColor(data, format) { format = format || 'rgb'; if (data && (data.length === 3 || data.length === 4)) { data = map(data, function(c) { return c > 1 ? Math.ceil(c) : c; }); if (format.indexOf('hex') > -1) { data = map(data.slice(0, 3), function(c) { c = Number(c).toString(16); return (c.length === 1) ? '0' + c : c; }); return '#' + data.join(''); } else if (format.indexOf('hs') > -1) { var sx = map(data.slice(1, 3), function(c) { return c + '%'; }); data[1] = sx[0]; data[2] = sx[1]; } if (format.indexOf('a') > -1) { if (data.length === 3) { data.push(1); } data[3] = adjust(data[3], [ 0, 1 ]); return format + '(' + data.slice(0, 4).join(',') + ')'; } return format + '(' + data.slice(0, 3).join(',') + ')'; } } /** * 返回颜色值数组 * @param {string} color 颜色 * @return {Array} 颜色值数组 */ function toArray(color) { color = trim(color); if (color.indexOf('#') > -1) { color = toRGB(color); } var data = color.replace(/[rgbahsvl%\(\)]/ig, '').split(','); data = map(data, function(c) { return Number(c); }); return data; } /** * 颜色格式转化 * @param {Array} data 颜色值数组 * @param {string} format 格式,默认rgb * @return {string} 颜色 */ function convert(color, format) { var data = getData(color); var alpha = data[3]; if(typeof alpha === 'undefined') { alpha = 1; } if (color.indexOf('hsb') > -1) { data = _HSV_2_RGB(data); } else if (color.indexOf('hsl') > -1) { data = _HSL_2_RGB(data); } if (format.indexOf('hsb') > -1 || format.indexOf('hsv') > -1) { data = _RGB_2_HSB(data); } else if (format.indexOf('hsl') > -1) { data = _RGB_2_HSL(data); } data[3] = alpha; return toColor(data, format); } /** * 转换为rgba格式的颜色 * @param {string} color 颜色 * @return {string} rgba颜色,rgba(r,g,b,a) */ function toRGBA(color) { return convert(color, 'rgba'); } /** * 转换为rgb数字格式的颜色 * @param {string} color 颜色 * @return {string} rgb颜色,rgb(0,0,0)格式 */ function toRGB(color) { return convert(color, 'rgb'); } /** * 转换为16进制颜色 * @param {string} color 颜色 * @return {string} 16进制颜色,#rrggbb格式 */ function toHex(color) { return convert(color, 'hex'); } /** * 转换为HSV颜色 * @param {string} color 颜色 * @return {string} HSVA颜色,hsva(h,s,v,a) */ function toHSVA(color) { return convert(color, 'hsva'); } /** * 转换为HSV颜色 * @param {string} color 颜色 * @return {string} HSV颜色,hsv(h,s,v) */ function toHSV(color) { return convert(color, 'hsv'); } /** * 转换为HSBA颜色 * @param {string} color 颜色 * @return {string} HSBA颜色,hsba(h,s,b,a) */ function toHSBA(color) { return convert(color, 'hsba'); } /** * 转换为HSB颜色 * @param {string} color 颜色 * @return {string} HSB颜色,hsb(h,s,b) */ function toHSB(color) { return convert(color, 'hsb'); } /** * 转换为HSLA颜色 * @param {string} color 颜色 * @return {string} HSLA颜色,hsla(h,s,l,a) */ function toHSLA(color) { return convert(color, 'hsla'); } /** * 转换为HSL颜色 * @param {string} color 颜色 * @return {string} HSL颜色,hsl(h,s,l) */ function toHSL(color) { return convert(color, 'hsl'); } /** * 转换颜色名 * @param {string} color 颜色 * @return {String} 颜色名 */ function toName(color) { for ( var key in _nameColors) { if (toHex(_nameColors[key]) === toHex(color)) { return key; } } return null; } /** * 移除颜色中多余空格 * @param {String} color 颜色 * @return {String} 无空格颜色 */ function trim(color) { color = String(color); color = color.replace(/(^\s*)|(\s*$)/g, ''); if (/^[^#]*?$/i.test(color)) { color = color.replace(/\s/g, ''); } return color; } // 规范化 function normalize(color) { // 颜色名 if (_nameColors[color]) { color = _nameColors[color]; } // 去掉空格 color = trim(color); // hsv与hsb等价 color = color.replace(/hsv/i, 'hsb'); // rgb转为rrggbb if (/^#[0-9a-f]{3}$/i.test(color)) { var d = color.replace('#', '').split(''); color = '#' + d[0] + d[0] + d[1] + d[1] + d[2] + d[2]; } return color; } /** * 颜色加深或减淡,当level>0加深,当level<0减淡 * @param {string} color 颜色 * @param {number} level 升降程度,取值区间[-1,1] * @return {string} 加深或减淡后颜色值 */ function lift(color, level) { var direct = level > 0 ? 1 : -1; if (typeof level === 'undefined') { level = 0; } level = Math.abs(level) > 1 ? 1 : Math.abs(level); color = toRGB(color); var data = getData(color); for ( var i = 0; i < 3; i++) { if (direct === 1) { data[i] = Math.floor(data[i] * (1 - level)); } else { data[i] = Math.floor((255 - data[i]) * level + data[i]); } } return 'rgb(' + data.join(',') + ')'; } /** * 颜色翻转,[255-r,255-g,255-b,1-a] * @param {string} color 颜色 * @return {string} 翻转颜色 */ function reverse(color) { var data = getData(toRGBA(color)); data = map(data, function(c) { return 255 - c; }); return toColor(data, 'rgb'); } /** * 简单两种颜色混合 * @param {String} color1 第一种颜色 * @param {String} color2 第二种颜色 * @param {String} weight 混合权重[0-1] * @return {String} 结果色,rgb(r,g,b)或rgba(r,g,b,a) */ function mix(color1, color2, weight) { if(typeof weight === 'undefined') { weight = 0.5; } weight = 1 - adjust(weight, [0, 1]); var w = weight * 2 - 1; var data1 = getData(toRGBA(color1)); var data2 = getData(toRGBA(color2)); var d = data1[3] - data2[3]; var weight1 = (((w * d === -1) ? w : (w + d) / (1 + w * d)) + 1) / 2; var weight2 = 1 - weight1; var data = []; for ( var i = 0; i < 3; i++) { data[i] = data1[i] * weight1 + data2[i] * weight2; } var alpha = data1[3] * weight + data2[3] * (1 - weight); alpha = Math.max(0, Math.min(1, alpha)); if (data1[3] === 1 && data2[3] === 1) {// 不考虑透明度 return toColor(data, 'rgb'); } data[3] = alpha; return toColor(data, 'rgba'); } /** * 随机颜色 * @return {string} 颜色值,#rrggbb格式 */ function random() { return toHex( 'rgb(' + Math.round(Math.random() * 256) + ',' + Math.round(Math.random() * 256) + ',' + Math.round(Math.random() * 256) + ')' ); } /** * 获取颜色值数组,返回值范围: <br/> * RGB 范围[0-255] <br/> * HSL/HSV/HSB 范围[0-1]<br/> * A透明度范围[0-1] * 支持格式: * #rgb * #rrggbb * rgb(r,g,b) * rgb(r%,g%,b%) * rgba(r,g,b,a) * hsb(h,s,b) // hsv与hsb等价 * hsb(h%,s%,b%) * hsba(h,s,b,a) * hsl(h,s,l) * hsl(h%,s%,l%) * hsla(h,s,l,a) * @param {string} color 颜色 * @return {Array} 颜色值数组或null */ function getData(color) { color = normalize(color); var r = color.match(colorRegExp); if (r === null) { throw new Error('The color format error'); // 颜色格式错误 } var d; var a; var data = []; var rgb; if (r[2]) { // #rrggbb d = r[2].replace('#', '').split(''); rgb = [ d[0] + d[1], d[2] + d[3], d[4] + d[5] ]; data = map(rgb, function(c) { return adjust(parseInt(c, 16), [ 0, 255 ]); }); } else if (r[4]) { // rgb rgba var rgba = (r[4]).split(','); a = rgba[3]; rgb = rgba.slice(0, 3); data = map( rgb, function(c) { c = Math.floor( c.indexOf('%') > 0 ? parseInt(c, 0) * 2.55 : c ); return adjust(c, [ 0, 255 ]); } ); if( typeof a !== 'undefined') { data.push(adjust(parseFloat(a), [ 0, 1 ])); } } else if (r[5] || r[6]) { // hsb hsba hsl hsla var hsxa = (r[5] || r[6]).split(','); var h = parseInt(hsxa[0], 0) / 360; var s = hsxa[1]; var x = hsxa[2]; a = hsxa[3]; data = map( [ s, x ], function(c) { return adjust(parseFloat(c) / 100, [ 0, 1 ]); }); data.unshift(h); if( typeof a !== 'undefined') { data.push(adjust(parseFloat(a), [ 0, 1 ])); } } return data; } /** * 设置颜色透明度 * @param {string} color 颜色 * @param {number} alpha 透明度,区间[0,1] * @return {string} rgba颜色值 */ function alpha(color, a) { if (a === null) { a = 1; } var data = getData(toRGBA(color)); data[3] = adjust(Number(a).toFixed(4), [ 0, 1 ]); return toColor(data, 'rgba'); } // 数组映射 function map(array, fun) { if (typeof fun !== 'function') { throw new TypeError(); } var len = array ? array.length : 0; for ( var i = 0; i < len; i++) { array[i] = fun(array[i]); } return array; } // 调整值区间 function adjust(value, region) { // < to <= & > to >= // modify by linzhifeng 2014-05-25 because -0 == 0 if (value <= region[0]) { value = region[0]; } else if (value >= region[1]) { value = region[1]; } return value; } // 参见 http:// www.easyrgb.com/index.php?X=MATH function _HSV_2_RGB(data) { var H = data[0]; var S = data[1]; var V = data[2]; // HSV from 0 to 1 var R, G, B; if (S === 0) { R = V * 255; G = V * 255; B = V * 255; } else { var h = H * 6; if (h === 6) { h = 0; } var i = Math.floor(h); var v1 = V * (1 - S); var v2 = V * (1 - S * (h - i)); var v3 = V * (1 - S * (1 - (h - i))); var r = 0; var g = 0; var b = 0; if (i === 0) { r = V; g = v3; b = v1; } else if (i === 1) { r = v2; g = V; b = v1; } else if (i === 2) { r = v1; g = V; b = v3; } else if (i === 3) { r = v1; g = v2; b = V; } else if (i === 4) { r = v3; g = v1; b = V; } else { r = V; g = v1; b = v2; } // RGB results from 0 to 255 R = r * 255; G = g * 255; B = b * 255; } return [ R, G, B ]; } function _HSL_2_RGB(data) { var H = data[0]; var S = data[1]; var L = data[2]; // HSL from 0 to 1 var R, G, B; if (S === 0) { R = L * 255; G = L * 255; B = L * 255; } else { var v2; if (L < 0.5) { v2 = L * (1 + S); } else { v2 = (L + S) - (S * L); } var v1 = 2 * L - v2; R = 255 * _HUE_2_RGB(v1, v2, H + (1 / 3)); G = 255 * _HUE_2_RGB(v1, v2, H); B = 255 * _HUE_2_RGB(v1, v2, H - (1 / 3)); } return [ R, G, B ]; } function _HUE_2_RGB(v1, v2, vH) { if (vH < 0) { vH += 1; } if (vH > 1) { vH -= 1; } if ((6 * vH) < 1) { return (v1 + (v2 - v1) * 6 * vH); } if ((2 * vH) < 1) { return (v2); } if ((3 * vH) < 2) { return (v1 + (v2 - v1) * ((2 / 3) - vH) * 6); } return v1; } function _RGB_2_HSB(data) { // RGB from 0 to 255 var R = (data[0] / 255); var G = (data[1] / 255); var B = (data[2] / 255); var vMin = Math.min(R, G, B); // Min. value of RGB var vMax = Math.max(R, G, B); // Max. value of RGB var delta = vMax - vMin; // Delta RGB value var V = vMax; var H; var S; // HSV results from 0 to 1 if (delta === 0) { H = 0; S = 0; } else { S = delta / vMax; var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta; var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta; var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta; if (R === vMax) { H = deltaB - deltaG; } else if (G === vMax) { H = (1 / 3) + deltaR - deltaB; } else if (B === vMax) { H = (2 / 3) + deltaG - deltaR; } if (H < 0) { H += 1; } if (H > 1) { H -= 1; } } H = H * 360; S = S * 100; V = V * 100; return [ H, S, V ]; } function _RGB_2_HSL(data) { // RGB from 0 to 255 var R = (data[0] / 255); var G = (data[1] / 255); var B = (data[2] / 255); var vMin = Math.min(R, G, B); // Min. value of RGB var vMax = Math.max(R, G, B); // Max. value of RGB var delta = vMax - vMin; // Delta RGB value var L = (vMax + vMin) / 2; var H; var S; // HSL results from 0 to 1 if (delta === 0) { H = 0; S = 0; } else { if (L < 0.5) { S = delta / (vMax + vMin); } else { S = delta / (2 - vMax - vMin); } var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta; var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta; var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta; if (R === vMax) { H = deltaB - deltaG; } else if (G === vMax) { H = (1 / 3) + deltaR - deltaB; } else if (B === vMax) { H = (2 / 3) + deltaG - deltaR; } if (H < 0) { H += 1; } if (H > 1) { H -= 1; } } H = H * 360; S = S * 100; L = L * 100; return [ H, S, L ]; } return { customPalette : customPalette, resetPalette : resetPalette, getColor : getColor, getHighlightColor : getHighlightColor, customHighlight : customHighlight, resetHighlight : resetHighlight, getRadialGradient : getRadialGradient, getLinearGradient : getLinearGradient, getGradientColors : getGradientColors, getStepColors : getStepColors, reverse : reverse, mix : mix, lift : lift, trim : trim, random : random, toRGB : toRGB, toRGBA : toRGBA, toHex : toHex, toHSL : toHSL, toHSLA : toHSLA, toHSB : toHSB, toHSBA : toHSBA, toHSV : toHSV, toHSVA : toHSVA, toName : toName, toColor : toColor, toArray : toArray, alpha : alpha, getData : getData }; }); /** * zrender : shape基类 * * desc: zrender是一个轻量级的Canvas类库,MVC封装,数据驱动,提供类Dom事件模型。 * author: Kener (@Kener-林峰, linzhifeng@baidu.com) * * 可配图形属性: { // 基础属性,详见各shape shape : {string}, // 必须,shape类标识,需要显式指定 id : {string}, // 必须,图形唯一标识,可通过zrender实例方法newShapeId生成 zlevel : {number}, // 默认为0,z层level,决定绘画在哪层canvas中 invisible : {boolean}, // 默认为false,是否可见 // 变换 position : {array}, // 默认为[0, 0], shape的坐标 rotation : {number|array}, // 默认为[0, 0, 0],shape绕自身旋转的角度,不被translate 影响 // 后两个值为旋转的origin scale : {array}, // 默认为[1, 1, 0, 0], shape纵横缩放比例,不被translate影响 // 后两个值为缩放的origin // 样式属性,详见各shape,默认状态样式属性 style : {Object}, // 样式属性,详见各shape,高亮样式属性,当不存在highlightStyle时使用默认样式扩展显示 highlightStyle : {Object}, // 交互属性,zrender支持,非图形类实现 hoverable : {boolean}, // 默认为true,可悬浮响应,默认悬浮响应为高亮显示 // 可在onbrush中捕获并阻塞高亮绘画 clickable : {boolean}, // 默认为false,可点击响应,影响鼠标hover时图标是否为可点击样式 // 为false则阻断点击事件抛出,为true可在onclick中捕获 draggable : {boolean}, // 默认为false,可拖拽响应,默认拖拽响应改变图形位置, // 可在ondrift中捕获并阻塞默认拖拽行为 // 事件属性 onbrush : {Function}, // 默认为null,当前图形被刷画时回调,可用于实现自定义绘画 // 回传参数为: // @param {2D Context} context 当前canvas context // @param {Object} shape 当前shape // @param {boolean} isHighlight 是否高亮 // @return {boolean} 回调返回true则不执行默认绘画 ondrift : {Function}, // 默认为null,当前图形被拖拽改变位置时回调,可用于限制拖拽范围 // 回传参数为: // @param {Object} shape 当前shape // @param {number} dx x方向变化 // @param {number} dy y方向变化 onclick : {Function}, // 默认为null,当前图形点击响应,回传参数为: // @param {Object} eventPacket 对象内容如下: // @param {string} eventPacket.type 事件类型,EVENT.CLICK // @param {event} eventPacket.event 原始dom事件对象 // @param {Object} eventPacket.target 当前图形shape对象 // @return {boolean} 回调返回true则阻止抛出全局事件 onmousewheel : {Function}, // 默认为null,当前图形上鼠标滚轮触发,回传参数格式同onclick,其中: // 事件类型为confit.EVENT.MOUSEWHEEL // @return {boolean} 回调返回true则阻止抛出全局事件 onmousemove : {Function}, // 默认为null,当前图上形鼠标(或手指)移动触发,回传参数格式同onclick,其中: // 事件类型为confit.EVENT.MOUSEMOVE // @return {boolean} 回调返回true则阻止抛出全局事件 onmouseover : {Function}, // 默认为null,鼠标(或手指)移动到当前图形上触发,回传参数格式同onclick: // 事件类型为confit.EVENT.MOUSEOVER // @return {boolean} 回调返回true则阻止抛出全局事件 onmouseout : {Function}, // 默认为null,鼠标(或手指)从当前图形移开,回传参数格式同onclick,其中: // 事件类型为confit.EVENT.MOUSEOUT // @return {boolean} 回调返回true则阻止抛出全局事件 onmousedown : {Function}, // 默认为null,鼠标按钮(或手指)按下,回传参数格式同onclick,其中: // 事件类型为confit.EVENT.MOUSEDOWN // @return {boolean} 回调返回true则阻止抛出全局事件 onmouseup : {Function}, // 默认为null,鼠标按钮(或手指)松开,回传参数格式同onclick,其中: // 事件类型为confit.EVENT.MOUSEUP // @return {boolean} 回调返回true则阻止抛出全局事件 ondragstart : {Function}, // 默认为null,开始拖拽时触发,回传参数格式同onclick,其中: // 事件类型为confit.EVENT.DRAGSTART // @return {boolean} 回调返回true则阻止抛出全局事件 ondragend : {Function}, // 默认为null,拖拽完毕时触发,回传参数格式同onclick,其中: // 事件类型为confit.EVENT.DRAGEND // @return {boolean} 回调返回true则阻止抛出全局事件 ondragenter : {Function}, // 默认为null,拖拽图形元素进入目标图形元素时触发 // 回传参数格式同onclick,其中: // @param {string} eventPacket.type 事件类型,EVENT.DRAGENTER // @param {Object} eventPacket.target 目标图形元素shape对象 // @param {Object} eventPacket.dragged 拖拽图形元素shape对象 // @return {boolean} 回调返回true则阻止抛出全局事件 ondragover : {Function}, // 默认为null,拖拽图形元素在目标图形元素上移动时触发, // 回传参数格式同onclick,其中: // @param {string} eventPacket.type 事件类型,EVENT.DRAGOVER // @param {Object} eventPacket.target 目标图形元素shape对象 // @param {Object} eventPacket.dragged 拖拽图形元素shape对象 // @return {boolean} 回调返回true则阻止抛出全局事件 ondragleave : {Function}, // 默认为null,拖拽图形元素离开目标图形元素时触发, // 回传参数格式同onclick,其中: // @param {string} eventPacket.type 事件类型,EVENT.DRAGLEAVE // @param {Object} eventPacket.target 目标图形元素shape对象 // @param {Object} eventPacket.dragged 拖拽图形元素shape对象 // @return {boolean} 回调返回true则阻止抛出全局事件 ondrop : {Function}, // 默认为null,拖拽图形元素放在目标图形元素内时触发, // 回传参数格式同onclick,其中: // @param {string} eventPacket.type 事件类型,EVENT.DRAG // @param {Object} eventPacket.target 目标图形元素shape对象 // @param {Object} eventPacket.dragged 拖拽图形元素shape对象 // @return {boolean} 回调返回true则阻止抛出全局事件 } */ define( 'zrender/shape/base',['require','../tool/area','../tool/matrix','../tool/color'],function(require) { var self; var area = require('../tool/area'); var matrix = require('../tool/matrix'); /** * 派生实现通用功能 * @param {Object} clazz 图形类 */ function derive(clazz) { var methods = [ // 派生实现的基类方法 'brush', 'setContext', 'dashedLineTo', 'drawText', 'getHighlightStyle', 'getHighlightZoom', 'drift', 'isCover', 'updateTransform' ]; var len = methods.length; var proto = clazz.prototype; var i = 0; var method; for (; i < len; i++) { method = methods[i]; if (!proto[method]) { proto[method] = self[method]; } } } /** * 画刷 * @param ctx 画布句柄 * @param e 形状实体 * @param isHighlight 是否为高亮状态 * @param updateCallback 需要异步加载资源的shape可以通过这个callback(e) * 让painter更新视图,base.brush没用,需要的话重载brush */ function brush(ctx, e, isHighlight) { var style = e.style || {}; if (this.brushTypeOnly) { style.brushType = this.brushTypeOnly; } if (isHighlight) { // 根据style扩展默认高亮样式 style = this.getHighlightStyle( style, e.highlightStyle || {}, this.brushTypeOnly ); } if (this.brushTypeOnly == 'stroke') { style.strokeColor = style.strokeColor || style.color; } ctx.save(); this.setContext(ctx, style); // 设置transform if (e.__needTransform) { ctx.transform.apply(ctx,this.updateTransform(e)); } ctx.beginPath(); this.buildPath(ctx, style); if (this.brushTypeOnly != 'stroke') { ctx.closePath(); } switch (style.brushType) { case 'fill': ctx.fill(); break; case 'stroke': ctx.stroke(); break; case 'both': ctx.stroke(); ctx.fill(); break; default: ctx.fill(); } if (style.text) { this.drawText(ctx, style, e.style); } ctx.restore(); return; } /** * 画布通用设置 * @param ctx 画布句柄 * @param style 通用样式 */ function setContext(ctx, style) { // 简单判断不做严格类型检测 if (style.color) { ctx.fillStyle = style.color; } if (style.strokeColor) { ctx.strokeStyle = style.strokeColor; } if (typeof style.opacity != 'undefined') { ctx.globalAlpha = style.opacity; } if (style.lineCap) { ctx.lineCap = style.lineCap; } if (style.lineJoin) { ctx.lineJoin = style.lineJoin; } if (style.miterLimit) { ctx.miterLimit = style.miterLimit; } if (typeof style.lineWidth != 'undefined') { ctx.lineWidth = style.lineWidth; } if (typeof style.shadowBlur != 'undefined') { ctx.shadowBlur = style.shadowBlur; } if (style.shadowColor) { ctx.shadowColor = style.shadowColor; } if (typeof style.shadowOffsetX != 'undefined') { ctx.shadowOffsetX = style.shadowOffsetX; } if (typeof style.shadowOffsetY != 'undefined') { ctx.shadowOffsetY = style.shadowOffsetY; } } /** * 虚线lineTo */ function dashedLineTo(ctx, x1, y1, x2, y2, dashLength) { dashLength = typeof dashLength == 'undefined' ? 5 : dashLength; var deltaX = x2 - x1; var deltaY = y2 - y1; var numDashes = Math.floor( Math.sqrt(deltaX * deltaX + deltaY * deltaY) / dashLength ); for (var i = 0; i < numDashes; ++i) { ctx[i % 2 === 0 ? 'moveTo' : 'lineTo']( x1 + (deltaX / numDashes) * i, y1 + (deltaY / numDashes) * i ); } } /** * 附加文本 * @param {Context2D} ctx Canvas 2D上下文 * @param {Object} style 样式 * @param {Object} normalStyle 默认样式,用于定位文字显示 */ function drawText(ctx, style, normalStyle) { // 字体颜色策略 style.textColor= style.textColor || style.color || style.strokeColor; ctx.fillStyle = style.textColor; if (style.textPosition == 'inside') { ctx.shadowColor = 'rgba(0,0,0,0)'; // 内部文字不带shadowColor } // 文本与图形间空白间隙 var dd = 10; var al; // 文本水平对齐 var bl; // 文本垂直对齐 var tx; // 文本横坐标 var ty; // 文本纵坐标 var textPosition = style.textPosition // 用户定义 || this.textPosition // shape默认 || 'top'; // 全局默认 if ((textPosition == 'inside' || textPosition == 'top' || textPosition == 'bottom' || textPosition == 'left' || textPosition == 'right') && this.getRect // 矩形定位文字的图形必须提供getRect方法 ) { var rect = (normalStyle || style).__rect || this.getRect(normalStyle || style); switch (textPosition) { case 'inside': tx = rect.x + rect.width / 2; ty = rect.y + rect.height / 2; al = 'center'; bl = 'middle'; if (style.brushType != 'stroke' && style.textColor == style.color ) { ctx.fillStyle = '#fff'; } break; case 'left': tx = rect.x - dd; ty = rect.y + rect.height / 2; al = 'end'; bl = 'middle'; break; case 'right': tx = rect.x + rect.width + dd; ty = rect.y + rect.height / 2; al = 'start'; bl = 'middle'; break; case 'top': tx = rect.x + rect.width / 2; ty = rect.y - dd; al = 'center'; bl = 'bottom'; break; case 'bottom': tx = rect.x + rect.width / 2; ty = rect.y + rect.height + dd; al = 'center'; bl = 'top'; break; } } else if (textPosition == 'start' || textPosition == 'end') { var xStart; var xEnd; var yStart; var yEnd; if (typeof style.pointList != 'undefined') { var pointList = style.pointList; if (pointList.length < 2) { // 少于2个点就不画了~ return; } var length = pointList.length; switch (textPosition) { case 'start': xStart = pointList[0][0]; xEnd = pointList[1][0]; yStart = pointList[0][1]; yEnd = pointList[1][1]; break; case 'end': xStart = pointList[length - 2][0]; xEnd = pointList[length - 1][0]; yStart = pointList[length - 2][1]; yEnd = pointList[length - 1][1]; break; } } else { xStart = style.xStart || 0; xEnd = style.xEnd || 0; yStart = style.yStart || 0; yEnd = style.yEnd || 0; } switch (textPosition) { case 'start': al = xStart < xEnd ? 'end' : 'start'; bl = yStart < yEnd ? 'bottom' : 'top'; tx = xStart; ty = yStart; break; case 'end': al = xStart < xEnd ? 'start' : 'end'; bl = yStart < yEnd ? 'top' : 'bottom'; tx = xEnd; ty = yEnd; break; } dd -= 4; if (xStart != xEnd) { tx -= (al == 'end' ? dd : -dd); } else { al = 'center'; } if (yStart != yEnd) { ty -= (bl == 'bottom' ? dd : -dd); } else { bl = 'middle'; } } else if (textPosition == 'specific') { tx = style.textX || 0; ty = style.textY || 0; al = 'start'; bl = 'middle'; } if (typeof tx != 'undefined' && typeof ty != 'undefined') { if (style.textFont) { ctx.font = style.textFont; } ctx.textAlign = style.textAlign || al; ctx.textBaseline = style.textBaseLine || bl; ctx.fillText(style.text, tx, ty); } } /** * 根据默认样式扩展高亮样式 * @param ctx Canvas 2D上下文 * @param {Object} style 默认样式 * @param {Object} highlightStyle 高亮样式 */ function getHighlightStyle(style, highlightStyle, brushTypeOnly) { var newStyle = {}; for (var k in style) { newStyle[k] = style[k]; } var color = require('../tool/color'); var highlightColor = color.getHighlightColor(); // 根据highlightStyle扩展 if (style.brushType != 'stroke') { // 带填充则用高亮色加粗边线 newStyle.strokeColor = highlightColor; newStyle.lineWidth = (style.lineWidth || 1) + this.getHighlightZoom(); newStyle.brushType = 'both'; } else { if (brushTypeOnly != 'stroke') { // 描边型的则用原色加工高亮 newStyle.strokeColor = highlightColor; newStyle.lineWidth = (style.lineWidth || 1) + this.getHighlightZoom(); } else { // 线型的则用原色加工高亮 newStyle.strokeColor = highlightStyle.strokeColor || color.mix( style.strokeColor, color.toRGB(highlightColor) ); } } // 可自定义覆盖默认值 for (var k in highlightStyle) { newStyle[k] = highlightStyle[k]; } return newStyle; } /** * 高亮放大效果参数 * 当前统一设置为6,如有需要差异设置,通过this.type判断实例类型 */ function getHighlightZoom() { return this.type != 'text' ? 6 : 2; } /** * 默认漂移 * @param e 图形实体 * @param dx 横坐标变化 * @param dy 纵坐标变化 */ function drift(e, dx, dy) { e.position[0] += dx; e.position[1] += dy; } /** * 默认区域包含判断 * @param e 图形实体 * @param x 横坐标 * @param y 纵坐标 */ function isCover(e, x, y) { //对鼠标的坐标也做相同的变换 if(e.__needTransform && e._transform){ var inverseMatrix = []; matrix.invert(inverseMatrix, e._transform); var originPos = [x, y]; matrix.mulVector(originPos, inverseMatrix, [x, y, 1]); if (x == originPos[0] && y == originPos[1]) { // 避免外部修改导致的__needTransform不准确 if (Math.abs(e.rotation[0]) > 0.0001 || Math.abs(e.position[0]) > 0.0001 || Math.abs(e.position[1]) > 0.0001 || Math.abs(e.scale[0] - 1) > 0.0001 || Math.abs(e.scale[1] - 1) > 0.0001 ) { e.__needTransform = true; } else { e.__needTransform = false; } } x = originPos[0]; y = originPos[1]; } // 快速预判并保留判断矩形 var rect; if (e.style.__rect) { rect = e.style.__rect; } else { rect = this.getRect(e.style); e.style.__rect = rect; } if (x >= rect.x && x <= (rect.x + rect.width) && y >= rect.y && y <= (rect.y + rect.height) ) { // 矩形内 return area.isInside(this, e.style, x, y); } else { return false; } } function updateTransform(e) { var _transform = e._transform || matrix.create(); matrix.identity(_transform); if (e.scale && (e.scale[0] !== 1 || e.scale[1] !== 1)) { var originX = e.scale[2] || 0; var originY = e.scale[3] || 0; if (originX || originY ) { matrix.translate( _transform, _transform, [-originX, -originY] ); } matrix.scale(_transform, _transform, e.scale); if ( originX || originY ) { matrix.translate( _transform, _transform, [originX, originY] ); } } if (e.rotation) { if (e.rotation instanceof Array) { if (e.rotation[0] !== 0) { var originX = e.rotation[1] || 0, originY = e.rotation[2] || 0; if (originX || originY ) { matrix.translate( _transform, _transform, [-originX, -originY] ); } matrix.rotate(_transform, _transform, e.rotation[0]); if (originX || originY ) { matrix.translate( _transform, _transform, [originX, originY] ); } } }else{ if (e.rotation !== 0) { matrix.rotate(_transform, _transform, e.rotation); } } } if (e.position && (e.position[0] !==0 || e.position[1] !== 0)) { matrix.translate(_transform, _transform, e.position); } // 保存这个变换矩阵 e._transform = _transform; return _transform; } self = { derive : derive, brush : brush, setContext : setContext, dashedLineTo : dashedLineTo, drawText : drawText, getHighlightStyle : getHighlightStyle, getHighlightZoom : getHighlightZoom, drift : drift, isCover : isCover, updateTransform : updateTransform }; return self; } ); /** * zrender * * @author Kener (@Kener-林峰, linzhifeng@baidu.com) * * shape类:圆 * 可配图形属性: { // 基础属性 shape : 'circle', // 必须,shape类标识,需要显式指定 id : {string}, // 必须,图形唯一标识,可通过zrender实例方法newShapeId生成 zlevel : {number}, // 默认为0,z层level,决定绘画在哪层canvas中 invisible : {boolean}, // 默认为false,是否可见 // 样式属性,默认状态样式样式属性 style : { x : {number}, // 必须,圆心横坐标 y : {number}, // 必须,圆心纵坐标 r : {number}, // 必须,圆半径 brushType : {string}, // 默认为fill,绘画方式 // fill(填充) | stroke(描边) | both(填充+描边) color : {color}, // 默认为'#000',填充颜色,支持rgba strokeColor : {color}, // 默认为'#000',描边颜色(轮廓),支持rgba lineWidth : {number}, // 默认为1,线条宽度,描边下有效 opacity : {number}, // 默认为1,透明度设置,如果color为rgba,则最终透明度效果叠加 shadowBlur : {number}, // 默认为0,阴影模糊度,大于0有效 shadowColor : {color}, // 默认为'#000',阴影色彩,支持rgba shadowOffsetX : {number}, // 默认为0,阴影横向偏移,正值往右,负值往左 shadowOffsetY : {number}, // 默认为0,阴影纵向偏移,正值往下,负值往上 text : {string}, // 默认为null,附加文本 textFont : {string}, // 默认为null,附加文本样式,eg:'bold 18px verdana' textPosition : {string}, // 默认为top,附加文本位置。 // inside | left | right | top | bottom textAlign : {string}, // 默认根据textPosition自动设置,附加文本水平对齐。 // start | end | left | right | center textBaseline : {string}, // 默认根据textPosition自动设置,附加文本垂直对齐。 // top | bottom | middle | // alphabetic | hanging | ideographic textColor : {color}, // 默认根据textPosition自动设置,默认策略如下,附加文本颜色 // 'inside' ? '#fff' : color }, // 样式属性,高亮样式属性,当不存在highlightStyle时使用基于默认样式扩展显示 highlightStyle : { // 同style } // 交互属性,详见shape.Base // 事件属性,详见shape.Base } 例子: { shape : 'circle', id : '123456', zlevel : 1, style : { x : 200, y : 100, r : 50, color : '#eee', text : 'Baidu' }, myName : 'kener', // 可自带任何有效自定义属性 clickable : true, onClick : function(eventPacket) { alert(eventPacket.target.myName); } } */ define( 'zrender/shape/circle',['require','./base','../shape'],function(require) { function Circle() { this.type = 'circle'; } Circle.prototype = { /** * 创建圆形路径 * @param {Context2D} ctx Canvas 2D上下文 * @param {Object} style 样式 */ buildPath : function(ctx, style) { ctx.arc(style.x, style.y, style.r, 0, Math.PI * 2, true); return; }, /** * 返回矩形区域,用于局部刷新和文字定位 * @param {Object} style */ getRect : function(style) { var lineWidth; if (style.brushType == 'stroke' || style.brushType == 'fill') { lineWidth = style.lineWidth || 1; } else { lineWidth = 0; } return { x : Math.round(style.x - style.r - lineWidth / 2), y : Math.round(style.y - style.r - lineWidth / 2), width : style.r * 2 + lineWidth, height : style.r * 2 + lineWidth }; } }; var base = require('./base'); base.derive(Circle); var shape = require('../shape'); shape.define('circle', new Circle()); return Circle; } ); /** * zrender * * author: loutongbing@baidu.com * * shape类:椭圆 * Todo:excanvas bug ~ 连续scale保持?? IE8下不建议使用 * 可配图形属性: { // 基础属性 shape : 'ellipse', // 必须,shape类标识,需要显式指定 id : {string}, // 必须,图形唯一标识,可通过zrender实例方法newShapeId生成 zlevel : {number}, // 默认为0,z层level,决定绘画在哪层canvas中 invisible : {boolean}, // 默认为false,是否可见 // 样式属性,默认状态样式样式属性 style : { x : {number}, // 必须,椭圆心横坐标 y : {number}, // 必须,椭圆心纵坐标 a : {number}, // 必须,椭圆横轴半径 b : {number}, // 必须,椭圆纵轴半径 brushType : {string}, // 默认为fill,绘画方式 // fill(填充) | stroke(描边) | both(填充+描边) color : {color}, // 默认为'#000',填充颜色,支持rgba strokeColor : {color}, // 默认为'#000',描边颜色(轮廓),支持rgba lineWidth : {number}, // 默认为1,线条宽度,描边下有效 opacity : {number}, // 默认为1,透明度设置,如果color为rgba,则最终透明度效果叠加 shadowBlur : {number}, // 默认为0,阴影模糊度,大于0有效 shadowColor : {color}, // 默认为'#000',阴影色彩,支持rgba shadowOffsetX : {number}, // 默认为0,阴影横向偏移,正值往右,负值往左 shadowOffsetY : {number}, // 默认为0,阴影纵向偏移,正值往下,负值往上 text : {string}, // 默认为null,附加文本 textFont : {string}, // 默认为null,附加文本样式,eg:'bold 18px verdana' textPosition : {string}, // 默认为top,附加文本位置。 // inside | left | right | top | bottom textAlign : {string}, // 默认根据textPosition自动设置,附加文本水平对齐。 // start | end | left | right | center textBaseline : {string}, // 默认根据textPosition自动设置,附加文本垂直对齐。 // top | bottom | middle | // alphabetic | hanging | ideographic textColor : {color}, // 默认根据textPosition自动设置,默认策略如下,附加文本颜色 // 'inside' ? '#fff' : color }, // 样式属性,高亮样式属性,当不存在highlightStyle时使用基于默认样式扩展显示 highlightStyle : { // 同style } // 交互属性,详见shape.Base // 事件属性,详见shape.Base } 例子: { shape : 'ellipse', id : '123456', zlevel : 1, style : { x : 200, y : 100, a : 100, b : 50, color : '#eee', text : 'Baidu' }, myName : 'kener', // 可自带任何有效自定义属性 clickable : true, onClick : function(eventPacket) { alert(eventPacket.target.myName); } } */ define( 'zrender/shape/ellipse',['require','./base','../shape'],function(require) { function Ellipse() { this.type = 'ellipse'; } Ellipse.prototype = { /** * 创建圆形路径 * @param {Context2D} ctx Canvas 2D上下文 * @param {Object} style 样式 */ buildPath : function(ctx, style) { var r = (style.a > style.b) ? style.a : style.b; var ratioX = style.a / r; //横轴缩放比率 var ratioY = style.b / r; ctx.scale(ratioX, ratioY); ctx.arc( style.x / ratioX, style.y / ratioY, r, 0, Math.PI * 2, true ); ctx.scale(1/ratioX, 1/ratioY); // excanvas bug~~ return; }, /** * 返回矩形区域,用于局部刷新和文字定位 * @param {Object} style */ getRect : function(style) { var lineWidth; if (style.brushType == 'stroke' || style.brushType == 'fill') { lineWidth = style.lineWidth || 1; } else { lineWidth = 0; } return { x : Math.round(style.x - style.a - lineWidth / 2), y : Math.round(style.y - style.b - lineWidth / 2), width : style.a * 2 + lineWidth, height : style.b * 2 + lineWidth }; } }; var base = require('./base'); base.derive(Ellipse); var shape = require('../shape'); shape.define('ellipse', new Ellipse()); return Ellipse; } ); /** * zrender * * @author Kener (@Kener-林峰, linzhifeng@baidu.com) * * shape类:直线 * 可配图形属性: { // 基础属性 shape : 'line', // 必须,shape类标识,需要显式指定 id : {string}, // 必须,图形唯一标识,可通过zrender实例方法newShapeId生成 zlevel : {number}, // 默认为0,z层level,决定绘画在哪层canvas中 invisible : {boolean}, // 默认为false,是否可见 // 样式属性,默认状态样式样式属性 style : { xStart : {number}, // 必须,起点横坐标 yStart : {number}, // 必须,起点纵坐标 xEnd : {number}, // 必须,终点横坐标 yEnd : {number}, // 必须,终点纵坐标 strokeColor : {color}, // 默认为'#000',线条颜色(轮廓),支持rgba lineType : {string}, // 默认为solid,线条类型,solid | dashed | dotted lineWidth : {number}, // 默认为1,线条宽度 lineCap : {string}, // 默认为butt,线帽样式。butt | round | square opacity : {number}, // 默认为1,透明度设置,如果color为rgba,则最终透明度效果叠加 shadowBlur : {number}, // 默认为0,阴影模糊度,大于0有效 shadowColor : {color}, // 默认为'#000',阴影色彩,支持rgba shadowOffsetX : {number}, // 默认为0,阴影横向偏移,正值往右,负值往左 shadowOffsetY : {number}, // 默认为0,阴影纵向偏移,正值往下,负值往上 text : {string}, // 默认为null,附加文本 textFont : {string}, // 默认为null,附加文本样式,eg:'bold 18px verdana' textPosition : {string}, // 默认为end,附加文本位置。 // inside | start | end textAlign : {string}, // 默认根据textPosition自动设置,附加文本水平对齐。 // start | end | left | right | center textBaseline : {string}, // 默认根据textPosition自动设置,附加文本垂直对齐。 // top | bottom | middle | // alphabetic | hanging | ideographic textColor : {color}, // 默认根据textPosition自动设置,默认策略如下,附加文本颜色 // 'inside' ? '#000' : color }, // 样式属性,高亮样式属性,当不存在highlightStyle时使用基于默认样式扩展显示 highlightStyle : { // 同style } // 交互属性,详见shape.Base // 事件属性,详见shape.Base } 例子: { shape : 'line', id : '123456', zlevel : 1, style : { xStart : 100, yStart : 100, xEnd : 200, yEnd : 200, strokeColor : '#eee', lineWidth : 20, text : 'Baidu' }, myName : 'kener', //可自带任何有效自定义属性 clickable : true, onClick : function(eventPacket) { alert(eventPacket.target.myName); } } */ define( 'zrender/shape/line',['require','./base','../shape'],function(require) { function Line() { this.type = 'line'; this.brushTypeOnly = 'stroke'; //线条只能描边,填充后果自负 this.textPosition = 'end'; } Line.prototype = { /** * 创建线条路径 * @param {Context2D} ctx Canvas 2D上下文 * @param {Object} style 样式 */ buildPath : function(ctx, style) { if (!style.lineType || style.lineType == 'solid') { //默认为实线 ctx.moveTo(style.xStart, style.yStart); ctx.lineTo(style.xEnd, style.yEnd); } else if (style.lineType == 'dashed' || style.lineType == 'dotted' ) { var dashLength =(style.lineWidth || 1) * (style.lineType == 'dashed' ? 5 : 1); this.dashedLineTo( ctx, style.xStart, style.yStart, style.xEnd, style.yEnd, dashLength ); } }, /** * 返回矩形区域,用于局部刷新和文字定位 * @param {Object} style */ getRect : function(style) { var lineWidth = style.lineWidth || 1; return { x : Math.min(style.xStart, style.xEnd) - lineWidth, y : Math.min(style.yStart, style.yEnd) - lineWidth, width : Math.abs(style.xStart - style.xEnd) + lineWidth, height : Math.abs(style.yStart - style.yEnd) + lineWidth }; } }; var base = require('./base'); base.derive(Line); var shape = require('../shape'); shape.define('line', new Line()); return Line; } ); /** * zrender * * @author Kener (@Kener-林峰, linzhifeng@baidu.com) * * shape类:多边形 * 可配图形属性: { // 基础属性 shape : 'polygon', // 必须,shape类标识,需要显式指定 id : {string}, // 必须,图形唯一标识,可通过zrender实例方法newShapeId生成 zlevel : {number}, // 默认为0,z层level,决定绘画在哪层canvas中 invisible : {boolean}, // 默认为false,是否可见 // 样式属性,默认状态样式样式属性 style : { pointList : {Array}, // 必须,多边形各个顶角坐标 brushType : {string}, // 默认为fill,绘画方式 // fill(填充) | stroke(描边) | both(填充+描边) color : {color}, // 默认为'#000',填充颜色,支持rgba strokeColor : {color}, // 默认为'#000',描边颜色(轮廓),支持rgba lineWidth : {number}, // 默认为1,线条宽度,描边下有效 opacity : {number}, // 默认为1,透明度设置,如果color为rgba,则最终透明度效果叠加 shadowBlur : {number}, // 默认为0,阴影模糊度,大于0有效 shadowColor : {color}, // 默认为'#000',阴影色彩,支持rgba shadowOffsetX : {number}, // 默认为0,阴影横向偏移,正值往右,负值往左 shadowOffsetY : {number}, // 默认为0,阴影纵向偏移,正值往下,负值往上 text : {string}, // 默认为null,附加文本 textFont : {string}, // 默认为null,附加文本样式,eg:'bold 18px verdana' textPosition : {string}, // 默认为top,附加文本位置。 // inside | left | right | top | bottom textAlign : {string}, // 默认根据textPosition自动设置,附加文本水平对齐。 // start | end | left | right | center textBaseline : {string}, // 默认根据textPosition自动设置,附加文本垂直对齐。 // top | bottom | middle | // alphabetic | hanging | ideographic textColor : {color}, // 默认根据textPosition自动设置,默认策略如下,附加文本颜色 // 'inside' ? '#fff' : color }, // 样式属性,高亮样式属性,当不存在highlightStyle时使用基于默认样式扩展显示 highlightStyle : { // 同style } // 交互属性,详见shape.Base // 事件属性,详见shape.Base } 例子: { shape : 'polygon', id : '123456', zlevel : 1, style : { pointList : [[10, 10], [300, 20], [298, 400], [50, 450]] color : '#eee', text : 'Baidu' }, myName : 'kener', // 可自带任何有效自定义属性 clickable : true, onClick : function(eventPacket) { alert(eventPacket.target.myName); } } */ define( 'zrender/shape/polygon',['require','./base','../shape'],function(require) { function Polygon() { this.type = 'polygon'; } Polygon.prototype = { /** * 画刷 * @param ctx 画布句柄 * @param e 形状实体 * @param isHighlight 是否为高亮状态 * @param updateCallback 需要异步加载资源的shape可以通过这个callback(e) * 让painter更新视图,base.brush没用,需要的话重载brush */ brush : function (ctx, e, isHighlight) { var style = e.style || {}; if (isHighlight) { // 根据style扩展默认高亮样式 style = this.getHighlightStyle( style, e.highlightStyle || {} ); } ctx.save(); this.setContext(ctx, style); // 设置transform if (e.__needTransform) { ctx.transform.apply(ctx,this.updateTransform(e)); } ctx.beginPath(); this.buildPath(ctx, style); ctx.closePath(); if (style.brushType == 'stroke' || style.brushType == 'both') { ctx.stroke(); } if (style.brushType == 'fill' || style.brushType == 'both' || typeof style.brushType == 'undefined' // 默认为fill ) { if (style.lineType == 'dashed' || style.lineType == 'dotted' ) { // 特殊处理,虚线围不成path,实线再build一次 ctx.beginPath(); this.buildPath( ctx, { lineType: 'solid', lineWidth: style.lineWidth, pointList: style.pointList } ); ctx.closePath(); } ctx.fill(); } if (style.text) { this.drawText(ctx, style, e.style); } ctx.restore(); return; }, /** * 创建多边形路径 * @param {Context2D} ctx Canvas 2D上下文 * @param {Object} style 样式 */ buildPath : function(ctx, style) { // 虽然能重用brokenLine,但底层图形基于性能考虑,重复代码减少调用吧 var pointList = style.pointList; if (pointList.length < 2) { // 少于2个点就不画了~ return; } if (!style.lineType || style.lineType == 'solid') { //默认为实线 ctx.moveTo(pointList[0][0],pointList[0][1]); for (var i = 1, l = pointList.length; i < l; i++) { ctx.lineTo(pointList[i][0],pointList[i][1]); } ctx.lineTo(pointList[0][0], pointList[0][1]); } else if (style.lineType == 'dashed' || style.lineType == 'dotted' ) { var dashLength = style._dashLength || (style.lineWidth || 1) * (style.lineType == 'dashed' ? 5 : 1); style._dashLength = dashLength; ctx.moveTo(pointList[0][0],pointList[0][1]); for (var i = 1, l = pointList.length; i < l; i++) { this.dashedLineTo( ctx, pointList[i - 1][0], pointList[i - 1][1], pointList[i][0], pointList[i][1], dashLength ); } this.dashedLineTo( ctx, pointList[pointList.length - 1][0], pointList[pointList.length - 1][1], pointList[0][0], pointList[0][1], dashLength ); } return; }, /** * 返回矩形区域,用于局部刷新和文字定位 * @param {Object} style */ getRect : function(style) { var minX = Number.MAX_VALUE; var maxX = Number.MIN_VALUE; var minY = Number.MAX_VALUE; var maxY = Number.MIN_VALUE; var pointList = style.pointList; for(var i = 0, l = pointList.length; i < l; i++) { if (pointList[i][0] < minX) { minX = pointList[i][0]; } if (pointList[i][0] > maxX) { maxX = pointList[i][0]; } if (pointList[i][1] < minY) { minY = pointList[i][1]; } if (pointList[i][1] > maxY) { maxY = pointList[i][1]; } } var lineWidth; if (style.brushType == 'stroke' || style.brushType == 'fill') { lineWidth = style.lineWidth || 1; } else { lineWidth = 0; } return { x : Math.round(minX - lineWidth / 2), y : Math.round(minY - lineWidth / 2), width : maxX - minX + lineWidth, height : maxY - minY + lineWidth }; } }; var base = require('./base'); base.derive(Polygon); var shape = require('../shape'); shape.define('polygon', new Polygon()); return Polygon; } ); /** * zrender * * @author Kener (@Kener-林峰, linzhifeng@baidu.com) * * shape类:折线 * 可配图形属性: { // 基础属性 shape : 'brokenLine', // 必须,shape类标识,需要显式指定 id : {string}, // 必须,图形唯一标识,可通过zrender实例方法newShapeId生成 zlevel : {number}, // 默认为0,z层level,决定绘画在哪层canvas中 invisible : {boolean}, // 默认为false,是否可见 // 样式属性,默认状态样式样式属性 style : { pointList : {Array}, // 必须,各个顶角坐标 strokeColor : {color}, // 默认为'#000',线条颜色(轮廓),支持rgba lineType : {string}, // 默认为solid,线条类型,solid | dashed | dotted lineWidth : {number}, // 默认为1,线条宽度 lineCap : {string}, // 默认为butt,线帽样式。butt | round | square lineJoin : {string}, // 默认为miter,线段连接样式。miter | round | bevel miterLimit : {number}, // 默认为10,最大斜接长度,仅当lineJoin为miter时生效 opacity : {number}, // 默认为1,透明度设置,如果color为rgba,则最终透明度效果叠加 shadowBlur : {number}, // 默认为0,阴影模糊度,大于0有效 shadowColor : {color}, // 默认为'#000',阴影色彩,支持rgba shadowOffsetX : {number}, // 默认为0,阴影横向偏移,正值往右,负值往左 shadowOffsetY : {number}, // 默认为0,阴影纵向偏移,正值往下,负值往上 text : {string}, // 默认为null,附加文本 textFont : {string}, // 默认为null,附加文本样式,eg:'bold 18px verdana' textPosition : {string}, // 默认为end,附加文本位置。 // start | end textAlign : {string}, // 默认根据textPosition自动设置,附加文本水平对齐。 // start | end | left | right | center textBaseline : {string}, // 默认根据textPosition自动设置,附加文本垂直对齐。 // top | bottom | middle | // alphabetic | hanging | ideographic textColor : {color}, // 默认根据textPosition自动设置,默认策略如下,附加文本颜色 // 'inside' ? '#000' : color }, // 样式属性,高亮样式属性,当不存在highlightStyle时使用基于默认样式扩展显示 highlightStyle : { // 同style } // 交互属性,详见shape.Base // 事件属性,详见shape.Base } 例子: { shape : 'brokenLine', id : '123456', zlevel : 1, style : { pointList : [[10, 10], [300, 20], [298, 400], [50, 450]], strokeColor : '#eee', lineWidth : 20, text : 'Baidu' }, myName : 'kener', //可自带任何有效自定义属性 clickable : true, onClick : function(eventPacket) { alert(eventPacket.target.myName); } } */ define( 'zrender/shape/brokenLine',['require','../shape','./base','../shape'],function(require) { function BrokenLine() { this.type = 'brokenLine'; this.brushTypeOnly = 'stroke'; //线条只能描边,填充后果自负 this.textPosition = 'end'; } BrokenLine.prototype = { /** * 创建多边形路径 * @param {Context2D} ctx Canvas 2D上下文 * @param {Object} style 样式 */ buildPath : function(ctx, style) { var pointList = style.pointList; if (pointList.length < 2) { // 少于2个点就不画了~ return; } if (!style.lineType || style.lineType == 'solid') { //默认为实线 ctx.moveTo(pointList[0][0],pointList[0][1]); for (var i = 1, l = pointList.length; i < l; i++) { ctx.lineTo(pointList[i][0],pointList[i][1]); } } else if (style.lineType == 'dashed' || style.lineType == 'dotted' ) { var dashLength = (style.lineWidth || 1) * (style.lineType == 'dashed' ? 5 : 1); ctx.moveTo(pointList[0][0],pointList[0][1]); for (var i = 1, l = pointList.length; i < l; i++) { this.dashedLineTo( ctx, pointList[i - 1][0], pointList[i - 1][1], pointList[i][0], pointList[i][1], dashLength ); } } return; }, /** * 返回矩形区域,用于局部刷新和文字定位 * @param {Object} style */ getRect : function(style) { var shape = require('../shape'); return shape.get('polygon').getRect(style); } }; var base = require('./base'); base.derive(BrokenLine); var shape = require('../shape'); shape.define('brokenLine', new BrokenLine()); return BrokenLine; } ); /** * zrender * * @author Kener (@Kener-林峰, linzhifeng@baidu.com) , * strwind (@劲风FEI, yaofeifei@baidu.com) * * shape类:矩形 * 可配图形属性: { // 基础属性 shape : 'rectangle', // 必须,shape类标识,需要显式指定 id : {string}, // 必须,图形唯一标识,可通过zrender实例方法newShapeId生成 zlevel : {number}, // 默认为0,z层level,决定绘画在哪层canvas中 invisible : {boolean}, // 默认为false,是否可见 // 样式属性,默认状态样式样式属性 style : { x : {number}, // 必须,左上角横坐标 y : {number}, // 必须,左上角纵坐标 width : {number}, // 必须,宽度 height : {number}, // 必须,高度 radius : {array}, // 默认为[0],圆角 brushType : {string}, // 默认为fill,绘画方式 // fill(填充) | stroke(描边) | both(填充+描边) color : {color}, // 默认为'#000',填充颜色,支持rgba strokeColor : {color}, // 默认为'#000',描边颜色(轮廓),支持rgba lineWidth : {number}, // 默认为1,线条宽度,描边下有效 opacity : {number}, // 默认为1,透明度设置,如果color为rgba,则最终透明度效果叠加 shadowBlur : {number}, // 默认为0,阴影模糊度,大于0有效 shadowColor : {color}, // 默认为'#000',阴影色彩,支持rgba shadowOffsetX : {number}, // 默认为0,阴影横向偏移,正值往右,负值往左 shadowOffsetY : {number}, // 默认为0,阴影纵向偏移,正值往下,负值往上 text : {string}, // 默认为null,附加文本 textFont : {string}, // 默认为null,附加文本样式,eg:'bold 18px verdana' textPosition : {string}, // 默认为top,附加文本位置。 // inside | left | right | top | bottom textAlign : {string}, // 默认根据textPosition自动设置,附加文本水平对齐。 // start | end | left | right | center textBaseline : {string}, // 默认根据textPosition自动设置,附加文本垂直对齐。 // top | bottom | middle | // alphabetic | hanging | ideographic textColor : {color}, // 默认根据textPosition自动设置,默认策略如下,附加文本颜色 // 'inside' ? '#fff' : color }, // 样式属性,高亮样式属性,当不存在highlightStyle时使用基于默认样式扩展显示 highlightStyle : { // 同style } // 交互属性,详见shape.Base // 事件属性,详见shape.Base } 例子: { shape : 'rectangle', id : '123456', zlevel : 1, style : { x : 200, y : 100, width : 150, height : 50, color : '#eee', text : 'Baidu' }, myName : 'kener', // 可自带任何有效自定义属性 clickable : true, onClick : function(eventPacket) { alert(eventPacket.target.myName); } } */ define( 'zrender/shape/rectangle',['require','./base','../shape'],function(require) { function Rectangle() { this.type = 'rectangle'; } Rectangle.prototype = { /** * 绘制圆角矩形 * @param {Context2D} ctx Canvas 2D上下文 * @param {Object} style 样式 */ _buildRadiusPath: function(ctx, style) { //左上、右上、右下、左下角的半径依次为r1、r2、r3、r4 //r缩写为1 相当于 [1, 1, 1, 1] //r缩写为[1] 相当于 [1, 1, 1, 1] //r缩写为[1, 2] 相当于 [1, 2, 1, 2] //r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2] var x = style.x; var y = style.y; var width = style.width; var height = style.height; var r = style.radius; var r1; var r2; var r3; var r4; if(typeof r === 'number') { r1 = r2 = r3 = r4 = r; } else if(r instanceof Array) { if (r.length === 1) { r1 = r2 = r3 = r4 = r[0]; } else if(r.length === 2) { r1 = r3 = r[0]; r2 = r4 = r[1]; } else if(r.length === 3) { r1 = r[0]; r2 = r4 = r[1]; r3 = r[2]; } else { r1 = r[0]; r2 = r[1]; r3 = r[2]; r4 = r[3]; } } else { r1 = r2 = r3 = r4 = 0; } ctx.moveTo(x + r1, y); ctx.lineTo(x + width - r2, y); r2 !== 0 && ctx.quadraticCurveTo( x + width, y, x + width, y + r2 ); ctx.lineTo(x + width, y + height - r3); r3 !== 0 && ctx.quadraticCurveTo( x + width, y + height, x + width - r3, y + height ); ctx.lineTo(x + r4, y + height); r4 !== 0 && ctx.quadraticCurveTo( x, y + height, x, y + height - r4 ); ctx.lineTo(x, y + r1); r1 !== 0 && ctx.quadraticCurveTo(x, y, x + r1, y); }, /** * 创建矩形路径 * @param {Context2D} ctx Canvas 2D上下文 * @param {Object} style 样式 */ buildPath : function(ctx, style) { if(!style.radius) { ctx.moveTo(style.x, style.y); ctx.lineTo(style.x + style.width, style.y); ctx.lineTo(style.x + style.width, style.y + style.height); ctx.lineTo(style.x, style.y + style.height); ctx.lineTo(style.x, style.y); //ctx.rect(style.x, style.y, style.width, style.height); } else { this._buildRadiusPath(ctx, style); } return; }, /** * 返回矩形区域,用于局部刷新和文字定位 * @param {Object} style */ getRect : function(style) { var lineWidth; if (style.brushType == 'stroke' || style.brushType == 'fill') { lineWidth = style.lineWidth || 1; } else { lineWidth = 0; } return { x : Math.round(style.x - lineWidth / 2), y : Math.round(style.y - lineWidth / 2), width : style.width + lineWidth, height : style.height + lineWidth }; } }; var base = require('./base'); base.derive(Rectangle); var shape = require('../shape'); shape.define('rectangle', new Rectangle()); return Rectangle; } ); /** * zrender * * @author Kener (@Kener-林峰, linzhifeng@baidu.com) * * shape类:圆环 * 可配图形属性: { // 基础属性 shape : 'ring', // 必须,shape类标识,需要显式指定 id : {string}, // 必须,图形唯一标识,可通过zrender实例方法newShapeId生成 zlevel : {number}, // 默认为0,z层level,决定绘画在哪层canvas中 invisible : {boolean}, // 默认为false,是否可见 // 样式属性,默认状态样式样式属性 style : { x : {number}, // 必须,圆心横坐标 y : {number}, // 必须,圆心纵坐标 r0 : {number}, // 必须,内圆半径 r : {number}, // 必须,外圆半径 brushType : {string}, // 默认为fill,绘画方式 // fill(填充) | stroke(描边) | both(填充+描边) color : {color}, // 默认为'#000',填充颜色,支持rgba strokeColor : {color}, // 默认为'#000',描边颜色(轮廓),支持rgba lineWidth : {number}, // 默认为1,线条宽度,描边下有效 opacity : {number}, // 默认为1,透明度设置,如果color为rgba,则最终透明度效果叠加 shadowBlur : {number}, // 默认为0,阴影模糊度,大于0有效 shadowColor : {color}, // 默认为'#000',阴影色彩,支持rgba shadowOffsetX : {number}, // 默认为0,阴影横向偏移,正值往右,负值往左 shadowOffsetY : {number}, // 默认为0,阴影纵向偏移,正值往下,负值往上 text : {string}, // 默认为null,附加文本 textFont : {string}, // 默认为null,附加文本样式,eg:'bold 18px verdana' textPosition : {string}, // 默认为outside,附加文本位置。 // outside | inside textAlign : {string}, // 默认根据textPosition自动设置,附加文本水平对齐。 // start | end | left | right | center textBaseline : {string}, // 默认根据textPosition自动设置,附加文本垂直对齐。 // top | bottom | middle | // alphabetic | hanging | ideographic textColor : {color}, // 默认根据textPosition自动设置,默认策略如下,附加文本颜色 // 'inside' ? '#fff' : color }, // 样式属性,高亮样式属性,当不存在highlightStyle时使用基于默认样式扩展显示 highlightStyle : { // 同style } // 交互属性,详见shape.Base // 事件属性,详见shape.Base } 例子: { shape : 'ring', id : '123456', zlevel : 1, style : { x : 200, y : 100, r : 50, color : '#eee', text : 'Baidu' }, myName : 'kener', // 可自带任何有效自定义属性 clickable : true, onClick : function(eventPacket) { alert(eventPacket.target.myName); } } */ define( 'zrender/shape/ring',['require','./base','../shape'],function(require) { function Ring() { this.type = 'ring'; } Ring.prototype = { /** * 创建圆环路径,依赖扇形路径 * @param {Context2D} ctx Canvas 2D上下文 * @param {Object} style 样式 */ buildPath : function(ctx, style) { // 非零环绕填充优化 ctx.arc(style.x, style.y, style.r, 0, Math.PI * 2, false); ctx.moveTo(style.x + style.r0, style.y); ctx.arc(style.x, style.y, style.r0, 0, Math.PI * 2, true); return; }, /** * 返回矩形区域,用于局部刷新和文字定位 * @param {Object} style */ getRect : function(style) { var lineWidth; if (style.brushType == 'stroke' || style.brushType == 'fill') { lineWidth = style.lineWidth || 1; } else { lineWidth = 0; } return { x : Math.round(style.x - style.r - lineWidth / 2), y : Math.round(style.y - style.r - lineWidth / 2), width : style.r * 2 + lineWidth, height : style.r * 2 + lineWidth }; } }; var base = require('./base'); base.derive(Ring); var shape = require('../shape'); shape.define('ring', new Ring()); return Ring; } ); /** * zrender: 数学辅助类 * * @author Kener (@Kener-林峰, linzhifeng@baidu.com) * * sin:正弦函数,自动缓存 * cos:余弦函数,自动缓存 * degreeToRadian:角度转弧度 * radianToDegree:弧度转角度 */ define( 'zrender/tool/math',[],function() { var _cache = { sin : {}, //sin缓存 cos : {} //cos缓存 }; var _radians = Math.PI / 180; /** * @param angle 弧度(角度)参数 * @param isDegrees angle参数是否为角度计算,默认为false,angle为以弧度计量的角度 */ function sin(angle, isDegrees) { angle = (isDegrees ? angle * _radians : angle).toFixed(4); if(typeof _cache.sin[angle] == 'undefined') { _cache.sin[angle] = Math.sin(angle); } return _cache.sin[angle]; } /** * @param radians 弧度参数 */ function cos(angle, isDegrees) { angle = (isDegrees ? angle * _radians : angle).toFixed(4); if(typeof _cache.cos[angle] == 'undefined') { _cache.cos[angle] = Math.cos(angle); } return _cache.cos[angle]; } /** * 角度转弧度 * @param {Object} angle */ function degreeToRadian(angle) { return angle * _radians; } /** * 弧度转角度 * @param {Object} angle */ function radianToDegree(angle) { return angle / _radians; } return { sin : sin, cos : cos, degreeToRadian : degreeToRadian, radianToDegree : radianToDegree }; } ); /** * zrender * * @author Kener (@Kener-林峰, linzhifeng@baidu.com) * * shape类:扇形 * 可配图形属性: { // 基础属性 shape : 'sector', // 必须,shape类标识,需要显式指定 id : {string}, // 必须,图形唯一标识,可通过zrender实例方法newShapeId生成 zlevel : {number}, // 默认为0,z层level,决定绘画在哪层canvas中 invisible : {boolean}, // 默认为false,是否可见 // 样式属性,默认状态样式样式属性 style : { x : {number}, // 必须,圆心横坐标 y : {number}, // 必须,圆心纵坐标 r0 : {number}, // 默认为0,内圆半径,指定后将出现内弧,同时扇边长度 = r - r0 r : {number}, // 必须,外圆半径 startAngle : {number}, // 必须,起始角度[0, 360) endAngle : {number}, // 必须,结束角度(0, 360] brushType : {string}, // 默认为fill,绘画方式 // fill(填充) | stroke(描边) | both(填充+描边) color : {color}, // 默认为'#000',填充颜色,支持rgba strokeColor : {color}, // 默认为'#000',描边颜色(轮廓),支持rgba lineWidth : {number}, // 默认为1,线条宽度,描边下有效 opacity : {number}, // 默认为1,透明度设置,如果color为rgba,则最终透明度效果叠加 shadowBlur : {number}, // 默认为0,阴影模糊度,大于0有效 shadowColor : {color}, // 默认为'#000',阴影色彩,支持rgba shadowOffsetX : {number}, // 默认为0,阴影横向偏移,正值往右,负值往左 shadowOffsetY : {number}, // 默认为0,阴影纵向偏移,正值往下,负值往上 text : {string}, // 默认为null,附加文本 textFont : {string}, // 默认为null,附加文本样式,eg:'bold 18px verdana' textPosition : {string}, // 默认为outside,附加文本位置。 // outside | inside textAlign : {string}, // 默认根据textPosition自动设置,附加文本水平对齐。 // start | end | left | right | center textBaseline : {string}, // 默认根据textPosition自动设置,附加文本垂直对齐。 // top | bottom | middle | // alphabetic | hanging | ideographic textColor : {color}, // 默认根据textPosition自动设置,默认策略如下,附加文本颜色 // 'inside' ? '#fff' : color }, // 样式属性,高亮样式属性,当不存在highlightStyle时使用基于默认样式扩展显示 highlightStyle : { // 同style } // 交互属性,详见shape.Base // 事件属性,详见shape.Base } 例子: { shape : 'sector', id : '123456', zlevel : 1, style : { x : 200, y : 100, r : 50, color : '#eee', text : 'Baidu' }, myName : 'kener', // 可自带任何有效自定义属性 clickable : true, onClick : function(eventPacket) { alert(eventPacket.target.myName); } } */ define( 'zrender/shape/sector',['require','../tool/math','../shape','./base','../shape'],function(require) { var math = require('../tool/math'); function Sector() { this.type = 'sector'; } Sector.prototype = { /** * 创建扇形路径 * @param {Context2D} ctx Canvas 2D上下文 * @param {Object} style 样式 */ buildPath : function(ctx, style) { var x = style.x; // 圆心x var y = style.y; // 圆心y var r0 = typeof style.r0 == 'undefined' // 形内半径[0,r) ? 0 : style.r0; var r = style.r; // 扇形外半径(0,r] var startAngle = style.startAngle; // 起始角度[0,360) var endAngle = style.endAngle; // 结束角度(0,360] var PI2 = Math.PI * 2; startAngle = math.degreeToRadian(startAngle); endAngle = math.degreeToRadian(endAngle); //sin&cos已经在tool.math中缓存了,放心大胆的重复调用 ctx.moveTo( math.cos(startAngle) * r0 + x, y - math.sin(startAngle) * r0 ); ctx.lineTo( math.cos(startAngle) * r + x, y - math.sin(startAngle) * r ); ctx.arc(x, y, r, PI2 - startAngle, PI2 - endAngle, true); ctx.lineTo( math.cos(endAngle) * r0 + x, y - math.sin(endAngle) * r0 ); if (r0 !== 0) { ctx.arc(x, y, r0, PI2 - endAngle, PI2 - startAngle, false); } return; }, /** * 返回矩形区域,用于局部刷新和文字定位 * @param {Object} style */ getRect : function(style) { var x = style.x; // 圆心x var y = style.y; // 圆心y var r0 = typeof style.r0 == 'undefined' // 形内半径[0,r) ? 0 : style.r0; var r = style.r; // 扇形外半径(0,r] var startAngle = style.startAngle; // 起始角度[0,360) var endAngle = style.endAngle; // 结束角度(0,360] var pointList = []; if (startAngle < 90 && endAngle > 90) { pointList.push([ x, y - r ]); } if (startAngle < 180 && endAngle > 180) { pointList.push([ x - r, y ]); } if (startAngle < 270 && endAngle > 270) { pointList.push([ x, y + r ]); } if (startAngle < 360 && endAngle > 360) { pointList.push([ x + r, y ]); } startAngle = math.degreeToRadian(startAngle); endAngle = math.degreeToRadian(endAngle); pointList.push([ math.cos(startAngle) * r0 + x, y - math.sin(startAngle) * r0 ]); pointList.push([ math.cos(startAngle) * r + x, y - math.sin(startAngle) * r ]); pointList.push([ math.cos(endAngle) * r + x, y - math.sin(endAngle) * r ]); pointList.push([ math.cos(endAngle) * r0 + x, y - math.sin(endAngle) * r0 ]); var shape = require('../shape'); return shape.get('polygon').getRect({ brushType : style.brushType, lineWidth : style.lineWidth, pointList : pointList }); } }; var base = require('./base'); base.derive(Sector); var shape = require('../shape'); shape.define('sector', new Sector()); return Sector; } ); /** * zrender * * @author Kener (@Kener-林峰, linzhifeng@baidu.com) * * shape类:文字 * 可配图形属性: { // 基础属性 shape : 'text', // 必须,shape类标识,需要显式指定 id : {string}, // 必须,图形唯一标识,可通过zrender实例方法newShapeId生成 zlevel : {number}, // 默认为0,z层level,决定绘画在哪层canvas中 invisible : {boolean}, // 默认为false,是否可见 // 样式属性,默认状态样式样式属性 style : { x : {number}, // 必须,横坐标 y : {number}, // 必须,纵坐标 brushType : {string}, // 默认为fill,绘画方式 // fill(填充) | stroke(描边) | both(填充+描边) color : {color}, // 默认为'#000',填充颜色,支持rgba strokeColor : {color}, // 默认为'#000',线条颜色(轮廓),支持rgba lineWidth : {number}, // 默认为1,线条宽度 opacity : {number}, // 默认为1,透明度设置,如果color为rgba,则最终透明度效果叠加 shadowBlur : {number}, // 默认为0,阴影模糊度,大于0有效 shadowColor : {color}, // 默认为'#000',阴影色彩,支持rgba shadowOffsetX : {number}, // 默认为0,阴影横向偏移,正值往右,负值往左 shadowOffsetY : {number}, // 默认为0,阴影纵向偏移,正值往下,负值往上 text : {string}, // 必须,文本内容 textFont : {string}, // 默认为null,文本文字样式,eg:'bold 18px verdana' textAlign : {string}, // 默认为start,文本水平对齐。 // start | end | left | right | center textBaseline : {string}, // 默认为middle,文本垂直对齐。 // top | bottom | middle | // alphabetic | hanging | ideographic maxWidth : {number} // 默认为null,最大宽度 }, // 样式属性,高亮样式属性,当不存在highlightStyle时使用基于默认样式扩展显示 highlightStyle : { // 同style } // 交互属性,详见shape.Base // 事件属性,详见shape.Base } 例子: { shape : 'text', id : '123456', zlevel : 1, style : { x : 200, y : 100, color : 'red', text : 'Baidu' }, myName : 'kener', //可自带任何有效自定义属性 clickable : true, onClick : function(eventPacket) { alert(eventPacket.target.myName); } } */ define( 'zrender/shape/text',['require','../tool/area','./base','../shape'],function(require) { function Text() { this.type = 'text'; } Text.prototype = { /** * 画刷,重载基类方法 * @param {Context2D} ctx Canvas 2D上下文 * @param e 图形形状实体 * @param isHighlight 是否为高亮状态 */ brush : function(ctx, e, isHighlight) { var style = e.style || {}; if (isHighlight) { // 根据style扩展默认高亮样式 style = this.getHighlightStyle( style, e.highlightStyle || {} ); } ctx.save(); this.setContext(ctx, style); // 设置transform if (e.__needTransform) { ctx.transform.apply(ctx,this.updateTransform(e)); } if (style.textFont) { ctx.font = style.textFont; } ctx.textAlign = style.textAlign || 'start'; ctx.textBaseline = style.textBaseline || 'middle'; if (style.maxWidth) { switch (style.brushType) { case 'fill': ctx.fillText( style.text, style.x, style.y, style.maxWidth ); break; case 'stroke': ctx.strokeText( style.text, style.x, style.y, style.maxWidth ); break; case 'both': ctx.strokeText( style.text, style.x, style.y, style.maxWidth ); ctx.fillText( style.text, style.x, style.y, style.maxWidth ); break; default: ctx.fillText( style.text, style.x, style.y, style.maxWidth ); } } else{ switch (style.brushType) { case 'fill': ctx.fillText(style.text, style.x, style.y); break; case 'stroke': ctx.strokeText(style.text, style.x, style.y); break; case 'both': ctx.strokeText(style.text, style.x, style.y); ctx.fillText(style.text, style.x, style.y); break; default: ctx.fillText(style.text, style.x, style.y); } } ctx.restore(); return; }, /** * 返回矩形区域,用于局部刷新和文字定位 * @param {Object} style */ getRect : function(style) { var area = require('../tool/area'); var width = area.getTextWidth(style.text, style.textFont); var height = area.getTextWidth('国', style.textFont); //比较粗暴 var textX = style.x; //默认start == left if (style.textAlign == 'end' || style.textAlign == 'right') { textX -= width; } else if (style.textAlign == 'center') { textX -= (width / 2); } var textY = style.y - height / 2; //默认middle if (style.textBaseline == 'top') { textY += height / 2; } else if (style.textBaseline == 'bottom') { textX -= height / 2; } return { x : textX, y : textY, width : width, height : height }; } }; var base = require('./base'); base.derive(Text); var shape = require('../shape'); shape.define('text', new Text()); return Text; } ); /** * zrender * * @author Kener (@Kener-林峰, linzhifeng@baidu.com) * * shape类:心形 * 可配图形属性: { // 基础属性 shape : 'heart', // 必须,shape类标识,需要显式指定 id : {string}, // 必须,图形唯一标识,可通过zrender实例方法newShapeId生成 zlevel : {number}, // 默认为0,z层level,决定绘画在哪层canvas中 invisible : {boolean}, // 默认为false,是否可见 // 样式属性,默认状态样式样式属性 style : { x : {number}, // 必须,心形内部尖端横坐标 y : {number}, // 必须,心形内部尖端纵坐标 a : {number}, // 必须,心形横宽(中轴线到水平边缘最宽处距离) b : {number}, // 必须,心形纵高(内尖到外尖距离) brushType : {string}, // 默认为fill,绘画方式 // fill(填充) | stroke(描边) | both(填充+描边) color : {color}, // 默认为'#000',填充颜色,支持rgba strokeColor : {color}, // 默认为'#000',描边颜色(轮廓),支持rgba lineWidth : {number}, // 默认为1,线条宽度,描边下有效 shadowBlur : {number}, // 默认为0,阴影模糊度,大于0有效 shadowColor : {color}, // 默认为'#000',阴影色彩,支持rgba shadowOffsetX : {number}, // 默认为0,阴影横向偏移,正值往右,负值往左 shadowOffsetY : {number}, // 默认为0,阴影横向偏移,正值往右,负值往左 text : {string}, // 默认为null,附加文本 textFont : {string}, // 默认为null,附加文本样式,eg:'bold 18px verdana' textPosition : {string}, // 默认为outside,附加文本位置。 // outside | inside textAlign : {string}, // 默认根据textPosition自动设置,附加文本水平对齐。 // start | end | left | right | center textBaseline : {string}, // 默认根据textPosition自动设置,附加文本垂直对齐。 // top | bottom | middle | // alphabetic | hanging | ideographic textColor : {color}, // 默认根据textPosition自动设置,默认策略如下,附加文本颜色 // 'inside' ? '#fff' : color }, // 样式属性,高亮样式属性,当不存在highlightStyle时使用基于默认样式扩展显示 highlightStyle : { // 同style } // 交互属性,详见shape.Base // 事件属性,详见shape.Base } 例子: { shape : 'heart', id : '123456', zlevel : 1, style : { x : 200, y : 100, a : 50, b : 80, color : '#eee', text : 'Baidu' }, myName : 'kener', // 可自带任何有效自定义属性 clickable : true, onClick : function(eventPacket) { alert(eventPacket.target.myName); } } */ define( 'zrender/shape/heart',['require','./base','../shape'],function(require) { function Heart() { this.type = 'heart'; } Heart.prototype = { /** * 创建扇形路径 * @param {Context2D} ctx Canvas 2D上下文 * @param {Object} style 样式 */ buildPath : function(ctx, style) { ctx.moveTo(style.x, style.y); ctx.bezierCurveTo( style.x + style.a / 2, style.y - style.b * 2 / 3, style.x + style.a * 2, style.y + style.b / 3, style.x, style.y + style.b ); ctx.bezierCurveTo( style.x - style.a * 2, style.y + style.b / 3, style.x - style.a / 2, style.y - style.b * 2 / 3, style.x, style.y ); return; }, /** * 返回矩形区域,用于局部刷新和文字定位 * @param {Object} style */ getRect : function(style) { var lineWidth; if (style.brushType == 'stroke' || style.brushType == 'fill') { lineWidth = style.lineWidth || 1; } else { lineWidth = 0; } return { x : Math.round(style.x - style.a - lineWidth / 2), y : Math.round(style.y - style.b / 4 - lineWidth / 2), width : style.a * 2 + lineWidth, height : style.b * 5 / 4 + lineWidth }; } }; var base = require('./base'); base.derive(Heart); var shape = require('../shape'); shape.define('heart', new Heart()); return Heart; } ); /** * zrender * * @author Kener (@Kener-林峰, linzhifeng@baidu.com) * * shape类:水滴 * 可配图形属性: { // 基础属性 shape : 'heart', // 必须,shape类标识,需要显式指定 id : {string}, // 必须,图形唯一标识,可通过zrender实例方法newShapeId生成 zlevel : {number}, // 默认为0,z层level,决定绘画在哪层canvas中 invisible : {boolean}, // 默认为false,是否可见 // 样式属性,默认状态样式样式属性 style : { x : {number}, // 必须,水滴中心横坐标 y : {number}, // 必须,水滴中心纵坐标 a : {number}, // 必须,水滴横宽(中心到水平边缘最宽处距离) b : {number}, // 必须,水滴纵高(中心到尖端距离) brushType : {string}, // 默认为fill,绘画方式 // fill(填充) | stroke(描边) | both(填充+描边) color : {color}, // 默认为'#000',填充颜色,支持rgba strokeColor : {color}, // 默认为'#000',描边颜色(轮廓),支持rgba lineWidth : {number}, // 默认为1,线条宽度,描边下有效 shadowBlur : {number}, // 默认为0,阴影模糊度,大于0有效 shadowColor : {color}, // 默认为'#000',阴影色彩,支持rgba shadowOffsetX : {number}, // 默认为0,阴影横向偏移,正值往右,负值往左 shadowOffsetY : {number}, // 默认为0,阴影横向偏移,正值往右,负值往左 text : {string}, // 默认为null,附加文本 textFont : {string}, // 默认为null,附加文本样式,eg:'bold 18px verdana' textPosition : {string}, // 默认为outside,附加文本位置。 // outside | inside textAlign : {string}, // 默认根据textPosition自动设置,附加文本水平对齐。 // start | end | left | right | center textBaseline : {string}, // 默认根据textPosition自动设置,附加文本垂直对齐。 // top | bottom | middle | // alphabetic | hanging | ideographic textColor : {color}, // 默认根据textPosition自动设置,默认策略如下,附加文本颜色 // 'inside' ? '#fff' : color }, // 样式属性,高亮样式属性,当不存在highlightStyle时使用基于默认样式扩展显示 highlightStyle : { // 同style } // 交互属性,详见shape.Base // 事件属性,详见shape.Base } 例子: { shape : 'droplet', id : '123456', zlevel : 1, style : { x : 200, y : 100, a : 50, b : 80, color : '#eee', text : 'Baidu' }, myName : 'kener', // 可自带任何有效自定义属性 clickable : true, onClick : function(eventPacket) { alert(eventPacket.target.myName); } } */ define( 'zrender/shape/droplet',['require','./base','../shape'],function(require) { function Droplet() { this.type = 'droplet'; } Droplet.prototype = { /** * 创建扇形路径 * @param {Context2D} ctx Canvas 2D上下文 * @param {Object} style 样式 */ buildPath : function(ctx, style) { ctx.moveTo(style.x, style.y + style.a); ctx.bezierCurveTo( style.x + style.a, style.y + style.a, style.x + style.a * 3 / 2, style.y - style.a / 3, style.x, style.y - style.b ); ctx.bezierCurveTo( style.x - style.a * 3 / 2, style.y - style.a / 3, style.x - style.a, style.y + style.a, style.x, style.y + style.a ); return; }, /** * 返回矩形区域,用于局部刷新和文字定位 * @param {Object} style */ getRect : function(style) { var lineWidth; if (style.brushType == 'stroke' || style.brushType == 'fill') { lineWidth = style.lineWidth || 1; } else { lineWidth = 0; } return { x : Math.round(style.x - style.a - lineWidth / 2), y : Math.round(style.y - style.b - lineWidth / 2), width : style.a * 2 + lineWidth, height : style.a + style.b + lineWidth }; } }; var base = require('./base'); base.derive(Droplet); var shape = require('../shape'); shape.define('droplet', new Droplet()); return Droplet; } ); /** * zrender * * author: CrossDo (chenhuaimu@baidu.com) * * shape类:路径 * 可配图形属性: { // 基础属性 shape : 'path', // 必须,shape类标识,需要显式指定 id : {string}, // 必须,图形唯一标识,可通过zrender实例方法newShapeId生成 zlevel : {number}, // 默认为0,z层level,决定绘画在哪层canvas中 invisible : {boolean}, // 默认为false,是否可见 // 样式属性,默认状态样式样式属性 style : { path : {string},// 必须,路径。例如:M 0 0 L 0 10 L 10 10 Z (一个三角形) //M = moveto //L = lineto //H = horizontal lineto //V = vertical lineto //C = curveto //S = smooth curveto //Q = quadratic Belzier curve //T = smooth quadratic Belzier curveto //Z = closepath x : {number}, // 必须,x轴坐标 y : {number}, // 必须,y轴坐标 brushType : {string}, // 默认为fill,绘画方式 // fill(填充) | stroke(描边) | both(填充+描边) color : {color}, // 默认为'#000',填充颜色,支持rgba strokeColor : {color}, // 默认为'#000',描边颜色(轮廓),支持rgba lineWidth : {number}, // 默认为1,线条宽度,描边下有效 opacity : {number}, // 默认为1,透明度设置,如果color为rgba,则最终透明度效果叠加 shadowBlur : {number}, // 默认为0,阴影模糊度,大于0有效 shadowColor : {color}, // 默认为'#000',阴影色彩,支持rgba shadowOffsetX : {number}, // 默认为0,阴影横向偏移,正值往右,负值往左 shadowOffsetY : {number}, // 默认为0,阴影纵向偏移,正值往下,负值往上 text : {string}, // 默认为null,附加文本 textFont : {string}, // 默认为null,附加文本样式,eg:'bold 18px verdana' textPosition : {string}, // 默认为top,附加文本位置。 // inside | left | right | top | bottom textAlign : {string}, // 默认根据textPosition自动设置,附加文本水平对齐。 // start | end | left | right | center textBaseline : {string}, // 默认根据textPosition自动设置,附加文本垂直对齐。 // top | bottom | middle | // alphabetic | hanging | ideographic textColor : {color}, // 默认根据textPosition自动设置,默认策略如下,附加文本颜色 // 'inside' ? '#fff' : color }, // 样式属性,高亮样式属性,当不存在highlightStyle时使用基于默认样式扩展显示 highlightStyle : { // 同style } // 交互属性,详见shape.Base // 事件属性,详见shape.Base } **/ define('zrender/shape/path',['require','./base','../shape'],function(require) { function Path() { this.type = 'path'; } Path.prototype = { _parsePathData : function(data) { if (!data) { return []; } // command string var cs = data; // command chars var cc = [ 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z', 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A' ]; cs = cs.replace(/ /g, ' '); cs = cs.replace(/ /g, ','); cs = cs.replace(/,,/g, ','); var n; // create pipes so that we can split the data for (n = 0; n < cc.length; n++) { cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]); } // create array var arr = cs.split('|'); var ca = []; // init context point var cpx = 0; var cpy = 0; for (n = 1; n < arr.length; n++) { var str = arr[n]; var c = str.charAt(0); str = str.slice(1); str = str.replace(new RegExp('e,-', 'g'), 'e-'); var p = str.split(','); if (p.length > 0 && p[0] === '') { p.shift(); } for (var i = 0; i < p.length; i++) { p[i] = parseFloat(p[i]); } while (p.length > 0) { if (isNaN(p[0])) { break; } var cmd = null; var points = []; var ctlPtx; var ctlPty; var prevCmd; var rx; var ry; var psi; var fa; var fs; var x1 = cpx; var y1 = cpy; // convert l, H, h, V, and v to L switch (c) { case 'l': cpx += p.shift(); cpy += p.shift(); cmd = 'L'; points.push(cpx, cpy); break; case 'L': cpx = p.shift(); cpy = p.shift(); points.push(cpx, cpy); break; case 'm': cpx += p.shift(); cpy += p.shift(); cmd = 'M'; points.push(cpx, cpy); c = 'l'; break; case 'M': cpx = p.shift(); cpy = p.shift(); cmd = 'M'; points.push(cpx, cpy); c = 'L'; break; case 'h': cpx += p.shift(); cmd = 'L'; points.push(cpx, cpy); break; case 'H': cpx = p.shift(); cmd = 'L'; points.push(cpx, cpy); break; case 'v': cpy += p.shift(); cmd = 'L'; points.push(cpx, cpy); break; case 'V': cpy = p.shift(); cmd = 'L'; points.push(cpx, cpy); break; case 'C': points.push(p.shift(), p.shift(), p.shift(), p.shift()); cpx = p.shift(); cpy = p.shift(); points.push(cpx, cpy); break; case 'c': points.push( cpx + p.shift(), cpy + p.shift(), cpx + p.shift(), cpy + p.shift() ); cpx += p.shift(); cpy += p.shift(); cmd = 'C'; points.push(cpx, cpy); break; case 'S': ctlPtx = cpx; ctlPty = cpy; prevCmd = ca[ca.length - 1]; if (prevCmd.command === 'C') { ctlPtx = cpx + (cpx - prevCmd.points[2]); ctlPty = cpy + (cpy - prevCmd.points[3]); } points.push(ctlPtx, ctlPty, p.shift(), p.shift()); cpx = p.shift(); cpy = p.shift(); cmd = 'C'; points.push(cpx, cpy); break; case 's': ctlPtx = cpx, ctlPty = cpy; prevCmd = ca[ca.length - 1]; if (prevCmd.command === 'C') { ctlPtx = cpx + (cpx - prevCmd.points[2]); ctlPty = cpy + (cpy - prevCmd.points[3]); } points.push( ctlPtx, ctlPty, cpx + p.shift(), cpy + p.shift() ); cpx += p.shift(); cpy += p.shift(); cmd = 'C'; points.push(cpx, cpy); break; case 'Q': points.push(p.shift(), p.shift()); cpx = p.shift(); cpy = p.shift(); points.push(cpx, cpy); break; case 'q': points.push(cpx + p.shift(), cpy + p.shift()); cpx += p.shift(); cpy += p.shift(); cmd = 'Q'; points.push(cpx, cpy); break; case 'T': ctlPtx = cpx, ctlPty = cpy; prevCmd = ca[ca.length - 1]; if (prevCmd.command === 'Q') { ctlPtx = cpx + (cpx - prevCmd.points[0]); ctlPty = cpy + (cpy - prevCmd.points[1]); } cpx = p.shift(); cpy = p.shift(); cmd = 'Q'; points.push(ctlPtx, ctlPty, cpx, cpy); break; case 't': ctlPtx = cpx, ctlPty = cpy; prevCmd = ca[ca.length - 1]; if (prevCmd.command === 'Q') { ctlPtx = cpx + (cpx - prevCmd.points[0]); ctlPty = cpy + (cpy - prevCmd.points[1]); } cpx += p.shift(); cpy += p.shift(); cmd = 'Q'; points.push(ctlPtx, ctlPty, cpx, cpy); break; case 'A': rx = p.shift(); ry = p.shift(); psi = p.shift(); fa = p.shift(); fs = p.shift(); x1 = cpx, y1 = cpy; cpx = p.shift(), cpy = p.shift(); cmd = 'A'; points = this._convertPoint( x1, y1, cpx, cpy, fa, fs, rx, ry, psi ); break; case 'a': rx = p.shift(); ry = p.shift(); psi = p.shift(); fa = p.shift(); fs = p.shift(); x1 = cpx, y1 = cpy; cpx += p.shift(); cpy += p.shift(); cmd = 'A'; points = this._convertPoint( x1, y1, cpx, cpy, fa, fs, rx, ry, psi ); break; } ca.push({ command : cmd || c, points : points }); } if (c === 'z' || c === 'Z') { ca.push({ command : 'z', points : [] }); } } return ca; }, _convertPoint : function(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg) { var psi = psiDeg * (Math.PI / 180.0); var xp = Math.cos(psi) * (x1 - x2) / 2.0 + Math.sin(psi) * (y1 - y2) / 2.0; var yp = -1 * Math.sin(psi) * (x1 - x2) / 2.0 + Math.cos(psi) * (y1 - y2) / 2.0; var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry); if (lambda > 1) { rx *= Math.sqrt(lambda); ry *= Math.sqrt(lambda); } var f = Math.sqrt((((rx * rx) * (ry * ry)) - ((rx * rx) * (yp * yp)) - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp) + (ry * ry) * (xp * xp)) ); if (fa === fs) { f *= -1; } if (isNaN(f)) { f = 0; } var cxp = f * rx * yp / ry; var cyp = f * -ry * xp / rx; var cx = (x1 + x2) / 2.0 + Math.cos(psi) * cxp - Math.sin(psi) * cyp; var cy = (y1 + y2) / 2.0 + Math.sin(psi) * cxp + Math.cos(psi) * cyp; var vMag = function(v) { return Math.sqrt(v[0] * v[0] + v[1] * v[1]); }; var vRatio = function(u, v) { return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v)); }; var vAngle = function(u, v) { return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(vRatio(u, v)); }; var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]); var u = [ (xp - cxp) / rx, (yp - cyp) / ry ]; var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ]; var dTheta = vAngle(u, v); if (vRatio(u, v) <= -1) { dTheta = Math.PI; } if (vRatio(u, v) >= 1) { dTheta = 0; } if (fs === 0 && dTheta > 0) { dTheta = dTheta - 2 * Math.PI; } if (fs === 1 && dTheta < 0) { dTheta = dTheta + 2 * Math.PI; } return [ cx, cy, rx, ry, theta, dTheta, psi, fs ]; }, /** * 创建路径 * @param {Context2D} ctx Canvas 2D上下文 * @param {Object} style 样式 */ buildPath : function(ctx, style) { var path = style.path; var pathArray = this._parsePathData(path); // 平移坐标 var x = style.x || 0; var y = style.y || 0; var p; // 记录边界点,用于判断inside var pointList = style.pointList = []; var singlePointList = []; for (var i = 0, l = pathArray.length; i < l; i++) { if (pathArray[i].command.toUpperCase() == 'M') { singlePointList.length > 0 && pointList.push(singlePointList); singlePointList = []; } p = pathArray[i].points; for (var j = 0, k = p.length; j < k; j += 2) { singlePointList.push([p[j] + x, p[j+1] + y]); } } singlePointList.length > 0 && pointList.push(singlePointList); var c; for (var i = 0, l = pathArray.length; i < l; i++) { c = pathArray[i].command; p = pathArray[i].points; // 平移变换 for (var j = 0, k = p.length; j < k; j++) { if (j % 2 === 0) { p[j] += x; } else { p[j] += y; } } switch (c) { case 'L': ctx.lineTo(p[0], p[1]); break; case 'M': ctx.moveTo(p[0], p[1]); break; case 'C': ctx.bezierCurveTo(p[0], p[1], p[2], p[3], p[4], p[5]); break; case 'Q': ctx.quadraticCurveTo(p[0], p[1], p[2], p[3]); break; case 'A': var cx = p[0]; var cy = p[1]; var rx = p[2]; var ry = p[3]; var theta = p[4]; var dTheta = p[5]; var psi = p[6]; var fs = p[7]; var r = (rx > ry) ? rx : ry; var scaleX = (rx > ry) ? 1 : rx / ry; var scaleY = (rx > ry) ? ry / rx : 1; ctx.translate(cx, cy); ctx.rotate(psi); ctx.scale(scaleX, scaleY); ctx.arc(0, 0, r, theta, theta + dTheta, 1 - fs); ctx.scale(1 / scaleX, 1 / scaleY); ctx.rotate(-psi); ctx.translate(-cx, -cy); break; case 'z': ctx.closePath(); break; } } return; }, /** * 返回矩形区域,用于局部刷新和文字定位 * @param {Object} style 样式 */ getRect : function(style) { var lineWidth; if (style.brushType == 'stroke' || style.brushType == 'fill') { lineWidth = style.lineWidth || 1; } else { lineWidth = 0; } var minX = Number.MAX_VALUE; var maxX = Number.MIN_VALUE; var minY = Number.MAX_VALUE; var maxY = Number.MIN_VALUE; // 平移坐标 var x = style.x || 0; var y = style.y || 0; var pathArray = this._parsePathData(style.path); for (var i = 0; i < pathArray.length; i++) { var p = pathArray[i].points; for (var j = 0; j < p.length; j++) { if (j % 2 === 0) { if (p[j] + x < minX) { minX = p[j] + x; } if (p[j] + x > maxX) { maxX = p[j] + x; } } else { if (p[j] + y < minY) { minY = p[j] + y; } if (p[j] + y > maxY) { maxY = p[j] + y; } } } } var rect; if (minX === Number.MAX_VALUE || maxX === Number.MIN_VALUE || minY === Number.MAX_VALUE || maxY === Number.MIN_VALUE ) { rect = { x : 0, y : 0, width : 0, height : 0 }; } else { rect = { x : Math.round(minX - lineWidth / 2), y : Math.round(minY - lineWidth / 2), width : maxX - minX + lineWidth, height : maxY - minY + lineWidth }; } return rect; } }; var base = require('./base'); base.derive(Path); var shape = require('../shape'); shape.define('path', new Path()); return Path; }); /** * zrender * * @author lang( shenyi01@baidu.com ) * * shape类:图片 * 可配图形属性: { // 基础属性 shape : 'image', // 必须,shape类标识,需要显式指定 id : {string}, // 必须,图形唯一标识,可通过zrender实例方法newShapeId生成 zlevel : {number}, // 默认为0,z层level,决定绘画在哪层canvas中 invisible : {boolean}, // 默认为false,是否可见 // 样式属性,默认状态样式样式属性 style : { x : {number}, // 必须,左上角横坐标 y : {number}, // 必须,左上角纵坐标 width : {number}, // 可选,宽度 height : {number}, // 可选,高度 sx : {number}, // 可选, 从图片中裁剪的x sy : {number}, // 可选, 从图片中裁剪的y sWidth : {number}, // 可选, 从图片中裁剪的宽度 sHeight : {number}, // 可选, 从图片中裁剪的高度 image : {string|Image} // 必须,图片url或者图片对象 lineWidth : {number}, // 默认为1,线条宽度,描边下有效 opacity : {number}, // 默认为1,透明度设置,如果color为rgba,则最终透明度效果叠加 shadowBlur : {number}, // 默认为0,阴影模糊度,大于0有效 shadowColor : {color}, // 默认为'#000',阴影色彩,支持rgba shadowOffsetX : {number}, // 默认为0,阴影横向偏移,正值往右,负值往左 shadowOffsetY : {number}, // 默认为0,阴影纵向偏移,正值往下,负值往上 text : {string}, // 默认为null,附加文本 textFont : {string}, // 默认为null,附加文本样式,eg:'bold 18px verdana' textPosition : {string}, // 默认为top,附加文本位置。 // inside | left | right | top | bottom textAlign : {string}, // 默认根据textPosition自动设置,附加文本水平对齐。 // start | end | left | right | center textBaseline : {string}, // 默认根据textPosition自动设置,附加文本垂直对齐。 // top | bottom | middle | // alphabetic | hanging | ideographic textColor : {color}, // 默认根据textPosition自动设置,默认策略如下,附加文本颜色 // 'inside' ? '#fff' : color }, // 样式属性,高亮样式属性,当不存在highlightStyle时使用基于默认样式扩展显示 highlightStyle : { // 同style } // 交互属性,详见shape.Base // 事件属性,详见shape.Base } 例子: { shape : 'image', id : '123456', zlevel : 1, style : { x : 200, y : 100, width : 150, height : 50, image : 'tests.jpg', text : 'Baidu' }, myName : 'kener', // 可自带任何有效自定义属性 clickable : true, onClick : function(eventPacket) { alert(eventPacket.target.myName); } } */ define( 'zrender/shape/image',['require','./base','../shape'],function(require) { var _cache = {}; var _needsRefresh = []; var _refreshTimeout; function ZImage() { this.type = 'image'; } ZImage.prototype = { brush : function(ctx, e, isHighlight, refresh) { var style = e.style || {}; if (isHighlight) { // 根据style扩展默认高亮样式 style = this.getHighlightStyle( style, e.highlightStyle || {} ); } var image = style.image; if (typeof(image) === 'string') { var src = image; if (_cache[src]) { image = _cache[src]; } else { image = document.createElement('image');//new Image(); image.onload = function(){ image.onload = null; clearTimeout( _refreshTimeout ); _needsRefresh.push( e ); // 防止因为缓存短时间内触发多次onload事件 _refreshTimeout = setTimeout(function(){ refresh( _needsRefresh ); // 清空needsRefresh _needsRefresh = []; }, 10); }; _cache[ src ] = image; image.src = src; } } if (image) { //图片已经加载完成 if (window.ActiveXObject) { if (image.readyState != 'complete') { return; } } else { if (!image.complete) { return; } } ctx.save(); this.setContext(ctx, style); // 设置transform if (e.__needTransform) { ctx.transform.apply(ctx,this.updateTransform(e)); } var width = style.width || image.width; var height = style.height || image.height; var x = style.x; var y = style.y; if (style.sWidth && style.sHeight) { var sx = style.sx || 0; var sy = style.sy || 0; ctx.drawImage( image, sx, sy, style.sWidth, style.sHeight, x, y, width, height ); } else if (style.sx && style.sy) { var sx = style.sx; var sy = style.sy; var sWidth = width - sx; var sHeight = height - sy; ctx.drawImage( image, sx, sy, sWidth, sHeight, x, y, width, height ); } else { ctx.drawImage(image, x, y, width, height); } // 如果没设置宽和高的话自动根据图片宽高设置 style.width = width; style.height = height; e.style.width = width; e.style.height = height; if (style.text) { this.drawText(ctx, style, e.style); } ctx.restore(); } return; }, /** * 创建路径,用于判断hover时调用isPointInPath~ * @param {Context2D} ctx Canvas 2D上下文 * @param {Object} style 样式 */ buildPath : function(ctx, style) { ctx.rect(style.x, style.y, style.width, style.height); return; }, /** * 返回矩形区域,用于局部刷新和文字定位 * @param {Object} style */ getRect : function(style) { return { x : style.x, y : style.y, width : style.width, height : style.height }; } }; var base = require('./base'); base.derive(ZImage); var shape = require('../shape'); shape.define('image', new ZImage()); return ZImage; } ); /** * zrender * * @author Neil (杨骥, yangji01@baidu.com) * * shape类:贝塞尔曲线 * 可配图形属性: { // 基础属性 shape : 'beziercurve', // 必须,shape类标识,需要显式指定 id : {string}, // 必须,图形唯一标识,可通过zrender实例方法newShapeId生成 zlevel : {number}, // 默认为0,z层level,决定绘画在哪层canvas中 invisible : {boolean}, // 默认为false,是否可见 // 样式属性,默认状态样式样式属性 style : { xStart : {number}, // 必须,起点横坐标 yStart : {number}, // 必须,起点纵坐标 cpX1 : {number}, // 必须,第一个关联点横坐标 cpY1 : {number}, // 必须,第一个关联点纵坐标 cpX2 : {number}, // 可选,第二个关联点横坐标 缺省即为二次贝塞尔曲线 cpY2 : {number}, // 可选,第二个关联点纵坐标 xEnd : {number}, // 必须,终点横坐标 yEnd : {number}, // 必须,终点纵坐标 strokeColor : {color}, // 默认为'#000',线条颜色(轮廓),支持rgba lineWidth : {number}, // 默认为1,线条宽度 lineCap : {string}, // 默认为butt,线帽样式。butt | round | square opacity : {number}, // 默认为1,透明度设置,如果color为rgba,则最终透明度效果叠加 shadowBlur : {number}, // 默认为0,阴影模糊度,大于0有效 shadowColor : {color}, // 默认为'#000',阴影色彩,支持rgba shadowOffsetX : {number}, // 默认为0,阴影横向偏移,正值往右,负值往左 shadowOffsetY : {number}, // 默认为0,阴影纵向偏移,正值往下,负值往上 text : {string}, // 默认为null,附加文本 textFont : {string}, // 默认为null,附加文本样式,eg:'bold 18px verdana' textPosition : {string}, // 默认为end,附加文本位置。 // inside | start | end textAlign : {string}, // 默认根据textPosition自动设置,附加文本水平对齐。 // start | end | left | right | center textBaseline : {string}, // 默认根据textPosition自动设置,附加文本垂直对齐。 // top | bottom | middle | // alphabetic | hanging | ideographic textColor : {color}, // 默认根据textPosition自动设置,默认策略如下,附加文本颜色 // 'inside' ? '#000' : color }, // 样式属性,高亮样式属性,当不存在highlightStyle时使用基于默认样式扩展显示 highlightStyle : { // 同style } // 交互属性,详见shape.Base // 事件属性,详见shape.Base } 例子: { shape : 'beziercurve', id : '123456', zlevel : 1, style : { xStart : 100, yStart : 100, xEnd : 200, yEnd : 200, strokeColor : '#eee', lineWidth : 20, text : 'Baidu' }, myName : 'kener', //可自带任何有效自定义属性 clickable : true, onClick : function(eventPacket) { alert(eventPacket.target.myName); } } */ define( 'zrender/shape/beziercurve',['require','./base','../shape'],function(require) { function Beziercurve() { this.type = 'beziercurve'; this.brushTypeOnly = 'stroke'; //线条只能描边,填充后果自负 this.textPosition = 'end'; } Beziercurve.prototype = { /** * 创建线条路径 * @param {Context2D} ctx Canvas 2D上下文 * @param {Object} style 样式 */ buildPath : function(ctx, style) { ctx.moveTo(style.xStart, style.yStart); if (typeof style.cpX2 != 'undefined' && typeof style.cpY2 != 'undefined' ) { ctx.bezierCurveTo( style.cpX1, style.cpY1, style.cpX2, style.cpY2, style.xEnd, style.yEnd ); } else { ctx.quadraticCurveTo( style.cpX1, style.cpY1, style.xEnd, style.yEnd ); } }, /** * 返回矩形区域,用于局部刷新和文字定位 * @param {Object} style */ getRect : function(style) { var _minX = Math.min(style.xStart, style.xEnd, style.cpX1); var _minY = Math.min(style.yStart, style.yEnd, style.cpY1); var _maxX = Math.max(style.xStart, style.xEnd, style.cpX1); var _maxY = Math.max(style.yStart, style.yEnd, style.cpY1); var _x2 = style.cpX2; var _y2 = style.cpY2; if (typeof _x2 != 'undefined' && typeof _y2 != 'undefined' ) { _minX = Math.min(_minX, _x2); _minY = Math.min(_minY, _y2); _maxX = Math.max(_maxX, _x2); _maxY = Math.max(_maxY, _y2); } var lineWidth = style.lineWidth || 1; return { x : _minX - lineWidth, y : _minY - lineWidth, width : _maxX - _minX + lineWidth, height : _maxY - _minY + lineWidth }; } }; var base = require('./base'); base.derive(Beziercurve); var shape = require('../shape'); shape.define('beziercurve', new Beziercurve()); return Beziercurve; } ); /** * zrender * * @author sushuang (宿爽, sushuang@baidu.com) * * shape类:n角星(n>3) * 可配图形属性: { // 基础属性 shape : 'star', // 必须,shape类标识,需要显式指定 id : {string}, // 必须,图形唯一标识,可通过zrender实例方法newShapeId生成 zlevel : {number}, // 默认为0,z层level,决定绘画在哪层canvas中 invisible : {boolean}, // 默认为false,是否可见 // 样式属性,默认状态样式样式属性 style : { x : {number}, // 必须,n角星外接圆心横坐标 y : {number}, // 必须,n角星外接圆心纵坐标 r : {number}, // 必须,n角星外接圆半径 r0 : {number}, // n角星内部顶点(凹点)的外接圆半径, // 如果不指定此参数,则自动计算:取相隔外部顶点连线的交点作内部顶点 n : {number}, // 必须,指明几角星 brushType : {string}, // 默认为fill,绘画方式 // fill(填充) | stroke(描边) | both(填充+描边) color : {color}, // 默认为'#000',填充颜色,支持rgba strokeColor : {color}, // 默认为'#000',描边颜色(轮廓),支持rgba lineWidth : {number}, // 默认为1,线条宽度,描边下有效 lineJoin : {string}, // 默认为miter,线段连接样式。miter | round | bevel shadowBlur : {number}, // 默认为0,阴影模糊度,大于0有效 shadowColor : {color}, // 默认为'#000',阴影色彩,支持rgba shadowOffsetX : {number}, // 默认为0,阴影横向偏移,正值往右,负值往左 shadowOffsetY : {number}, // 默认为0,阴影横向偏移,正值往右,负值往左 text : {string}, // 默认为null,附加文本 textFont : {string}, // 默认为null,附加文本样式,eg:'bold 18px verdana' textPosition : {string}, // 默认为outside,附加文本位置。 // outside | inside textAlign : {string}, // 默认根据textPosition自动设置,附加文本水平对齐。 // start | end | left | right | center textBaseline : {string}, // 默认根据textPosition自动设置,附加文本垂直对齐。 // top | bottom | middle | // alphabetic | hanging | ideographic textColor : {color}, // 默认根据textPosition自动设置,默认策略如下,附加文本颜色 // 'inside' ? '#fff' : color }, // 样式属性,高亮样式属性,当不存在highlightStyle时使用基于默认样式扩展显示 highlightStyle : { // 同style } // 交互属性,详见shape.Base // 事件属性,详见shape.Base } 例子: { shape : 'star', id : '123456', zlevel : 1, style : { x : 200, y : 100, r : 150, n : 5, color : '#eee' }, myName : 'kener', // 可自带任何有效自定义属性 clickable : true, onClick : function(eventPacket) { alert(eventPacket.target.myName); } } */ define( 'zrender/shape/star',['require','../tool/math','./base','../shape'],function(require) { var math = require('../tool/math'); var sin = math.sin; var cos = math.cos; var PI = Math.PI; function Star() { this.type = 'heart'; } Star.prototype = { /** * 创建n角星(n>3)路径 * @param {Context2D} ctx Canvas 2D上下文 * @param {Object} style 样式 */ buildPath : function(ctx, style) { var n = style.n; if (!n || n < 2) { return; } var x = style.x; var y = style.y; var r = style.r; var r0 = style.r0; // 如果未指定内部顶点外接圆半径,则自动计算 if (r0 == null) { r0 = n > 4 // 相隔的外部顶点的连线的交点, // 被取为内部交点,以此计算r0 ? r * cos(2 * PI / n) / cos(PI / n) // 二三四角星的特殊处理 : r / 3; } var dStep = PI / n; var deg = -PI / 2; var xStart = x + r * cos(deg); var yStart = y + r * sin(deg); deg += dStep; // 记录边界点,用于判断inside var pointList = style.pointList = []; pointList.push([xStart, yStart]); for (var i = 0, end = n * 2 - 1, ri; i < end; i ++) { ri = i % 2 === 0 ? r0 : r; pointList.push([x + ri * cos(deg), y + ri * sin(deg)]); deg += dStep; } pointList.push([xStart, yStart]); // 绘制 ctx.moveTo(pointList[0][0], pointList[0][1]); for (var i = 0; i < pointList.length; i ++) { ctx.lineTo(pointList[i][0], pointList[i][1]); } return; }, /** * 返回矩形区域,用于局部刷新和文字定位 * @param {Object} style */ getRect : function(style) { var lineWidth; if (style.brushType == 'stroke' || style.brushType == 'fill') { lineWidth = style.lineWidth || 1; } else { lineWidth = 0; } return { x : Math.round(style.x - style.r - lineWidth / 2), y : Math.round(style.y - style.r - lineWidth / 2), width : style.r * 2 + lineWidth, height : style.r * 2 + lineWidth }; } }; var base = require('./base'); base.derive(Star); var shape = require('../shape'); shape.define('star', new Star()); return Star; } ); /** * zrender * * @author sushuang (宿爽, sushuang@baidu.com) * * shape类:正n边形(n>=3) * 可配图形属性: { // 基础属性 shape : 'isogon', // 必须,shape类标识,需要显式指定 id : {string}, // 必须,图形唯一标识,可通过zrender实例方法newShapeId生成 zlevel : {number}, // 默认为0,z层level,决定绘画在哪层canvas中 invisible : {boolean}, // 默认为false,是否可见 // 样式属性,默认状态样式样式属性 style : { x : {number}, // 必须,正n边形外接圆心横坐标 y : {number}, // 必须,正n边形外接圆心纵坐标 r : {number}, // 必须,正n边形外接圆半径 n : {number}, // 必须,指明正几边形 brushType : {string}, // 默认为fill,绘画方式 // fill(填充) | stroke(描边) | both(填充+描边) color : {color}, // 默认为'#000',填充颜色,支持rgba strokeColor : {color}, // 默认为'#000',描边颜色(轮廓),支持rgba lineWidth : {number}, // 默认为1,线条宽度,描边下有效 lineJoin : {string}, // 默认为miter,线段连接样式。miter | round | bevel shadowBlur : {number}, // 默认为0,阴影模糊度,大于0有效 shadowColor : {color}, // 默认为'#000',阴影色彩,支持rgba shadowOffsetX : {number}, // 默认为0,阴影横向偏移,正值往右,负值往左 shadowOffsetY : {number}, // 默认为0,阴影横向偏移,正值往右,负值往左 text : {string}, // 默认为null,附加文本 textFont : {string}, // 默认为null,附加文本样式,eg:'bold 18px verdana' textPosition : {string}, // 默认为outside,附加文本位置。 // outside | inside textAlign : {string}, // 默认根据textPosition自动设置,附加文本水平对齐。 // start | end | left | right | center textBaseline : {string}, // 默认根据textPosition自动设置,附加文本垂直对齐。 // top | bottom | middle | // alphabetic | hanging | ideographic textColor : {color}, // 默认根据textPosition自动设置,默认策略如下,附加文本颜色 // 'inside' ? '#fff' : color }, // 样式属性,高亮样式属性,当不存在highlightStyle时使用基于默认样式扩展显示 highlightStyle : { // 同style } // 交互属性,详见shape.Base // 事件属性,详见shape.Base } 例子: { shape : 'isogon', id : '123456', zlevel : 1, style : { x : 400, y : 100, r : 150, n : 7, color : '#eee' }, myName : 'kener', // 可自带任何有效自定义属性 clickable : true, onClick : function(eventPacket) { alert(eventPacket.target.myName); } } */ define( 'zrender/shape/isogon',['require','../tool/math','./base','../shape'],function(require) { var math = require('../tool/math'); var sin = math.sin; var cos = math.cos; var PI = Math.PI; function Isogon() { this.type = 'isogon'; } Isogon.prototype = { /** * 创建n角星(n>=3)路径 * @param {Context2D} ctx Canvas 2D上下文 * @param {Object} style 样式 */ buildPath : function(ctx, style) { var n = style.n; if (!n || n < 2) { return; } var x = style.x; var y = style.y; var r = style.r; var dStep = 2 * PI / n; var deg = -PI / 2; var xStart = x + r * cos(deg); var yStart = y + r * sin(deg); deg += dStep; // 记录边界点,用于判断insight var pointList = style.pointList = []; pointList.push([xStart, yStart]); for (var i = 0, end = n - 1; i < end; i ++) { pointList.push([x + r * cos(deg), y + r * sin(deg)]); deg += dStep; } pointList.push([xStart, yStart]); // 绘制 ctx.moveTo(pointList[0][0], pointList[0][1]); for (var i = 0; i < pointList.length; i ++) { ctx.lineTo(pointList[i][0], pointList[i][1]); } return; }, /** * 返回矩形区域,用于局部刷新和文字定位 * @param {Object} style */ getRect : function(style) { var lineWidth; if (style.brushType == 'stroke' || style.brushType == 'fill') { lineWidth = style.lineWidth || 1; } else { lineWidth = 0; } return { x : Math.round(style.x - style.r - lineWidth / 2), y : Math.round(style.y - style.r - lineWidth / 2), width : style.r * 2 + lineWidth, height : style.r * 2 + lineWidth }; } }; var base = require('./base'); base.derive(Isogon); var shape = require('../shape'); shape.define('isogon', new Isogon()); return Isogon; } ); /** * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js * author: lang(shenyi01@baidu.com) */ define( 'zrender/animation/easing',[],function() { var Easing = { // 线性 Linear: function(k) { return k; }, // 二次方的缓动(t^2) QuadraticIn: function(k) { return k * k; }, QuadraticOut: function(k) { return k * (2 - k); }, QuadraticInOut: function(k) { if ((k *= 2) < 1) { return 0.5 * k * k; } return - 0.5 * (--k * (k - 2) - 1); }, // 三次方的缓动(t^3) CubicIn: function(k) { return k * k * k; }, CubicOut: function(k) { return --k * k * k + 1; }, CubicInOut: function(k) { if ((k *= 2) < 1) { return 0.5 * k * k * k; } return 0.5 * ((k -= 2) * k * k + 2); }, // 四次方的缓动(t^4) QuarticIn: function(k) { return k * k * k * k; }, QuarticOut: function(k) { return 1 - (--k * k * k * k); }, QuarticInOut: function(k) { if ((k *= 2) < 1) { return 0.5 * k * k * k * k; } return - 0.5 * ((k -= 2) * k * k * k - 2); }, // 五次方的缓动(t^5) QuinticIn: function(k) { return k * k * k * k * k; }, QuinticOut: function(k) { return --k * k * k * k * k + 1; }, QuinticInOut: function(k) { if ((k *= 2) < 1) { return 0.5 * k * k * k * k * k; } return 0.5 * ((k -= 2) * k * k * k * k + 2); }, // 正弦曲线的缓动(sin(t)) SinusoidalIn: function(k) { return 1 - Math.cos(k * Math.PI / 2); }, SinusoidalOut: function(k) { return Math.sin(k * Math.PI / 2); }, SinusoidalInOut: function(k) { return 0.5 * (1 - Math.cos(Math.PI * k)); }, // 指数曲线的缓动(2^t) ExponentialIn: function(k) { return k === 0 ? 0 : Math.pow(1024, k - 1); }, ExponentialOut: function(k) { return k === 1 ? 1 : 1 - Math.pow(2, - 10 * k); }, ExponentialInOut: function(k) { if (k === 0) { return 0; } if (k === 1) { return 1; } if ((k *= 2) < 1) { return 0.5 * Math.pow(1024, k - 1); } return 0.5 * (- Math.pow(2, - 10 * (k - 1)) + 2); }, // 圆形曲线的缓动(sqrt(1-t^2)) CircularIn: function(k) { return 1 - Math.sqrt(1 - k * k); }, CircularOut: function(k) { return Math.sqrt(1 - (--k * k)); }, CircularInOut: function(k) { if ((k *= 2) < 1) { return - 0.5 * (Math.sqrt(1 - k * k) - 1); } return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1); }, // 创建类似于弹簧在停止前来回振荡的动画 ElasticIn: function(k) { var s, a = 0.1, p = 0.4; if (k === 0) { return 0; } if (k === 1) { return 1; } if (!a || a < 1) { a = 1; s = p / 4; }else{ s = p * Math.asin(1 / a) / (2 * Math.PI); } return - (a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p)); }, ElasticOut: function(k) { var s, a = 0.1, p = 0.4; if (k === 0) { return 0; } if (k === 1) { return 1; } if (!a || a < 1) { a = 1; s = p / 4; } else{ s = p * Math.asin(1 / a) / (2 * Math.PI); } return (a * Math.pow(2, - 10 * k) * Math.sin((k - s) * (2 * Math.PI) / p) + 1); }, ElasticInOut: function(k) { var s, a = 0.1, p = 0.4; if (k === 0) { return 0; } if (k === 1) { return 1; } if (!a || a < 1) { a = 1; s = p / 4; } else{ s = p * Math.asin(1 / a) / (2 * Math.PI); } if ((k *= 2) < 1) { return - 0.5 * (a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p)); } return a * Math.pow(2, -10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1; }, // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动 BackIn: function(k) { var s = 1.70158; return k * k * ((s + 1) * k - s); }, BackOut: function(k) { var s = 1.70158; return --k * k * ((s + 1) * k + s) + 1; }, BackInOut: function(k) { var s = 1.70158 * 1.525; if ((k *= 2) < 1) { return 0.5 * (k * k * ((s + 1) * k - s)); } return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2); }, // 创建弹跳效果 BounceIn: function(k) { return 1 - Easing.BounceOut(1 - k); }, BounceOut: function(k) { if (k < (1 / 2.75)) { return 7.5625 * k * k; } else if (k < (2 / 2.75)) { return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75; } else if (k < (2.5 / 2.75)) { return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375; } else { return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375; } }, BounceInOut: function(k) { if (k < 0.5) { return Easing.BounceIn(k * 2) * 0.5; } return Easing.BounceOut(k * 2 - 1) * 0.5 + 0.5; } }; return Easing; } ); /** * 动画主控制器 * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件 * @config life(1000) 动画时长 * @config delay(0) 动画延迟时间 * @config loop(true) * @config gap(0) 循环的间隔时间 * @config onframe * @config easing(optional) * @config ondestroy(optional) * @config onrestart(optional) */ define( 'zrender/animation/controller',['require','./easing'],function(require) { var Easing = require('./easing'); var Controller = function(options) { this._targetPool = options.target || {}; if (this._targetPool.constructor != Array) { this._targetPool = [this._targetPool]; } //生命周期 this._life = options.life || 1000; //延时 this._delay = options.delay || 0; //开始时间 this._startTime = new Date().getTime() + this._delay;//单位毫秒 //结束时间 this._endTime = this._startTime + this._life*1000; //是否循环 this.loop = typeof(options.loop) == 'undefined' ? false : options.loop; this.gap = options.gap || 0; this.easing = options.easing || 'Linear'; this.onframe = options.onframe || null; this.ondestroy = options.ondestroy || null; this.onrestart = options.onrestart || null; }; Controller.prototype = { step : function(time) { var percent = (time - this._startTime) / this._life; //还没开始 if (percent < 0) { return; } percent = Math.min(percent, 1); var easingFunc = typeof(this.easing) == 'string' ? Easing[this.easing] : this.easing; var schedule; if (typeof easingFunc === 'function') { schedule = easingFunc(percent); }else{ schedule = percent; } this.fire('frame', schedule); //结束 if (percent == 1) { if (this.loop) { this.restart(); // 重新开始周期 // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件 return 'restart'; }else{ // 动画完成将这个控制器标识为待删除 // 在Animation.update中进行批量删除 this._needsRemove = true; return 'destroy'; } }else{ return null; } }, restart : function() { this._startTime = new Date().getTime() + this.gap; }, fire : function(eventType, arg) { for(var i = 0, len = this._targetPool.length; i < len; i++) { if (this['on' + eventType]) { this['on' + eventType](this._targetPool[i], arg); } } } }; Controller.prototype.constructor = Controller; return Controller; } ); /** * 动画主类, 调度和管理所有动画控制器 * * @author lang(shenyi01@baidu.com) * * @class : Animation * @config : stage(optional) 绘制类, 需要提供update接口 * @config : fps(optional) 帧率, 是自动更新动画的时候需要提供 * @config : onframe(optional) * @method : add * @method : remove * @method : update * @method : start * @method : stop */ define( 'zrender/animation/animation',['require','./controller','../tool/util'],function(require) { var Controller = require('./controller'); var util = require('../tool/util'); // Polyfill of requestAnimationFrame var requrestAnimationFrame = window.requrestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || function(callback) { window.setTimeout( callback, 1000 / 60 ); }; var Animation = function(options) { options = options || {}; this.stage = options.stage || {}; this.onframe = options.onframe || function() {}; // private properties this._controllerPool = []; this._running = false; }; Animation.prototype = { add : function(controller) { this._controllerPool.push(controller); }, remove : function(controller) { var idx = util.indexOf(this._controllerPool, controller); if (idx >= 0) { this._controllerPool.splice(idx, 1); } }, update : function() { var time = new Date().getTime(); var cp = this._controllerPool; var len = cp.length; var deferredEvents = []; var deferredCtls = []; for (var i = 0; i < len; i++) { var controller = cp[i]; var e = controller.step(time); // 需要在stage.update之后调用的事件,例如destroy if (e) { deferredEvents.push(e); deferredCtls.push(controller); } } if (this.stage && this.stage.update && this._controllerPool.length ) { this.stage.update(); } // 删除动画完成的控制器 var newArray = []; for (var i = 0; i < len; i++) { if (!cp[i]._needsRemove) { newArray.push(cp[i]); cp[i]._needsRemove = false; } } this._controllerPool = newArray; len = deferredEvents.length; for (var i = 0; i < len; i++) { deferredCtls[i].fire(deferredEvents[i]); } this.onframe(); }, // 启用start函数之后每个1000/fps事件就会刷新 // 也可以不使用animation的start函数 // 手动每一帧去调用update函数更新状态 start : function() { var self = this; this._running = true; function step() { if (self._running) { self.update(); requrestAnimationFrame(step); } } requrestAnimationFrame(step); }, stop : function() { this._running = false; }, clear : function() { this._controllerPool = []; }, animate : function(target, loop, getter, setter) { var deferred = new Deferred(target, loop, getter, setter); deferred.animation = this; return deferred; } }; Animation.prototype.constructor = Animation; function _defaultGetter(target, key) { return target[key]; } function _defaultSetter(target, key, value) { target[key] = value; } // 递归做插值 // TODO 对象的插值 function _interpolate( prevValue, nextValue, percent, target, propName, getter, setter ) { // 遍历数组做插值 if (prevValue instanceof Array && nextValue instanceof Array ) { var minLen = Math.min(prevValue.length, nextValue.length); var largerArray; var maxLen; var result = []; if (minLen === prevValue.length) { maxLen = nextValue.length; largerArray = nextValue; }else{ maxLen = prevValue.length; largerArray = prevValue.length; } for (var i = 0; i < minLen; i++) { // target[propName] 作为新的target, // i 作为新的propName递归进行插值 result.push(_interpolate( prevValue[i], nextValue[i], percent, getter(target, propName), i, getter, setter )); } // 赋值剩下不需要插值的数组项 for (var i = minLen; i < maxLen; i++) { result.push(largerArray[i]); } setter(target, propName, result); } else{ prevValue = parseFloat(prevValue); nextValue = parseFloat(nextValue); if (!isNaN(prevValue) && !isNaN(nextValue)) { var value = (nextValue-prevValue) * percent+prevValue; setter(target, propName, value); return value; } } } function Deferred(target, loop, getter, setter) { this._tracks = {}; this._target = target; this._loop = loop || false; this._getter = getter || _defaultGetter; this._setter = setter || _defaultSetter; this._controllerCount = 0; this._delay = 0; this._doneList = []; this._onframeList = []; this._controllerList = []; } Deferred.prototype = { when : function(time /* ms */, props, easing) { for (var propName in props) { if (! this._tracks[propName]) { this._tracks[propName] = []; // 初始状态 this._tracks[propName].push({ time : 0, value : this._getter(this._target, propName) }); } this._tracks[propName].push({ time : time, value : props[propName], easing : easing }); } return this; }, during : function(callback) { this._onframeList.push(callback); return this; }, start : function() { var self = this; var delay; var track; var trackMaxTime; function createOnframe(now, next, propName) { // 复制出新的数组,不然动画的时候改变数组的值也会影响到插值 var prevValue = clone(now.value); var nextValue = clone(next.value); return function(target, schedule) { _interpolate( prevValue, nextValue, schedule, target, propName, self._getter, self._setter ); for (var i = 0; i < self._onframeList.length; i++) { self._onframeList[i](target, schedule); } }; } function ondestroy() { self._controllerCount--; if (self._controllerCount === 0) { var len = self._doneList.length; // 所有动画完成 for (var i = 0; i < len; i++) { self._doneList[i].call(self); } } } for (var propName in this._tracks) { delay = this._delay; track = this._tracks[propName]; if (track.length) { trackMaxTime = track[track.length-1].time; }else{ continue; } for (var i = 0; i < track.length-1; i++) { var now = track[i], next = track[i+1]; var controller = new Controller({ target : self._target, life : next.time - now.time, delay : delay, loop : self._loop, gap : trackMaxTime - (next.time - now.time), easing : next.easing, onframe : createOnframe(now, next, propName), ondestroy : ondestroy }); this._controllerList.push(controller); this._controllerCount++; delay = next.time + this._delay; self.animation.add(controller); } } return this; }, stop : function() { for (var i = 0; i < this._controllerList.length; i++) { var controller = this._controllerList[i]; this.animation.remove(controller); } }, delay : function(time) { this._delay = time; return this; }, done : function(func) { this._doneList.push(func); return this; } }; function clone(value) { if (value && value instanceof Array) { return Array.prototype.slice.call(value); } else { return value; } } return Animation; } ); /** * zrender: config默认配置项 * * @desc zrender是一个轻量级的Canvas类库,MVC封装,数据驱动,提供类Dom事件模型。 * @author Kener (@Kener-林峰, linzhifeng@baidu.com) * */ define( 'zrender/config',{ loadingEffect : 'spin', // 默认loading特效 EVENT : { // 支持事件列表 RESIZE : 'resize', // 窗口大小变化 CLICK : 'click', // 鼠标按钮被(手指)按下,事件对象是:目标图形元素或空 MOUSEWHEEL : 'mousewheel', // 鼠标滚轮变化,事件对象是:目标图形元素或空 MOUSEMOVE : 'mousemove', // 鼠标(手指)被移动,事件对象是:目标图形元素或空 MOUSEOVER : 'mouseover', // 鼠标移到某图形元素之上,事件对象是:目标图形元素 MOUSEOUT : 'mouseout', // 鼠标从某图形元素移开,事件对象是:目标图形元素 MOUSEDOWN : 'mousedown', // 鼠标按钮(手指)被按下,事件对象是:目标图形元素或空 MOUSEUP : 'mouseup', // 鼠标按键(手指)被松开,事件对象是:目标图形元素或空 // GLOBALOUT : 'globalout', // 全局离开,MOUSEOUT触发比较频繁,一次离开优化绑定 // 一次成功元素拖拽的行为事件过程是: // dragstart > dragenter > dragover [> dragleave] > drop > dragend DRAGSTART : 'dragstart', // 开始拖拽时触发,事件对象是:被拖拽图形元素 DRAGEND : 'dragend', // 拖拽完毕时触发(在drop之后触发),事件对象是:被拖拽图形元素 DRAGENTER : 'dragenter', // 拖拽图形元素进入目标图形元素时触发,事件对象是:目标图形元素 DRAGOVER : 'dragover', // 拖拽图形元素在目标图形元素上移动时触发,事件对象是:目标图形元素 DRAGLEAVE : 'dragleave', // 拖拽图形元素离开目标图形元素时触发,事件对象是:目标图形元素 DROP : 'drop', // 拖拽图形元素放在目标图形元素内时触发,事件对象是:目标图形元素 touchClickDelay : 300 // touch end - start < delay is click } } ); /** * zrender: loading特效 * * @author Kener (@Kener-林峰, linzhifeng@baidu.com) * * 扩展loading effect: * getBackgroundShape:获取背景图形 * getTextShape:获取文字 * define : 定义效果 * * 内置效果 * bar:进度条 * whirling:旋转水滴 * dynamicLine:动态线条 * bubble:气泡 */ define( 'zrender/tool/loadingEffect',['require','./util','./color','./color','./color','./color','./color','./math'],function(require) { var util = require('./util'); var self; var _defaultText = 'Loading...'; var _defaultTextFont = 'normal 16px Arial'; var _width; var _height; function define(name, fun) { self[name] = fun; } /** * 获取loading文字图形 * @param {Object} textStyle 文字style,同shape/text.style */ function getTextShape(textStyle) { return { shape : 'text', highlightStyle : util.merge( { x : _width / 2, y : _height / 2, text : _defaultText, textAlign : 'center', textBaseline : 'middle', textFont : _defaultTextFont, color: '#333', brushType : 'fill' }, textStyle, {'overwrite': true, 'recursive': true} ) }; } /** * 获取loading背景图形 * @param {color} color 背景颜色 */ function getBackgroundShape (color) { return { shape : 'rectangle', highlightStyle : { x : 0, y : 0, width : _width, height : _height, brushType : 'fill', color : color } }; } // 调整值区间 function _adjust(value, region) { if (value <= region[0]) { value = region[0]; } else if (value >= region[1]) { value = region[1]; } return value; } /** * 进度条 * @param {Object} loadingOption * @param {Object} addShapeHandle * @param {Object} refreshHandle */ function bar(loadingOption, addShapeHandle, refreshHandle) { var zrColor = require('./color'); // 特效默认配置 loadingOption = util.merge( loadingOption, { textStyle : { color : '#888' }, backgroundColor : 'rgba(250, 250, 250, 0.8)', effectOption : { x : 0, y : _height / 2 - 30, width : _width, height : 5, brushType : 'fill', timeInterval : 100 } }, {'overwrite': false, 'recursive': true} ); var textShape = getTextShape(loadingOption.textStyle); var background = getBackgroundShape(loadingOption.backgroundColor); var effectOption = loadingOption.effectOption; // 初始化动画元素 var barShape = { shape : 'rectangle', highlightStyle : util.clone(effectOption) }; barShape.highlightStyle.color = effectOption.color || zrColor.getLinearGradient( effectOption.x, effectOption.y, effectOption.x + effectOption.width, effectOption.y + effectOption.height, [[0, '#ff6400'], [0.5, '#ffe100'], [1, '#b1ff00']] ); if (typeof loadingOption.progress != 'undefined') { // 指定进度 addShapeHandle(background); barShape.highlightStyle.width = _adjust(loadingOption.progress, [0,1]) * loadingOption.effectOption.width; addShapeHandle(barShape); addShapeHandle(textShape); refreshHandle(); return; } else { // 循环显示 barShape.highlightStyle.width = 0; return setInterval( function() { addShapeHandle(background); if (barShape.highlightStyle.width < loadingOption.effectOption.width ) { barShape.highlightStyle.width += 8; } else { barShape.highlightStyle.width = 0; } addShapeHandle(barShape); addShapeHandle(textShape); refreshHandle(); }, effectOption.timeInterval ); } } /** * 旋转水滴 * @param {Object} loadingOption * @param {Object} addShapeHandle * @param {Object} refreshHandle */ function whirling(loadingOption, addShapeHandle, refreshHandle) { // 特效默认配置 loadingOption.effectOption = util.merge( loadingOption.effectOption || {}, { x : _width / 2 - 80, y : _height / 2, r : 18, colorIn : '#fff', colorOut : '#555', colorWhirl : '#6cf', timeInterval : 50 } ); var effectOption = loadingOption.effectOption; loadingOption = util.merge( loadingOption, { textStyle : { color : '#888', x : effectOption.x + effectOption.r + 10, y : effectOption.y, textAlign : 'start' }, backgroundColor : 'rgba(250, 250, 250, 0.8)' }, {'overwrite': false, 'recursive': true} ); var textShape = getTextShape(loadingOption.textStyle); var background = getBackgroundShape(loadingOption.backgroundColor); // 初始化动画元素 var droplet = { shape : 'droplet', highlightStyle : { a : Math.round(effectOption.r / 2), b : Math.round(effectOption.r - effectOption.r / 6), brushType : 'fill', color : effectOption.colorWhirl } }; var circleIn = { shape : 'circle', highlightStyle : { r : Math.round(effectOption.r / 6), brushType : 'fill', color : effectOption.colorIn } }; var circleOut = { shape : 'ring', highlightStyle : { r0 : Math.round(effectOption.r - effectOption.r / 3), r : effectOption.r, brushType : 'fill', color : effectOption.colorOut } }; var pos = [0, effectOption.x, effectOption.y]; droplet.highlightStyle.x = circleIn.highlightStyle.x = circleOut.highlightStyle.x = pos[1]; droplet.highlightStyle.y = circleIn.highlightStyle.y = circleOut.highlightStyle.y = pos[2]; return setInterval( function() { addShapeHandle(background); addShapeHandle(circleOut); pos[0] -= 0.3; droplet.rotation = pos; addShapeHandle(droplet); addShapeHandle(circleIn); addShapeHandle(textShape); refreshHandle(); }, effectOption.timeInterval ); } /** * 动态线 * @param {Object} loadingOption * @param {Object} addShapeHandle * @param {Object} refreshHandle */ function dynamicLine(loadingOption, addShapeHandle, refreshHandle) { var zrColor = require('./color'); // 特效默认配置 loadingOption = util.merge( loadingOption, { textStyle : { color : '#fff' }, backgroundColor : 'rgba(0, 0, 0, 0.8)', effectOption : { n : 30, lineWidth : 1, color : 'random', timeInterval : 100 } }, {'overwrite': false, 'recursive': true} ); var textShape = getTextShape(loadingOption.textStyle); var background = getBackgroundShape(loadingOption.backgroundColor); var effectOption = loadingOption.effectOption; var n = effectOption.n; var lineWidth = effectOption.lineWidth; var shapeList = []; var pos; var len; var xStart; var color; // 初始化动画元素 for(var i = 0; i < n; i++) { xStart = -Math.ceil(Math.random() * 1000); len = Math.ceil(Math.random() * 400); pos = Math.ceil(Math.random() * _height); if (effectOption.color == 'random') { color = zrColor.random(); } else { color = effectOption.color; } shapeList[i] = { shape : 'line', highlightStyle : { xStart : xStart, yStart : pos, xEnd : xStart + len, yEnd : pos, strokeColor : color, lineWidth : lineWidth }, animationX : Math.ceil(Math.random() * 100), len : len }; } return setInterval( function() { addShapeHandle(background); var style; for(var i = 0; i < n; i++) { style = shapeList[i].highlightStyle ; if (style.xStart >= _width){ shapeList[i].len = Math.ceil(Math.random() * 400); shapeList[i].highlightStyle .xStart = -400; shapeList[i].highlightStyle .xEnd = -400 + shapeList[i].len; shapeList[i].highlightStyle .yStart = Math.ceil(Math.random() * _height); shapeList[i].highlightStyle .yEnd = shapeList[i].highlightStyle.yStart; } shapeList[i].highlightStyle.xStart += shapeList[i].animationX; shapeList[i].highlightStyle.xEnd += shapeList[i].animationX; addShapeHandle(shapeList[i]); } addShapeHandle(textShape); refreshHandle(); }, effectOption.timeInterval ); } /** * 泡泡 * @param {Object} loadingOption * @param {Object} addShapeHandle * @param {Object} refreshHandle */ function bubble(loadingOption, addShapeHandle, refreshHandle) { var zrColor = require('./color'); // 特效默认配置 loadingOption = util.merge( loadingOption, { textStyle : { color : '#888' }, backgroundColor : 'rgba(250, 250, 250, 0.8)', effectOption : { n : 50, lineWidth : 2, brushType : 'stroke', color : 'random', timeInterval : 100 } }, {'overwrite': false, 'recursive': true} ); var textShape = getTextShape(loadingOption.textStyle); var background = getBackgroundShape(loadingOption.backgroundColor); var effectOption = loadingOption.effectOption; var n = effectOption.n; var brushType = effectOption.brushType; var lineWidth = effectOption.lineWidth; var shapeList = []; var color; // 初始化动画元素 for(var i = 0; i < n; i++) { if (effectOption.color == 'random') { color = zrColor.alpha(zrColor.random(), 0.3); } else { color = effectOption.color; } shapeList[i] = { shape : 'circle', highlightStyle : { x : Math.ceil(Math.random() * _width), y : Math.ceil(Math.random() * _height), r : Math.ceil(Math.random() * 40), brushType : brushType, color : color, strokeColor : color, lineWidth : lineWidth }, animationY : Math.ceil(Math.random() * 20) }; } return setInterval( function () { addShapeHandle(background); var style; for(var i = 0; i < n; i++) { style = shapeList[i].highlightStyle; if (style.y - shapeList[i].animationY + style.r <= 0){ shapeList[i].highlightStyle.y = _height + style.r; shapeList[i].highlightStyle.x = Math.ceil( Math.random() * _width ); } shapeList[i].highlightStyle.y -= shapeList[i].animationY; addShapeHandle(shapeList[i]); } addShapeHandle(textShape); refreshHandle(); }, effectOption.timeInterval ); } /** * 旋转 * @param {Object} loadingOption * @param {Object} addShapeHandle * @param {Object} refreshHandle */ function spin(loadingOption, addShapeHandle, refreshHandle) { var zrColor = require('./color'); // 特效默认配置 loadingOption.effectOption = util.merge( loadingOption.effectOption || {}, { x : _width / 2 - 80, y : _height / 2, r0 : 9, r : 15, n : 18, color : '#fff', timeInterval : 100 } ); var effectOption = loadingOption.effectOption; loadingOption = util.merge( loadingOption, { textStyle : { color : '#fff', x : effectOption.x + effectOption.r + 10, y : effectOption.y, textAlign : 'start' }, backgroundColor : 'rgba(0, 0, 0, 0.8)' }, {'overwrite': false, 'recursive': true} ); var textShape = getTextShape(loadingOption.textStyle); var background = getBackgroundShape(loadingOption.backgroundColor); var n = effectOption.n; var x = effectOption.x; var y = effectOption.y; var r0 = effectOption.r0; var r = effectOption.r; var color = effectOption.color; // 初始化动画元素 var shapeList = []; var preAngle = Math.round(180 / n); for(var i = 0; i < n; i++) { shapeList[i] = { shape : 'sector', highlightStyle : { x : x, y : y, r0 : r0, r : r, startAngle : preAngle * i * 2, endAngle : preAngle * i * 2 + preAngle, color : zrColor.alpha(color, (i + 1) / n), brushType: 'fill' } }; } var pos = [0, x, y]; return setInterval( function() { addShapeHandle(background); pos[0] -= 0.3; for(var i = 0; i < n; i++) { shapeList[i].rotation = pos; addShapeHandle(shapeList[i]); } addShapeHandle(textShape); refreshHandle(); }, effectOption.timeInterval ); } /** * 圆环 * @param {Object} loadingOption * @param {Object} addShapeHandle * @param {Object} refreshHandle */ function ring(loadingOption, addShapeHandle, refreshHandle) { var zrColor = require('./color'); var zrMath = require('./math'); // 特效默认配置 loadingOption = util.merge( loadingOption, { textStyle : { color : '#07a' }, backgroundColor : 'rgba(250, 250, 250, 0.8)', effectOption : { x : _width / 2, y : _height / 2, r0 : 60, r : 100, color : '#bbdcff', brushType: 'fill', textPosition : 'inside', textFont : 'normal 30px verdana', textColor : 'rgba(30, 144, 255, 0.6)', timeInterval : 100 } }, {'overwrite': false, 'recursive': true} ); var effectOption = loadingOption.effectOption; var textStyle = loadingOption.textStyle; textStyle.x = typeof textStyle.x != 'undefined' ? textStyle.x : effectOption.x; textStyle.y = typeof textStyle.y != 'undefined' ? textStyle.y : (effectOption.y + (effectOption.r0 + effectOption.r) / 2 - 5); var textShape = getTextShape(loadingOption.textStyle); var background = getBackgroundShape(loadingOption.backgroundColor); var x = effectOption.x; var y = effectOption.y; var r0 = effectOption.r0 + 6; var r = effectOption.r - 6; var color = effectOption.color; var darkColor = zrColor.lift(color, 0.1); var shapeRing = { shape : 'ring', highlightStyle : util.clone(effectOption) }; // 初始化动画元素 var shapeList = []; var clolrList = zrColor.getGradientColors( ['#ff6400', '#ffe100', '#97ff00'], 25 ); var preAngle = 15; var endAngle = 240; for(var i = 0; i < 16; i++) { shapeList.push({ shape : 'sector', highlightStyle : { x : x, y : y, r0 : r0, r : r, startAngle : endAngle - preAngle, endAngle : endAngle, brushType: 'fill', color : darkColor }, _color : zrColor.getLinearGradient( x + r0 * zrMath.cos(endAngle, true), y - r0 * zrMath.sin(endAngle, true), x + r0 * zrMath.cos(endAngle - preAngle, true), y - r0 * zrMath.sin(endAngle - preAngle, true), [ [0, clolrList[i * 2]], [1, clolrList[i * 2 + 1]] ] ) }); endAngle -= preAngle; } endAngle = 360; for(var i = 0; i < 4; i++) { shapeList.push({ shape : 'sector', highlightStyle : { x : x, y : y, r0 : r0, r : r, startAngle : endAngle - preAngle, endAngle : endAngle, brushType: 'fill', color : darkColor }, _color : zrColor.getLinearGradient( x + r0 * zrMath.cos(endAngle, true), y - r0 * zrMath.sin(endAngle, true), x + r0 * zrMath.cos(endAngle - preAngle, true), y - r0 * zrMath.sin(endAngle - preAngle, true), [ [0, clolrList[i * 2 + 32]], [1, clolrList[i * 2 + 33]] ] ) }); endAngle -= preAngle; } var n = 0; if (typeof loadingOption.progress != 'undefined') { // 指定进度 addShapeHandle(background); n = _adjust(loadingOption.progress, [0,1]).toFixed(2) * 100 / 5; shapeRing.highlightStyle.text = n * 5 + '%'; addShapeHandle(shapeRing); for(var i = 0; i < 20; i++) { shapeList[i].highlightStyle.color = i < n ? shapeList[i]._color : darkColor; addShapeHandle(shapeList[i]); } addShapeHandle(textShape); refreshHandle(); return; } else { // 循环显示 return setInterval( function() { addShapeHandle(background); n += n >= 20 ? -20 : 1; //shapeRing.highlightStyle.text = n * 5 + '%'; addShapeHandle(shapeRing); for(var i = 0; i < 20; i++) { shapeList[i].highlightStyle.color = i < n ? shapeList[i]._color : darkColor; addShapeHandle(shapeList[i]); } addShapeHandle(textShape); refreshHandle(); }, effectOption.timeInterval ); } } function start(loadingOption, addShapeHandle, refreshHandle) { var loadingEffect = self.ring; // 默认特效 if (typeof loadingOption.effect == 'function') { // 自定义特效 loadingEffect = loadingOption.effect; } else if (typeof self[loadingOption.effect] == 'function'){ // 指定特效 loadingEffect = self[loadingOption.effect]; } _width = loadingOption.canvasSize.width; _height = loadingOption.canvasSize.height; return loadingEffect( loadingOption, addShapeHandle, refreshHandle ); } function stop(loadingTimer) { clearInterval(loadingTimer); } self = { // 这三个方法用于扩展loading effect getBackgroundShape : getBackgroundShape, getTextShape : getTextShape, define : define, // 内置特效 bar : bar, whirling : whirling, dynamicLine : dynamicLine, bubble : bubble, spin : spin, ring : ring, // 方法 start : start, stop : stop }; return self; } ); /** * zrender: 事件辅助类 * * @author Kener (@Kener-林峰, linzhifeng@baidu.com) * * getX:获取事件横坐标 * getY:或者事件纵坐标 * getDelta:或者鼠标滚轮变化 * stop:停止事件传播 * Dispatcher:事件分发器 */ define( 'zrender/tool/event',[],function() { /** * 提取鼠标(手指)x坐标 * @param {event} e 事件. * @return {number} 鼠标(手指)x坐标. */ function getX(e) { return typeof e.zrenderX != 'undefined' && e.zrenderX || typeof e.offsetX != 'undefined' && e.offsetX || typeof e.layerX != 'undefined' && e.layerX || typeof e.clientX != 'undefined' && e.clientX; } /** * 提取鼠标y坐标 * @param {event} e 事件. * @return {number} 鼠标(手指)y坐标. */ function getY(e) { return typeof e.zrenderY != 'undefined' && e.zrenderY || typeof e.offsetY != 'undefined' && e.offsetY || typeof e.layerY != 'undefined' && e.layerY || typeof e.clientY != 'undefined' && e.clientY; } /** * 提取鼠标滚轮变化 * @param {event} e 事件. * @return {number} 滚轮变化,正值说明滚轮是向上滚动,如果是负值说明滚轮是向下滚动 */ function getDelta(e) { return typeof e.wheelDelta != 'undefined' && e.wheelDelta || typeof e.detail != 'undefined' && -e.detail; } /** * 停止冒泡和阻止默认行为 * @param {Object} e : event对象 */ function stop(e) { if (e.preventDefault) { e.preventDefault(); e.stopPropagation(); } else { e.returnValue = false; } } /** * 事件分发器 */ function Dispatcher() { var _self = this; var _h = {}; /** * 单次触发绑定,dispatch后销毁 * @param {string} event 事件字符串 * @param {function} handler 响应函数 */ function one(event, handler) { if(!handler || !event) { return _self; } if(!_h[event]) { _h[event] = []; } _h[event].push({ h : handler, one : true }); return _self; } /** * 事件绑定 * @param {string} event 事件字符串 * @param {function} handler : 响应函数 */ function bind(event, handler) { if(!handler || !event) { return _self; } if(!_h[event]) { _h[event] = []; } _h[event].push({ h : handler, one : false }); return _self; } /** * 事件解绑定 * @param {string} event 事件字符串 * @param {function} handler : 响应函数 */ function unbind(event, handler) { if(!event) { _h = {}; return _self; } if(handler) { if(_h[event]) { var newList = []; for (var i = 0, l = _h[event].length; i < l; i++) { if (_h[event][i]['h'] != handler) { newList.push(_h[event][i]); } } _h[event] = newList; } if(_h[event] && _h[event].length === 0) { delete _h[event]; } } else { delete _h[event]; } return _self; } /** * 事件分发 * @param {string} type : 事件类型 * @param {Object} event : event对象 * @param {Object} [attachment] : 附加信息 */ function dispatch(type, event, attachment) { if(_h[type]) { var newList = []; var eventPacket = attachment || {}; eventPacket.type = type; eventPacket.event = event; //eventPacket._target = self; for (var i = 0, l = _h[type].length; i < l; i++) { _h[type][i]['h'](eventPacket); if (!_h[type][i]['one']) { newList.push(_h[type][i]); } } if (newList.length != _h[type].length) { _h[type] = newList; } } return _self; } _self.one = one; _self.bind = bind; _self.unbind = unbind; _self.dispatch = dispatch; } return { getX : getX, getY : getY, getDelta : getDelta, stop : stop, Dispatcher : Dispatcher }; } ); /*! * ZRender, a lightweight canvas library with a MVC architecture, data-driven * and provides an event model like DOM. * * Copyright (c) 2013, Baidu Inc. * All rights reserved. * * Redistribution and use of this software in source and binary forms, with or * without modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Baidu Inc. nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission of Baidu Inc. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * zrender: core核心类 * * @desc zrender是一个轻量级的Canvas类库,MVC封装,数据驱动,提供类Dom事件模型。 * @author Kener (@Kener-林峰, linzhifeng@baidu.com) * */ define( 'zrender/zrender',['require','./lib/excanvas','./shape','./shape/circle','./shape/ellipse','./shape/line','./shape/polygon','./shape/brokenLine','./shape/rectangle','./shape/ring','./shape/sector','./shape/text','./shape/heart','./shape/droplet','./shape/path','./shape/image','./shape/beziercurve','./shape/star','./shape/isogon','./animation/animation','./tool/util','./tool/util','./config','./tool/loadingEffect','./tool/loadingEffect','./config','./tool/event'],function(require) { /* * HTML5 Canvas for Internet Explorer! * Modern browsers like Firefox, Safari, Chrome and Opera support * the HTML5 canvas tag to allow 2D command-based drawing. * ExplorerCanvas brings the same functionality to Internet Explorer. * To use, web developers only need to include a single script tag * in their existing web pages. * * https://code.google.com/p/explorercanvas/ * http://explorercanvas.googlecode.com/svn/trunk/excanvas.js */ // 核心代码会生成一个全局变量 G_vmlCanvasManager,模块改造后借用于快速判断canvas支持 require('./lib/excanvas'); var self = {}; var zrender = self; // 提供MVC内部反向使用静态方法; var _idx = 0; //ZRender instance's id var _instances = {}; //ZRender实例map索引 /** * zrender初始化 * 不让外部直接new ZRender实例,为啥? * 不为啥,提供全局可控同时减少全局污染和降低命名冲突的风险! * * @param {HTMLElement} dom dom对象,不帮你做document.getElementById了 * @param {Object=} params 个性化参数,如自定义shape集合,带进来就好 * * @return {ZRender} ZRender实例 */ self.init = function(dom, params) { var zi = new ZRender(++_idx + '', dom, params || {}); _instances[_idx] = zi; return zi; }; /** * zrender实例销毁,记在_instances里的索引也会删除了 * 管生就得管死,可以通过zrender.dispose(zi)销毁指定ZRender实例 * 当然也可以直接zi.dispose()自己销毁 * * @param {ZRender=} zi ZRender对象,不传则销毁全部 */ self.dispose = function(zi) { if (zi) { zi.dispose(); } else { for (var z in _instances) { _instances[z].dispose(); } _instances = {}; } return self; }; /** * 获取zrender实例 * * @param {string} id ZRender对象索引 */ self.getInstance = function(id) { return _instances[id]; }; /** * 删除zrender实例,ZRender实例dispose时会调用, * 删除后getInstance则返回undefined * ps: 仅是删除,删除的实例不代表已经dispose了~~ * 这是一个摆脱全局zrender.dispose()自动销毁的后门, * take care of yourself~ * * @param {string} id ZRender对象索引 */ self.delInstance = function(id) { if (_instances[id]) { //只是对垃圾回收上的友好照顾,不写也大不了~ _instances[id] = null; delete _instances[id]; } return self; }; // 是否异常捕获 self.catchBrushException = false; /** * debug日志选项:catchBrushException为true下有效 * 0 : 不生成debug数据,发布用 * 1 : 异常抛出,调试用 * 2 : 控制台输出,调试用 */ self.debugMode = 0; self.log = function() { if (self.debugMode === 0) { return; } else if (self.debugMode == 1) { for (var k in arguments) { throw new Error(arguments[k]); } } else if (self.debugMode > 1) { for (var k in arguments) { console.log(arguments[k]); } } return self; }; /** * ZRender接口类,对外可用的所有接口都在这里!! * storage(M)、painter(V)、handler(C)为内部私有类,外部接口不可见 * 非get接口统一返回self支持链式调用~ * * @param {string} id 唯一标识 * @param {HTMLElement} dom dom对象,不帮你做document.getElementById * @param {Object=} params 个性化参数,如自定义shape集合,带进来就好 * * @return {ZRender} ZRender实例 */ function ZRender(id, dom, params) { var self = this; var shape = require('./shape'); // 内置图形注册 require('./shape/circle'); require('./shape/ellipse'); require('./shape/line'); require('./shape/polygon'); require('./shape/brokenLine'); require('./shape/rectangle'); require('./shape/ring'); require('./shape/sector'); require('./shape/text'); require('./shape/heart'); require('./shape/droplet'); require('./shape/path'); require('./shape/image'); require('./shape/beziercurve'); require('./shape/star'); require('./shape/isogon'); var shapeLibrary; if (typeof params.shape == 'undefined') { //默认图形库 shapeLibrary = shape; } else { //自定义图形库,私有化,实例独占 shapeLibrary = {}; for (var s in params.shape) { shapeLibrary[s] = params.shape[s]; } shapeLibrary.get = function(name) { return shapeLibrary[name] || shape.get(name); }; } var storage = new Storage(shapeLibrary); var painter = new Painter(dom, storage, shapeLibrary); var handler = new Handler(dom, storage, painter, shapeLibrary); // 动画控制 var Animation = require('./animation/animation'); var animatingShapes = []; var animation = new Animation({ stage : { update : function(){ self.update(animatingShapes); } } }); animation.start(); /** * 获取实例唯一标识 */ self.getId = function() { return id; }; /** * 添加图形形状 * @param {Object} shape 形状对象,可用属性全集,详见各shape */ self.addShape = function(shape) { storage.add(shape); return self; }; /** * 删除图形形状 * @param {string} shapeId 形状对象唯一标识 */ self.delShape = function(shapeId) { storage.del(shapeId); return self; }; /** * 修改图形形状 * @param {string} shapeId 形状对象唯一标识 * @param {Object} shape 形状对象 */ self.modShape = function(shapeId, shape) { storage.mod(shapeId, shape); return self; }; /** * 添加额外高亮层显示,仅提供添加方法,每次刷新后高亮层图形均被清空 * @param {Object} shape 形状对象 */ self.addHoverShape = function(shape) { storage.addHover(shape); return self; }; /** * 渲染 * @param {Function} callback 渲染结束后回调函数 * todo:增加缓动函数 */ self.render = function(callback) { painter.render(callback); return self; }; /** * 视图更新 * @param {Function} callback 视图更新后回调函数 */ self.refresh = function(callback) { painter.refresh(callback); return self; }; /** * 视图更新 * @param {Array} shapeList 需要更新的图形元素列表 * @param {Function} callback 视图更新后回调函数 */ self.update = function(shapeList, callback) { painter.update(shapeList, callback); return self; }; self.resize = function() { painter.resize(); return self; }; /** * 动画 * @param {string} shapeId 形状对象唯一标识 * @param {string} path 需要添加动画的属性获取路径,可以通过a.b.c来获取深层的属性 * @param {boolean} loop 动画是否循环 * @return {Object} 动画的Deferred对象 * Example: * zr.animate( circleId, 'style', false) * .when(1000, { x: 10} ) * .done( function(){ console.log('Animation done')}) * .start() */ self.animate = function(shapeId, path, loop) { var util = require('./tool/util'); var shape = storage.get(shapeId); if (shape) { var target; if (path) { var pathSplitted = path.split('.'); var prop = shape; for (var i = 0, l = pathSplitted.length; i < l; i++) { if (!prop) { continue; } prop = prop[pathSplitted[i]]; } if (prop) { target = prop; } } else { target = shape; } if (!target) { zrender.log( 'Property "' + path + '" is not existed in shape ' + shapeId ); return; } if( typeof(shape.__aniCount) === 'undefined'){ // 正在进行的动画记数 shape.__aniCount = 0; } if( shape.__aniCount === 0 ){ animatingShapes.push(shape); } shape.__aniCount ++; return animation.animate(target, loop) .done(function() { shape.__aniCount --; if( shape.__aniCount === 0){ // 从animatingShapes里移除 var idx = util.indexOf(animatingShapes, shape); animatingShapes.splice(idx, 1); } }); } else { zrender.log('Shape "'+ shapeId + '" not existed'); } }; /** * loading显示 * @param {Object} loadingOption 参数 * { * effect, * //loading话术 * text:'', * // 水平安放位置,默认为 'center',可指定x坐标 * x:'center' || 'left' || 'right' || {number}, * // 垂直安放位置,默认为'top',可指定y坐标 * y:'top' || 'bottom' || {number}, * * textStyle:{ * textFont: 'normal 20px Arial' || {textFont}, //文本字体 * color: {color} * } * } */ self.showLoading = function(loadingOption) { painter.showLoading(loadingOption); return self; }; /** * loading结束 */ self.hideLoading = function() { painter.hideLoading(); return self; }; /** * 生成形状唯一ID * @param {string} [idPrefix] id前缀 * @return {string} 不重复ID */ self.newShapeId = function(idPrefix) { return storage.newShapeId(idPrefix); }; /** * 获取视图宽度 */ self.getWidth = function() { return painter.getWidth(); }; /** * 获取视图高度 */ self.getHeight = function() { return painter.getHeight(); }; /** * 图像导出 */ self.toDataURL = function(type, args) { return painter.toDataURL(type, args); }; /** * 事件绑定 * @param {string} eventName 事件名称 * @param {Function} eventHandler 响应函数 */ self.on = function(eventName, eventHandler) { handler.on(eventName, eventHandler); return self; }; /** * 事件解绑定,参数为空则解绑所有自定义事件 * @param {string} eventName 事件名称 * @param {Function} eventHandler 响应函数 */ self.un = function(eventName, eventHandler) { handler.un(eventName, eventHandler); return self; }; /** * 清除当前ZRender下所有类图的数据和显示,clear后MVC和已绑定事件均还存在在,ZRender可用 */ self.clear = function() { storage.del(); painter.clear(); return self; }; /** * 释放当前ZR实例(删除包括dom,数据、显示和事件绑定),dispose后ZR不可用 */ self.dispose = function() { animation.stop(); animation = null; animatingShapes = null; self.clear(); self = null; storage.dispose(); storage = null; painter.dispose(); painter = null; handler.dispose(); handler = null; //释放后告诉全局删除对自己的索引,没想到啥好方法 zrender.delInstance(id); return; }; } /** * 内容仓库 (M) * @param {Object} shape 图形库 */ function Storage(shape) { var util = require('./tool/util'); var self = this; var _idBase = 0; //图形数据id自增基础 // 所有常规形状,id索引的map var _elements = {}; // 所有形状的z轴方向排列,提高遍历性能,zElements[0]的形状在zElements[1]形状下方 var _zElements = []; // 高亮层形状,不稳定,动态增删,数组位置也是z轴方向,靠前显示在下方 var _hoverElements = []; var _maxZlevel = 0; // 最大zlevel var _changedZlevel = {}; // 有数据改变的zlevel /** * 快速判断标志~ * e.__silent 是否需要hover判断 * e.__needTransform 是否需要进行transform * e.style.__rect 区域矩阵缓存,修改后清空,重新计算一次 */ function _mark(e) { if (e.hoverable || e.onclick || e.draggable || e.onmousemove || e.onmouseover || e.onmouseout || e.onmousedown || e.onmouseup || e.ondragenter || e.ondragover || e.ondragleave || e.ondrop ) { e.__silent = false; } else { e.__silent = true; } if (Math.abs(e.rotation[0]) > 0.0001 || Math.abs(e.position[0]) > 0.0001 || Math.abs(e.position[1]) > 0.0001 || Math.abs(e.scale[0] - 1) > 0.0001 || Math.abs(e.scale[1] - 1) > 0.0001 ) { e.__needTransform = true; } else { e.__needTransform = false; } e.style = e.style || {}; e.style.__rect = null; } /** * 唯一标识id生成 * @param {string=} idHead 标识前缀 */ function newShapeId(idHead) { return (idHead || '') + (++_idBase); } /** * 添加 * @param {Object} params 参数 */ function add(params) { // 默认&必须的参数 var e = { 'shape': 'circle', // 形状 'id': params.id || self.newShapeId(), // 唯一标识 'zlevel': 0, // z轴位置 'draggable': false, // draggable可拖拽 'clickable': false, // clickable可点击响应 'hoverable': true, // hoverable可悬浮响应 'position': [0, 0], 'rotation' : [0, 0, 0], 'scale' : [1, 1, 0, 0] }; util.merge( e, params, { 'overwrite': true, 'recursive': true } ); _mark(e); _elements[e.id] = e; _zElements[e.zlevel] = _zElements[e.zlevel] || []; _zElements[e.zlevel].push(e); _maxZlevel = Math.max(_maxZlevel,e.zlevel); _changedZlevel[e.zlevel] = true; return self; } /** * 根据指定的shapeId获取相应的shape属性 * @param {string=} idx 唯一标识 */ function get(shapeId) { return _elements[shapeId]; } /** * 删除,shapeId不指定则全清空 * @param {string= | Array} idx 唯一标识 */ function del(shapeId) { if (typeof shapeId != 'undefined') { var delMap = {}; if (!(shapeId instanceof Array)) { // 单个 delMap[shapeId] = true; } else { // 批量删除 for (var i = 0, l = shapeId.length; i < l; i++) { delMap[shapeId[i].id] = true; } } var newList; var oldList; var zlevel; var zChanged = {}; for (var sId in delMap) { if (_elements[sId]) { zlevel = _elements[sId].zlevel; _changedZlevel[zlevel] = true; if (!zChanged[zlevel]) { oldList = _zElements[zlevel]; newList = []; for (var i = 0, l = oldList.length; i < l; i++){ if (!delMap[oldList[i].id]) { newList.push(oldList[i]); } } _zElements[zlevel] = newList; zChanged[zlevel] = true; } delete _elements[sId]; } } } else{ //不指定shapeId清空 _elements = {}; _zElements = []; _hoverElements = []; _maxZlevel = 0; //最大zlevel _changedZlevel = { //有数据改变的zlevel all : true }; } return self; } /** * 修改 * @param {string} idx 唯一标识 * @param {Object} params]参数 */ function mod(shapeId, params) { var e = _elements[shapeId]; if (e) { _changedZlevel[e.zlevel] = true; // 可能修改前后不在一层 util.merge( e, params, { 'overwrite': true, 'recursive': true } ); _mark(e); _changedZlevel[e.zlevel] = true; // 可能修改前后不在一层 _maxZlevel = Math.max(_maxZlevel,e.zlevel); } return self; } /** * 常规形状位置漂移,形状自身定义漂移函数 * @param {string} idx 形状唯一标识 * */ function drift(shapeId, dx, dy) { var e = _elements[shapeId]; if (!e) { return; } e.__needTransform = true; if (!e.ondrift //ondrift //有onbrush并且调用执行返回false或undefined则继续 || (e.ondrift && !e.ondrift(e, dx, dy)) ) { if (zrender.catchBrushException) { try { shape.get(e.shape).drift(e, dx, dy); } catch(error) { zrender.log(error, 'drift error of ' + e.shape, e); } } else { shape.get(e.shape).drift(e, dx, dy); } } _changedZlevel[e.zlevel] = true; return self; } /** * 添加高亮层数据 * @param {Object} params 参数 */ function addHover(params) { if ((params.rotation && Math.abs(params.rotation[0]) > 0.0001) || (params.position && (Math.abs(params.position[0]) > 0.0001 || Math.abs(params.position[1]) > 0.0001)) || (params.scale && (Math.abs(params.scale[0] - 1) > 0.0001 || Math.abs(params.scale[1] - 1) > 0.0001)) ) { params.__needTransform = true; } else { params.__needTransform = false; } _hoverElements.push(params); return self; } /** * 删除高亮层数据 */ function delHover() { _hoverElements = []; return self; } function hasHoverShape() { return _hoverElements.length > 0; } /** * 遍历迭代器 * @param {Function} fun 迭代回调函数,return true终止迭代 * @param {Object=} option 迭代参数,缺省为仅降序遍历常规形状 * hover : true 是否迭代高亮层数据 * normal : 'down' | 'up' | 'free' 是否迭代常规数据,迭代时是否指定及z轴顺序 */ function iterShape(fun, option) { if (!option) { option = { hover: false, normal: 'down' }; } if (option.hover) { //高亮层数据遍历 for (var i = 0, l = _hoverElements.length; i < l; i++) { if (fun(_hoverElements[i])) { return self; } } } var zlist; var len; if (typeof option.normal != 'undefined') { //z轴遍历: 'down' | 'up' | 'free' switch (option.normal) { case 'down': //降序遍历,高层优先 for (var l = _zElements.length - 1; l >= 0; l--) { zlist = _zElements[l]; if (zlist) { len = zlist.length; while (len--) { if (fun(zlist[len])) { return self; } } } } break; case 'up': //升序遍历,底层优先 for (var i = 0, l = _zElements.length; i < l; i++) { zlist = _zElements[i]; if (zlist) { len = zlist.length; for (var k = 0; k < len; k++) { if (fun(zlist[k])) { return self; } } } } break; // case 'free': default: //无序遍历 for (var i in _elements) { if (fun(_elements[i])) { return self; } } break; } } return self; } function getMaxZlevel() { return _maxZlevel; } function getChangedZlevel() { return _changedZlevel; } function clearChangedZlevel() { _changedZlevel = {}; return self; } function setChangedZlevle(level){ _changedZlevel[level] = true; return self; } /** * 释放 */ function dispose() { _elements = null; _zElements = null; _hoverElements = null; self = null; return; } self.newShapeId = newShapeId; self.add = add; self.get = get; self.del = del; self.addHover = addHover; self.delHover = delHover; self.hasHoverShape = hasHoverShape; self.mod = mod; self.drift = drift; self.iterShape = iterShape; self.getMaxZlevel = getMaxZlevel; self.getChangedZlevel = getChangedZlevel; self.clearChangedZlevel = clearChangedZlevel; self.setChangedZlevle = setChangedZlevle; self.dispose = dispose; } /** * 绘图类 (V) * @param {HTMLElement} root 绘图区域 * @param {storage} storage Storage实例 * @param {Object} shape 图形库 */ function Painter(root, storage, shape) { var config = require('./config'); var self = this; var _domList = {}; //canvas dom元素 var _ctxList = {}; //canvas 2D context对象,与domList对应 var _maxZlevel = 0; //最大zlevel,缓存记录 var _loadingTimer; var _domRoot = document.createElement('div'); // 避免页面选中的尴尬 _domRoot.onselectstart = function() { return false; }; //宽,缓存记录 var _width; //高,缓存记录 var _height; //retina 屏幕优化 var _devicePixelRatio = window.devicePixelRatio || 1; function _getWidth() { var stl = root.currentStyle || document.defaultView.getComputedStyle(root); return root.clientWidth - stl.paddingLeft.replace(/\D/g,'') // 请原谅我这比较粗暴 - stl.paddingRight.replace(/\D/g,''); } function _getHeight(){ var stl = root.currentStyle || document.defaultView.getComputedStyle(root); return root.clientHeight - stl.paddingTop.replace(/\D/g,'') // 请原谅我这比较粗暴 - stl.paddingBottom.replace(/\D/g,''); } function _init() { _domRoot.innerHTML = ''; root.innerHTML = ''; _width = _getWidth(); _height = _getHeight(); //没append呢,原谅我这样写,清晰~ _domRoot.style.position = 'relative'; _domRoot.style.overflow = 'hidden'; _domRoot.style.width = _width + 'px'; _domRoot.style.height = _height + 'px'; root.appendChild(_domRoot); _domList = {}; _ctxList = {}; _maxZlevel = storage.getMaxZlevel(); //创建各层canvas //背景 _domList['bg'] = _createDom('bg','div'); _domRoot.appendChild(_domList['bg']); //实体 for (var i = 0; i <= _maxZlevel; i++) { _domList[i] = _createDom(i,'canvas'); _domRoot.appendChild(_domList[i]); if (G_vmlCanvasManager) { G_vmlCanvasManager.initElement(_domList[i]); } _ctxList[i] = _domList[i].getContext('2d'); _devicePixelRatio != 1 && _ctxList[i].scale(_devicePixelRatio, _devicePixelRatio); } //高亮 _domList['hover'] = _createDom('hover','canvas'); _domList['hover'].id = '_zrender_hover_'; _domRoot.appendChild(_domList['hover']); if (G_vmlCanvasManager) { G_vmlCanvasManager.initElement(_domList['hover']); } _ctxList['hover'] = _domList['hover'].getContext('2d'); _devicePixelRatio != 1 && _ctxList['hover'].scale( _devicePixelRatio, _devicePixelRatio ); } /** * 检查_maxZlevel是否变大,如是则同步创建需要的Canvas */ function _syncMaxZlevelCanvase(){ var curMaxZlevel = storage.getMaxZlevel(); if (_maxZlevel < curMaxZlevel) { //实体 for (var i = _maxZlevel + 1; i <= curMaxZlevel; i++) { _domList[i] = _createDom(i,'canvas'); _domRoot.insertBefore(_domList[i], _domList['hover']); if (G_vmlCanvasManager) { G_vmlCanvasManager.initElement(_domList[i]); } _ctxList[i] = _domList[i].getContext('2d'); _devicePixelRatio != 1 && _ctxList[i].scale( _devicePixelRatio, _devicePixelRatio ); } _maxZlevel = curMaxZlevel; } } /** * 创建dom * @param {string} id dom id 待用 * @param {string} type : dom type, such as canvas, div etc. */ function _createDom(id, type) { var newDom = document.createElement(type); //没append呢,请原谅我这样写,清晰~ newDom.style.position = 'absolute'; newDom.style.left = 0; newDom.style.top = 0; newDom.style.width = _width + 'px'; newDom.style.height = _height + 'px'; newDom.setAttribute('width', _width * _devicePixelRatio); newDom.setAttribute('height', _height * _devicePixelRatio); //id不作为索引用,避免可能造成的重名,定义为私有属性 newDom.setAttribute('data-id', id); return newDom; } /** * 刷画图形 * @param {Object} changedZlevel 需要更新的zlevel索引 */ function _brush(changedZlevel) { return function(e) { if ((changedZlevel.all || changedZlevel[e.zlevel]) && !e.invisible ) { var ctx = _ctxList[e.zlevel]; if (ctx) { if (!e.onbrush //没有onbrush //有onbrush并且调用执行返回false或undefined则继续粉刷 || (e.onbrush && !e.onbrush(ctx, e, false)) ) { if (zrender.catchBrushException) { try { shape.get(e.shape).brush( ctx, e, false, update ); } catch(error) { zrender.log( error, 'brush error of ' + e.shape, e ); } } else { shape.get(e.shape).brush( ctx, e, false, update ); } } } else { zrender.log( 'can not find the specific zlevel canvas!' ); } } }; } /** * 鼠标悬浮刷画 */ function _brushHover(e) { var ctx = _ctxList['hover']; if (!e.onbrush //没有onbrush //有onbrush并且调用执行返回false或undefined则继续粉刷 || (e.onbrush && !e.onbrush(ctx, e, true)) ) { // Retina 优化 if (zrender.catchBrushException) { try { shape.get(e.shape).brush(ctx, e, true, update); } catch(error) { zrender.log( error, 'hoverBrush error of ' + e.shape, e ); } } else { shape.get(e.shape).brush(ctx, e, true, update); } } } /** * 首次绘图,创建各种dom和context * @param {Function=} callback 绘画结束后的回调函数 */ function render(callback) { if (isLoading()) { hideLoading(); } //检查_maxZlevel是否变大,如是则同步创建需要的Canvas _syncMaxZlevelCanvase(); //升序遍历,shape上的zlevel指定绘画图层的z轴层叠 storage.iterShape( _brush({ all : true }), { normal: 'up' } ); //update到最新则清空标志位 storage.clearChangedZlevel(); if (typeof callback == 'function') { callback(); } return self; } /** * 刷新 * @param {Function=} callback 刷新结束后的回调函数 */ function refresh(callback) { //检查_maxZlevel是否变大,如是则同步创建需要的Canvas _syncMaxZlevelCanvase(); //仅更新有修改的canvas var changedZlevel = storage.getChangedZlevel(); //擦除有修改的canvas if (changedZlevel.all){ clear(); } else { for (var k in changedZlevel) { if (_ctxList[k]) { _ctxList[k].clearRect( 0, 0, _width * _devicePixelRatio, _height * _devicePixelRatio ); } } } //重绘内容,升序遍历,shape上的zlevel指定绘画图层的z轴层叠 storage.iterShape( _brush(changedZlevel), { normal: 'up'} ); //update到最新则清空标志位 storage.clearChangedZlevel(); if (typeof callback == 'function') { callback(); } return self; } /** * 视图更新 * @param {Array} shapeList 需要更新的图形元素列表 * @param {Function} callback 视图更新后回调函数 */ function update(shapeList, callback) { var shape; for (var i = 0, l = shapeList.length; i < l; i++) { shape = shapeList[i]; storage.mod(shape.id, shape); } refresh(callback); return self; } /** * 清除hover层外所有内容 */ function clear() { for (var k in _ctxList) { if (k == 'hover') { continue; } _ctxList[k].clearRect( 0, 0, _width * _devicePixelRatio, _height * _devicePixelRatio ); } return self; } /** * 刷新hover层 */ function refreshHover() { clearHover(); storage.iterShape(_brushHover, { hover: true }); storage.delHover(); return self; } /** * 清除hover层所有内容 */ function clearHover() { _ctxList && _ctxList['hover'] && _ctxList['hover'].clearRect( 0, 0, _width * _devicePixelRatio, _height * _devicePixelRatio ); return self; } /** * 显示loading * @param {Object} loadingOption 选项,内容见下 * @param {color} -.backgroundColor 背景颜色 * @param {Object} -.textStyle 文字样式,同shape/text.style * @param {number=} -.progress 进度参数,部分特效有用 * @param {Object=} -.effectOption 特效参数,部分特效有用 * @param {string | function} -.effect 特效依赖tool/loadingEffect, * 可传入自定义特效function */ function showLoading(loadingOption) { var effect = require('./tool/loadingEffect'); effect.stop(_loadingTimer); loadingOption = loadingOption || {}; loadingOption.effect = loadingOption.effect || config.loadingEffect; loadingOption.canvasSize = { width : _width, height : _height }; _loadingTimer = effect.start( loadingOption, storage.addHover, refreshHover ); self.loading = true; return self; } /** * loading结束 * 乱来的,待重写 */ function hideLoading() { var effect = require('./tool/loadingEffect'); effect.stop(_loadingTimer); clearHover(); self.loading = false; return self; } /** * loading结束判断 */ function isLoading() { return self.loading; } /** * 获取绘图区域宽度 */ function getWidth() { return _width; } /** * 获取绘图区域高度 */ function getHeight() { return _height; } /** * 区域大小变化后重绘 */ function resize() { var width; var height; var dom; _domRoot.style.display = 'none'; width = _getWidth(); height = _getHeight(); _domRoot.style.display = ''; //优化没有实际改变的resize if (_width != width || height != _height){ _width = width; _height = height; _domRoot.style.width = _width + 'px'; _domRoot.style.height = _height + 'px'; for (var i in _domList) { dom = _domList[i]; dom.setAttribute('width', _width); dom.setAttribute('height', _height); dom.style.width = _width + 'px'; dom.style.height = _height + 'px'; } storage.setChangedZlevle('all'); refresh(); } return self; } /** * 释放 */ function dispose() { if (isLoading()) { hideLoading(); } root.innerHTML = ''; root = null; storage = null; shape = null; _domRoot = null; _domList = null; _ctxList = null; self = null; return; } function getDomHover() { return _domList['hover']; } function toDataURL(type, args) { if (G_vmlCanvasManager) { return null; } var imageDom = _createDom('image','canvas'); _domList['bg'].appendChild(imageDom); var ctx = imageDom.getContext('2d'); _devicePixelRatio != 1 && ctx.scale(_devicePixelRatio, _devicePixelRatio); ctx.fillStyle = '#fff'; ctx.rect( 0, 0, _width * _devicePixelRatio, _height * _devicePixelRatio ); ctx.fill(); //升序遍历,shape上的zlevel指定绘画图层的z轴层叠 storage.iterShape( function (e) { if (!e.invisible) { if (!e.onbrush //没有onbrush //有onbrush并且调用执行返回false或undefined则继续粉刷 || (e.onbrush && !e.onbrush(ctx, e, false)) ) { if (zrender.catchBrushException) { try { shape.get(e.shape).brush( ctx, e, false, update ); } catch(error) { zrender.log( error, 'brush error of ' + e.shape, e ); } } else { shape.get(e.shape).brush( ctx, e, false, update ); } } } }, { normal: 'up' } ); var image = imageDom.toDataURL(type, args); ctx = null; _domList['bg'].removeChild(imageDom); return image; } self.render = render; self.refresh = refresh; self.update = update; self.clear = clear; self.refreshHover = refreshHover; self.clearHover = clearHover; self.showLoading = showLoading; self.hideLoading = hideLoading; self.isLoading = isLoading; self.getWidth = getWidth; self.getHeight = getHeight; self.resize = resize; self.dispose = dispose; self.getDomHover = getDomHover; self.toDataURL = toDataURL; _init(); } /** * 控制类 (C) * @param {HTMLElement} root 绘图区域 * @param {storage} storage Storage实例 * @param {painter} painter Painter实例 * @param {Object} shape 图形库 * * 分发事件支持详见config.EVENT */ function Handler(root, storage, painter, shape) { var config = require('./config'); //添加事件分发器特性 var eventTool = require('./tool/event'); eventTool.Dispatcher.call(this); var self = this; //常用函数加速 var getX = eventTool.getX; var getY = eventTool.getY; //各种事件标识的私有变量 var _event; //原生dom事件 var _hasfound = false; //是否找到hover图形元素 var _lastHover = null; //最后一个hover图形元素 var _mouseDownTarget = null; var _draggingTarget = null; //当前被拖拽的图形元素 var _isMouseDown = false; var _isDragging = false; var _lastTouchMoment; var _lastX = 0; var _lastY = 0; var _mouseX = 0; var _mouseY = 0; var _domHover = painter.getDomHover(); /** * 初始化,事件绑定,支持的所有事件都由如下原生事件计算得来 */ function _init() { if (window.addEventListener) { window.addEventListener('resize', _resizeHandler); root.addEventListener('click', _clickHandler); root.addEventListener('mousewheel', _mouseWheelHandler); root.addEventListener('DOMMouseScroll', _mouseWheelHandler); root.addEventListener('mousemove', _mouseMoveHandler); root.addEventListener('mouseout', _mouseOutHandler); root.addEventListener('mousedown', _mouseDownHandler); root.addEventListener('mouseup', _mouseUpHandler); // mobile支持 root.addEventListener('touchstart', _touchStartHandler); root.addEventListener('touchmove', _touchMoveHandler); root.addEventListener('touchend', _touchEndHandler); } else { window.attachEvent('onresize', _resizeHandler); root.attachEvent('onclick', _clickHandler); root.attachEvent('onmousewheel', _mouseWheelHandler); root.attachEvent('onmousemove', _mouseMoveHandler); root.attachEvent('onmouseout', _mouseOutHandler); root.attachEvent('onmousedown', _mouseDownHandler); root.attachEvent('onmouseup', _mouseUpHandler); } } /** * 窗口大小改变响应函数 * @param {event} event dom事件对象 */ function _resizeHandler(event) { _event = event || window.event; _lastHover = null; _isMouseDown = false; //分发config.EVENT.RESIZE事件,global self.dispatch(config.EVENT.RESIZE, _event); } /** * 点击事件 * @param {event} event dom事件对象 */ function _clickHandler(event) { _event = _zrenderEventFixed(event); //分发config.EVENT.CLICK事件 if (!_lastHover) { _dispatchAgency(_lastHover, config.EVENT.CLICK); } else if (_lastHover && _lastHover.clickable) { _dispatchAgency(_lastHover, config.EVENT.CLICK); } _mouseMoveHandler(_event); } /** * 鼠标滚轮响应函数 * @param {event} event dom事件对象 */ function _mouseWheelHandler(event) { _event = _zrenderEventFixed(event); //分发config.EVENT.MOUSEWHEEL事件 _dispatchAgency(_lastHover, config.EVENT.MOUSEWHEEL); _mouseMoveHandler(_event); } /** * 鼠标(手指)移动响应函数 * @param {event} event dom事件对象 */ function _mouseMoveHandler(event) { if (painter.isLoading()) { return; } _event = _zrenderEventFixed(event); _lastX = _mouseX; _lastY = _mouseY; _mouseX = getX(_event); _mouseY = getY(_event); // 可能出现config.EVENT.DRAGSTART事件 // 避免手抖点击误认为拖拽 //if (_mouseX - _lastX > 1 || _mouseY - _lastY > 1) { _dragStartHandler(); //} _hasfound = false; storage.iterShape(_findHover, { normal: 'down'}); //找到的在迭代函数里做了处理,没找到得在迭代完后处理 if (!_hasfound) { //过滤首次拖拽产生的mouseout和dragLeave if (!_draggingTarget || (_lastHover && _lastHover.id != _draggingTarget.id) ) { //可能出现config.EVENT.MOUSEOUT事件 _outShapeHandler(); //可能出现config.EVENT.DRAGLEAVE事件 _dragLeaveHandler(); } _lastHover = null; storage.delHover(); painter.clearHover(); } //如果存在拖拽中元素,被拖拽的图形元素最后addHover if (_draggingTarget) { storage.drift( _draggingTarget.id, _mouseX - _lastX, _mouseY - _lastY ); storage.addHover(_draggingTarget); } if (_draggingTarget || (_hasfound && _lastHover.draggable)) { root.style.cursor = 'move'; } else if (_hasfound && _lastHover.clickable) { root.style.cursor = 'pointer'; } else { root.style.cursor = 'default'; } //分发config.EVENT.MOUSEMOVE事件 _dispatchAgency(_lastHover, config.EVENT.MOUSEMOVE); if (_draggingTarget || _hasfound || storage.hasHoverShape()) { painter.refreshHover(); } } /** * 鼠标(手指)离开响应函数 * @param {event} event dom事件对象 */ function _mouseOutHandler(event) { _event = _zrenderEventFixed(event); var element = _event.toElement || _event.relatedTarget; if (element != root) { while (element && element.nodeType != 9) { if (element == root) { // 忽略包含在root中的dom引起的mouseOut _mouseMoveHandler(event); return; } element = element.parentNode; } } _event.zrenderX = _lastX; _event.zrenderY = _lastY; root.style.cursor = 'default'; _isMouseDown = false; _outShapeHandler(); _dropHandler(); _dragEndHandler(); if (!painter.isLoading()) { painter.refreshHover(); } self.dispatch(config.EVENT.GLOBALOUT, _event); } /** * 鼠标在某个图形元素上移动 */ function _overShapeHandler() { //分发config.EVENT.MOUSEOVER事件 _dispatchAgency(_lastHover, config.EVENT.MOUSEOVER); } /** * 鼠标离开某个图形元素 */ function _outShapeHandler() { //分发config.EVENT.MOUSEOUT事件 _dispatchAgency(_lastHover, config.EVENT.MOUSEOUT); } /** * 鼠标(手指)按下响应函数 * @param {event} event dom事件对象 */ function _mouseDownHandler(event) { _event = _zrenderEventFixed(event); _isMouseDown = true; //分发config.EVENT.MOUSEDOWN事件 _mouseDownTarget = _lastHover; _dispatchAgency(_lastHover, config.EVENT.MOUSEDOWN); } /** * 鼠标(手指)抬起响应函数 * @param {event} event dom事件对象 */ function _mouseUpHandler(event) { _event = _zrenderEventFixed(event); root.style.cursor = 'default'; _isMouseDown = false; _mouseDownTarget = null; //分发config.EVENT.MOUSEUP事件 _dispatchAgency(_lastHover, config.EVENT.MOUSEUP); _dropHandler(); _dragEndHandler(); } /** * Touch开始响应函数 * @param {event} event dom事件对象 */ function _touchStartHandler(event) { //eventTool.stop(event);// 阻止浏览器默认事件,重要 _event = _zrenderEventFixed(event, true); _lastTouchMoment = new Date(); _mouseDownHandler(_event); } /** * Touch移动响应函数 * @param {event} event dom事件对象 */ function _touchMoveHandler(event) { _event = _zrenderEventFixed(event, true); _mouseMoveHandler(_event); if (_isDragging) { eventTool.stop(event);// 阻止浏览器默认事件,重要 } } /** * Touch结束响应函数 * @param {event} event dom事件对象 */ function _touchEndHandler(event) { //eventTool.stop(event);// 阻止浏览器默认事件,重要 _event = _zrenderEventFixed(event, true); _mouseUpHandler(_event); painter.clearHover(); if (new Date() - _lastTouchMoment < config.EVENT.touchClickDelay ) { _lastHover = null; _mouseX = _event.zrenderX; _mouseY = _event.zrenderY; // touch有指尖错觉,四向尝试,让touch上的点击更好触发事件 storage.iterShape(_findHover, { normal: 'down'}); if (!_lastHover) { _mouseX += 10; storage.iterShape(_findHover, { normal: 'down'}); } if (!_lastHover) { _mouseX -= 20; storage.iterShape(_findHover, { normal: 'down'}); } if (!_lastHover) { _mouseX += 10; _mouseY += 10; storage.iterShape(_findHover, { normal: 'down'}); } if (!_lastHover) { _mouseY -= 20; storage.iterShape(_findHover, { normal: 'down'}); } if (_lastHover) { _event.zrenderX = _mouseX; _event.zrenderY = _mouseY; } _clickHandler(_event); } } /** * 拖拽开始 */ function _dragStartHandler() { if (_isMouseDown && _lastHover && _lastHover.draggable && !_draggingTarget && _mouseDownTarget == _lastHover ) { _draggingTarget = _lastHover; _isDragging = true; _draggingTarget.invisible = true; storage.mod(_draggingTarget.id,_draggingTarget); //分发config.EVENT.DRAGSTART事件 _dispatchAgency( _draggingTarget, config.EVENT.DRAGSTART ); painter.refresh(); } } /** * 拖拽进入目标元素 */ function _dragEnterHandler() { if (_draggingTarget) { //分发config.EVENT.DRAGENTER事件 _dispatchAgency( _lastHover, config.EVENT.DRAGENTER, _draggingTarget ); } } /** * 拖拽在目标元素上移动 */ function _dragOverHandler() { if (_draggingTarget) { //分发config.EVENT.DRAGOVER事件 _dispatchAgency( _lastHover, config.EVENT.DRAGOVER, _draggingTarget ); } } /** * 拖拽离开目标元素 */ function _dragLeaveHandler() { if (_draggingTarget) { //分发config.EVENT.DRAGLEAVE事件 _dispatchAgency( _lastHover, config.EVENT.DRAGLEAVE, _draggingTarget ); } } /** * 拖拽在目标元素上完成 */ function _dropHandler() { if (_draggingTarget) { _draggingTarget.invisible = false; storage.mod(_draggingTarget.id,_draggingTarget); painter.refresh(); //分发config.EVENT.DROP事件 _dispatchAgency( _lastHover, config.EVENT.DROP, _draggingTarget ); } } /** * 拖拽结束 */ function _dragEndHandler() { if (_draggingTarget) { //分发config.EVENT.DRAGEND事件 _dispatchAgency( _draggingTarget, config.EVENT.DRAGEND ); _lastHover = null; } _isDragging = false; _draggingTarget = null; } /** * 事件分发代理 * @param {Object} targetShape 目标图形元素 * @param {string} eventName 事件名称 * @param {Object=} draggedShape 拖拽事件特有,当前被拖拽图形元素 */ function _dispatchAgency(targetShape, eventName, draggedShape) { var eventHandler = 'on' + eventName; var eventPacket = { type : eventName, event : _event, target : targetShape }; if (draggedShape) { eventPacket.dragged = draggedShape; } if (targetShape) { //“不存在shape级事件”或“存在shape级事件但事件回调返回非true” if (!targetShape[eventHandler] || !targetShape[eventHandler](eventPacket) ) { self.dispatch( eventName, _event, eventPacket ); } } else if (!draggedShape) { //无hover目标,无拖拽对象,原生事件分发 self.dispatch(eventName, _event); } } /** * 迭代函数,查找hover到的图形元素并即时做些事件分发 * @param {Object} e 图形元素 */ function _findHover(e) { if (_draggingTarget && _draggingTarget.id == e.id) { //迭代到当前拖拽的图形上 return false; } //打酱油的路过,啥都不响应的shape~ if (e.__silent) { return false; } var shapeInstance = shape.get(e.shape); if (shapeInstance.isCover(e, _mouseX, _mouseY)) { if (e.hoverable) { storage.addHover(e); } if (_lastHover != e) { _outShapeHandler(); //可能出现config.EVENT.DRAGLEAVE事件 _dragLeaveHandler(); _lastHover = e; //可能出现config.EVENT.DRAGENTER事件 _dragEnterHandler(); } _overShapeHandler(); //可能出现config.EVENT.DRAGOVER _dragOverHandler(); _hasfound = true; return true; //找到则中断迭代查找 } return false; } // 如果存在第三方嵌入的一些dom触发的事件,或touch事件,需要转换一下事件坐标 function _zrenderEventFixed(event, isTouch) { if (!isTouch) { _event = event || window.event; // 进入对象优先~ var target = _event.toElement || _event.relatedTarget || _event.srcElement || _event.target; if (target && target != _domHover) { _event.zrenderX = (typeof _event.offsetX != 'undefined' ? _event.offsetX : _event.layerX) + target.offsetLeft; _event.zrenderY = (typeof _event.offsetY != 'undefined' ? _event.offsetY : _event.layerY) + target.offsetTop; } } else { _event = event; var touch = _event.type != 'touchend' ? _event.targetTouches[0] : _event.changedTouches[0]; if (touch) { // touch事件坐标是全屏的~ _event.zrenderX = touch.clientX - root.offsetLeft + document.body.scrollLeft; _event.zrenderY = touch.clientY - root.offsetTop + document.body.scrollTop; } } return _event; } /** * 自定义事件绑定 * @param {string} eventName 事件名称,resize,hover,drag,etc~ * @param {Function} handler 响应函数 */ function on(eventName, handler) { self.bind(eventName, handler); return self; } /** * 自定义事件解绑 * @param {string} event 事件名称,resize,hover,drag,etc~ * @param {Function} handler 响应函数 */ function un(eventName, handler) { self.unbind(eventName, handler); return self; } /** * 比较不可控,先不开放了~ * 触发原生dom事件,用于自定义元素在顶层截获事件后触发zrender行为 * @param {string} event 事件名称,resize,hover,drag,etc~ * @param {event=} event event dom事件对象 function trigger(eventName, event) { switch (eventName) { case config.EVENT.RESIZE : _resizeHandler(event); break; case config.EVENT.CLICK : _clickHandler(event); break; case config.EVENT.MOUSEWHEEL : _mouseWheelHandler(event); break; case config.EVENT.MOUSEMOVE : _mouseMoveHandler(event); break; case config.EVENT.MOUSEDOWN : _mouseDownHandler(event); break; case config.EVENT.MOUSEUP : _mouseUpHandleru(event); break; } } */ /** * 释放 */ function dispose() { if (window.removeEventListener) { window.removeEventListener('resize', _resizeHandler); root.removeEventListener('click', _clickHandler); root.removeEventListener('mousewheel', _mouseWheelHandler); root.removeEventListener( 'DOMMouseScroll', _mouseWheelHandler ); root.removeEventListener('mousemove', _mouseMoveHandler); root.removeEventListener('mouseout', _mouseOutHandler); root.removeEventListener('mousedown', _mouseDownHandler); root.removeEventListener('mouseup', _mouseUpHandler); // mobile支持 root.removeEventListener('touchstart', _touchStartHandler); root.removeEventListener('touchmove', _touchMoveHandler); root.removeEventListener('touchend', _touchEndHandler); } else { window.detachEvent('onresize', _resizeHandler); root.detachEvent('onclick', _clickHandler); root.detachEvent('onmousewheel', _mouseWheelHandler); root.detachEvent('onmousemove', _mouseMoveHandler); root.detachEvent('onmouseout', _mouseOutHandler); root.detachEvent('onmousedown', _mouseDownHandler); root.detachEvent('onmouseup', _mouseUpHandler); } root = null; _domHover = null; storage = null; painter = null; shape = null; un(); self = null; return; } self.on = on; self.un = un; // self.trigger = trigger; self.dispose = dispose; _init(); } return self; } ); define('zrender', ['zrender/zrender'], function (main) { return main; });
Clazz.declarePackage ("J.api"); Clazz.declareInterface (J.api, "JmolRepaintManager");
module.exports={"title":"Kirby","hex":"FF0100","source":"http://getkirby.com/assets/images/logo.svg","svg":"<svg aria-labelledby=\"simpleicons-kirby-icon\" role=\"img\" viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\"><title id=\"simpleicons-kirby-icon\">Kirby icon</title><path d=\"M12 0L1.428 6v12L12 24l10.573-6V6L12 0zm4.709 12.255l-2.963 1.598v.219h2.965v2.325H7.29v-2.312h2.955v-.225l-2.963-1.605V9.39L12 11.933l4.715-2.545v2.865l-.006.002z\"/></svg>"};
/* Project: angular-gantt v1.3.2 - Gantt chart component for AngularJS Authors: Marco Schweighauser, Rémi Alvergnat License: MIT Homepage: https://www.angular-gantt.com Github: https://github.com/angular-gantt/angular-gantt.git */ (function(){ 'use strict'; angular.module('gantt.labels', ['gantt', 'gantt.labels.templates']).directive('ganttLabels', ['ganttUtils', '$compile', '$document', '$log', function(utils, $compile, $document, $log) { // Provides the row sort functionality to any Gantt row // Uses the sortableState to share the current row return { restrict: 'E', require: '^gantt', scope: { enabled: '=?', header: '=?' }, link: function(scope, element, attrs, ganttCtrl) { var api = ganttCtrl.gantt.api; $log.warn('Angular Gantt Labels plugin is deprecated. Please use Table plugin instead.'); // Load options from global options attribute. if (scope.options && typeof(scope.options.labels) === 'object') { for (var option in scope.options.labels) { scope[option] = scope.options.labels[option]; } } if (scope.enabled === undefined) { scope.enabled = true; } if (scope.header === undefined) { scope.header = 'Name'; } api.directives.on.new(scope, function(directiveName, sideContentScope, sideContentElement) { if (directiveName === 'ganttSideContent') { var labelsScope = sideContentScope.$new(); labelsScope.pluginScope = scope; var ifElement = $document[0].createElement('div'); angular.element(ifElement).attr('data-ng-if', 'pluginScope.enabled'); angular.element(ifElement).addClass('side-element'); var labelsElement = $document[0].createElement('gantt-side-content-labels'); angular.element(ifElement).append(labelsElement); sideContentElement.append($compile(ifElement)(labelsScope)); } }); function fitSideWidthToLabels() { var labels = ganttCtrl.gantt.side.$element[0].getElementsByClassName('gantt-row-label'); var newSideWidth = 0; for (var i=0; i<labels.length; i++) { var width = labels[i].children[0].offsetWidth; newSideWidth = Math.max(newSideWidth, width); } if (newSideWidth >= 0) { api.side.setWidth(newSideWidth); } } api.registerMethod('labels', 'fitSideWidth', fitSideWidthToLabels, this); } }; }]); }()); (function(){ 'use strict'; angular.module('gantt.labels').directive('ganttLabelsBody', ['GanttDirectiveBuilder', 'ganttLayout', function(Builder, layout) { var builder = new Builder('ganttLabelsBody', 'plugins/labels/labelsBody.tmpl.html'); builder.controller = function($scope) { var hScrollBarHeight = layout.getScrollBarHeight(); $scope.getLabelsCss = function() { var css = {}; var maxHeight = $scope.maxHeight; if (!maxHeight) { maxHeight = $scope.gantt.getContainerHeight(); } var bodyScrollBarHeight = $scope.gantt.scroll.isHScrollbarVisible() ? hScrollBarHeight : 0; css['max-height'] = maxHeight - bodyScrollBarHeight - $scope.gantt.header.getHeight() + 'px'; return css; }; }; return builder.build(); }]); }()); (function(){ 'use strict'; angular.module('gantt.labels').directive('ganttLabelsHeader', ['GanttDirectiveBuilder', function(Builder) { var builder = new Builder('ganttLabelsHeader', 'plugins/labels/labelsHeader.tmpl.html'); return builder.build(); }]); }()); (function(){ 'use strict'; angular.module('gantt.labels').directive('ganttSideContentLabels', ['GanttDirectiveBuilder', function(Builder) { var builder = new Builder('ganttSideContentLabels', 'plugins/labels/sideContentLabels.tmpl.html'); return builder.build(); }]); }()); angular.module('gantt.labels.templates', []).run(['$templateCache', function ($templateCache) { $templateCache.put('plugins/labels/labelsBody.tmpl.html', '<div class="gantt-labels-body" ng-style="getLabelsCss()">\n' + ' <div gantt-vertical-scroll-receiver>\n' + ' <div ng-repeat="row in gantt.rowsManager.visibleRows track by row.model.id">\n' + ' <div gantt-row-label\n' + ' class="gantt-row-label gantt-row-height"\n' + ' ng-class="row.model.classes"\n' + ' ng-style="{\'height\': row.model.height}">\n' + ' <span class="gantt-label-text">{{row.model.name}}</span>\n' + ' </div>\n' + ' </div>\n' + ' </div>\n' + '</div>\n' + ''); $templateCache.put('plugins/labels/labelsHeader.tmpl.html', '<div class="gantt-labels-header">\n' + ' <div ng-show="gantt.columnsManager.columns.length > 0 && gantt.columnsManager.headers.length > 0">\n' + ' <div ng-repeat="header in gantt.columnsManager.headers">\n' + ' <div class="gantt-row-height" ng-class="{\'gantt-labels-header-row\': $last, \'gantt-labels-header-row-last\': $last}"><span>{{$last ? pluginScope.header : ""}}</span></div>\n' + ' </div>\n' + ' </div>\n' + '</div>\n' + ''); $templateCache.put('plugins/labels/sideContentLabels.tmpl.html', '<div class="gantt-side-content-labels">\n' + ' <gantt-labels-header>\n' + ' </gantt-labels-header>\n' + ' <gantt-labels-body>\n' + ' </gantt-labels-body>\n' + '</div>\n' + ''); }]); //# sourceMappingURL=angular-gantt-labels-plugin.js.map
import React, { Component } from 'react' import Slider from '../src/slider' export default class FocusOnSelect extends Component { render() { const settings = { focusOnSelect: true, infinite: true, slidesToShow: 3, slidesToScroll: 1, speed: 500 }; return ( <div> <h2>FocusOnSelect</h2> <div>Click on any slide to select and make it current slide</div> <Slider {...settings}> <div><h3>1</h3></div> <div><h3>2</h3></div> <div><h3>3</h3></div> <div><h3>4</h3></div> <div><h3>5</h3></div> <div><h3>6</h3></div> </Slider> </div> ); } }
/** * filesize * * @author Jason Mulligan <jason.mulligan@avoidwork.com> * @copyright 2015 Jason Mulligan * @license BSD-3 <https://raw.github.com/avoidwork/filesize.js/master/LICENSE> * @link http://filesizejs.com * @module filesize * @version 3.0.0 */ ( function ( global ) { "use strict"; var bit = /b$/; /** * filesize * * @method filesize * @param {Mixed} arg String, Int or Float to transform * @param {Object} descriptor [Optional] Flags * @return {String} Readable file size String */ function filesize ( arg, descriptor ) { var result = [], skip = false, val = 0, e, base, bits, ceil, neg, num, output, round, unix, spacer, suffixes; if ( isNaN( arg ) ) { throw new Error( "Invalid arguments" ); } descriptor = descriptor || {}; bits = ( descriptor.bits === true ); unix = ( descriptor.unix === true ); base = descriptor.base !== undefined ? descriptor.base : 2; round = descriptor.round !== undefined ? descriptor.round : unix ? 1 : 2; spacer = descriptor.spacer !== undefined ? descriptor.spacer : unix ? "" : " "; suffixes = descriptor.suffixes !== undefined ? descriptor.suffixes : {}; output = descriptor.output !== undefined ? descriptor.output : "string"; num = Number( arg ); neg = ( num < 0 ); ceil = base > 2 ? 1000 : 1024; // Flipping a negative number to determine the size if ( neg ) { num = -num; } // Zero is now a special case because bytes divide by 1 if ( num === 0 ) { result[ 0 ] = 0; if ( unix ) { result[ 1 ] = ""; } else { result[ 1 ] = "B"; } } else { e = Math.floor( Math.log( num ) / Math.log( 1000 ) ); // Exceeding supported length, time to reduce & multiply if ( e > 8 ) { val = val * ( 1000 * ( e - 8 ) ); e = 8; } if ( base === 2 ) { val = num / Math.pow( 2, ( e * 10 ) ); } else { val = num / Math.pow( 1000, e ); } if ( bits ) { val = ( val * 8 ); if ( val > ceil ) { val = val / ceil; e++; } } result[ 0 ] = Number( val.toFixed( e > 0 ? round : 0 ) ); result[ 1 ] = si[ bits ? "bits" : "bytes" ][ e ]; if ( !skip && unix ) { if ( bits && bit.test( result[ 1 ] ) ) { result[ 1 ] = result[ 1 ].toLowerCase(); } result[ 1 ] = result[ 1 ].charAt( 0 ); if ( result[ 1 ] === "B" ) { result[ 0 ] = Math.floor( result[ 0 ] ); result[ 1 ] = ""; } else if ( !bits && result[ 1 ] === "k" ) { result[ 1 ] = "K"; } } } // Decorating a 'diff' if ( neg ) { result[ 0 ] = -result[ 0 ]; } // Applying custom suffix result[ 1 ] = suffixes[ result[ 1 ] ] || result[ 1 ]; // Returning Array, Object, or String (default) if ( output === "array" ) { return result; } else if ( output === "object" ) { return { value: result[ 0 ], suffix: result[ 1 ] }; } else { return result.join( spacer ); } } /** * SI suffixes * * @type {Object} */ var si = { bits: [ "B", "kb", "Mb", "Gb", "Tb", "Pb", "Eb", "Zb", "Yb" ], bytes: [ "B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" ] }; // CommonJS, AMD, script tag if ( typeof exports !== "undefined" ) { module.exports = filesize; } else if ( typeof define === "function" ) { define( function () { return filesize; } ); } else { global.filesize = filesize; } } )( this );
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v9.0.0 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var eventService_1 = require("../eventService"); var events_1 = require("../events"); var gridOptionsWrapper_1 = require("../gridOptionsWrapper"); var selectionController_1 = require("../selectionController"); var valueService_1 = require("../valueService"); var columnController_1 = require("../columnController/columnController"); var context_1 = require("../context/context"); var constants_1 = require("../constants"); var utils_1 = require("../utils"); var RowNode = (function () { function RowNode() { /** Children mapped by the pivot columns */ this.childrenMapped = {}; this.selected = false; } RowNode.prototype.setData = function (data) { var oldData = this.data; this.data = data; var event = { oldData: oldData, newData: data }; this.dispatchLocalEvent(RowNode.EVENT_DATA_CHANGED, event); }; RowNode.prototype.createDaemonNode = function () { var oldNode = new RowNode(); this.context.wireBean(oldNode); // just copy the id and data, this is enough for the node to be used // in the selection controller (the selection controller is the only // place where daemon nodes can live). oldNode.id = this.id; oldNode.data = this.data; oldNode.daemon = true; oldNode.selected = this.selected; oldNode.level = this.level; return oldNode; }; RowNode.prototype.setDataAndId = function (data, id) { var oldNode = utils_1.Utils.exists(this.id) ? this.createDaemonNode() : null; var oldData = this.data; this.data = data; this.setId(id); this.selectionController.syncInRowNode(this, oldNode); var event = { oldData: oldData, newData: data }; this.dispatchLocalEvent(RowNode.EVENT_DATA_CHANGED, event); }; RowNode.prototype.setId = function (id) { // see if user is providing the id's var getRowNodeId = this.gridOptionsWrapper.getRowNodeIdFunc(); if (getRowNodeId) { // if user is providing the id's, then we set the id only after the data has been set. // this is important for virtual pagination and viewport, where empty rows exist. if (this.data) { this.id = getRowNodeId(this.data); } else { // this can happen if user has set blank into the rowNode after the row previously // having data. this happens in virtual page row model, when data is delete and // the page is refreshed. this.id = undefined; } } else { this.id = id; } }; RowNode.prototype.setLoading = function (loading) { if (this.loading === loading) { return; } this.loading = loading; if (this.eventService) { this.eventService.dispatchEvent(RowNode.EVENT_LOADING_CHANGED); } }; RowNode.prototype.clearRowTop = function () { this.oldRowTop = this.rowTop; this.setRowTop(null); }; RowNode.prototype.setRowTop = function (rowTop) { if (this.rowTop === rowTop) { return; } this.rowTop = rowTop; if (this.eventService) { this.eventService.dispatchEvent(RowNode.EVENT_TOP_CHANGED); } }; RowNode.prototype.setRowHeight = function (rowHeight) { this.rowHeight = rowHeight; if (this.eventService) { this.eventService.dispatchEvent(RowNode.EVENT_HEIGHT_CHANGED); } }; RowNode.prototype.setRowIndex = function (rowIndex) { this.rowIndex = rowIndex; if (this.eventService) { this.eventService.dispatchEvent(RowNode.EVENT_ROW_INDEX_CHANGED); } }; RowNode.prototype.setExpanded = function (expanded) { if (this.expanded === expanded) { return; } this.expanded = expanded; if (this.eventService) { this.eventService.dispatchEvent(RowNode.EVENT_EXPANDED_CHANGED); } var event = { node: this }; this.mainEventService.dispatchEvent(events_1.Events.EVENT_ROW_GROUP_OPENED, event); }; RowNode.prototype.dispatchLocalEvent = function (eventName, event) { if (this.eventService) { this.eventService.dispatchEvent(eventName, event); } }; // we also allow editing the value via the editors. when it is done via // the editors, no 'cell changed' event gets fired, as it's assumed that // the cell knows about the change given it's in charge of the editing. // this method is for the client to call, so the cell listens for the change // event, and also flashes the cell when the change occurs. RowNode.prototype.setDataValue = function (colKey, newValue) { var column = this.columnController.getGridColumn(colKey); this.valueService.setValue(this, column, newValue); var event = { column: column, newValue: newValue }; this.dispatchLocalEvent(RowNode.EVENT_CELL_CHANGED, event); }; RowNode.prototype.resetQuickFilterAggregateText = function () { this.quickFilterAggregateText = null; }; RowNode.prototype.isExpandable = function () { return this.group || this.canFlower; }; RowNode.prototype.isSelected = function () { // for footers, we just return what our sibling selected state is, as cannot select a footer if (this.footer) { return this.sibling.isSelected(); } return this.selected; }; RowNode.prototype.depthFirstSearch = function (callback) { if (this.childrenAfterGroup) { this.childrenAfterGroup.forEach(function (child) { return child.depthFirstSearch(callback); }); } callback(this); }; // + rowController.updateGroupsInSelection() RowNode.prototype.calculateSelectedFromChildren = function () { var atLeastOneSelected = false; var atLeastOneDeSelected = false; var atLeastOneMixed = false; var newSelectedValue; if (this.childrenAfterGroup) { for (var i = 0; i < this.childrenAfterGroup.length; i++) { var childState = this.childrenAfterGroup[i].isSelected(); switch (childState) { case true: atLeastOneSelected = true; break; case false: atLeastOneDeSelected = true; break; default: atLeastOneMixed = true; break; } } } if (atLeastOneMixed) { newSelectedValue = undefined; } else if (atLeastOneSelected && !atLeastOneDeSelected) { newSelectedValue = true; } else if (!atLeastOneSelected && atLeastOneDeSelected) { newSelectedValue = false; } else { newSelectedValue = undefined; } this.selectThisNode(newSelectedValue); }; RowNode.prototype.calculateSelectedFromChildrenBubbleUp = function () { this.calculateSelectedFromChildren(); if (this.parent) { this.parent.calculateSelectedFromChildrenBubbleUp(); } }; RowNode.prototype.setSelectedInitialValue = function (selected) { this.selected = selected; }; RowNode.prototype.setSelected = function (newValue, clearSelection, tailingNodeInSequence) { if (clearSelection === void 0) { clearSelection = false; } if (tailingNodeInSequence === void 0) { tailingNodeInSequence = false; } this.setSelectedParams({ newValue: newValue, clearSelection: clearSelection, tailingNodeInSequence: tailingNodeInSequence, rangeSelect: false }); }; RowNode.prototype.isFloating = function () { return this.floating === constants_1.Constants.FLOATING_TOP || this.floating === constants_1.Constants.FLOATING_BOTTOM; }; // to make calling code more readable, this is the same method as setSelected except it takes names parameters RowNode.prototype.setSelectedParams = function (params) { var groupSelectsChildren = this.gridOptionsWrapper.isGroupSelectsChildren(); var newValue = params.newValue === true; var clearSelection = params.clearSelection === true; var tailingNodeInSequence = params.tailingNodeInSequence === true; var rangeSelect = params.rangeSelect === true; // groupSelectsFiltered only makes sense when group selects children var groupSelectsFiltered = groupSelectsChildren && (params.groupSelectsFiltered === true); if (this.id === undefined) { console.warn('ag-Grid: cannot select node until id for node is known'); return 0; } if (this.floating) { console.log('ag-Grid: cannot select floating rows'); return 0; } // if we are a footer, we don't do selection, just pass the info // to the sibling (the parent of the group) if (this.footer) { var count = this.sibling.setSelectedParams(params); return count; } if (rangeSelect) { var rowModelNormal = this.rowModel.getType() === constants_1.Constants.ROW_MODEL_TYPE_NORMAL; var newRowClicked = this.selectionController.getLastSelectedNode() !== this; var allowMultiSelect = this.gridOptionsWrapper.isRowSelectionMulti(); if (rowModelNormal && newRowClicked && allowMultiSelect) { return this.doRowRangeSelection(); } } var updatedCount = 0; // when groupSelectsFiltered, then this node may end up intermediate despite // trying to set it to true / false. this group will be calculated further on // down when we call calculatedSelectedForAllGroupNodes(). we need to skip it // here, otherwise the updatedCount would include it. var skipThisNode = groupSelectsFiltered && this.group; if (!skipThisNode) { var thisNodeWasSelected = this.selectThisNode(newValue); if (thisNodeWasSelected) { updatedCount++; } } if (groupSelectsChildren && this.group) { updatedCount += this.selectChildNodes(newValue, groupSelectsFiltered); } // clear other nodes if not doing multi select var actionWasOnThisNode = !tailingNodeInSequence; if (actionWasOnThisNode) { if (newValue && (clearSelection || !this.gridOptionsWrapper.isRowSelectionMulti())) { updatedCount += this.selectionController.clearOtherNodes(this); } // only if we selected something, then update groups and fire events if (updatedCount > 0) { // update groups if (groupSelectsFiltered) { // if the group was selecting filtered, then all nodes above and or below // this node could have check, unchecked or intermediate, so easiest is to // recalculate selected state for all group nodes this.calculatedSelectedForAllGroupNodes(); } else { // if no selecting filtered, then everything below the group node was either // selected or not selected, no intermediate, so no need to check items below // this one, just the parents all the way up to the root if (groupSelectsChildren && this.parent) { this.parent.calculateSelectedFromChildrenBubbleUp(); } } // fire events // this is the very end of the 'action node', so we are finished all the updates, // include any parent / child changes that this method caused this.mainEventService.dispatchEvent(events_1.Events.EVENT_SELECTION_CHANGED); } // so if user next does shift-select, we know where to start the selection from if (newValue) { this.selectionController.setLastSelectedNode(this); } } return updatedCount; }; // selects all rows between this node and the last selected node (or the top if this is the first selection). // not to be mixed up with 'cell range selection' where you drag the mouse, this is row range selection, by // holding down 'shift'. RowNode.prototype.doRowRangeSelection = function () { var _this = this; var lastSelectedNode = this.selectionController.getLastSelectedNode(); // if lastSelectedNode is missing, we start at the first row var firstRowHit = !lastSelectedNode; var lastRowHit = false; var lastRow; var groupsSelectChildren = this.gridOptionsWrapper.isGroupSelectsChildren(); var updatedCount = 0; var inMemoryRowModel = this.rowModel; inMemoryRowModel.forEachNodeAfterFilterAndSort(function (rowNode) { var lookingForLastRow = firstRowHit && !lastRowHit; // check if we need to flip the select switch if (!firstRowHit) { if (rowNode === lastSelectedNode || rowNode === _this) { firstRowHit = true; } } var skipThisGroupNode = rowNode.group && groupsSelectChildren; if (!skipThisGroupNode) { var inRange = firstRowHit && !lastRowHit; var childOfLastRow = rowNode.isParentOfNode(lastRow); var nodeWasSelected = rowNode.selectThisNode(inRange || childOfLastRow); if (nodeWasSelected) { updatedCount++; } } if (lookingForLastRow) { if (rowNode === lastSelectedNode || rowNode === _this) { lastRowHit = true; if (rowNode === lastSelectedNode) { lastRow = lastSelectedNode; } else { lastRow = _this; } } } }); if (groupsSelectChildren) { this.calculatedSelectedForAllGroupNodes(); } this.mainEventService.dispatchEvent(events_1.Events.EVENT_SELECTION_CHANGED); return updatedCount; }; RowNode.prototype.isParentOfNode = function (potentialParent) { var parentNode = this.parent; while (parentNode) { if (parentNode === potentialParent) { return true; } parentNode = parentNode.parent; } return false; }; RowNode.prototype.calculatedSelectedForAllGroupNodes = function () { // we have to make sure we do this dept first, as parent nodes // will have dependencies on the children having correct values var inMemoryRowModel = this.rowModel; inMemoryRowModel.getTopLevelNodes().forEach(function (topLevelNode) { if (topLevelNode.group) { topLevelNode.depthFirstSearch(function (childNode) { if (childNode.group) { childNode.calculateSelectedFromChildren(); } }); topLevelNode.calculateSelectedFromChildren(); } }); }; RowNode.prototype.selectThisNode = function (newValue) { if (this.selected === newValue) { return false; } this.selected = newValue; if (this.eventService) { this.dispatchLocalEvent(RowNode.EVENT_ROW_SELECTED); } var event = { node: this }; this.mainEventService.dispatchEvent(events_1.Events.EVENT_ROW_SELECTED, event); return true; }; RowNode.prototype.selectChildNodes = function (newValue, groupSelectsFiltered) { var children = groupSelectsFiltered ? this.childrenAfterFilter : this.childrenAfterGroup; var updatedCount = 0; if (utils_1.Utils.missing(children)) { return; } for (var i = 0; i < children.length; i++) { updatedCount += children[i].setSelectedParams({ newValue: newValue, clearSelection: false, tailingNodeInSequence: true }); } return updatedCount; }; RowNode.prototype.addEventListener = function (eventType, listener) { if (!this.eventService) { this.eventService = new eventService_1.EventService(); } this.eventService.addEventListener(eventType, listener); }; RowNode.prototype.removeEventListener = function (eventType, listener) { this.eventService.removeEventListener(eventType, listener); }; RowNode.prototype.onMouseEnter = function () { this.dispatchLocalEvent(RowNode.EVENT_MOUSE_ENTER); }; RowNode.prototype.onMouseLeave = function () { this.dispatchLocalEvent(RowNode.EVENT_MOUSE_LEAVE); }; return RowNode; }()); RowNode.EVENT_ROW_SELECTED = 'rowSelected'; RowNode.EVENT_DATA_CHANGED = 'dataChanged'; RowNode.EVENT_CELL_CHANGED = 'cellChanged'; RowNode.EVENT_MOUSE_ENTER = 'mouseEnter'; RowNode.EVENT_MOUSE_LEAVE = 'mouseLeave'; RowNode.EVENT_HEIGHT_CHANGED = 'heightChanged'; RowNode.EVENT_TOP_CHANGED = 'topChanged'; RowNode.EVENT_ROW_INDEX_CHANGED = 'rowIndexChanged'; RowNode.EVENT_EXPANDED_CHANGED = 'expandedChanged'; RowNode.EVENT_LOADING_CHANGED = 'loadingChanged'; __decorate([ context_1.Autowired('eventService'), __metadata("design:type", eventService_1.EventService) ], RowNode.prototype, "mainEventService", void 0); __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper) ], RowNode.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.Autowired('selectionController'), __metadata("design:type", selectionController_1.SelectionController) ], RowNode.prototype, "selectionController", void 0); __decorate([ context_1.Autowired('columnController'), __metadata("design:type", columnController_1.ColumnController) ], RowNode.prototype, "columnController", void 0); __decorate([ context_1.Autowired('valueService'), __metadata("design:type", valueService_1.ValueService) ], RowNode.prototype, "valueService", void 0); __decorate([ context_1.Autowired('rowModel'), __metadata("design:type", Object) ], RowNode.prototype, "rowModel", void 0); __decorate([ context_1.Autowired('context'), __metadata("design:type", context_1.Context) ], RowNode.prototype, "context", void 0); exports.RowNode = RowNode;
angular.module('bottomSheetDemo1', ['ngMaterial']) .config(function($mdIconProvider) { $mdIconProvider .icon('share-arrow', 'img/icons/share-arrow.svg', 24) .icon('upload', 'img/icons/upload.svg', 24) .icon('copy', 'img/icons/copy.svg', 24) .icon('print', 'img/icons/print.svg', 24) .icon('hangout', 'img/icons/hangout.svg', 24) .icon('mail', 'img/icons/mail.svg', 24) .icon('message', 'img/icons/message.svg', 24) .icon('copy2', 'img/icons/copy2.svg', 24) .icon('facebook', 'img/icons/facebook.svg', 24) .icon('twitter', 'img/icons/twitter.svg', 24); }) .controller('BottomSheetExample', function($scope, $timeout, $mdBottomSheet, $mdToast) { $scope.alert = ''; $scope.showListBottomSheet = function() { $scope.alert = ''; $mdBottomSheet.show({ templateUrl: 'bottom-sheet-list-template.html', controller: 'ListBottomSheetCtrl' }).then(function(clickedItem) { $scope.alert = clickedItem['name'] + ' clicked!'; }); }; $scope.showGridBottomSheet = function() { $scope.alert = ''; $mdBottomSheet.show({ templateUrl: 'bottom-sheet-grid-template.html', controller: 'GridBottomSheetCtrl', clickOutsideToClose: false }).then(function(clickedItem) { $mdToast.show( $mdToast.simple() .textContent(clickedItem['name'] + ' clicked!') .position('top right') .hideDelay(1500) ); }); }; }) .controller('ListBottomSheetCtrl', function($scope, $mdBottomSheet) { $scope.items = [ { name: 'Share', icon: 'share-arrow' }, { name: 'Upload', icon: 'upload' }, { name: 'Copy', icon: 'copy' }, { name: 'Print this page', icon: 'print' }, ]; $scope.listItemClick = function($index) { var clickedItem = $scope.items[$index]; $mdBottomSheet.hide(clickedItem); }; }) .controller('GridBottomSheetCtrl', function($scope, $mdBottomSheet) { $scope.items = [ { name: 'Hangout', icon: 'hangout' }, { name: 'Mail', icon: 'mail' }, { name: 'Message', icon: 'message' }, { name: 'Copy', icon: 'copy2' }, { name: 'Facebook', icon: 'facebook' }, { name: 'Twitter', icon: 'twitter' }, ]; $scope.listItemClick = function($index) { var clickedItem = $scope.items[$index]; $mdBottomSheet.hide(clickedItem); }; }) .run(function($templateRequest) { var urls = [ 'img/icons/share-arrow.svg', 'img/icons/upload.svg', 'img/icons/copy.svg', 'img/icons/print.svg', 'img/icons/hangout.svg', 'img/icons/mail.svg', 'img/icons/message.svg', 'img/icons/copy2.svg', 'img/icons/facebook.svg', 'img/icons/twitter.svg' ]; angular.forEach(urls, function(url) { $templateRequest(url); }); });
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2010, Ajax.org B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Ajax.org B.V. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ***** END LICENSE BLOCK ***** */ ace.define('ace/ext/searchbox', ['require', 'exports', 'module' , 'ace/lib/dom', 'ace/lib/lang', 'ace/lib/event', 'ace/keyboard/hash_handler', 'ace/lib/keys'], function(require, exports, module) { var dom = require("../lib/dom"); var lang = require("../lib/lang"); var event = require("../lib/event"); var searchboxCss = "\ /* ------------------------------------------------------------------------------------------\ * Editor Search Form\ * --------------------------------------------------------------------------------------- */\ .ace_search {\ background-color: #ddd;\ border: 1px solid #cbcbcb;\ border-top: 0 none;\ max-width: 297px;\ overflow: hidden;\ margin: 0;\ padding: 4px;\ padding-right: 6px;\ padding-bottom: 0;\ position: absolute;\ top: 0px;\ z-index: 99;\ }\ .ace_search.left {\ border-left: 0 none;\ border-radius: 0px 0px 5px 0px;\ left: 0;\ }\ .ace_search.right {\ border-radius: 0px 0px 0px 5px;\ border-right: 0 none;\ right: 0;\ }\ .ace_search_form, .ace_replace_form {\ border-radius: 3px;\ border: 1px solid #cbcbcb;\ float: left;\ margin-bottom: 4px;\ overflow: hidden;\ }\ .ace_search_form.ace_nomatch {\ outline: 1px solid red;\ }\ .ace_search_field {\ background-color: white;\ border-right: 1px solid #cbcbcb;\ border: 0 none;\ -webkit-box-sizing: border-box;\ -moz-box-sizing: border-box;\ box-sizing: border-box;\ display: block;\ float: left;\ height: 22px;\ outline: 0;\ padding: 0 7px;\ width: 214px;\ margin: 0;\ }\ .ace_searchbtn,\ .ace_replacebtn {\ background: #fff;\ border: 0 none;\ border-left: 1px solid #dcdcdc;\ cursor: pointer;\ display: block;\ float: left;\ height: 22px;\ margin: 0;\ padding: 0;\ position: relative;\ }\ .ace_searchbtn:last-child,\ .ace_replacebtn:last-child {\ border-top-right-radius: 3px;\ border-bottom-right-radius: 3px;\ }\ .ace_searchbtn:disabled {\ background: none;\ cursor: default;\ }\ .ace_searchbtn {\ background-position: 50% 50%;\ background-repeat: no-repeat;\ width: 27px;\ }\ .ace_searchbtn.prev {\ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAFCAYAAAB4ka1VAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADFJREFUeNpiSU1NZUAC/6E0I0yACYskCpsJiySKIiY0SUZk40FyTEgCjGgKwTRAgAEAQJUIPCE+qfkAAAAASUVORK5CYII=); \ }\ .ace_searchbtn.next {\ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAFCAYAAAB4ka1VAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADRJREFUeNpiTE1NZQCC/0DMyIAKwGJMUAYDEo3M/s+EpvM/mkKwCQxYjIeLMaELoLMBAgwAU7UJObTKsvAAAAAASUVORK5CYII=); \ }\ .ace_searchbtn_close {\ background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAcCAYAAABRVo5BAAAAZ0lEQVR42u2SUQrAMAhDvazn8OjZBilCkYVVxiis8H4CT0VrAJb4WHT3C5xU2a2IQZXJjiQIRMdkEoJ5Q2yMqpfDIo+XY4k6h+YXOyKqTIj5REaxloNAd0xiKmAtsTHqW8sR2W5f7gCu5nWFUpVjZwAAAABJRU5ErkJggg==) no-repeat 50% 0;\ border-radius: 50%;\ border: 0 none;\ color: #656565;\ cursor: pointer;\ display: block;\ float: right;\ font-family: Arial;\ font-size: 16px;\ height: 14px;\ line-height: 16px;\ margin: 5px 1px 9px 5px;\ padding: 0;\ text-align: center;\ width: 14px;\ }\ .ace_searchbtn_close:hover {\ background-color: #656565;\ background-position: 50% 100%;\ color: white;\ }\ .ace_replacebtn.prev {\ width: 54px\ }\ .ace_replacebtn.next {\ width: 27px\ }\ .ace_button {\ margin-left: 2px;\ cursor: pointer;\ -webkit-user-select: none;\ -moz-user-select: none;\ -o-user-select: none;\ -ms-user-select: none;\ user-select: none;\ overflow: hidden;\ opacity: 0.7;\ border: 1px solid rgba(100,100,100,0.23);\ padding: 1px;\ -moz-box-sizing: border-box;\ box-sizing: border-box;\ color: black;\ }\ .ace_button:hover {\ background-color: #eee;\ opacity:1;\ }\ .ace_button:active {\ background-color: #ddd;\ }\ .ace_button.checked {\ border-color: #3399ff;\ opacity:1;\ }\ .ace_search_options{\ margin-bottom: 3px;\ text-align: right;\ -webkit-user-select: none;\ -moz-user-select: none;\ -o-user-select: none;\ -ms-user-select: none;\ user-select: none;\ }"; var HashHandler = require("../keyboard/hash_handler").HashHandler; var keyUtil = require("../lib/keys"); dom.importCssString(searchboxCss, "ace_searchbox"); var html = '<div class="ace_search right">\ <button type="button" action="hide" class="ace_searchbtn_close"></button>\ <div class="ace_search_form">\ <input class="ace_search_field" placeholder="Search for" spellcheck="false"></input>\ <button type="button" action="findNext" class="ace_searchbtn next"></button>\ <button type="button" action="findPrev" class="ace_searchbtn prev"></button>\ </div>\ <div class="ace_replace_form">\ <input class="ace_search_field" placeholder="Replace with" spellcheck="false"></input>\ <button type="button" action="replace" class="ace_replacebtn">Replace</button>\ <button type="button" action="replaceAll" class="ace_replacebtn">All</button>\ </div>\ <div class="ace_search_options">\ <span action="toggleRegexpMode" class="ace_button" title="RegExp Search">.*</span>\ <span action="toggleCaseSensitive" class="ace_button" title="CaseSensitive Search">Aa</span>\ <span action="toggleWholeWords" class="ace_button" title="Whole Word Search">\\b</span>\ </div>\ </div>'.replace(/>\s+/g, ">"); var SearchBox = function(editor, range, showReplaceForm) { var div = dom.createElement("div"); div.innerHTML = html; this.element = div.firstChild; this.$init(); this.setEditor(editor); }; (function() { this.setEditor = function(editor) { editor.searchBox = this; editor.container.appendChild(this.element); this.editor = editor; }; this.$init = function() { var sb = this.element; this.searchBox = sb.querySelector(".ace_search_form"); this.replaceBox = sb.querySelector(".ace_replace_form"); this.searchOptions = sb.querySelector(".ace_search_options"); this.regExpOption = sb.querySelector("[action=toggleRegexpMode]"); this.caseSensitiveOption = sb.querySelector("[action=toggleCaseSensitive]"); this.wholeWordOption = sb.querySelector("[action=toggleWholeWords]"); this.searchInput = this.searchBox.querySelector(".ace_search_field"); this.replaceInput = this.replaceBox.querySelector(".ace_search_field"); var _this = this; event.addListener(sb, "mousedown", function(e) { setTimeout(function(){ _this.activeInput.focus(); }, 0); event.stopPropagation(e); }); event.addListener(sb, "click", function(e) { var t = e.target; var action = t.getAttribute("action"); if (action && _this[action]) _this[action](); else if (_this.$searchBarKb.commands[action]) _this.$searchBarKb.commands[action].exec(_this); event.stopPropagation(e); }); event.addCommandKeyListener(sb, function(e, hashId, keyCode) { var keyString = keyUtil.keyCodeToString(keyCode); var command = _this.$searchBarKb.findKeyCommand(hashId, keyString); if (command && command.exec) { command.exec(_this); event.stopEvent(e); } }); this.$onChange = lang.delayedCall(function() { _this.find(false, false); }); event.addListener(this.searchInput, "input", function() { _this.$onChange.schedule(20); }); event.addListener(this.searchInput, "focus", function() { _this.activeInput = _this.searchInput; }); event.addListener(this.replaceInput, "focus", function() { _this.activeInput = _this.replaceInput; }); }; this.$closeSearchBarKb = new HashHandler([{ bindKey: "Esc", name: "closeSearchBar", exec: function(editor) { editor.searchBox.hide(); } }]); this.$searchBarKb = new HashHandler(); this.$searchBarKb.bindKeys({ "Ctrl-f|Command-f|Ctrl-H|Command-Option-F": function(sb) { var isReplace = sb.isReplace = !sb.isReplace; sb.replaceBox.style.display = isReplace ? "" : "none"; sb[isReplace ? "replaceInput" : "searchInput"].focus(); }, "Ctrl-G|Command-G": function(sb) { sb.findNext(); }, "Ctrl-Shift-G|Command-Shift-G": function(sb) { sb.findPrev(); }, "esc": function(sb) { setTimeout(function() { sb.hide();}); }, "Return": function(sb) { if (sb.activeInput == sb.replaceInput) sb.replace(); sb.findNext(); }, "Shift-Return": function(sb) { if (sb.activeInput == sb.replaceInput) sb.replace(); sb.findPrev(); }, "Tab": function(sb) { (sb.activeInput == sb.replaceInput ? sb.searchInput : sb.replaceInput).focus(); } }); this.$searchBarKb.addCommands([{ name: "toggleRegexpMode", bindKey: {win: "Alt-R|Alt-/", mac: "Ctrl-Alt-R|Ctrl-Alt-/"}, exec: function(sb) { sb.regExpOption.checked = !sb.regExpOption.checked; sb.$syncOptions(); } }, { name: "toggleCaseSensitive", bindKey: {win: "Alt-C|Alt-I", mac: "Ctrl-Alt-R|Ctrl-Alt-I"}, exec: function(sb) { sb.caseSensitiveOption.checked = !sb.caseSensitiveOption.checked; sb.$syncOptions(); } }, { name: "toggleWholeWords", bindKey: {win: "Alt-B|Alt-W", mac: "Ctrl-Alt-B|Ctrl-Alt-W"}, exec: function(sb) { sb.wholeWordOption.checked = !sb.wholeWordOption.checked; sb.$syncOptions(); } }]); this.$syncOptions = function() { dom.setCssClass(this.regExpOption, "checked", this.regExpOption.checked); dom.setCssClass(this.wholeWordOption, "checked", this.wholeWordOption.checked); dom.setCssClass(this.caseSensitiveOption, "checked", this.caseSensitiveOption.checked); this.find(false, false); }; this.find = function(skipCurrent, backwards) { var range = this.editor.find(this.searchInput.value, { skipCurrent: skipCurrent, backwards: backwards, wrap: true, regExp: this.regExpOption.checked, caseSensitive: this.caseSensitiveOption.checked, wholeWord: this.wholeWordOption.checked }); dom.setCssClass(this.searchBox, "ace_nomatch", !range && this.searchInput.value); this.editor.session.highlight(this.editor.$search.$options.re); }; this.findNext = function() { this.find(true, false); }; this.findPrev = function() { this.find(true, true); }; this.replace = function() { this.editor.replace(this.replaceInput.value); }; this.replaceAll = function() { this.editor.replaceAll(this.replaceInput.value); }; this.hide = function () { this.element.style.display = "none"; this.editor.keyBinding.removeKeyboardHandler(this.$closeSearchBarKb); this.editor.focus(); }; this.show = function(value, isReplace) { this.element.style.display = ""; this.replaceBox.style.display = isReplace ? "" : "none"; this.isReplace = isReplace; if (value) this.searchInput.value = value; this.searchInput.focus(); this.searchInput.select(); this.editor.keyBinding.addKeyboardHandler(this.$closeSearchBarKb); }; }).call(SearchBox.prototype); exports.SearchBox = SearchBox; exports.Search = function(editor, isReplace) { var sb = editor.searchBox || new SearchBox(editor); sb.show(editor.session.getTextRange(), isReplace); }; exports.ISearch = function(session, options) { this.$changeListener = this.$changeListener.bind(this); this.startRange = session.selection.toOrientedRange(); this.options = options || {}; }; (function(){ this.setSession = function(session) { if (this.session) { this.session.removeListener(this.$changeListener); } this.session = session; this.session.addListener(this.$changeListener); }; this.setSearchString = function() { }; this.getValue = function() { if (this.value == null) this.value = this.session.getValue(); return this.value; }; this.$changeListener = function() { this.value = null; }; this.find = function() { }; this.$edgeBefore = function() { this.cursor = this.startRange[this.options.backwards ? "start" : "end"]; }; this.$edgeAfter = function() { }; this.next = function(dir) { }; }).call(exports.ISearch.prototype); });
/* @flow */ import { addAttr } from 'compiler/helpers' import { RECYCLE_LIST_MARKER } from 'weex/util/index' // mark components as inside recycle-list so that we know we need to invoke // their special @render function instead of render in create-component.js export function postTransformComponent ( el: ASTElement, options: WeexCompilerOptions ) { // $flow-disable-line (we know isReservedTag is there) if (!options.isReservedTag(el.tag) && el.tag !== 'cell-slot') { addAttr(el, RECYCLE_LIST_MARKER, 'true') } }
// ================================================== // fancyBox v3.0.39 // // Licensed GPLv3 for open source use // or fancyBox Commercial License for commercial use // // http://fancyapps.com/fancybox/ // Copyright 2017 fancyApps // // ================================================== ;(function (window, document, $, undefined) { 'use strict'; // If there's no jQuery, fancyBox can't work // ========================================= if ( !$ ) { return undefined; } // Private default settings // ======================== var defaults = { // Animation duration in ms speed : 330, // Enable infinite gallery navigation loop : true, // Should zoom animation change opacity, too // If opacity is 'auto', then fade-out if image and thumbnail have different aspect ratios opacity : 'auto', // Space around image, ignored if zoomed-in or viewport smaller than 800px margin : [44, 0], // Horizontal space between slides gutter : 30, // Should display toolbars infobar : true, buttons : true, // What buttons should appear in the toolbar slideShow : true, fullScreen : true, thumbs : true, closeBtn : true, // Should apply small close button at top right corner of the content // If 'auto' - will be set for content having type 'html', 'inline' or 'ajax' smallBtn : 'auto', image : { // Wait for images to load before displaying // Requires predefined image dimensions // If 'auto' - will zoom in thumbnail if 'width' and 'height' attributes are found preload : "auto", // Protect an image from downloading by right-click protect : false }, ajax : { // Object containing settings for ajax request settings : { // This helps to indicate that request comes from the modal // Feel free to change naming data : { fancybox : true } } }, iframe : { // Iframe template tpl : '<iframe id="fancybox-frame{rnd}" name="fancybox-frame{rnd}" class="fancybox-iframe" frameborder="0" vspace="0" hspace="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen allowtransparency="true" src=""></iframe>', // Preload iframe before displaying it // This allows to calculate iframe content width and height // (note: Due to "Same Origin Policy", you can't get cross domain data). preload : true, // Scrolling attribute for iframe tag scrolling : 'no', // Custom CSS styling for iframe wrapping element css : {} }, // Custom CSS class for layout baseClass : '', // Custom CSS class for slide element slideClass : '', // Base template for layout baseTpl : '<div class="fancybox-container" role="dialog" tabindex="-1">' + '<div class="fancybox-bg"></div>' + '<div class="fancybox-controls">' + '<div class="fancybox-infobar">' + '<button data-fancybox-previous class="fancybox-button fancybox-button--left" title="Previous"></button>' + '<div class="fancybox-infobar__body">' + '<span class="js-fancybox-index"></span>&nbsp;/&nbsp;<span class="js-fancybox-count"></span>' + '</div>' + '<button data-fancybox-next class="fancybox-button fancybox-button--right" title="Next"></button>' + '</div>' + '<div class="fancybox-buttons">' + '<button data-fancybox-close class="fancybox-button fancybox-button--close" title="Close (Esc)"></button>' + '</div>' + '</div>' + '<div class="fancybox-slider-wrap">' + '<div class="fancybox-slider"></div>' + '</div>' + '<div class="fancybox-caption-wrap"><div class="fancybox-caption"></div></div>' + '</div>', // Loading indicator template spinnerTpl : '<div class="fancybox-loading"></div>', // Error message template errorTpl : '<div class="fancybox-error"><p>The requested content cannot be loaded. <br /> Please try again later.<p></div>', // This will be appended to html content, if "smallBtn" option is not set to false closeTpl : '<button data-fancybox-close class="fancybox-close-small">×</button>', // Container is injected into this element parentEl : 'body', // Enable gestures (tap, zoom, pan and pinch) touch : true, // Enable keyboard navigation keyboard : true, // Try to focus on first focusable element after opening focus : true, // Close when clicked outside of the content closeClickOutside : true, // Callbacks beforeLoad : $.noop, afterLoad : $.noop, beforeMove : $.noop, afterMove : $.noop, onComplete : $.noop, onInit : $.noop, beforeClose : $.noop, afterClose : $.noop, onActivate : $.noop, onDeactivate : $.noop }; var $W = $(window); var $D = $(document); var called = 0; // Check if an object is a jQuery object and not a native JavaScript object // ======================================================================== var isQuery = function (obj) { return obj && obj.hasOwnProperty && obj instanceof $; }; // Handle multiple browsers for requestAnimationFrame() // ==================================================== var requestAFrame = (function() { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function( callback ) { window.setTimeout(callback, 1000 / 60); }; })(); // Check if element is inside the viewport by at least 1 pixel // =========================================================== var isElementInViewport = function( el ) { var rect; if ( typeof $ === "function" && el instanceof $ ) { el = el[0]; } rect = el.getBoundingClientRect(); return rect.bottom > 0 && rect.right > 0 && rect.left < (window.innerWidth || document.documentElement.clientWidth) && rect.top < (window.innerHeight || document.documentElement.clientHeight); }; // Class definition // ================ var FancyBox = function( content, opts, index ) { var self = this; self.opts = $.extend( true, { index : index }, defaults, opts || {} ); self.id = self.opts.id || ++called; self.group = []; self.currIndex = parseInt( self.opts.index, 10 ) || 0; self.prevIndex = null; self.prevPos = null; self.currPos = 0; self.firstRun = null; // Create group elements from original item collection self.createGroup( content ); if ( !self.group.length ) { return; } // Save last active element and current scroll position self.$lastFocus = $(document.activeElement).blur(); // Collection of gallery objects self.slides = {}; self.init( content ); }; $.extend(FancyBox.prototype, { // Create DOM structure // ==================== init : function() { var self = this; var testWidth; var $container; self.scrollTop = $W.scrollTop(); self.scrollLeft = $W.scrollLeft(); // Disable compensating on touch-enabled devices as they probably do not have scrollbars anyway // and therefore we avoid of unnecessary layout reflow if ( !$.fancybox.isTouch && !$( 'html' ).hasClass( 'fancybox-enabled' ) ) { testWidth = $( 'body' ).width(); $( 'html' ).addClass( 'fancybox-enabled' ); testWidth = $( 'body' ).width() - testWidth; // Body width has increased - compensate missing scrollbars if ( testWidth > 1 ) { $( '<style id="fancybox-noscroll" type="text/css">' ).html( '.compensate-for-scrollbar, .fancybox-enabled body { margin-right: ' + testWidth + 'px; }' ).appendTo( 'head' ); } } $container = $( self.opts.baseTpl ) .attr('id', 'fancybox-container-' + self.id) .data( 'FancyBox', self ) .addClass( self.opts.baseClass ) .hide() .prependTo( self.opts.parentEl ); // Create object holding references to jQuery wrapped nodes self.$refs = { container : $container, bg : $container.find('.fancybox-bg'), controls : $container.find('.fancybox-controls'), buttons : $container.find('.fancybox-buttons'), slider_wrap : $container.find('.fancybox-slider-wrap'), slider : $container.find('.fancybox-slider'), caption : $container.find('.fancybox-caption') }; self.trigger( 'onInit' ); // Bring to front and enable events self.activate(); // Try to avoid running multiple times if ( self.current ) { return; } self.jumpTo( self.currIndex ); }, // Create array of gally item objects // Check if each object has valid type and content // =============================================== createGroup : function ( content ) { var self = this; var items = $.makeArray( content ); $.each(items, function( i, item ) { var obj = {}, opts = {}, data = [], $item, type, src, srcParts; // Step 1 - Make sure we have an object if ( $.isPlainObject( item ) ) { obj = item; opts = item.opts || {}; } else if ( $.type( item ) === 'object' && $( item ).length ) { $item = $( item ); data = $item.data(); opts = 'options' in data ? data.options : {}; opts = $.type( opts ) === 'object' ? opts : {}; obj.type = 'type' in data ? data.type : opts.type; obj.src = 'src' in data ? data.src : ( opts.src || $item.attr( 'href' ) ); opts.width = 'width' in data ? data.width : opts.width; opts.height = 'height' in data ? data.height : opts.height; opts.thumb = 'thumb' in data ? data.thumb : opts.thumb; opts.selector = 'selector' in data ? data.selector : opts.selector; if ( 'srcset' in data ) { opts.image = { srcset : data.srcset }; } opts.$orig = $item; } else { obj = { type : 'html', content : item + '' }; } obj.opts = $.extend( true, {}, self.opts, opts ); // Step 2 - Make sure we have supported content type type = obj.type; src = obj.src || ''; if ( !type ) { if ( obj.content ) { type = 'html'; } else if ( src.match(/(^data:image\/[a-z0-9+\/=]*,)|(\.(jp(e|g|eg)|gif|png|bmp|webp|svg|ico)((\?|#).*)?$)/i) ) { type = 'image'; } else if ( src.match(/\.(pdf)((\?|#).*)?$/i) ) { type = 'pdf'; } else if ( src.charAt(0) === '#' ) { type = 'inline'; } obj.type = type; } // Step 3 - Some adjustments obj.index = self.group.length; // Check if $orig and $thumb objects exist if ( obj.opts.$orig && !obj.opts.$orig.length ) { delete obj.opts.$orig; } if ( !obj.opts.$thumb && obj.opts.$orig ) { obj.opts.$thumb = obj.opts.$orig.find( 'img:first' ); } if ( obj.opts.$thumb && !obj.opts.$thumb.length ) { delete obj.opts.$thumb; } // Caption is a "special" option, it can be passed as a method if ( $.type( obj.opts.caption ) === 'function' ) { obj.opts.caption = obj.opts.caption.apply( item, [ self, obj ] ); } else if ( 'caption' in data ) { obj.opts.caption = data.caption; } else if ( opts.$orig ) { obj.opts.caption = $item.attr( 'title' ); } // Make sure we have caption as a string obj.opts.caption = obj.opts.caption === undefined ? '' : obj.opts.caption + ''; // Check if url contains selector used to filter the content // Example: "ajax.html #something" if ( type === 'ajax' ) { srcParts = src.split(/\s+/, 2); if ( srcParts.length > 1 ) { obj.src = srcParts.shift(); obj.opts.selector = srcParts.shift(); } } if ( obj.opts.smallBtn == 'auto' ) { if ( $.inArray( type, ['html', 'inline', 'ajax'] ) > -1 ) { obj.opts.buttons = false; obj.opts.smallBtn = true; } else { obj.opts.smallBtn = false; } } if ( type === 'pdf' ) { obj.type = 'iframe'; obj.opts.closeBtn = true; obj.opts.smallBtn = false; obj.opts.iframe.preload = false; } if ( obj.opts.modal ) { $.extend(true, obj.opts, { infobar : 0, buttons : 0, keyboard : 0, slideShow : 0, fullScreen : 0, closeClickOutside : 0 }); } self.group.push( obj ); }); }, // Attach an event handler functions for: // - navigation elements // - browser scrolling, resizing; // - focusing // - keyboard // ================= addEvents : function() { var self = this; var runUpdate = function () { $W.scrollTop( self.scrollTop ).scrollLeft( self.scrollLeft ); self.$refs.slider_wrap.show(); self.update(); }; self.removeEvents(); // Make navigation elements clickable self.$refs.container.on('click.fb-close', '[data-fancybox-close]', function(e) { e.stopPropagation(); e.preventDefault(); self.close( e ); }).on('click.fb-previous', '[data-fancybox-previous]', function(e) { e.stopPropagation(); e.preventDefault(); self.previous(); }).on('click.fb-next', '[data-fancybox-next]', function(e) { e.stopPropagation(); e.preventDefault(); self.next(); }); // Handle page scrolling and browser resizing $( window ).on('orientationchange.fb resize.fb', function(e) { requestAFrame(function() { if ( e && e.originalEvent && e.originalEvent.type == "orientationchange" ) { self.$refs.slider_wrap.hide(); requestAFrame( runUpdate ); } else { runUpdate(); } }); }); // Trap focus $D.on('focusin.fb', function(e) { var instance = $.fancybox ? $.fancybox.getInstance() : null; if ( instance && !$( e.target ).hasClass( 'fancybox-container' ) && !$.contains( instance.$refs.container[0], e.target ) ) { e.stopPropagation(); instance.focus(); // Sometimes page gets scrolled, set it back $W.scrollTop( self.scrollTop ).scrollLeft( self.scrollLeft ); } }); // Enable keyboard navigation $( document ).on('keydown.fb', function (e) { var current = self.current, keycode = e.keyCode || e.which; if ( !current || !current.opts.keyboard ) { return; } if ( $(e.target).is('input') || $(e.target).is('textarea') ) { return; } // Backspace and Esc keys if ( keycode === 8 || keycode === 27 ) { e.preventDefault(); self.close( e ); return; } switch ( keycode ) { case 37: // Left arrow case 38: // Up arrow e.preventDefault(); self.previous(); break; case 39: // Right arrow case 40: // Down arrow e.preventDefault(); self.next(); break; case 80: // "P" case 32: // Spacebar e.preventDefault(); if ( self.SlideShow ) { e.preventDefault(); self.SlideShow.toggle(); } break; case 70: // "F" if ( self.FullScreen ) { e.preventDefault(); self.FullScreen.toggle(); } break; case 71: // "G" if ( self.Thumbs ) { e.preventDefault(); self.Thumbs.toggle(); } break; } }); }, // Remove events added by the core // =============================== removeEvents : function () { $W.off( 'scroll.fb resize.fb orientationchange.fb' ); $D.off( 'keydown.fb focusin.fb click.fb-close' ); this.$refs.container.off('click.fb-close click.fb-previous click.fb-next'); }, // Slide to left // ================== previous : function( duration ) { this.jumpTo( this.currIndex - 1, duration ); }, // Slide to right // =================== next : function( duration ) { this.jumpTo( this.currIndex + 1, duration ); }, // Display current gallery item, move slider to current position // ============================================================= jumpTo : function ( to, duration ) { var self = this, firstRun, index, pos, loop; firstRun = self.firstRun = ( self.firstRun === null ); index = pos = to = parseInt( to, 10 ); loop = self.current ? self.current.opts.loop : false; if ( self.isAnimating || ( index == self.currIndex && !firstRun ) ) { return; } if ( self.group.length > 1 && loop ) { index = index % self.group.length; index = index < 0 ? self.group.length + index : index; // Calculate closest position of upcoming item from the current one if ( self.group.length == 2 ) { pos = to - self.currIndex + self.currPos; } else { pos = index - self.currIndex + self.currPos; if ( Math.abs( self.currPos - ( pos + self.group.length ) ) < Math.abs( self.currPos - pos ) ) { pos = pos + self.group.length; } else if ( Math.abs( self.currPos - ( pos - self.group.length ) ) < Math.abs( self.currPos - pos ) ) { pos = pos - self.group.length; } } } else if ( !self.group[ index ] ) { self.update( false, false, duration ); return; } if ( self.current ) { self.current.$slide.removeClass('fancybox-slide--current fancybox-slide--complete'); self.updateSlide( self.current, true ); } self.prevIndex = self.currIndex; self.prevPos = self.currPos; self.currIndex = index; self.currPos = pos; // Create slides self.current = self.createSlide( pos ); if ( self.group.length > 1 ) { if ( self.opts.loop || pos - 1 >= 0 ) { self.createSlide( pos - 1 ); } if ( self.opts.loop || pos + 1 < self.group.length ) { self.createSlide( pos + 1 ); } } self.current.isMoved = false; self.current.isComplete = false; duration = parseInt( duration === undefined ? self.current.opts.speed * 1.5 : duration, 10 ); // Move slider to the next position // Note: the content might still be loading self.trigger( 'beforeMove' ); self.updateControls(); if ( firstRun ) { self.current.$slide.addClass('fancybox-slide--current'); self.$refs.container.show(); requestAFrame(function() { self.$refs.bg.css('transition-duration', self.current.opts.speed + 'ms'); self.$refs.container.addClass( 'fancybox-container--ready' ); }); } // Set position immediately on first opening self.update( true, false, firstRun ? 0 : duration, function() { self.afterMove(); }); self.loadSlide( self.current ); if ( !( firstRun && self.current.$ghost ) ) { self.preload(); } }, // Create new "slide" element // These are gallery items that are actually added to DOM // ======================================================= createSlide : function( pos ) { var self = this; var $slide; var index; var found; index = pos % self.group.length; index = index < 0 ? self.group.length + index : index; if ( !self.slides[ pos ] && self.group[ index ] ) { // If we are looping and slide with that index already exists, then reuse it if ( self.opts.loop && self.group.length > 2 ) { for (var key in self.slides) { if ( self.slides[ key ].index === index ) { found = self.slides[ key ]; found.pos = pos; self.slides[ pos ] = found; delete self.slides[ key ]; self.updateSlide( found ); return found; } } } $slide = $('<div class="fancybox-slide"></div>').appendTo( self.$refs.slider ); self.slides[ pos ] = $.extend( true, {}, self.group[ index ], { pos : pos, $slide : $slide, isMoved : false, isLoaded : false }); } return self.slides[ pos ]; }, zoomInOut : function( type, duration, callback ) { var self = this; var current = self.current; var $what = current.$placeholder; var opacity = current.opts.opacity; var $thumb = current.opts.$thumb; var thumbPos = $thumb ? $thumb.offset() : 0; var slidePos = current.$slide.offset(); var props; var start; var end; if ( !$what || !current.isMoved || !thumbPos || !isElementInViewport( $thumb ) ) { return false; } if ( type === 'In' && !self.firstRun ) { return false; } $.fancybox.stop( $what ); self.isAnimating = true; props = { top : thumbPos.top - slidePos.top + parseFloat( $thumb.css( "border-top-width" ) || 0 ), left : thumbPos.left - slidePos.left + parseFloat( $thumb.css( "border-left-width" ) || 0 ), width : $thumb.width(), height : $thumb.height(), scaleX : 1, scaleY : 1 }; // Check if we need to animate opacity if ( opacity == 'auto' ) { opacity = Math.abs( current.width / current.height - props.width / props.height ) > 0.1; } if ( type === 'In' ) { start = props; end = self.getFitPos( current ); end.scaleX = end.width / start.width; end.scaleY = end.height / start.height; if ( opacity ) { start.opacity = 0.1; end.opacity = 1; } } else { start = $.fancybox.getTranslate( $what ); end = props; // Switch to thumbnail image to improve animation performance if ( current.$ghost ) { current.$ghost.show(); if ( current.$image ) { current.$image.remove(); } } start.scaleX = start.width / end.width; start.scaleY = start.height / end.height; start.width = end.width; start.height = end.height; if ( opacity ) { end.opacity = 0; } } self.updateCursor( end.width, end.height ); // There is no need to animate width/height properties delete end.width; delete end.height; $.fancybox.setTranslate( $what, start ); $what.show(); self.trigger( 'beforeZoom' + type ); requestAFrame(function() { $what.css( 'transition', 'all ' + duration + 'ms' ); $.fancybox.setTranslate( $what, end ); setTimeout(function() { requestAFrame(function() { var reset; $what.css( 'transition', 'none' ); reset = $.fancybox.getTranslate( $what ); reset.scaleX = 1; reset.scaleY = 1; // Reset scalex/scaleY values; this helps for perfomance $.fancybox.setTranslate( $what, reset ); self.trigger( 'afterZoom' + type ); callback.apply( self ); self.isAnimating = false; }); }, duration); }); return true; }, // Check if image dimensions exceed parent element // =============================================== canPan : function() { var self = this; var current = self.current; var $what = current.$placeholder; var rez = false; if ( $what ) { rez = self.getFitPos( current ); rez = Math.abs( $what.width() - rez.width ) > 1 || Math.abs( $what.height() - rez.height ) > 1; } return rez; }, // Check if current image dimensions are smaller than actual // ========================================================= isScaledDown : function() { var self = this; var current = self.current; var $what = current.$placeholder; var rez = false; if ( $what ) { rez = $.fancybox.getTranslate( $what ); rez = rez.width < current.width || rez.height < current.height; } return rez; }, // Scale image to the actual size of the image // =========================================== scaleToActual : function( x, y, duration ) { var self = this; var current = self.current; var $what = current.$placeholder; var imgPos, posX, posY, scaleX, scaleY; var canvasWidth = parseInt( current.$slide.width(), 10 ); var canvasHeight = parseInt( current.$slide.height(), 10 ); var newImgWidth = current.width; var newImgHeight = current.height; if ( !$what ) { return; } self.isAnimating = true; x = x === undefined ? canvasWidth * 0.5 : x; y = y === undefined ? canvasHeight * 0.5 : y; imgPos = $.fancybox.getTranslate( $what ); scaleX = newImgWidth / imgPos.width; scaleY = newImgHeight / imgPos.height; // Get center position for original image posX = ( canvasWidth * 0.5 - newImgWidth * 0.5 ); posY = ( canvasHeight * 0.5 - newImgHeight * 0.5 ); // Make sure image does not move away from edges if ( newImgWidth > canvasWidth ) { posX = imgPos.left * scaleX - ( ( x * scaleX ) - x ); if ( posX > 0 ) { posX = 0; } if ( posX < canvasWidth - newImgWidth ) { posX = canvasWidth - newImgWidth; } } if ( newImgHeight > canvasHeight) { posY = imgPos.top * scaleY - ( ( y * scaleY ) - y ); if ( posY > 0 ) { posY = 0; } if ( posY < canvasHeight - newImgHeight ) { posY = canvasHeight - newImgHeight; } } self.updateCursor( newImgWidth, newImgHeight ); $.fancybox.animate( $what, null, { top : posY, left : posX, scaleX : scaleX, scaleY : scaleY }, duration || current.opts.speed, function() { self.isAnimating = false; }); }, // Scale image to fit inside parent element // ======================================== scaleToFit : function( duration ) { var self = this; var current = self.current; var $what = current.$placeholder; var end; if ( !$what ) { return; } self.isAnimating = true; end = self.getFitPos( current ); self.updateCursor( end.width, end.height ); $.fancybox.animate( $what, null, { top : end.top, left : end.left, scaleX : end.width / $what.width(), scaleY : end.height / $what.height() }, duration || current.opts.speed, function() { self.isAnimating = false; }); }, // Calculate image size to fit inside viewport // =========================================== getFitPos : function( slide ) { var $what = slide.$placeholder || slide.$content; var imgWidth = slide.width; var imgHeight = slide.height; var margin = slide.opts.margin; var canvasWidth, canvasHeight, minRatio, top, left, width, height; if ( !$what || !$what.length || ( !imgWidth && !imgHeight) ) { return false; } // Convert "margin to CSS style: [ top, right, bottom, left ] if ( $.type( margin ) === "number" ) { margin = [ margin, margin ]; } if ( margin.length == 2 ) { margin = [ margin[0], margin[1], margin[0], margin[1] ]; } if ( $W.width() < 800 ) { margin = [0, 0, 0, 0]; } canvasWidth = parseInt( slide.$slide.width(), 10 ) - ( margin[ 1 ] + margin[ 3 ] ); canvasHeight = parseInt( slide.$slide.height(), 10 ) - ( margin[ 0 ] + margin[ 2 ] ); minRatio = Math.min(1, canvasWidth / imgWidth, canvasHeight / imgHeight ); // Use floor rounding to make sure it really fits width = Math.floor( minRatio * imgWidth ); height = Math.floor( minRatio * imgHeight ); top = Math.floor( ( canvasHeight - height ) * 0.5 ) + margin[ 0 ]; left = Math.floor( ( canvasWidth - width ) * 0.5 ) + margin[ 3 ]; return { top : top, left : left, width : width, height : height }; }, // Move slider to current position // Update all slides (and their content) // ===================================== update : function( andSlides, andContent, duration, callback ) { var self = this; var leftValue = ( self.current.pos * Math.floor( self.current.$slide.width() ) * -1 ) - ( self.current.pos * self.current.opts.gutter ) ; if ( self.isAnimating === true ) { return; } duration = parseInt( duration, 10 ) || 0; $.fancybox.stop( self.$refs.slider ); if ( andSlides === false ) { self.updateSlide( self.current, andContent ); } else { $.each( self.slides, function( key, slide ) { self.updateSlide( slide, andContent ); }); } if ( duration ) { $.fancybox.animate( self.$refs.slider, null, { top : 0, left : leftValue }, duration, function() { self.current.isMoved = true; if ( $.type( callback ) === 'function' ) { callback.apply( self ); } }); } else { $.fancybox.setTranslate( self.$refs.slider, { top : 0, left : leftValue } ); self.current.isMoved = true; if ( $.type( callback ) === 'function' ) { callback.apply( self ); } } }, // Update slide position and scale content to fit // ============================================== updateSlide : function( slide, andContent ) { var self = this; var $what = slide.$placeholder; var leftPos; slide = slide || self.current; if ( !slide || self.isClosing ) { return; } leftPos = ( slide.pos * Math.floor( slide.$slide.width() ) ) + ( slide.pos * slide.opts.gutter); if ( leftPos !== slide.leftPos ) { $.fancybox.setTranslate( slide.$slide, { top: 0, left : leftPos } ); slide.leftPos = leftPos; } if ( andContent !== false && $what ) { $.fancybox.setTranslate( $what, self.getFitPos( slide ) ); if ( slide.pos === self.currPos ) { self.updateCursor(); } } slide.$slide.trigger( 'refresh' ); self.trigger( 'onUpdate', slide ); }, // Update cursor style depending if content can be zoomed // ====================================================== updateCursor : function( nextWidth, nextHeight ) { var self = this; var canScale; var $container = self.$refs.container.removeClass('fancybox-controls--canzoomIn fancybox-controls--canzoomOut fancybox-controls--canGrab'); if ( self.isClosing || !self.opts.touch ) { return; } if ( nextWidth !== undefined && nextHeight !== undefined ) { canScale = nextWidth < self.current.width && nextHeight < self.current.height; } else { canScale = self.isScaledDown(); } if ( canScale ) { $container.addClass('fancybox-controls--canzoomIn'); } else if ( self.group.length < 2 ) { $container.addClass('fancybox-controls--canzoomOut'); } else { $container.addClass('fancybox-controls--canGrab'); } }, // Load content into the slide // =========================== loadSlide : function( slide ) { var self = this, type, $slide; var ajaxLoad; if ( !slide || slide.isLoaded || slide.isLoading ) { return; } slide.isLoading = true; self.trigger( 'beforeLoad', slide ); type = slide.type; $slide = slide.$slide; $slide .off( 'refresh' ) .trigger( 'onReset' ) .addClass( 'fancybox-slide--' + ( type || 'unknown' ) ) .addClass( slide.opts.slideClass ); // Create content depending on the type switch ( type ) { case 'image': self.setImage( slide ); break; case 'iframe': self.setIframe( slide ); break; case 'html': self.setContent( slide, slide.content ); break; case 'inline': if ( $( slide.src ).length ) { self.setContent( slide, $( slide.src ) ); } else { self.setError( slide ); } break; case 'ajax': self.showLoading( slide ); ajaxLoad = $.ajax( $.extend( {}, slide.opts.ajax.settings, { url: slide.src, success: function ( data, textStatus ) { if ( textStatus === 'success' ) { self.setContent( slide, data ); } }, error: function ( jqXHR, textStatus ) { if ( jqXHR && textStatus !== 'abort' ) { self.setError( slide ); } } })); $slide.one( 'onReset', function () { ajaxLoad.abort(); }); break; default: self.setError( slide ); break; } return true; }, // Use thumbnail image, if possible // ================================ setImage : function( slide ) { var self = this; var srcset = slide.opts.image.srcset; var found, temp, pxRatio, windowWidth; if ( slide.isLoaded && !slide.hasError ) { self.afterLoad( slide ); return; } // If we have "srcset", then we need to find matching "src" value. // This is necessary, because when you set an src attribute, the browser will preload the image // before any javascript or even CSS is applied. if ( srcset ) { pxRatio = window.devicePixelRatio || 1; windowWidth = window.innerWidth * pxRatio; temp = srcset.split(',').map(function (el) { var ret = {}; el.trim().split(/\s+/).forEach(function (el, i) { var value = parseInt(el.substring(0, el.length - 1), 10); if ( i === 0 ) { return (ret.url = el); } if ( value ) { ret.value = value; ret.postfix = el[el.length - 1]; } }); return ret; }); // Sort by value temp.sort(function (a, b) { return a.value - b.value; }); // Ok, now we have an array of all srcset values for ( var j = 0; j < temp.length; j++ ) { var el = temp[ j ]; if ( ( el.postfix === 'w' && el.value >= windowWidth ) || ( el.postfix === 'x' && el.value >= pxRatio ) ) { found = el; break; } } // If not found, take the last one if ( !found && temp.length ) { found = temp[ temp.length - 1 ]; } if ( found ) { slide.src = found.url; // If we have default width/height values, we can calculate height for matching source if ( slide.width && slide.height && found.postfix == 'w' ) { slide.height = ( slide.width / slide.height ) * found.value; slide.width = found.value; } } } slide.$placeholder = $('<div class="fancybox-placeholder"></div>') .hide() .appendTo( slide.$slide ); if ( slide.opts.preload !== false && slide.opts.width && slide.opts.height && ( slide.opts.thumb || slide.opts.$thumb ) ) { slide.width = slide.opts.width; slide.height = slide.opts.height; slide.$ghost = $('<img />') .one('load error', function() { if ( self.isClosing ) { return; } // Start preloading full size image $('<img/>')[0].src = slide.src; // zoomIn or just show self.revealImage( slide, function() { self.setBigImage( slide ); if ( self.firstRun && slide.index === self.currIndex ) { self.preload(); } }); }) .addClass( 'fancybox-image' ) .appendTo( slide.$placeholder ) .attr( 'src', slide.opts.thumb || slide.opts.$thumb.attr( 'src' ) ); } else { self.setBigImage( slide ); } }, // Create full-size image // ====================== setBigImage : function ( slide ) { var self = this; var $img = $('<img />'); slide.$image = $img .one('error', function() { self.setError( slide ); }) .one('load', function() { // Clear timeout that checks if loading icon needs to be displayed clearTimeout( slide.timouts ); slide.timouts = null; if ( self.isClosing ) { return; } slide.width = this.naturalWidth; slide.height = this.naturalHeight; if ( slide.opts.image.srcset ) { $img.attr('sizes', '100vw').attr('srcset', slide.opts.image.srcset); } self.afterLoad( slide ); if ( slide.$ghost ) { slide.timouts = setTimeout(function() { slide.$ghost.hide(); }, 350); } }) .addClass('fancybox-image') .attr('src', slide.src) .appendTo( slide.$placeholder ); if ( $img[0].complete ) { $img.trigger('load'); } else if( $img[0].error ) { $img.trigger('error'); } else { slide.timouts = setTimeout(function() { if ( !$img[0].complete && !slide.hasError ) { self.showLoading( slide ); } }, 150); } if ( slide.opts.image.protect ) { $('<div class="fancybox-spaceball"></div>').appendTo( slide.$placeholder ).on('contextmenu.fb',function(e){ if ( e.button == 2 ) { e.preventDefault(); } return true; }); } }, // Simply show image holder without animation // It has been hidden initially to avoid flickering // ================================================ revealImage : function( slide, callback ) { var self = this; callback = callback || $.noop; if ( slide.type !== 'image' || slide.hasError || slide.isRevealed === true ) { callback.apply( self ); return; } slide.isRevealed = true; if ( !( slide.pos === self.currPos && self.zoomInOut( 'In', slide.opts.speed, callback ) ) ) { if ( slide.$ghost && !slide.isLoaded ) { self.updateSlide( slide, true ); } if ( slide.pos === self.currPos ) { $.fancybox.animate( slide.$placeholder, { opacity: 0 }, { opacity: 1 }, 300, callback ); } else { slide.$placeholder.show(); } callback.apply( self ); } }, // Create iframe wrapper, iframe and bindings // ========================================== setIframe : function( slide ) { var self = this, opts = slide.opts.iframe, $slide = slide.$slide, $iframe; slide.$content = $('<div class="fancybox-content"></div>') .css( opts.css ) .appendTo( $slide ); $iframe = $( opts.tpl.replace(/\{rnd\}/g, new Date().getTime()) ) .attr('scrolling', $.fancybox.isTouch ? 'auto' : opts.scrolling) .appendTo( slide.$content ); if ( opts.preload ) { slide.$content.addClass( 'fancybox-tmp' ); self.showLoading( slide ); // Unfortunately, it is not always possible to determine if iframe is successfully loaded // (due to browser security policy) $iframe.on('load.fb error.fb', function(e) { this.isReady = 1; slide.$slide.trigger( 'refresh' ); self.afterLoad( slide ); }); // Recalculate iframe content size $slide.on('refresh.fb', function() { var $wrap = slide.$content, $contents, $body, scrollWidth, frameWidth, frameHeight; if ( $iframe[0].isReady !== 1 ) { return; } // Check if content is accessible, // it will fail if frame is not with the same origin try { $contents = $iframe.contents(); $body = $contents.find('body'); } catch (ignore) {} // Calculate dimensions for the wrapper if ( $body && $body.length && !( opts.css.width !== undefined && opts.css.height !== undefined ) ) { scrollWidth = $iframe[0].contentWindow.document.documentElement.scrollWidth; frameWidth = Math.ceil( $body.outerWidth(true) + ( $wrap.width() - scrollWidth ) ); frameHeight = Math.ceil( $body.outerHeight(true) ); // Resize wrapper to fit iframe content $wrap.css({ 'width' : opts.css.width === undefined ? frameWidth + ( $wrap.outerWidth() - $wrap.innerWidth() ) : opts.css.width, 'height' : opts.css.height === undefined ? frameHeight + ( $wrap.outerHeight() - $wrap.innerHeight() ) : opts.css.height }); } $wrap.removeClass( 'fancybox-tmp' ); }); } else { this.afterLoad( slide ); } $iframe.attr( 'src', slide.src ); if ( slide.opts.smallBtn ) { slide.$content.prepend( slide.opts.closeTpl ); } // Remove iframe if closing or changing gallery item $slide.one('onReset', function () { // This helps IE not to throw errors when closing try { $(this).find('iframe').hide().attr('src', '//about:blank'); } catch (ignore) {} $(this).empty(); slide.isLoaded = false; }); }, // Wrap and append content to the slide // ====================================== setContent : function ( slide, content ) { var self = this; if ( self.isClosing ) { return; } self.hideLoading( slide ); slide.$slide.empty(); if ( isQuery( content ) && content.parent().length ) { // If it is a jQuery object, then it will be moved to the box. // The placeholder is created so we will know where to put it back. // If user is navigating gallery fast, then the content might be already moved to the box if ( content.data( 'placeholder' ) ) { content.parents('.fancybox-slide').trigger( 'onReset' ); } content.data({'placeholder' : $('<div></div>' ).hide().insertAfter( content ) }).css('display', 'inline-block'); } else { if ( $.type( content ) === 'string' ) { content = $('<div>').append( content ).contents(); if ( content[0].nodeType === 3 ) { content = $('<div>').html( content ); } } if ( slide.opts.selector ) { content = $('<div>').html( content ).find( slide.opts.selector ); } } slide.$slide.one('onReset', function () { var placeholder = isQuery( content ) ? content.data('placeholder') : 0; if ( placeholder ) { content.hide().replaceAll( placeholder ); content.data( 'placeholder', null ); } if ( !slide.hasError ) { $(this).empty(); slide.isLoaded = false; } }); slide.$content = $( content ).appendTo( slide.$slide ); if ( slide.opts.smallBtn === true ) { slide.$content.find( '.fancybox-close-small' ).remove().end().eq(0).append( slide.opts.closeTpl ); } this.afterLoad( slide ); }, // Display error message // ===================== setError : function ( slide ) { slide.hasError = true; this.setContent( slide, slide.opts.errorTpl ); }, showLoading : function( slide ) { var self = this; slide = slide || self.current; if ( slide && !slide.$spinner ) { slide.$spinner = $( self.opts.spinnerTpl ).appendTo( slide.$slide ); } }, hideLoading : function( slide ) { var self = this; slide = slide || self.current; if ( slide && slide.$spinner ) { slide.$spinner.remove(); delete slide.$spinner; } }, afterMove : function() { var self = this; var current = self.current; var slides = {}; if ( !current ) { return; } current.$slide.siblings().trigger( 'onReset' ); // Remove unnecessary slides $.each( self.slides, function( key, slide ) { if ( slide.pos >= self.currPos - 1 && slide.pos <= self.currPos + 1 ) { slides[ slide.pos ] = slide; } else if ( slide ) { slide.$slide.remove(); } }); self.slides = slides; self.trigger( 'afterMove' ); if ( current.isLoaded ) { self.complete(); } }, // Adjustments after slide has been loaded // ======================================= afterLoad : function( slide ) { var self = this; if ( self.isClosing ) { return; } slide.isLoading = false; slide.isLoaded = true; self.trigger( 'afterLoad', slide ); self.hideLoading( slide ); // Resize content to fit inside slide // Skip if slide has an $ghost element, because then it has been already processed if ( !slide.$ghost ) { self.updateSlide( slide, true ); } if ( slide.index === self.currIndex && slide.isMoved ) { self.complete(); } else if ( !slide.$ghost ) { self.revealImage( slide ); } }, // Final adjustments after current gallery item is moved to position // and it`s content is loaded // ================================================================== complete : function() { var self = this; var current = self.current; self.revealImage( current, function() { current.isComplete = true; current.$slide.addClass('fancybox-slide--complete'); self.updateCursor(); self.trigger( 'onComplete' ); // Try to focus on the first focusable element, skip for images and iframes if ( current.opts.focus && !( current.type === 'image' || current.type === 'iframe' ) ) { self.focus(); } }); }, // Preload next and previous slides // ================================ preload : function() { var self = this; var next, prev; if ( self.group.length < 2 ) { return; } next = self.slides[ self.currPos + 1 ]; prev = self.slides[ self.currPos - 1 ]; if ( next && next.type === 'image' ) { self.loadSlide( next ); } if ( prev && prev.type === 'image' ) { self.loadSlide( prev ); } }, // Try to find and focus on the first focusable element // ==================================================== focus : function() { var current = this.current; var $el; $el = current && current.isComplete ? current.$slide.find('button,:input,[tabindex],a:not(".disabled")').filter(':visible:first') : null; if ( !$el || !$el.length ) { $el = this.$refs.container; } $el.focus(); // Scroll position of wrapper element sometimes changes after focusing (IE) this.$refs.slider_wrap.scrollLeft(0); // And the same goes for slide element if ( current ) { current.$slide.scrollTop(0); } }, // Activates current instance - brings container to the front and enables keyboard, // notifies other instances about deactivating // ================================================================================= activate : function () { var self = this; // Deactivate all instances $( '.fancybox-container' ).each(function () { var instance = $(this).data( 'FancyBox' ); // Skip self and closing instances if (instance && instance.uid !== self.uid && !instance.isClosing) { instance.trigger( 'onDeactivate' ); } }); if ( self.current ) { if ( self.$refs.container.index() > 0 ) { self.$refs.container.prependTo( document.body ); } self.updateControls(); } self.trigger( 'onActivate' ); self.addEvents(); }, // Start closing procedure // This will start "zoom-out" animation if needed and clean everything up afterwards // ================================================================================= close : function( e ) { var self = this; var current = self.current; var duration = current.opts.speed; var done = $.proxy(function() { self.cleanUp( e ); // Now "this" is again our instance }, this); if ( self.isAnimating || self.isClosing ) { return false; } if ( self.trigger( 'beforeClose', e ) === false ) { return; } self.isClosing = true; if ( current.timouts ) { clearTimeout( current.timouts ); } if ( e !== true) { $.fancybox.stop( self.$refs.slider ); } self.$refs.container .removeClass('fancybox-container--active') .addClass('fancybox-container--closing'); current.$slide .removeClass('fancybox-slide--complete') .siblings() .remove(); if ( !current.isMoved ) { current.$slide.css('overflow', 'visible'); } // Remove all events // If there are multiple instances, they will be set again by "activate" method self.removeEvents(); // Clean up self.hideLoading( current ); self.hideControls(); self.updateCursor(); self.$refs.bg.css('transition-duration', duration + 'ms'); this.$refs.container.removeClass( 'fancybox-container--ready' ); if ( e === true ) { setTimeout( done, duration ); } else if ( !self.zoomInOut( 'Out', duration, done ) ) { $.fancybox.animate( self.$refs.container, null, { opacity : 0 }, duration, "easeInSine", done ); } }, // Final adjustments after removing the instance // ============================================= cleanUp : function( e ) { var self = this, instance; self.$refs.slider.children().trigger( 'onReset' ); self.$refs.container.empty().remove(); self.trigger( 'afterClose', e ); self.current = null; // Check if there are other instances instance = $.fancybox.getInstance(); if ( instance ) { instance.activate(); } else { $( 'html' ).removeClass( 'fancybox-enabled' ); $( '#fancybox-noscroll' ).remove(); } // Place back focus if ( self.$lastFocus ) { self.$lastFocus.focus(); } }, // Call callback and trigger an event // ================================== trigger : function( name, slide ) { var args = Array.prototype.slice.call(arguments, 1), self = this, obj = slide && slide.opts ? slide : self.current, rez; if ( obj ) { args.unshift( obj ); } else { obj = self; } args.unshift( self ); if ( $.isFunction( obj.opts[ name ] ) ) { rez = obj.opts[ name ].apply( obj, args ); } if ( rez === false ) { return rez; } self.$refs.container.trigger( name + '.fb', args ); }, // Toggle toolbar and caption // ========================== toggleControls : function( force ) { if ( this.isHiddenControls ) { this.updateControls( force ); } else { this.hideControls(); } }, // Hide toolbar and caption // ======================== hideControls : function () { this.isHiddenControls = true; this.$refs.container.removeClass('fancybox-show-controls'); this.$refs.container.removeClass('fancybox-show-caption'); }, // Update infobar values, navigation button states and reveal caption // ================================================================== updateControls : function ( force ) { var self = this; var $container = self.$refs.container; var $caption = self.$refs.caption; // Toggle infobar and buttons var current = self.current; var index = current.index; var opts = current.opts; var caption = opts.caption; if ( this.isHiddenControls && force !== true ) { return; } this.isHiddenControls = false; self.$refs.container.addClass('fancybox-show-controls'); $container .toggleClass('fancybox-show-infobar', !!opts.infobar && self.group.length > 1) .toggleClass('fancybox-show-buttons', !!opts.buttons ) .toggleClass('fancybox-is-modal', !!opts.modal ); $('.fancybox-button--left', $container).toggleClass( 'fancybox-button--disabled', (!opts.loop && index <= 0 ) ); $('.fancybox-button--right', $container).toggleClass( 'fancybox-button--disabled', (!opts.loop && index >= self.group.length - 1) ); $('.fancybox-button--play', $container).toggle( !!( opts.slideShow && self.group.length > 1) ); $('.fancybox-button--close', $container).toggle( !!opts.closeBtn ); // Update infobar values $('.js-fancybox-count', $container).html( self.group.length ); $('.js-fancybox-index', $container).html( index + 1 ); // Recalculate content dimensions current.$slide.trigger( 'refresh' ); // Reveal or create new caption if ( $caption ) { $caption.empty(); } if ( caption && caption.length ) { $caption.html( caption ); this.$refs.container.addClass( 'fancybox-show-caption '); self.$caption = $caption; } else { this.$refs.container.removeClass( 'fancybox-show-caption' ); } } }); $.fancybox = { version : "3.0.39", defaults : defaults, // Get current instance and execute a command. // // Examples of usage: // // $instance = $.fancybox.getInstance(); // $.fancybox.getInstance().jumpTo( 1 ); // $.fancybox.getInstance( 'jumpTo', 1 ); // $.fancybox.getInstance( function() { // console.info( this.currIndex ); // }); // ====================================================== getInstance : function ( command ) { var instance = $('.fancybox-container:not(".fancybox-container--closing"):first').data( 'FancyBox' ); var args = Array.prototype.slice.call(arguments, 1); if ( instance instanceof FancyBox ) { if ( $.type( command ) === 'string' ) { instance[ command ].apply( instance, args ); } else if ( $.type( command ) === 'function' ) { command.apply( instance, args ); } return instance; } return false; }, // Create new instance // =================== open : function ( items, opts, index ) { return new FancyBox( items, opts, index ); }, // Close current or all instances // ============================== close : function ( all ) { var instance = this.getInstance(); if ( instance ) { instance.close(); // Try to find and close next instance if ( all === true ) { this.close(); } } }, // Test for the existence of touch events in the browser // Limit to mobile devices // ==================================================== isTouch : document.createTouch !== undefined && /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent), // Detect if 'translate3d' support is available // ============================================ use3d : (function() { var div = document.createElement('div'); return window.getComputedStyle( div ).getPropertyValue('transform') && !(document.documentMode && document.documentMode <= 11); }()), // Helper function to get current visual state of an element // returns array[ top, left, horizontal-scale, vertical-scale, opacity ] // ===================================================================== getTranslate : function( $el ) { var position, matrix; if ( !$el || !$el.length ) { return false; } position = $el.get( 0 ).getBoundingClientRect(); matrix = $el.eq( 0 ).css('transform'); if ( matrix && matrix.indexOf( 'matrix' ) !== -1 ) { matrix = matrix.split('(')[1]; matrix = matrix.split(')')[0]; matrix = matrix.split(','); } else { matrix = []; } if ( matrix.length ) { // If IE if ( matrix.length > 10 ) { matrix = [ matrix[13], matrix[12], matrix[0], matrix[5] ]; } else { matrix = [ matrix[5], matrix[4], matrix[0], matrix[3]]; } matrix = matrix.map(parseFloat); } else { matrix = [ 0, 0, 1, 1 ]; } return { top : matrix[ 0 ], left : matrix[ 1 ], scaleX : matrix[ 2 ], scaleY : matrix[ 3 ], opacity : parseFloat( $el.css('opacity') ), width : position.width, height : position.height }; }, // Shortcut for setting "translate3d" properties for element // Can set be used to set opacity, too // ======================================================== setTranslate : function( $el, props ) { var str = ''; var css = {}; if ( !$el || !props ) { return; } if ( props.left !== undefined || props.top !== undefined ) { str = ( props.left === undefined ? $el.position().top : props.left ) + 'px, ' + ( props.top === undefined ? $el.position().top : props.top ) + 'px'; if ( this.use3d ) { str = 'translate3d(' + str + ', 0px)'; } else { str = 'translate(' + str + ')'; } } if ( props.scaleX !== undefined && props.scaleY !== undefined ) { str = (str.length ? str + ' ' : '') + 'scale(' + props.scaleX + ', ' + props.scaleY + ')'; } if ( str.length ) { css.transform = str; } if ( props.opacity !== undefined ) { css.opacity = props.opacity; } if ( props.width !== undefined ) { css.width = props.width; } if ( props.height !== undefined ) { css.height = props.height; } return $el.css( css ); }, // Common easings for entrances and exits // t: current time, b: begInnIng value, c: change In value, d: duration // ==================================================================== easing : { easeOutCubic : function (t, b, c, d) { return c * ((t=t/d-1)*t*t + 1) + b; }, easeInCubic : function (t, b, c, d) { return c * (t/=d)*t*t + b; }, easeOutSine : function (t, b, c, d) { return c * Math.sin(t/d * (Math.PI/2)) + b; }, easeInSine : function (t, b, c, d) { return -c * Math.cos(t/d * (Math.PI/2)) + c + b; } }, // Stop fancyBox animation // ======================= stop : function( $el ) { $el.removeData( 'animateID' ); }, // Animate element using "translate3d" // Usage: // animate( element, start properties, end properties, duration, easing, callback ) // or // animate( element, start properties, end properties, duration, callback ) // ================================================================================= animate : function( $el, from, to, duration, easing, done ) { var self = this; var lastTime = null; var animTime = 0; var curr; var diff; var id; var finish = function() { if ( to.scaleX !== undefined && to.scaleY !== undefined && from && from.width !== undefined && from.height !== undefined ) { to.width = from.width * to.scaleX; to.height = from.height * to.scaleY; to.scaleX = 1; to.scaleY = 1; } self.setTranslate( $el, to ); done(); } var frame = function ( timestamp ) { curr = []; diff = 0; // If "stop" method has been called on this element, then just stop if ( !$el.length || $el.data( 'animateID' ) !== id ) { return; } timestamp = timestamp || Date.now(); if ( lastTime ) { diff = timestamp - lastTime; } lastTime = timestamp; animTime += diff; // Are we done? if ( animTime >= duration ) { finish(); return; } for ( var prop in to ) { if ( to.hasOwnProperty( prop ) && from[ prop ] !== undefined ) { if ( from[ prop ] == to[ prop ] ) { curr[ prop ] = to[ prop ]; } else { curr[ prop ] = self.easing[ easing ]( animTime, from[ prop ], to[ prop ] - from[ prop ], duration ); } } } self.setTranslate( $el, curr ); requestAFrame( frame ); }; self.animateID = id = self.animateID === undefined ? 1 : self.animateID + 1; $el.data( 'animateID', id ); if ( done === undefined && $.type(easing) == 'function' ) { done = easing; easing = undefined; } if ( !easing ) { easing = "easeOutCubic"; } done = done || $.noop; if ( from ) { this.setTranslate( $el, from ); } else { // We need current values to calculate change in time from = this.getTranslate( $el ); } if ( duration ) { $el.show(); requestAFrame( frame ); } else { finish(); } } }; // Event handler for click event to "fancyboxed" links // =================================================== function _run( e ) { var target = e.currentTarget, opts = e.data ? e.data.options : {}, items = e.data ? e.data.items : [], value = '', index = 0; e.preventDefault(); e.stopPropagation(); // Get all related items and find index for clicked one if ( $(target).attr( 'data-fancybox' ) ) { value = $(target).data( 'fancybox' ); } if ( value ) { items = items.length ? items.filter( '[data-fancybox="' + value + '"]' ) : $( '[data-fancybox=' + value + ']' ); index = items.index( target ); } else { items = [ target ]; } $.fancybox.open( items, opts, index ); } // Create a jQuery plugin // ====================== $.fn.fancybox = function (options) { this.off('click.fb-start').on('click.fb-start', { items : this, options : options || {} }, _run); return this; }; // Self initializing plugin // ======================== $(document).on('click.fb-start', '[data-fancybox]', _run); }(window, document, window.jQuery)); // ========================================================================== // // Media // Adds additional media type support // // ========================================================================== ;(function ($) { 'use strict'; // Formats matching url to final form var format = function (url, rez, params) { if ( !url ) { return; } params = params || ''; if ( $.type(params) === "object" ) { params = $.param(params, true); } $.each(rez, function (key, value) { url = url.replace('$' + key, value || ''); }); if (params.length) { url += (url.indexOf('?') > 0 ? '&' : '?') + params; } return url; }; // Object containing properties for each media type var media = { youtube: { matcher: /(youtube\.com|youtu\.be|youtube\-nocookie\.com)\/(watch\?(.*&)?v=|v\/|u\/|embed\/?)?(videoseries\?list=(.*)|[\w-]{11}|\?listType=(.*)&list=(.*))(.*)/i, params: { autoplay: 1, autohide: 1, fs: 1, rel: 0, hd: 1, wmode: 'transparent', enablejsapi: 1, html5: 1 }, paramPlace : 8, type: 'iframe', url: '//www.youtube.com/embed/$4', thumb: '//img.youtube.com/vi/$4/hqdefault.jpg' }, vimeo: { matcher: /^.+vimeo.com\/(.*\/)?([\d]+)(.*)?/, params: { autoplay: 1, hd: 1, show_title: 1, show_byline: 1, show_portrait: 0, fullscreen: 1, api: 1 }, paramPlace : 3, type: 'iframe', url: '//player.vimeo.com/video/$2' }, metacafe: { matcher: /metacafe.com\/watch\/(\d+)\/(.*)?/, type: 'iframe', url: '//www.metacafe.com/embed/$1/?ap=1' }, dailymotion: { matcher: /dailymotion.com\/video\/(.*)\/?(.*)/, params: { additionalInfos: 0, autoStart: 1 }, type: 'iframe', url: '//www.dailymotion.com/embed/video/$1' }, vine: { matcher: /vine.co\/v\/([a-zA-Z0-9\?\=\-]+)/, type: 'iframe', url: '//vine.co/v/$1/embed/simple' }, instagram: { matcher: /(instagr\.am|instagram\.com)\/p\/([a-zA-Z0-9_\-]+)\/?/i, type: 'image', url: '//$1/p/$2/media/?size=l' }, // Examples: // http://maps.google.com/?ll=48.857995,2.294297&spn=0.007666,0.021136&t=m&z=16 // http://maps.google.com/?ll=48.857995,2.294297&spn=0.007666,0.021136&t=m&z=16 // https://www.google.lv/maps/place/Googleplex/@37.4220041,-122.0833494,17z/data=!4m5!3m4!1s0x0:0x6c296c66619367e0!8m2!3d37.4219998!4d-122.0840572 google_maps: { matcher: /(maps\.)?google\.([a-z]{2,3}(\.[a-z]{2})?)\/(((maps\/(place\/(.*)\/)?\@(.*),(\d+.?\d+?)z))|(\?ll=))(.*)?/i, type: 'iframe', url: function (rez) { return '//maps.google.' + rez[2] + '/?ll=' + ( rez[9] ? rez[9] + '&z=' + Math.floor( rez[10] ) + ( rez[12] ? rez[12].replace(/^\//, "&") : '' ) : rez[12] ) + '&output=' + ( rez[12] && rez[12].indexOf('layer=c') > 0 ? 'svembed' : 'embed' ); } } }; $(document).on('onInit.fb', function (e, instance) { $.each(instance.group, function( i, item ) { var url = item.src || '', type = false, thumb, rez, params, urlParams, o, id, provider; // Skip items that already have content type if ( item.type ) { return; } // Look for any matching media type $.each(media, function ( n, el ) { rez = url.match(el.matcher); o = {}; provider = n; if (!rez) { return; } type = el.type; if ( el.paramPlace && rez[ el.paramPlace ] ) { urlParams = rez[ el.paramPlace ]; if ( urlParams[ 0 ] == '?' ) { urlParams = urlParams.substring(1); } urlParams = urlParams.split('&'); for ( var m = 0; m < urlParams.length; ++m ) { var p = urlParams[ m ].split('=', 2); if ( p.length == 2 ) { o[ p[0] ] = decodeURIComponent( p[1].replace(/\+/g, " ") ); } } } params = $.extend( true, {}, el.params, item.opts[ n ], o ); url = $.type(el.url) === "function" ? el.url.call(this, rez, params, item) : format(el.url, rez, params); thumb = $.type(el.thumb) === "function" ? el.thumb.call(this, rez, params, item) : format(el.thumb, rez); if ( provider === 'vimeo' ) { url = url.replace('&%23', '#'); } return false; }); // If it is found, then change content type and update the url if ( type ) { item.src = url; item.type = type; if ( !item.opts.thumb && !(item.opts.$thumb && item.opts.$thumb.length ) ) { item.opts.thumb = thumb; } if ( type === 'iframe' ) { $.extend(true, item.opts, { iframe : { preload : false, scrolling : "no" }, smallBtn : false, closeBtn : true, fullScreen : false, slideShow : false }); item.opts.slideClass += ' fancybox-slide--video'; } } else { // If no content type is found, then set it to `iframe` as fallback item.type = 'iframe'; } }); }); }(window.jQuery)); // ========================================================================== // // Guestures // Adds touch guestures, handles click and tap events // // ========================================================================== ;(function (window, document, $) { 'use strict'; var requestAFrame = (function() { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function( callback ) { window.setTimeout(callback, 1000 / 60); }; })(); var pointers = function( e ) { var result = []; e = e.originalEvent || e || window.e; e = e.touches && e.touches.length ? e.touches : ( e.changedTouches && e.changedTouches.length ? e.changedTouches : [ e ] ); for ( var key in e ) { if ( e[ key ].pageX ) { result.push( { x : e[ key ].pageX, y : e[ key ].pageY } ); } else if ( e[ key ].clientX ) { result.push( { x : e[ key ].clientX, y : e[ key ].clientY } ); } } return result; }; var distance = function( point2, point1, what ) { if ( !point1 || !point2 ) { return 0; } if ( what === 'x' ) { return point2.x - point1.x; } else if ( what === 'y' ) { return point2.y - point1.y; } return Math.sqrt( Math.pow( point2.x - point1.x, 2 ) + Math.pow( point2.y - point1.y, 2 ) ); }; var isClickable = function( $el ) { return $el.is('a') || $el.is('button') || $el.is('input') || $el.is('select') || $el.is('textarea') || $.isFunction( $el.get(0).onclick ); }; var hasScrollbars = function( el ) { var overflowY = window.getComputedStyle( el )['overflow-y']; var overflowX = window.getComputedStyle( el )['overflow-x']; var vertical = (overflowY === 'scroll' || overflowY === 'auto') && el.scrollHeight > el.clientHeight; var horizontal = (overflowX === 'scroll' || overflowX === 'auto') && el.scrollWidth > el.clientWidth; return vertical || horizontal; }; var isScrollable = function ( $el ) { var rez = false; while ( true ) { rez = hasScrollbars( $el.get(0) ); if ( rez ) { break; } $el = $el.parent(); if ( !$el.length || $el.hasClass('fancybox-slider') || $el.is('body') ) { break; } } return rez; }; var Guestures = function ( instance ) { var self = this; self.instance = instance; self.$wrap = instance.$refs.slider_wrap; self.$slider = instance.$refs.slider; self.$container = instance.$refs.container; self.destroy(); self.$wrap.on('touchstart.fb mousedown.fb', $.proxy(self, "ontouchstart")); }; Guestures.prototype.destroy = function() { this.$wrap.off('touchstart.fb mousedown.fb touchmove.fb mousemove.fb touchend.fb touchcancel.fb mouseup.fb mouseleave.fb'); }; Guestures.prototype.ontouchstart = function( e ) { var self = this; var $target = $( e.target ); var instance = self.instance; var current = instance.current; var $content = current.$content || current.$placeholder; self.startPoints = pointers( e ); self.$target = $target; self.$content = $content; self.canvasWidth = Math.round( current.$slide[0].clientWidth ); self.canvasHeight = Math.round( current.$slide[0].clientHeight ); self.startEvent = e; // Skip if clicked on the scrollbar if ( e.originalEvent.clientX > self.canvasWidth ) { return true; } // If "touch" is disabled, then handle click event if ( !current.opts.touch ) { self.endPoints = self.startPoints; return self.ontap(); } // Ignore taping on links, buttons and scrollable items if ( isClickable( $target ) || isClickable( $target.parent() ) || ( isScrollable( $target ) && !$target.hasClass('fancybox-slide') ) ) { return; } // Ignore right click if ( e.originalEvent && e.originalEvent.button == 2 ) { return; } e.stopPropagation(); e.preventDefault(); if ( !current || self.instance.isAnimating || self.instance.isClosing ) { return; } // Prevent zooming if already swiping if ( !self.startPoints || ( self.startPoints.length > 1 && !current.isMoved ) ) { return; } self.$wrap.off('touchmove.fb mousemove.fb', $.proxy(self, "ontouchmove")); self.$wrap.off('touchend.fb touchcancel.fb mouseup.fb mouseleave.fb', $.proxy(self, "ontouchend")); self.$wrap.on('touchend.fb touchcancel.fb mouseup.fb mouseleave.fb', $.proxy(self, "ontouchend")); self.$wrap.on('touchmove.fb mousemove.fb', $.proxy(self, "ontouchmove")); self.startTime = new Date().getTime(); self.distanceX = self.distanceY = self.distance = 0; self.canTap = false; self.isPanning = false; self.isSwiping = false; self.isZooming = false; self.sliderStartPos = $.fancybox.getTranslate( self.$slider ); self.contentStartPos = $.fancybox.getTranslate( self.$content ); self.contentLastPos = null; if ( self.startPoints.length === 1 && !self.isZooming ) { self.canTap = current.isMoved; if ( current.type === 'image' && ( self.contentStartPos.width > self.canvasWidth + 1 || self.contentStartPos.height > self.canvasHeight + 1 ) ) { $.fancybox.stop( self.$content ); self.isPanning = true; } else { $.fancybox.stop( self.$slider ); self.isSwiping = true; } self.$container.addClass('fancybox-controls--isGrabbing'); } if ( self.startPoints.length === 2 && current.isMoved && !current.hasError && current.type === 'image' && ( current.isLoaded || current.$ghost ) ) { self.isZooming = true; self.isSwiping = false; self.isPanning = false; $.fancybox.stop( self.$content ); self.centerPointStartX = ( ( self.startPoints[0].x + self.startPoints[1].x ) * 0.5 ) - $(window).scrollLeft(); self.centerPointStartY = ( ( self.startPoints[0].y + self.startPoints[1].y ) * 0.5 ) - $(window).scrollTop(); self.percentageOfImageAtPinchPointX = ( self.centerPointStartX - self.contentStartPos.left ) / self.contentStartPos.width; self.percentageOfImageAtPinchPointY = ( self.centerPointStartY - self.contentStartPos.top ) / self.contentStartPos.height; self.startDistanceBetweenFingers = distance( self.startPoints[0], self.startPoints[1] ); } }; Guestures.prototype.ontouchmove = function( e ) { var self = this; e.preventDefault(); self.newPoints = pointers( e ); if ( !self.newPoints || !self.newPoints.length ) { return; } self.distanceX = distance( self.newPoints[0], self.startPoints[0], 'x' ); self.distanceY = distance( self.newPoints[0], self.startPoints[0], 'y' ); self.distance = distance( self.newPoints[0], self.startPoints[0] ); // Skip false ontouchmove events (Chrome) if ( self.distance > 0 ) { if ( self.isSwiping ) { self.onSwipe(); } else if ( self.isPanning ) { self.onPan(); } else if ( self.isZooming ) { self.onZoom(); } } }; Guestures.prototype.onSwipe = function() { var self = this; var swiping = self.isSwiping; var left = self.sliderStartPos.left; var angle; if ( swiping === true ) { if ( Math.abs( self.distance ) > 10 ) { if ( self.instance.group.length < 2 ) { self.isSwiping = 'y'; } else if ( !self.instance.current.isMoved || self.instance.opts.touch.vertical === false || ( self.instance.opts.touch.vertical === 'auto' && $( window ).width() > 800 ) ) { self.isSwiping = 'x'; } else { angle = Math.abs( Math.atan2( self.distanceY, self.distanceX ) * 180 / Math.PI ); self.isSwiping = ( angle > 45 && angle < 135 ) ? 'y' : 'x'; } self.canTap = false; self.instance.current.isMoved = false; // Reset points to avoid jumping, because we dropped first swipes to calculate the angle self.startPoints = self.newPoints; } } else { if ( swiping == 'x' ) { // Sticky edges if ( !self.instance.current.opts.loop && self.instance.current.index === 0 && self.distanceX > 0 ) { left = left + Math.pow( self.distanceX, 0.8 ); } else if ( !self.instance.current.opts.loop &&self.instance.current.index === self.instance.group.length - 1 && self.distanceX < 0 ) { left = left - Math.pow( -self.distanceX, 0.8 ); } else { left = left + self.distanceX; } } self.sliderLastPos = { top : swiping == 'x' ? 0 : self.sliderStartPos.top + self.distanceY, left : left }; requestAFrame(function() { $.fancybox.setTranslate( self.$slider, self.sliderLastPos ); }); } }; Guestures.prototype.onPan = function() { var self = this; var newOffsetX, newOffsetY, newPos; self.canTap = false; if ( self.contentStartPos.width > self.canvasWidth ) { newOffsetX = self.contentStartPos.left + self.distanceX; } else { newOffsetX = self.contentStartPos.left; } newOffsetY = self.contentStartPos.top + self.distanceY; newPos = self.limitMovement( newOffsetX, newOffsetY, self.contentStartPos.width, self.contentStartPos.height ); newPos.scaleX = self.contentStartPos.scaleX; newPos.scaleY = self.contentStartPos.scaleY; self.contentLastPos = newPos; requestAFrame(function() { $.fancybox.setTranslate( self.$content, self.contentLastPos ); }); }; // Make panning sticky to the edges Guestures.prototype.limitMovement = function( newOffsetX, newOffsetY, newWidth, newHeight ) { var self = this; var minTranslateX, minTranslateY, maxTranslateX, maxTranslateY; var canvasWidth = self.canvasWidth; var canvasHeight = self.canvasHeight; var currentOffsetX = self.contentStartPos.left; var currentOffsetY = self.contentStartPos.top; var distanceX = self.distanceX; var distanceY = self.distanceY; // Slow down proportionally to traveled distance minTranslateX = Math.max(0, canvasWidth * 0.5 - newWidth * 0.5 ); minTranslateY = Math.max(0, canvasHeight * 0.5 - newHeight * 0.5 ); maxTranslateX = Math.min( canvasWidth - newWidth, canvasWidth * 0.5 - newWidth * 0.5 ); maxTranslateY = Math.min( canvasHeight - newHeight, canvasHeight * 0.5 - newHeight * 0.5 ); if ( newWidth > canvasWidth ) { // -> if ( distanceX > 0 && newOffsetX > minTranslateX ) { newOffsetX = minTranslateX - 1 + Math.pow( -minTranslateX + currentOffsetX + distanceX, 0.8 ) || 0; } // <- if ( distanceX < 0 && newOffsetX < maxTranslateX ) { newOffsetX = maxTranslateX + 1 - Math.pow( maxTranslateX - currentOffsetX - distanceX, 0.8 ) || 0; } } if ( newHeight > canvasHeight ) { // \/ if ( distanceY > 0 && newOffsetY > minTranslateY ) { newOffsetY = minTranslateY - 1 + Math.pow(-minTranslateY + currentOffsetY + distanceY, 0.8 ) || 0; } // /\ if ( distanceY < 0 && newOffsetY < maxTranslateY ) { newOffsetY = maxTranslateY + 1 - Math.pow ( maxTranslateY - currentOffsetY - distanceY, 0.8 ) || 0; } } return { top : newOffsetY, left : newOffsetX }; }; Guestures.prototype.limitPosition = function( newOffsetX, newOffsetY, newWidth, newHeight ) { var self = this; var canvasWidth = self.canvasWidth; var canvasHeight = self.canvasHeight; if ( newWidth > canvasWidth ) { newOffsetX = newOffsetX > 0 ? 0 : newOffsetX; newOffsetX = newOffsetX < canvasWidth - newWidth ? canvasWidth - newWidth : newOffsetX; } else { // Center horizontally newOffsetX = Math.max( 0, canvasWidth / 2 - newWidth / 2 ); } if ( newHeight > canvasHeight ) { newOffsetY = newOffsetY > 0 ? 0 : newOffsetY; newOffsetY = newOffsetY < canvasHeight - newHeight ? canvasHeight - newHeight : newOffsetY; } else { // Center vertically newOffsetY = Math.max( 0, canvasHeight / 2 - newHeight / 2 ); } return { top : newOffsetY, left : newOffsetX }; }; Guestures.prototype.onZoom = function() { var self = this; // Calculate current distance between points to get pinch ratio and new width and height var currentWidth = self.contentStartPos.width; var currentHeight = self.contentStartPos.height; var currentOffsetX = self.contentStartPos.left; var currentOffsetY = self.contentStartPos.top; var endDistanceBetweenFingers = distance( self.newPoints[0], self.newPoints[1] ); var pinchRatio = endDistanceBetweenFingers / self.startDistanceBetweenFingers; var newWidth = Math.floor( currentWidth * pinchRatio ); var newHeight = Math.floor( currentHeight * pinchRatio ); // This is the translation due to pinch-zooming var translateFromZoomingX = (currentWidth - newWidth) * self.percentageOfImageAtPinchPointX; var translateFromZoomingY = (currentHeight - newHeight) * self.percentageOfImageAtPinchPointY; //Point between the two touches var centerPointEndX = ((self.newPoints[0].x + self.newPoints[1].x) / 2) - $(window).scrollLeft(); var centerPointEndY = ((self.newPoints[0].y + self.newPoints[1].y) / 2) - $(window).scrollTop(); // And this is the translation due to translation of the centerpoint // between the two fingers var translateFromTranslatingX = centerPointEndX - self.centerPointStartX; var translateFromTranslatingY = centerPointEndY - self.centerPointStartY; // The new offset is the old/current one plus the total translation var newOffsetX = currentOffsetX + ( translateFromZoomingX + translateFromTranslatingX ); var newOffsetY = currentOffsetY + ( translateFromZoomingY + translateFromTranslatingY ); var newPos = { top : newOffsetY, left : newOffsetX, scaleX : self.contentStartPos.scaleX * pinchRatio, scaleY : self.contentStartPos.scaleY * pinchRatio }; self.canTap = false; self.newWidth = newWidth; self.newHeight = newHeight; self.contentLastPos = newPos; requestAFrame(function() { $.fancybox.setTranslate( self.$content, self.contentLastPos ); }); }; Guestures.prototype.ontouchend = function( e ) { var self = this; var current = self.instance.current; var dMs = Math.max( (new Date().getTime() ) - self.startTime, 1); var swiping = self.isSwiping; var panning = self.isPanning; var zooming = self.isZooming; self.endPoints = pointers( e ); self.$container.removeClass('fancybox-controls--isGrabbing'); self.$wrap.off('touchmove.fb mousemove.fb', $.proxy(this, "ontouchmove")); self.$wrap.off('touchend.fb touchcancel.fb mouseup.fb mouseleave.fb', $.proxy(this, "ontouchend")); self.isSwiping = false; self.isPanning = false; self.isZooming = false; if ( self.canTap ) { return self.ontap(); } // Speed in px/ms self.velocityX = self.distanceX / dMs * 0.5; self.velocityY = self.distanceY / dMs * 0.5; self.speed = current.opts.speed || 330; self.speedX = Math.max( self.speed * 0.75, Math.min( self.speed * 1.5, ( 1 / Math.abs( self.velocityX ) ) * self.speed ) ); self.speedY = Math.max( self.speed * 0.75, Math.min( self.speed * 1.5, ( 1 / Math.abs( self.velocityY ) ) * self.speed ) ); if ( panning ) { self.endPanning(); } else if ( zooming ) { self.endZooming(); } else { self.endSwiping( swiping ); } return; }; Guestures.prototype.endSwiping = function( swiping ) { var self = this; // Close if swiped vertically / navigate if horizontally if ( swiping == 'y' && Math.abs( self.distanceY ) > 50 ) { // Continue vertical movement $.fancybox.animate( self.$slider, null, { top : self.sliderStartPos.top + self.distanceY + self.velocityY * 150, left : self.sliderStartPos.left, opacity : 0 }, self.speedY ); self.instance.close( true ); } else if ( swiping == 'x' && self.distanceX > 50 ) { self.instance.previous( self.speedX ); } else if ( swiping == 'x' && self.distanceX < -50 ) { self.instance.next( self.speedX ); } else { // Move back to center self.instance.update( false, true, 150 ); } }; Guestures.prototype.endPanning = function() { var self = this; var newOffsetX, newOffsetY, newPos; if ( !self.contentLastPos ) { return; } newOffsetX = self.contentLastPos.left + ( self.velocityX * self.speed * 2 ); newOffsetY = self.contentLastPos.top + ( self.velocityY * self.speed * 2 ); newPos = self.limitPosition( newOffsetX, newOffsetY, self.contentStartPos.width, self.contentStartPos.height ); newPos.width = self.contentStartPos.width; newPos.height = self.contentStartPos.height; $.fancybox.animate( self.$content, null, newPos, self.speed, "easeOutSine" ); }; Guestures.prototype.endZooming = function() { var self = this; var current = self.instance.current; var newOffsetX, newOffsetY, newPos, reset; var newWidth = self.newWidth; var newHeight = self.newHeight; if ( !self.contentLastPos ) { return; } newOffsetX = self.contentLastPos.left; newOffsetY = self.contentLastPos.top; reset = { top : newOffsetY, left : newOffsetX, width : newWidth, height : newHeight, scaleX : 1, scaleY : 1 }; // Reset scalex/scaleY values; this helps for perfomance and does not break animation $.fancybox.setTranslate( self.$content, reset ); if ( newWidth < self.canvasWidth && newHeight < self.canvasHeight ) { self.instance.scaleToFit( 150 ); } else if ( newWidth > current.width || newHeight > current.height ) { self.instance.scaleToActual( self.centerPointStartX, self.centerPointStartY, 150 ); } else { newPos = self.limitPosition( newOffsetX, newOffsetY, newWidth, newHeight ); $.fancybox.animate( self.$content, null, newPos, self.speed, "easeOutSine" ); } }; Guestures.prototype.ontap = function() { var self = this; var instance = self.instance; var current = instance.current; var x = self.endPoints[0].x; var y = self.endPoints[0].y; x = x - self.$wrap.offset().left; y = y - self.$wrap.offset().top; // Stop slideshow if ( instance.SlideShow && instance.SlideShow.isActive ) { instance.SlideShow.stop(); } if ( !$.fancybox.isTouch ) { if ( current.opts.closeClickOutside && self.$target.is('.fancybox-slide') ) { instance.close( self.startEvent ); return; } if ( current.type == 'image' && current.isMoved ) { if ( instance.canPan() ) { instance.scaleToFit(); } else if ( instance.isScaledDown() ) { instance.scaleToActual( x, y ); } else if ( instance.group.length < 2 ) { instance.close( self.startEvent ); } } return; } // Double tap if ( self.tapped ) { clearTimeout( self.tapped ); self.tapped = null; if ( Math.abs( x - self.x ) > 50 || Math.abs( y - self.y ) > 50 || !current.isMoved ) { return this; } if ( current.type == 'image' && ( current.isLoaded || current.$ghost ) ) { if ( instance.canPan() ) { instance.scaleToFit(); } else if ( instance.isScaledDown() ) { instance.scaleToActual( x, y ); } } } else { // Single tap self.x = x; self.y = y; self.tapped = setTimeout(function() { self.tapped = null; instance.toggleControls( true ); }, 300); } return this; }; $(document).on('onActivate.fb', function (e, instance) { if ( !instance.Guestures ) { instance.Guestures = new Guestures( instance ); } }); $(document).on('beforeClose.fb', function (e, instance) { if ( instance.Guestures ) { instance.Guestures.destroy(); } }); }(window, document, window.jQuery)); // ========================================================================== // // SlideShow // Enables slideshow functionality // // Example of usage: // $.fancybox.getInstance().slideShow.start() // // ========================================================================== ;(function (document, $) { 'use strict'; var SlideShow = function( instance ) { this.instance = instance; this.init(); }; $.extend( SlideShow.prototype, { timer : null, isActive : false, $button : null, speed : 3000, init : function() { var self = this; self.$button = $('<button data-fancybox-play class="fancybox-button fancybox-button--play" title="Slideshow (P)"></button>') .appendTo( self.instance.$refs.buttons ); self.instance.$refs.container.on('click', '[data-fancybox-play]', function() { self.toggle(); }); }, set : function() { var self = this; // Check if reached last element if ( self.instance && self.instance.current && (self.instance.current.opts.loop || self.instance.currIndex < self.instance.group.length - 1 )) { self.timer = setTimeout(function() { self.instance.next(); }, self.instance.current.opts.slideShow.speed || self.speed); } else { self.stop(); } }, clear : function() { var self = this; clearTimeout( self.timer ); self.timer = null; }, start : function() { var self = this; self.stop(); if ( self.instance && self.instance.current && ( self.instance.current.opts.loop || self.instance.currIndex < self.instance.group.length - 1 )) { self.instance.$refs.container.on({ 'beforeLoad.fb.player' : $.proxy(self, "clear"), 'onComplete.fb.player' : $.proxy(self, "set"), }); self.isActive = true; if ( self.instance.current.isComplete ) { self.set(); } self.instance.$refs.container.trigger('onPlayStart'); self.$button.addClass('fancybox-button--pause'); } }, stop: function() { var self = this; self.clear(); self.instance.$refs.container .trigger('onPlayEnd') .off('.player'); self.$button.removeClass('fancybox-button--pause'); self.isActive = false; }, toggle : function() { var self = this; if ( self.isActive ) { self.stop(); } else { self.start(); } } }); $(document).on('onInit.fb', function(e, instance) { if ( !!instance.opts.slideShow && !instance.SlideShow && instance.group.length > 1 ) { instance.SlideShow = new SlideShow( instance ); } }); $(document).on('beforeClose.fb onDeactivate.fb', function(e, instance) { if ( instance.SlideShow ) { instance.SlideShow.stop(); } }); }(document, window.jQuery)); // ========================================================================== // // FullScreen // Adds fullscreen functionality // // ========================================================================== ;(function (document, $) { 'use strict'; var FullScreen = function( instance ) { this.instance = instance; this.init(); }; $.extend( FullScreen.prototype, { $button : null, init : function() { var self = this; if ( !self.isAvailable() ) { return; } self.$button = $('<button data-fancybox-fullscreen class="fancybox-button fancybox-button--fullscreen" title="Full screen (F)"></button>') .appendTo( self.instance.$refs.buttons ); self.instance.$refs.container.on('click.fb-fullscreen', '[data-fancybox-fullscreen]', function(e) { e.stopPropagation(); e.preventDefault(); self.toggle(); }); $(document).on('onUpdate.fb', function(e, instance) { self.$button.toggle( !!instance.current.opts.fullScreen ); self.$button.toggleClass('fancybox-button-shrink', self.isActivated() ); }); $(document).on('afterClose.fb', function() { self.exit(); }); }, isAvailable : function() { var element = this.instance.$refs.container.get(0); return !!(element.requestFullscreen || element.msRequestFullscreen || element.mozRequestFullScreen || element.webkitRequestFullscreen); }, isActivated : function() { return !(!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement); }, launch : function() { var element = this.instance.$refs.container.get(0); if ( !element || this.instance.isClosing ) { return; } if (element.requestFullscreen) { element.requestFullscreen(); } else if (element.msRequestFullscreen) { element.msRequestFullscreen(); } else if (element.mozRequestFullScreen) { element.mozRequestFullScreen(); } else if (element.webkitRequestFullscreen) { element.webkitRequestFullscreen(element.ALLOW_KEYBOARD_INPUT); } }, exit : function() { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); } }, toggle : function() { if ( this.isActivated() ) { this.exit(); } else if ( this.isAvailable() ) { this.launch(); } } }); $(document).on('onInit.fb', function(e, instance) { if ( !!instance.opts.fullScreen && !instance.FullScreen) { instance.FullScreen = new FullScreen( instance ); } }); }(document, window.jQuery)); // ========================================================================== // // Thumbs // Displays thumbnails in a grid // // ========================================================================== ;(function (document, $) { 'use strict'; var FancyThumbs = function( instance ) { this.instance = instance; this.init(); }; $.extend( FancyThumbs.prototype, { $button : null, $grid : null, $list : null, isVisible : false, init : function() { var self = this; self.$button = $('<button data-fancybox-thumbs class="fancybox-button fancybox-button--thumbs" title="Thumbnails (G)"></button>') .appendTo( this.instance.$refs.buttons ) .on('touchend click', function(e) { e.stopPropagation(); e.preventDefault(); self.toggle(); }); }, create : function() { var instance = this.instance, list, src; this.$grid = $('<div class="fancybox-thumbs"></div>').appendTo( instance.$refs.container ); list = '<ul>'; $.each(instance.group, function( i, item ) { src = item.opts.thumb || ( item.opts.$thumb ? item.opts.$thumb.attr('src') : null ); if ( !src && item.type === 'image' ) { src = item.src; } if ( src && src.length ) { list += '<li data-index="' + i + '" tabindex="0" class="fancybox-thumbs-loading"><img data-src="' + src + '" /></li>'; } }); list += '</ul>'; this.$list = $( list ).appendTo( this.$grid ).on('click touchstart', 'li', function() { instance.jumpTo( $(this).data('index') ); }); this.$list.find('img').hide().one('load', function() { var $parent = $(this).parent().removeClass('fancybox-thumbs-loading'), thumbWidth = $parent.outerWidth(), thumbHeight = $parent.outerHeight(), width, height, widthRatio, heightRatio; width = this.naturalWidth || this.width; height = this.naturalHeight || this.height; //Calculate thumbnail width/height and center it widthRatio = width / thumbWidth; heightRatio = height / thumbHeight; if (widthRatio >= 1 && heightRatio >= 1) { if (widthRatio > heightRatio) { width = width / heightRatio; height = thumbHeight; } else { width = thumbWidth; height = height / widthRatio; } } $(this).css({ width : Math.floor(width), height : Math.floor(height), 'margin-top' : Math.min( 0, Math.floor(thumbHeight * 0.3 - height * 0.3 ) ), 'margin-left' : Math.min( 0, Math.floor(thumbWidth * 0.5 - width * 0.5 ) ) }).show(); }) .each(function() { this.src = $( this ).data( 'src' ); }); }, focus : function() { if ( this.instance.current ) { this.$list .children() .removeClass('fancybox-thumbs-active') .filter('[data-index="' + this.instance.current.index + '"]') .addClass('fancybox-thumbs-active') .focus(); } }, close : function() { this.$grid.hide(); }, update : function() { this.instance.$refs.container.toggleClass('fancybox-container--thumbs', this.isVisible); if ( this.isVisible ) { if ( !this.$grid ) { this.create(); } this.$grid.show(); this.focus(); } else if ( this.$grid ) { this.$grid.hide(); } this.instance.update(); }, hide : function() { this.isVisible = false; this.update(); }, show : function() { this.isVisible = true; this.update(); }, toggle : function() { if ( this.isVisible ) { this.hide(); } else { this.show(); } } }); $(document).on('onInit.fb', function(e, instance) { var first = instance.group[0], second = instance.group[1]; if ( !!instance.opts.thumbs && !instance.Thumbs && instance.group.length > 1 && ( ( first.type == 'image' || first.opts.thumb || first.opts.$thumb ) && ( second.type == 'image' || second.opts.thumb || second.opts.$thumb ) ) ) { instance.Thumbs = new FancyThumbs( instance ); } }); $(document).on('beforeMove.fb', function(e, instance, item) { var self = instance.Thumbs; if ( !self ) { return; } if ( item.modal ) { self.$button.hide(); self.hide(); } else { if ( instance.opts.thumbs.showOnStart === true && instance.firstRun ) { self.show(); } self.$button.show(); if ( self.isVisible ) { self.focus(); } } }); $(document).on('beforeClose.fb', function(e, instance) { if ( instance.Thumbs && instance.Thumbs.isVisible && instance.opts.thumbs.hideOnClosing !== false ) { instance.Thumbs.close(); } instance.Thumbs = null; }); }(document, window.jQuery));
YUI.add('event-simulate', function(Y) { (function() { /** * Simulate user interaction by generating native DOM events. * * @module event-simulate * @requires event */ //shortcuts var L = Y.Lang, isFunction = L.isFunction, isString = L.isString, isBoolean = L.isBoolean, isObject = L.isObject, isNumber = L.isNumber, //mouse events supported mouseEvents = { click: 1, dblclick: 1, mouseover: 1, mouseout: 1, mousedown: 1, mouseup: 1, mousemove: 1, contextmenu:1 }, //key events supported keyEvents = { keydown: 1, keyup: 1, keypress: 1 }, //HTML events supported uiEvents = { submit: 1, blur: 1, change: 1, focus: 1, resize: 1, scroll: 1, select: 1 }, //events that bubble by default bubbleEvents = { scroll: 1, resize: 1, reset: 1, submit: 1, change: 1, select: 1, error: 1, abort: 1 }, //touch events supported touchEvents = { touchstart: 1, touchmove: 1, touchend: 1, touchcancel: 1 }, gestureEvents = { gesturestart: 1, gesturechange: 1, gestureend: 1 }; //all key, mouse and touch events bubble Y.mix(bubbleEvents, mouseEvents); Y.mix(bubbleEvents, keyEvents); Y.mix(bubbleEvents, touchEvents); /* * Note: Intentionally not for YUIDoc generation. * Simulates a key event using the given event information to populate * the generated event object. This method does browser-equalizing * calculations to account for differences in the DOM and IE event models * as well as different browser quirks. Note: keydown causes Safari 2.x to * crash. * @method simulateKeyEvent * @private * @static * @param {HTMLElement} target The target of the given event. * @param {String} type The type of event to fire. This can be any one of * the following: keyup, keydown, and keypress. * @param {Boolean} bubbles (Optional) Indicates if the event can be * bubbled up. DOM Level 3 specifies that all key events bubble by * default. The default is true. * @param {Boolean} cancelable (Optional) Indicates if the event can be * canceled using preventDefault(). DOM Level 3 specifies that all * key events can be cancelled. The default * is true. * @param {Window} view (Optional) The view containing the target. This is * typically the window object. The default is window. * @param {Boolean} ctrlKey (Optional) Indicates if one of the CTRL keys * is pressed while the event is firing. The default is false. * @param {Boolean} altKey (Optional) Indicates if one of the ALT keys * is pressed while the event is firing. The default is false. * @param {Boolean} shiftKey (Optional) Indicates if one of the SHIFT keys * is pressed while the event is firing. The default is false. * @param {Boolean} metaKey (Optional) Indicates if one of the META keys * is pressed while the event is firing. The default is false. * @param {int} keyCode (Optional) The code for the key that is in use. * The default is 0. * @param {int} charCode (Optional) The Unicode code for the character * associated with the key being used. The default is 0. */ function simulateKeyEvent(target /*:HTMLElement*/, type /*:String*/, bubbles /*:Boolean*/, cancelable /*:Boolean*/, view /*:Window*/, ctrlKey /*:Boolean*/, altKey /*:Boolean*/, shiftKey /*:Boolean*/, metaKey /*:Boolean*/, keyCode /*:int*/, charCode /*:int*/) /*:Void*/ { //check target if (!target){ Y.error("simulateKeyEvent(): Invalid target."); } //check event type if (isString(type)){ type = type.toLowerCase(); switch(type){ case "textevent": //DOM Level 3 type = "keypress"; break; case "keyup": case "keydown": case "keypress": break; default: Y.error("simulateKeyEvent(): Event type '" + type + "' not supported."); } } else { Y.error("simulateKeyEvent(): Event type must be a string."); } //setup default values if (!isBoolean(bubbles)){ bubbles = true; //all key events bubble } if (!isBoolean(cancelable)){ cancelable = true; //all key events can be cancelled } if (!isObject(view)){ view = Y.config.win; //view is typically window } if (!isBoolean(ctrlKey)){ ctrlKey = false; } if (!isBoolean(altKey)){ altKey = false; } if (!isBoolean(shiftKey)){ shiftKey = false; } if (!isBoolean(metaKey)){ metaKey = false; } if (!isNumber(keyCode)){ keyCode = 0; } if (!isNumber(charCode)){ charCode = 0; } //try to create a mouse event var customEvent /*:MouseEvent*/ = null; //check for DOM-compliant browsers first if (isFunction(Y.config.doc.createEvent)){ try { //try to create key event customEvent = Y.config.doc.createEvent("KeyEvents"); /* * Interesting problem: Firefox implemented a non-standard * version of initKeyEvent() based on DOM Level 2 specs. * Key event was removed from DOM Level 2 and re-introduced * in DOM Level 3 with a different interface. Firefox is the * only browser with any implementation of Key Events, so for * now, assume it's Firefox if the above line doesn't error. */ // @TODO: Decipher between Firefox's implementation and a correct one. customEvent.initKeyEvent(type, bubbles, cancelable, view, ctrlKey, altKey, shiftKey, metaKey, keyCode, charCode); } catch (ex /*:Error*/){ /* * If it got here, that means key events aren't officially supported. * Safari/WebKit is a real problem now. WebKit 522 won't let you * set keyCode, charCode, or other properties if you use a * UIEvent, so we first must try to create a generic event. The * fun part is that this will throw an error on Safari 2.x. The * end result is that we need another try...catch statement just to * deal with this mess. */ try { //try to create generic event - will fail in Safari 2.x customEvent = Y.config.doc.createEvent("Events"); } catch (uierror /*:Error*/){ //the above failed, so create a UIEvent for Safari 2.x customEvent = Y.config.doc.createEvent("UIEvents"); } finally { customEvent.initEvent(type, bubbles, cancelable); //initialize customEvent.view = view; customEvent.altKey = altKey; customEvent.ctrlKey = ctrlKey; customEvent.shiftKey = shiftKey; customEvent.metaKey = metaKey; customEvent.keyCode = keyCode; customEvent.charCode = charCode; } } //fire the event target.dispatchEvent(customEvent); } else if (isObject(Y.config.doc.createEventObject)){ //IE //create an IE event object customEvent = Y.config.doc.createEventObject(); //assign available properties customEvent.bubbles = bubbles; customEvent.cancelable = cancelable; customEvent.view = view; customEvent.ctrlKey = ctrlKey; customEvent.altKey = altKey; customEvent.shiftKey = shiftKey; customEvent.metaKey = metaKey; /* * IE doesn't support charCode explicitly. CharCode should * take precedence over any keyCode value for accurate * representation. */ customEvent.keyCode = (charCode > 0) ? charCode : keyCode; //fire the event target.fireEvent("on" + type, customEvent); } else { Y.error("simulateKeyEvent(): No event simulation framework present."); } } /* * Note: Intentionally not for YUIDoc generation. * Simulates a mouse event using the given event information to populate * the generated event object. This method does browser-equalizing * calculations to account for differences in the DOM and IE event models * as well as different browser quirks. * @method simulateMouseEvent * @private * @static * @param {HTMLElement} target The target of the given event. * @param {String} type The type of event to fire. This can be any one of * the following: click, dblclick, mousedown, mouseup, mouseout, * mouseover, and mousemove. * @param {Boolean} bubbles (Optional) Indicates if the event can be * bubbled up. DOM Level 2 specifies that all mouse events bubble by * default. The default is true. * @param {Boolean} cancelable (Optional) Indicates if the event can be * canceled using preventDefault(). DOM Level 2 specifies that all * mouse events except mousemove can be cancelled. The default * is true for all events except mousemove, for which the default * is false. * @param {Window} view (Optional) The view containing the target. This is * typically the window object. The default is window. * @param {int} detail (Optional) The number of times the mouse button has * been used. The default value is 1. * @param {int} screenX (Optional) The x-coordinate on the screen at which * point the event occured. The default is 0. * @param {int} screenY (Optional) The y-coordinate on the screen at which * point the event occured. The default is 0. * @param {int} clientX (Optional) The x-coordinate on the client at which * point the event occured. The default is 0. * @param {int} clientY (Optional) The y-coordinate on the client at which * point the event occured. The default is 0. * @param {Boolean} ctrlKey (Optional) Indicates if one of the CTRL keys * is pressed while the event is firing. The default is false. * @param {Boolean} altKey (Optional) Indicates if one of the ALT keys * is pressed while the event is firing. The default is false. * @param {Boolean} shiftKey (Optional) Indicates if one of the SHIFT keys * is pressed while the event is firing. The default is false. * @param {Boolean} metaKey (Optional) Indicates if one of the META keys * is pressed while the event is firing. The default is false. * @param {int} button (Optional) The button being pressed while the event * is executing. The value should be 0 for the primary mouse button * (typically the left button), 1 for the terciary mouse button * (typically the middle button), and 2 for the secondary mouse button * (typically the right button). The default is 0. * @param {HTMLElement} relatedTarget (Optional) For mouseout events, * this is the element that the mouse has moved to. For mouseover * events, this is the element that the mouse has moved from. This * argument is ignored for all other events. The default is null. */ function simulateMouseEvent(target /*:HTMLElement*/, type /*:String*/, bubbles /*:Boolean*/, cancelable /*:Boolean*/, view /*:Window*/, detail /*:int*/, screenX /*:int*/, screenY /*:int*/, clientX /*:int*/, clientY /*:int*/, ctrlKey /*:Boolean*/, altKey /*:Boolean*/, shiftKey /*:Boolean*/, metaKey /*:Boolean*/, button /*:int*/, relatedTarget /*:HTMLElement*/) /*:Void*/ { //check target if (!target){ Y.error("simulateMouseEvent(): Invalid target."); } //check event type if (isString(type)){ type = type.toLowerCase(); //make sure it's a supported mouse event if (!mouseEvents[type]){ Y.error("simulateMouseEvent(): Event type '" + type + "' not supported."); } } else { Y.error("simulateMouseEvent(): Event type must be a string."); } //setup default values if (!isBoolean(bubbles)){ bubbles = true; //all mouse events bubble } if (!isBoolean(cancelable)){ cancelable = (type != "mousemove"); //mousemove is the only one that can't be cancelled } if (!isObject(view)){ view = Y.config.win; //view is typically window } if (!isNumber(detail)){ detail = 1; //number of mouse clicks must be at least one } if (!isNumber(screenX)){ screenX = 0; } if (!isNumber(screenY)){ screenY = 0; } if (!isNumber(clientX)){ clientX = 0; } if (!isNumber(clientY)){ clientY = 0; } if (!isBoolean(ctrlKey)){ ctrlKey = false; } if (!isBoolean(altKey)){ altKey = false; } if (!isBoolean(shiftKey)){ shiftKey = false; } if (!isBoolean(metaKey)){ metaKey = false; } if (!isNumber(button)){ button = 0; } relatedTarget = relatedTarget || null; //try to create a mouse event var customEvent /*:MouseEvent*/ = null; //check for DOM-compliant browsers first if (isFunction(Y.config.doc.createEvent)){ customEvent = Y.config.doc.createEvent("MouseEvents"); //Safari 2.x (WebKit 418) still doesn't implement initMouseEvent() if (customEvent.initMouseEvent){ customEvent.initMouseEvent(type, bubbles, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget); } else { //Safari //the closest thing available in Safari 2.x is UIEvents customEvent = Y.config.doc.createEvent("UIEvents"); customEvent.initEvent(type, bubbles, cancelable); customEvent.view = view; customEvent.detail = detail; customEvent.screenX = screenX; customEvent.screenY = screenY; customEvent.clientX = clientX; customEvent.clientY = clientY; customEvent.ctrlKey = ctrlKey; customEvent.altKey = altKey; customEvent.metaKey = metaKey; customEvent.shiftKey = shiftKey; customEvent.button = button; customEvent.relatedTarget = relatedTarget; } /* * Check to see if relatedTarget has been assigned. Firefox * versions less than 2.0 don't allow it to be assigned via * initMouseEvent() and the property is readonly after event * creation, so in order to keep YAHOO.util.getRelatedTarget() * working, assign to the IE proprietary toElement property * for mouseout event and fromElement property for mouseover * event. */ if (relatedTarget && !customEvent.relatedTarget){ if (type == "mouseout"){ customEvent.toElement = relatedTarget; } else if (type == "mouseover"){ customEvent.fromElement = relatedTarget; } } //fire the event target.dispatchEvent(customEvent); } else if (isObject(Y.config.doc.createEventObject)){ //IE //create an IE event object customEvent = Y.config.doc.createEventObject(); //assign available properties customEvent.bubbles = bubbles; customEvent.cancelable = cancelable; customEvent.view = view; customEvent.detail = detail; customEvent.screenX = screenX; customEvent.screenY = screenY; customEvent.clientX = clientX; customEvent.clientY = clientY; customEvent.ctrlKey = ctrlKey; customEvent.altKey = altKey; customEvent.metaKey = metaKey; customEvent.shiftKey = shiftKey; //fix button property for IE's wacky implementation switch(button){ case 0: customEvent.button = 1; break; case 1: customEvent.button = 4; break; case 2: //leave as is break; default: customEvent.button = 0; } /* * Have to use relatedTarget because IE won't allow assignment * to toElement or fromElement on generic events. This keeps * YAHOO.util.customEvent.getRelatedTarget() functional. */ customEvent.relatedTarget = relatedTarget; //fire the event target.fireEvent("on" + type, customEvent); } else { Y.error("simulateMouseEvent(): No event simulation framework present."); } } /* * Note: Intentionally not for YUIDoc generation. * Simulates a UI event using the given event information to populate * the generated event object. This method does browser-equalizing * calculations to account for differences in the DOM and IE event models * as well as different browser quirks. * @method simulateHTMLEvent * @private * @static * @param {HTMLElement} target The target of the given event. * @param {String} type The type of event to fire. This can be any one of * the following: click, dblclick, mousedown, mouseup, mouseout, * mouseover, and mousemove. * @param {Boolean} bubbles (Optional) Indicates if the event can be * bubbled up. DOM Level 2 specifies that all mouse events bubble by * default. The default is true. * @param {Boolean} cancelable (Optional) Indicates if the event can be * canceled using preventDefault(). DOM Level 2 specifies that all * mouse events except mousemove can be cancelled. The default * is true for all events except mousemove, for which the default * is false. * @param {Window} view (Optional) The view containing the target. This is * typically the window object. The default is window. * @param {int} detail (Optional) The number of times the mouse button has * been used. The default value is 1. */ function simulateUIEvent(target /*:HTMLElement*/, type /*:String*/, bubbles /*:Boolean*/, cancelable /*:Boolean*/, view /*:Window*/, detail /*:int*/) /*:Void*/ { //check target if (!target){ Y.error("simulateUIEvent(): Invalid target."); } //check event type if (isString(type)){ type = type.toLowerCase(); //make sure it's a supported mouse event if (!uiEvents[type]){ Y.error("simulateUIEvent(): Event type '" + type + "' not supported."); } } else { Y.error("simulateUIEvent(): Event type must be a string."); } //try to create a mouse event var customEvent = null; //setup default values if (!isBoolean(bubbles)){ bubbles = (type in bubbleEvents); //not all events bubble } if (!isBoolean(cancelable)){ cancelable = (type == "submit"); //submit is the only one that can be cancelled } if (!isObject(view)){ view = Y.config.win; //view is typically window } if (!isNumber(detail)){ detail = 1; //usually not used but defaulted to this } //check for DOM-compliant browsers first if (isFunction(Y.config.doc.createEvent)){ //just a generic UI Event object is needed customEvent = Y.config.doc.createEvent("UIEvents"); customEvent.initUIEvent(type, bubbles, cancelable, view, detail); //fire the event target.dispatchEvent(customEvent); } else if (isObject(Y.config.doc.createEventObject)){ //IE //create an IE event object customEvent = Y.config.doc.createEventObject(); //assign available properties customEvent.bubbles = bubbles; customEvent.cancelable = cancelable; customEvent.view = view; customEvent.detail = detail; //fire the event target.fireEvent("on" + type, customEvent); } else { Y.error("simulateUIEvent(): No event simulation framework present."); } } /* * (iOS only) This is for creating native DOM gesture events which only iOS * v2.0+ is supporting. * * @method simulateGestureEvent * @private * @param {HTMLElement} target The target of the given event. * @param {String} type The type of event to fire. This can be any one of * the following: touchstart, touchmove, touchend, touchcancel. * @param {Boolean} bubbles (Optional) Indicates if the event can be * bubbled up. DOM Level 2 specifies that all mouse events bubble by * default. The default is true. * @param {Boolean} cancelable (Optional) Indicates if the event can be * canceled using preventDefault(). DOM Level 2 specifies that all * touch events except touchcancel can be cancelled. The default * is true for all events except touchcancel, for which the default * is false. * @param {Window} view (Optional) The view containing the target. This is * typically the window object. The default is window. * @param {int} detail (Optional) Specifies some detail information about * the event depending on the type of event. * @param {int} screenX (Optional) The x-coordinate on the screen at which * point the event occured. The default is 0. * @param {int} screenY (Optional) The y-coordinate on the screen at which * point the event occured. The default is 0. * @param {int} clientX (Optional) The x-coordinate on the client at which * point the event occured. The default is 0. * @param {int} clientY (Optional) The y-coordinate on the client at which * point the event occured. The default is 0. * @param {Boolean} ctrlKey (Optional) Indicates if one of the CTRL keys * is pressed while the event is firing. The default is false. * @param {Boolean} altKey (Optional) Indicates if one of the ALT keys * is pressed while the event is firing. The default is false. * @param {Boolean} shiftKey (Optional) Indicates if one of the SHIFT keys * is pressed while the event is firing. The default is false. * @param {Boolean} metaKey (Optional) Indicates if one of the META keys * is pressed while the event is firing. The default is false. * @param {float} scale (iOS v2+ only) The distance between two fingers * since the start of an event as a multiplier of the initial distance. * The default value is 1.0. * @param {float} rotation (iOS v2+ only) The delta rotation since the start * of an event, in degrees, where clockwise is positive and * counter-clockwise is negative. The default value is 0.0. */ function simulateGestureEvent(target, type, bubbles, // boolean cancelable, // boolean view, // DOMWindow detail, // long screenX, screenY, // long clientX, clientY, // long ctrlKey, altKey, shiftKey, metaKey, // boolean scale, // float rotation // float ) { var customEvent; if(!Y.UA.ios || Y.UA.ios<2.0) { Y.error("simulateGestureEvent(): Native gesture DOM eventframe is not available in this platform."); } // check taget if (!target){ Y.error("simulateGestureEvent(): Invalid target."); } //check event type if (Y.Lang.isString(type)) { type = type.toLowerCase(); //make sure it's a supported touch event if (!gestureEvents[type]){ Y.error("simulateTouchEvent(): Event type '" + type + "' not supported."); } } else { Y.error("simulateGestureEvent(): Event type must be a string."); } // setup default values if (!Y.Lang.isBoolean(bubbles)) { bubbles = true; } // bubble by default if (!Y.Lang.isBoolean(cancelable)) { cancelable = true; } if (!Y.Lang.isObject(view)) { view = Y.config.win; } if (!Y.Lang.isNumber(detail)) { detail = 2; } // usually not used. if (!Y.Lang.isNumber(screenX)) { screenX = 0; } if (!Y.Lang.isNumber(screenY)) { screenY = 0; } if (!Y.Lang.isNumber(clientX)) { clientX = 0; } if (!Y.Lang.isNumber(clientY)) { clientY = 0; } if (!Y.Lang.isBoolean(ctrlKey)) { ctrlKey = false; } if (!Y.Lang.isBoolean(altKey)) { altKey = false; } if (!Y.Lang.isBoolean(shiftKey)){ shiftKey = false; } if (!Y.Lang.isBoolean(metaKey)) { metaKey = false; } if (!Y.Lang.isNumber(scale)){ scale = 1.0; } if (!Y.Lang.isNumber(rotation)){ rotation = 0.0; } customEvent = Y.config.doc.createEvent("GestureEvent"); customEvent.initGestureEvent(type, bubbles, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, target, scale, rotation); target.dispatchEvent(customEvent); } /* * @method simulateTouchEvent * @private * @param {HTMLElement} target The target of the given event. * @param {String} type The type of event to fire. This can be any one of * the following: touchstart, touchmove, touchend, touchcancel. * @param {Boolean} bubbles (Optional) Indicates if the event can be * bubbled up. DOM Level 2 specifies that all mouse events bubble by * default. The default is true. * @param {Boolean} cancelable (Optional) Indicates if the event can be * canceled using preventDefault(). DOM Level 2 specifies that all * touch events except touchcancel can be cancelled. The default * is true for all events except touchcancel, for which the default * is false. * @param {Window} view (Optional) The view containing the target. This is * typically the window object. The default is window. * @param {int} detail (Optional) Specifies some detail information about * the event depending on the type of event. * @param {int} screenX (Optional) The x-coordinate on the screen at which * point the event occured. The default is 0. * @param {int} screenY (Optional) The y-coordinate on the screen at which * point the event occured. The default is 0. * @param {int} clientX (Optional) The x-coordinate on the client at which * point the event occured. The default is 0. * @param {int} clientY (Optional) The y-coordinate on the client at which * point the event occured. The default is 0. * @param {Boolean} ctrlKey (Optional) Indicates if one of the CTRL keys * is pressed while the event is firing. The default is false. * @param {Boolean} altKey (Optional) Indicates if one of the ALT keys * is pressed while the event is firing. The default is false. * @param {Boolean} shiftKey (Optional) Indicates if one of the SHIFT keys * is pressed while the event is firing. The default is false. * @param {Boolean} metaKey (Optional) Indicates if one of the META keys * is pressed while the event is firing. The default is false. * @param {TouchList} touches A collection of Touch objects representing * all touches associated with this event. * @param {TouchList} targetTouches A collection of Touch objects * representing all touches associated with this target. * @param {TouchList} changedTouches A collection of Touch objects * representing all touches that changed in this event. * @param {float} scale (iOS v2+ only) The distance between two fingers * since the start of an event as a multiplier of the initial distance. * The default value is 1.0. * @param {float} rotation (iOS v2+ only) The delta rotation since the start * of an event, in degrees, where clockwise is positive and * counter-clockwise is negative. The default value is 0.0. */ function simulateTouchEvent(target, type, bubbles, // boolean cancelable, // boolean view, // DOMWindow detail, // long screenX, screenY, // long clientX, clientY, // long ctrlKey, altKey, shiftKey, metaKey, // boolean touches, // TouchList targetTouches, // TouchList changedTouches, // TouchList scale, // float rotation // float ) { var customEvent; // check taget if (!target){ Y.error("simulateTouchEvent(): Invalid target."); } //check event type if (Y.Lang.isString(type)) { type = type.toLowerCase(); //make sure it's a supported touch event if (!touchEvents[type]){ Y.error("simulateTouchEvent(): Event type '" + type + "' not supported."); } } else { Y.error("simulateTouchEvent(): Event type must be a string."); } // note that the caller is responsible to pass appropriate touch objects. // check touch objects // Android(even 4.0) doesn't define TouchList yet /*if(type === 'touchstart' || type === 'touchmove') { if(!touches instanceof TouchList) { Y.error('simulateTouchEvent(): Invalid touches. It must be a TouchList'); } else { if(touches.length === 0) { Y.error('simulateTouchEvent(): No touch object found.'); } } } else if(type === 'touchend') { if(!changedTouches instanceof TouchList) { Y.error('simulateTouchEvent(): Invalid touches. It must be a TouchList'); } else { if(changedTouches.length === 0) { Y.error('simulateTouchEvent(): No touch object found.'); } } }*/ if(type === 'touchstart' || type === 'touchmove') { if(touches.length === 0) { Y.error('simulateTouchEvent(): No touch object in touches'); } } else if(type === 'touchend') { if(changedTouches.length === 0) { Y.error('simulateTouchEvent(): No touch object in changedTouches'); } } // setup default values if (!Y.Lang.isBoolean(bubbles)) { bubbles = true; } // bubble by default. if (!Y.Lang.isBoolean(cancelable)) { cancelable = (type != "touchcancel"); // touchcancel is not cancelled } if (!Y.Lang.isObject(view)) { view = Y.config.win; } if (!Y.Lang.isNumber(detail)) { detail = 1; } // usually not used. defaulted to # of touch objects. if (!Y.Lang.isNumber(screenX)) { screenX = 0; } if (!Y.Lang.isNumber(screenY)) { screenY = 0; } if (!Y.Lang.isNumber(clientX)) { clientX = 0; } if (!Y.Lang.isNumber(clientY)) { clientY = 0; } if (!Y.Lang.isBoolean(ctrlKey)) { ctrlKey = false; } if (!Y.Lang.isBoolean(altKey)) { altKey = false; } if (!Y.Lang.isBoolean(shiftKey)){ shiftKey = false; } if (!Y.Lang.isBoolean(metaKey)) { metaKey = false; } if (!Y.Lang.isNumber(scale)) { scale = 1.0; } if (!Y.Lang.isNumber(rotation)) { rotation = 0.0; } //check for DOM-compliant browsers first if (Y.Lang.isFunction(Y.config.doc.createEvent)) { if (Y.UA.android) { /** * Couldn't find android start version that supports touch event. * Assumed supported(btw APIs broken till icecream sandwitch) * from the beginning. */ if(Y.UA.android < 4.0) { /** * Touch APIs are broken in androids older than 4.0. We will use * simulated touch apis for these versions. * App developer still can listen for touch events. This events * will be dispatched with touch event types. * * (Note) Used target for the relatedTarget. Need to verify if * it has a side effect. */ customEvent = Y.config.doc.createEvent("MouseEvents"); customEvent.initMouseEvent(type, bubbles, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, 0, target); customEvent.touches = touches; customEvent.targetTouches = targetTouches; customEvent.changedTouches = changedTouches; } else { customEvent = Y.config.doc.createEvent("TouchEvent"); // Andoroid isn't compliant W3C initTouchEvent method signature. customEvent.initTouchEvent(touches, targetTouches, changedTouches, type, view, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey); } } else if (Y.UA.ios) { if(Y.UA.ios >= 2.0) { customEvent = Y.config.doc.createEvent("TouchEvent"); // Available iOS 2.0 and later customEvent.initTouchEvent(type, bubbles, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, touches, targetTouches, changedTouches, scale, rotation); } else { Y.error('simulateTouchEvent(): No touch event simulation framework present for iOS, '+Y.UA.ios+'.'); } } else { Y.error('simulateTouchEvent(): Not supported agent yet, '+Y.UA.userAgent); } //fire the event target.dispatchEvent(customEvent); //} else if (Y.Lang.isObject(doc.createEventObject)){ // Windows Mobile/IE, support later } else { Y.error('simulateTouchEvent(): No event simulation framework present.'); } } /** * Simulates the event or gesture with the given name on a target. * @param {HTMLElement} target The DOM element that's the target of the event. * @param {String} type The type of event or name of the supported gesture to simulate * (i.e., "click", "doubletap", "flick"). * @param {Object} options (Optional) Extra options to copy onto the event object. * For gestures, options are used to refine the gesture behavior. * @return {void} * @for Event * @method simulate * @static */ Y.Event.simulate = function(target, type, options){ options = options || {}; if (mouseEvents[type]){ simulateMouseEvent(target, type, options.bubbles, options.cancelable, options.view, options.detail, options.screenX, options.screenY, options.clientX, options.clientY, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, options.relatedTarget); } else if (keyEvents[type]){ simulateKeyEvent(target, type, options.bubbles, options.cancelable, options.view, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.keyCode, options.charCode); } else if (uiEvents[type]){ simulateUIEvent(target, type, options.bubbles, options.cancelable, options.view, options.detail); // touch low-level event simulation } else if (touchEvents[type]) { if((Y.config.win && ("ontouchstart" in Y.config.win)) && !(Y.UA.phantomjs) && !(Y.UA.chrome && Y.UA.chrome < 6)) { simulateTouchEvent(target, type, options.bubbles, options.cancelable, options.view, options.detail, options.screenX, options.screenY, options.clientX, options.clientY, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.touches, options.targetTouches, options.changedTouches, options.scale, options.rotation); } else { Y.error("simulate(): Event '" + type + "' can't be simulated. Use gesture-simulate module instead."); } // ios gesture low-level event simulation (iOS v2+ only) } else if(Y.UA.ios && Y.UA.ios >= 2.0 && gestureEvents[type]) { simulateGestureEvent(target, type, options.bubbles, options.cancelable, options.view, options.detail, options.screenX, options.screenY, options.clientX, options.clientY, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.scale, options.rotation); // anything else } else { Y.error("simulate(): Event '" + type + "' can't be simulated."); } }; })(); }, '@VERSION@' ,{requires:['event-base']});
window.onload = LoadPage; var sd; var lfc; var tf; var mf; var lc; var lang = 'CSharp'; function ListController() { this.tabCollections = new Array(); this.listCollections = new Array(); this.tabCollectionIds = new Array(); this.listCollectionIds = new Array(); } ListController.prototype.registerTabbedArea = function(tabCollection, listCollection, tabCollectionId, listCollectionId, filter) { this.tabCollections.push(tabCollection); this.listCollections.push(listCollection); this.tabCollectionIds.push(tabCollectionId); this.listCollectionIds.push(listCollectionId); } function LoadPage() { registerEventHandler(window, 'load', function () { }); sd = getStyleDictionary(); lfc = new LanguageFilterController(); lc = new ListController(); tf = new TypeFilter(); mf = new MemberFilter(); setUpLanguage(); setUpSyntax(); setUpSnippets(); setUpType(); setUpAllMembers(); } function setUpLanguage() { var langFilter = document.getElementById('languageFilter'); if (langFilter == null) return; var options = langFilter.getElementsByTagName('option'); if (options == null) return; var value = options[0].getAttribute('value'); var names = value.split(' '); lang = names[0]; } function setUpSnippets() { var divs = document.getElementsByTagName("DIV"); for (var i = 0; i < divs.length; i++) { var temp = i; var name = divs[i].getAttribute("name"); if (name == null || name != "snippetGroup") continue; processSection(divs[i], 'x-lang', lang, true, true, lfc); i= temp + 1; } } function setUpSyntax() { var syntax = document.getElementById('syntaxSection'); if (syntax == null) return; processSection(syntax, 'x-lang', lang, true, true, lfc); var usyntax = document.getElementById('usyntaxSection'); if (usyntax == null) return; processSection(usyntax, 'x-lang', lang, true, true, lfc); } function setUpType() { var typeSection = document.getElementById('typeSection'); if (typeSection == null) return; processSection(typeSection, 'value', 'all', true, false, lc); } function setUpAllMembers() { var allMembersSection = document.getElementById('allMembersSection'); if (allMembersSection == null) return; processSection(allMembersSection, 'value', 'all', true, false, lc); } function processSection(section, attribute, value, toggleClassValue, toggleStyleValue, registerObject) { var nodes = section.childNodes; var tabs; var blocks; var tabId; var blockId; if(nodes.length != 2) return; if(nodes[0].tagName == 'TABLE') { var rows = nodes[0].getElementsByTagName('tr'); if (rows.length == 0) return; tabId = rows[0].getAttribute('id'); if (tabId == null) return; tabs = new ElementCollection(tabId); } if(nodes[1].tagName == 'DIV') { blockId = nodes[1].getAttribute('id'); if (blockId == null) return; blocks = new ElementCollection(blockId); } else if (nodes[1].tagName == 'TABLE') { blockId = nodes[1].getAttribute('id'); if (blockId == null) return; blocks = new ElementCollection(blockId); } if (registerObject != null) registerObject.registerTabbedArea(tabs, blocks, tabId, blockId); if (toggleClassValue) tabs.toggleClass(attribute,value,'activeTab','tab'); if (toggleStyleValue) blocks.toggleStyle(attribute,value,'display','block','none'); } function toggleClass(id, attributeName, attributeValue, trueClass, falseClass) { for(var i = 0; i < lfc.tabCollections.length; i++) { var tabs = lfc.tabCollections[i]; if (lfc.tabCollectionIds[i] == id) { tabs.toggleClass(attributeName, attributeValue, trueClass, falseClass); } } for(var j = 0; j < lc.tabCollections.length; j++) { var listTabs = lc.tabCollections[j]; if (lc.tabCollectionIds[j] == id) { listTabs.toggleClass(attributeName, attributeValue, trueClass, falseClass); } } } function toggleStyle(id, attributeName, attributeValue, styleName, trueStyleValue, falseStyleValue) { for (var i = 0; i < lfc.blockCollections.length; i++) { var blocks = lfc.blockCollections[i]; if (lfc.blockCollectionIds[i] == id) { blocks.toggleStyle(attributeName, attributeValue, styleName, trueStyleValue, falseStyleValue); } } } function processList(id, methodName, typeName) { for (var i = 0; i < lc.listCollections.length; i++) { var list = lc.listCollections[i]; if (lc.listCollectionIds[i] == id) { if (typeName == 'type') list.process(getInstanceDelegate(tf,methodName)); else if (typeName == 'member') list.process(getInstanceDelegate(mf, methodName)); } } } function processSubgroup(subgroup, typeName) { if (typeName == 'type' && tf != null) tf.subgroup = subgroup; else if (typeName == 'member' && mf != null) mf.subgroup = subgroup; } function toggleCheckState(visibility, value) { if (mf == null) return; mf[visibility] = value; } function switchLanguage(names, value) { if (lfc != null) lfc.switchLanguage(names[0]); }
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'preview', 'hr', { preview: 'Pregledaj' } );
var templates = ['partial_subdir', 'subdir/parent', 'partial_fullpath']; templates = templates.map(function(template) { return 'hbs!'+require.toUrl('tests/templates/'+template); }); define(templates, function(template, parentTemplate, fullPathTemplate) { describe("template with a partial in a subdirectory {{> partials/_simple}}", function() { it("loads the partials", function() { var html = template({partialValue: "ha"}); var container = document.createElement('div'); container.innerHTML = html; var bs = container.getElementsByTagName('b'); expect(bs).to.exist; expect(bs.length).to.equal(1); expect(bs[0].innerText).to.equal('Hello ha'); }); }); describe("template with a partial in a higher directory", function() { it("loads the partial using a relative path {{> ../partials/_simple}}", function() { var html = parentTemplate({partialValue: "ha"}); var container = document.createElement('div'); container.innerHTML = html; var bs = container.getElementsByTagName('b'); expect(bs).to.exist; expect(bs.length).to.equal(1); expect(bs[0].innerText).to.equal('Hello ha'); }); it("loads the partial using an absolute path {{> tests/templates/partials/_simple}}", function() { var html = fullPathTemplate({partialValue: "ha"}); var container = document.createElement('div'); container.innerHTML = html; var bs = container.getElementsByTagName('b'); expect(bs).to.exist; expect(bs.length).to.equal(1); expect(bs[0].innerText).to.equal('Hello ha'); }); }); });
//Created by Aran Khanna All Rights Reserved // Global Variables // Map Variables L.mapbox.accessToken = 'pk.eyJ1IjoiYXJhbmtoYW5uYSIsImEiOiJjYWYxOTcwYTI4ZTNhNDA5NTdlMzFjMDQ0NWM3OThjMSJ9.j6OVr_W3jAAdxusZ5qLXlg'; var map_id = "arankhanna.m3ankjj3"; // Map object var map = null; // Lines between points drawn on map var polyline = null; // Facebooks message data endpoint var endpoint_url = "https://www.facebook.com/ajax/mercury/thread_info.php"; // User Data Structures // Dictionary of FB users and their location data var user_dict = {}; // List of names of users loaded (for lookahead search) with corresponding list of FB ids var user_list = ['Most Recent']; var id_list = [0]; // User Data Variables // The most recent data point over all users var most_recent_time = 0; // Counters for the number of users and data points loaded var users_loaded = 0; var coords_loaded = 0; // User to focus in on var focus_user = null; // Counter for total number of async rest calls made var async_reqs = 0; // The Logic // On every request from the background script get the rest messages chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { getRestMessages(request.bodyText, function() { sendResponse(); }); } ); // When the document is pull cached big pipe data out of it and add the map html $( document ).ready(function() { // Pull cached big-piped data (not async loaded and most recent) getPipeMessages(document.URL, function() {}); // Set up map setupMap(document); setupMapControls(document); //Check for URL change (react simply diffs and rerenders page so we want to remove map overlay if the URL changes) var storedHash = document.URL; window.setInterval(function () { if (document.URL != storedHash) { storedHash = document.URL; if(storedHash.indexOf('facebook.com/messages') > -1){ $('#map-tab').css("display", "inline"); }else{ $('#map-tab').css("display", "none"); } } }, 100); }); // Gets and parses json data on user location from posting to FB messages endpoint // with the requestBody, calling the callback after its done function getRestMessages(requestBody, callback) { async_reqs++; console.log("requesting "+async_reqs); $.ajax({ type:"POST", url: endpoint_url, data: requestBody, processData: false, complete: function(msg) { // Convert wierd json format to regular json string var cleanedText = "" var splitText = msg.responseText.split(';'); for(var i=3; i<splitText.length; i++){ var cleanedText = cleanedText+splitText[i]; } // Parse json string and extract location info for each message var json = jQuery.parseJSON(cleanedText); var messages = json.payload.actions; if(messages != undefined){ console.log(messages); for(var i =0; i<messages.length; i++){ if(messages[i]['coordinates'] != null){ var data = { "latitude": messages[i]['coordinates']['latitude'], "longitude": messages[i]['coordinates']['longitude'], "time": messages[i]['timestamp'], "user": messages[i]['author'].split(':')[1] } console.log(data); addLayer(data); } } }else{ console.log("No messages returned: "+msg.responseText); } callback(); } }); } // Gets and parses and data delivered in the html body via BigPipe // calling the callback after its done adding the data to the map. function getPipeMessages(url, callback) { console.log("parsing HTML"); $.ajax({ type: "GET", url: url, complete: function(msg) { var regexp = /{"message_id"/g; var match; while ((match = regexp.exec(msg.responseText)) != null) { // console.log("matched"); var braceCount=1; var i; for(i=match.index+1; braceCount>0; i++){ if(msg.responseText[i]=='{'){ braceCount++; } else if(msg.responseText[i]=='}'){ braceCount--; } } var cache_message = jQuery.parseJSON(msg.responseText.substring(match.index, i)); // console.log(cache_message); if(cache_message['coordinates'] != null){ var data = { "latitude": cache_message['coordinates']['latitude'], "longitude": cache_message['coordinates']['longitude'], "time": cache_message['timestamp'], "user": cache_message['author'].split(':')[1] } console.log(data); addLayer(data); } } callback(); } }); } // Adds the map div and map to the document, along with interactability function setupMap(document) { // Create tab for map var mapTab = document.createElement('div'); mapTab.id = 'map-tab'; $('body').append(mapTab); $('#map-tab').addClass("map-label"); $('#map-tab').text('Marauders Map'); // Create map for DOM var mapDiv = document.createElement('div'); mapDiv.id = 'map'; $('#map-tab').append(mapDiv); // Set up click hierarchy for map tab and add expand retract functionality $("#map-tab div").click(function(e) { e.stopPropagation(); }); $('#map-tab').on("click", function() { if($(this).hasClass("map-expand")){ $(this).removeClass("map-expand").addClass("map-label"); $('#map').css("visibility", "visible"); }else{ $(this).removeClass("map-label").addClass("map-expand"); $('#map').css("visibility", "hidden"); } }); // Set scene to default home map = L.mapbox.map('map', map_id) .setView([42.381982, -71.124694], 3); // Set to default layer (no user zoom) for(var key in user_dict){ user_dict[key]["last_layer"].addTo(map); } updateAllOpacities(); } // Adds the control panel for the map to the document, including search bar // back button and counters function setupMapControls(document) { // Create icon container var containerDiv = document.createElement('div'); containerDiv.id = 'button-container'; $('#map').append(containerDiv); // Create search bar var searchDiv = document.createElement('div'); searchDiv.id ="search-holder"; $('#button-container').append(searchDiv); var searchBar = document.createElement('input'); searchBar.setAttribute("class", "typeahead"); searchBar.setAttribute("type", "text"); searchBar.setAttribute("placeholder", "Search Friends"); $('#search-holder').append(searchBar); // Create button to change layers var backButton = document.createElement('a'); backButton.href = '#'; backButton.id = 'back-button'; backButton.innerHTML = "Back"; $('#button-container').append(backButton); // Create counter and update it to most recent var counterDiv = document.createElement('div'); counterDiv.id = 'counter'; $('#button-container').append(counterDiv); $('#counter').text('Users: 0 Points: 0'); updateCounters(); // Attach handler to search bar to autocomplete and focus on user $('.typeahead').bind("enterKey",function(e) { if(map != null && focus_user==null){ var name = $(this).val(); var index = user_list.indexOf(name); if(index != -1){ var latlng = user_dict[id_list[index]]["last_latlng"]; map.setView([latlng.lat, latlng.lng], 20); } } }); $('.typeahead').keyup(function(e) { if(e.keyCode == 13) { $(this).trigger("enterKey"); } }); // Attach handler to back button to clear user zoom $('#back-button').on("click", function() { clearUser(); }); } // Updates all the opacities for the coordinates points if we are focused in // on a specific user's location history function updateFocusOpacity() { var min = Number.MAX_VALUE; var max = 0; if(focus_user != null){ for(var i=0; i<user_dict[focus_user]["layers"].length; i++){ if(user_dict[focus_user]["layers"][i]["time"] > max){ max = user_dict[focus_user]["layers"][i]["time"]; } if(user_dict[focus_user]["layers"][i]["time"] < min){ min = user_dict[focus_user]["layers"][i]["time"]; } } for(var i=0; i<user_dict[focus_user]["layers"].length; i++){ // Opacity is set to % of total range with 0.3 as floor var calcOpacity = (((user_dict[focus_user]["layers"][i]["time"] - min)/(max - min))*0.7) + 0.3; $('.'+focus_user+'-'+user_dict[focus_user]["layers"][i]["time"]).css({opacity: calcOpacity}); } } } // Updates all the opacities for the coordinate points if we are not focused on a user function updateAllOpacities() { var min = Number.MAX_VALUE; var max = 0; if(focus_user == null){ // Calculate min and max (for 1 element min=max) for(var key in user_dict){ if(user_dict[key]["last_time"] > max){ max = user_dict[key]["last_time"] } if(user_dict[key]["last_time"] < min){ min = user_dict[key]["last_time"] } } for(var key in user_dict){ if(max != min){ // Opacity is set to % of total range with 0.3 as floor var calcOpacity = (((user_dict[key]["last_time"] - min)/(max - min))*0.7) + 0.3; $('.'+key+'-'+user_dict[key]["last_time"]).css({opacity: calcOpacity}); } } } } // Updates counters with most recent counts of users and coordinates loaded function updateCounters() { $('#counter').text('Users: '+users_loaded+' Points: '+coords_loaded); } // Updates typeahead for search box with the most recent list of users function updateTypeahead(){ var substringMatcher = function(strs) { return function findMatches(q, cb) { var matches, substringRegex; // an array that will be populated with substring matches matches = []; // regex used to determine if a string contains the substring `q` substrRegex = new RegExp(q, 'i'); // iterate through the pool of strings and for any string that // contains the substring `q`, add it to the `matches` array $.each(strs, function(i, str) { if(substrRegex.test(str)){ matches.push(str); } }); cb(matches); }; }; // remove the old search box and add the new one var searchBox = $('#search-holder .typeahead'); searchBox.typeahead('destroy'); searchBox.typeahead({ hint: true, highlight: true, minLength: 1 }, { name: 'states', source: substringMatcher(user_list) }); } // Un-focus on a user and go back to the default map of most recent positions for // all users function clearUser() { if(focus_user != null){ // Layout changes $('#search-holder').css("display", "inline"); $('#back-button').css("display", "none"); $('#counter').css("display", "inline"); // Remove zoomed layers map.removeLayer(polyline); polyline = null; for(var i=0; i<user_dict[focus_user]["layers"].length; i++){ map.removeLayer(user_dict[focus_user]["layers"][i]["layer"]); } focus_user = null; // Set to default layer (no-zoom) for(var key in user_dict){ user_dict[key]["last_layer"].addTo(map); } updateAllOpacities(); } } // Focus on a specific user and display just their search history on the map function focusUser(userId) { if(focus_user == null){ focus_user = userId; // Layout changes $('#search-holder').css("display", "none"); $('#back-button').css("display", "inline"); $('#counter').css("display", "none"); for(var key in user_dict){ map.removeLayer(user_dict[key]["last_layer"]); } var line = []; var polyline_options = { color: '#3B5998' }; var sorted = user_dict[userId]["layers"].sort(function(a,b) {return a['time'] - b['time']}); for(var i=0; i<sorted.length; i++){ user_dict[userId]["layers"][i]["layer"].addTo(map); line.push(user_dict[userId]["layers"][i]["latlng"]); } polyline = L.polyline(line, polyline_options).addTo(map); updateFocusOpacity(); } } // Add the user to list of all users function registerUser(rawUserJson, data) { var userInfo = jQuery.parseJSON(rawUserJson); var name = userInfo["first_name"] +" "+ userInfo["last_name"]; if(user_list.indexOf(name) == -1){ user_list.push(name); id_list.push(data.user); } if(data.time > most_recent_time){ most_recent_time = data.time; id_list[0] = data.user; } return name; } // Creates a new map layer for a user's location function createUserLayer(name, data) { var date = new Date(data.time); var layer = L.mapbox.featureLayer(); var geoJSON = { type: 'Feature', geometry: { type: 'Point', // coordinates here are in longitude, latitude order coordinates: [ data.longitude, data.latitude ] }, properties: { title: name, description: 'Recorded at: '+date.toGMTString(), icon: { className: "dot "+data.user+"-"+data.time, iconUrl: "https://graph.facebook.com/"+data.user+"/picture?type=square", iconSize: [20, 20], iconAnchor: [10,10], popupAnchor:[0,-10] } } } // Set pictures as icons layer.on('layeradd', function(e) { var marker = e.layer, feature = marker.feature; marker.setIcon(L.icon(feature.properties.icon)); }); // Transition to zoom in on user layer.on('click', function(e) { if(focus_user == null){ focusUser(data.user); } }); // Add layer's Json layer.setGeoJSON(geoJSON); return layer; } // Adds a layer to the map function addUserLayer(layer, data) { coords_loaded++; if(user_dict[data.user] == undefined){ users_loaded++; user_dict[data.user] = { last_time: data.time, last_layer: layer, last_latlng: { lat: data.latitude, lng: data.longitude }, layers: [{ layer: layer, time: data.time, latlng: { lat: data.latitude, lng: data.longitude } }] } // Add to map if not zoomed on user if(map != null && focus_user==null){ layer.addTo(map); } }else{ // Add recorded point to user object user_dict[data.user]["layers"].push({ layer: layer, time: data.time, latlng: { lat: data.latitude, lng: data.longitude } }); // If this is newst point remove curret one and update if(data.time > user_dict[data.user]["last_time"]){ // This layer may already be removed if it is zoomed or null if(map != null && focus_user==null){ map.removeLayer(user_dict[data.user]["last_layer"]); } user_dict[data.user]["last_latlng"] = { lat: data.latitude, lng: data.longitude }; user_dict[data.user]["last_time"] = data.time; user_dict[data.user]["last_layer"] = layer; // Add to map if not zoomed on user if(map != null && focus_user==null){ layer.addTo(map); } } } } // Updates all the map control UI components function updateUI() { if(map != null){ updateAllOpacities(); if(focus_user==null){ updateCounters(); updateTypeahead(); } } } // Getting FB images doesn't work with ghostery or other tracker blockers function addLayer(data) { // Get the user's data from FB (also ensures existence of picture for user) $.ajax({ type:"GET", url: "https://graph.facebook.com/"+data.user, complete: function(msg) { var name = registerUser(msg.responseText, data); var layer = createUserLayer(name, data); addUserLayer(layer, data); updateUI(); } }); }
/* =========================================================== * vi.js * Vietnamese translation for Trumbowyg * http://alex-d.github.com/Trumbowyg * =========================================================== * Author : heocoi * Github: https://github.com/heocoi */ jQuery.trumbowyg.langs.vi = { viewHTML: 'Hiển thị HTML', formatting: 'Định dạng', p: 'Đoạn', blockquote: 'Trích dẫn', code: 'Code', header: 'Đầu trang', bold: 'In đậm', italic: 'In nghiêng', strikethrough: 'Gạch ngang', underline: 'Gạch chân', strong: 'In đậm', em: 'In nghiêng', del: 'Gạch ngang', unorderedList: 'Danh sách không thứ tự', orderedList: 'Danh sách có thứ tự', insertImage: 'Chèn hình ảnh', insertVideo: 'Chèn video', link: 'Đường dẫn', createLink: 'Tạo đường dẫn', unlink: 'Hủy đường dẫn', justifyLeft: 'Canh lề trái', justifyCenter: 'Canh giữa', justifyRight: 'Canh lề phải', justifyFull: 'Canh đều', horizontalRule: 'Thêm đường kẻ ngang', fullscreen: 'Toàn màn hình', close: 'Đóng', submit: 'Đồng ý', reset: 'Hủy bỏ', required: 'Bắt buộc', description: 'Mô tả', title: 'Tiêu đề', text: 'Nội dung' };
import Stream from 'ember-metal/streams/stream'; import merge from 'ember-metal/merge'; import { getArrayValues, getHashValues } from 'ember-htmlbars/streams/utils'; export default function BuiltInHelperStream(helper, params, hash, templates, env, scope, context, label) { this.init(label); this.helper = helper; this.params = params; this.templates = templates; this.env = env; this.scope = scope; this.hash = hash; this.context = context; } BuiltInHelperStream.prototype = Object.create(Stream.prototype); merge(BuiltInHelperStream.prototype, { compute() { // Using call and undefined is probably not needed, these are only internal return this.helper.call(this.context, getArrayValues(this.params), getHashValues(this.hash), this.templates, this.env, this.scope); } });
// Generated by CoffeeScript 1.9.3 var changeNumbers, inner, outer; outer = 1; changeNumbers = function() { var inner; inner = -1; return outer = 10; }; inner = changeNumbers();
/** * jqPlot * Pure JavaScript plotting plugin using jQuery * * Version: 1.0.4 * Revision: 1120 * * Copyright (c) 2009-2012 Chris Leonello * jqPlot is currently available for use in all personal or commercial projects * under both the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL * version 2.0 (http://www.gnu.org/licenses/gpl-2.0.html) licenses. This means that you can * choose the license that best suits your project and use it accordingly. * * Although not required, the author would appreciate an email letting him * know of any substantial use of jqPlot. You can reach the author at: * chris at jqplot dot com or see http://www.jqplot.com/info.php . * * If you are feeling kind and generous, consider supporting the project by * making a donation at: http://www.jqplot.com/donate.php . * * sprintf functions contained in jqplot.sprintf.js by Ash Searle: * * version 2007.04.27 * author Ash Searle * http://hexmen.com/blog/2007/03/printf-sprintf/ * http://hexmen.com/js/sprintf.js * The author (Ash Searle) has placed this code in the public domain: * "This code is unrestricted: you are free to use it however you like." * * included jsDate library by Chris Leonello: * * Copyright (c) 2010-2012 Chris Leonello * * jsDate is currently available for use in all personal or commercial projects * under both the MIT and GPL version 2.0 licenses. This means that you can * choose the license that best suits your project and use it accordingly. * * jsDate borrows many concepts and ideas from the Date Instance * Methods by Ken Snyder along with some parts of Ken's actual code. * * Ken's origianl Date Instance Methods and copyright notice: * * Ken Snyder (ken d snyder at gmail dot com) * 2008-09-10 * version 2.0.2 (http://kendsnyder.com/sandbox/date/) * Creative Commons Attribution License 3.0 (http://creativecommons.org/licenses/by/3.0/) * * jqplotToImage function based on Larry Siden's export-jqplot-to-png.js. * Larry has generously given permission to adapt his code for inclusion * into jqPlot. * * Larry's original code can be found here: * * https://github.com/lsiden/export-jqplot-to-png * * */ (function($) { // This code is a modified version of the canvastext.js code, copyright below: // // This code is released to the public domain by Jim Studt, 2007. // He may keep some sort of up to date copy at http://www.federated.com/~jim/canvastext/ // $.jqplot.CanvasTextRenderer = function(options){ this.fontStyle = 'normal'; // normal, italic, oblique [not implemented] this.fontVariant = 'normal'; // normal, small caps [not implemented] this.fontWeight = 'normal'; // normal, bold, bolder, lighter, 100 - 900 this.fontSize = '10px'; this.fontFamily = 'sans-serif'; this.fontStretch = 1.0; this.fillStyle = '#666666'; this.angle = 0; this.textAlign = 'start'; this.textBaseline = 'alphabetic'; this.text; this.width; this.height; this.pt2px = 1.28; $.extend(true, this, options); this.normalizedFontSize = this.normalizeFontSize(this.fontSize); this.setHeight(); }; $.jqplot.CanvasTextRenderer.prototype.init = function(options) { $.extend(true, this, options); this.normalizedFontSize = this.normalizeFontSize(this.fontSize); this.setHeight(); }; // convert css spec into point size // returns float $.jqplot.CanvasTextRenderer.prototype.normalizeFontSize = function(sz) { sz = String(sz); var n = parseFloat(sz); if (sz.indexOf('px') > -1) { return n/this.pt2px; } else if (sz.indexOf('pt') > -1) { return n; } else if (sz.indexOf('em') > -1) { return n*12; } else if (sz.indexOf('%') > -1) { return n*12/100; } // default to pixels; else { return n/this.pt2px; } }; $.jqplot.CanvasTextRenderer.prototype.fontWeight2Float = function(w) { // w = normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 // return values adjusted for Hershey font. if (Number(w)) { return w/400; } else { switch (w) { case 'normal': return 1; break; case 'bold': return 1.75; break; case 'bolder': return 2.25; break; case 'lighter': return 0.75; break; default: return 1; break; } } }; $.jqplot.CanvasTextRenderer.prototype.getText = function() { return this.text; }; $.jqplot.CanvasTextRenderer.prototype.setText = function(t, ctx) { this.text = t; this.setWidth(ctx); return this; }; $.jqplot.CanvasTextRenderer.prototype.getWidth = function(ctx) { return this.width; }; $.jqplot.CanvasTextRenderer.prototype.setWidth = function(ctx, w) { if (!w) { this.width = this.measure(ctx, this.text); } else { this.width = w; } return this; }; // return height in pixels. $.jqplot.CanvasTextRenderer.prototype.getHeight = function(ctx) { return this.height; }; // w - height in pt // set heigh in px $.jqplot.CanvasTextRenderer.prototype.setHeight = function(w) { if (!w) { //height = this.fontSize /0.75; this.height = this.normalizedFontSize * this.pt2px; } else { this.height = w; } return this; }; $.jqplot.CanvasTextRenderer.prototype.letter = function (ch) { return this.letters[ch]; }; $.jqplot.CanvasTextRenderer.prototype.ascent = function() { return this.normalizedFontSize; }; $.jqplot.CanvasTextRenderer.prototype.descent = function() { return 7.0*this.normalizedFontSize/25.0; }; $.jqplot.CanvasTextRenderer.prototype.measure = function(ctx, str) { var total = 0; var len = str.length; for (var i = 0; i < len; i++) { var c = this.letter(str.charAt(i)); if (c) { total += c.width * this.normalizedFontSize / 25.0 * this.fontStretch; } } return total; }; $.jqplot.CanvasTextRenderer.prototype.draw = function(ctx,str) { var x = 0; // leave room at bottom for descenders. var y = this.height*0.72; var total = 0; var len = str.length; var mag = this.normalizedFontSize / 25.0; ctx.save(); var tx, ty; // 1st quadrant if ((-Math.PI/2 <= this.angle && this.angle <= 0) || (Math.PI*3/2 <= this.angle && this.angle <= Math.PI*2)) { tx = 0; ty = -Math.sin(this.angle) * this.width; } // 4th quadrant else if ((0 < this.angle && this.angle <= Math.PI/2) || (-Math.PI*2 <= this.angle && this.angle <= -Math.PI*3/2)) { tx = Math.sin(this.angle) * this.height; ty = 0; } // 2nd quadrant else if ((-Math.PI < this.angle && this.angle < -Math.PI/2) || (Math.PI <= this.angle && this.angle <= Math.PI*3/2)) { tx = -Math.cos(this.angle) * this.width; ty = -Math.sin(this.angle) * this.width - Math.cos(this.angle) * this.height; } // 3rd quadrant else if ((-Math.PI*3/2 < this.angle && this.angle < Math.PI) || (Math.PI/2 < this.angle && this.angle < Math.PI)) { tx = Math.sin(this.angle) * this.height - Math.cos(this.angle)*this.width; ty = -Math.cos(this.angle) * this.height; } ctx.strokeStyle = this.fillStyle; ctx.fillStyle = this.fillStyle; ctx.translate(tx, ty); ctx.rotate(this.angle); ctx.lineCap = "round"; // multiplier was 2.0 var fact = (this.normalizedFontSize > 30) ? 2.0 : 2 + (30 - this.normalizedFontSize)/20; ctx.lineWidth = fact * mag * this.fontWeight2Float(this.fontWeight); for ( var i = 0; i < len; i++) { var c = this.letter( str.charAt(i)); if ( !c) { continue; } ctx.beginPath(); var penUp = 1; var needStroke = 0; for ( var j = 0; j < c.points.length; j++) { var a = c.points[j]; if ( a[0] == -1 && a[1] == -1) { penUp = 1; continue; } if ( penUp) { ctx.moveTo( x + a[0]*mag*this.fontStretch, y - a[1]*mag); penUp = false; } else { ctx.lineTo( x + a[0]*mag*this.fontStretch, y - a[1]*mag); } } ctx.stroke(); x += c.width*mag*this.fontStretch; } ctx.restore(); return total; }; $.jqplot.CanvasTextRenderer.prototype.letters = { ' ': { width: 16, points: [] }, '!': { width: 10, points: [[5,21],[5,7],[-1,-1],[5,2],[4,1],[5,0],[6,1],[5,2]] }, '"': { width: 16, points: [[4,21],[4,14],[-1,-1],[12,21],[12,14]] }, '#': { width: 21, points: [[11,25],[4,-7],[-1,-1],[17,25],[10,-7],[-1,-1],[4,12],[18,12],[-1,-1],[3,6],[17,6]] }, '$': { width: 20, points: [[8,25],[8,-4],[-1,-1],[12,25],[12,-4],[-1,-1],[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]] }, '%': { width: 24, points: [[21,21],[3,0],[-1,-1],[8,21],[10,19],[10,17],[9,15],[7,14],[5,14],[3,16],[3,18],[4,20],[6,21],[8,21],[10,20],[13,19],[16,19],[19,20],[21,21],[-1,-1],[17,7],[15,6],[14,4],[14,2],[16,0],[18,0],[20,1],[21,3],[21,5],[19,7],[17,7]] }, '&': { width: 26, points: [[23,12],[23,13],[22,14],[21,14],[20,13],[19,11],[17,6],[15,3],[13,1],[11,0],[7,0],[5,1],[4,2],[3,4],[3,6],[4,8],[5,9],[12,13],[13,14],[14,16],[14,18],[13,20],[11,21],[9,20],[8,18],[8,16],[9,13],[11,10],[16,3],[18,1],[20,0],[22,0],[23,1],[23,2]] }, '\'': { width: 10, points: [[5,19],[4,20],[5,21],[6,20],[6,18],[5,16],[4,15]] }, '(': { width: 14, points: [[11,25],[9,23],[7,20],[5,16],[4,11],[4,7],[5,2],[7,-2],[9,-5],[11,-7]] }, ')': { width: 14, points: [[3,25],[5,23],[7,20],[9,16],[10,11],[10,7],[9,2],[7,-2],[5,-5],[3,-7]] }, '*': { width: 16, points: [[8,21],[8,9],[-1,-1],[3,18],[13,12],[-1,-1],[13,18],[3,12]] }, '+': { width: 26, points: [[13,18],[13,0],[-1,-1],[4,9],[22,9]] }, ',': { width: 10, points: [[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]] }, '-': { width: 18, points: [[6,9],[12,9]] }, '.': { width: 10, points: [[5,2],[4,1],[5,0],[6,1],[5,2]] }, '/': { width: 22, points: [[20,25],[2,-7]] }, '0': { width: 20, points: [[9,21],[6,20],[4,17],[3,12],[3,9],[4,4],[6,1],[9,0],[11,0],[14,1],[16,4],[17,9],[17,12],[16,17],[14,20],[11,21],[9,21]] }, '1': { width: 20, points: [[6,17],[8,18],[11,21],[11,0]] }, '2': { width: 20, points: [[4,16],[4,17],[5,19],[6,20],[8,21],[12,21],[14,20],[15,19],[16,17],[16,15],[15,13],[13,10],[3,0],[17,0]] }, '3': { width: 20, points: [[5,21],[16,21],[10,13],[13,13],[15,12],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]] }, '4': { width: 20, points: [[13,21],[3,7],[18,7],[-1,-1],[13,21],[13,0]] }, '5': { width: 20, points: [[15,21],[5,21],[4,12],[5,13],[8,14],[11,14],[14,13],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]] }, '6': { width: 20, points: [[16,18],[15,20],[12,21],[10,21],[7,20],[5,17],[4,12],[4,7],[5,3],[7,1],[10,0],[11,0],[14,1],[16,3],[17,6],[17,7],[16,10],[14,12],[11,13],[10,13],[7,12],[5,10],[4,7]] }, '7': { width: 20, points: [[17,21],[7,0],[-1,-1],[3,21],[17,21]] }, '8': { width: 20, points: [[8,21],[5,20],[4,18],[4,16],[5,14],[7,13],[11,12],[14,11],[16,9],[17,7],[17,4],[16,2],[15,1],[12,0],[8,0],[5,1],[4,2],[3,4],[3,7],[4,9],[6,11],[9,12],[13,13],[15,14],[16,16],[16,18],[15,20],[12,21],[8,21]] }, '9': { width: 20, points: [[16,14],[15,11],[13,9],[10,8],[9,8],[6,9],[4,11],[3,14],[3,15],[4,18],[6,20],[9,21],[10,21],[13,20],[15,18],[16,14],[16,9],[15,4],[13,1],[10,0],[8,0],[5,1],[4,3]] }, ':': { width: 10, points: [[5,14],[4,13],[5,12],[6,13],[5,14],[-1,-1],[5,2],[4,1],[5,0],[6,1],[5,2]] }, ';': { width: 10, points: [[5,14],[4,13],[5,12],[6,13],[5,14],[-1,-1],[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]] }, '<': { width: 24, points: [[20,18],[4,9],[20,0]] }, '=': { width: 26, points: [[4,12],[22,12],[-1,-1],[4,6],[22,6]] }, '>': { width: 24, points: [[4,18],[20,9],[4,0]] }, '?': { width: 18, points: [[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],[-1,-1],[9,2],[8,1],[9,0],[10,1],[9,2]] }, '@': { width: 27, points: [[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],[-1,-1],[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],[-1,-1],[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],[-1,-1],[19,16],[18,8],[18,6],[19,5]] }, 'A': { width: 18, points: [[9,21],[1,0],[-1,-1],[9,21],[17,0],[-1,-1],[4,7],[14,7]] }, 'B': { width: 21, points: [[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[-1,-1],[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]] }, 'C': { width: 21, points: [[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]] }, 'D': { width: 21, points: [[4,21],[4,0],[-1,-1],[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]] }, 'E': { width: 19, points: [[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11],[-1,-1],[4,0],[17,0]] }, 'F': { width: 18, points: [[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11]] }, 'G': { width: 21, points: [[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],[-1,-1],[13,8],[18,8]] }, 'H': { width: 22, points: [[4,21],[4,0],[-1,-1],[18,21],[18,0],[-1,-1],[4,11],[18,11]] }, 'I': { width: 8, points: [[4,21],[4,0]] }, 'J': { width: 16, points: [[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]] }, 'K': { width: 21, points: [[4,21],[4,0],[-1,-1],[18,21],[4,7],[-1,-1],[9,12],[18,0]] }, 'L': { width: 17, points: [[4,21],[4,0],[-1,-1],[4,0],[16,0]] }, 'M': { width: 24, points: [[4,21],[4,0],[-1,-1],[4,21],[12,0],[-1,-1],[20,21],[12,0],[-1,-1],[20,21],[20,0]] }, 'N': { width: 22, points: [[4,21],[4,0],[-1,-1],[4,21],[18,0],[-1,-1],[18,21],[18,0]] }, 'O': { width: 22, points: [[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]] }, 'P': { width: 21, points: [[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]] }, 'Q': { width: 22, points: [[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],[-1,-1],[12,4],[18,-2]] }, 'R': { width: 21, points: [[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],[-1,-1],[11,11],[18,0]] }, 'S': { width: 20, points: [[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]] }, 'T': { width: 16, points: [[8,21],[8,0],[-1,-1],[1,21],[15,21]] }, 'U': { width: 22, points: [[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]] }, 'V': { width: 18, points: [[1,21],[9,0],[-1,-1],[17,21],[9,0]] }, 'W': { width: 24, points: [[2,21],[7,0],[-1,-1],[12,21],[7,0],[-1,-1],[12,21],[17,0],[-1,-1],[22,21],[17,0]] }, 'X': { width: 20, points: [[3,21],[17,0],[-1,-1],[17,21],[3,0]] }, 'Y': { width: 18, points: [[1,21],[9,11],[9,0],[-1,-1],[17,21],[9,11]] }, 'Z': { width: 20, points: [[17,21],[3,0],[-1,-1],[3,21],[17,21],[-1,-1],[3,0],[17,0]] }, '[': { width: 14, points: [[4,25],[4,-7],[-1,-1],[5,25],[5,-7],[-1,-1],[4,25],[11,25],[-1,-1],[4,-7],[11,-7]] }, '\\': { width: 14, points: [[0,21],[14,-3]] }, ']': { width: 14, points: [[9,25],[9,-7],[-1,-1],[10,25],[10,-7],[-1,-1],[3,25],[10,25],[-1,-1],[3,-7],[10,-7]] }, '^': { width: 16, points: [[6,15],[8,18],[10,15],[-1,-1],[3,12],[8,17],[13,12],[-1,-1],[8,17],[8,0]] }, '_': { width: 16, points: [[0,-2],[16,-2]] }, '`': { width: 10, points: [[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]] }, 'a': { width: 19, points: [[15,14],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]] }, 'b': { width: 19, points: [[4,21],[4,0],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]] }, 'c': { width: 18, points: [[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]] }, 'd': { width: 19, points: [[15,21],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]] }, 'e': { width: 18, points: [[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]] }, 'f': { width: 12, points: [[10,21],[8,21],[6,20],[5,17],[5,0],[-1,-1],[2,14],[9,14]] }, 'g': { width: 19, points: [[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]] }, 'h': { width: 19, points: [[4,21],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]] }, 'i': { width: 8, points: [[3,21],[4,20],[5,21],[4,22],[3,21],[-1,-1],[4,14],[4,0]] }, 'j': { width: 10, points: [[5,21],[6,20],[7,21],[6,22],[5,21],[-1,-1],[6,14],[6,-3],[5,-6],[3,-7],[1,-7]] }, 'k': { width: 17, points: [[4,21],[4,0],[-1,-1],[14,14],[4,4],[-1,-1],[8,8],[15,0]] }, 'l': { width: 8, points: [[4,21],[4,0]] }, 'm': { width: 30, points: [[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],[-1,-1],[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]] }, 'n': { width: 19, points: [[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]] }, 'o': { width: 19, points: [[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]] }, 'p': { width: 19, points: [[4,14],[4,-7],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]] }, 'q': { width: 19, points: [[15,14],[15,-7],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]] }, 'r': { width: 13, points: [[4,14],[4,0],[-1,-1],[4,8],[5,11],[7,13],[9,14],[12,14]] }, 's': { width: 17, points: [[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]] }, 't': { width: 12, points: [[5,21],[5,4],[6,1],[8,0],[10,0],[-1,-1],[2,14],[9,14]] }, 'u': { width: 19, points: [[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],[-1,-1],[15,14],[15,0]] }, 'v': { width: 16, points: [[2,14],[8,0],[-1,-1],[14,14],[8,0]] }, 'w': { width: 22, points: [[3,14],[7,0],[-1,-1],[11,14],[7,0],[-1,-1],[11,14],[15,0],[-1,-1],[19,14],[15,0]] }, 'x': { width: 17, points: [[3,14],[14,0],[-1,-1],[14,14],[3,0]] }, 'y': { width: 16, points: [[2,14],[8,0],[-1,-1],[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]] }, 'z': { width: 17, points: [[14,14],[3,0],[-1,-1],[3,14],[14,14],[-1,-1],[3,0],[14,0]] }, '{': { width: 14, points: [[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],[-1,-1],[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],[-1,-1],[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]] }, '|': { width: 8, points: [[4,25],[4,-7]] }, '}': { width: 14, points: [[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],[-1,-1],[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],[-1,-1],[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]] }, '~': { width: 24, points: [[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],[-1,-1],[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]] } }; $.jqplot.CanvasFontRenderer = function(options) { options = options || {}; if (!options.pt2px) { options.pt2px = 1.5; } $.jqplot.CanvasTextRenderer.call(this, options); }; $.jqplot.CanvasFontRenderer.prototype = new $.jqplot.CanvasTextRenderer({}); $.jqplot.CanvasFontRenderer.prototype.constructor = $.jqplot.CanvasFontRenderer; $.jqplot.CanvasFontRenderer.prototype.measure = function(ctx, str) { // var fstyle = this.fontStyle+' '+this.fontVariant+' '+this.fontWeight+' '+this.fontSize+' '+this.fontFamily; var fstyle = this.fontSize+' '+this.fontFamily; ctx.save(); ctx.font = fstyle; var w = ctx.measureText(str).width; ctx.restore(); return w; }; $.jqplot.CanvasFontRenderer.prototype.draw = function(ctx, str) { var x = 0; // leave room at bottom for descenders. var y = this.height*0.72; //var y = 12; ctx.save(); var tx, ty; // 1st quadrant if ((-Math.PI/2 <= this.angle && this.angle <= 0) || (Math.PI*3/2 <= this.angle && this.angle <= Math.PI*2)) { tx = 0; ty = -Math.sin(this.angle) * this.width; } // 4th quadrant else if ((0 < this.angle && this.angle <= Math.PI/2) || (-Math.PI*2 <= this.angle && this.angle <= -Math.PI*3/2)) { tx = Math.sin(this.angle) * this.height; ty = 0; } // 2nd quadrant else if ((-Math.PI < this.angle && this.angle < -Math.PI/2) || (Math.PI <= this.angle && this.angle <= Math.PI*3/2)) { tx = -Math.cos(this.angle) * this.width; ty = -Math.sin(this.angle) * this.width - Math.cos(this.angle) * this.height; } // 3rd quadrant else if ((-Math.PI*3/2 < this.angle && this.angle < Math.PI) || (Math.PI/2 < this.angle && this.angle < Math.PI)) { tx = Math.sin(this.angle) * this.height - Math.cos(this.angle)*this.width; ty = -Math.cos(this.angle) * this.height; } ctx.strokeStyle = this.fillStyle; ctx.fillStyle = this.fillStyle; // var fstyle = this.fontStyle+' '+this.fontVariant+' '+this.fontWeight+' '+this.fontSize+' '+this.fontFamily; var fstyle = this.fontSize+' '+this.fontFamily; ctx.font = fstyle; ctx.translate(tx, ty); ctx.rotate(this.angle); ctx.fillText(str, x, y); // ctx.strokeText(str, x, y); ctx.restore(); }; })(jQuery);
/*global jQuery */ /*jshint multistr:true, browser:true */ /*! * FitVids 1.0 * * Copyright 2013, Chris Coyier - http://css-tricks.com + Dave Rupert - http://daverupert.com * Credit to Thierry Koblentz - http://www.alistapart.com/articles/creating-intrinsic-ratios-for-video/ * Released under the WTFPL license - http://sam.zoy.org/wtfpl/ * * Date: Thu Sept 01 18:00:00 2011 -0500 */ (function( $ ){ "use strict"; $.fn.fitVids = function( options ) { var settings = { customSelector: null }; if(!document.getElementById('fit-vids-style')) { var div = document.createElement('div'), ref = document.getElementsByTagName('base')[0] || document.getElementsByTagName('script')[0], cssStyles = '&shy;<style>.fluid-width-video-wrapper{width:100%;position:relative;padding:0;}.fluid-width-video-wrapper iframe,.fluid-width-video-wrapper object,.fluid-width-video-wrapper embed {position:absolute;top:0;left:0;width:100%;height:100%;}</style>'; div.className = 'fit-vids-style'; div.id = 'fit-vids-style'; div.style.display = 'none'; div.innerHTML = cssStyles; ref.parentNode.insertBefore(div,ref); } if ( options ) { $.extend( settings, options ); } return this.each(function(){ var selectors = [ "iframe[src*='player.vimeo.com']", "iframe[src*='youtube.com']", "iframe[src*='youtube-nocookie.com']", "iframe[src*='kickstarter.com'][src*='video.html']", "object", "embed" ]; if (settings.customSelector) { selectors.push(settings.customSelector); } var $allVideos = $(this).find(selectors.join(',')); $allVideos = $allVideos.not("object object"); // SwfObj conflict patch $allVideos.each(function(){ var $this = $(this); if (this.tagName.toLowerCase() === 'embed' && $this.parent('object').length || $this.parent('.fluid-width-video-wrapper').length) { return; } var height = ( this.tagName.toLowerCase() === 'object' || ($this.attr('height') && !isNaN(parseInt($this.attr('height'), 10))) ) ? parseInt($this.attr('height'), 10) : $this.height(), width = !isNaN(parseInt($this.attr('width'), 10)) ? parseInt($this.attr('width'), 10) : $this.width(), aspectRatio = height / width; if(!$this.attr('id')){ var videoID = 'fitvid' + Math.floor(Math.random()*999999); $this.attr('id', videoID); } $this.wrap('<div class="fluid-width-video-wrapper"></div>').parent('.fluid-width-video-wrapper').css('padding-top', (aspectRatio * 100)+"%"); $this.removeAttr('height').removeAttr('width'); }); }); }; // Works with either jQuery or Zepto })( window.jQuery || window.Zepto );
// original source code is taken from: // https://github.com/SimpleWebRTC/hark // copyright goes to &yet team // edited by Muaz Khan for RTCMultiConnection.js function hark(stream, options) { var audioContextType = window.webkitAudioContext || window.AudioContext; var harker = this; harker.events = {}; harker.on = function (event, callback) { harker.events[event] = callback; }; harker.emit = function () { if (harker.events[arguments[0]]) { harker.events[arguments[0]](arguments[1], arguments[2], arguments[3], arguments[4]); } }; // make it not break in non-supported browsers if (!audioContextType) return harker; options = options || {}; // Config var smoothing = (options.smoothing || 0.1), interval = (options.interval || 50), threshold = options.threshold, play = options.play, history = options.history || 10, running = true; // Setup Audio Context if (!window.audioContext00) { window.audioContext00 = new audioContextType(); } var gainNode = audioContext00.createGain(); gainNode.connect(audioContext00.destination); // don't play for self gainNode.gain.value = 0; var sourceNode, fftBins, analyser; analyser = audioContext00.createAnalyser(); analyser.fftSize = 512; analyser.smoothingTimeConstant = smoothing; fftBins = new Float32Array(analyser.fftSize); //WebRTC Stream sourceNode = audioContext00.createMediaStreamSource(stream); threshold = threshold || -50; sourceNode.connect(analyser); if (play) analyser.connect(audioContext00.destination); harker.speaking = false; harker.setThreshold = function (t) { threshold = t; }; harker.setInterval = function (i) { interval = i; }; harker.stop = function () { running = false; harker.emit('volume_change', -100, threshold); if (harker.speaking) { harker.speaking = false; harker.emit('stopped_speaking'); } }; harker.speakingHistory = []; for (var i = 0; i < history; i++) { harker.speakingHistory.push(0); } // Poll the analyser node to determine if speaking // and emit events if changed var looper = function () { setTimeout(function () { //check if stop has been called if (!running) { return; } var currentVolume = getMaxVolume(analyser, fftBins); harker.emit('volume_change', currentVolume, threshold); var history = 0; if (currentVolume > threshold && !harker.speaking) { // trigger quickly, short history for (var i = harker.speakingHistory.length - 3; i < harker.speakingHistory.length; i++) { history += harker.speakingHistory[i]; } if (history >= 2) { harker.speaking = true; harker.emit('speaking'); } } else if (currentVolume < threshold && harker.speaking) { for (var j = 0; j < harker.speakingHistory.length; j++) { history += harker.speakingHistory[j]; } if (history === 0) { harker.speaking = false; harker.emit('stopped_speaking'); } } harker.speakingHistory.shift(); harker.speakingHistory.push(0 + (currentVolume > threshold)); looper(); }, interval); }; looper(); function getMaxVolume(analyser, fftBins) { var maxVolume = -Infinity; analyser.getFloatFrequencyData(fftBins); for (var i = 4, ii = fftBins.length; i < ii; i++) { if (fftBins[i] > maxVolume && fftBins[i] < 0) { maxVolume = fftBins[i]; } } return maxVolume; } return harker; }
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.xstream = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var NO = {}; function noop() { } function copy(a) { var l = a.length; var b = Array(l); for (var i = 0; i < l; ++i) { b[i] = a[i]; } return b; } exports.NO_IL = { _n: noop, _e: noop, _c: noop, }; function internalizeProducer(producer) { producer._start = function _start(il) { il.next = il._n; il.error = il._e; il.complete = il._c; this.start(il); }; producer._stop = producer.stop; } function compose2(f1, f2) { return function composedFn(arg) { return f1(f2(arg)); }; } function and(f1, f2) { return function andFn(t) { return f1(t) && f2(t); }; } var MergeProducer = (function () { function MergeProducer(insArr) { this.type = 'merge'; this.insArr = insArr; this.out = NO; this.ac = 0; } MergeProducer.prototype._start = function (out) { this.out = out; var s = this.insArr; var L = s.length; this.ac = L; for (var i = 0; i < L; i++) { s[i]._add(this); } }; MergeProducer.prototype._stop = function () { var s = this.insArr; var L = s.length; for (var i = 0; i < L; i++) { s[i]._remove(this); } this.out = NO; }; MergeProducer.prototype._n = function (t) { var u = this.out; if (u === NO) return; u._n(t); }; MergeProducer.prototype._e = function (err) { var u = this.out; if (u === NO) return; u._e(err); }; MergeProducer.prototype._c = function () { if (--this.ac <= 0) { var u = this.out; if (u === NO) return; u._c(); } }; return MergeProducer; }()); exports.MergeProducer = MergeProducer; var CombineListener = (function () { function CombineListener(i, out, p) { this.i = i; this.out = out; this.p = p; p.ils.push(this); } CombineListener.prototype._n = function (t) { var p = this.p, out = this.out; if (!out) return; if (p.up(t, this.i)) { out._n(p.vals); } }; CombineListener.prototype._e = function (err) { var out = this.out; if (!out) return; out._e(err); }; CombineListener.prototype._c = function () { var p = this.p; if (!p.out) return; if (--p.Nc === 0) { p.out._c(); } }; return CombineListener; }()); exports.CombineListener = CombineListener; var CombineProducer = (function () { function CombineProducer(insArr) { this.type = 'combine'; this.insArr = insArr; this.out = NO; this.ils = []; this.Nc = this.Nn = 0; this.vals = []; } CombineProducer.prototype.up = function (t, i) { var v = this.vals[i]; var Nn = !this.Nn ? 0 : v === NO ? --this.Nn : this.Nn; this.vals[i] = t; return Nn === 0; }; CombineProducer.prototype._start = function (out) { this.out = out; var s = this.insArr; var n = this.Nc = this.Nn = s.length; var vals = this.vals = new Array(n); if (n === 0) { out._n([]); out._c(); } else { for (var i = 0; i < n; i++) { vals[i] = NO; s[i]._add(new CombineListener(i, out, this)); } } }; CombineProducer.prototype._stop = function () { var s = this.insArr; var n = s.length; for (var i = 0; i < n; i++) { s[i]._remove(this.ils[i]); } this.out = NO; this.ils = []; this.vals = []; }; return CombineProducer; }()); exports.CombineProducer = CombineProducer; var FromArrayProducer = (function () { function FromArrayProducer(a) { this.type = 'fromArray'; this.a = a; } FromArrayProducer.prototype._start = function (out) { var a = this.a; for (var i = 0, l = a.length; i < l; i++) { out._n(a[i]); } out._c(); }; FromArrayProducer.prototype._stop = function () { }; return FromArrayProducer; }()); exports.FromArrayProducer = FromArrayProducer; var FromPromiseProducer = (function () { function FromPromiseProducer(p) { this.type = 'fromPromise'; this.on = false; this.p = p; } FromPromiseProducer.prototype._start = function (out) { var prod = this; this.on = true; this.p.then(function (v) { if (prod.on) { out._n(v); out._c(); } }, function (e) { out._e(e); }).then(null, function (err) { setTimeout(function () { throw err; }); }); }; FromPromiseProducer.prototype._stop = function () { this.on = false; }; return FromPromiseProducer; }()); exports.FromPromiseProducer = FromPromiseProducer; var PeriodicProducer = (function () { function PeriodicProducer(period) { this.type = 'periodic'; this.period = period; this.intervalID = -1; this.i = 0; } PeriodicProducer.prototype._start = function (stream) { var self = this; function intervalHandler() { stream._n(self.i++); } this.intervalID = setInterval(intervalHandler, this.period); }; PeriodicProducer.prototype._stop = function () { if (this.intervalID !== -1) clearInterval(this.intervalID); this.intervalID = -1; this.i = 0; }; return PeriodicProducer; }()); exports.PeriodicProducer = PeriodicProducer; var DebugOperator = (function () { function DebugOperator(arg, ins) { this.type = 'debug'; this.ins = ins; this.out = NO; this.s = noop; this.l = ''; if (typeof arg === 'string') { this.l = arg; } else if (typeof arg === 'function') { this.s = arg; } } DebugOperator.prototype._start = function (out) { this.out = out; this.ins._add(this); }; DebugOperator.prototype._stop = function () { this.ins._remove(this); this.out = NO; }; DebugOperator.prototype._n = function (t) { var u = this.out; if (u === NO) return; var s = this.s, l = this.l; if (s !== noop) { try { s(t); } catch (e) { u._e(e); } } else if (l) { console.log(l + ':', t); } else { console.log(t); } u._n(t); }; DebugOperator.prototype._e = function (err) { var u = this.out; if (u === NO) return; u._e(err); }; DebugOperator.prototype._c = function () { var u = this.out; if (u === NO) return; u._c(); }; return DebugOperator; }()); exports.DebugOperator = DebugOperator; var DropOperator = (function () { function DropOperator(max, ins) { this.type = 'drop'; this.ins = ins; this.out = NO; this.max = max; this.dropped = 0; } DropOperator.prototype._start = function (out) { this.out = out; this.dropped = 0; this.ins._add(this); }; DropOperator.prototype._stop = function () { this.ins._remove(this); this.out = NO; }; DropOperator.prototype._n = function (t) { var u = this.out; if (u === NO) return; if (this.dropped++ >= this.max) u._n(t); }; DropOperator.prototype._e = function (err) { var u = this.out; if (u === NO) return; u._e(err); }; DropOperator.prototype._c = function () { var u = this.out; if (u === NO) return; u._c(); }; return DropOperator; }()); exports.DropOperator = DropOperator; var OtherIL = (function () { function OtherIL(out, op) { this.out = out; this.op = op; } OtherIL.prototype._n = function (t) { this.op.end(); }; OtherIL.prototype._e = function (err) { this.out._e(err); }; OtherIL.prototype._c = function () { this.op.end(); }; return OtherIL; }()); var EndWhenOperator = (function () { function EndWhenOperator(o, ins) { this.type = 'endWhen'; this.ins = ins; this.out = NO; this.o = o; this.oil = exports.NO_IL; } EndWhenOperator.prototype._start = function (out) { this.out = out; this.o._add(this.oil = new OtherIL(out, this)); this.ins._add(this); }; EndWhenOperator.prototype._stop = function () { this.ins._remove(this); this.o._remove(this.oil); this.out = NO; this.oil = exports.NO_IL; }; EndWhenOperator.prototype.end = function () { var u = this.out; if (u === NO) return; u._c(); }; EndWhenOperator.prototype._n = function (t) { var u = this.out; if (u === NO) return; u._n(t); }; EndWhenOperator.prototype._e = function (err) { var u = this.out; if (u === NO) return; u._e(err); }; EndWhenOperator.prototype._c = function () { this.end(); }; return EndWhenOperator; }()); exports.EndWhenOperator = EndWhenOperator; var FilterOperator = (function () { function FilterOperator(passes, ins) { this.type = 'filter'; this.ins = ins; this.out = NO; this.passes = passes; } FilterOperator.prototype._start = function (out) { this.out = out; this.ins._add(this); }; FilterOperator.prototype._stop = function () { this.ins._remove(this); this.out = NO; }; FilterOperator.prototype._n = function (t) { var u = this.out; if (u === NO) return; try { if (this.passes(t)) u._n(t); } catch (e) { u._e(e); } }; FilterOperator.prototype._e = function (err) { var u = this.out; if (u === NO) return; u._e(err); }; FilterOperator.prototype._c = function () { var u = this.out; if (u === NO) return; u._c(); }; return FilterOperator; }()); exports.FilterOperator = FilterOperator; var FlattenListener = (function () { function FlattenListener(out, op) { this.out = out; this.op = op; } FlattenListener.prototype._n = function (t) { this.out._n(t); }; FlattenListener.prototype._e = function (err) { this.out._e(err); }; FlattenListener.prototype._c = function () { this.op.inner = NO; this.op.less(); }; return FlattenListener; }()); var FlattenOperator = (function () { function FlattenOperator(ins) { this.type = 'flatten'; this.ins = ins; this.out = NO; this.open = true; this.inner = NO; this.il = exports.NO_IL; } FlattenOperator.prototype._start = function (out) { this.out = out; this.open = true; this.inner = NO; this.il = exports.NO_IL; this.ins._add(this); }; FlattenOperator.prototype._stop = function () { this.ins._remove(this); if (this.inner !== NO) this.inner._remove(this.il); this.out = NO; this.open = true; this.inner = NO; this.il = exports.NO_IL; }; FlattenOperator.prototype.less = function () { var u = this.out; if (u === NO) return; if (!this.open && this.inner === NO) u._c(); }; FlattenOperator.prototype._n = function (s) { var u = this.out; if (u === NO) return; var _a = this, inner = _a.inner, il = _a.il; if (inner !== NO && il !== exports.NO_IL) inner._remove(il); (this.inner = s)._add(this.il = new FlattenListener(u, this)); }; FlattenOperator.prototype._e = function (err) { var u = this.out; if (u === NO) return; u._e(err); }; FlattenOperator.prototype._c = function () { this.open = false; this.less(); }; return FlattenOperator; }()); exports.FlattenOperator = FlattenOperator; var FoldOperator = (function () { function FoldOperator(f, seed, ins) { this.type = 'fold'; this.ins = ins; this.out = NO; this.f = f; this.acc = this.seed = seed; } FoldOperator.prototype._start = function (out) { this.out = out; this.acc = this.seed; out._n(this.acc); this.ins._add(this); }; FoldOperator.prototype._stop = function () { this.ins._remove(this); this.out = NO; this.acc = this.seed; }; FoldOperator.prototype._n = function (t) { var u = this.out; if (u === NO) return; try { u._n(this.acc = this.f(this.acc, t)); } catch (e) { u._e(e); } }; FoldOperator.prototype._e = function (err) { var u = this.out; if (u === NO) return; u._e(err); }; FoldOperator.prototype._c = function () { var u = this.out; if (u === NO) return; u._c(); }; return FoldOperator; }()); exports.FoldOperator = FoldOperator; var LastOperator = (function () { function LastOperator(ins) { this.type = 'last'; this.ins = ins; this.out = NO; this.has = false; this.val = NO; } LastOperator.prototype._start = function (out) { this.out = out; this.has = false; this.ins._add(this); }; LastOperator.prototype._stop = function () { this.ins._remove(this); this.out = NO; this.val = NO; }; LastOperator.prototype._n = function (t) { this.has = true; this.val = t; }; LastOperator.prototype._e = function (err) { var u = this.out; if (u === NO) return; u._e(err); }; LastOperator.prototype._c = function () { var u = this.out; if (u === NO) return; if (this.has) { u._n(this.val); u._c(); } else { u._e('TODO show proper error'); } }; return LastOperator; }()); exports.LastOperator = LastOperator; var MapFlattenInner = (function () { function MapFlattenInner(out, op) { this.out = out; this.op = op; } MapFlattenInner.prototype._n = function (r) { this.out._n(r); }; MapFlattenInner.prototype._e = function (err) { this.out._e(err); }; MapFlattenInner.prototype._c = function () { this.op.inner = NO; this.op.less(); }; return MapFlattenInner; }()); var MapFlattenOperator = (function () { function MapFlattenOperator(mapOp) { this.type = mapOp.type + "+flatten"; this.ins = mapOp.ins; this.out = NO; this.mapOp = mapOp; this.inner = NO; this.il = exports.NO_IL; this.open = true; } MapFlattenOperator.prototype._start = function (out) { this.out = out; this.inner = NO; this.il = exports.NO_IL; this.open = true; this.mapOp.ins._add(this); }; MapFlattenOperator.prototype._stop = function () { this.mapOp.ins._remove(this); if (this.inner !== NO) this.inner._remove(this.il); this.out = NO; this.inner = NO; this.il = exports.NO_IL; }; MapFlattenOperator.prototype.less = function () { if (!this.open && this.inner === NO) { var u = this.out; if (u === NO) return; u._c(); } }; MapFlattenOperator.prototype._n = function (v) { var u = this.out; if (u === NO) return; var _a = this, inner = _a.inner, il = _a.il; var s; try { s = this.mapOp.project(v); } catch (e) { u._e(e); return; } if (inner !== NO && il !== exports.NO_IL) inner._remove(il); (this.inner = s)._add(this.il = new MapFlattenInner(u, this)); }; MapFlattenOperator.prototype._e = function (err) { var u = this.out; if (u === NO) return; u._e(err); }; MapFlattenOperator.prototype._c = function () { this.open = false; this.less(); }; return MapFlattenOperator; }()); exports.MapFlattenOperator = MapFlattenOperator; var MapOperator = (function () { function MapOperator(project, ins) { this.type = 'map'; this.ins = ins; this.out = NO; this.project = project; } MapOperator.prototype._start = function (out) { this.out = out; this.ins._add(this); }; MapOperator.prototype._stop = function () { this.ins._remove(this); this.out = NO; }; MapOperator.prototype._n = function (t) { var u = this.out; if (u === NO) return; try { u._n(this.project(t)); } catch (e) { u._e(e); } }; MapOperator.prototype._e = function (err) { var u = this.out; if (u === NO) return; u._e(err); }; MapOperator.prototype._c = function () { var u = this.out; if (u === NO) return; u._c(); }; return MapOperator; }()); exports.MapOperator = MapOperator; var FilterMapOperator = (function (_super) { __extends(FilterMapOperator, _super); function FilterMapOperator(passes, project, ins) { _super.call(this, project, ins); this.type = 'filter+map'; this.passes = passes; } FilterMapOperator.prototype._n = function (v) { if (this.passes(v)) { _super.prototype._n.call(this, v); } ; }; return FilterMapOperator; }(MapOperator)); exports.FilterMapOperator = FilterMapOperator; var RememberOperator = (function () { function RememberOperator(ins) { this.type = 'remember'; this.ins = ins; this.out = NO; } RememberOperator.prototype._start = function (out) { this.out = out; this.ins._add(out); }; RememberOperator.prototype._stop = function () { this.ins._remove(this.out); this.out = NO; }; return RememberOperator; }()); exports.RememberOperator = RememberOperator; var ReplaceErrorOperator = (function () { function ReplaceErrorOperator(fn, ins) { this.type = 'replaceError'; this.ins = ins; this.out = NO; this.fn = fn; } ReplaceErrorOperator.prototype._start = function (out) { this.out = out; this.ins._add(this); }; ReplaceErrorOperator.prototype._stop = function () { this.ins._remove(this); this.out = NO; }; ReplaceErrorOperator.prototype._n = function (t) { var u = this.out; if (u === NO) return; u._n(t); }; ReplaceErrorOperator.prototype._e = function (err) { var u = this.out; if (u === NO) return; try { this.ins._remove(this); (this.ins = this.fn(err))._add(this); } catch (e) { u._e(e); } }; ReplaceErrorOperator.prototype._c = function () { var u = this.out; if (u === NO) return; u._c(); }; return ReplaceErrorOperator; }()); exports.ReplaceErrorOperator = ReplaceErrorOperator; var StartWithOperator = (function () { function StartWithOperator(ins, val) { this.type = 'startWith'; this.ins = ins; this.out = NO; this.val = val; } StartWithOperator.prototype._start = function (out) { this.out = out; this.out._n(this.val); this.ins._add(out); }; StartWithOperator.prototype._stop = function () { this.ins._remove(this.out); this.out = NO; }; return StartWithOperator; }()); exports.StartWithOperator = StartWithOperator; var TakeOperator = (function () { function TakeOperator(max, ins) { this.type = 'take'; this.ins = ins; this.out = NO; this.max = max; this.taken = 0; } TakeOperator.prototype._start = function (out) { this.out = out; this.taken = 0; this.ins._add(this); }; TakeOperator.prototype._stop = function () { this.ins._remove(this); this.out = NO; }; TakeOperator.prototype._n = function (t) { var u = this.out; if (u === NO) return; if (this.taken++ < this.max - 1) { u._n(t); } else { u._n(t); u._c(); } }; TakeOperator.prototype._e = function (err) { var u = this.out; if (u === NO) return; u._e(err); }; TakeOperator.prototype._c = function () { var u = this.out; if (u === NO) return; u._c(); }; return TakeOperator; }()); exports.TakeOperator = TakeOperator; var Stream = (function () { function Stream(producer) { this._prod = producer || NO; this._ils = []; this._stopID = NO; this._target = NO; this._err = NO; } Stream.prototype._n = function (t) { var a = this._ils; var L = a.length; if (L == 1) a[0]._n(t); else { var b = copy(a); for (var i = 0; i < L; i++) b[i]._n(t); } }; Stream.prototype._e = function (err) { if (this._err !== NO) return; this._err = err; var a = this._ils; var L = a.length; if (L == 1) a[0]._e(err); else { var b = copy(a); for (var i = 0; i < L; i++) b[i]._e(err); } this._x(); }; Stream.prototype._c = function () { var a = this._ils; var L = a.length; if (L == 1) a[0]._c(); else { var b = copy(a); for (var i = 0; i < L; i++) b[i]._c(); } this._x(); }; Stream.prototype._x = function () { if (this._ils.length === 0) return; if (this._prod !== NO) this._prod._stop(); this._err = NO; this._ils = []; }; Stream.prototype._stopNow = function () { this._prod._stop(); this._err = NO; this._stopID = NO; }; Stream.prototype._add = function (il) { var ta = this._target; if (ta !== NO) return ta._add(il); var a = this._ils; a.push(il); if (a.length === 1) { if (this._stopID !== NO) { clearTimeout(this._stopID); this._stopID = NO; } var p = this._prod; if (p !== NO) p._start(this); } }; Stream.prototype._remove = function (il) { var _this = this; var ta = this._target; if (ta !== NO) return ta._remove(il); var a = this._ils; var i = a.indexOf(il); if (i > -1) { a.splice(i, 1); if (this._prod !== NO && a.length <= 0) { this._err = NO; this._stopID = setTimeout(function () { return _this._stopNow(); }); } else if (a.length === 1) { this._pruneCycles(); } } }; Stream.prototype._pruneCycles = function () { if (this._hasNoSinks(this, [])) { this._remove(this._ils[0]); } }; Stream.prototype._hasNoSinks = function (x, trace) { if (trace.indexOf(x) !== -1) { return true; } else if (x.out === this) { return true; } else if (x.out && x.out !== NO) { return this._hasNoSinks(x.out, trace.concat(x)); } else if (x._ils) { for (var i = 0, N = x._ils.length; i < N; i++) { if (!this._hasNoSinks(x._ils[i], trace.concat(x))) { return false; } } return true; } else { return false; } }; Stream.prototype.ctor = function () { return this instanceof MemoryStream ? MemoryStream : Stream; }; Stream.prototype.addListener = function (listener) { if (typeof listener.next !== 'function' || typeof listener.error !== 'function' || typeof listener.complete !== 'function') { throw new Error('stream.addListener() requires all three next, error, ' + 'and complete functions.'); } listener._n = listener.next; listener._e = listener.error; listener._c = listener.complete; this._add(listener); }; Stream.prototype.removeListener = function (listener) { this._remove(listener); }; Stream.create = function (producer) { if (producer) { if (typeof producer.start !== 'function' || typeof producer.stop !== 'function') { throw new Error('producer requires both start and stop functions'); } internalizeProducer(producer); } return new Stream(producer); }; Stream.createWithMemory = function (producer) { if (producer) { internalizeProducer(producer); } return new MemoryStream(producer); }; Stream.never = function () { return new Stream({ _start: noop, _stop: noop }); }; Stream.empty = function () { return new Stream({ _start: function (il) { il._c(); }, _stop: noop, }); }; Stream.throw = function (error) { return new Stream({ _start: function (il) { il._e(error); }, _stop: noop, }); }; Stream.of = function () { var items = []; for (var _i = 0; _i < arguments.length; _i++) { items[_i - 0] = arguments[_i]; } return Stream.fromArray(items); }; Stream.fromArray = function (array) { return new Stream(new FromArrayProducer(array)); }; Stream.fromPromise = function (promise) { return new Stream(new FromPromiseProducer(promise)); }; Stream.periodic = function (period) { return new Stream(new PeriodicProducer(period)); }; Stream.prototype._map = function (project) { var p = this._prod; var ctor = this.ctor(); if (p instanceof FilterOperator) { return new ctor(new FilterMapOperator(p.passes, project, p.ins)); } if (p instanceof FilterMapOperator) { return new ctor(new FilterMapOperator(p.passes, compose2(project, p.project), p.ins)); } if (p instanceof MapOperator) { return new ctor(new MapOperator(compose2(project, p.project), p.ins)); } return new ctor(new MapOperator(project, this)); }; Stream.prototype.map = function (project) { return this._map(project); }; Stream.prototype.mapTo = function (projectedValue) { var s = this.map(function () { return projectedValue; }); var op = s._prod; op.type = op.type.replace('map', 'mapTo'); return s; }; Stream.prototype.filter = function (passes) { var p = this._prod; if (p instanceof FilterOperator) { return new Stream(new FilterOperator(and(p.passes, passes), p.ins)); } return new Stream(new FilterOperator(passes, this)); }; Stream.prototype.take = function (amount) { return new (this.ctor())(new TakeOperator(amount, this)); }; Stream.prototype.drop = function (amount) { return new Stream(new DropOperator(amount, this)); }; Stream.prototype.last = function () { return new Stream(new LastOperator(this)); }; Stream.prototype.startWith = function (initial) { return new MemoryStream(new StartWithOperator(this, initial)); }; Stream.prototype.endWhen = function (other) { return new (this.ctor())(new EndWhenOperator(other, this)); }; Stream.prototype.fold = function (accumulate, seed) { return new MemoryStream(new FoldOperator(accumulate, seed, this)); }; Stream.prototype.replaceError = function (replace) { return new (this.ctor())(new ReplaceErrorOperator(replace, this)); }; Stream.prototype.flatten = function () { var p = this._prod; return new Stream(p instanceof MapOperator && !(p instanceof FilterMapOperator) ? new MapFlattenOperator(p) : new FlattenOperator(this)); }; Stream.prototype.compose = function (operator) { return operator(this); }; Stream.prototype.remember = function () { return new MemoryStream(new RememberOperator(this)); }; Stream.prototype.debug = function (labelOrSpy) { return new (this.ctor())(new DebugOperator(labelOrSpy, this)); }; Stream.prototype.imitate = function (target) { if (target instanceof MemoryStream) { throw new Error('A MemoryStream was given to imitate(), but it only ' + 'supports a Stream. Read more about this restriction here: ' + 'https://github.com/staltz/xstream#faq'); } this._target = target; for (var ils = this._ils, N = ils.length, i = 0; i < N; i++) { target._add(ils[i]); } this._ils = []; }; Stream.prototype.shamefullySendNext = function (value) { this._n(value); }; Stream.prototype.shamefullySendError = function (error) { this._e(error); }; Stream.prototype.shamefullySendComplete = function () { this._c(); }; Stream.merge = function merge() { var streams = []; for (var _i = 0; _i < arguments.length; _i++) { streams[_i - 0] = arguments[_i]; } return new Stream(new MergeProducer(streams)); }; Stream.combine = function combine() { var streams = []; for (var _i = 0; _i < arguments.length; _i++) { streams[_i - 0] = arguments[_i]; } return new Stream(new CombineProducer(streams)); }; return Stream; }()); exports.Stream = Stream; var MemoryStream = (function (_super) { __extends(MemoryStream, _super); function MemoryStream(producer) { _super.call(this, producer); this._has = false; } MemoryStream.prototype._n = function (x) { this._v = x; this._has = true; _super.prototype._n.call(this, x); }; MemoryStream.prototype._add = function (il) { if (this._has) { il._n(this._v); } _super.prototype._add.call(this, il); }; MemoryStream.prototype._stopNow = function () { this._has = false; _super.prototype._stopNow.call(this); }; MemoryStream.prototype._x = function () { this._has = false; _super.prototype._x.call(this); }; MemoryStream.prototype.map = function (project) { return this._map(project); }; MemoryStream.prototype.mapTo = function (projectedValue) { return _super.prototype.mapTo.call(this, projectedValue); }; MemoryStream.prototype.take = function (amount) { return _super.prototype.take.call(this, amount); }; MemoryStream.prototype.endWhen = function (other) { return _super.prototype.endWhen.call(this, other); }; MemoryStream.prototype.replaceError = function (replace) { return _super.prototype.replaceError.call(this, replace); }; MemoryStream.prototype.remember = function () { return this; }; MemoryStream.prototype.debug = function (labelOrSpy) { return _super.prototype.debug.call(this, labelOrSpy); }; return MemoryStream; }(Stream)); exports.MemoryStream = MemoryStream; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Stream; },{}],2:[function(require,module,exports){ "use strict"; var core_1 = require('./core'); exports.Stream = core_1.Stream; exports.MemoryStream = core_1.MemoryStream; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = core_1.Stream; },{"./core":1}]},{},[2])(2) });
/*! Qoopido.demand 3.0.0 | https://github.com/dlueth/qoopido.demand | (c) 2016 Dirk Lueth */ !function(){"use strict";function n(){return{process:function(){var n=this;provide(function(){return n.source})}}}provide(n)}(); //# sourceMappingURL=text.js.map
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import ReactDOM from 'react-dom'; import ObjectDestructuring from './ObjectDestructuring'; describe('object destructuring', () => { it('renders without crashing', () => { const div = document.createElement('div'); return new Promise(resolve => { ReactDOM.render(<ObjectDestructuring onReady={resolve} />, div); }); }); });
x: while (true) { (function () { break x; }); }
/* Highmaps JS v4.2.6 (2016-08-02) Client side exporting module (c) 2015 Torstein Honsi / Oystein Moseng License: www.highcharts.com/license */ (function(a){typeof module==="object"&&module.exports?module.exports=a:a(Highcharts)})(function(a){function v(g,a){var c=m.getElementsByTagName("head")[0],b=m.createElement("script");b.type="text/javascript";b.src=g;b.onload=a;c.appendChild(b)}var j=a.win,k=j.navigator,m=j.document,r=j.URL||j.webkitURL||j,s=/Edge\/|Trident\/|MSIE /.test(k.userAgent),w=s?150:0;a.CanVGRenderer={};a.downloadURL=function(g,a){var c=m.createElement("a"),b;if(k.msSaveOrOpenBlob)k.msSaveOrOpenBlob(g,a);else if(c.download!== void 0)c.href=g,c.download=a,c.target="_blank",m.body.appendChild(c),c.click(),m.body.removeChild(c);else try{if(b=j.open(g,"chart"),b===void 0||b===null)throw"Failed to open window";}catch(i){j.location.href=g}};a.svgToDataUrl=function(a){var h=k.userAgent.indexOf("WebKit")>-1&&k.userAgent.indexOf("Chrome")<0;try{if(!h&&k.userAgent.toLowerCase().indexOf("firefox")<0)return r.createObjectURL(new j.Blob([a],{type:"image/svg+xml;charset-utf-16"}))}catch(c){}return"data:image/svg+xml;charset=UTF-8,"+ encodeURIComponent(a)};a.imageToDataUrl=function(a,h,c,b,i,d,l,f,n){var e=new j.Image,k,o=function(){setTimeout(function(){var d=m.createElement("canvas"),o=d.getContext&&d.getContext("2d"),f;try{if(o){d.height=e.height*b;d.width=e.width*b;o.drawImage(e,0,0,d.width,d.height);try{f=d.toDataURL(h),i(f,h,c,b)}catch(j){k(a,h,c,b)}}else l(a,h,c,b)}finally{n&&n(a,h,c,b)}},w)},q=function(){f(a,h,c,b);n&&n(a,h,c,b)};k=function(){e=new j.Image;k=d;e.crossOrigin="Anonymous";e.onload=o;e.onerror=q;e.src=a}; e.onload=o;e.onerror=q;e.src=a};a.downloadSVGLocal=function(g,h,c,b,i,d){var l,f,n=!0,e;if(c==="image/svg+xml")try{k.msSaveOrOpenBlob?(f=new MSBlobBuilder,f.append(g),l=f.getBlob("image/svg+xml")):l=a.svgToDataUrl(g),a.downloadURL(l,h),d&&d()}catch(p){i()}else l=a.svgToDataUrl(g),e=function(){try{r.revokeObjectURL(l)}catch(a){}},a.imageToDataUrl(l,c,{},b,function(b){try{a.downloadURL(b,h),d&&d()}catch(c){i()}},function(){var f=m.createElement("canvas"),l=f.getContext("2d"),t=g.match(/^<svg[^>]*width\s*=\s*\"?(\d+)\"?[^>]*>/)[1]* b,p=g.match(/^<svg[^>]*height\s*=\s*\"?(\d+)\"?[^>]*>/)[1]*b,u=function(){l.drawSvg(g,0,0,t,p);try{a.downloadURL(k.msSaveOrOpenBlob?f.msToBlob():f.toDataURL(c),h),d&&d()}catch(b){i()}finally{e()}};f.width=t;f.height=p;j.canvg?u():(n=!0,v(a.getOptions().global.canvasToolsURL,function(){u()}))},i,i,function(){n&&e()})};a.Chart.prototype.getSVGForLocalExport=function(g,h,c,b){var i=this,d,l=0,f,j,e,k,m=function(a,c,e){++l;e.imageElement.setAttributeNS("http://www.w3.org/1999/xlink","href",a);l===d.length&& b(i.sanitizeSVG(f.innerHTML))};a.wrap(a.Chart.prototype,"getChartHTML",function(a){f=this.container.cloneNode(!0);return a.apply(this,Array.prototype.slice.call(arguments,1))});i.getSVGForExport(g,h);d=f.getElementsByTagName("image");try{if(d.length)for(e=0,k=d.length;e<k;++e)j=d[e],a.imageToDataUrl(j.getAttributeNS("http://www.w3.org/1999/xlink","href"),"image/png",{imageElement:j},g.scale,m,c,c,c);else b(i.sanitizeSVG(f.innerHTML))}catch(q){c()}};a.Chart.prototype.exportChartLocal=function(g,h){var c= this,b=a.merge(c.options.exporting,g),i=b&&b.type||"image/png",d=function(){if(b.fallbackToExportServer===!1)if(b.error)b.error();else throw"Fallback to export server disabled";else c.exportChart(b)};s&&i!=="image/svg+xml"&&c.container.getElementsByTagName("image").length?d():c.getSVGForLocalExport(b,h,d,function(c){var f=(b.filename||"chart")+"."+(i==="image/svg+xml"?"svg":i.split("/")[1]);a.downloadSVGLocal(c,f,i,b.scale,d)})};a.getOptions().exporting.buttons.contextButton.menuItems=[{textKey:"printChart", onclick:function(){this.print()}},{separator:!0},{textKey:"downloadPNG",onclick:function(){this.exportChartLocal()}},{textKey:"downloadJPEG",onclick:function(){this.exportChartLocal({type:"image/jpeg"})}},{textKey:"downloadSVG",onclick:function(){this.exportChartLocal({type:"image/svg+xml"})}}]});
// subkit.js - 1.1.14 // https://github.com/subkit // Copyright 2012 - 2015 http://subkit.io // MIT License !function(e){"object"==typeof exports?module.exports=e():"function"==typeof define&&define.amd?define(e):"undefined"!=typeof window?window.Subkit=e():"undefined"!=typeof global?global.Subkit=e():"undefined"!=typeof self&&(self.Subkit=e())}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; process.nextTick = (function () { var canSetImmediate = typeof window !== 'undefined' && window.setImmediate; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canSetImmediate) { return function (f) { return window.setImmediate(f) }; } if (canPost) { var queue = []; window.addEventListener('message', function (ev) { var source = ev.source; if ((source === window || source === null) && ev.data === 'process-tick') { ev.stopPropagation(); if (queue.length > 0) { var fn = queue.shift(); fn(); } } }, true); return function nextTick(fn) { queue.push(fn); window.postMessage('process-tick', '*'); }; } return function nextTick(fn) { setTimeout(fn, 0); }; })(); process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.binding = function (name) { throw new Error('process.binding is not supported'); } // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; },{}],2:[function(require,module,exports){ var process=require("__browserify_process");// vim:ts=4:sts=4:sw=4: /*! * * Copyright 2009-2012 Kris Kowal under the terms of the MIT * license found at http://github.com/kriskowal/q/raw/master/LICENSE * * With parts by Tyler Close * Copyright 2007-2009 Tyler Close under the terms of the MIT X license found * at http://www.opensource.org/licenses/mit-license.html * Forked at ref_send.js version: 2009-05-11 * * With parts by Mark Miller * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ (function (definition) { "use strict"; // This file will function properly as a <script> tag, or a module // using CommonJS and NodeJS or RequireJS module formats. In // Common/Node/RequireJS, the module exports the Q API and when // executed as a simple <script>, it creates a Q global instead. // Montage Require if (typeof bootstrap === "function") { bootstrap("promise", definition); // CommonJS } else if (typeof exports === "object" && typeof module === "object") { module.exports = definition(); // RequireJS } else if (typeof define === "function" && define.amd) { define(definition); // SES (Secure EcmaScript) } else if (typeof ses !== "undefined") { if (!ses.ok()) { return; } else { ses.makeQ = definition; } // <script> } else if (typeof self !== "undefined") { self.Q = definition(); } else { throw new Error("This environment was not anticipated by Q. Please file a bug."); } })(function () { "use strict"; var hasStacks = false; try { throw new Error(); } catch (e) { hasStacks = !!e.stack; } // All code after this point will be filtered from stack traces reported // by Q. var qStartingLine = captureLine(); var qFileName; // shims // used for fallback in "allResolved" var noop = function () {}; // Use the fastest possible means to execute a task in a future turn // of the event loop. var nextTick =(function () { // linked list of tasks (single, with head node) var head = {task: void 0, next: null}; var tail = head; var flushing = false; var requestTick = void 0; var isNodeJS = false; function flush() { /* jshint loopfunc: true */ while (head.next) { head = head.next; var task = head.task; head.task = void 0; var domain = head.domain; if (domain) { head.domain = void 0; domain.enter(); } try { task(); } catch (e) { if (isNodeJS) { // In node, uncaught exceptions are considered fatal errors. // Re-throw them synchronously to interrupt flushing! // Ensure continuation if the uncaught exception is suppressed // listening "uncaughtException" events (as domains does). // Continue in next event to avoid tick recursion. if (domain) { domain.exit(); } setTimeout(flush, 0); if (domain) { domain.enter(); } throw e; } else { // In browsers, uncaught exceptions are not fatal. // Re-throw them asynchronously to avoid slow-downs. setTimeout(function() { throw e; }, 0); } } if (domain) { domain.exit(); } } flushing = false; } nextTick = function (task) { tail = tail.next = { task: task, domain: isNodeJS && process.domain, next: null }; if (!flushing) { flushing = true; requestTick(); } }; if (typeof process !== "undefined" && process.nextTick) { // Node.js before 0.9. Note that some fake-Node environments, like the // Mocha test runner, introduce a `process` global without a `nextTick`. isNodeJS = true; requestTick = function () { process.nextTick(flush); }; } else if (typeof setImmediate === "function") { // In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate if (typeof window !== "undefined") { requestTick = setImmediate.bind(window, flush); } else { requestTick = function () { setImmediate(flush); }; } } else if (typeof MessageChannel !== "undefined") { // modern browsers // http://www.nonblocking.io/2011/06/windownexttick.html var channel = new MessageChannel(); // At least Safari Version 6.0.5 (8536.30.1) intermittently cannot create // working message ports the first time a page loads. channel.port1.onmessage = function () { requestTick = requestPortTick; channel.port1.onmessage = flush; flush(); }; var requestPortTick = function () { // Opera requires us to provide a message payload, regardless of // whether we use it. channel.port2.postMessage(0); }; requestTick = function () { setTimeout(flush, 0); requestPortTick(); }; } else { // old browsers requestTick = function () { setTimeout(flush, 0); }; } return nextTick; })(); // Attempt to make generics safe in the face of downstream // modifications. // There is no situation where this is necessary. // If you need a security guarantee, these primordials need to be // deeply frozen anyway, and if you don’t need a security guarantee, // this is just plain paranoid. // However, this **might** have the nice side-effect of reducing the size of // the minified code by reducing x.call() to merely x() // See Mark Miller’s explanation of what this does. // http://wiki.ecmascript.org/doku.php?id=conventions:safe_meta_programming var call = Function.call; function uncurryThis(f) { return function () { return call.apply(f, arguments); }; } // This is equivalent, but slower: // uncurryThis = Function_bind.bind(Function_bind.call); // http://jsperf.com/uncurrythis var array_slice = uncurryThis(Array.prototype.slice); var array_reduce = uncurryThis( Array.prototype.reduce || function (callback, basis) { var index = 0, length = this.length; // concerning the initial value, if one is not provided if (arguments.length === 1) { // seek to the first value in the array, accounting // for the possibility that is is a sparse array do { if (index in this) { basis = this[index++]; break; } if (++index >= length) { throw new TypeError(); } } while (1); } // reduce for (; index < length; index++) { // account for the possibility that the array is sparse if (index in this) { basis = callback(basis, this[index], index); } } return basis; } ); var array_indexOf = uncurryThis( Array.prototype.indexOf || function (value) { // not a very good shim, but good enough for our one use of it for (var i = 0; i < this.length; i++) { if (this[i] === value) { return i; } } return -1; } ); var array_map = uncurryThis( Array.prototype.map || function (callback, thisp) { var self = this; var collect = []; array_reduce(self, function (undefined, value, index) { collect.push(callback.call(thisp, value, index, self)); }, void 0); return collect; } ); var object_create = Object.create || function (prototype) { function Type() { } Type.prototype = prototype; return new Type(); }; var object_hasOwnProperty = uncurryThis(Object.prototype.hasOwnProperty); var object_keys = Object.keys || function (object) { var keys = []; for (var key in object) { if (object_hasOwnProperty(object, key)) { keys.push(key); } } return keys; }; var object_toString = uncurryThis(Object.prototype.toString); function isObject(value) { return value === Object(value); } // generator related shims // FIXME: Remove this function once ES6 generators are in SpiderMonkey. function isStopIteration(exception) { return ( object_toString(exception) === "[object StopIteration]" || exception instanceof QReturnValue ); } // FIXME: Remove this helper and Q.return once ES6 generators are in // SpiderMonkey. var QReturnValue; if (typeof ReturnValue !== "undefined") { QReturnValue = ReturnValue; } else { QReturnValue = function (value) { this.value = value; }; } // long stack traces var STACK_JUMP_SEPARATOR = "From previous event:"; function makeStackTraceLong(error, promise) { // If possible, transform the error stack trace by removing Node and Q // cruft, then concatenating with the stack trace of `promise`. See #57. if (hasStacks && promise.stack && typeof error === "object" && error !== null && error.stack && error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1 ) { var stacks = []; for (var p = promise; !!p; p = p.source) { if (p.stack) { stacks.unshift(p.stack); } } stacks.unshift(error.stack); var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n"); error.stack = filterStackString(concatedStacks); } } function filterStackString(stackString) { var lines = stackString.split("\n"); var desiredLines = []; for (var i = 0; i < lines.length; ++i) { var line = lines[i]; if (!isInternalFrame(line) && !isNodeFrame(line) && line) { desiredLines.push(line); } } return desiredLines.join("\n"); } function isNodeFrame(stackLine) { return stackLine.indexOf("(module.js:") !== -1 || stackLine.indexOf("(node.js:") !== -1; } function getFileNameAndLineNumber(stackLine) { // Named functions: "at functionName (filename:lineNumber:columnNumber)" // In IE10 function name can have spaces ("Anonymous function") O_o var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine); if (attempt1) { return [attempt1[1], Number(attempt1[2])]; } // Anonymous functions: "at filename:lineNumber:columnNumber" var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine); if (attempt2) { return [attempt2[1], Number(attempt2[2])]; } // Firefox style: "function@filename:lineNumber or @filename:lineNumber" var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine); if (attempt3) { return [attempt3[1], Number(attempt3[2])]; } } function isInternalFrame(stackLine) { var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine); if (!fileNameAndLineNumber) { return false; } var fileName = fileNameAndLineNumber[0]; var lineNumber = fileNameAndLineNumber[1]; return fileName === qFileName && lineNumber >= qStartingLine && lineNumber <= qEndingLine; } // discover own file name and line number range for filtering stack // traces function captureLine() { if (!hasStacks) { return; } try { throw new Error(); } catch (e) { var lines = e.stack.split("\n"); var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2]; var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine); if (!fileNameAndLineNumber) { return; } qFileName = fileNameAndLineNumber[0]; return fileNameAndLineNumber[1]; } } function deprecate(callback, name, alternative) { return function () { if (typeof console !== "undefined" && typeof console.warn === "function") { console.warn(name + " is deprecated, use " + alternative + " instead.", new Error("").stack); } return callback.apply(callback, arguments); }; } // end of shims // beginning of real work /** * Constructs a promise for an immediate reference, passes promises through, or * coerces promises from different systems. * @param value immediate reference or promise */ function Q(value) { // If the object is already a Promise, return it directly. This enables // the resolve function to both be used to created references from objects, // but to tolerably coerce non-promises to promises. if (value instanceof Promise) { return value; } // assimilate thenables if (isPromiseAlike(value)) { return coerce(value); } else { return fulfill(value); } } Q.resolve = Q; /** * Performs a task in a future turn of the event loop. * @param {Function} task */ Q.nextTick = nextTick; /** * Controls whether or not long stack traces will be on */ Q.longStackSupport = false; // enable long stacks if Q_DEBUG is set if (typeof process === "object" && process && process.env && process.env.Q_DEBUG) { Q.longStackSupport = true; } /** * Constructs a {promise, resolve, reject} object. * * `resolve` is a callback to invoke with a more resolved value for the * promise. To fulfill the promise, invoke `resolve` with any value that is * not a thenable. To reject the promise, invoke `resolve` with a rejected * thenable, or invoke `reject` with the reason directly. To resolve the * promise to another thenable, thus putting it in the same state, invoke * `resolve` with that other thenable. */ Q.defer = defer; function defer() { // if "messages" is an "Array", that indicates that the promise has not yet // been resolved. If it is "undefined", it has been resolved. Each // element of the messages array is itself an array of complete arguments to // forward to the resolved promise. We coerce the resolution value to a // promise using the `resolve` function because it handles both fully // non-thenable values and other thenables gracefully. var messages = [], progressListeners = [], resolvedPromise; var deferred = object_create(defer.prototype); var promise = object_create(Promise.prototype); promise.promiseDispatch = function (resolve, op, operands) { var args = array_slice(arguments); if (messages) { messages.push(args); if (op === "when" && operands[1]) { // progress operand progressListeners.push(operands[1]); } } else { Q.nextTick(function () { resolvedPromise.promiseDispatch.apply(resolvedPromise, args); }); } }; // XXX deprecated promise.valueOf = function () { if (messages) { return promise; } var nearerValue = nearer(resolvedPromise); if (isPromise(nearerValue)) { resolvedPromise = nearerValue; // shorten chain } return nearerValue; }; promise.inspect = function () { if (!resolvedPromise) { return { state: "pending" }; } return resolvedPromise.inspect(); }; if (Q.longStackSupport && hasStacks) { try { throw new Error(); } catch (e) { // NOTE: don't try to use `Error.captureStackTrace` or transfer the // accessor around; that causes memory leaks as per GH-111. Just // reify the stack trace as a string ASAP. // // At the same time, cut off the first line; it's always just // "[object Promise]\n", as per the `toString`. promise.stack = e.stack.substring(e.stack.indexOf("\n") + 1); } } // NOTE: we do the checks for `resolvedPromise` in each method, instead of // consolidating them into `become`, since otherwise we'd create new // promises with the lines `become(whatever(value))`. See e.g. GH-252. function become(newPromise) { resolvedPromise = newPromise; promise.source = newPromise; array_reduce(messages, function (undefined, message) { Q.nextTick(function () { newPromise.promiseDispatch.apply(newPromise, message); }); }, void 0); messages = void 0; progressListeners = void 0; } deferred.promise = promise; deferred.resolve = function (value) { if (resolvedPromise) { return; } become(Q(value)); }; deferred.fulfill = function (value) { if (resolvedPromise) { return; } become(fulfill(value)); }; deferred.reject = function (reason) { if (resolvedPromise) { return; } become(reject(reason)); }; deferred.notify = function (progress) { if (resolvedPromise) { return; } array_reduce(progressListeners, function (undefined, progressListener) { Q.nextTick(function () { progressListener(progress); }); }, void 0); }; return deferred; } /** * Creates a Node-style callback that will resolve or reject the deferred * promise. * @returns a nodeback */ defer.prototype.makeNodeResolver = function () { var self = this; return function (error, value) { if (error) { self.reject(error); } else if (arguments.length > 2) { self.resolve(array_slice(arguments, 1)); } else { self.resolve(value); } }; }; /** * @param resolver {Function} a function that returns nothing and accepts * the resolve, reject, and notify functions for a deferred. * @returns a promise that may be resolved with the given resolve and reject * functions, or rejected by a thrown exception in resolver */ Q.Promise = promise; // ES6 Q.promise = promise; function promise(resolver) { if (typeof resolver !== "function") { throw new TypeError("resolver must be a function."); } var deferred = defer(); try { resolver(deferred.resolve, deferred.reject, deferred.notify); } catch (reason) { deferred.reject(reason); } return deferred.promise; } promise.race = race; // ES6 promise.all = all; // ES6 promise.reject = reject; // ES6 promise.resolve = Q; // ES6 // XXX experimental. This method is a way to denote that a local value is // serializable and should be immediately dispatched to a remote upon request, // instead of passing a reference. Q.passByCopy = function (object) { //freeze(object); //passByCopies.set(object, true); return object; }; Promise.prototype.passByCopy = function () { //freeze(object); //passByCopies.set(object, true); return this; }; /** * If two promises eventually fulfill to the same value, promises that value, * but otherwise rejects. * @param x {Any*} * @param y {Any*} * @returns {Any*} a promise for x and y if they are the same, but a rejection * otherwise. * */ Q.join = function (x, y) { return Q(x).join(y); }; Promise.prototype.join = function (that) { return Q([this, that]).spread(function (x, y) { if (x === y) { // TODO: "===" should be Object.is or equiv return x; } else { throw new Error("Can't join: not the same: " + x + " " + y); } }); }; /** * Returns a promise for the first of an array of promises to become settled. * @param answers {Array[Any*]} promises to race * @returns {Any*} the first promise to be settled */ Q.race = race; function race(answerPs) { return promise(function(resolve, reject) { // Switch to this once we can assume at least ES5 // answerPs.forEach(function(answerP) { // Q(answerP).then(resolve, reject); // }); // Use this in the meantime for (var i = 0, len = answerPs.length; i < len; i++) { Q(answerPs[i]).then(resolve, reject); } }); } Promise.prototype.race = function () { return this.then(Q.race); }; /** * Constructs a Promise with a promise descriptor object and optional fallback * function. The descriptor contains methods like when(rejected), get(name), * set(name, value), post(name, args), and delete(name), which all * return either a value, a promise for a value, or a rejection. The fallback * accepts the operation name, a resolver, and any further arguments that would * have been forwarded to the appropriate method above had a method been * provided with the proper name. The API makes no guarantees about the nature * of the returned object, apart from that it is usable whereever promises are * bought and sold. */ Q.makePromise = Promise; function Promise(descriptor, fallback, inspect) { if (fallback === void 0) { fallback = function (op) { return reject(new Error( "Promise does not support operation: " + op )); }; } if (inspect === void 0) { inspect = function () { return {state: "unknown"}; }; } var promise = object_create(Promise.prototype); promise.promiseDispatch = function (resolve, op, args) { var result; try { if (descriptor[op]) { result = descriptor[op].apply(promise, args); } else { result = fallback.call(promise, op, args); } } catch (exception) { result = reject(exception); } if (resolve) { resolve(result); } }; promise.inspect = inspect; // XXX deprecated `valueOf` and `exception` support if (inspect) { var inspected = inspect(); if (inspected.state === "rejected") { promise.exception = inspected.reason; } promise.valueOf = function () { var inspected = inspect(); if (inspected.state === "pending" || inspected.state === "rejected") { return promise; } return inspected.value; }; } return promise; } Promise.prototype.toString = function () { return "[object Promise]"; }; Promise.prototype.then = function (fulfilled, rejected, progressed) { var self = this; var deferred = defer(); var done = false; // ensure the untrusted promise makes at most a // single call to one of the callbacks function _fulfilled(value) { try { return typeof fulfilled === "function" ? fulfilled(value) : value; } catch (exception) { return reject(exception); } } function _rejected(exception) { if (typeof rejected === "function") { makeStackTraceLong(exception, self); try { return rejected(exception); } catch (newException) { return reject(newException); } } return reject(exception); } function _progressed(value) { return typeof progressed === "function" ? progressed(value) : value; } Q.nextTick(function () { self.promiseDispatch(function (value) { if (done) { return; } done = true; deferred.resolve(_fulfilled(value)); }, "when", [function (exception) { if (done) { return; } done = true; deferred.resolve(_rejected(exception)); }]); }); // Progress propagator need to be attached in the current tick. self.promiseDispatch(void 0, "when", [void 0, function (value) { var newValue; var threw = false; try { newValue = _progressed(value); } catch (e) { threw = true; if (Q.onerror) { Q.onerror(e); } else { throw e; } } if (!threw) { deferred.notify(newValue); } }]); return deferred.promise; }; Q.tap = function (promise, callback) { return Q(promise).tap(callback); }; /** * Works almost like "finally", but not called for rejections. * Original resolution value is passed through callback unaffected. * Callback may return a promise that will be awaited for. * @param {Function} callback * @returns {Q.Promise} * @example * doSomething() * .then(...) * .tap(console.log) * .then(...); */ Promise.prototype.tap = function (callback) { callback = Q(callback); return this.then(function (value) { return callback.fcall(value).thenResolve(value); }); }; /** * Registers an observer on a promise. * * Guarantees: * * 1. that fulfilled and rejected will be called only once. * 2. that either the fulfilled callback or the rejected callback will be * called, but not both. * 3. that fulfilled and rejected will not be called in this turn. * * @param value promise or immediate reference to observe * @param fulfilled function to be called with the fulfilled value * @param rejected function to be called with the rejection exception * @param progressed function to be called on any progress notifications * @return promise for the return value from the invoked callback */ Q.when = when; function when(value, fulfilled, rejected, progressed) { return Q(value).then(fulfilled, rejected, progressed); } Promise.prototype.thenResolve = function (value) { return this.then(function () { return value; }); }; Q.thenResolve = function (promise, value) { return Q(promise).thenResolve(value); }; Promise.prototype.thenReject = function (reason) { return this.then(function () { throw reason; }); }; Q.thenReject = function (promise, reason) { return Q(promise).thenReject(reason); }; /** * If an object is not a promise, it is as "near" as possible. * If a promise is rejected, it is as "near" as possible too. * If it’s a fulfilled promise, the fulfillment value is nearer. * If it’s a deferred promise and the deferred has been resolved, the * resolution is "nearer". * @param object * @returns most resolved (nearest) form of the object */ // XXX should we re-do this? Q.nearer = nearer; function nearer(value) { if (isPromise(value)) { var inspected = value.inspect(); if (inspected.state === "fulfilled") { return inspected.value; } } return value; } /** * @returns whether the given object is a promise. * Otherwise it is a fulfilled value. */ Q.isPromise = isPromise; function isPromise(object) { return object instanceof Promise; } Q.isPromiseAlike = isPromiseAlike; function isPromiseAlike(object) { return isObject(object) && typeof object.then === "function"; } /** * @returns whether the given object is a pending promise, meaning not * fulfilled or rejected. */ Q.isPending = isPending; function isPending(object) { return isPromise(object) && object.inspect().state === "pending"; } Promise.prototype.isPending = function () { return this.inspect().state === "pending"; }; /** * @returns whether the given object is a value or fulfilled * promise. */ Q.isFulfilled = isFulfilled; function isFulfilled(object) { return !isPromise(object) || object.inspect().state === "fulfilled"; } Promise.prototype.isFulfilled = function () { return this.inspect().state === "fulfilled"; }; /** * @returns whether the given object is a rejected promise. */ Q.isRejected = isRejected; function isRejected(object) { return isPromise(object) && object.inspect().state === "rejected"; } Promise.prototype.isRejected = function () { return this.inspect().state === "rejected"; }; //// BEGIN UNHANDLED REJECTION TRACKING // This promise library consumes exceptions thrown in handlers so they can be // handled by a subsequent promise. The exceptions get added to this array when // they are created, and removed when they are handled. Note that in ES6 or // shimmed environments, this would naturally be a `Set`. var unhandledReasons = []; var unhandledRejections = []; var trackUnhandledRejections = true; function resetUnhandledRejections() { unhandledReasons.length = 0; unhandledRejections.length = 0; if (!trackUnhandledRejections) { trackUnhandledRejections = true; } } function trackRejection(promise, reason) { if (!trackUnhandledRejections) { return; } unhandledRejections.push(promise); if (reason && typeof reason.stack !== "undefined") { unhandledReasons.push(reason.stack); } else { unhandledReasons.push("(no stack) " + reason); } } function untrackRejection(promise) { if (!trackUnhandledRejections) { return; } var at = array_indexOf(unhandledRejections, promise); if (at !== -1) { unhandledRejections.splice(at, 1); unhandledReasons.splice(at, 1); } } Q.resetUnhandledRejections = resetUnhandledRejections; Q.getUnhandledReasons = function () { // Make a copy so that consumers can't interfere with our internal state. return unhandledReasons.slice(); }; Q.stopUnhandledRejectionTracking = function () { resetUnhandledRejections(); trackUnhandledRejections = false; }; resetUnhandledRejections(); //// END UNHANDLED REJECTION TRACKING /** * Constructs a rejected promise. * @param reason value describing the failure */ Q.reject = reject; function reject(reason) { var rejection = Promise({ "when": function (rejected) { // note that the error has been handled if (rejected) { untrackRejection(this); } return rejected ? rejected(reason) : this; } }, function fallback() { return this; }, function inspect() { return { state: "rejected", reason: reason }; }); // Note that the reason has not been handled. trackRejection(rejection, reason); return rejection; } /** * Constructs a fulfilled promise for an immediate reference. * @param value immediate reference */ Q.fulfill = fulfill; function fulfill(value) { return Promise({ "when": function () { return value; }, "get": function (name) { return value[name]; }, "set": function (name, rhs) { value[name] = rhs; }, "delete": function (name) { delete value[name]; }, "post": function (name, args) { // Mark Miller proposes that post with no name should apply a // promised function. if (name === null || name === void 0) { return value.apply(void 0, args); } else { return value[name].apply(value, args); } }, "apply": function (thisp, args) { return value.apply(thisp, args); }, "keys": function () { return object_keys(value); } }, void 0, function inspect() { return { state: "fulfilled", value: value }; }); } /** * Converts thenables to Q promises. * @param promise thenable promise * @returns a Q promise */ function coerce(promise) { var deferred = defer(); Q.nextTick(function () { try { promise.then(deferred.resolve, deferred.reject, deferred.notify); } catch (exception) { deferred.reject(exception); } }); return deferred.promise; } /** * Annotates an object such that it will never be * transferred away from this process over any promise * communication channel. * @param object * @returns promise a wrapping of that object that * additionally responds to the "isDef" message * without a rejection. */ Q.master = master; function master(object) { return Promise({ "isDef": function () {} }, function fallback(op, args) { return dispatch(object, op, args); }, function () { return Q(object).inspect(); }); } /** * Spreads the values of a promised array of arguments into the * fulfillment callback. * @param fulfilled callback that receives variadic arguments from the * promised array * @param rejected callback that receives the exception if the promise * is rejected. * @returns a promise for the return value or thrown exception of * either callback. */ Q.spread = spread; function spread(value, fulfilled, rejected) { return Q(value).spread(fulfilled, rejected); } Promise.prototype.spread = function (fulfilled, rejected) { return this.all().then(function (array) { return fulfilled.apply(void 0, array); }, rejected); }; /** * The async function is a decorator for generator functions, turning * them into asynchronous generators. Although generators are only part * of the newest ECMAScript 6 drafts, this code does not cause syntax * errors in older engines. This code should continue to work and will * in fact improve over time as the language improves. * * ES6 generators are currently part of V8 version 3.19 with the * --harmony-generators runtime flag enabled. SpiderMonkey has had them * for longer, but under an older Python-inspired form. This function * works on both kinds of generators. * * Decorates a generator function such that: * - it may yield promises * - execution will continue when that promise is fulfilled * - the value of the yield expression will be the fulfilled value * - it returns a promise for the return value (when the generator * stops iterating) * - the decorated function returns a promise for the return value * of the generator or the first rejected promise among those * yielded. * - if an error is thrown in the generator, it propagates through * every following yield until it is caught, or until it escapes * the generator function altogether, and is translated into a * rejection for the promise returned by the decorated generator. */ Q.async = async; function async(makeGenerator) { return function () { // when verb is "send", arg is a value // when verb is "throw", arg is an exception function continuer(verb, arg) { var result; // Until V8 3.19 / Chromium 29 is released, SpiderMonkey is the only // engine that has a deployed base of browsers that support generators. // However, SM's generators use the Python-inspired semantics of // outdated ES6 drafts. We would like to support ES6, but we'd also // like to make it possible to use generators in deployed browsers, so // we also support Python-style generators. At some point we can remove // this block. if (typeof StopIteration === "undefined") { // ES6 Generators try { result = generator[verb](arg); } catch (exception) { return reject(exception); } if (result.done) { return Q(result.value); } else { return when(result.value, callback, errback); } } else { // SpiderMonkey Generators // FIXME: Remove this case when SM does ES6 generators. try { result = generator[verb](arg); } catch (exception) { if (isStopIteration(exception)) { return Q(exception.value); } else { return reject(exception); } } return when(result, callback, errback); } } var generator = makeGenerator.apply(this, arguments); var callback = continuer.bind(continuer, "next"); var errback = continuer.bind(continuer, "throw"); return callback(); }; } /** * The spawn function is a small wrapper around async that immediately * calls the generator and also ends the promise chain, so that any * unhandled errors are thrown instead of forwarded to the error * handler. This is useful because it's extremely common to run * generators at the top-level to work with libraries. */ Q.spawn = spawn; function spawn(makeGenerator) { Q.done(Q.async(makeGenerator)()); } // FIXME: Remove this interface once ES6 generators are in SpiderMonkey. /** * Throws a ReturnValue exception to stop an asynchronous generator. * * This interface is a stop-gap measure to support generator return * values in older Firefox/SpiderMonkey. In browsers that support ES6 * generators like Chromium 29, just use "return" in your generator * functions. * * @param value the return value for the surrounding generator * @throws ReturnValue exception with the value. * @example * // ES6 style * Q.async(function* () { * var foo = yield getFooPromise(); * var bar = yield getBarPromise(); * return foo + bar; * }) * // Older SpiderMonkey style * Q.async(function () { * var foo = yield getFooPromise(); * var bar = yield getBarPromise(); * Q.return(foo + bar); * }) */ Q["return"] = _return; function _return(value) { throw new QReturnValue(value); } /** * The promised function decorator ensures that any promise arguments * are settled and passed as values (`this` is also settled and passed * as a value). It will also ensure that the result of a function is * always a promise. * * @example * var add = Q.promised(function (a, b) { * return a + b; * }); * add(Q(a), Q(B)); * * @param {function} callback The function to decorate * @returns {function} a function that has been decorated. */ Q.promised = promised; function promised(callback) { return function () { return spread([this, all(arguments)], function (self, args) { return callback.apply(self, args); }); }; } /** * sends a message to a value in a future turn * @param object* the recipient * @param op the name of the message operation, e.g., "when", * @param args further arguments to be forwarded to the operation * @returns result {Promise} a promise for the result of the operation */ Q.dispatch = dispatch; function dispatch(object, op, args) { return Q(object).dispatch(op, args); } Promise.prototype.dispatch = function (op, args) { var self = this; var deferred = defer(); Q.nextTick(function () { self.promiseDispatch(deferred.resolve, op, args); }); return deferred.promise; }; /** * Gets the value of a property in a future turn. * @param object promise or immediate reference for target object * @param name name of property to get * @return promise for the property value */ Q.get = function (object, key) { return Q(object).dispatch("get", [key]); }; Promise.prototype.get = function (key) { return this.dispatch("get", [key]); }; /** * Sets the value of a property in a future turn. * @param object promise or immediate reference for object object * @param name name of property to set * @param value new value of property * @return promise for the return value */ Q.set = function (object, key, value) { return Q(object).dispatch("set", [key, value]); }; Promise.prototype.set = function (key, value) { return this.dispatch("set", [key, value]); }; /** * Deletes a property in a future turn. * @param object promise or immediate reference for target object * @param name name of property to delete * @return promise for the return value */ Q.del = // XXX legacy Q["delete"] = function (object, key) { return Q(object).dispatch("delete", [key]); }; Promise.prototype.del = // XXX legacy Promise.prototype["delete"] = function (key) { return this.dispatch("delete", [key]); }; /** * Invokes a method in a future turn. * @param object promise or immediate reference for target object * @param name name of method to invoke * @param value a value to post, typically an array of * invocation arguments for promises that * are ultimately backed with `resolve` values, * as opposed to those backed with URLs * wherein the posted value can be any * JSON serializable object. * @return promise for the return value */ // bound locally because it is used by other methods Q.mapply = // XXX As proposed by "Redsandro" Q.post = function (object, name, args) { return Q(object).dispatch("post", [name, args]); }; Promise.prototype.mapply = // XXX As proposed by "Redsandro" Promise.prototype.post = function (name, args) { return this.dispatch("post", [name, args]); }; /** * Invokes a method in a future turn. * @param object promise or immediate reference for target object * @param name name of method to invoke * @param ...args array of invocation arguments * @return promise for the return value */ Q.send = // XXX Mark Miller's proposed parlance Q.mcall = // XXX As proposed by "Redsandro" Q.invoke = function (object, name /*...args*/) { return Q(object).dispatch("post", [name, array_slice(arguments, 2)]); }; Promise.prototype.send = // XXX Mark Miller's proposed parlance Promise.prototype.mcall = // XXX As proposed by "Redsandro" Promise.prototype.invoke = function (name /*...args*/) { return this.dispatch("post", [name, array_slice(arguments, 1)]); }; /** * Applies the promised function in a future turn. * @param object promise or immediate reference for target function * @param args array of application arguments */ Q.fapply = function (object, args) { return Q(object).dispatch("apply", [void 0, args]); }; Promise.prototype.fapply = function (args) { return this.dispatch("apply", [void 0, args]); }; /** * Calls the promised function in a future turn. * @param object promise or immediate reference for target function * @param ...args array of application arguments */ Q["try"] = Q.fcall = function (object /* ...args*/) { return Q(object).dispatch("apply", [void 0, array_slice(arguments, 1)]); }; Promise.prototype.fcall = function (/*...args*/) { return this.dispatch("apply", [void 0, array_slice(arguments)]); }; /** * Binds the promised function, transforming return values into a fulfilled * promise and thrown errors into a rejected one. * @param object promise or immediate reference for target function * @param ...args array of application arguments */ Q.fbind = function (object /*...args*/) { var promise = Q(object); var args = array_slice(arguments, 1); return function fbound() { return promise.dispatch("apply", [ this, args.concat(array_slice(arguments)) ]); }; }; Promise.prototype.fbind = function (/*...args*/) { var promise = this; var args = array_slice(arguments); return function fbound() { return promise.dispatch("apply", [ this, args.concat(array_slice(arguments)) ]); }; }; /** * Requests the names of the owned properties of a promised * object in a future turn. * @param object promise or immediate reference for target object * @return promise for the keys of the eventually settled object */ Q.keys = function (object) { return Q(object).dispatch("keys", []); }; Promise.prototype.keys = function () { return this.dispatch("keys", []); }; /** * Turns an array of promises into a promise for an array. If any of * the promises gets rejected, the whole array is rejected immediately. * @param {Array*} an array (or promise for an array) of values (or * promises for values) * @returns a promise for an array of the corresponding values */ // By Mark Miller // http://wiki.ecmascript.org/doku.php?id=strawman:concurrency&rev=1308776521#allfulfilled Q.all = all; function all(promises) { return when(promises, function (promises) { var pendingCount = 0; var deferred = defer(); array_reduce(promises, function (undefined, promise, index) { var snapshot; if ( isPromise(promise) && (snapshot = promise.inspect()).state === "fulfilled" ) { promises[index] = snapshot.value; } else { ++pendingCount; when( promise, function (value) { promises[index] = value; if (--pendingCount === 0) { deferred.resolve(promises); } }, deferred.reject, function (progress) { deferred.notify({ index: index, value: progress }); } ); } }, void 0); if (pendingCount === 0) { deferred.resolve(promises); } return deferred.promise; }); } Promise.prototype.all = function () { return all(this); }; /** * Returns the first resolved promise of an array. Prior rejected promises are * ignored. Rejects only if all promises are rejected. * @param {Array*} an array containing values or promises for values * @returns a promise fulfilled with the value of the first resolved promise, * or a rejected promise if all promises are rejected. */ Q.any = any; function any(promises) { if (promises.length === 0) { return Q.resolve(); } var deferred = Q.defer(); var pendingCount = 0; array_reduce(promises, function(prev, current, index) { var promise = promises[index]; pendingCount++; when(promise, onFulfilled, onRejected, onProgress); function onFulfilled(result) { deferred.resolve(result); } function onRejected() { pendingCount--; if (pendingCount === 0) { deferred.reject(new Error( "Can't get fulfillment value from any promise, all " + "promises were rejected." )); } } function onProgress(progress) { deferred.notify({ index: index, value: progress }); } }, undefined); return deferred.promise; } Promise.prototype.any = function() { return any(this); }; /** * Waits for all promises to be settled, either fulfilled or * rejected. This is distinct from `all` since that would stop * waiting at the first rejection. The promise returned by * `allResolved` will never be rejected. * @param promises a promise for an array (or an array) of promises * (or values) * @return a promise for an array of promises */ Q.allResolved = deprecate(allResolved, "allResolved", "allSettled"); function allResolved(promises) { return when(promises, function (promises) { promises = array_map(promises, Q); return when(all(array_map(promises, function (promise) { return when(promise, noop, noop); })), function () { return promises; }); }); } Promise.prototype.allResolved = function () { return allResolved(this); }; /** * @see Promise#allSettled */ Q.allSettled = allSettled; function allSettled(promises) { return Q(promises).allSettled(); } /** * Turns an array of promises into a promise for an array of their states (as * returned by `inspect`) when they have all settled. * @param {Array[Any*]} values an array (or promise for an array) of values (or * promises for values) * @returns {Array[State]} an array of states for the respective values. */ Promise.prototype.allSettled = function () { return this.then(function (promises) { return all(array_map(promises, function (promise) { promise = Q(promise); function regardless() { return promise.inspect(); } return promise.then(regardless, regardless); })); }); }; /** * Captures the failure of a promise, giving an oportunity to recover * with a callback. If the given promise is fulfilled, the returned * promise is fulfilled. * @param {Any*} promise for something * @param {Function} callback to fulfill the returned promise if the * given promise is rejected * @returns a promise for the return value of the callback */ Q.fail = // XXX legacy Q["catch"] = function (object, rejected) { return Q(object).then(void 0, rejected); }; Promise.prototype.fail = // XXX legacy Promise.prototype["catch"] = function (rejected) { return this.then(void 0, rejected); }; /** * Attaches a listener that can respond to progress notifications from a * promise's originating deferred. This listener receives the exact arguments * passed to ``deferred.notify``. * @param {Any*} promise for something * @param {Function} callback to receive any progress notifications * @returns the given promise, unchanged */ Q.progress = progress; function progress(object, progressed) { return Q(object).then(void 0, void 0, progressed); } Promise.prototype.progress = function (progressed) { return this.then(void 0, void 0, progressed); }; /** * Provides an opportunity to observe the settling of a promise, * regardless of whether the promise is fulfilled or rejected. Forwards * the resolution to the returned promise when the callback is done. * The callback can return a promise to defer completion. * @param {Any*} promise * @param {Function} callback to observe the resolution of the given * promise, takes no arguments. * @returns a promise for the resolution of the given promise when * ``fin`` is done. */ Q.fin = // XXX legacy Q["finally"] = function (object, callback) { return Q(object)["finally"](callback); }; Promise.prototype.fin = // XXX legacy Promise.prototype["finally"] = function (callback) { callback = Q(callback); return this.then(function (value) { return callback.fcall().then(function () { return value; }); }, function (reason) { // TODO attempt to recycle the rejection with "this". return callback.fcall().then(function () { throw reason; }); }); }; /** * Terminates a chain of promises, forcing rejections to be * thrown as exceptions. * @param {Any*} promise at the end of a chain of promises * @returns nothing */ Q.done = function (object, fulfilled, rejected, progress) { return Q(object).done(fulfilled, rejected, progress); }; Promise.prototype.done = function (fulfilled, rejected, progress) { var onUnhandledError = function (error) { // forward to a future turn so that ``when`` // does not catch it and turn it into a rejection. Q.nextTick(function () { makeStackTraceLong(error, promise); if (Q.onerror) { Q.onerror(error); } else { throw error; } }); }; // Avoid unnecessary `nextTick`ing via an unnecessary `when`. var promise = fulfilled || rejected || progress ? this.then(fulfilled, rejected, progress) : this; if (typeof process === "object" && process && process.domain) { onUnhandledError = process.domain.bind(onUnhandledError); } promise.then(void 0, onUnhandledError); }; /** * Causes a promise to be rejected if it does not get fulfilled before * some milliseconds time out. * @param {Any*} promise * @param {Number} milliseconds timeout * @param {Any*} custom error message or Error object (optional) * @returns a promise for the resolution of the given promise if it is * fulfilled before the timeout, otherwise rejected. */ Q.timeout = function (object, ms, error) { return Q(object).timeout(ms, error); }; Promise.prototype.timeout = function (ms, error) { var deferred = defer(); var timeoutId = setTimeout(function () { if (!error || "string" === typeof error) { error = new Error(error || "Timed out after " + ms + " ms"); error.code = "ETIMEDOUT"; } deferred.reject(error); }, ms); this.then(function (value) { clearTimeout(timeoutId); deferred.resolve(value); }, function (exception) { clearTimeout(timeoutId); deferred.reject(exception); }, deferred.notify); return deferred.promise; }; /** * Returns a promise for the given value (or promised value), some * milliseconds after it resolved. Passes rejections immediately. * @param {Any*} promise * @param {Number} milliseconds * @returns a promise for the resolution of the given promise after milliseconds * time has elapsed since the resolution of the given promise. * If the given promise rejects, that is passed immediately. */ Q.delay = function (object, timeout) { if (timeout === void 0) { timeout = object; object = void 0; } return Q(object).delay(timeout); }; Promise.prototype.delay = function (timeout) { return this.then(function (value) { var deferred = defer(); setTimeout(function () { deferred.resolve(value); }, timeout); return deferred.promise; }); }; /** * Passes a continuation to a Node function, which is called with the given * arguments provided as an array, and returns a promise. * * Q.nfapply(FS.readFile, [__filename]) * .then(function (content) { * }) * */ Q.nfapply = function (callback, args) { return Q(callback).nfapply(args); }; Promise.prototype.nfapply = function (args) { var deferred = defer(); var nodeArgs = array_slice(args); nodeArgs.push(deferred.makeNodeResolver()); this.fapply(nodeArgs).fail(deferred.reject); return deferred.promise; }; /** * Passes a continuation to a Node function, which is called with the given * arguments provided individually, and returns a promise. * @example * Q.nfcall(FS.readFile, __filename) * .then(function (content) { * }) * */ Q.nfcall = function (callback /*...args*/) { var args = array_slice(arguments, 1); return Q(callback).nfapply(args); }; Promise.prototype.nfcall = function (/*...args*/) { var nodeArgs = array_slice(arguments); var deferred = defer(); nodeArgs.push(deferred.makeNodeResolver()); this.fapply(nodeArgs).fail(deferred.reject); return deferred.promise; }; /** * Wraps a NodeJS continuation passing function and returns an equivalent * version that returns a promise. * @example * Q.nfbind(FS.readFile, __filename)("utf-8") * .then(console.log) * .done() */ Q.nfbind = Q.denodeify = function (callback /*...args*/) { var baseArgs = array_slice(arguments, 1); return function () { var nodeArgs = baseArgs.concat(array_slice(arguments)); var deferred = defer(); nodeArgs.push(deferred.makeNodeResolver()); Q(callback).fapply(nodeArgs).fail(deferred.reject); return deferred.promise; }; }; Promise.prototype.nfbind = Promise.prototype.denodeify = function (/*...args*/) { var args = array_slice(arguments); args.unshift(this); return Q.denodeify.apply(void 0, args); }; Q.nbind = function (callback, thisp /*...args*/) { var baseArgs = array_slice(arguments, 2); return function () { var nodeArgs = baseArgs.concat(array_slice(arguments)); var deferred = defer(); nodeArgs.push(deferred.makeNodeResolver()); function bound() { return callback.apply(thisp, arguments); } Q(bound).fapply(nodeArgs).fail(deferred.reject); return deferred.promise; }; }; Promise.prototype.nbind = function (/*thisp, ...args*/) { var args = array_slice(arguments, 0); args.unshift(this); return Q.nbind.apply(void 0, args); }; /** * Calls a method of a Node-style object that accepts a Node-style * callback with a given array of arguments, plus a provided callback. * @param object an object that has the named method * @param {String} name name of the method of object * @param {Array} args arguments to pass to the method; the callback * will be provided by Q and appended to these arguments. * @returns a promise for the value or error */ Q.nmapply = // XXX As proposed by "Redsandro" Q.npost = function (object, name, args) { return Q(object).npost(name, args); }; Promise.prototype.nmapply = // XXX As proposed by "Redsandro" Promise.prototype.npost = function (name, args) { var nodeArgs = array_slice(args || []); var deferred = defer(); nodeArgs.push(deferred.makeNodeResolver()); this.dispatch("post", [name, nodeArgs]).fail(deferred.reject); return deferred.promise; }; /** * Calls a method of a Node-style object that accepts a Node-style * callback, forwarding the given variadic arguments, plus a provided * callback argument. * @param object an object that has the named method * @param {String} name name of the method of object * @param ...args arguments to pass to the method; the callback will * be provided by Q and appended to these arguments. * @returns a promise for the value or error */ Q.nsend = // XXX Based on Mark Miller's proposed "send" Q.nmcall = // XXX Based on "Redsandro's" proposal Q.ninvoke = function (object, name /*...args*/) { var nodeArgs = array_slice(arguments, 2); var deferred = defer(); nodeArgs.push(deferred.makeNodeResolver()); Q(object).dispatch("post", [name, nodeArgs]).fail(deferred.reject); return deferred.promise; }; Promise.prototype.nsend = // XXX Based on Mark Miller's proposed "send" Promise.prototype.nmcall = // XXX Based on "Redsandro's" proposal Promise.prototype.ninvoke = function (name /*...args*/) { var nodeArgs = array_slice(arguments, 1); var deferred = defer(); nodeArgs.push(deferred.makeNodeResolver()); this.dispatch("post", [name, nodeArgs]).fail(deferred.reject); return deferred.promise; }; /** * If a function would like to support both Node continuation-passing-style and * promise-returning-style, it can end its internal promise chain with * `nodeify(nodeback)`, forwarding the optional nodeback argument. If the user * elects to use a nodeback, the result will be sent there. If they do not * pass a nodeback, they will receive the result promise. * @param object a result (or a promise for a result) * @param {Function} nodeback a Node.js-style callback * @returns either the promise or nothing */ Q.nodeify = nodeify; function nodeify(object, nodeback) { return Q(object).nodeify(nodeback); } Promise.prototype.nodeify = function (nodeback) { if (nodeback) { this.then(function (value) { Q.nextTick(function () { nodeback(null, value); }); }, function (error) { Q.nextTick(function () { nodeback(error); }); }); } else { return this; } }; // All code before this point will be filtered from stack traces. var qEndingLine = captureLine(); return Q; }); },{"__browserify_process":1}],3:[function(require,module,exports){ module.exports = function(subkit, subscriptions, poll){ 'use strict'; return function(){ return { list: function(callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/events/streams'; subkit.httpRequest.get(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, log: function(stream, callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/events/log/' + stream; subkit.httpRequest.get(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, remove: function(stream, callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/events/log/' + stream; subkit.httpRequest.del(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status!==202 && status!==204) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, emit: function(stream, payload, persistent, metadata, callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/events/emit/' + stream; var msg = JSON.parse(JSON.stringify(subkit.options)); msg.data = payload; if(persistent) msg.headers['X-Subkit-Event-Persistent'] = true; if(metadata) msg.headers['X-Subkit-Event-Metadata'] = JSON.stringify(metadata); subkit.httpRequest.post(url, msg, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status !== 201 && status !== 202) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, on: function(stream, callback) { stream = stream.replace('/', '_'); subscriptions[stream] = poll(stream, callback); return { off: function(){ delete subscriptions[stream]; if(subscriptions[stream]) subscriptions[stream]().abort(); }, emit: function(value, callback){ subkit.events.emit(stream, value, callback); } }; }, off: function(stream){ if(subscriptions[stream]) subscriptions[stream]().abort(); delete subscriptions[stream]; return false; } }; }; }; },{}],4:[function(require,module,exports){ module.exports = function(subkit){ 'use strict'; return function(){ return { login: function(callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/login'; subkit.httpRequest.authBasic(subkit.options.username, subkit.options.password); subkit.httpRequest.post(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200) deferred.reject(new Error(result.json().message)); else { subkit.options.apiKey = result.json().api.apiKey; deferred.resolve({ apiKey: subkit.options.apiKey, username: subkit.options.username, password: subkit.options.password, baseUrl: subkit.baseUrl }); } }); return deferred.promise.nodeify(callback); }, import: function(file, callback){ var deferred = subkit.$q.defer(); var msg = JSON.parse(JSON.stringify(subkit.options)); msg.headers = { 'Content-Type': 'application/octed-stream' }; msg.data = file; var url = subkit.baseUrl + '/manage/import'; subkit.httpRequest.post(url, msg, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 201) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, export: function(callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/export'; subkit.httpRequest.get(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200) deferred.reject(new Error(result.json().message)); else deferred.resolve('data:application/octet-stream,' + result.text()); }); return deferred.promise.nodeify(callback); }, backups:{ list:function(callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/savepoints'; subkit.httpRequest.get(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, backup:function(callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/backup'; subkit.httpRequest.post(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 201) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, restore:function(name, callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/restore/' + name; subkit.httpRequest.put(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status !== 202) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, uploadRestore: function(file, callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/restore/' + file.name; var msg = JSON.parse(JSON.stringify(subkit.options)); msg.headers['Content-Type'] = 'application/octed-stream'; msg['data'] = file; subkit.httpRequest.put(url, msg, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status !== 202) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); } }, password: { set: function(oldPassword, newPassword, verifyPassword, callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/password/action/reset'; var msg = JSON.parse(JSON.stringify(subkit.options)); msg.data = { password: oldPassword, newPassword: newPassword, newPasswordValidation: verifyPassword }; subkit.httpRequest.put(url, msg, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status !== 202) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); } }, user: { set: function(username, callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/user'; var msg = JSON.parse(JSON.stringify(subkit.options)); msg.data = { username: username }; subkit.httpRequest.put(url, msg, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status !== 202) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); } }, apikey: { reset: function(callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/apikey/action/reset'; subkit.httpRequest.put(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status !== 202) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); } }, certificate:{ get: function(callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/certificate'; subkit.httpRequest.get(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, set: function(certificate, callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/certificate/action/change'; var msg = JSON.parse(JSON.stringify(subkit.options)); msg.data = certificate; subkit.httpRequest.put(url, msg, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status !== 201 && status !== 202) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); } }, status: { get: function(callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/os'; subkit.httpRequest.get(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, kill: function(callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/kill'; subkit.httpRequest.put(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status!==202 && status!==204) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, update: function(callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/update'; subkit.httpRequest.put(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status!==202 && status!==204) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); } }, plugins: { list: function(callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/plugins'; subkit.httpRequest.get(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, install: function(name,callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/plugins/' + name; subkit.httpRequest.post(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status !== 201 && status !== 202) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, uploadInstall: function(file, callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/plugins/' + file.name; var msg = JSON.parse(JSON.stringify(subkit.options)); msg.headers['Content-Type'] = 'application/octed-stream'; msg['data'] = file; subkit.httpRequest.post(url, msg, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status !== 201 && status !== 202) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, update: function(name,callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/plugins/' + name; subkit.httpRequest.post(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status!==202 && status!==204) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, uninstall: function(name,callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/plugins/' + name; subkit.httpRequest.del(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status!==202 && status!==204) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); } }, permissions:{ roles: function(callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/permissions/identities'; subkit.httpRequest.get(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, list: function(identity, callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/permissions/' + identity; subkit.httpRequest.get(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, set: function(key, callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/permissions/' + encodeURIComponent(key); subkit.httpRequest.post(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status !== 201 && status !== 202) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, remove: function(key, callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/permissions/' + encodeURIComponent(key); subkit.httpRequest.del(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status!==202 && status!==204) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, grantInsert: function(key, identity, callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/permissions/' + encodeURIComponent(key) + '/action/grantinsert/' + identity; subkit.httpRequest.put(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status !== 202) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, grantUpdate: function(key, identity, callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/permissions/' + encodeURIComponent(key) + '/action/grantupdate/' + identity; subkit.httpRequest.put(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status !== 202) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, grantDelete: function(key, identity, callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/permissions/' + encodeURIComponent(key) + '/action/grantdelete/' + identity; subkit.httpRequest.put(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status !== 202) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, grantRead: function(key, identity, callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/permissions/' + encodeURIComponent(key) + '/action/grantread/' + identity; subkit.httpRequest.put(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status !== 202) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, revokeInsert: function(key, identity, callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/permissions/' + encodeURIComponent(key) + '/action/revokeinsert/' + identity; subkit.httpRequest.put(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status !== 202) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, revokeUpdate: function(key, identity, callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/permissions/' + encodeURIComponent(key) + '/action/revokeupdate/' + identity; subkit.httpRequest.put(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status !== 202) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, revokeDelete: function(key, identity, callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/permissions/' + encodeURIComponent(key) + '/action/revokedelete/' + identity; subkit.httpRequest.put(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status !== 202) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, revokeRead: function(key, identity, callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/permissions/' + encodeURIComponent(key) + '/action/revokeread/' + identity; subkit.httpRequest.put(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status !== 202) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); } } }; }; }; },{}],5:[function(require,module,exports){ module.exports = function(subkit, subscriptions, poll){ 'use strict'; return function(store){ var _prepareUrl = function(key){ if(store && !key) return subkit.baseUrl + '/stores/' + store; if(store && key) return subkit.baseUrl + '/stores/' + store + '/' + key; if(!store && key && key.indexOf('!') !== -1) { key = key.replace(/^[a-zA-z0-9]\/\//, '!'); return subkit.baseUrl + '/stores/' + key; } if(!store && key) return subkit.baseUrl + '/stores/' + key; return subkit.baseUrl + '/stores'; }; var _prepareParams = function(url, params){ var queryString = ''; for(var key in params){ if(key === 'where') { var jsonFilter = JSON.stringify(params[key]); queryString += '&where=' + jsonFilter; } else { queryString += '&' + key + '=' + params[key]; } } queryString = queryString.substring(1, queryString.length); return url + '?' + queryString; }; var ref = { key: function(){ return Subkit.UUID(); }, import: function(file, callback){ var deferred = subkit.$q.defer(); var msg = JSON.parse(JSON.stringify(subkit.options)); msg.headers = { 'Content-Type': 'application/octed-stream', apiKey: config.apiKey }; msg.data = file; var url = subkit.baseUrl + '/manage/import/' + store; subkit.httpRequest.post(url, msg, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status!==201 && status!==202) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, export: function(callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/manage/export/' + store; subkit.httpRequest.get(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200) deferred.reject(new Error(result.json().message)); else deferred.resolve('data:application/octet-stream,' + result.text()); }); return deferred.promise.nodeify(callback); }, add: function(key, value, callback){ var deferred = subkit.$q.defer(); key = arguments[0]; value = arguments[1]; if(arguments.length === 1 && key instanceof Object){ value = key; key = Subkit.UUID(); } var url = _prepareUrl(key); var msg = JSON.parse(JSON.stringify(subkit.options)); msg.data = value; subkit.httpRequest.post(url, msg, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status!==201) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, set: function(key, value, version, callback){ if(typeof version === 'function') { callback = version; version = undefined; } var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/stores/' + store + '/' + key; var msg = JSON.parse(JSON.stringify(subkit.options)); msg.data = value; if(version) msg.headers['If-Match'] = version; subkit.httpRequest.put(url, msg, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status!==202) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, get: function(key, callback){ var deferred = subkit.$q.defer(); subkit.httpRequest.get(_prepareUrl(key), subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, find: function(query, callback){ var url = _prepareUrl(query.key); url = _prepareParams(url, query); var deferred = subkit.$q.defer(); subkit.httpRequest.get(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, remove: function(key, version, callback){ if(typeof version === 'function') { callback = version; version = undefined; } var deferred = subkit.$q.defer(); var msg = JSON.parse(JSON.stringify(subkit.options)); if(version) msg.headers['If-Match'] = version; subkit.httpRequest.del(_prepareUrl(key), msg, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status!==202 && status!==204) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, log: function(callback){ var deferred = subkit.$q.defer(); subkit.httpRequest.get('', subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, on: function(callback){ if(subscriptions[store]) subscriptions[store]().abort(); subscriptions[store] = poll(store, callback); return true; }, off: function(){ if(subscriptions[store]) subscriptions[store]().abort(); delete subscriptions[store]; return false; } }; return ref; }; }; },{}],6:[function(require,module,exports){ module.exports = function(subkit){ 'use strict'; return function(){ return { set: function(task, callback){ var deferred = subkit.$q.defer(); var msg = JSON.parse(JSON.stringify(subkit.options)); msg.data = task; var url = subkit.baseUrl + '/tasks/' + task.name; subkit.httpRequest.put(url, msg, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status !== 201 && status!==202) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, get: function(taskName, callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/tasks/' + taskName; subkit.httpRequest.get(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, remove: function(taskName, callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/tasks/' + taskName; subkit.httpRequest.del(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200 && status!==202 && status!==204) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, list: function(callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/tasks'; subkit.httpRequest.get(url, subkit.options, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); }, runDebug: function(taskName, value, callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/tasks/api/' + taskName; var msg = JSON.parse(JSON.stringify(subkit.options)); msg.data = value; subkit.httpRequest.get(url, msg, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200) deferred.reject(new Error(result.json().message)); else deferred.resolve({ result: result.json(), raw: result.text(), headers: result.headers(), log: result.log() }); }); return deferred.promise.nodeify(callback); }, run: function(taskName, value, callback){ var deferred = subkit.$q.defer(); var url = subkit.baseUrl + '/tasks/action/run/' + taskName; var msg = JSON.parse(JSON.stringify(subkit.options)); msg.data = value; subkit.httpRequest.get(url, msg, function(status, result){ if (status === 0) deferred.reject(new Error('No network connection.')); else if (status !== 200) deferred.reject(new Error(result.json().message)); else deferred.resolve(result.json()); }); return deferred.promise.nodeify(callback); } }; }; }; },{}],7:[function(require,module,exports){ /** @module Subkit */ /** * Subkit * @param {object} config - A Subkit configuration */ var Subkit = function (config){ 'use strict'; var self = this; var subscriptions = {}; self.clientId = config.clientId || initClientId(); self.baseUrl = config.baseUrl || ((window.location.origin.indexOf('http') !== -1) ? window.location.origin : 'https://localhost:8080'); self.options = { apiKey: config.apiKey || '', username: config.username || '', password: config.password || '', headers : { 'Content-Type': 'application/json' } }; self.httpRequest = { authBasic: function (username, password) { self.httpRequest.headers({}); ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password); }, connect: function (url, options, callback) { return ajax('CONNECT', url, options, callback); }, del: function (url, options, callback) { return ajax('DELETE', url, options, callback); }, get: function (url, options, callback) { return ajax('GET', url, options, callback); }, head: function (url, options, callback) { return ajax('HEAD', url, options, callback); }, headers: function (headers) { ajax.headers = headers || {}; }, isAllowed: function (url, verb, callback) { this.options(url, function (status, data) { callback(data.text().indexOf(verb) !== -1); }); }, options: function (url, options, callback) { return ajax('OPTIONS', url, options, callback); }, patch: function (url, options, callback) { return ajax('PATCH', url, options, callback); }, post: function (url, options, callback) { return ajax('POST', url, options, callback); }, put: function (url, options, callback) { return ajax('PUT', url, options, callback); }, trace: function (url, options, callback) { return ajax('TRACE', url, options, callback); } }; self.$q = require('q'); self.manage = require('./lib/manage')(self); self.tasks = require('./lib/tasks')(self); self.stores = require('./lib/stores')(self, subscriptions, poll); self.events = require('./lib/events')(self, subscriptions, poll); function getXhr(callback) { if (window.XMLHttpRequest) { return callback(null, new XMLHttpRequest()); } else if (window.ActiveXObject) { try { return callback(null, new ActiveXObject('Msxml2.XMLHTTP')); } catch (e) { return callback(null, new ActiveXObject('Microsoft.XMLHTTP')); } } return callback(new Error()); } function encodeUsingUrlEncoding(data) { if(typeof data === 'string') { return data; } var result = []; for(var dataItem in data) { if(data.hasOwnProperty(dataItem)) { result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem])); } } return result.join('&'); } function utf8(text) { text = text.replace(/\r\n/g, '\n'); var result = ''; for(var i = 0; i < text.length; i++) { var c = text.charCodeAt(i); if(c < 128) { result += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { result += String.fromCharCode((c >> 6) | 192); result += String.fromCharCode((c & 63) | 128); } else { result += String.fromCharCode((c >> 12) | 224); result += String.fromCharCode(((c >> 6) & 63) | 128); result += String.fromCharCode((c & 63) | 128); } } return result; } function base64(text) { var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; text = utf8(text); var result = '', chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0; do { chr1 = text.charCodeAt(i++); chr2 = text.charCodeAt(i++); chr3 = text.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if(isNaN(chr2)) { enc3 = enc4 = 64; } else if(isNaN(chr3)) { enc4 = 64; } result += keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); chr1 = chr2 = chr3 = ''; enc1 = enc2 = enc3 = enc4 = ''; } while(i < text.length); return result; } function mergeHeaders() { var result = arguments[0]; for(var i = 1; i < arguments.length; i++) { var currentHeaders = arguments[i]; for(var header in currentHeaders) { if(currentHeaders.hasOwnProperty(header)) { result[header] = currentHeaders[header]; } } } return result; } function ajax(method, url, options, callback) { if(typeof options === 'function') { callback = options; options = {}; } options.cache = options.cache || true; options.headers = options.headers || {}; options.jsonp = options.jsonp || false; var headers = mergeHeaders({ 'Accept': '*/*', 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', 'X-Auth-Token': options.apiKey }, ajax.headers, options.headers); var payload; if(options.data) { if ((method === 'GET') && (headers['Content-Type'] === 'application/json')) { payload = encodeUsingUrlEncoding(options.data); } else if (headers['Content-Type'] === 'application/json') { payload = JSON.stringify(options.data); } else if(headers['Content-Type'].indexOf('application/octed-stream') !== -1){ payload = options.data; } else { payload = encodeUsingUrlEncoding(options.data); } } if(method === 'GET') { var queryString = []; if(payload) { queryString.push(payload); payload = null; } if(!options.cache) { queryString.push('_=' + (new Date()).getTime()); } if(options.jsonp) { queryString.push('callback=' + options.jsonp); queryString.push('jsonp=' + options.jsonp); } queryString = '?' + queryString.join('&'); url += queryString !== '?' ? queryString : ''; if(options.jsonp) { var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = url; head.appendChild(script); return; } } var xhrRef = null; getXhr(function (err, xhr) { xhrRef = xhr; if(err) return callback(err); xhr.open(method, url, options.async || true); for(var header in headers) { if(headers.hasOwnProperty(header)) { xhr.setRequestHeader(header, headers[header]); } } xhr.timeout = 240000; xhr.ontimeout = function (){ callback(0, { text: function () { return 'Connection timeout'; }, json: function(){ return {message: 'Connection timeout'} } }); } xhr.onerror = function(){ callback(xhr.status, { text: function () { return xhr.statusText; }, json: function(){ return {message: xhr.statusText} } }); }; xhr.onreadystatechange = function () { if(xhr.readyState === 4 && xhr.status !== 0) { if(!callback) return; var data = xhr.responseText || ''; callback(xhr.status, { text: function () { return data; }, json: function () { if(data) return JSON.parse(data); return {}; }, headers: function(){ return xhr.getAllResponseHeaders(); }, log: function(){ return xhr.getResponseHeader('subkit-log'); } }); } }; xhr.send(payload); }); return xhrRef; } function initClientId(){ var clientId = window.sessionStorage.getItem('clientId'); if(!clientId) { clientId = Subkit.UUID(); window.sessionStorage.setItem('clientId', clientId); } return clientId; } function poll(stream, callback) { var subscribeUrl = self.baseUrl + '/events/bind/' + stream; var request = null; var count = 1; (function _pollRef(){ request = self.httpRequest.get(subscribeUrl, self.options, function(status, result){ if(status !== 200) { if(subscriptions[stream]){ callback({message: 'subscription error - retry'}); setTimeout(function(){_pollRef(stream, callback);},300*count++); } }else{ count = 1; result.json().forEach(function(item){ callback(null, item); }); if(subscriptions[stream]) _pollRef(stream, callback); } }); })(); return function(){ return request; }; } }; Subkit.UUID = function () { // http://www.ietf.org/rfc/rfc4122.txt var s = []; var hexDigits = '0123456789abcdef'; for (var i = 0; i < 36; i++) { s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1); } s[14] = '4'; // bits 12-15 of the time_hi_and_version field to 0010 s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01 s[8] = s[13] = s[18] = s[23] = '-'; var uuid = s.join(''); return uuid; }; module.exports = Subkit },{"./lib/events":3,"./lib/manage":4,"./lib/stores":5,"./lib/tasks":6,"q":2}]},{},[7]) (7) }); ;
/*! * sweetalert2 v3.3.4 * Released under the MIT License. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.Sweetalert2 = factory()); }(this, function () { 'use strict'; var swalPrefix = 'swal2-'; var prefix = function(items) { var result = {}; for (var i in items) { result[items[i]] = swalPrefix + items[i]; } return result; }; var swalClasses = prefix([ 'container', 'modal', 'overlay', 'close', 'content', 'spacer', 'confirm', 'cancel', 'icon', 'image', 'input', 'select', 'radio', 'checkbox', 'textarea', 'validationerror' ]); var iconTypes = prefix([ 'success', 'warning', 'info', 'question', 'error' ]); var defaultParams = { title: '', text: '', html: '', type: null, animation: true, allowOutsideClick: true, allowEscapeKey: true, showConfirmButton: true, showCancelButton: false, preConfirm: null, confirmButtonText: 'OK', confirmButtonColor: '#3085d6', confirmButtonClass: null, cancelButtonText: 'Cancel', cancelButtonColor: '#aaa', cancelButtonClass: null, buttonsStyling: true, reverseButtons: false, showCloseButton: false, showLoaderOnConfirm: false, imageUrl: null, imageWidth: null, imageHeight: null, imageClass: null, timer: null, width: 500, padding: 20, background: '#fff', input: null, // 'text' | 'email' | 'password' | 'select' | 'radio' | 'checkbox' | 'textarea' inputPlaceholder: '', inputValue: '', inputOptions: {}, inputAutoTrim: true, inputClass: null, inputAttributes: {}, inputValidator: null }; var sweetHTML = '<div class="' + swalClasses.overlay + '" tabIndex="-1"></div>' + '<div class="' + swalClasses.modal + '" style="display: none" tabIndex="-1">' + '<div class="' + swalClasses.icon + ' ' + iconTypes.error + '">' + '<span class="x-mark"><span class="line left"></span><span class="line right"></span></span>' + '</div>' + '<div class="' + swalClasses.icon + ' ' + iconTypes.question + '">?</div>' + '<div class="' + swalClasses.icon + ' ' + iconTypes.warning + '">!</div>' + '<div class="' + swalClasses.icon + ' ' + iconTypes.info + '">i</div>' + '<div class="' + swalClasses.icon + ' ' + iconTypes.success + '">' + '<span class="line tip"></span> <span class="line long"></span>' + '<div class="placeholder"></div> <div class="fix"></div>' + '</div>' + '<img class="' + swalClasses.image + '">' + '<h2></h2>' + '<div class="' + swalClasses.content + '"></div>' + '<input class="' + swalClasses.input + '">' + '<select class="' + swalClasses.select + '"></select>' + '<div class="' + swalClasses.radio + '"></div>' + '<label for="' + swalClasses.checkbox + '" class="' + swalClasses.checkbox + '">' + '<input type="checkbox" id="' + swalClasses.checkbox + '">' + '</label>' + '<textarea class="' + swalClasses.textarea + '"></textarea>' + '<div class="' + swalClasses.validationerror + '"></div>' + '<hr class="' + swalClasses.spacer + '">' + '<button class="' + swalClasses.confirm + '">OK</button>' + '<button class="' + swalClasses.cancel + '">Cancel</button>' + '<span class="' + swalClasses.close + '">&times;</span>' + '</div>'; var extend = function(a, b) { for (var key in b) { if (b.hasOwnProperty(key)) { a[key] = b[key]; } } return a; }; /* * Set hover, active and focus-states for buttons (source: http://www.sitepoint.com/javascript-generate-lighter-darker-color) */ var colorLuminance = function(hex, lum) { // Validate hex string hex = String(hex).replace(/[^0-9a-f]/gi, ''); if (hex.length < 6) { hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]; } lum = lum || 0; // Convert to decimal and change luminosity var rgb = '#'; for (var i = 0; i < 3; i++) { var c = parseInt(hex.substr(i * 2, 2), 16); c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16); rgb += ('00' + c).substr(c.length); } return rgb; }; var mediaqueryId = swalPrefix + 'mediaquery'; // Remember state in cases where opening and handling a modal will fiddle with it. var states = { previousDocumentClick: null, previousWindowKeyDown: null, previousActiveElement: null }; /* * Manipulate DOM */ var elementByClass = function(className) { return document.querySelector('.' + className); }; var getModal = function() { return elementByClass(swalClasses.modal); }; var getOverlay = function() { return elementByClass(swalClasses.overlay); }; var hasClass = function(elem, className) { return new RegExp(' ' + className + ' ').test(' ' + elem.className + ' '); }; var focusInput = function(input) { input.focus(); // http://stackoverflow.com/a/2345915/1331425 var val = input.value; input.value = ''; input.value = val; }; var addClass = function(elem, className) { if (className && !hasClass(elem, className)) { elem.className += ' ' + className; } }; var removeClass = function(elem, className) { var newClass = ' ' + elem.className.replace(/[\t\r\n]/g, ' ') + ' '; if (hasClass(elem, className)) { while (newClass.indexOf(' ' + className + ' ') >= 0) { newClass = newClass.replace(' ' + className + ' ', ' '); } elem.className = newClass.replace(/^\s+|\s+$/g, ''); } }; var getChildByClass = function(elem, className) { for (var i = 0; i < elem.childNodes.length; i++) { if (elem.childNodes[i].classList.contains(className)) { return elem.childNodes[i]; } } }; var _show = function(elem) { elem.style.opacity = ''; elem.style.display = 'block'; }; var show = function(elems) { if (elems && !elems.length) { return _show(elems); } for (var i = 0; i < elems.length; ++i) { _show(elems[i]); } }; var _hide = function(elem) { elem.style.opacity = ''; elem.style.display = 'none'; }; var hide = function(elems) { if (elems && !elems.length) { return _hide(elems); } for (var i = 0; i < elems.length; ++i) { _hide(elems[i]); } }; var removeStyleProperty = function(elem, property) { if (elem.style.removeProperty) { elem.style.removeProperty(property); } else { elem.style.removeAttribute(property); } }; var getTopMargin = function(elem) { elem.style.left = '-9999px'; elem.style.display = 'block'; var height = elem.clientHeight; var paddingTop = parseInt(getComputedStyle(elem).getPropertyValue('padding-top'), 10); elem.style.left = ''; elem.style.display = 'none'; return ('-' + parseInt(height / 2 + paddingTop, 10) + 'px'); }; var fadeIn = function(elem, interval) { if (+elem.style.opacity < 1) { interval = interval || 16; elem.style.opacity = 0; elem.style.display = 'block'; var last = +new Date(); var tick = function() { var newOpacity = +elem.style.opacity + (new Date() - last) / 100; elem.style.opacity = (newOpacity > 1) ? 1 : newOpacity; last = +new Date(); if (+elem.style.opacity < 1) { setTimeout(tick, interval); } }; tick(); } }; var fadeOut = function(elem, interval) { if (+elem.style.opacity > 0) { interval = interval || 16; var opacity = elem.style.opacity; var last = +new Date(); var tick = function() { var change = new Date() - last; var newOpacity = +elem.style.opacity - change / (opacity * 100); elem.style.opacity = newOpacity; last = +new Date(); if (+elem.style.opacity > 0) { setTimeout(tick, interval); } else { _hide(elem); } }; tick(); } }; var stopEventPropagation = function(e) { // In particular, make sure the space bar doesn't scroll the main window. if (typeof e.stopPropagation === 'function') { e.stopPropagation(); e.preventDefault(); } else if (window.event && window.event.hasOwnProperty('cancelBubble')) { window.event.cancelBubble = true; } }; var animationEndEvent = (function() { var testEl = document.createElement('div'), transEndEventNames = { 'WebkitAnimation': 'webkitAnimationEnd', 'MozAnimation': 'animationend', 'OAnimation': 'oAnimationEnd oanimationend', 'msAnimation': 'MSAnimationEnd', 'animation': 'animationend' }; for (var i in transEndEventNames) { if (transEndEventNames.hasOwnProperty(i) && testEl.style[i] !== undefined) { return transEndEventNames[i]; } } return false; })(); // Reset the page to its previous state var resetPrevState = function() { var modal = getModal(); window.onkeydown = states.previousWindowKeyDown; document.onclick = states.previousDocumentClick; if (states.previousActiveElement) { states.previousActiveElement.focus(); } clearTimeout(modal.timeout); // Remove dynamically created media query var head = document.getElementsByTagName('head')[0]; var mediaquery = document.getElementById(mediaqueryId); if (mediaquery) { head.removeChild(mediaquery); } }; var modalParams = extend({}, defaultParams); /* * Set type, text and actions on modal */ var setParameters = function(params) { var i; var modal = getModal(); // set modal width, padding and margin-left modal.style.width = params.width + 'px'; modal.style.padding = params.padding + 'px'; modal.style.marginLeft = -params.width / 2 + 'px'; modal.style.background = params.background; // add dynamic media query css var head = document.getElementsByTagName('head')[0]; var cssNode = document.createElement('style'); cssNode.type = 'text/css'; cssNode.id = mediaqueryId; var margin = 5; // % var mediaQueryMaxWidth = params.width + parseInt(params.width * (margin/100) * 2, 10); cssNode.innerHTML = '@media screen and (max-width: ' + mediaQueryMaxWidth + 'px) {' + '.' + swalClasses.modal + ' {' + 'width: auto !important;' + 'left: ' + margin + '% !important;' + 'right: ' + margin + '% !important;' + 'margin-left: 0 !important;' + '}' + '}'; head.appendChild(cssNode); var $title = modal.querySelector('h2'); var $content = modal.querySelector('.' + swalClasses.content); var $confirmBtn = modal.querySelector('button.' + swalClasses.confirm); var $cancelBtn = modal.querySelector('button.' + swalClasses.cancel); var $spacer = modal.querySelector('.' + swalClasses.spacer); var $closeButton = modal.querySelector('.' + swalClasses.close); // Title $title.innerHTML = params.title.split('\n').join('<br>'); // Content if (params.text || params.html) { if (typeof params.html === 'object') { $content.innerHTML = ''; if (0 in params.html) { for (i = 0; i in params.html; i++) { $content.appendChild(params.html[i]); } } else { $content.appendChild(params.html); } } else { $content.innerHTML = params.html || (params.text.split('\n').join('<br>')); } show($content); } else { hide($content); } // Close button if (params.showCloseButton) { show($closeButton); } else { hide($closeButton); } // Custom Class modal.className = swalClasses.modal; if (params.customClass) { addClass(modal, params.customClass); } // Icon hide(modal.querySelectorAll('.' + swalClasses.icon)); if (params.type) { var validType = false; for (var iconType in iconTypes) { if (params.type === iconType) { validType = true; break; } } if (!validType) { console.error('Unknown alert type: ' + params.type); return false; } var $icon = modal.querySelector('.' + swalClasses.icon + '.' + iconTypes[params.type]); show($icon); // Animate icon switch (params.type) { case 'success': addClass($icon, 'animate'); addClass($icon.querySelector('.tip'), 'animate-success-tip'); addClass($icon.querySelector('.long'), 'animate-success-long'); break; case 'error': addClass($icon, 'animate-error-icon'); addClass($icon.querySelector('.x-mark'), 'animate-x-mark'); break; case 'warning': addClass($icon, 'pulse-warning'); break; default: break; } } // Custom image var $customImage = modal.querySelector('.' + swalClasses.image); if (params.imageUrl) { $customImage.setAttribute('src', params.imageUrl); show($customImage); if (params.imageWidth) { $customImage.setAttribute('width', params.imageWidth); } if (params.imageHeight) { $customImage.setAttribute('height', params.imageHeight); } if (params.imageClass) { addClass($customImage, params.imageClass); } } else { hide($customImage); } // input, select var inputTypes = ['input', 'select', 'radio', 'checkbox', 'textarea']; var input; for (i = 0; i < inputTypes.length; i++) { var inputClass = swalClasses[inputTypes[i]]; input = getChildByClass(modal, inputClass); // set attributes while (input.attributes.length > 0) { input.removeAttribute(input.attributes[0].name); } for (var attr in params.inputAttributes) { input.setAttribute(attr, params.inputAttributes[attr]); } // set class input.className = inputClass; if (params.inputClass) { addClass(input, params.inputClass); } _hide(input); } switch (params.input) { case 'text': case 'email': case 'password': input = getChildByClass(modal, swalClasses.input); input.value = params.inputValue; input.placeholder = params.inputPlaceholder; input.type = params.input; _show(input); break; case 'select': var select = getChildByClass(modal, swalClasses.select); select.innerHTML = ''; if (params.inputPlaceholder) { var placeholder = document.createElement('option'); placeholder.innerHTML = params.inputPlaceholder; placeholder.value = ''; placeholder.disabled = true; placeholder.selected = true; select.appendChild(placeholder); } for (var optionValue in params.inputOptions) { var option = document.createElement('option'); option.value = optionValue; option.innerHTML = params.inputOptions[optionValue]; if (params.inputValue === optionValue) { option.selected = true; } select.appendChild(option); } _show(select); break; case 'radio': var radio = getChildByClass(modal, swalClasses.radio); radio.innerHTML = ''; for (var radioValue in params.inputOptions) { var id = 1; var radioInput = document.createElement('input'); var radioLabel = document.createElement('label'); var radioLabelSpan = document.createElement('span'); radioInput.type = 'radio'; radioInput.name = swalClasses.radio; radioInput.value = radioValue; radioInput.id = swalClasses.radio + '-' + (id++); if (params.inputValue === radioValue) { radioInput.checked = true; } radioLabelSpan.innerHTML = params.inputOptions[radioValue]; radioLabel.appendChild(radioInput); radioLabel.appendChild(radioLabelSpan); radioLabel.for = radioInput.id; radio.appendChild(radioLabel); } _show(radio); break; case 'checkbox': var checkbox = getChildByClass(modal, swalClasses.checkbox); var checkboxInput = modal.querySelector('#' + swalClasses.checkbox); checkboxInput.value = 1; checkboxInput.checked = Boolean(params.inputValue); var label = checkbox.getElementsByTagName('span'); if (label.length) { checkbox.removeChild(label[0]); } label = document.createElement('span'); label.innerHTML = params.inputPlaceholder; checkbox.appendChild(label); _show(checkbox); break; case 'textarea': var textarea = getChildByClass(modal, swalClasses.textarea); textarea.value = params.inputValue; textarea.placeholder = params.inputPlaceholder; _show(textarea); break; case null: break; default: console.error('Unexpected type of input! Expected "text" or "email" or "password", "select", "checkbox" or "textarea", got ' + typeof arguments[0]); break; } // Cancel button if (params.showCancelButton) { $cancelBtn.style.display = 'inline-block'; } else { hide($cancelBtn); } // Confirm button if (params.showConfirmButton) { removeStyleProperty($confirmBtn, 'display'); } else { hide($confirmBtn); } // Buttons spacer if (!params.showConfirmButton && !params.showCancelButton) { hide($spacer); } else { show($spacer); } // Edit text on cancel and confirm buttons $confirmBtn.innerHTML = params.confirmButtonText; $cancelBtn.innerHTML = params.cancelButtonText; // Set buttons to selected background colors if (params.buttonsStyling) { $confirmBtn.style.backgroundColor = params.confirmButtonColor; $cancelBtn.style.backgroundColor = params.cancelButtonColor; } // Add buttons custom classes $confirmBtn.className = swalClasses.confirm; addClass($confirmBtn, params.confirmButtonClass); $cancelBtn.className = swalClasses.cancel; addClass($cancelBtn, params.cancelButtonClass); // Buttons styling if (params.buttonsStyling) { addClass($confirmBtn, 'styled'); addClass($cancelBtn, 'styled'); } else { removeClass($confirmBtn, 'styled'); removeClass($cancelBtn, 'styled'); $confirmBtn.style.backgroundColor = $confirmBtn.style.borderLeftColor = $confirmBtn.style.borderRightColor = ''; $cancelBtn.style.backgroundColor = $cancelBtn.style.borderLeftColor = $cancelBtn.style.borderRightColor = ''; } // CSS animation if (params.animation === true) { removeClass(modal, 'no-animation'); } else { addClass(modal, 'no-animation'); } }; /* * Animations */ var openModal = function(animation) { var modal = getModal(); if (animation) { fadeIn(getOverlay(), 10); addClass(modal, 'show-swal2'); removeClass(modal, 'hide-swal2'); } else { show(getOverlay()); } show(modal); states.previousActiveElement = document.activeElement; addClass(modal, 'visible'); }; /* * Set 'margin-top'-property on modal based on its computed height */ var fixVerticalPosition = function() { var modal = getModal(); modal.style.marginTop = getTopMargin(modal); }; function modalDependant() { if (arguments[0] === undefined) { console.error('sweetAlert2 expects at least 1 attribute!'); return false; } var params = extend({}, modalParams); switch (typeof arguments[0]) { case 'string': params.title = arguments[0]; params.text = arguments[1] || ''; params.type = arguments[2] || ''; break; case 'object': extend(params, arguments[0]); params.extraParams = arguments[0].extraParams; if (params.input === 'email' && params.inputValidator === null) { params.inputValidator = function(email) { return new Promise(function(resolve, reject) { var emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/; if (emailRegex.test(email)) { resolve(); } else { reject('Invalid email address'); } }); }; } break; default: console.error('Unexpected type of argument! Expected "string" or "object", got ' + typeof arguments[0]); return false; } setParameters(params); fixVerticalPosition(); openModal(params.animation); // Modal interactions var modal = getModal(); return new Promise(function(resolve) { // Close on timer if (params.timer) { modal.timeout = setTimeout(function() { sweetAlert.closeModal(); resolve(undefined); }, params.timer); } // input/select autofocus var getInput = function() { switch (params.input) { case 'select': return getChildByClass(modal, swalClasses.select); case 'radio': return modal.querySelector('.' + swalClasses.radio + ' input:checked') || modal.querySelector('.' + swalClasses.radio + ' input:first-child'); case 'checkbox': return modal.querySelector('#' + swalClasses.checkbox); case 'textarea': return getChildByClass(modal, swalClasses.textarea); default: return getChildByClass(modal, swalClasses.input); } }; var getInputValue = function() { var input = getInput(); switch (params.input) { case 'checkbox': return input.checked ? 1 : 0; case 'radio': return input.checked ? input.value : null; default: return params.inputAutoTrim? input.value.trim() : input.value; } }; if (params.input) { setTimeout(function() { focusInput(getInput()); }, 0); } var confirm = function(value) { if (params.showLoaderOnConfirm) { sweetAlert.showLoading(); } if (params.preConfirm) { params.preConfirm(value, params.extraParams).then( function(preConfirmValue) { resolve(preConfirmValue || value); sweetAlert.closeModal(); }, function() { sweetAlert.hideLoading(); } ); } else { resolve(value); sweetAlert.closeModal(); } }; // Mouse interactions var onButtonEvent = function(event) { var e = event || window.event; var target = e.target || e.srcElement; var targetedConfirm = hasClass(target, swalClasses.confirm); var targetedCancel = hasClass(target, swalClasses.cancel); var modalIsVisible = hasClass(modal, 'visible'); switch (e.type) { case 'mouseover': case 'mouseup': case 'focus': if (params.buttonsStyling) { if (targetedConfirm) { target.style.backgroundColor = colorLuminance(params.confirmButtonColor, -0.1); } else if (targetedCancel) { target.style.backgroundColor = colorLuminance(params.cancelButtonColor, -0.1); } } break; case 'mouseout': case 'blur': if (params.buttonsStyling) { if (targetedConfirm) { target.style.backgroundColor = params.confirmButtonColor; } else if (targetedCancel) { target.style.backgroundColor = params.cancelButtonColor; } } break; case 'mousedown': if (params.buttonsStyling) { if (targetedConfirm) { target.style.backgroundColor = colorLuminance(params.confirmButtonColor, -0.2); } else if (targetedCancel) { target.style.backgroundColor = colorLuminance(params.cancelButtonColor, -0.2); } } break; case 'click': // Clicked 'confirm' if (targetedConfirm && modalIsVisible) { if (params.input) { var inputValue = getInputValue(); if (params.inputValidator) { sweetAlert.disableInput(); params.inputValidator(inputValue, params.extraParams).then( function() { sweetAlert.enableInput(); confirm(inputValue); }, function(error) { sweetAlert.enableInput(); sweetAlert.showValidationError(error); } ); } else { confirm(inputValue); } } else { confirm(true); } // Clicked 'cancel' } else if (targetedCancel && modalIsVisible) { sweetAlert.closeModal(); resolve(false); } break; default: } }; var $buttons = modal.querySelectorAll('button'); var i; for (i = 0; i < $buttons.length; i++) { $buttons[i].onclick = onButtonEvent; $buttons[i].onmouseover = onButtonEvent; $buttons[i].onmouseout = onButtonEvent; $buttons[i].onmousedown = onButtonEvent; } // Remember the current document.onclick event. states.previousDocumentClick = document.onclick; document.onclick = function(event) { var e = event || window.event; var target = e.target || e.srcElement; if (hasClass(target, swalClasses.close) || (target === getOverlay() && params.allowOutsideClick)) { sweetAlert.closeModal(); resolve(undefined); } }; // Keyboard interactions var $confirmButton = modal.querySelector('button.' + swalClasses.confirm); var $cancelButton = modal.querySelector('button.' + swalClasses.cancel); var $modalElements = [$confirmButton, $cancelButton].concat(Array.prototype.slice.call( modal.querySelectorAll('button:not([class^=' + swalPrefix + ']), input:not([type=hidden]), textarea, select') )); for (i = 0; i < $modalElements.length; i++) { $modalElements[i].onfocus = onButtonEvent; $modalElements[i].onblur = onButtonEvent; } // Reverse buttons if neede d if (params.reverseButtons) { $confirmButton.parentNode.insertBefore($cancelButton, $confirmButton); } function setFocus(index, increment) { // search for visible elements and select the next possible match for (var i = 0; i < $modalElements.length; i++) { index = index + increment; // rollover to first item if (index === $modalElements.length) { index = 0; // go to last item } else if (index === -1) { index = $modalElements.length - 1; } // determine if element is visible, the following is borrowed from jqeury $(elem).is(':visible') implementation if ( $modalElements[index].offsetWidth || $modalElements[index].offsetHeight || $modalElements[index].getClientRects().length ) { $modalElements[index].focus(); return; } } } // Focus the first element (input or button) setFocus(-1, 1); function handleKeyDown(event) { var e = event || window.event; var keyCode = e.keyCode || e.which; if ([9, 13, 32, 27].indexOf(keyCode) === -1) { // Don't do work on keys we don't care about. return; } var $targetElement = e.target || e.srcElement; var btnIndex = -1; // Find the button - note, this is a nodelist, not an array. for (var i = 0; i < $modalElements.length; i++) { if ($targetElement === $modalElements[i]) { btnIndex = i; break; } } // TAB if (keyCode === 9) { if (!e.shiftKey) { // Cycle to the next button setFocus(btnIndex, 1); } else { // Cycle to the prev button setFocus(btnIndex, -1); } stopEventPropagation(e); } else { if (keyCode === 13 || keyCode === 32) { if (btnIndex === -1) { // ENTER/SPACE clicked outside of a button. fireClick($confirmButton, e); } } else if (keyCode === 27 && params.allowEscapeKey === true) { sweetAlert.closeModal(); resolve(undefined); } } } states.previousWindowKeyDown = window.onkeydown; window.onkeydown = handleKeyDown; // Loading state if (params.buttonsStyling) { $confirmButton.style.borderLeftColor = params.confirmButtonColor; $confirmButton.style.borderRightColor = params.confirmButtonColor; } sweetAlert.showLoading = sweetAlert.enableLoading = function() { addClass($confirmButton, 'loading'); addClass(modal, 'loading'); $cancelButton.disabled = true; }; sweetAlert.hideLoading = sweetAlert.disableLoading = function() { removeClass($confirmButton, 'loading'); removeClass(modal, 'loading'); $cancelButton.disabled = false; }; sweetAlert.enableButtons = function() { $confirmButton.disabled = false; $cancelButton.disabled = false; }; sweetAlert.disableButtons = function() { $confirmButton.disabled = true; $cancelButton.disabled = true; }; sweetAlert.enableInput = function() { var input = getInput(); if (input.type === 'radio') { var radiosContainer = input.parentNode.parentNode; var radios = radiosContainer.querySelectorAll('input'); for (var i = 0; i < radios.length; i++) { radios[i].disabled = false; } } else { input.disabled = false; } }; sweetAlert.disableInput = function() { var input = getInput(); if (input.type === 'radio') { var radiosContainer = input.parentNode.parentNode; var radios = radiosContainer.querySelectorAll('input'); for (var i = 0; i < radios.length; i++) { radios[i].disabled = true; } } else { input.disabled = true; } }; sweetAlert.showValidationError = function(error) { var $validationError = modal.querySelector('.' + swalClasses.validationerror); $validationError.innerHTML = error; show($validationError); var input = getInput(); focusInput(input); addClass(input, 'error'); }; sweetAlert.resetValidationError = function() { var $validationError = modal.querySelector('.' + swalClasses.validationerror); hide($validationError); var input = getInput(); removeClass(input, 'error'); }; sweetAlert.enableButtons(); sweetAlert.hideLoading(); sweetAlert.resetValidationError(); }); } // SweetAlert function function sweetAlert() { // Copy arguments to the local args variable var args = arguments; var modal = getModal(); if (modal === null) { sweetAlert.init(); modal = getModal(); } if (hasClass(modal, 'visible')) { resetPrevState(); } return modalDependant.apply(this, args); } /* * Global function for chaining sweetAlert modals */ sweetAlert.queue = function(steps) { return new Promise(function(resolve, reject) { (function step(i, callback) { if (i < steps.length) { sweetAlert(steps[i]).then(function(isConfirm) { if (isConfirm) { step(i+1, callback); } else { reject(); } }); } else { resolve(); } })(0); }); }; /* * Global function to close sweetAlert */ sweetAlert.close = sweetAlert.closeModal = function() { var modal = getModal(); removeClass(modal, 'show-swal2'); addClass(modal, 'hide-swal2'); removeClass(modal, 'visible'); // Reset icon animations var $successIcon = modal.querySelector('.' + swalClasses.icon + '.' + iconTypes.success); removeClass($successIcon, 'animate'); removeClass($successIcon.querySelector('.tip'), 'animate-success-tip'); removeClass($successIcon.querySelector('.long'), 'animate-success-long'); var $errorIcon = modal.querySelector('.' + swalClasses.icon + '.' + iconTypes.error); removeClass($errorIcon, 'animate-error-icon'); removeClass($errorIcon.querySelector('.x-mark'), 'animate-x-mark'); var $warningIcon = modal.querySelector('.' + swalClasses.icon + '.' + iconTypes.warning); removeClass($warningIcon, 'pulse-warning'); resetPrevState(); if (animationEndEvent && !hasClass(modal, 'no-animation')) { modal.addEventListener(animationEndEvent, function swalCloseEventFinished() { modal.removeEventListener(animationEndEvent, swalCloseEventFinished); if (hasClass(modal, 'hide-swal2')) { _hide(modal); fadeOut(getOverlay(), 0); } }); } else { _hide(modal); _hide(getOverlay()); } }; /* * Global function to click 'Confirm' button */ sweetAlert.clickConfirm = function() { var modal = getModal(); var $confirmButton = modal.querySelector('button.' + swalClasses.confirm); $confirmButton.click(); }; /* * Global function to click 'Cancel' button */ sweetAlert.clickCancel = function() { var modal = getModal(); var $cancelButton = modal.querySelector('button.' + swalClasses.cancel); $cancelButton.click(); }; /* * Add modal + overlay to DOM */ sweetAlert.init = function() { if (typeof document === 'undefined') { console.log('SweetAlert2 requires document to initialize'); return; } else if (document.getElementsByClassName(swalClasses.container).length) { return; } var sweetWrap = document.createElement('div'); sweetWrap.className = swalClasses.container; sweetWrap.innerHTML = sweetHTML; document.body.appendChild(sweetWrap); var modal = getModal(); var $input = getChildByClass(modal, swalClasses.input); var $select = getChildByClass(modal, swalClasses.select); var $checkbox = modal.querySelector('#' + swalClasses.checkbox); var $textarea = getChildByClass(modal, swalClasses.textarea); $input.oninput = function() { sweetAlert.resetValidationError(); }; $input.onkeyup = function(event) { event.stopPropagation(); if (event.keyCode === 13) { sweetAlert.clickConfirm(); } }; $select.onchange = function() { sweetAlert.resetValidationError(); }; $checkbox.onchange = function() { sweetAlert.resetValidationError(); }; $textarea.onchange = function() { sweetAlert.resetValidationError(); }; }; /** * Set default params for each popup * @param {Object} userParams */ sweetAlert.setDefaults = function(userParams) { if (!userParams) { throw new Error('userParams is required'); } if (typeof userParams !== 'object') { throw new Error('userParams has to be a object'); } extend(modalParams, userParams); }; /** * Reset default params for each popup */ sweetAlert.resetDefaults = function() { modalParams = extend({}, defaultParams); }; sweetAlert.version = '3.3.4'; window.sweetAlert = window.swal = sweetAlert; /* * If library is injected after page has loaded */ (function() { if (document.readyState === 'complete' || document.readyState === 'interactive' && document.body) { sweetAlert.init(); } else { document.addEventListener('DOMContentLoaded', function onDomContentLoaded() { document.removeEventListener('DOMContentLoaded', onDomContentLoaded, false); sweetAlert.init(); }, false); } })(); return sweetAlert; }));
module.exports = { prefix: 'fas', iconName: 'chart-bar', icon: [512, 512, [], "f080", "M500 384c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12H12c-6.6 0-12-5.4-12-12V76c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v308h436zm-308-44v-72c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v72c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm192 0V204c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v136c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 0V140c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v200c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm192 0V108c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v232c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12z"] };
/* Riot v3.0.0-alpha.12, @license MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.riot = global.riot || {}))); }(this, (function (exports) { 'use strict'; var __VIRTUAL_DOM = []; var __TAG_IMPL = {}; var GLOBAL_MIXIN = '__global_mixin'; var RIOT_PREFIX = 'riot-'; var RIOT_TAG_IS = 'data-is'; var T_STRING = 'string'; var T_OBJECT = 'object'; var T_UNDEF = 'undefined'; var T_FUNCTION = 'function'; var XLINK_NS = 'http://www.w3.org/1999/xlink'; var XLINK_REGEX = /^xlink:(\w+)/; var WIN = typeof window === T_UNDEF ? undefined : window; var RE_SPECIAL_TAGS = /^(?:t(?:body|head|foot|[rhd])|caption|col(?:group)?|opt(?:ion|group))$/; var RE_SPECIAL_TAGS_NO_OPTION = /^(?:t(?:body|head|foot|[rhd])|caption|col(?:group)?)$/; var RE_RESERVED_NAMES = /^(?:_(?:item|id|parent)|update|root|(?:un)?mount|mixin|is(?:Mounted|Loop)|tags|parent|opts|trigger|o(?:n|ff|ne))$/; var RE_SVG_TAGS = /^(altGlyph|animate(?:Color)?|circle|clipPath|defs|ellipse|fe(?:Blend|ColorMatrix|ComponentTransfer|Composite|ConvolveMatrix|DiffuseLighting|DisplacementMap|Flood|GaussianBlur|Image|Merge|Morphology|Offset|SpecularLighting|Tile|Turbulence)|filter|font|foreignObject|g(?:lyph)?(?:Ref)?|image|line(?:arGradient)?|ma(?:rker|sk)|missing-glyph|path|pattern|poly(?:gon|line)|radialGradient|rect|stop|svg|switch|symbol|text(?:Path)?|tref|tspan|use)$/; var RE_HTML_ATTRS = /([-\w]+) ?= ?(?:"([^"]*)|'([^']*)|({[^}]*}))/g; var RE_BOOL_ATTRS = /^(?:disabled|checked|readonly|required|allowfullscreen|auto(?:focus|play)|compact|controls|default|formnovalidate|hidden|ismap|itemscope|loop|multiple|muted|no(?:resize|shade|validate|wrap)?|open|reversed|seamless|selected|sortable|truespeed|typemustmatch)$/; var IE_VERSION = (WIN && WIN.document || {}).documentMode | 0; /** * Check whether a DOM node must be considered a part of an svg document * @param { String } name - * @returns { Boolean } - */ function isSVGTag(name) { return RE_SVG_TAGS.test(name) } /** * Check Check if the passed argument is undefined * @param { String } value - * @returns { Boolean } - */ function isBoolAttr(value) { return RE_BOOL_ATTRS.test(value) } /** * Check if passed argument is a function * @param { * } value - * @returns { Boolean } - */ function isFunction(value) { return typeof value === T_FUNCTION || false // avoid IE problems } /** * Check if passed argument is an object, exclude null * NOTE: use isObject(x) && !isArray(x) to excludes arrays. * @param { * } value - * @returns { Boolean } - */ function isObject(value) { return value && typeof value === T_OBJECT // typeof null is 'object' } /** * Check if passed argument is undefined * @param { * } value - * @returns { Boolean } - */ function isUndefined(value) { return typeof value === T_UNDEF } /** * Check if passed argument is a string * @param { * } value - * @returns { Boolean } - */ function isString(value) { return typeof value === T_STRING } /** * Check if passed argument is empty. Different from falsy, because we dont consider 0 or false to be blank * @param { * } value - * @returns { Boolean } - */ function isBlank(value) { return isUndefined(value) || value === null || value === '' } /** * Check if passed argument is a kind of array * @param { * } value - * @returns { Boolean } - */ function isArray(value) { return Array.isArray(value) || value instanceof Array } /** * Check whether object's property could be overridden * @param { Object } obj - source object * @param { String } key - object property * @returns { Boolean } - */ function isWritable(obj, key) { var descriptor = Object.getOwnPropertyDescriptor(obj, key); return isUndefined(obj[key]) || descriptor && descriptor.writable } /** * Check if passed argument is a reserved name * @param { String } value - * @returns { Boolean } - */ function isReservedName(value) { return RE_RESERVED_NAMES.test(value) } var check = Object.freeze({ isSVGTag: isSVGTag, isBoolAttr: isBoolAttr, isFunction: isFunction, isObject: isObject, isUndefined: isUndefined, isString: isString, isBlank: isBlank, isArray: isArray, isWritable: isWritable, isReservedName: isReservedName }); /** * Shorter and fast way to select multiple nodes in the DOM * @param { String } selector - DOM selector * @param { Object } ctx - DOM node where the targets of our search will is located * @returns { Object } dom nodes found */ function $$(selector, ctx) { return (ctx || document).querySelectorAll(selector) } /** * Shorter and fast way to select a single node in the DOM * @param { String } selector - unique dom selector * @param { Object } ctx - DOM node where the target of our search will is located * @returns { Object } dom node found */ function $(selector, ctx) { return (ctx || document).querySelector(selector) } /** * Create a document fragment * @returns { Object } document fragment */ function createFrag() { return document.createDocumentFragment() } /** * Create a document text node * @returns { Object } create a text node to use as placeholder */ function createDOMPlaceholder() { return document.createTextNode('') } /** * Create a generic DOM node * @param { String } name - name of the DOM node we want to create * @param { Boolean } isSvg - should we use a SVG as parent node? * @returns { Object } DOM node just created */ function mkEl(name, isSvg) { return isSvg ? document.createElementNS('http://www.w3.org/2000/svg', 'svg') : document.createElement(name) } /** * Get the outer html of any DOM node SVGs included * @param { Object } el - DOM node to parse * @returns { String } el.outerHTML */ function getOuterHTML(el) { if (el.outerHTML) { return el.outerHTML } // some browsers do not support outerHTML on the SVGs tags else { var container = mkEl('div'); container.appendChild(el.cloneNode(true)); return container.innerHTML } } /** * Set the inner html of any DOM node SVGs included * @param { Object } container - DOM node where we'll inject new html * @param { String } html - html to inject */ function setInnerHTML(container, html) { if (!isUndefined(container.innerHTML)) { container.innerHTML = html; } // some browsers do not support innerHTML on the SVGs tags else { var doc = new DOMParser().parseFromString(html, 'application/xml'); var node = container.ownerDocument.importNode(doc.documentElement, true); container.appendChild(node); } } /** * Remove any DOM attribute from a node * @param { Object } dom - DOM node we want to update * @param { String } name - name of the property we want to remove */ function remAttr(dom, name) { dom.removeAttribute(name); } /** * Get the value of any DOM attribute on a node * @param { Object } dom - DOM node we want to parse * @param { String } name - name of the attribute we want to get * @returns { String | undefined } name of the node attribute whether it exists */ function getAttr(dom, name) { return dom.getAttribute(name) } /** * Set any DOM attribute * @param { Object } dom - DOM node we want to update * @param { String } name - name of the property we want to set * @param { String } val - value of the property we want to set */ function setAttr(dom, name, val) { var xlink = XLINK_REGEX.exec(name); if (xlink && xlink[1]) { dom.setAttributeNS(XLINK_NS, xlink[1], val); } else { dom.setAttribute(name, val); } } /** * Insert safely a tag to fix #1962 #1649 * @param { HTMLElement } root - children container * @param { HTMLElement } curr - node to insert * @param { HTMLElement } next - node that should preceed the current node inserted */ function safeInsert(root, curr, next) { root.insertBefore(curr, next.parentNode && next); } /** * Minimize risk: only zero or one _space_ between attr & value * @param { String } html - html string we want to parse * @param { Function } fn - callback function to apply on any attribute found */ function walkAttrs(html, fn) { if (!html) { return } var m; while (m = RE_HTML_ATTRS.exec(html)) { fn(m[1].toLowerCase(), m[2] || m[3] || m[4]); } } /** * Walk down recursively all the children tags starting dom node * @param { Object } dom - starting node where we will start the recursion * @param { Function } fn - callback to transform the child node just found * @param { Object } context - fn can optionally return an object, which is passed to children */ function walkNodes(dom, fn, context) { if (dom) { var res = fn(dom, context); var next; // stop the recursion if (res === false) { return } dom = dom.firstChild; while (dom) { next = dom.nextSibling; walkNodes(dom, fn, res); dom = next; } } } var dom = Object.freeze({ $$: $$, $: $, createFrag: createFrag, createDOMPlaceholder: createDOMPlaceholder, mkEl: mkEl, getOuterHTML: getOuterHTML, setInnerHTML: setInnerHTML, remAttr: remAttr, getAttr: getAttr, setAttr: setAttr, safeInsert: safeInsert, walkAttrs: walkAttrs, walkNodes: walkNodes }); var styleNode; var cssTextProp; var byName = {}; var remainder = []; // skip the following code on the server if (WIN) { styleNode = (function () { // create a new style element with the correct type var newNode = mkEl('style'); setAttr(newNode, 'type', 'text/css'); // replace any user node or insert the new one into the head var userNode = $('style[type=riot]'); if (userNode) { if (userNode.id) { newNode.id = userNode.id; } userNode.parentNode.replaceChild(newNode, userNode); } else { document.getElementsByTagName('head')[0].appendChild(newNode); } return newNode })(); cssTextProp = styleNode.styleSheet; } /** * Object that will be used to inject and manage the css of every tag instance */ var styleManager = { styleNode: styleNode, /** * Save a tag style to be later injected into DOM * @param { String } css - css string * @param { String } name - if it's passed we will map the css to a tagname */ add: function add(css, name) { if (name) { byName[name] = css; } else { remainder.push(css); } }, /** * Inject all previously saved tag styles into DOM * innerHTML seems slow: http://jsperf.com/riot-insert-style */ inject: function inject() { if (!WIN) { return } var style = Object.keys(byName) .map(function(k) { return byName[k] }) .concat(remainder).join('\n'); if (cssTextProp) { cssTextProp.cssText = style; } else { styleNode.innerHTML = style; } } }; /** * The riot template engine * @version v2.4.2 */ /** * riot.util.brackets * * - `brackets ` - Returns a string or regex based on its parameter * - `brackets.set` - Change the current riot brackets * * @module */ /* global riot */ var brackets = (function (UNDEF) { var REGLOB = 'g', R_MLCOMMS = /\/\*[^*]*\*+(?:[^*\/][^*]*\*+)*\//g, R_STRINGS = /"[^"\\]*(?:\\[\S\s][^"\\]*)*"|'[^'\\]*(?:\\[\S\s][^'\\]*)*'/g, S_QBLOCKS = R_STRINGS.source + '|' + /(?:\breturn\s+|(?:[$\w\)\]]|\+\+|--)\s*(\/)(?![*\/]))/.source + '|' + /\/(?=[^*\/])[^[\/\\]*(?:(?:\[(?:\\.|[^\]\\]*)*\]|\\.)[^[\/\\]*)*?(\/)[gim]*/.source, UNSUPPORTED = RegExp('[\\' + 'x00-\\x1F<>a-zA-Z0-9\'",;\\\\]'), NEED_ESCAPE = /(?=[[\]()*+?.^$|])/g, FINDBRACES = { '(': RegExp('([()])|' + S_QBLOCKS, REGLOB), '[': RegExp('([[\\]])|' + S_QBLOCKS, REGLOB), '{': RegExp('([{}])|' + S_QBLOCKS, REGLOB) }, DEFAULT = '{ }'; var _pairs = [ '{', '}', '{', '}', /{[^}]*}/, /\\([{}])/g, /\\({)|{/g, RegExp('\\\\(})|([[({])|(})|' + S_QBLOCKS, REGLOB), DEFAULT, /^\s*{\^?\s*([$\w]+)(?:\s*,\s*(\S+))?\s+in\s+(\S.*)\s*}/, /(^|[^\\]){=[\S\s]*?}/ ]; var cachedBrackets = UNDEF, _regex, _cache = [], _settings; function _loopback (re) { return re } function _rewrite (re, bp) { if (!bp) { bp = _cache; } return new RegExp( re.source.replace(/{/g, bp[2]).replace(/}/g, bp[3]), re.global ? REGLOB : '' ) } function _create (pair) { if (pair === DEFAULT) { return _pairs } var arr = pair.split(' '); if (arr.length !== 2 || UNSUPPORTED.test(pair)) { throw new Error('Unsupported brackets "' + pair + '"') } arr = arr.concat(pair.replace(NEED_ESCAPE, '\\').split(' ')); arr[4] = _rewrite(arr[1].length > 1 ? /{[\S\s]*?}/ : _pairs[4], arr); arr[5] = _rewrite(pair.length > 3 ? /\\({|})/g : _pairs[5], arr); arr[6] = _rewrite(_pairs[6], arr); arr[7] = RegExp('\\\\(' + arr[3] + ')|([[({])|(' + arr[3] + ')|' + S_QBLOCKS, REGLOB); arr[8] = pair; return arr } function _brackets (reOrIdx) { return reOrIdx instanceof RegExp ? _regex(reOrIdx) : _cache[reOrIdx] } _brackets.split = function split (str, tmpl, _bp) { // istanbul ignore next: _bp is for the compiler if (!_bp) { _bp = _cache; } var parts = [], match, isexpr, start, pos, re = _bp[6]; isexpr = start = re.lastIndex = 0; while ((match = re.exec(str))) { pos = match.index; if (isexpr) { if (match[2]) { re.lastIndex = skipBraces(str, match[2], re.lastIndex); continue } if (!match[3]) { continue } } if (!match[1]) { unescapeStr(str.slice(start, pos)); start = re.lastIndex; re = _bp[6 + (isexpr ^= 1)]; re.lastIndex = start; } } if (str && start < str.length) { unescapeStr(str.slice(start)); } return parts function unescapeStr (s) { if (tmpl || isexpr) { parts.push(s && s.replace(_bp[5], '$1')); } else { parts.push(s); } } function skipBraces (s, ch, ix) { var match, recch = FINDBRACES[ch]; recch.lastIndex = ix; ix = 1; while ((match = recch.exec(s))) { if (match[1] && !(match[1] === ch ? ++ix : --ix)) { break } } return ix ? s.length : recch.lastIndex } }; _brackets.hasExpr = function hasExpr (str) { return _cache[4].test(str) }; _brackets.loopKeys = function loopKeys (expr) { var m = expr.match(_cache[9]); return m ? { key: m[1], pos: m[2], val: _cache[0] + m[3].trim() + _cache[1] } : { val: expr.trim() } }; _brackets.array = function array (pair) { return pair ? _create(pair) : _cache }; function _reset (pair) { if ((pair || (pair = DEFAULT)) !== _cache[8]) { _cache = _create(pair); _regex = pair === DEFAULT ? _loopback : _rewrite; _cache[9] = _regex(_pairs[9]); } cachedBrackets = pair; } function _setSettings (o) { var b; o = o || {}; b = o.brackets; Object.defineProperty(o, 'brackets', { set: _reset, get: function () { return cachedBrackets }, enumerable: true }); _settings = o; _reset(b); } Object.defineProperty(_brackets, 'settings', { set: _setSettings, get: function () { return _settings } }); /* istanbul ignore next: in the browser riot is always in the scope */ _brackets.settings = typeof riot !== 'undefined' && riot.settings || {}; _brackets.set = _reset; _brackets.R_STRINGS = R_STRINGS; _brackets.R_MLCOMMS = R_MLCOMMS; _brackets.S_QBLOCKS = S_QBLOCKS; return _brackets })(); /** * @module tmpl * * tmpl - Root function, returns the template value, render with data * tmpl.hasExpr - Test the existence of a expression inside a string * tmpl.loopKeys - Get the keys for an 'each' loop (used by `_each`) */ var tmpl = (function () { var _cache = {}; function _tmpl (str, data) { if (!str) { return str } return (_cache[str] || (_cache[str] = _create(str))).call(data, _logErr) } _tmpl.haveRaw = brackets.hasRaw; _tmpl.hasExpr = brackets.hasExpr; _tmpl.loopKeys = brackets.loopKeys; // istanbul ignore next _tmpl.clearCache = function () { _cache = {}; }; _tmpl.errorHandler = null; function _logErr (err, ctx) { if (_tmpl.errorHandler) { err.riotData = { tagName: ctx && ctx.root && ctx.root.tagName, _riot_id: ctx && ctx._riot_id //eslint-disable-line camelcase }; _tmpl.errorHandler(err); } } function _create (str) { var expr = _getTmpl(str); if (expr.slice(0, 11) !== 'try{return ') { expr = 'return ' + expr; } return new Function('E', expr + ';') // eslint-disable-line no-new-func } var CH_IDEXPR = String.fromCharCode(0x2057), RE_CSNAME = /^(?:(-?[_A-Za-z\xA0-\xFF][-\w\xA0-\xFF]*)|\u2057(\d+)~):/, RE_QBLOCK = RegExp(brackets.S_QBLOCKS, 'g'), RE_DQUOTE = /\u2057/g, RE_QBMARK = /\u2057(\d+)~/g; function _getTmpl (str) { var qstr = [], expr, parts = brackets.split(str.replace(RE_DQUOTE, '"'), 1); if (parts.length > 2 || parts[0]) { var i, j, list = []; for (i = j = 0; i < parts.length; ++i) { expr = parts[i]; if (expr && (expr = i & 1 ? _parseExpr(expr, 1, qstr) : '"' + expr .replace(/\\/g, '\\\\') .replace(/\r\n?|\n/g, '\\n') .replace(/"/g, '\\"') + '"' )) { list[j++] = expr; } } expr = j < 2 ? list[0] : '[' + list.join(',') + '].join("")'; } else { expr = _parseExpr(parts[1], 0, qstr); } if (qstr[0]) { expr = expr.replace(RE_QBMARK, function (_, pos) { return qstr[pos] .replace(/\r/g, '\\r') .replace(/\n/g, '\\n') }); } return expr } var RE_BREND = { '(': /[()]/g, '[': /[[\]]/g, '{': /[{}]/g }; function _parseExpr (expr, asText, qstr) { expr = expr .replace(RE_QBLOCK, function (s, div) { return s.length > 2 && !div ? CH_IDEXPR + (qstr.push(s) - 1) + '~' : s }) .replace(/\s+/g, ' ').trim() .replace(/\ ?([[\({},?\.:])\ ?/g, '$1'); if (expr) { var list = [], cnt = 0, match; while (expr && (match = expr.match(RE_CSNAME)) && !match.index ) { var key, jsb, re = /,|([[{(])|$/g; expr = RegExp.rightContext; key = match[2] ? qstr[match[2]].slice(1, -1).trim().replace(/\s+/g, ' ') : match[1]; while (jsb = (match = re.exec(expr))[1]) { skipBraces(jsb, re); } jsb = expr.slice(0, match.index); expr = RegExp.rightContext; list[cnt++] = _wrapExpr(jsb, 1, key); } expr = !cnt ? _wrapExpr(expr, asText) : cnt > 1 ? '[' + list.join(',') + '].join(" ").trim()' : list[0]; } return expr function skipBraces (ch, re) { var mm, lv = 1, ir = RE_BREND[ch]; ir.lastIndex = re.lastIndex; while (mm = ir.exec(expr)) { if (mm[0] === ch) { ++lv; } else if (!--lv) { break } } re.lastIndex = lv ? expr.length : ir.lastIndex; } } // istanbul ignore next: not both var // eslint-disable-next-line max-len JS_CONTEXT = '"in this?this:' + (typeof window !== 'object' ? 'global' : 'window') + ').', JS_VARNAME = /[,{][\$\w]+(?=:)|(^ *|[^$\w\.{])(?!(?:typeof|true|false|null|undefined|in|instanceof|is(?:Finite|NaN)|void|NaN|new|Date|RegExp|Math)(?![$\w]))([$_A-Za-z][$\w]*)/g, JS_NOPROPS = /^(?=(\.[$\w]+))\1(?:[^.[(]|$)/; function _wrapExpr (expr, asText, key) { var tb; expr = expr.replace(JS_VARNAME, function (match, p, mvar, pos, s) { if (mvar) { pos = tb ? 0 : pos + match.length; if (mvar !== 'this' && mvar !== 'global' && mvar !== 'window') { match = p + '("' + mvar + JS_CONTEXT + mvar; if (pos) { tb = (s = s[pos]) === '.' || s === '(' || s === '['; } } else if (pos) { tb = !JS_NOPROPS.test(s.slice(pos)); } } return match }); if (tb) { expr = 'try{return ' + expr + '}catch(e){E(e,this)}'; } if (key) { expr = (tb ? 'function(){' + expr + '}.call(this)' : '(' + expr + ')' ) + '?"' + key + '":""'; } else if (asText) { expr = 'function(v){' + (tb ? expr.replace('return ', 'v=') : 'v=(' + expr + ')' ) + ';return v||v===0?v:""}.call(this)'; } return expr } _tmpl.version = brackets.version = 'v2.4.2'; return _tmpl })(); /** * Simple object prototypal inheritance * @param { Object } parent - parent object * @returns { Object } child instance */ function inherit(parent) { return Object.assign ? Object.assign({}, parent) : extend({}, parent) } /** * Specialized function for looping an array-like collection with `each={}` * @param { Array } list - collection of items * @param {Function} fn - callback function * @returns { Array } the array looped */ function each(list, fn) { var len = list ? list.length : 0; for (var i = 0, el; i < len; ++i) { el = list[i]; // return false -> current item was removed by fn during the loop if (fn(el, i) === false) { i--; } } return list } /** * Check whether an array contains an item * @param { Array } array - target array * @param { * } item - item to test * @returns { Boolean } - */ function contains(array, item) { return ~array.indexOf(item) } /** * Convert a string containing dashes to camel case * @param { String } str - input string * @returns { String } my-string -> myString */ function toCamel(str) { return str.replace(/-(\w)/g, function (_, c) { return c.toUpperCase(); }) } /** * Faster String startsWith alternative * @param { String } str - source string * @param { String } value - test string * @returns { Boolean } - */ function startsWith(str, value) { return str.slice(0, value.length) === value } /** * Helper function to set an immutable property * @param { Object } el - object where the new property will be set * @param { String } key - object key where the new property will be stored * @param { * } value - value of the new property * @param { Object } options - set the propery overriding the default options * @returns { Object } - the initial object */ function defineProperty(el, key, value, options) { Object.defineProperty(el, key, extend({ value: value, enumerable: false, writable: false, configurable: true }, options)); return el } /** * Extend any object with other properties * @param { Object } src - source object * @returns { Object } the resulting extended object * * var obj = { foo: 'baz' } * extend(obj, {bar: 'bar', foo: 'bar'}) * console.log(obj) => {bar: 'bar', foo: 'bar'} * */ function extend(src) { var obj, args = arguments; for (var i = 1; i < args.length; ++i) { if (obj = args[i]) { for (var key in obj) { // check if this property of the source object could be overridden if (isWritable(src, key)) { src[key] = obj[key]; } } } } return src } var misc = Object.freeze({ inherit: inherit, each: each, contains: contains, toCamel: toCamel, startsWith: startsWith, defineProperty: defineProperty, extend: extend }); var observable = function(el) { /** * Extend the original object or create a new empty one * @type { Object } */ el = el || {}; /** * Private variables */ var callbacks = {}, slice = Array.prototype.slice; /** * Public Api */ // extend the el object adding the observable methods Object.defineProperties(el, { /** * Listen to the given `event` ands * execute the `callback` each time an event is triggered. * @param { String } event - event id * @param { Function } fn - callback function * @returns { Object } el */ on: { value: function(event, fn) { if (typeof fn == 'function') { (callbacks[event] = callbacks[event] || []).push(fn); } return el }, enumerable: false, writable: false, configurable: false }, /** * Removes the given `event` listeners * @param { String } event - event id * @param { Function } fn - callback function * @returns { Object } el */ off: { value: function(event, fn) { if (event == '*' && !fn) { callbacks = {}; } else { if (fn) { var arr = callbacks[event]; for (var i = 0, cb; cb = arr && arr[i]; ++i) { if (cb == fn) { arr.splice(i--, 1); } } } else { delete callbacks[event]; } } return el }, enumerable: false, writable: false, configurable: false }, /** * Listen to the given `event` and * execute the `callback` at most once * @param { String } event - event id * @param { Function } fn - callback function * @returns { Object } el */ one: { value: function(event, fn) { function on() { el.off(event, on); fn.apply(el, arguments); } return el.on(event, on) }, enumerable: false, writable: false, configurable: false }, /** * Execute all callback functions that listen to * the given `event` * @param { String } event - event id * @returns { Object } el */ trigger: { value: function(event) { var arguments$1 = arguments; // getting the arguments var arglen = arguments.length - 1, args = new Array(arglen), fns, fn, i; for (i = 0; i < arglen; i++) { args[i] = arguments$1[i + 1]; // skip first argument } fns = slice.call(callbacks[event] || [], 0); for (i = 0; fn = fns[i]; ++i) { fn.apply(el, args); if (fns[i] !== fn) { i--; } } if (callbacks['*'] && event != '*') { el.trigger.apply(el, ['*', event].concat(args)); } return el }, enumerable: false, writable: false, configurable: false } }); return el }; var EVENTS_PREFIX_REGEX = /^on/; /** * Trigger DOM events * @param { HTMLElement } dom - dom element target of the event * @param { Function } handler - user function * @param { Object } e - event object */ function handleEvent(dom, handler, e) { var ptag = this._parent, item = this._item; if (!item) { while (ptag && !item) { item = ptag._item; ptag = ptag._parent; } } // override the event properties if (isWritable(e, 'currentTarget')) { e.currentTarget = dom; } if (isWritable(e, 'target')) { e.target = e.srcElement; } if (isWritable(e, 'which')) { e.which = e.charCode || e.keyCode; } e.item = item; handler.call(this, e); if (!e.preventUpdate) { getImmediateCustomParentTag(this).update(); } } /** * Attach an event to a DOM node * @param { String } name - event name * @param { Function } handler - event callback * @param { Object } dom - dom node * @param { Tag } tag - tag instance */ function setEventHandler(name, handler, dom, tag) { var eventName, cb = handleEvent.bind(tag, dom, handler); if (!dom.addEventListener) { dom[name] = cb; return } // avoid to bind twice the same event dom[name] = null; // normalize event name eventName = name.replace(EVENTS_PREFIX_REGEX, ''); // cache the callback directly on the DOM node if (!dom._riotEvents) { dom._riotEvents = {}; } if (dom._riotEvents[name]) { dom.removeEventListener(eventName, dom._riotEvents[name]); } dom._riotEvents[name] = cb; dom.addEventListener(eventName, cb, false); } /** * Update dynamically created riot-tag with changing expressions * @param { Object } expr - expression tag and expression info * @param { Tag } parent - parent for tag creation */ function updateRtag(expr, parent) { var tagName = tmpl(expr.value, parent), conf; if (expr.tag && expr.tagName === tagName) { expr.tag.update(); return } // sync _parent to accommodate changing tagnames if (expr.tag) { var delName = expr.tag.opts.dataIs, tags = expr.tag._parent.tags; setAttr(expr.tag.root, RIOT_TAG_IS, tagName); // update for css arrayishRemove(tags, delName, expr.tag); } expr.impl = __TAG_IMPL[tagName]; conf = {root: expr.dom, parent: parent, hasImpl: true, tagName: tagName}; expr.tag = initChildTag(expr.impl, conf, expr.dom.innerHTML, parent); expr.tagName = tagName; expr.tag.mount(); expr.tag.update(); // parent is the placeholder tag, not the dynamic tag so clean up parent.on('unmount', function () { var delName = expr.tag.opts.dataIs, tags = expr.tag.parent.tags, _tags = expr.tag._parent.tags; arrayishRemove(tags, delName, expr.tag); arrayishRemove(_tags, delName, expr.tag); expr.tag.unmount(); }); } /** * Update on single tag expression * @this Tag * @param { Object } expr - expression logic * @returns { undefined } */ function updateExpression(expr) { var dom = expr.dom, attrName = expr.attr, value = tmpl(expr.expr, this), isValueAttr = attrName === 'value', isVirtual = expr.root && expr.root.tagName === 'VIRTUAL', parent = dom && (expr.parent || dom.parentNode), old; if (expr.bool) { value = value ? attrName : false; } else if (isUndefined(value) || value === null) { value = ''; } if (expr._riot_id) { // if it's a tag if (expr.isMounted) { expr.update(); // if it hasn't been mounted yet, do that now. } else { expr.mount(); if (isVirtual) { var frag = document.createDocumentFragment(); makeVirtual.call(expr, frag); expr.root.parentElement.replaceChild(frag, expr.root); } } return } old = expr.value; expr.value = value; if (expr.update) { expr.update(); return } if (old === value) { return } if (expr.isRtag && value) { return updateRtag(expr, this) } // no change, so nothing more to do if (isValueAttr && dom.value === value) { return } // textarea and text nodes have no attribute name if (!attrName) { // about #815 w/o replace: the browser converts the value to a string, // the comparison by "==" does too, but not in the server value += ''; // test for parent avoids error with invalid assignment to nodeValue if (parent) { // cache the parent node because somehow it will become null on IE // on the next iteration expr.parent = parent; if (parent.tagName === 'TEXTAREA') { parent.value = value; // #1113 if (!IE_VERSION) { dom.nodeValue = value; } // #1625 IE throws here, nodeValue } // will be available on 'updated' else { dom.nodeValue = value; } } return } // remove original attribute remAttr(dom, attrName); // event handler if (isFunction(value)) { setEventHandler(attrName, value, dom, this); // show / hide } else if (/^(show|hide)$/.test(attrName)) { if (attrName === 'hide') { value = !value; } dom.style.display = value ? '' : 'none'; // field value } else if (isValueAttr) { dom.value = value; // <img src="{ expr }"> } else if (startsWith(attrName, RIOT_PREFIX) && attrName !== RIOT_TAG_IS) { if (value) { setAttr(dom, attrName.slice(RIOT_PREFIX.length), value); } } else { // <select> <option selected={true}> </select> if (attrName === 'selected' && parent && /^(SELECT|OPTGROUP)$/.test(parent.nodeName) && value) { parent.value = dom.value; } if (expr.bool) { dom[attrName] = value; if (!value) { return } } if (value === 0 || value && typeof value !== T_OBJECT) { setAttr(dom, attrName, value); } } } /** * Update all the expressions in a Tag instance * @this Tag * @param { Array } expressions - expression that must be re evaluated */ function update$1$1(expressions) { each(expressions, updateExpression.bind(this)); } var IfExpr = { init: function init(dom, parentTag, expr) { remAttr(dom, 'if'); this.parentTag = parentTag; this.expr = expr; this.stub = document.createTextNode(''); this.pristine = dom; var p = dom.parentNode; p.insertBefore(this.stub, dom); p.removeChild(dom); return this }, update: function update$1() { var newValue = tmpl(this.expr, this.parentTag); if (newValue && !this.current) { // insert this.current = this.pristine.cloneNode(true); this.stub.parentNode.insertBefore(this.current, this.stub); this.expressions = []; parseExpressions.apply(this.parentTag, [this.current, this.expressions, true]); } else if (!newValue && this.current) { // remove unmountAll(this.expressions); this.current.parentNode.removeChild(this.current); this.current = null; this.expressions = []; } if (newValue) { update$1$1.call(this.parentTag, this.expressions); } }, unmount: function unmount() { unmountAll(this.expressions || []); delete this.pristine; delete this.parentNode; delete this.stub; } }; var RefExpr = { init: function init(dom, attrName, attrValue, parent) { this.dom = dom; this.attr = attrName; this.rawValue = attrValue; this.parent = parent; this.hasExp = tmpl.hasExpr(attrValue); this.firstRun = true; return this }, update: function update() { var value = this.rawValue; if (this.hasExp) { value = tmpl(this.rawValue, this.parent); } // if nothing changed, we're done if (!this.firstRun && value === this.value) { return } var customParent = this.parent && getImmediateCustomParentTag(this.parent); // if the referenced element is a custom tag, then we set the tag itself, rather than DOM var tagOrDom = this.tag || this.dom; // the name changed, so we need to remove it from the old key (if present) if (!isBlank(this.value) && customParent) { arrayishRemove(customParent.refs, this.value, tagOrDom); } if (isBlank(value)) { // if the value is blank, we remove it remAttr(this.dom, this.attr); } else { // add it to the refs of parent tag (this behavior was changed >=3.0) if (customParent) { arrayishAdd(customParent.refs, value, tagOrDom); } // set the actual DOM attr setAttr(this.dom, this.attr, value); } this.value = value; this.firstRun = false; }, unmount: function unmount() { var tagOrDom = this.tag || this.dom; var customParent = this.parent && getImmediateCustomParentTag(this.parent); if (!isBlank(this.value) && customParent) { arrayishRemove(customParent.refs, this.value, tagOrDom); } delete this.dom; delete this.parent; } }; /** * Convert the item looped into an object used to extend the child tag properties * @param { Object } expr - object containing the keys used to extend the children tags * @param { * } key - value to assign to the new object returned * @param { * } val - value containing the position of the item in the array * @param { Object } base - prototype object for the new item * @returns { Object } - new object containing the values of the original item * * The variables 'key' and 'val' are arbitrary. * They depend on the collection type looped (Array, Object) * and on the expression used on the each tag * */ function mkitem(expr, key, val, base) { var item = base ? Object.create(base) : {}; item[expr.key] = key; if (expr.pos) { item[expr.pos] = val; } return item } /** * Unmount the redundant tags * @param { Array } items - array containing the current items to loop * @param { Array } tags - array containing all the children tags * @param { String } tagName - key used to identify the type of tag * @param { Object } parent - parent tag to remove the child from */ function unmountRedundant(items, tags, tagName, parent) { var i = tags.length, j = items.length, t; while (i > j) { t = tags[--i]; tags.splice(i, 1); t.unmount(); arrayishRemove(parent.tags, tagName, t, true); } } /** * Move the nested custom tags in non custom loop tags * @this Tag * @param { Number } i - current position of the loop tag */ function moveNestedTags(i) { var this$1 = this; each(Object.keys(this.tags), function (tagName) { var tag = this$1.tags[tagName]; if (isArray(tag)) { each(tag, function (t) { moveChildTag.apply(t, [tagName, i]); }); } else { moveChildTag.apply(tag, [tagName, i]); } }); } /** * Move a child tag * @this Tag * @param { HTMLElement } root - dom node containing all the loop children * @param { Tag } nextTag - instance of the next tag preceding the one we want to move * @param { Boolean } isVirtual - is it a virtual tag? */ function move(root, nextTag, isVirtual) { if (isVirtual) { moveVirtual.apply(this, [root, nextTag]); } else { safeInsert(root, this.root, nextTag.root); } } /** * Insert and mount a child tag * @this Tag * @param { HTMLElement } root - dom node containing all the loop children * @param { Tag } nextTag - instance of the next tag preceding the one we want to insert * @param { Boolean } isVirtual - is it a virtual tag? */ function insert(root, nextTag, isVirtual) { if (isVirtual) { makeVirtual.apply(this, [root, nextTag]); } else { safeInsert(root, this.root, nextTag.root); } } /** * Append a new tag into the DOM * @this Tag * @param { HTMLElement } root - dom node containing all the loop children * @param { Boolean } isVirtual - is it a virtual tag? */ function append(root, isVirtual) { if (isVirtual) { makeVirtual.call(this, root); } else { root.appendChild(this.root); } } /** * Manage tags having the 'each' * @param { HTMLElement } dom - DOM node we need to loop * @param { Tag } parent - parent tag instance where the dom node is contained * @param { String } expr - string contained in the 'each' attribute * @returns { Object } expression object for this each loop */ function _each(dom, parent, expr) { // remove the each property from the original tag remAttr(dom, 'each'); var mustReorder = typeof getAttr(dom, 'no-reorder') !== T_STRING || remAttr(dom, 'no-reorder'), tagName = getTagName(dom), impl = __TAG_IMPL[tagName] || { tmpl: getOuterHTML(dom) }, useRoot = RE_SPECIAL_TAGS.test(tagName), root = dom.parentNode, ref = createDOMPlaceholder(), child = getTag(dom), ifExpr = getAttr(dom, 'if'), tags = [], oldItems = [], hasKeys, isLoop = true, isAnonymous = !__TAG_IMPL[tagName], isVirtual = dom.tagName === 'VIRTUAL'; // parse the each expression expr = tmpl.loopKeys(expr); expr.isLoop = true; if (ifExpr) { remAttr(dom, 'if'); } // insert a marked where the loop tags will be injected root.insertBefore(ref, dom); root.removeChild(dom); expr.update = function updateEach() { // get the new items collection var items = tmpl(expr.val, parent), parentNode, frag, placeholder; root = ref.parentNode; if (parentNode) { placeholder = createDOMPlaceholder(''); parentNode.insertBefore(placeholder, root); parentNode.removeChild(root); } else { frag = createFrag(); } // object loop. any changes cause full redraw if (!isArray(items)) { hasKeys = items || false; items = hasKeys ? Object.keys(items).map(function (key) { return mkitem(expr, items[key], key) }) : []; } else { hasKeys = false; } if (ifExpr) { items = items.filter(function(item, i) { var context = mkitem(expr, item, i, parent); return !!tmpl(ifExpr, context) }); } // loop all the new items each(items, function(item, i) { // reorder only if the items are objects var _mustReorder = mustReorder && typeof item === T_OBJECT && !hasKeys, oldPos = oldItems.indexOf(item), pos = ~oldPos && _mustReorder ? oldPos : i, // does a tag exist in this position? tag = tags[pos]; item = !hasKeys && expr.key ? mkitem(expr, item, i) : item; // new tag if ( !_mustReorder && !tag // with no-reorder we just update the old tags || _mustReorder && !~oldPos || !tag // by default we always try to reorder the DOM elements ) { var mustAppend = i === tags.length; tag = new Tag$$1(impl, { parent: parent, isLoop: isLoop, isAnonymous: isAnonymous, root: useRoot ? root : dom.cloneNode(), item: item }, dom.innerHTML); // mount the tag tag.mount(); if (mustAppend) { append.apply(tag, [frag || root, isVirtual]); } else { insert.apply(tag, [root, tags[i], isVirtual]); } if (!mustAppend) { oldItems.splice(i, 0, item); } tags.splice(i, 0, tag); if (child) { arrayishAdd(parent.tags, tagName, tag, true); } pos = i; // handled here so no move } else { tag.update(item); } // reorder the tag if it's not located in its previous position if (pos !== i && _mustReorder) { move.apply(tag, [root, tags[i], isVirtual]); // update the position attribute if it exists if (expr.pos) { tag[expr.pos] = i; } // move the old tag instance tags.splice(i, 0, tags.splice(pos, 1)[0]); // move the old item oldItems.splice(i, 0, oldItems.splice(pos, 1)[0]); // if the loop tags are not custom // we need to move all their custom tags into the right position if (!child && tag.tags) { moveNestedTags.call(tag, i); } } // cache the original item to use it in the events bound to this node // and its children tag._item = item; // cache the real parent tag internally defineProperty(tag, '_parent', parent); }); // remove the redundant tags unmountRedundant(items, tags, tagName, parent); // clone the items array oldItems = items.slice(); if (frag) { root.insertBefore(frag, ref); } else { parentNode.insertBefore(root, placeholder); parentNode.removeChild(placeholder); } }; expr.unmount = function() { each(tags, function(t) { t.unmount(); }); }; return expr } /** * Walk the tag DOM to detect the expressions to evaluate * @this Tag * @param { HTMLElement } root - root tag where we will start digging the expressions * @param { Array } expressions - empty array where the expressions will be added * @param { Boolean } mustIncludeRoot - flag to decide whether the root must be parsed as well */ function parseExpressions(root, expressions, mustIncludeRoot) { var this$1 = this; var base = {parent: {children: expressions}}; walkNodes(root, function (dom, ctx) { var type = dom.nodeType, parent = ctx.parent, attr, expr, tagImpl; if (!mustIncludeRoot && dom === root) { return {parent: parent} } // text node if (type === 3 && dom.parentNode.tagName !== 'STYLE' && tmpl.hasExpr(dom.nodeValue)) { parent.children.push({dom: dom, expr: dom.nodeValue}); } if (type !== 1) { return ctx } // not an element // loop. each does it's own thing (for now) if (attr = getAttr(dom, 'each')) { parent.children.push(_each(dom, this$1, attr)); return false } // if-attrs become the new parent. Any following expressions (either on the current // element, or below it) become children of this expression. if (attr = getAttr(dom, 'if')) { parent.children.push(Object.create(IfExpr).init(dom, this$1, attr)); return false } if (expr = getAttr(dom, RIOT_TAG_IS)) { if (tmpl.hasExpr(expr)) { parent.children.push({isRtag: true, expr: expr, dom: dom}); return false } } // if this is a tag, stop traversing here. // we ignore the root, since parseExpressions is called while we're mounting that root tagImpl = getTag(dom); if (tagImpl && (dom !== root || mustIncludeRoot)) { var conf = {root: dom, parent: this$1, hasImpl: true}; parent.children.push(initChildTag(tagImpl, conf, dom.innerHTML, this$1)); return false } // attribute expressions parseAttributes.apply(this$1, [dom, dom.attributes, function(attr, expr) { if (!expr) { return } parent.children.push(expr); }]); // whatever the parent is, all child elements get the same parent. // If this element had an if-attr, that's the parent for all child elements return {parent: parent} }, base); } /** * Calls `fn` for every attribute on an element. If that attr has an expression, * it is also passed to fn. * @this Tag * @param { HTMLElement } dom - dom node to parse * @param { Array } attrs - array of attributes * @param { Function } fn - callback to exec on any iteration */ function parseAttributes(dom, attrs, fn) { var this$1 = this; each(attrs, function (attr) { var name = attr.name, bool = isBoolAttr(name), expr; if (~['ref', 'data-ref'].indexOf(name)) { expr = Object.create(RefExpr).init(dom, name, attr.value, this$1); } else if (tmpl.hasExpr(attr.value)) { expr = {dom: dom, expr: attr.value, attr: attr.name, bool: bool}; } fn(attr, expr); }); } /* Includes hacks needed for the Internet Explorer version 9 and below See: http://kangax.github.io/compat-table/es5/#ie8 http://codeplanet.io/dropping-ie8/ */ var reHasYield = /<yield\b/i; var reYieldAll = /<yield\s*(?:\/>|>([\S\s]*?)<\/yield\s*>|>)/ig; var reYieldSrc = /<yield\s+to=['"]([^'">]*)['"]\s*>([\S\s]*?)<\/yield\s*>/ig; var reYieldDest = /<yield\s+from=['"]?([-\w]+)['"]?\s*(?:\/>|>([\S\s]*?)<\/yield\s*>)/ig; var rootEls = { tr: 'tbody', th: 'tr', td: 'tr', col: 'colgroup' }; var tblTags = IE_VERSION && IE_VERSION < 10 ? RE_SPECIAL_TAGS : RE_SPECIAL_TAGS_NO_OPTION; var GENERIC = 'div'; /* Creates the root element for table or select child elements: tr/th/td/thead/tfoot/tbody/caption/col/colgroup/option/optgroup */ function specialTags(el, templ, tagName) { var select = tagName[0] === 'o', parent = select ? 'select>' : 'table>'; // trim() is important here, this ensures we don't have artifacts, // so we can check if we have only one element inside the parent el.innerHTML = '<' + parent + templ.trim() + '</' + parent; parent = el.firstChild; // returns the immediate parent if tr/th/td/col is the only element, if not // returns the whole tree, as this can include additional elements if (select) { parent.selectedIndex = -1; // for IE9, compatible w/current riot behavior } else { // avoids insertion of cointainer inside container (ex: tbody inside tbody) var tname = rootEls[tagName]; if (tname && parent.childElementCount === 1) { parent = $(tname, parent); } } return parent } /* Replace the yield tag from any tag template with the innerHTML of the original tag in the page */ function replaceYield(templ, html) { // do nothing if no yield if (!reHasYield.test(templ)) { return templ } // be careful with #1343 - string on the source having `$1` var src = {}; html = html && html.replace(reYieldSrc, function (_, ref, text) { src[ref] = src[ref] || text; // preserve first definition return '' }).trim(); return templ .replace(reYieldDest, function (_, ref, def) { // yield with from - to attrs return src[ref] || def || '' }) .replace(reYieldAll, function (_, def) { // yield without any "from" return html || def || '' }) } /** * Creates a DOM element to wrap the given content. Normally an `DIV`, but can be * also a `TABLE`, `SELECT`, `TBODY`, `TR`, or `COLGROUP` element. * * @param {string} templ - The template coming from the custom tag definition * @param {string} [html] - HTML content that comes from the DOM element where you * will mount the tag, mostly the original tag in the page * @returns {HTMLElement} DOM element with _templ_ merged through `YIELD` with the _html_. */ function mkdom(templ, html) { var match = templ && templ.match(/^\s*<([-\w]+)/), tagName = match && match[1].toLowerCase(), el = mkEl(GENERIC, isSVGTag(tagName)); // replace all the yield tags with the tag inner html templ = replaceYield(templ, html); /* istanbul ignore next */ if (tblTags.test(tagName)) { el = specialTags(el, templ, tagName); } else { setInnerHTML(el, templ); } el.stub = true; return el } /** * Another way to create a riot tag a bit more es6 friendly * @param { HTMLElement } el - tag DOM selector or DOM node/s * @param { Object } opts - tag logic * @returns { Tag } new riot tag instance */ function Tag$1(el, opts) { // get the tag properties from the class constructor var ref = this; var name = ref.name; var tmpl = ref.tmpl; var css = ref.css; var attrs = ref.attrs; var onCreate = ref.onCreate; // register a new tag and cache the class prototype if (!__TAG_IMPL[name]) { tag$$1(name, tmpl, css, attrs, onCreate); // cache the class constructor __TAG_IMPL[name].class = this.constructor; } // mount the tag using the class instance mountTo(el, name, opts, this); return this } /** * Create a new riot tag implementation * @param { String } name - name/id of the new riot tag * @param { String } tmpl - tag template * @param { String } css - custom tag css * @param { String } attrs - root tag attributes * @param { Function } fn - user function * @returns { String } name/id of the tag just created */ function tag$$1(name, tmpl, css, attrs, fn) { if (isFunction(attrs)) { fn = attrs; if (/^[\w\-]+\s?=/.test(css)) { attrs = css; css = ''; } else { attrs = ''; } } if (css) { if (isFunction(css)) { fn = css; } else { styleManager.add(css); } } name = name.toLowerCase(); __TAG_IMPL[name] = { name: name, tmpl: tmpl, attrs: attrs, fn: fn }; return name } /** * Create a new riot tag implementation (for use by the compiler) * @param { String } name - name/id of the new riot tag * @param { String } tmpl - tag template * @param { String } css - custom tag css * @param { String } attrs - root tag attributes * @param { Function } fn - user function * @returns { String } name/id of the tag just created */ function tag2$$1(name, tmpl, css, attrs, fn) { if (css) { styleManager.add(css, name); } var exists = !!__TAG_IMPL[name]; __TAG_IMPL[name] = { name: name, tmpl: tmpl, attrs: attrs, fn: fn }; if (exists && util.hotReloader) { util.hotReloader(name); } return name } /** * Mount a tag using a specific tag implementation * @param { * } selector - tag DOM selector or DOM node/s * @param { String } tagName - tag implementation name * @param { Object } opts - tag logic * @returns { Array } new tags instances */ function mount$$1(selector, tagName, opts) { var tags = []; function pushTagsTo(root) { if (root.tagName) { var riotTag = getAttr(root, RIOT_TAG_IS); // have tagName? force riot-tag to be the same if (tagName && riotTag !== tagName) { riotTag = tagName; setAttr(root, RIOT_TAG_IS, tagName); } var tag$$1 = mountTo(root, riotTag || root.tagName.toLowerCase(), opts); if (tag$$1) { tags.push(tag$$1); } } else if (root.length) { each(root, pushTagsTo); } // assume nodeList } // inject styles into DOM styleManager.inject(); if (isObject(tagName)) { opts = tagName; tagName = 0; } var elem; var allTags; // crawl the DOM to find the tag if (isString(selector)) { selector = selector === '*' ? // select all registered tags // & tags found with the riot-tag attribute set allTags = selectTags() : // or just the ones named like the selector selector + selectTags(selector.split(/, */)); // make sure to pass always a selector // to the querySelectorAll function elem = selector ? $$(selector) : []; } else // probably you have passed already a tag or a NodeList { elem = selector; } // select all the registered and mount them inside their root elements if (tagName === '*') { // get all custom tags tagName = allTags || selectTags(); // if the root els it's just a single tag if (elem.tagName) { elem = $$(tagName, elem); } else { // select all the children for all the different root elements var nodeList = []; each(elem, function (_el) { return nodeList.push($$(tagName, _el)); }); elem = nodeList; } // get rid of the tagName tagName = 0; } pushTagsTo(elem); return tags } // Create a mixin that could be globally shared across all the tags var mixins = {}; var globals = mixins[GLOBAL_MIXIN] = {}; var _id = 0; /** * Create/Return a mixin by its name * @param { String } name - mixin name (global mixin if object) * @param { Object } mix - mixin logic * @param { Boolean } g - is global? * @returns { Object } the mixin logic */ function mixin$$1(name, mix, g) { // Unnamed global if (isObject(name)) { mixin$$1(("__unnamed_" + (_id++)), name, true); return } var store = g ? globals : mixins; // Getter if (!mix) { if (isUndefined(store[name])) { throw new Error('Unregistered mixin: ' + name) } return store[name] } // Setter store[name] = isFunction(mix) ? extend(mix.prototype, store[name] || {}) && mix : extend(store[name] || {}, mix); } /** * Update all the tags instances created * @returns { Array } all the tags instances */ function update$2() { return each(__VIRTUAL_DOM, function (tag$$1) { return tag$$1.update(); }) } function unregister$$1(name) { delete __TAG_IMPL[name]; } // counter to give a unique id to all the Tag instances var __uid = 0; /** * We need to update opts for this tag. That requires updating the expressions * in any attributes on the tag, and then copying the result onto opts. * @this Tag * @param {Boolean} isLoop - is it a loop tag? * @param { Tag } parent - parent tag node * @param { Boolean } isAnonymous - is it a tag without any impl? (a tag not registered) * @param { Object } opts - tag options * @param { Array } instAttrs - tag attributes array */ function updateOpts(isLoop, parent, isAnonymous, opts, instAttrs) { // isAnonymous `each` tags treat `dom` and `root` differently. In this case // (and only this case) we don't need to do updateOpts, because the regular parse // will update those attrs. Plus, isAnonymous tags don't need opts anyway if (isLoop && isAnonymous) { return } var ctx = !isAnonymous && isLoop ? this : parent || this; each(instAttrs, function (attr) { if (attr.expr) { update$1$1.call(ctx, [attr.expr]); } opts[toCamel(attr.name)] = attr.expr ? attr.expr.value : attr.value; }); } /** * Tag class * @constructor * @param { Object } impl - it contains the tag template, and logic * @param { Object } conf - tag options * @param { String } innerHTML - html that eventually we need to inject in the tag */ function Tag$$1(impl, conf, innerHTML) { var opts = inherit(conf.opts), parent = conf.parent, isLoop = conf.isLoop, isAnonymous = conf.isAnonymous, item = cleanUpData(conf.item), instAttrs = [], // All attributes on the Tag when it's first parsed implAttrs = [], // expressions on this type of Tag expressions = [], root = conf.root, tagName = conf.tagName || root.tagName.toLowerCase(), isVirtual = tagName === 'virtual', propsInSyncWithParent = [], dom; // make this tag observable observable(this); // only call unmount if we have a valid __TAG_IMPL (has name property) if (impl.name && root._tag) { root._tag.unmount(true); } // not yet mounted this.isMounted = false; root.isLoop = isLoop; defineProperty(this, '_internal', { isAnonymous: isAnonymous, instAttrs: instAttrs, innerHTML: innerHTML, // these vars will be needed only for the virtual tags virts: [], tail: null, head: null }); // create a unique id to this tag // it could be handy to use it also to improve the virtual dom rendering speed defineProperty(this, '_riot_id', ++__uid); // base 1 allows test !t._riot_id extend(this, { parent: parent, root: root, opts: opts }, item); // protect the "tags" and "refs" property from being overridden defineProperty(this, 'tags', {}); defineProperty(this, 'refs', {}); dom = mkdom(impl.tmpl, innerHTML); /** * Update the tag expressions and options * @param { * } data - data we want to use to extend the tag properties * @returns { Tag } the current tag instance */ defineProperty(this, 'update', function tagUpdate(data) { if (isFunction(this.shouldUpdate) && !this.shouldUpdate(data)) { return } // make sure the data passed will not override // the component core methods data = cleanUpData(data); // inherit properties from the parent, but only for isAnonymous tags if (isLoop && isAnonymous) { inheritFrom.apply(this, [this.parent, propsInSyncWithParent]); } extend(this, data); updateOpts.apply(this, [isLoop, parent, isAnonymous, opts, instAttrs]); if (this.isMounted) { this.trigger('update', data); } update$1$1.call(this, expressions); if (this.isMounted) { this.trigger('updated'); } return this }.bind(this)); /** * Add a mixin to this tag * @returns { Tag } the current tag instance */ defineProperty(this, 'mixin', function tagMixin() { var this$1 = this; each(arguments, function (mix) { var instance, props = [], obj; mix = isString(mix) ? mixin$$1(mix) : mix; // check if the mixin is a function if (isFunction(mix)) { // create the new mixin instance instance = new mix(); } else { instance = mix; } var proto = Object.getPrototypeOf(instance); // build multilevel prototype inheritance chain property list do { props = props.concat(Object.getOwnPropertyNames(obj || instance)); } while (obj = Object.getPrototypeOf(obj || instance)) // loop the keys in the function prototype or the all object keys each(props, function (key) { // bind methods to this // allow mixins to override other properties/parent mixins if (key !== 'init') { // check for getters/setters var descriptor = Object.getOwnPropertyDescriptor(instance, key) || Object.getOwnPropertyDescriptor(proto, key); var hasGetterSetter = descriptor && (descriptor.get || descriptor.set); // apply method only if it does not already exist on the instance if (!this$1.hasOwnProperty(key) && hasGetterSetter) { Object.defineProperty(this$1, key, descriptor); } else { this$1[key] = isFunction(instance[key]) ? instance[key].bind(this$1) : instance[key]; } } }); // init method will be called automatically if (instance.init) { instance.init.bind(this$1)(); } }); return this }.bind(this)); /** * Mount the current tag instance * @returns { Tag } the current tag instance */ defineProperty(this, 'mount', function tagMount() { var this$1 = this; root._tag = this; // keep a reference to the tag just created // Read all the attrs on this instance. This give us the info we need for updateOpts parseAttributes.apply(parent, [root, root.attributes, function (attr, expr) { if (!isAnonymous && RefExpr.isPrototypeOf(expr)) { expr.tag = this$1; } attr.expr = expr; instAttrs.push(attr); }]); // update the root adding custom attributes coming from the compiler implAttrs = []; walkAttrs(impl.attrs, function (k, v) { implAttrs.push({name: k, value: v}); }); parseAttributes.apply(this, [root, implAttrs, function (attr, expr) { if (expr) { expressions.push(expr); } else { setAttr(root, attr.name, attr.value); } }]); // children in loop should inherit from true parent if (this._parent && isAnonymous) { inheritFrom.apply(this, [this._parent, propsInSyncWithParent]); } // initialiation updateOpts.apply(this, [isLoop, parent, isAnonymous, opts, instAttrs]); // add global mixins var globalMixin = mixin$$1(GLOBAL_MIXIN); if (globalMixin) { for (var i in globalMixin) { if (globalMixin.hasOwnProperty(i)) { this$1.mixin(globalMixin[i]); } } } if (impl.fn) { impl.fn.call(this, opts); } this.trigger('before-mount'); // parse layout after init. fn may calculate args for nested custom tags parseExpressions.apply(this, [dom, expressions, false]); this.update(item); if (isLoop && isAnonymous) { // update the root attribute for the looped elements this.root = root = dom.firstChild; } else { while (dom.firstChild) { root.appendChild(dom.firstChild); } if (root.stub) { root = parent.root; } } defineProperty(this, 'root', root); this.isMounted = true; // if it's not a child tag we can trigger its mount event if (!this.parent || this.parent.isMounted) { this.trigger('mount'); } // otherwise we need to wait that the parent event gets triggered else { this.parent.one('mount', function () { this$1.trigger('mount'); }); } return this }.bind(this)); /** * Unmount the tag instance * @param { Boolean } mustKeepRoot - if it's true the root node will not be removed * @returns { Tag } the current tag instance */ defineProperty(this, 'unmount', function tagUnmount(mustKeepRoot) { var this$1 = this; var el = this.root, p = el.parentNode, ptag, tagIndex = __VIRTUAL_DOM.indexOf(this); this.trigger('before-unmount'); // remove this tag instance from the global virtualDom variable if (~tagIndex) { __VIRTUAL_DOM.splice(tagIndex, 1); } if (p) { if (parent) { ptag = getImmediateCustomParentTag(parent); if (isVirtual) { Object.keys(this.tags).forEach(function (tagName) { arrayishRemove(ptag.tags, tagName, this$1.tags[tagName]); }); } else { arrayishRemove(ptag.tags, tagName, this); } } else { while (el.firstChild) { el.removeChild(el.firstChild); } } if (!mustKeepRoot) { p.removeChild(el); } else // the riot-tag and the data-is attributes aren't needed anymore, remove them { remAttr(p, RIOT_TAG_IS); } } if (this._internal.virts) { each(this._internal.virts, function (v) { if (v.parentNode) { v.parentNode.removeChild(v); } }); } // allow expressions to unmount themselves unmountAll(expressions); each(instAttrs, function (a) { return a.expr && a.expr.unmount && a.expr.unmount(); }); this.trigger('unmount'); this.off('*'); this.isMounted = false; delete this.root._tag; return this }.bind(this)); } /** * Detect the tag implementation by a DOM node * @param { Object } dom - DOM node we need to parse to get its tag implementation * @returns { Object } it returns an object containing the implementation of a custom tag (template and boot function) */ function getTag(dom) { return dom.tagName && __TAG_IMPL[getAttr(dom, RIOT_TAG_IS) || getAttr(dom, RIOT_TAG_IS) || dom.tagName.toLowerCase()] } /** * Inherit properties from a target tag instance * @this Tag * @param { Tag } target - tag where we will inherit properties * @param { Array } propsInSyncWithParent - array of properties to sync with the target */ function inheritFrom(target, propsInSyncWithParent) { var this$1 = this; each(Object.keys(target), function (k) { // some properties must be always in sync with the parent tag var mustSync = !isReservedName(k) && contains(propsInSyncWithParent, k); if (isUndefined(this$1[k]) || mustSync) { // track the property to keep in sync // so we can keep it updated if (!mustSync) { propsInSyncWithParent.push(k); } this$1[k] = target[k]; } }); } /** * Move the position of a custom tag in its parent tag * @this Tag * @param { String } tagName - key where the tag was stored * @param { Number } newPos - index where the new tag will be stored */ function moveChildTag(tagName, newPos) { var parent = this.parent, tags; // no parent no move if (!parent) { return } tags = parent.tags[tagName]; if (isArray(tags)) { tags.splice(newPos, 0, tags.splice(tags.indexOf(this), 1)[0]); } else { arrayishAdd(parent.tags, tagName, this); } } /** * Create a new child tag including it correctly into its parent * @param { Object } child - child tag implementation * @param { Object } opts - tag options containing the DOM node where the tag will be mounted * @param { String } innerHTML - inner html of the child node * @param { Object } parent - instance of the parent tag including the child custom tag * @param { Boolean } skipName - hack to ignore the name attribute when attaching to parent * @returns { Object } instance of the new child tag just created */ function initChildTag(child, opts, innerHTML, parent) { var tag = new Tag$$1(child, opts, innerHTML), tagName = opts.tagName || getTagName(opts.root, true), ptag = getImmediateCustomParentTag(parent); // fix for the parent attribute in the looped elements tag.parent = ptag; // store the real parent tag // in some cases this could be different from the custom parent tag // for example in nested loops tag._parent = parent; // add this tag to the custom parent tag arrayishAdd(ptag.tags, tagName, tag); // and also to the real parent tag if (ptag !== parent) { arrayishAdd(parent.tags, tagName, tag); } // empty the child node once we got its template // to avoid that its children get compiled multiple times opts.root.innerHTML = ''; return tag } /** * Loop backward all the parents tree to detect the first custom parent tag * @param { Object } tag - a Tag instance * @returns { Object } the instance of the first custom parent tag found */ function getImmediateCustomParentTag(tag) { var ptag = tag; while (ptag._internal.isAnonymous) { if (!ptag.parent) { break } ptag = ptag.parent; } return ptag } /** * Trigger the unmount method on all the expressions * @param { Array } expressions - DOM expressions */ function unmountAll(expressions) { each(expressions, function(expr) { if (expr instanceof Tag$$1) { expr.unmount(true); } else if (expr.unmount) { expr.unmount(); } }); } /** * Get the tag name of any DOM node * @param { Object } dom - DOM node we want to parse * @param { Boolean } skipName - hack to ignore the name attribute when attaching to parent * @returns { String } name to identify this dom node in riot */ function getTagName(dom, skipName) { var child = getTag(dom), namedTag = !skipName && getAttr(dom, 'name'), tagName = namedTag && !tmpl.hasExpr(namedTag) ? namedTag : child ? child.name : dom.tagName.toLowerCase(); return tagName } /** * With this function we avoid that the internal Tag methods get overridden * @param { Object } data - options we want to use to extend the tag instance * @returns { Object } clean object without containing the riot internal reserved words */ function cleanUpData(data) { if (!(data instanceof Tag$$1) && !(data && typeof data.trigger === T_FUNCTION)) { return data } var o = {}; for (var key in data) { if (!RE_RESERVED_NAMES.test(key)) { o[key] = data[key]; } } return o } /** * Set the property of an object for a given key. If something already * exists there, then it becomes an array containing both the old and new value. * @param { Object } obj - object on which to set the property * @param { String } key - property name * @param { Object } value - the value of the property to be set * @param { Boolean } ensureArray - ensure that the property remains an array */ function arrayishAdd(obj, key, value, ensureArray) { var dest = obj[key]; var isArr = isArray(dest); if (dest && dest === value) { return } // if the key was never set, set it once if (!dest && ensureArray) { obj[key] = [value]; } else if (!dest) { obj[key] = value; } // if it was an array and not yet set else if (!isArr || isArr && !contains(dest, value)) { if (isArr) { dest.push(value); } else { obj[key] = [dest, value]; } } } /** * Removes an item from an object at a given key. If the key points to an array, * then the item is just removed from the array. * @param { Object } obj - object on which to remove the property * @param { String } key - property name * @param { Object } value - the value of the property to be removed * @param { Boolean } ensureArray - ensure that the property remains an array */ function arrayishRemove(obj, key, value, ensureArray) { if (isArray(obj[key])) { each(obj[key], function(item, i) { if (item === value) { obj[key].splice(i, 1); } }); if (!obj[key].length) { delete obj[key]; } else if (obj[key].length === 1 && !ensureArray) { obj[key] = obj[key][0]; } } else { delete obj[key]; } // otherwise just delete the key } /** * Check whether a DOM node is in stub mode, useful for the riot 'if' directive * @param { Object } dom - DOM node we want to parse * @returns { Boolean } - */ function isInStub(dom) { while (dom) { if (dom.inStub) { return true } dom = dom.parentNode; } return false } /** * Mount a tag creating new Tag instance * @param { Object } root - dom node where the tag will be mounted * @param { String } tagName - name of the riot tag we want to mount * @param { Object } opts - options to pass to the Tag instance * @param { Object } ctx - optional context that will be used to extend an existing class ( used in riot.Tag ) * @returns { Tag } a new Tag instance */ function mountTo(root, tagName, opts, ctx) { var impl = __TAG_IMPL[tagName], implClass = __TAG_IMPL[tagName].class, tag = ctx || (implClass ? Object.create(implClass.prototype) : {}), // cache the inner HTML to fix #855 innerHTML = root._innerHTML = root._innerHTML || root.innerHTML; // clear the inner html root.innerHTML = ''; var conf = { root: root, opts: opts }; if (opts && opts.parent) { conf.parent = opts.parent; } if (impl && root) { Tag$$1.apply(tag, [impl, conf, innerHTML]); } if (tag && tag.mount) { tag.mount(true); // add this tag to the virtualDom variable if (!contains(__VIRTUAL_DOM, tag)) { __VIRTUAL_DOM.push(tag); } } return tag } /** * Adds the elements for a virtual tag * @this Tag * @param { Node } src - the node that will do the inserting or appending * @param { Tag } target - only if inserting, insert before this tag's first child */ function makeVirtual(src, target) { var this$1 = this; var head = createDOMPlaceholder(), tail = createDOMPlaceholder(), frag = createFrag(), sib, el; this._internal.head = this.root.insertBefore(head, this.root.firstChild); this._internal.tail = this.root.appendChild(tail); el = this._internal.head; while (el) { sib = el.nextSibling; frag.appendChild(el); this$1._internal.virts.push(el); // hold for unmounting el = sib; } if (target) { src.insertBefore(frag, target._internal.head); } else { src.appendChild(frag); } } /** * Move virtual tag and all child nodes * @this Tag * @param { Node } src - the node that will do the inserting * @param { Tag } target - insert before this tag's first child */ function moveVirtual(src, target) { var this$1 = this; var el = this._internal.head, frag = createFrag(), sib; while (el) { sib = el.nextSibling; frag.appendChild(el); el = sib; if (el === this$1._internal.tail) { frag.appendChild(el); src.insertBefore(frag, target._internal.head); break } } } /** * Get selectors for tags * @param { Array } tags - tag names to select * @returns { String } selector */ function selectTags(tags) { // select all tags if (!tags) { var keys = Object.keys(__TAG_IMPL); return keys + selectTags(keys) } return tags .filter(function (t) { return !/[^-\w]/.test(t); }) .reduce(function (list, t) { var name = t.trim().toLowerCase(); return list + ",[" + RIOT_TAG_IS + "=\"" + name + "\"]" }, '') } var tags = Object.freeze({ getTag: getTag, inheritFrom: inheritFrom, moveChildTag: moveChildTag, initChildTag: initChildTag, getImmediateCustomParentTag: getImmediateCustomParentTag, unmountAll: unmountAll, getTagName: getTagName, cleanUpData: cleanUpData, arrayishAdd: arrayishAdd, arrayishRemove: arrayishRemove, isInStub: isInStub, mountTo: mountTo, makeVirtual: makeVirtual, moveVirtual: moveVirtual, selectTags: selectTags }); /** * Riot public api */ var settings = Object.create(brackets.settings); var util = { tmpl: tmpl, brackets: brackets, styleManager: styleManager, vdom: __VIRTUAL_DOM, styleNode: styleManager.styleNode, // export the riot internal utils as well dom: dom, check: check, misc: misc, tags: tags }; exports.settings = settings; exports.util = util; exports.observable = observable; exports.Tag = Tag$1; exports.tag = tag$$1; exports.tag2 = tag2$$1; exports.mount = mount$$1; exports.mixin = mixin$$1; exports.update = update$2; exports.unregister = unregister$$1; Object.defineProperty(exports, '__esModule', { value: true }); })));
/*syn@0.1.2#key.support*/ var syn = require('./synthetic.js'); require('./key.js'); if (!syn.config.support) { (function checkForSupport() { if (!document.body) { return syn.schedule(checkForSupport, 1); } var div = document.createElement('div'), checkbox, submit, form, anchor, textarea, inputter, one, doc; doc = document.documentElement; div.innerHTML = '<form id=\'outer\'>' + '<input name=\'checkbox\' type=\'checkbox\'/>' + '<input name=\'radio\' type=\'radio\' />' + '<input type=\'submit\' name=\'submitter\'/>' + '<input type=\'input\' name=\'inputter\'/>' + '<input name=\'one\'>' + '<input name=\'two\'/>' + '<a href=\'#abc\'></a>' + '<textarea>1\n2</textarea>' + '</form>'; doc.insertBefore(div, doc.firstElementChild || doc.children[0]); form = div.firstChild; checkbox = form.childNodes[0]; submit = form.childNodes[2]; anchor = form.getElementsByTagName('a')[0]; textarea = form.getElementsByTagName('textarea')[0]; inputter = form.childNodes[3]; one = form.childNodes[4]; form.onsubmit = function (ev) { if (ev.preventDefault) { ev.preventDefault(); } syn.support.keypressSubmits = true; ev.returnValue = false; return false; }; syn.__tryFocus(inputter); syn.trigger(inputter, 'keypress', '\r'); syn.trigger(inputter, 'keypress', 'a'); syn.support.keyCharacters = inputter.value === 'a'; inputter.value = 'a'; syn.trigger(inputter, 'keypress', '\b'); syn.support.backspaceWorks = inputter.value === ''; inputter.onchange = function () { syn.support.focusChanges = true; }; syn.__tryFocus(inputter); syn.trigger(inputter, 'keypress', 'a'); syn.__tryFocus(form.childNodes[5]); syn.trigger(inputter, 'keypress', 'b'); syn.support.keysOnNotFocused = inputter.value === 'ab'; syn.bind(anchor, 'click', function (ev) { if (ev.preventDefault) { ev.preventDefault(); } syn.support.keypressOnAnchorClicks = true; ev.returnValue = false; return false; }); syn.trigger(anchor, 'keypress', '\r'); syn.support.textareaCarriage = textarea.value.length === 4; syn.support.oninput = 'oninput' in one; doc.removeChild(div); syn.support.ready++; }()); } else { syn.helpers.extend(syn.support, syn.config.support); }
/*! * Waves v0.6.4 * http://fian.my.id/Waves * * Copyright 2014 Alfiana E. Sibuea and other contributors * Released under the MIT license * https://github.com/fians/Waves/blob/master/LICENSE */ ;(function(window) { 'use strict'; var Waves = Waves || {}; var $$ = document.querySelectorAll.bind(document); // Find exact position of element function isWindow(obj) { return obj !== null && obj === obj.window; } function getWindow(elem) { return isWindow(elem) ? elem : elem.nodeType === 9 && elem.defaultView; } function offset(elem) { var docElem, win, box = {top: 0, left: 0}, doc = elem && elem.ownerDocument; docElem = doc.documentElement; if (typeof elem.getBoundingClientRect !== typeof undefined) { box = elem.getBoundingClientRect(); } win = getWindow(doc); return { top: box.top + win.pageYOffset - docElem.clientTop, left: box.left + win.pageXOffset - docElem.clientLeft }; } function convertStyle(obj) { var style = ''; for (var a in obj) { if (obj.hasOwnProperty(a)) { style += (a + ':' + obj[a] + ';'); } } return style; } var Effect = { // Effect delay duration: 750, show: function(e, element) { // Disable right click if (e.button === 2) { return false; } var el = element || this; // Create ripple var ripple = document.createElement('div'); ripple.className = 'waves-ripple'; el.appendChild(ripple); // Get click coordinate and element witdh var pos = offset(el); var relativeY = (e.pageY - pos.top); var relativeX = (e.pageX - pos.left); var scale = 'scale('+((el.clientWidth / 100) * 10)+')'; // Support for touch devices if ('touches' in e) { relativeY = (e.touches[0].pageY - pos.top); relativeX = (e.touches[0].pageX - pos.left); } // Attach data to element ripple.setAttribute('data-hold', Date.now()); ripple.setAttribute('data-scale', scale); ripple.setAttribute('data-x', relativeX); ripple.setAttribute('data-y', relativeY); // Set ripple position var rippleStyle = { 'top': relativeY+'px', 'left': relativeX+'px' }; ripple.className = ripple.className + ' waves-notransition'; ripple.setAttribute('style', convertStyle(rippleStyle)); ripple.className = ripple.className.replace('waves-notransition', ''); // Scale the ripple rippleStyle['-webkit-transform'] = scale; rippleStyle['-moz-transform'] = scale; rippleStyle['-ms-transform'] = scale; rippleStyle['-o-transform'] = scale; rippleStyle.transform = scale; rippleStyle.opacity = '1'; rippleStyle['-webkit-transition-duration'] = Effect.duration + 'ms'; rippleStyle['-moz-transition-duration'] = Effect.duration + 'ms'; rippleStyle['-o-transition-duration'] = Effect.duration + 'ms'; rippleStyle['transition-duration'] = Effect.duration + 'ms'; rippleStyle['-webkit-transition-timing-function'] = 'cubic-bezier(0.250, 0.460, 0.450, 0.940)'; rippleStyle['-moz-transition-timing-function'] = 'cubic-bezier(0.250, 0.460, 0.450, 0.940)'; rippleStyle['-o-transition-timing-function'] = 'cubic-bezier(0.250, 0.460, 0.450, 0.940)'; rippleStyle['transition-timing-function'] = 'cubic-bezier(0.250, 0.460, 0.450, 0.940)'; ripple.setAttribute('style', convertStyle(rippleStyle)); }, hide: function(e) { TouchHandler.touchup(e); var el = this; var width = el.clientWidth * 1.4; // Get first ripple var ripple = null; var ripples = el.getElementsByClassName('waves-ripple'); if (ripples.length > 0) { ripple = ripples[ripples.length - 1]; } else { return false; } var relativeX = ripple.getAttribute('data-x'); var relativeY = ripple.getAttribute('data-y'); var scale = ripple.getAttribute('data-scale'); // Get delay beetween mousedown and mouse leave var diff = Date.now() - Number(ripple.getAttribute('data-hold')); var delay = 350 - diff; if (delay < 0) { delay = 0; } // Fade out ripple after delay setTimeout(function() { var style = { 'top': relativeY+'px', 'left': relativeX+'px', 'opacity': '0', // Duration '-webkit-transition-duration': Effect.duration + 'ms', '-moz-transition-duration': Effect.duration + 'ms', '-o-transition-duration': Effect.duration + 'ms', 'transition-duration': Effect.duration + 'ms', '-webkit-transform': scale, '-moz-transform': scale, '-ms-transform': scale, '-o-transform': scale, 'transform': scale, }; ripple.setAttribute('style', convertStyle(style)); setTimeout(function() { try { el.removeChild(ripple); } catch(e) { return false; } }, Effect.duration); }, delay); }, // Little hack to make <input> can perform waves effect wrapInput: function(elements) { for (var a = 0; a < elements.length; a++) { var el = elements[a]; if (el.tagName.toLowerCase() === 'input') { var parent = el.parentNode; // If input already have parent just pass through if (parent.tagName.toLowerCase() === 'i' && parent.className.indexOf('waves-effect') !== -1) { continue; } // Put element class and style to the specified parent var wrapper = document.createElement('i'); wrapper.className = el.className + ' waves-input-wrapper'; var elementStyle = el.getAttribute('style'); if (!elementStyle) { elementStyle = ''; } wrapper.setAttribute('style', elementStyle); el.className = 'waves-button-input'; el.removeAttribute('style'); // Put element as child parent.replaceChild(wrapper, el); wrapper.appendChild(el); } } } }; /** * Disable mousedown event for 500ms during and after touch */ var TouchHandler = { /* uses an integer rather than bool so there's no issues with * needing to clear timeouts if another touch event occurred * within the 500ms. Cannot mouseup between touchstart and * touchend, nor in the 500ms after touchend. */ touches: 0, allowEvent: function(e) { var allow = true; if (e.type === 'touchstart') { TouchHandler.touches += 1; //push } else if (e.type === 'touchend' || e.type === 'touchcancel') { setTimeout(function() { if (TouchHandler.touches > 0) { TouchHandler.touches -= 1; //pop after 500ms } }, 500); } else if (e.type === 'mousedown' && TouchHandler.touches > 0) { allow = false; } return allow; }, touchup: function(e) { TouchHandler.allowEvent(e); } }; /** * Delegated click handler for .waves-effect element. * returns null when .waves-effect element not in "click tree" */ function getWavesEffectElement(e) { if (TouchHandler.allowEvent(e) === false) { return null; } var element = null; var target = e.target || e.srcElement; while (target.parentNode !== null) { if (!(target instanceof SVGElement) && target.className.indexOf('waves-effect') !== -1) { element = target; break; } target = target.parentNode; } return element; } /** * Bubble the click and show effect if .waves-effect elem was found */ function showEffect(e) { var element = getWavesEffectElement(e); if (element !== null) { Effect.show(e, element); if ('ontouchstart' in window) { element.addEventListener('touchend', Effect.hide, false); element.addEventListener('touchcancel', Effect.hide, false); } element.addEventListener('mouseup', Effect.hide, false); element.addEventListener('mouseleave', Effect.hide, false); element.addEventListener('dragend', Effect.hide, false); } } Waves.displayEffect = function(options) { options = options || {}; if ('duration' in options) { Effect.duration = options.duration; } //Wrap input inside <i> tag Effect.wrapInput($$('.waves-effect')); if ('ontouchstart' in window) { document.body.addEventListener('touchstart', showEffect, false); } document.body.addEventListener('mousedown', showEffect, false); }; /** * Attach Waves to an input element (or any element which doesn't * bubble mouseup/mousedown events). * Intended to be used with dynamically loaded forms/inputs, or * where the user doesn't want a delegated click handler. */ Waves.attach = function(element) { //FUTURE: automatically add waves classes and allow users // to specify them with an options param? Eg. light/classic/button if (element.tagName.toLowerCase() === 'input') { Effect.wrapInput([element]); element = element.parentNode; } if ('ontouchstart' in window) { element.addEventListener('touchstart', showEffect, false); } element.addEventListener('mousedown', showEffect, false); }; window.Waves = Waves; document.addEventListener('DOMContentLoaded', function() { Waves.displayEffect(); }, false); })(window);
Ext.define('Neptune.view.grid.widget.GroupHeader', { extend: 'Neptune.view.grid.widget.Basic', xtype: 'groupHeaderGrid', title: 'Group Header Grid', constructor: function(cfg) { var priceColumns; this.columns = Ext.Array.clone(this.columns); priceColumns = this.columns.splice(1, 3); this.columns.splice(1, 0, { text: 'Stock Price', columns: priceColumns }); this.callParent(arguments); } });
// Generated by CoffeeScript 1.10.0 (function() { 'use strict'; var _containersControllers, _windowEventsHandlerBinded, _windowInViewItems, addWindowInViewItem, angularInviewModule, bindWindowEvents, checkInView, debounce, getBoundingClientRect, getOffsetFromPercentage, getViewportHeight, offsetIsPercentage, removeWindowInViewItem, trackInViewContainer, triggerInViewCallback, unbindWindowEvents, untrackInViewContainer, windowCheckInView, windowEventsHandler, slice = [].slice; angularInviewModule = angular.module('angular-inview', []).directive('inView', [ '$parse', function($parse) { return { restrict: 'A', require: '?^inViewContainer', link: function(scope, element, attrs, containerController) { var inViewFunc, item, options, performCheck, ref, ref1; if (!attrs.inView) { return; } inViewFunc = $parse(attrs.inView); item = { element: element, wasInView: false, offset: 0, customDebouncedCheck: null, callback: function($event, $inview, $inviewpart) { if ($event == null) { $event = {}; } return scope.$evalAsync((function(_this) { return function() { $event.inViewTarget = element[0]; return inViewFunc(scope, { '$event': $event, '$inview': $inview, '$inviewpart': $inviewpart }); }; })(this)); } }; if ((attrs.inViewOptions != null) && (options = scope.$eval(attrs.inViewOptions))) { item.offset = options.offset || [options.offsetTop || 0, options.offsetBottom || 0]; if (options.debounce) { item.customDebouncedCheck = debounce((function(event) { return checkInView([item], element[0], event); }), options.debounce); } } performCheck = (ref = (ref1 = item.customDebouncedCheck) != null ? ref1 : containerController != null ? containerController.checkInView : void 0) != null ? ref : windowCheckInView; if (containerController != null) { containerController.addItem(item); } else { addWindowInViewItem(item); } setTimeout(performCheck); return scope.$on('$destroy', function() { if (containerController != null) { containerController.removeItem(item); } return removeWindowInViewItem(item); }); } }; } ]).directive('inViewContainer', function() { return { restrict: 'AC', controller: [ '$element', function($element) { this.items = []; this.addItem = function(item) { return this.items.push(item); }; this.removeItem = function(item) { var i; return this.items = (function() { var j, len, ref, results; ref = this.items; results = []; for (j = 0, len = ref.length; j < len; j++) { i = ref[j]; if (i !== item) { results.push(i); } } return results; }).call(this); }; this.checkInView = (function(_this) { return function(event) { var i, j, len, ref; ref = _this.items; for (j = 0, len = ref.length; j < len; j++) { i = ref[j]; if (i.customDebouncedCheck != null) { i.customDebouncedCheck(); } } return checkInView((function() { var k, len1, ref1, results; ref1 = this.items; results = []; for (k = 0, len1 = ref1.length; k < len1; k++) { i = ref1[k]; if (i.customDebouncedCheck == null) { results.push(i); } } return results; }).call(_this), $element[0], event); }; })(this); return this; } ], link: function(scope, element, attrs, controller) { element.bind('scroll', controller.checkInView); trackInViewContainer(controller); return scope.$on('$destroy', function() { element.unbind('scroll', controller.checkInView); return untrackInViewContainer(controller); }); } }; }); _windowInViewItems = []; addWindowInViewItem = function(item) { _windowInViewItems.push(item); return bindWindowEvents(); }; removeWindowInViewItem = function(item) { var i; _windowInViewItems = (function() { var j, len, results; results = []; for (j = 0, len = _windowInViewItems.length; j < len; j++) { i = _windowInViewItems[j]; if (i !== item) { results.push(i); } } return results; })(); return unbindWindowEvents(); }; _containersControllers = []; trackInViewContainer = function(controller) { _containersControllers.push(controller); return bindWindowEvents(); }; untrackInViewContainer = function(container) { var c; _containersControllers = (function() { var j, len, results; results = []; for (j = 0, len = _containersControllers.length; j < len; j++) { c = _containersControllers[j]; if (c !== container) { results.push(c); } } return results; })(); return unbindWindowEvents(); }; _windowEventsHandlerBinded = false; windowEventsHandler = function(event) { var c, j, len; for (j = 0, len = _containersControllers.length; j < len; j++) { c = _containersControllers[j]; c.checkInView(event); } if (_windowInViewItems.length) { return windowCheckInView(event); } }; bindWindowEvents = function() { if (_windowEventsHandlerBinded) { return; } _windowEventsHandlerBinded = true; return angular.element(window).bind('checkInView click ready scroll resize', windowEventsHandler); }; unbindWindowEvents = function() { if (!_windowEventsHandlerBinded) { return; } if (_windowInViewItems.length || _containersControllers.length) { return; } _windowEventsHandlerBinded = false; return angular.element(window).unbind('checkInView click ready scroll resize', windowEventsHandler); }; triggerInViewCallback = function(event, item, inview, isTopVisible, isBottomVisible) { var elOffsetTop, inviewpart; if (inview) { elOffsetTop = getBoundingClientRect(item.element[0]).top + window.pageYOffset; inviewpart = (isTopVisible && isBottomVisible && 'neither') || (isTopVisible && 'top') || (isBottomVisible && 'bottom') || 'both'; if (!(item.wasInView && item.wasInView === inviewpart && elOffsetTop === item.lastOffsetTop)) { item.lastOffsetTop = elOffsetTop; item.wasInView = inviewpart; return item.callback(event, true, inviewpart); } } else if (item.wasInView) { item.wasInView = false; return item.callback(event, false); } }; checkInView = function(items, container, event) { var bounds, boundsBottom, boundsTop, element, item, j, k, len, len1, ref, ref1, ref2, ref3, results, viewport; viewport = { top: 0, bottom: getViewportHeight() }; if (container && container !== window) { bounds = getBoundingClientRect(container); if (bounds.top > viewport.bottom || bounds.bottom < viewport.top) { for (j = 0, len = items.length; j < len; j++) { item = items[j]; triggerInViewCallback(event, item, false); } return; } if (bounds.top > viewport.top) { viewport.top = bounds.top; } if (bounds.bottom < viewport.bottom) { viewport.bottom = bounds.bottom; } } results = []; for (k = 0, len1 = items.length; k < len1; k++) { item = items[k]; element = item.element[0]; bounds = getBoundingClientRect(element); boundsTop = bounds.top + (offsetIsPercentage(item.offset) ? getOffsetFromPercentage(bounds, item.offset) : parseInt((ref = (ref1 = item.offset) != null ? ref1[0] : void 0) != null ? ref : item.offset)); boundsBottom = bounds.bottom + (offsetIsPercentage(item.offset) ? getOffsetFromPercentage(bounds, item.offset) : parseInt((ref2 = (ref3 = item.offset) != null ? ref3[1] : void 0) != null ? ref2 : item.offset)); if (boundsTop < viewport.bottom && boundsBottom >= viewport.top) { results.push(triggerInViewCallback(event, item, true, boundsBottom > viewport.bottom, boundsTop < viewport.top)); } else { results.push(triggerInViewCallback(event, item, false)); } } return results; }; offsetIsPercentage = function(offset) { return typeof offset === 'string' && offset.slice(-1) === '%'; }; getOffsetFromPercentage = function(bounds, offsetPercentage) { var percentage; percentage = offsetPercentage.substring(0, offsetPercentage.length - 1); return (bounds.bottom - bounds.top) * (percentage / 100); }; getViewportHeight = function() { var height, mode, ref; height = window.innerHeight; if (height) { return height; } mode = document.compatMode; if (mode || !(typeof $ !== "undefined" && $ !== null ? (ref = $.support) != null ? ref.boxModel : void 0 : void 0)) { height = mode === 'CSS1Compat' ? document.documentElement.clientHeight : document.body.clientHeight; } return height; }; getBoundingClientRect = function(element) { var el, parent, top; if (element.getBoundingClientRect != null) { return element.getBoundingClientRect(); } top = 0; el = element; while (el) { top += el.offsetTop; el = el.offsetParent; } parent = element.parentElement; while (parent) { if (parent.scrollTop != null) { top -= parent.scrollTop; } parent = parent.parentElement; } return { top: top, bottom: top + element.offsetHeight }; }; debounce = function(f, t) { var timer; timer = null; return function() { var args; args = 1 <= arguments.length ? slice.call(arguments, 0) : []; if (timer != null) { clearTimeout(timer); } return timer = setTimeout((function() { return f.apply(null, args); }), t != null ? t : 100); }; }; windowCheckInView = function(event) { var i, j, len; for (j = 0, len = _windowInViewItems.length; j < len; j++) { i = _windowInViewItems[j]; if (i.customDebouncedCheck != null) { i.customDebouncedCheck(); } } return checkInView((function() { var k, len1, results; results = []; for (k = 0, len1 = _windowInViewItems.length; k < len1; k++) { i = _windowInViewItems[k]; if (i.customDebouncedCheck == null) { results.push(i); } } return results; })(), null, event); }; if (typeof define === 'function' && define.amd) { define(['angular', 'inview'], angularInviewModule); } else if (typeof module !== 'undefined' && module && module.exports) { module.exports = angularInviewModule; } }).call(this);
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ importScripts( '../../../vendor/core.js', '../../../vendor/zone.js', '../../../vendor/long-stack-trace-zone.js', '../../../vendor/system.src.js', '../../../vendor/Reflect.js'); System.config({ baseURL: '/all', map: {'rxjs': '/all/playground/vendor/rxjs'}, packages: { '@angular/core': {main: 'index.js', defaultExtension: 'js'}, '@angular/compiler': {main: 'index.js', defaultExtension: 'js'}, '@angular/common': {main: 'index.js', defaultExtension: 'js'}, '@angular/platform-browser': {main: 'index.js', defaultExtension: 'js'}, '@angular/platform-browser-dynamic': {main: 'index.js', defaultExtension: 'js'}, '@angular/router': {main: 'index.js', defaultExtension: 'js'}, '@angular/platform-webworker': {main: 'index.js', defaultExtension: 'js'}, '@angular/platform-webworker-dynamic': {main: 'index.js', defaultExtension: 'js'}, 'rxjs': {defaultExtension: 'js'}, }, defaultJSExtensions: true }); System.import('playground/src/web_workers/message_broker/background_index') .then( function(m) { try { m.main(); } catch (e) { console.error(e); } }, function(error) { console.error('error loading background', error); });
var _ = require('../../../../src/util') var Vue = require('../../../../src/vue') function trigger (target, event, process) { var e = document.createEvent('HTMLEvents') e.initEvent(event, true, true) if (process) process(e) target.dispatchEvent(e) return e } if (_.inBrowser) { describe('v-on', function () { var el beforeEach(function () { el = document.createElement('div') spyOn(_, 'warn') }) it('methods', function () { var spy = jasmine.createSpy() var vm = new Vue({ el: el, template: '<a v-on="click:test"></a>', data: {a: 1}, methods: { test: spy } }) var a = el.firstChild trigger(a, 'click') expect(spy.calls.count()).toBe(1) vm.$destroy() trigger(a, 'click') expect(spy.calls.count()).toBe(1) }) it('inline expression', function (done) { new Vue({ el: el, template: '<a v-on="click:a++">{{a}}</a>', data: {a: 1} }) var a = el.firstChild trigger(a, 'click') _.nextTick(function () { expect(a.textContent).toBe('2') done() }) }) it('with key filter', function (done) { new Vue({ el: el, template: '<a v-on="keyup:test | key \'enter\'">{{a}}</a>', data: {a: 1}, methods: { test: function () { this.a++ } } }) var a = el.firstChild trigger(a, 'keyup', function (e) { e.keyCode = 13 }) _.nextTick(function () { expect(a.textContent).toBe('2') done() }) }) it('warn non-function values', function () { new Vue({ el: el, data: { test: 123 }, template: '<a v-on="keyup:test"></a>' }) expect(hasWarned(_, 'expects a function value')).toBe(true) }) it('iframe', function () { // iframes only gets contentWindow when inserted // into the document document.body.appendChild(el) var spy = jasmine.createSpy() var vm = new Vue({ el: el, template: '<iframe v-on="click:test"></iframe>', methods: { test: spy } }) var iframeDoc = el.firstChild.contentDocument trigger(iframeDoc, 'click') expect(spy.calls.count()).toBe(1) vm.$destroy() trigger(iframeDoc, 'click') expect(spy.calls.count()).toBe(1) document.body.removeChild(el) }) it('passing $event', function () { var test = jasmine.createSpy() new Vue({ el: el, template: '<a v-on="click:test($event)"></a>', methods: { test: test } }) var e = trigger(el.firstChild, 'click') expect(test).toHaveBeenCalledWith(e) }) it('passing $event on a nested instance', function () { var test = jasmine.createSpy() var parent = new Vue({ methods: { test: test } }) parent.$addChild({ el: el, inherit: true, template: '<a v-on="click:test($event)"></a>' }) var e = trigger(el.firstChild, 'click') expect(test).toHaveBeenCalledWith(e) }) }) }
/** * Chirashi.js v5.2.2 * (c) 2017 Alex Toudic * Released under MIT License. **/ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); /** * Iterates over items and apply callback on each one. * @param {*} items - The iterable. * @param {forEachCallback} callback - The callback to call for each iteratee. * @param {boolean} [forceOrder=false] - Respect items order. * @return {(Array|NodeList|HTMLCollection)} items for chaining. * @example //esnext * import { forEach } from 'chirashi' * * const items = forEach([0, 1, 2], (item, i) => console.log(`${i}: ${item + 1}`)) //returns: [0, 1, 2] * // logs: * // 2: 3 * // 1: 2 * // 0: 1 * forEach(items, (item, i) => console.log(`${i}: ${item + 1}`), true) //returns: [0, 1, 2] * // logs: * // 0: 1 * // 1: 2 * // 2: 3 * forEach(0, (item, i) => console.log(`${i}: ${item + 1}`)) //returns: [0] * // 0: 1 * @example //es5 * var items = Chirashi.forEach([0, 1, 2], function (item, i) { console.log(i+': '+(item + 1)) }) //returns: [0, 1, 2] * // logs: * // 2: 3 * // 1: 2 * // 0: 1 * Chirashi.forEach(items, function (item, i) { console.log(i+': '+(item + 1)) }, true) //returns: [0, 1, 2] * // logs: * // 0: 1 * // 1: 2 * // 2: 3 * Chirashi.forEach(0, function (item, i) { console.log(i+': '+(item + 1)) }) //returns: [0] * // logs: * // 0: 1 */ function forEach(items, callback) { var forceOrder = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; if (!items) return []; if (!(items instanceof Array)) { if (!(items instanceof window.NodeList || items instanceof window.HTMLCollection)) { items = [items]; } } if (!forceOrder) { var i = items.length; while (i--) { callback(items[i], i); } } else { var _i = -1; var len = items.length; while (++_i < len) { callback(items[_i], _i); } } return items; } /** * Callback to apply on item. * @callback forEachCallback * @param {*} item * @param {number} index - Index of item in items. */ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var defineProperty = function (obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var toConsumableArray = function (arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } }; var _breakingMethods = ['push', 'splice', 'unshift']; function _chirasizeArray(array) { array.chrshPush = function (input) { this.push.apply(this, toConsumableArray(getElements(input))); this['_chrsh-valid'] = true; return this; }; forEach(_breakingMethods, function (method) { array[method] = function () { this['_chrsh-valid'] = false; return Array.prototype[method].apply(this, arguments); }; }); array['_chrsh-valid'] = true; return array; } /** * Test if element is a dom element. Doesn't resolve selectors. * @param {*} element - The element to test. * @return {boolean} isDomElement - true if element is HTMLElement, SVGElement, window, document or Text. * @example //esnext * import { createElement, append, isDomElement } from 'chirashi' * const sushi = createElement('.sushi') * append(document.body, sushi) * isDomElement(window) //returns: true * isDomElement(sushi) //returns: true * isDomElement('.sushi') //returns: false * @example //es5 * var sushi = Chirashi.createElement('.sushi') * Chirashi.append(document.body, sushi) * Chirashi.isDomElement(window) //returns: true * Chirashi.isDomElement(sushi) //returns: true * Chirashi.isDomElement('.sushi') //returns: false */ function isDomElement(element) { return element instanceof window.HTMLElement || element === window || element === document || element instanceof window.SVGElement || element instanceof window.Text; } /** * Get dom element recursively from iterable or selector. * @param {(string|Array|NodeList|HTMLCollection|window|document|HTMLElement|SVGElement|Text)} input - The iterable, selector or elements. * @return {Array} domElements - The array of dom elements from elements. * @return {function} domElements.chrshPush - Methods to push dom elements into the array. Accepts same input as getElements. * @example //esnext * import { createElement, append, getElements } from 'chirashi' * const sushi = createElement('.sushi') * const unagi = createElement('.unagi') * const yakitori = createElement('.yakitori') * const sashimi = createElement('.sashimi') * append(document.body, [sushi, unagi, yakitori, sashimi]) * getElements('div') //returns: [<div class="sushi"></div>, <div class="unagi"></div>, <div class="yakitori"></div>, <div class="sashimi"></div>] * getElements('.yakitori, .sashimi') //returns: [<div class="yakitori"></div>, <div class="sashimi"></div>] * getElements([sushi, unagi, '.sashimi', '.wasabi']) //returns: [<div class="sushi"></div>, <div class="unagi"></div>, <div class="sashimi"></div>] * getElements('.wasabi') //returns: [] * @example //es5 * var sushi = Chirashi.createElement('.sushi') * var unagi = Chirashi.createElement('.unagi') * var yakitori = Chirashi.createElement('.yakitori') * var sashimi = Chirashi.createElement('.sashimi') * Chirashi.append(document.body, [sushi, unagi, yakitori, sashimi]) * Chirashi.getElements('div') //returns: [<div class="sushi"></div>, <div class="unagi"></div>, <div class="yakitori"></div>, <div class="sashimi"></div>] * Chirashi.getElements('.yakitori, .sashimi') //returns: [<div class="yakitori"></div>, <div class="sashimi"></div>] * Chirashi.getElements([sushi, unagi, '.sashimi', '.wasabi']) //returns: [<div class="sushi"></div>, <div class="unagi"></div>, <div class="sashimi"></div>] * Chirashi.getElements('.wasabi') //returns: [] */ function getElements(input) { if (input && input['_chrsh-valid']) return input; var output = void 0; if (typeof input === 'string') { output = [].concat(toConsumableArray(document.querySelectorAll(input))); } else if (input instanceof Array) { (function () { var parsedElements = []; forEach(input, function (element) { parsedElements.push.apply(parsedElements, toConsumableArray(getElements(element))); }); output = parsedElements; })(); } else if (input instanceof window.NodeList || input instanceof window.HTMLCollection) { output = [].concat(toConsumableArray(input)); } else { output = isDomElement(input) ? [input] : []; } return _chirasizeArray(output); } /** * Iterates over dom elements and apply callback on each one. * @param {(string|Array|NodeList|HTMLCollection|window|document|HTMLElement|SVGElement|Text)} elements - The iterable, selector or elements. * @param {forElementsCallback} callback - The function to call for each element. * @param {boolean} [forceOrder=false] - Respect elements order. * @return {Array} domElements - The array of dom elements from elements. * @return {function} domElements.chrshPush - Methods to push dom elements into the array. Accepts same input as getElements. * @example //esnext * import { createElement, append, forElements } from 'chirashi' * const sushi = createElement('.sushi') * const unagi = createElement('.unagi') * const yakitori = createElement('.yakitori') * const sashimi = createElement('.sashimi') * append(document.body, [sushi, unagi, yakitori, sashimi]) * forElements('div', console.log) //returns: [<div class="sushi"></div>, <div class="unagi"></div>, <div class="yakitori"></div>, <div class="sashimi"></div>] * // logs: * // <div class="sashimi"></div> 3 * // <div class="yakitori"></div> 2 * // <div class="unagi"></div> 1 * // <div class="sushi"></div> 0 * forElements([yakitori, sashimi], console.log, true) //returns: [<div class="yakitori"></div>, <div class="sashimi"></div>] * // logs: * // <div class="yakitori"></div> 0 * // <div class="sashimi"></div> 1 * @example //es5 * var sushi = Chirashi.createElement('.sushi') * var unagi = Chirashi.createElement('.unagi') * var yakitori = Chirashi.createElement('.yakitori') * var sashimi = Chirashi.createElement('.sashimi') * Chirashi.append(document.body, [sushi, unagi, yakitori, sashimi]) * Chirashi.forElements('div', console.log) //returns: [<div class="sushi"></div>, <div class="unagi"></div>, <div class="yakitori"></div>, <div class="sashimi"></div>] * // logs: * // <div class="sashimi"></div> 3 * // <div class="yakitori"></div> 2 * // <div class="unagi"></div> 1 * // <div class="sushi"></div> 0 * Chirashi.forElements([yakitori, sashimi], console.log, true) //returns: [<div class="yakitori"></div>, <div class="sashimi"></div>] * // logs: * // <div class="yakitori"></div> 0 * // <div class="sashimi"></div> 1 */ function forElements(elements, callback) { var forceOrder = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; return forEach(getElements(elements), callback, forceOrder); } /** * Callback to apply on element. * @callback forElementsCallback * @param {window | document | HTMLElement | SVGElement | Text} element * @param {number} index - Index of element in elements. */ /** * Iterates over object's keys and apply callback on each one. * @param {Object} object - The iterable. * @param {forInCallback} callback - The function to call for each key-value pair. * @param {boolean} [forceOrder=false] - Respect keys order. * @return {Object} object - The iterable for chaining. * @example //esnext * import { forIn } from 'chirashi' * const californiaRoll = { name: 'California Roll', price: 4.25, recipe: ['avocado', 'cucumber', 'crab', 'mayonnaise', 'sushi rice', 'seaweed'] } * forIn(californiaRoll, (key, value) => { * console.log(`${key} -> ${value}`) * }) //returns: { name: 'California Roll', price: 4.25, recipe: ['avocado', 'cucumber', 'crab', 'mayonnaise', 'sushi rice', 'seaweed'] } * // LOGS: * // recipe -> ['avocado', 'cucumber', 'crab', 'mayonnaise', 'sushi rice', 'seaweed'] * // price -> 4.25 * // name -> California Roll * forIn(californiaRoll, (key, value) => { * console.log(`${key} -> ${value}`) * }, true) //returns: { name: 'California Roll', price: 4.25, recipe: ['avocado', 'cucumber', 'crab', 'mayonnaise', 'sushi rice', 'seaweed'] } * // LOGS: * // name -> California Roll * // price -> 4.25 * // recipe -> ['avocado', 'cucumber', 'crab', 'mayonnaise', 'sushi rice', 'seaweed'] * @example //es5 * var californiaRoll = { name: 'California Roll', price: 4.25, recipe: ['avocado', 'cucumber', 'crab', 'mayonnaise', 'sushi rice', 'seaweed'] } * Chirashi.forIn(californiaRoll, (key, value) => { * console.log(key + ' -> ' + value) * }) //returns: { name: 'California Roll', price: 4.25, recipe: ['avocado', 'cucumber', 'crab', 'mayonnaise', 'sushi rice', 'seaweed'] } * // LOGS: * // recipe -> ['avocado', 'cucumber', 'crab', 'mayonnaise', 'sushi rice', 'seaweed'] * // price -> 4.25 * // name -> California Roll * Chirashi.forIn(californiaRoll, (key, value) => { * console.log(key + ' -> ' + value) * }, true) //returns: { name: 'California Roll', price: 4.25, recipe: ['avocado', 'cucumber', 'crab', 'mayonnaise', 'sushi rice', 'seaweed'] } * // LOGS: * // name -> California Roll * // price -> 4.25 * // recipe -> ['avocado', 'cucumber', 'crab', 'mayonnaise', 'sushi rice', 'seaweed'] */ function forIn(object, callback) { var forceOrder = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; if ((typeof object === 'undefined' ? 'undefined' : _typeof(object)) !== 'object') return; forEach(Object.keys(object), function (key) { return callback(key, object[key]); }, forceOrder); return object; } /** * Callback to apply on each key-value pair. * @callback forInCallback * @param {string} key * @param {*} value */ /** * Get first dom element from iterable or selector. * @param {(string|Array|NodeList|HTMLCollection|window|document|HTMLElement|SVGElement|Text)} input - The iterable, selector or elements. * @return {(window|document|HTMLElement|SVGElement|Text|boolean)} element - The dom element from input or false if no element found. * @example //esnext * import { createElement, append, getElement } from 'chirashi' * const sushi = createElement('.sushi') * const unagi = createElement('.unagi') * const yakitori = createElement('.yakitori') * const sashimi = createElement('.sashimi') * append(document.body, [sushi, unagi, yakitori, sashimi]) * getElement('div') //returns: <div class="sushi"></div> * getElement('.yakitori, .sashimi') //returns: <div class="yakitori"></div> * getElement([sushi, unagi, '.sashimi', '.unknown']) //returns: <div class="sushi"></div> * getElement('.wasabi') //returns: null * @example //es5 * var sushi = Chirashi.createElement('.sushi') * var unagi = Chirashi.createElement('.unagi') * var yakitori = Chirashi.createElement('.yakitori') * var sashimi = Chirashi.createElement('.sashimi') * Chirashi.append(document.body, [sushi, unagi, yakitori, sashimi]) * Chirashi.getElement('div') //returns: <div class="sushi"></div> * Chirashi.getElement('.yakitori, .sashimi') //returns: <div class="yakitori"></div> * Chirashi.getElement([sushi, unagi, '.sashimi', '.unknown']) //returns: <div class="sushi"></div> * Chirashi.getElement('.wasabi') //returns: null */ function getElement(input) { if (typeof input === 'string') return document.querySelector(input); if (input instanceof Array || input instanceof window.NodeList || input instanceof window.HTMLCollection) { return getElement(input[0]); } return isDomElement(input) && input; } function _stringToArray(input, prefix) { var output = typeof input === 'string' ? input.split(/[,\s]+/g) : input; return prefix ? output.map(function (string) { return '' + prefix + string; }) : output; } function _updateClassList(elements, method, classes) { classes = _stringToArray(classes); return forElements(elements, function (element) { var _element$classList; if (!element.classList) return; (_element$classList = element.classList)[method].apply(_element$classList, toConsumableArray(classes)); }); } /** * Iterates over classes and add it on each element of elements. * @param {(string|Array|NodeList|HTMLCollection|HTMLElement|SVGElement)} elements - The iterable, selector or elements. * @param {(string|string[])} classes - Array of classes or string of classes seperated with comma and/or spaces. * @return {Array} domElements - The array of dom elements from elements. * @return {function} domElements.chrshPush - Methods to push dom elements into the array. Accepts same input as getElements. * @example //esnext * import { createElement, addClass } from 'chirashi' * const maki = createElement('div') * addClass(maki, 'wasabi') //returns: <div class="wasabi"></div> * addClass(maki, 'seaweed, cheese') //returns: <div class="wasabi seaweed cheese"></div> * addClass(maki, 'avocado salmon') //returns: <div class="wasabi seaweed cheese avocado salmon"></div> * addClass(maki, ['egg', 'tuna']) //returns: <div class="wasabi seaweed cheese avocado salmon egg tuna"></div> * @example //es5 * var maki = Chirashi.createElement('div') * Chirashi.addClass(maki, 'wasabi') //returns: <div class="wasabi"></div> * Chirashi.addClass(maki, 'seaweed, cheese') //returns: <div class="wasabi seaweed cheese"></div> * Chirashi.addClass(maki, 'avocado salmon') //returns: <div class="wasabi seaweed cheese avocado salmon"></div> * Chirashi.addClass(maki, ['egg', 'tuna']) //returns: <div class="wasabi seaweed cheese avocado salmon egg tuna"></div> */ function addClass(elements, classes) { return _updateClassList(elements, 'add', classes); } var regex = /(([#.]?)([\w-_]+))|(\[([\w-_]+)(=([\w.{}:'"]+))?])/g; /** * Creates a dom element from an HTML string, tag or css selector. * @param {string} string - The html string, tag or css selector. * @return {(HTMLElement|SVGElement)} element - The dom element created from the string. * @example //esnext * import { createElement } from 'chirashi' * const maki = createElement('a#sushi.link[data-href="chirashijs.org"][data-link]') //returns: <a class="link" id="sushi" data-href="chirashijs.org" data-link></a> * const greetings = createElement('<h1>Hello <strong>World</strong>!</h1>') //returns: <h1>Hello <strong>World</strong>!</h1> * @example //es5 * var maki = Chirashi.createElement('a#sushi.link[data-href="chirashijs.org"][data-link]') //returns: <a class="link" id="sushi" data-href="chirashijs.org" data-link></a> * var greetings = Chirashi.createElement('<h1>Hello <strong>World</strong>!</h1>') //returns: <h1>Hello <strong>World</strong>!</h1> */ function createElement(string) { if (string.indexOf('<') === -1) { var core = null; var attributes = ''; var className = ''; var segment = void 0; while (segment = regex.exec(string)) { if (typeof segment[5] !== 'undefined') { // attribute attributes += ' ' + segment[5] + (typeof segment[7] !== 'undefined' ? '=' + segment[7] : ''); } else { if (segment[2] === '.') { // className className += ' ' + segment[3]; } else if (segment[2] === '#') { // id attributes += ' id="' + segment[3] + '"'; } else { // tag core = segment[3]; } } } if (core === null) core = 'div'; string = '<' + core + (className ? ' class="' + className.slice(1) + '"' : '') + attributes + '></' + core + '>'; } var temp = document.createElement('div'); temp.innerHTML = string; var element = temp.firstChild; return element; } /** * Appends each node to element. * @param {(string|HTMLElement|SVGElement)} element - Selector or element. * @param {(Array|string|HTMLElement|SVGElement|Text)} nodes - Dom element, string or array of dom elements or strings. Strings will be passed to createElement then append. * @return {(HTMLElement|SVGElement|boolean)} element - The element for chaining or false if nodes can't be appended. * @example //esnext * import { createElement, append } from 'chirashi' * const maki = createElement('.maki') * append(maki, '.salmon[data-fish="salmon"]') //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div></div> * const avocado = createElement('.avocado') * append(maki, [avocado, '.cheese[data-cheese="cream"]']) //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div><div class="avocado"></div><div class="cheese" data-cheese="cream"></div></div> * @example //es5 * var maki = Chirashi.createElement('.maki') * Chirashi.append(maki, '.salmon[data-fish="salmon"]') //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div></div> * var avocado = Chirashi.createElement('.avocado') * Chirashi.append(maki, [avocado, '.cheese[data-cheese="cream"]']) //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div><div class="avocado"></div><div class="cheese" data-cheese="cream"></div></div> */ function append(element, nodes) { element = getElement(element); if (!element || !element.appendChild) return false; forEach(nodes, function (node, index) { if (typeof node === 'string') { element.appendChild(createElement(node)); } else if (isDomElement(node)) { element.appendChild(node); } }, true); return element; } /** * Get the value for the property name on the element. * @param {(string|Array|NodeList|HTMLCollection|document|HTMLElement|SVGElement)} element - The selector or dom element. * @param {string} property - The name of the property. * @return {*} value - The value for the property or null if no element found. * @example //esnext * import { createElement, append, getProp } from 'chirashi' * const maki = createElement('.maki') * append(maki, '.salmon') * getProp(maki, 'firstChild') //returns: <div class="salmon"></div> * @example //es5 * var maki = Chirashi.createElement('.maki') * Chirashi.append(maki, '.salmon') * Chirashi.getProp(maki, 'firstChild') //returns: <div class="salmon"></div> */ function getProp(element, property) { element = getElement(element); return element ? element[property] : null; } /** * Returns an array of element's children. * @param {(string|HTMLElement|SVGElement)} element - Selector or element. * @return {(Array|boolean)} children - Array of element's children or false if elements has no children property or isn't a dom element. * @return {function} children.chrshPush - Methods to push dom elements into the array. Accepts same input as getElements. * @example //esnext * import { createElement, append, children } from 'chirashi' * const maki = createElement('.maki') * append(maki, ['.salmon', '.avocado']) * children(maki) //returns: [<div class="salmon"></div>, <div class="avocado"></div>] * @example //es5 * const maki = Chirashi.createElement('.maki') * Chirashi.append(maki, ['.salmon', '.avocado']) * Chirashi.children(maki) //returns: [<div class="salmon"></div>, <div class="avocado"></div>] */ function children(element) { var children = getProp(element, 'children'); return !!children && _chirasizeArray([].concat(toConsumableArray(children))); } /** * Clones element. * @param {(string|HTMLElement|SVGElement)} element - Selector or element. * @return {(string|HTMLElement|SVGElement|boolean)} clone - element's clone or false if element isn't a dom element or can't be cloned. * @example //esnext * import { createElement, append, clone } from 'chirashi' * const maki = createElement('.maki') * clone(maki) //returns: <div class="maki"></div> * const sushi = createElement('.sushi') * append(document.body, sushi) * clone('.sushi') //returns: <div class="sushi"></div> * @example //es5 * var maki = Chirashi.createElement('.maki') * Chirashi.clone(maki) //returns: <div class="maki"></div> * var sushi = Chirashi.createElement('.sushi') * Chirashi.append(document.body, sushi) * Chirashi.clone('.sushi') //returns: <div class="sushi"></div> */ function clone(element) { element = getElement(element); return !!element && 'cloneNode' in element && element.cloneNode(true); } /** * Get closest element matching the tested selector or tested element traveling up the DOM tree from element to limit. * @param {(string|HTMLElement|SVGElement|Text)} element - Selector or element. * @param {(string|HTMLElement|SVGElement|Text)} tested - The selector or dom element to match. * @param {(string|document|HTMLElement|SVGElement)} [limit=document] - Returns false when this selector or element is reached. * @return {(boolean|HTMLElement|SVGElement|Text)} matchedElement - The matched element or false. * @example //esnext * import { createElement, append, closest } from 'chirashi' * const maki = createElement('.maki') * const cheese = createElement('.cheese') * append(maki, cheese) * append(cheese, '.avocado') * append(document.body, maki) * closest('.avocado', '.maki') //returns: <div class="maki"></div> * closest('.avocado', '.maki', '.cheese') //returns: false * @example //es5 * var maki = Chirashi.createElement('.maki') * var cheese = Chirashi.createElement('.cheese') * Chirashi.append(maki, cheese) * Chirashi.append(cheese, '.avocado') * Chirashi.append(document.body, maki) * Chirashi.closest('.avocado', '.maki') //returns: <div class="maki"></div> * Chirashi.closest('.avocado', '.maki', '.cheese') //returns: false */ function closest(element, tested) { var limit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : document; element = getElement(element); if (!element || (typeof limit === 'string' ? element.matches(limit) : element === limit)) { return false; } if (typeof tested === 'string' ? element.matches(tested) : element === tested) { return element; } return !!element.parentNode && closest(element.parentNode, tested, limit); } /** * Iterates over elements, returning an array of all elements matching tested selector. * @param {(string|Array|NodeList|HTMLCollection|window|document|HTMLElement|SVGElement|Text)} elements - The iterable, selector or elements. * @param {(string|HTMLElement|SVGElement|Text)} tested - The selector or dom element to match. * @return {Array} matching - The array of filtered elements. * @example //esnext * import { createElement, append, filter } from 'chirashi' * const salmonMaki = createElement('.salmon.maki') * const tunaMaki = createElement('.tuna.maki') * const salmonSushi = createElement('.salmon.sushi') * const tunaSushi = createElement('.tuna.sushi') * append(document.body, [salmonMaki, tunaMaki, salmonSushi, tunaSushi]) * filter('div', '.salmon') //returns: [<div class="salmon sushi"></div>, <div class="salmon maki"></div>] * filter([salmonMaki, tunaMaki, salmonSushi, tunaSushi], '.maki') //returns: [<div class="salmon maki"></div>, <div class="tuna maki"></div>] * filter('div', '.salmon') //returns: [<div class="salmon sushi"></div>, <div class="salmon maki"></div>] * @example //es5 * var salmonMaki = Chirashi.createElement('.salmon.maki') * var tunaMaki = Chirashi.createElement('.tuna.maki') * var salmonSushi = Chirashi.createElement('.salmon.sushi') * var tunaSushi = Chirashi.createElement('.tuna.sushi') * Chirashi.append(document.body, [salmonMaki, tunaMaki, salmonSushi, tunaSushi]) * Chirashi.filter('div', '.salmon') //returns: [<div class="salmon sushi"></div>, <div class="salmon maki"></div>] * Chirashi.filter([salmonMaki, tunaMaki, salmonSushi, tunaSushi], '.maki') //returns: [<div class="salmon maki"></div>, <div class="tuna maki"></div>] * Chirashi.filter('div', '.salmon') //returns: [<div class="salmon sushi"></div>, <div class="salmon maki"></div>] */ function filter(elements, tested) { var matching = []; forElements(elements, function (element) { if (typeof tested === 'string' && 'matches' in element && element.matches(tested) || element === tested) { matching.push(element); } }); return _chirasizeArray(matching); } /** * Iterates over each element of elements and returns an array containing all elements' children matching a selector. * @param {(string|Array|NodeList|HTMLCollection|document|HTMLElement|SVGElement)} elements - The iterable, selector or elements. * @param {string} selector - The selector. * @return {Array} found - The elements' children matching the selector. * @return {function} found.chrshPush - Methods to push dom elements into the array. Accepts same input as getElements. * @example //esnext * import { createElement, append, find } from 'chirashi' * const maki = createElement('.maki') * append(maki, ['.salmon[data-fish][data-inside]', '.avocado[data-inside]']) * const roll = createElement('.roll') * append(roll, '.tuna[data-fish][data-inside]') * append(document.body, [maki, roll]) * find('div', '[data-fish]') //returns: [<div class="salmon" data-fish data-inside></div>, <div class="tuna" data-fish data-inside></div>] * find(maki, '[data-inside]') //returns: [<div class="salmon" data-fish data-inside></div>, <div class="avocado" data-inside></div>] * @example //es5 * var maki = Chirashi.createElement('.maki') * Chirashi.append(maki, ['.salmon[data-fish][data-inside]', '.avocado[data-inside]']) * var roll = Chirashi.createElement('.roll') * Chirashi.append(roll, '.tuna[data-fish][data-inside]') * Chirashi.append(document.body, [maki, roll]) * Chirashi.find('div', '[data-fish]') //returns: [<div class="salmon" data-fish data-inside></div>, <div class="tuna" data-fish data-inside></div>] * Chirashi.find(maki, '[data-inside]') //returns: [<div class="salmon" data-fish data-inside></div>, <div class="avocado" data-inside></div>] */ function find(elements, selector) { var found = []; forElements(elements, function (element) { if (!('querySelectorAll' in element)) return; found.push.apply(found, toConsumableArray(element.querySelectorAll(selector))); }); return _chirasizeArray(found); } /** * Find the first element's child matching the selector. * @param {(string|Array|NodeList|HTMLCollection|document|HTMLElement|SVGElement)} elements - The iterable, selector or elements. * @param {string} selector - The selector to match. * @return {(HTMLElement|SVGElement|null)} element - The first child of elements matching the selector or null. * @example //esnext * import { createElement, append, find } from 'chirashi' * const maki = createElement('.maki') * append(maki, ['.salmon[data-fish][data-inside]', '.avocado[data-inside]']) * const roll = createElement('.roll') * append(roll, '.tuna[data-fish][data-inside]') * append(document.body, [maki, roll]) * findOne('div', '[data-fish]') //returns: <div class="salmon" data-fish data-inside></div> * findOne(maki, '[data-inside]') //returns: <div class="salmon" data-fish data-inside></div> * @example //es5 * var maki = Chirashi.createElement('.maki') * Chirashi.append(maki, ['.salmon[data-fish][data-inside]', '.avocado[data-inside]']) * var roll = Chirashi.createElement('.roll') * Chirashi.append(roll, '.tuna[data-fish][data-inside]') * Chirashi.append(document.body, [maki, roll]) * Chirashi.findOne('div', '[data-fish]') //returns: <div class="salmon" data-fish data-inside></div> * Chirashi.findOne(maki, '[data-inside]') //returns: <div class="salmon" data-fish data-inside></div> */ function findOne(element, selector) { element = getElement(element); return !!element && 'querySelector' in element ? element.querySelector(selector) : null; } /** * Get value for named attribute of element. * @param {(string|Array|NodeList|HTMLCollection|document|HTMLElement|SVGElement)} element - The selector or dom element. * @param {string} name - The attribute's name. * @return {(string|boolean)} value - The value for the attribute or false if no element found. * @example //esnext * import { createElement, getAttr } from 'chirashi' * const maki = createElement('.maki[data-fish="salmon"]') * getAttr(maki, 'data-fish') //returns: "salmon" * @example //es5 * const maki = Chirashi.createElement('.maki[data-fish="salmon"]') * Chirashi.getAttr(maki, 'data-fish') //returns: "salmon" */ function getAttr(element, name) { element = getElement(element); return !!element && element.getAttribute(name); } /** * Alias on getAttr prefixing name with 'data-'. * @param {(string|Array|NodeList|HTMLCollection|document|HTMLElement|SVGElement)} element - The selector or dom element. * @param {string} name - The data-attribute's name. * @return {(string|boolean)} value - The value for the data-attribute or false if no element found. * @example //esnext * import { createElement, getData } from 'chirashi' * const maki = createElement('.maki[data-fish="salmon"]') * getData(maki, 'fish') //returns: "salmon" * @example //es5 * const maki = Chirashi.createElement('.maki[data-fish="salmon"]') * Chirashi.getData(maki, 'fish') //returns: "salmon" */ function getData(element, name) { return getAttr(element, 'data-' + name); } /** * Get the inner html of an element. * @param {(string|Array|NodeList|HTMLCollection|document|HTMLElement|SVGElement)} element - The selector or dom element. * @return {(string|null)} innerHTML - The inner html of the element or null if no element found. * @example //esnext * import { createElement, setHtml, getHtml } from 'chirashi' * const maki = createElement('p.maki') * setHtml(maki, 'salmon') * getHtml(maki) //returns: "salmon" * @example //es5 * var maki = createElement('p.maki') * setHtml(maki, 'salmon') * getHtml(maki) //returns: "salmon" */ function getHtml(element) { return getProp(element, 'innerHTML'); } /** * Iterates over classes and test if element has each. * @param {(string|HTMLElement|SVGElement)} element - The selector or dom element. * @param {(string|string[])} classes - Array of classes, classes seperated by coma and/or spaces or single class. * @return {boolean} hasClass - Is true if element has all classes. * @example //esnext * import { createElement, hasClass } from 'chirashi' * const maki = createElement('.salmon.cheese.maki') * hasClass(maki, 'salmon cheese') //returns: true * hasClass(maki, ['salmon', 'avocado']) //returns: false * @example //es5 * var maki = Chirashi.createElement('.salmon.cheese.maki') * Chirashi.hasClass(maki, 'salmon cheese') //returns: true * Chirashi.hasClass(maki, ['salmon', 'avocado']) //returns: false */ function hasClass(element, classes) { element = getElement(element); if (!element || !element.classList) return; classes = _stringToArray(classes); var i = classes.length; var found = void 0; while (i-- && (found = element.classList.contains(classes[i]))) {} return found; } /** * Returns index of element in parent's children. * @param {(string|HTMLElement|SVGElement|Text)} element - The selector or dom element. * @return {(number|null)} index - The position of element in his parent's children or null if no element found. * @example //esnext * import { createElement, append, indexInParent } from 'chirashi' * const maki = createElement('.maki') * append(document.body, maki) * append(maki, ['.salmon[data-fish="salmon"]', '.cheese[data-cheese="cream"]']) //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div><div class="cheese" data-cheese="cream"></div></div> * indexInParent('.cheese') //returns: 1 * @example //es5 * var maki = Chirashi.createElement('.maki') * Chirashi.append(document.body, maki) * Chirashi.append(maki, ['.salmon[data-fish="salmon"]', '.cheese[data-cheese="cream"]']) //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div><div class="cheese" data-cheese="cream"></div></div> * Chirashi.indexInParent('.cheese') //returns: 1 */ function indexInParent(element) { element = getElement(element); if (!element) return null; var current = element; var i = 0; while (current = current.previousElementSibling) { ++i; }return i; } /** * Insert nodes after element in his parent. * @param {(string|HTMLElement|SVGElement|Text)} element - The selector or dom element. * @param {(Array|string|HTMLElement|SVGElement|Text)} nodes - Array of dom elements or string to create it using createElement. * @return {(HTMLElement|SVGElement|undefined)} element - The element for chaining or undefined if no element found or element has no parent. * @example //esnext * import { createElement, append, insertAfter } from 'chirashi' * const maki = createElement('.maki') * append(document.body, maki) * append(maki, ['.salmon[data-fish="salmon"]', '.cheese[data-cheese="cream"]']) * insertAfter('.salmon', ['.avocado', '.wasabi']) //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div><div class="avocado"></div><div class="wasabi"></div><div class="cheese" data-cheese="cream"></div></div> * @example //es5 * var maki = Chirashi.createElement('.maki') * Chirashi.append(document.body, maki) * Chirashi.append(maki, ['.salmon[data-fish="salmon"]', '.cheese[data-cheese="cream"]']) * Chirashi.insertAfter('.salmon', ['.avocado', '.wasabi']) //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div><div class="avocado"></div><div class="wasabi"></div><div class="cheese" data-cheese="cream"></div></div> */ function insertAfter(element, nodes) { element = getElement(element); if (!element || !('parentNode' in element)) return; var parent = element.parentNode; forEach(nodes, function (node, index) { if (typeof node === 'string') { node = createElement(node); } if (isDomElement(node)) parent.insertBefore(node, element.nextElementSibling); }, true); return element; } /** * Insert nodes before element in his parent. * @param {(string|HTMLElement|SVGElement|Text)} element - The selector or dom element. * @param {(Array|string|HTMLElement|SVGElement|Text)} nodes - Array of dom elements or string to create it using createElement. * @return {(HTMLElement|SVGElement|undefined)} element - The element for chaining or undefined if no element found or element has no parent. * @example //esnext * import { createElement, append, insertBefore } from 'chirashi' * const maki = createElement('.maki') * append(document.body, maki) * append(maki, ['.salmon[data-fish="salmon"]', '.cheese[data-cheese="cream"]']) * insertBefore('.cheese', ['.avocado', '.wasabi']) //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div><div class="avocado"></div><div class="wasabi"></div><div class="cheese" data-cheese="cream"></div></div> * @example //es5 * var maki = Chirashi.createElement('.maki') * Chirashi.append(document.body, maki) * Chirashi.append(maki, ['.salmon[data-fish="salmon"]', '.cheese[data-cheese="cream"]']) * Chirashi.insertBefore('.cheese', ['.avocado', '.wasabi']) //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div><div class="avocado"></div><div class="wasabi"></div><div class="cheese" data-cheese="cream"></div></div> */ function insertBefore(element, nodes) { element = getElement(element); if (!element || !('parentNode' in element)) return; var parent = element.parentNode; forEach(nodes, function (node, index) { if (typeof node === 'string') { node = createElement(node); } if (isDomElement(node)) parent.insertBefore(node, element); }, true); return element; } /** * Get the next sibling of element. * @param {(string|HTMLElement|SVGElement|Text)} element - The selector or dom element. * @return {(HTMLElement|SVGElement|Text|null)} nextElement - The element's next sibling or null if no element found. * @example //esnext * import { createElement, append, next } from 'chirashi' * const maki = createElement('.maki') * append(maki, '.salmon[data-fish="salmon"]') //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div></div> * const avocado = createElement('.avocado') * append(maki, [avocado, '.cheese[data-cheese="cream"]']) //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div><div class="avocado"></div><div class="cheese" data-cheese="cream"></div></div> * next(avocado) //returns: <div class="cheese" data-cheese="cream"></div> * @example //es5 * var maki = Chirashi.createElement('.maki') * Chirashi.append(maki, '.salmon[data-fish="salmon"]') //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div></div> * var avocado = Chirashi.createElement('.avocado') * Chirashi.append(maki, [avocado, '.cheese[data-cheese="cream"]']) //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div><div class="avocado"></div><div class="cheese" data-cheese="cream"></div></div> * Chirashi.next(avocado) //returns: <div class="cheese" data-cheese="cream"></div> */ function next(element) { return getProp(element, 'nextElementSibling'); } /** * Returns the parent node of the element. * @param {(string|document|HTMLElement|SVGElement|Text)} element - The selector or dom element. * @return {(document|HTMLElement|SVGElement|null)} parentElement - The parent node or null if no element found. * @example //esnext * import { createElement, append, parent } from 'chirashi' * const maki = createElement('.maki') * append(document.body, maki) * append(maki, '.salmon[data-fish="salmon"]') //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div></div> * parent('.salmon') //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div></div> * @example //es5 * var maki = Chirashi.createElement('.maki') * append(maki * Chirashi.append(document.body, maki) * Chirashi.append(maki, '.salmon[data-fish="salmon"]') //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div></div> * Chirashi.parent('.salmon') //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div></div> */ function parent(element) { return getProp(element, 'parentNode'); } /** * Get the previous sibling of element. * @param {(string|HTMLElement|SVGElement|Text)} element - The selector or dom element. * @return {(HTMLElement|SVGElement|Text|null)} previousElement - The element's previous sibling or null if no element found. * @example //esnext * import { createElement, append, prev } from 'chirashi' * const maki = createElement('.maki') * append(maki, '.salmon[data-fish="salmon"]') //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div></div> * const avocado = createElement('.avocado') * append(maki, [avocado, '.cheese[data-cheese="cream"]']) //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div><div class="avocado"></div><div class="cheese" data-cheese="cream"></div></div> * prev(avocado) //returns: <div class="salmon" data-fish="salmon"></div> * @example //es5 * var maki = Chirashi.createElement('.maki') * Chirashi.append(maki, '.salmon[data-fish="salmon"]') //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div></div> * var avocado = Chirashi.createElement('.avocado') * Chirashi.append(maki, [avocado, '.cheese[data-cheese="cream"]']) //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div><div class="avocado"></div><div class="cheese" data-cheese="cream"></div></div> * Chirashi.prev(avocado) //returns: <div class="salmon" data-fish="salmon"></div> */ function prev(element) { return getProp(element, 'previousElementSibling'); } /** * Iterates over elements and removes it from DOM. * @param {(string|HTMLElement|SVGElement|Text)} element - The selector or dom element. * @return {Array} domElements - The removed elements. * @return {function} domElements.chrshPush - Methods to push dom elements into the array. Accepts same input as getElements. * @example //esnext * import { createElement, append, remove } from 'chirashi' * const maki = createElement('.maki') * append(document.body, maki) * append(maki, '.salmon[data-fish="salmon"]') //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div></div> * const avocado = createElement('.avocado') * append(maki, [avocado, '.cheese[data-cheese="cream"]']) //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div><div class="avocado"></div><div class="cheese" data-cheese="cream"></div></div> * remove('.cheese') //returns: [<div class="cheese" data-cheese="cream"></div>] * @example //es5 * var maki = Chirashi.createElement('.maki') * Chirashi.append(document.body, maki) * Chirashi.append(maki, '.salmon[data-fish="salmon"]') //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div></div> * var avocado = Chirashi.createElement('.avocado') * Chirashi.append(maki, [avocado, '.cheese[data-cheese="cream"]']) //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div><div class="avocado"></div><div class="cheese" data-cheese="cream"></div></div> * Chirashi.remove('.cheese') //returns: [<div class="cheese" data-cheese="cream"></div>] */ function remove(elements) { return forElements(elements, function (element) { if (!element.parentNode) return; element.parentNode.removeChild(element); }); } function _applyForEach(elements, method, args) { return forElements(elements, function (element) { if (!element[method]) return; forEach(args, function (arg) { element[method](arg); }); }); } /** * Iterates over attributes and removes it from each element of elements. * @param {(string|Array|NodeList|HTMLCollection|HTMLElement|SVGElement)} elements - The iterable, selector or elements. * @param {Array | string} attributes - Array of attributes' name, string of attributes' name seperated by space and/or comas or name of a single attribute. * @return {Array} domElements - The array of dom elements from elements. * @return {function} domElements.chrshPush - Methods to push dom elements into the array. Accepts same input as getElements. * @example //esnext * import { createElement, append, removeAttr } from 'chirashi' * const maki = createElement('.maki') * append(document.body, maki) * append(maki, ['.salmon[data-fish="salmon"]', '.cheese[data-cheese="cream"]']) //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div><div class="cheese" data-cheese="cream"></div></div> * removeAttr('.salmon', 'data-fish') //returns: [<div class="salmon"></div>] * @example //es5 * var maki = Chirashi.createElement('.maki') * Chirashi.append(document.body, maki) * Chirashi.append(maki, ['.salmon[data-fish="salmon"]', '.cheese[data-cheese="cream"]']) //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div><div class="cheese" data-cheese="cream"></div></div> * Chirashi.removeAttr('.salmon', 'data-fish') //returns: [<div class="salmon"></div>] */ function removeAttr(elements, attributes) { return _applyForEach(elements, 'removeAttribute', _stringToArray(attributes)); } /** * Iterates over classes and remove it from each element of elements. * @param {(string|Array|NodeList|HTMLCollection|window|document|HTMLElement|SVGElement|Text)} elements - The iterable, selector or elements. * @param {(string|string[])} classes - Array of classes or string of classes seperated with comma and/or spaces. * @return {Array} domElements - The array of dom elements from elements. * @return {function} domElements.chrshPush - Methods to push dom elements into the array. Accepts same input as getElements. * @example //esnext * import { createElement, removeClass } from 'chirashi' * const maki = createElement('.maki.salmon.cheese.wasabi') //returns: <div class="maki salmon cheese wasabi"></div> * removeClass(maki, 'cheese, wasabi') //returns: [<div class="maki salmon"></div>] * @example //es5 * var maki = Chirashi.createElement('.maki.salmon.cheese.wasabi') //returns: <div class="maki salmon cheese wasabi"></div> * Chirashi.removeClass(maki, 'cheese, wasabi') //returns: [<div class="maki salmon"></div>] */ function removeClass(elements, classes) { return _updateClassList(elements, 'remove', classes); } /** * Iterates over attributes and removes it from each element of elements. * @param {(string|Array|NodeList|HTMLCollection|HTMLElement|SVGElement)} elements - The iterable, selector or elements. * @param {(string|string[])} attributes - Array of attributes' name, string of attributes' name seperated by space and/or comas or name of a single attribute. * @return {Array} domElements - The array of dom elements from elements. * @return {function} domElements.chrshPush - Methods to push dom elements into the array. Accepts same input as getElements. * @example //esnext * import { createElement, append, removeData } from 'chirashi' * const maki = createElement('.maki') * append(document.body, maki) * append(maki, ['.salmon[data-fish="salmon"]', '.cheese[data-cheese="cream"]']) //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div><div class="cheese" data-cheese="cream"></div></div> * removeData('.salmon', 'fish') //returns: [<div class="salmon"></div>] * @example //es5 * var maki = Chirashi.createElement('.maki') * Chirashi.append(document.body, maki) * Chirashi.append(maki, ['.salmon[data-fish="salmon"]', '.cheese[data-cheese="cream"]']) //returns: <div class="maki"><div class="salmon" data-fish="salmon"></div><div class="cheese" data-cheese="cream"></div></div> * Chirashi.removeData('.salmon', 'fish') //returns: [<div class="salmon"></div>] */ function removeData(elements, attributes) { return _applyForEach(elements, 'removeAttribute', _stringToArray(attributes, 'data-')); } /** * Iterates over attributes as key value pairs and apply on each element of elements. * @param {Array | string | HTMLElement | SVGElement} elements - The iterable, selector or elements. * @param {Object} - The attributes key value pairs. * @return {Array} domElements - The array of dom elements from elements. * @return {function} domElements.chrshPush - Methods to push dom elements into the array. Accepts same input as getElements. * @example //esnext * import { createElement, setAttr } from 'chirashi' * const maki = createElement('.maki') * setAttr(maki, { * dataFish: 'salmon' * }) //returns: [<div class="maki" data-fish="salmon">] * @example //es5 * var maki = Chirashi.createElement('.maki') * Chirashi.setAttr(maki, { * dataFish: 'salmon' * }) //returns: [<div class="maki" data-fish="salmon">] */ function setAttr(elements, attributes) { forIn(attributes, function (name, value) { if (typeof value !== 'string' && !(value instanceof Array)) { attributes[name] = JSON.stringify(value); } }); return forElements(elements, function (element) { forIn(attributes, function (name, value) { element.setAttribute(name, value); }); }); } /** * Iterates over data-attributes as key value pairs and apply on each element of elements. * @param {Array | string | HTMLElement | SVGElement} elements - The iterable, selector or elements. * @param {Object} - The data-attributes key value pairs. * @return {Array} domElements - The array of dom elements from elements. * @return {function} domElements.chrshPush - Methods to push dom elements into the array. Accepts same input as getElements. * @example //esnext * import { createElement, setData } from 'chirashi' * const maki = createElement('.maki') * setData(maki, { * fish: 'salmon' * }) //returns: [<div class="maki" data-fish="salmon">] * @example //es5 * var maki = Chirashi.createElement('.maki') * Chirashi.setData(maki, { * fish: 'salmon' * }) //returns: [<div class="maki" data-fish="salmon">] */ function setData(elements, dataAttributes) { var attributes = {}; forIn(dataAttributes, function (name, value) { attributes['data-' + name] = value; }); return setAttr(elements, attributes); } /** * Apply props as key value pairs on each element of elements. * @param {(string|Array|NodeList|HTMLCollection|document|HTMLElement|SVGElement)} elements - The iterable, selector or elements. * @param {Object} - The props key value pairs. * @return {Array} domElements - The removed elements. * @return {function} domElements.chrshPush - Methods to push dom elements into the array. Accepts same input as getElements. * @example //esnext * import { createElement, setProp, getProp } from 'chirashi' * const maki = createElement('input.maki') * setProp(maki, { value: 'こんにちは世界' }) * getProp(maki, 'value') //returns: こんにちは世界 * @example //es5 * var maki = Chirashi.createElement('input.maki') * Chirashi.setProp(maki, { value: 'こんにちは世界' }) * Chirashi.getProp(maki, 'value') //returns: こんにちは世界 */ function setProp(elements, props) { return forElements(elements, function (element) { return Object.assign(element, props); }); } /** * Set the inner html of elements. * @param {Array | string | HTMLElement | SVGElement} elements - The iterable, selector or elements. * @param {string} html - The html to insert. * @return {Array} domElements - The removed elements. * @return {function} domElements.chrshPush - Methods to push dom elements into the array. Accepts same input as getElements. * @example //esnext * import { createElement, setHtml, getHtml } from 'chirashi' * const maki = createElement('p.maki') * setHtml(maki, 'salmon') //returns: [<p class="maki">salmon</p>] * getHtml(maki) //returns: "salmon" * @example //es5 * var maki = createElement('p.maki') * setHtml(maki, 'salmon') //returns: [<p class="maki">salmon</p>] * getHtml(maki) //returns: "salmon" */ function setHtml(elements, html) { return setProp(elements, { 'innerHTML': html }); } /** * Iterates over classes and toggle it on each element of elements. * @param {(string|Array|NodeList|HTMLCollection|window|document|HTMLElement|SVGElement|Text)} elements - The iterable, selector or elements. * @param {(string|Array|Object)} classes - Array of classes or string of classes seperated with comma and/or spaces. Or object with keys being the string of classes seperated with comma and/or spaces and values function returning a booleanean. * @return {Array} domElements - The removed elements. * @return {function} domElements.chrshPush - Methods to push dom elements into the array. Accepts same input as getElements. * @example //esnext * import { createElement, toggleClass, clone, setData, getData } from 'chirashi' * const maki = createElement('.wasabi.salmon.maki') //returns: <div class="maki salmon wasabi"></div> * const sushi = createElement('.salmon.sushi') //returns: <div class="sushi salmon"></div> * toggleClass([maki, sushi], 'wasabi') //returns: [<div class="maki salmon"></div>, <div class="sushi salmon wasabi"></div>] * const scdMaki = clone(maki) * setData(maki, { for: 'leonard' }) * setData(scdMaki, { for: 'sheldon' }) * toggleClass([maki, scdMaki], { * cheese: element => { * return getData(element, 'for') !== 'leonard' * } * }) //returns: [<div class="maki salmon cheese" data-for="sheldon"></div>, <div class="maki salmon" data-for="leonard"></div>] * @example //es5 * var maki = Chirashi.createElement('.wasabi.salmon.maki') //returns: <div class="wasabi salmon maki"></div> * var sushi = Chirashi.createElement('.salmon.sushi') //returns: <div class="salmon sushi"></div> * Chirashi.toggleClass([maki, sushi], 'wasabi') //returns: [<div class="maki salmon"></div>, <div class="sushi salmon wasabi"></div>] * var scdMaki = Chirashi.clone(maki) * Chirashi.setData(maki, { for: 'leonard' }) * Chirashi.setData(scdMaki, { for: 'sheldon' }) * Chirashi.toggleClass([maki, scdMaki], { * cheese: function (element) { * return Chirashi.getData(element, 'for') !== 'leonard' * } * }) //returns: [<div class="maki salmon cheese" data-for="sheldon"></div>, <div class="maki salmon" data-for="leonard"></div>] */ function toggleClass(elements, input) { if (input instanceof Array || typeof input === 'string') { var _ret = function () { var classes = _stringToArray(input); return { v: forElements(elements, function (element) { if (!element.classList) return; forEach(classes, function (className) { element.classList.toggle(className); }); }) }; }(); if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; } else { return forElements(elements, function (element) { if (!element.classList) return; forIn(input, function (classes, condition) { var toggle = condition(element); forEach(_stringToArray(classes), function (className) { element.classList.toggle(className, toggle); }); }); }); } } function _setEvents(elements, method, input) { method += 'EventListener'; return forElements(elements, function (element) { forIn(input, function (events, callback) { forEach(_stringToArray(events), function (event) { return element[method](event, callback); }); }); }); } /** * Bind events listener on each element of elements. * @param {(string|Array|NodeList|HTMLCollection|window|document|HTMLElement|SVGElement)} elements - The iterable, selector or elements. * @param {Object.<string, eventCallback>} input - An object in which keys are events to bind seperated with coma and/or spaces and values are eventCallbacks. * @return {Object} object - An object with off method to remove events listeners. * @return {offCallback} object.off - The off method. * @example //esnext * import { createElement, append, on, trigger } from 'chirashi' * const maki = createElement('a.cheese.maki') * const sushi = createElement('a.wasabi.sushi') * append(document.body, [maki, sushi]) * const listener = on('.cheese, .wasabi', { * click(e, target) => { * console.log('clicked', target) * }, * 'mouseenter mousemove': (e, target) => { * console.log('mouse in', target) * } * }) * trigger(maki, 'click') //simulate user's click * // LOGS: "clicked" <a class="maki cheese"></a> * trigger(sushi, 'click') //simulate user's click * // LOGS: "clicked" <a class="sushi wasabi"></a> * listener.off(maki, 'click') //remove click event listener on maki * listener.off() //remove all listeners from all elements * @example //es5 * var listener = Chirashi.bind('.cheese, .wasabi', { * 'click': function (e, target) { * console.log('clicked', target) * }, * 'mouseenter mousemove': function(e, target) { * console.log('mouse in', target) * } * }) * var maki = Chirashi.createElement('a.cheese.maki') * var sushi = Chirashi.createElement('a.wasabi.sushi') * Chirashi.append(document.body, [maki, sushi]) * Chirashi.trigger(maki, 'click') //simulate user's click * // LOGS: "clicked" <a class="maki cheese"></a> * Chirashi.trigger(sushi, 'click') //simulate user's click * // LOGS: "clicked" <a class="sushi wasabi"></a> * listener.off(maki, 'click') //remove click event listener on maki * listener.off() //remove all listeners from all elements */ function on(elements, input) { elements = _setEvents(elements, 'add', input); return { off: function off(offElements, events) { _setEvents(offElements || elements, 'remove', events ? defineProperty({}, events, input[events]) : input); } }; } /** * Callback to execute on event. * @callback eventCallback * @param {Event} event - Triggered event. */ /** * Called to remove one or all events listeners of one or all elements. * @callback offCallback * @param {(string|Array|NodeList|HTMLCollection|window|document|HTMLElement|SVGElement)} [offElements] - The iterable, selector or elements to unbind. * @param {string} [events] - The events to unbind. Must be provided in the same syntax as in input. */ /** * Bind events listener on delegate and execute callback when target matches selector (targets doesn't have to be in the DOM at binding). * @param {string} selector - The selector to match. * @param {Object.<string, bindCallback>} input - An object in which keys are events to bind seperated with coma and/or spaces and values are bindCallbacks. * @return {Object} object - An object with unbind method for unbinding. * @return {unbindCallback} object.unbind - The unbind method. * @example //esnext * import { createElement, append, bind, trigger } from 'chirashi' * const listener = bind('.cheese, .wasabi', { * click(e, target) => { * console.log('clicked', target) * }, * 'mouseenter mousemove': (e, target) => { * console.log('mouse in', target) * } * }) * const maki = createElement('a.cheese.maki') * const sushi = createElement('a.wasabi.sushi') * append(document.body, [maki, sushi]) * trigger(maki, 'click') //simulate user's click * // LOGS: "clicked" <a class="maki cheese"></a> * trigger(sushi, 'click') //simulate user's click * // LOGS: "clicked" <a class="sushi wasabi"></a> * listener.unbind('mouseenter mousemove') //remove mouseenter and mousemove listeners * listener.unbind() //remove all listeners * @example //es5 * var listener = Chirashi.bind('.cheese, .wasabi', { * 'click': function (e, target) { * console.log('clicked', target) * }, * 'mouseenter mousemove': function(e, target) { * console.log('mouse in', target) * } * }) * var maki = Chirashi.createElement('a.cheese.maki') * var sushi = Chirashi.createElement('a.wasabi.sushi') * Chirashi.append(document.body, [maki, sushi]) * Chirashi.trigger(maki, 'click') //simulate user's click * // LOGS: "clicked" <a class="maki cheese"></a> * Chirashi.trigger(sushi, 'click') //simulate user's click * // LOGS: "clicked" <a class="sushi wasabi"></a> * listener.unbind('mouseenter mousemove') //remove mouseenter and mousemove listeners * listener.unbind() //remove all listeners */ function bind(selector, input) { var delegate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : document.body; var eventsObj = {}; forIn(input, function (events, callback) { eventsObj[events] = function (event) { var target = closest(event.target, selector, delegate); if (target) callback(event, target); }; }); var bound = on(delegate, eventsObj); return { unbind: function unbind(events) { bound.off(delegate, events); } }; } /** * Callback to execute on event using delegate. * @callback bindCallback * @param {Event} event - Triggered event. * @param {HTMLElement | SVGElement} target - Target of the event. */ /** * Called to unbind one or all events. * @callback unbindCallback * @param {string} [events] - The events to unbind. Must be provided in the same syntax as in input. */ /** * Bind events listener on each element of elements and unbind after first triggered. * @param {(string|Array|NodeList|HTMLCollection)} elements - The iterable or selector * @param {Object.<string, eventCallback>} input - An object in which keys are events to bind seperated with coma and/or spaces and values are eventCallbacks. * @param {boolean} [eachElement=false] - If true only current target's events listeners will be removed after trigger. * @param {boolean} [eachEvent=false] - If true only triggered event group of events listeners will be removed. * @return {Object} cancelObject - An object with cancel method for unbinding. * @return {Object.cancel} cancel - cancel method. * @example //esnext * import { createElement, append, once, trigger } from 'chirashi' * const maki = createElement('a.cheese.maki') * const sushi = createElement('a.wasabi.sushi') * append(document.body, [maki, sushi]) * const listener = once('.cheese, .wasabi', { * click(e, target) => { * console.log('clicked', target) * }, * 'mouseenter mousemove': (e, target) => { * console.log('mouse in', target) * } * }, true, true) * trigger(maki, 'click') //simulate user's click * // LOGS: "clicked" <a class="maki cheese"></a> * // click event listener was auto-removed from maki * trigger(sushi, 'click') //simulate user's click * // LOGS: "clicked" <a class="sushi wasabi"></a> * // click event listener was auto-removed from sushi * listener.cancel() //remove all listeners from all elements * const listener2 = once('.cheese, .wasabi', { * click(e, target) => { * console.log('clicked', target) * } * }) * trigger(maki, 'click') //simulate user's click * // LOGS: "clicked" <a class="maki cheese"></a> * // all events listeners were auto-removed from all elements * trigger(sushi, 'click') //simulate user's click * // won't log anything * @example //es5 * var maki = Chirashi.createElement('a.cheese.maki') * var sushi = Chirashi.createElement('a.wasabi.sushi') * Chirashi.append(document.body, [maki, sushi]) * var listener = Chirashi.once('.cheese, .wasabi', { * click: function (e, target) { * console.log('clicked', target) * }, * 'mouseenter mousemove': function (e, target) { * console.log('mouse in', target) * } * }, true, true) * Chirashi.trigger(maki, 'click') //simulate user's click * // LOGS: "clicked" <a class="maki cheese"></a> * // click event listener was auto-removed from maki * Chirashi.trigger(sushi, 'click') //simulate user's click * // LOGS: "clicked" <a class="sushi wasabi"></a> * // click event listener was auto-removed from sushi * listener.cancel() //remove all listeners from all elements * var listener2 = Chirashi.once('.cheese, .wasabi', { * click: function (e, target) { * console.log('clicked', target) * } * }) * Chirashi.trigger(maki, 'click') //simulate user's click * // LOGS: "clicked" <a class="maki cheese"></a> * // all events listeners were auto-removed from all elements * Chirashi.trigger(sushi, 'click') //simulate user's click * // won't log anything */ function once(elements, input) { var eachElement = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var eachEvent = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; var listener = void 0; var eventsObj = {}; forIn(input, function (events, callback) { eventsObj[events] = function (event) { callback(event); listener.off(eachElement && event.currentTarget, eachEvent && events); }; }); listener = on(elements, eventsObj); return { cancel: listener.off }; } /** * Execute callback when dom is ready. * @param {eventCallback} callback - The callback. * @example //esnext * import { ready } from 'chirashi' * ready(() => { * console.log('Hello World!') * }) * // Dom already complete or event fired. * // LOGS: "Hello World!" * @example //es5 * Chirashi.ready(function () { * console.log('Hello World!') * }) * // Dom already complete or event fired. * // LOGS: "Hello World!" */ function ready(callback) { // arguments[1] is used for test purpose only if ((arguments[1] || document.readyState) === 'complete') { callback(); } else { once(document, { 'DOMContentLoaded': callback }); } } var defaults$1 = { bubbles: true, cancelable: true }; /** * Trigger events on elements with data * @param {(string|Array|NodeList|HTMLCollection)} elements - The iterable or selector * @param {string} events - The events that should be tiggered seperated with spaces * @param {Object} data - The events' data * @return {(string|Array|NodeList|HTMLCollection)} elements - The iterable for chaining * @example //esnext * import { createElement, append, on, trigger } from 'chirashi' * const maki = createElement('a.cheese.maki') * const sushi = createElement('a.wasabi.sushi') * append(document.body, [maki, sushi]) * const listener = on('.cheese, .wasabi', { * click(e, target) => { * console.log('clicked', target) * } * }) * trigger(maki, 'click') //simulate user's click * // LOGS: "clicked" <a class="maki cheese"></a> * trigger(sushi, 'click') //simulate user's click * // LOGS: "clicked" <a class="sushi wasabi"></a> * @example //es5 * var listener = Chirashi.bind('.cheese, .wasabi', { * 'click': function (e, target) { * console.log('clicked', target) * } * }) * var maki = Chirashi.createElement('a.cheese.maki') * var sushi = Chirashi.createElement('a.wasabi.sushi') * Chirashi.append(document.body, [maki, sushi]) * Chirashi.trigger(maki, 'click') //simulate user's click * // LOGS: "clicked" <a class="maki cheese"></a> * Chirashi.trigger(sushi, 'click') //simulate user's click * // LOGS: "clicked" <a class="sushi wasabi"></a> */ function trigger(elements, events) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; elements = getElements(elements); if (!elements.length) return; options = _extends({}, options, defaults$1); forEach(_stringToArray(events), function (event) { event = new window.CustomEvent(event, options); forEach(elements, function (element) { return element.dispatchEvent(event); }); }); return elements; } var caps = /[A-Z]/g; function _kebabCase(input) { var output = '' + input; var next = void 0; while (next = caps.exec(input)) { output = output.replace(new RegExp(next, 'g'), '-' + next[0].toLowerCase()); } return output; } var unitless = ['z-index', 'zoom', 'font-weight', 'line-height', 'counter-reset', 'counter-increment', 'volume', 'stress', 'pitch-range', 'richness', 'opacity']; /** * Set the provided style to elements. * @param {(string|Array|NodeList|HTMLCollection)} elements - The iterable, selector or elements. * @param {Object.<string, (number|string)>} style - The style options as object with keys the css property and values, string values or number. If the value is a number and property doesn't support unitless values, pixels will be used. * @return {Array} domElements - The array of dom elements from elements. * @return {function} domElements.chrshPush - Methods to push dom elements into the array. Accepts same input as getElements. * @example //esnext * import { append, setStyle, position } from 'chirashi' * * append(document.body, '.maki') * append('.maki', '.salmon') * * setStyle('.maki', { * display: 'block', * position: 'absolute', * top: 200, * left: 240, * width: 100, * height: 100, * borderRadius: '50%', * background: 'black' * }) // returns: [<div class="maki" style="display: block; position: absolute; top: 200px; left: 240px; width: 100px; height: 100px; border-radius: 50%; background: black;"><div class="salmon"></div></div>] * * const salmon = setStyle('.salmon', { * display: 'block', * position: 'absolute', * top: 20, * left: 10, * width: 10, * height: 10, * borderRadius: '50%', * background: 'pink' * }) // returns: [<div class="salmon" style="display: block; position: absolute; top: 20px; left: 10px; width: 10px; height: 10px; border-radius: 50%; background: pink;"></div>] * @example //es5 * Chirashi.append(document.body, '.maki') * Chirashi.append('.maki', '.salmon') * * Chirashi.setStyle('.maki', { * display: 'block', * position: 'absolute', * top: 200, * left: 240, * width: 100, * height: 100, * borderRadius: '50%', * background: 'black' * }) // returns: [<div class="maki" style="display: block; position: absolute; top: 200px; left: 240px; width: 100px; height: 100px; border-radius: 50%; background: black;"><div class="salmon"></div></div>] * * const salmon = Chirashi.setStyle('.salmon', { * display: 'block', * position: 'absolute', * top: 20, * left: 10, * width: 10, * height: 10, * borderRadius: '50%', * background: 'pink' * }) // returns: [<div class="salmon" style="display: block; position: absolute; top: 20px; left: 10px; width: 10px; height: 10px; border-radius: 50%; background: pink;"></div>] */ function setStyle(elements, style) { forIn(style, function (prop, value) { if (unitless.indexOf(_kebabCase(prop)) === -1 && typeof value === 'number') { style[prop] += 'px'; } }); return forElements(elements, function (element) { if (!element.style) return; Object.assign(element.style, style); }); } /** * Clear inline style properties from elements. * @param {(string|Array|NodeList|HTMLCollection)} elements - The iterable, selector or elements. * @param {Object.<string, string>} style - The style options as object with key the property and value the string value. * @return {Array} domElements - The array of dom elements from elements. * @return {function} domElements.chrshPush - Methods to push dom elements into the array. Accepts same input as getElements. * @example //esnext * import { createElement, setStyle, clearStyle } from 'chirashi' * const maki = createElement('a.cheese.maki') * setStyle(maki, { * position: 'absolute', * top: 10, * width: 200, * height: 200, * background: 'red' * }) * clearStyle(maki, ['position', top]) * clearStyle(maki, 'width, height, background') * @example //es5 * var maki = Chirashi.createElement('a.cheese.maki') * Chirashi.setStyle(maki, { * position: 'absolute', * top: 10, * width: 200, * height: 200, * background: 'red' * }) * Chirashi.clearStyle(maki, ['position', top]) * Chirashi.clearStyle(maki, 'width, height, background') */ function clearStyle(elements, props) { props = _stringToArray(props); var style = {}; forEach(props, function (prop) { style[prop] = ''; }); return setStyle(elements, style); } /** * Return the screen relative position of an element. * @param {(string|Array|NodeList|HTMLCollection|document|HTMLElement|SVGElement)} element - The selector or dom element. * @return {(Object|boolean)} clientRect - Element's screen position or false if no element found. * @return {Object.bottom} bottom - Y-coordinate, relative to the viewport origin, of the bottom of the rectangle box. * @return {Object.height} height - Height of the rectangle box (This is identical to bottom minus top). * @return {Object.left} left - X-coordinate, relative to the viewport origin, of the left of the rectangle box. * @return {Object.right} right - X-coordinate, relative to the viewport origin, of the right of the rectangle box. * @return {Object.top} top - Y-coordinate, relative to the viewport origin, of the top of the rectangle box. * @return {Object.width} width - Width of the rectangle box (This is identical to right minus left). * @example esnext * import { setStyle, append, clientRect } from 'chirashi' * * setStyle([document.documentElement, document.body], { * position: 'relative', * margin: 0, * padding: 0 * }) * * append(document.body, '.poulp') * * const poulp = setStyle('.poulp', { * display: 'block', * position: 'absolute', * top: 200, * left: 240, * width: 100, * height: 100, * background: 'red' * }) * * clientRect(poulp) // returns: { bottom: 300, height: 100, left: 240, right: 0, top: 200, width: 100 } * @example es5 * Chirashi.setStyle([document.documentElement, document.body], { * position: 'relative', * margin: 0, * padding: 0 * }) * * Chirashi.append(document.body, '.poulp') * * var poulp = Chirashi.setStyle('.poulp', { * display: 'block', * position: 'absolute', * top: 200, * left: 240, * width: 100, * height: 100, * background: 'red' * }) * * Chirashi.clientRect(poulp) // returns: { bottom: 300, height: 100, left: 240, right: 0, top: 200, width: 100 } */ function clientRect(element) { element = getElement(element); if (!element) return false; var rect = element.getBoundingClientRect(); return { bottom: rect.bottom, height: rect.height, left: rect.left, right: rect.right, top: rect.top, width: rect.width }; } function _getLength(element, direction, offset) { return getProp(element, '' + (offset ? 'offset' : 'client') + direction); } /** * Get element's height in pixels. * @param {(string|HTMLElement|SVGElement)} element - Selector or element. * @param {boolean} [offset=false] - If true height will include scrollbar and borders to size. * @return {number} height - The height in pixels. * @example //esnext * import { append, setStyle, getHeight } from 'chirashi' * append(document.body, '.maki') * const maki = setStyle('.maki', { * display: 'block', * border: '20px solid red', * padding: 10, * height: 200, * width: 200 * }) * getHeight(maki, true) //returns: 260 * getHeight(maki) //returns: 220 * @example //es5 * Chirashi.append(document.body, '.maki') * var maki = Chirashi.setStyle('.maki', { * display: 'block', * border: '20px solid red', * padding: 10, * height: 200, * width: 200 * }) * Chirashi.getHeight(maki, true) //returns: 260 * Chirashi.getHeight(maki) //returns: 220 */ function getHeight(element) { var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; return _getLength(element, 'Height', offset); } /** * Get element's width in pixels. * @param {(string|HTMLElement|SVGElement)} element - Selector or element. * @param {boolean} [offset=false] - If true width will include scrollbar and borders to size. * @return {number} width - The width in pixels. * @example //esnext * import { append, setStyle, getWidth } from 'chirashi' * append(document.body, '.maki') * const maki = setStyle('.maki', { * display: 'block', * border: '20px solid red', * padding: 10, * height: 200, * width: 200 * }) * getWidth(maki, true) //returns: 260 * getWidth(maki) //returns: 220 * @example //es5 * Chirashi.append(document.body, '.maki') * var maki = Chirashi.setStyle('.maki', { * display: 'block', * border: '20px solid red', * padding: 10, * height: 200, * width: 200 * }) * Chirashi.getWidth(maki, true) //returns: 260 * Chirashi.getWidth(maki) //returns: 220 */ function getWidth(element) { var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; return _getLength(element, 'Width', offset); } /** * Get element's size in pixels. * @param {(string|Array|NodeList|HTMLCollection|document|HTMLElement|SVGElement)} element - The selector or dom element * @param {boolean} [offset=false] - If true size will include scrollbar and borders. * @return {number} size - The size in pixels. * @example //esnext * import { append, setStyle, getSize } from 'chirashi' * append(document.body, '.maki') * const maki = setStyle('.maki', { * display: 'block', * border: '20px solid red', * padding: 10, * height: 200, * width: 200 * }) * getSize(maki, true) //returns: { width: 260, height: 260 } * getSize(maki) //returns: { width: 220, height: 220 } * @example //es5 * Chirashi.append(document.body, '.maki') * var maki = Chirashi.setStyle('.maki', { * display: 'block', * border: '20px solid red', * padding: 10, * height: 200, * width: 200 * }) * Chirashi.getSize(maki, true) //returns: { width: 260, height: 260 } * Chirashi.getSize(maki) //returns: { width: 220, height: 220 } */ function getSize(element) { var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; return { width: getWidth(element, offset), height: getHeight(element, offset) }; } /** * Get style property of element. * @param {(string|Array|NodeList|HTMLCollection|document|HTMLElement|SVGElement)} element - The selector or dom element * @return {number} value - The value for the property * @example //esnext * import { append, setStyle, getStyle } from 'chirashi' * append(document.body, '.maki') * const maki = setStyle('.maki', { * display: 'block', * position: 'relative', * top: 10 * }) * getStyle(maki, 'display') //returns: "block" * getStyle(maki, 'top') //returns: 10 * @example //es5 * Chirashi.append(document.body, '.maki') * var maki = Chirashi.setStyle('.maki', { * display: 'block', * position: 'relative', * top: 10 * }) * Chirashi.getStyle(maki, 'display') //returns: "block" * Chirashi.getStyle(maki, 'top') //returns: 10 */ function getStyle(element, property) { element = getElement(element); if (!element) return; var ret = window.getComputedStyle(element)[property]; return ret.indexOf('px') === -1 ? ret : parseFloat(ret); } /** * Hide each element of elements using visibility. * @param {(string|Array|NodeList|HTMLCollection)} elements - The iterable, selector or elements. * @return {Array} domElements - The array of dom elements from elements. * @return {function} domElements.chrshPush - Methods to push dom elements into the array. Accepts same input as getElements. * @example //esnext * import { append, hide, getStyle } * append(document.body, '.maki') * const maki = hide('.maki') * getStyle(maki, 'visibility') // returns: "hidden" * @example //es5 * Chirashi.append(document.body, '.maki') * var maki = Chirashi.hide('.maki') * Chirashi.getStyle(maki, 'visibility') // returns: "hidden" */ function hide(elements) { return setStyle(elements, { visibility: 'hidden' }); } /** * Return the screen relative position of an element. * @param {(string|Array|NodeList|HTMLCollection|document|HTMLElement|SVGElement)} element - The selector or dom element. * @return {(Object|boolean)} screenPosition - Element's screen position or false if no element found. * @return {Object.top} top - Y-coordinate, relative to the viewport origin, of the top of the rectangle box. * @return {Object.left} left - X-coordinate, relative to the viewport origin, of the left of the rectangle box. * @example esnext * import { setStyle, append, screenPosition } from 'chirashi' * * setStyle([document.documentElement, document.body], { * position: 'relative', * margin: 0, * padding: 0 * }) * * append(document.body, '.poulp') * * const poulp = setStyle('.poulp', { * display: 'block', * position: 'absolute', * top: 200, * left: 240, * width: 100, * height: 100, * background: 'red' * }) * * screenPosition(poulp) // returns: { top: 200, left: 240 } * @example es5 * Chirashi.setStyle([document.documentElement, document.body], { * position: 'relative', * margin: 0, * padding: 0 * }) * * Chirashi.append(document.body, '.poulp') * * var poulp = Chirashi.setStyle('.poulp', { * display: 'block', * position: 'absolute', * top: 200, * left: 240, * width: 100, * height: 100, * background: 'red' * }) * * Chirashi.screenPosition(poulp) // returns: { top: 200, left: 240 } */ function screenPosition(element) { var rect = clientRect(element); return rect && { top: rect.top, left: rect.left }; } /** * Returns the top and left offset of an element. Offset is relative to web page. * @param {(string|Array|NodeList|HTMLCollection|document|HTMLElement|SVGElement)} element - The selector or dom element. * @return {(Object|boolean)} offset - Offset object or false if no element found. * @return {Object.top} top - Top offset in pixels. * @return {Object.left} left - Left offset in pixels. * @example //esnext * import { setStyle, append, offset } * setStyle([document.documentElement, document.body], { * position: 'relative', * margin: 0, * padding: 0 * }) * append(document.body, '.sushi') * const sushi = setStyle('.sushi', { * display: 'block', * width: 100, * height: 100, * position: 'absolute', * top: 200, * left: 240, * background: 'red' * }) * offset(sushi) // returns: { top: 200, left: 240 } * @example //es5 * Chirashi.setStyle([document.documentElement, document.body], { * position: 'relative', * margin: 0, * padding: 0 * }) * Chirashi.append(document.body, '.sushi') * var sushi = Chirashi.setStyle('.sushi', { * display: 'block', * width: 100, * height: 100, * position: 'absolute', * top: 200, * left: 240, * background: 'red' * }) * Chirashi.offset(sushi) // returns: { top: 200, left: 240 } */ function offset(element) { var screenPos = screenPosition(element); return screenPos && { top: screenPos.top + window.scrollY, left: screenPos.left + window.scrollX }; } /** * Return the top and left position of an element. Position is relative to parent. * @param {(string|Array|NodeList|HTMLCollection|document|HTMLElement|SVGElement)} element - The selector or dom element. * @return {(Object|boolean)} offset - Offset object or false if no element found. * @return {Object.top} top - Top position in pixels. * @return {Object.left} left - Left position in pixels. * @example //esnext * import { append, setStyle, position } from 'chirashi' * * setStyle([document.documentElement, document.body], { * position: 'relative', * margin: 0, * padding: 0 * }) * * append(document.body, '.maki') * append('.maki', '.salmon') * * setStyle('.maki', { * display: 'block', * position: 'absolute', * top: 200, * left: 240, * width: 100, * height: 100, * borderRadius: '50%', * background: 'black' * }) * * const salmon = setStyle('.salmon', { * display: 'block', * position: 'absolute', * top: 20, * left: 10, * width: 10, * height: 10, * borderRadius: '50%', * background: 'pink' * }) * * position(salmon) // returns: { top: 20, left: 10 } * @example //es5 * Chirashi.setStyle([document.documentElement, document.body], { * position: 'relative', * margin: 0, * padding: 0 * }) * * Chirashi.append(document.body, '.maki') * Chirashi.append('.maki', '.salmon') * * Chirashi.setStyle('.maki', { * display: 'block', * position: 'absolute', * top: 200, * left: 240, * width: 100, * height: 100, * borderRadius: '50%', * background: 'black' * }) * * var salmon = Chirashi.setStyle('.salmon', { * display: 'block', * position: 'absolute', * top: 20, * left: 10, * width: 10, * height: 10, * borderRadius: '50%', * background: 'pink' * }) * * Chirashi.position(salmon) // returns: { top: 20, left: 10 } */ function position(element) { element = getElement(element); return !!element && { top: element.offsetTop, left: element.offsetLeft }; } /** * Set the provided height to elements. * @param {(string|Array|NodeList|HTMLCollection)} elements - The iterable, selector or elements. * @param {(number|string)} height - The height as number or string. For number, unit used will be pixels. * @return {Array} domElements - The array of dom elements from elements. * @return {function} domElements.chrshPush - Methods to push dom elements into the array. Accepts same input as getElements. * @example //esnext * import { append, setHeight } from 'chirashi' * * append(document.body, '.maki') * * setHeight('.maki', 20) // returns: [<div class="maki" style="height: 20px;"></div>] * setHeight('.maki', '100%') // returns: [<div class="maki" style="height: 100%;"></div>] * @example //es5 * Chirashi.append(document.body, '.maki') * * Chirashi.setHeight('.maki', 20) // returns: [<div class="maki" style="height: 20px;"></div>] * Chirashi.setHeight('.maki', '100%') // returns: [<div class="maki" style="height: 100%;"></div>] */ function setHeight(elements, height) { return setStyle(elements, { height: height }); } /** * Set the provided size to elements. * @param {(string|Array|NodeList|HTMLCollection)} elements - The iterable, selector or elements. * @param {(number|string)} width - The width as number or string. For number, unit used will be pixels. * @param {(number|string)} height - The height as number or string. For number, unit used will be pixels. * @return {Array} domElements - The array of dom elements from elements. * @return {function} domElements.chrshPush - Methods to push dom elements into the array. Accepts same input as getElements. * @example //esnext * import { append, setSize } from 'chirashi' * * append(document.body, '.maki') * * setSize('.maki', 20, '100%') // returns: [<div class="maki" style="width: 20px; height: 100%;"></div>] * @example //es5 * Chirashi.append(document.body, '.maki') * * Chirashi.setSize('.maki', 20, '100%') // returns: [<div class="maki" style="width: 20px; height: 100%;"></div>] */ function setSize(elements, width, height) { return setStyle(elements, { width: width, height: height }); } /** * Set the provided width to elements. * @param {(string|Array|NodeList|HTMLCollection)} elements - The iterable, selector or elements. * @param {(number|string)} width - The width as number or string. For number, unit used will be pixels. * @return {Array} domElements - The array of dom elements from elements. * @return {function} domElements.chrshPush - Methods to push dom elements into the array. Accepts same input as getElements. * @example //esnext * import { append, setWidth } from 'chirashi' * * append(document.body, '.maki') * * setWidth('.maki', 20) // returns: [<div class="maki" style="width: 20px;"></div>] * setWidth('.maki', '100%') // returns: [<div class="maki" style="width: 100%;"></div>] * @example //es5 * Chirashi.append(document.body, '.maki') * * Chirashi.setWidth('.maki', 20) // returns: [<div class="maki" style="width: 20px;"></div>] * Chirashi.setWidth('.maki', '100%') // returns: [<div class="maki" style="width: 100%;"></div>] */ function setWidth(elements, width) { return setStyle(elements, { width: width }); } /** * Show each element of elements using visibility. * @param {(string|Array|NodeList|HTMLCollection)} elements - The iterable, selector or elements. * @return {Array} domElements - The array of dom elements from elements. * @return {function} domElements.chrshPush - Methods to push dom elements into the array. Accepts same input as getElements. * @example //esnext * import { append, show, getStyle } * append(document.body, '.maki') * const maki = show('.maki') * getStyle(maki, 'visibility') // returns: "hidden" * @example //es5 * Chirashi.append(document.body, '.maki') * var maki = Chirashi.show('.maki') * Chirashi.getStyle(maki, 'visibility') // returns: "visible" */ function show(elements) { return setStyle(elements, { visibility: 'visible' }); } function _getValues(transformation, axes, name, defaultVal, defaultAxes) { var values = {}; if (name in transformation) { if (_typeof(transformation[name]) === 'object') { forEach(axes, function (axe) { values['' + name + axe.toUpperCase()] = axe in transformation[name] ? transformation[name][axe] : defaultVal; }); } else { forEach(axes, function (axe) { values['' + name + axe.toUpperCase()] = defaultAxes[axe]; }); } } else { forEach(axes, function (axe) { values['' + name + axe.toUpperCase()] = defaultVal; }); } return values; } function _transformMatrix(transformation) { var x = 'x' in transformation ? transformation.x : 0; var y = 'y' in transformation ? transformation.y : 0; var z = 'z' in transformation ? transformation.z : 0; var _getValues2 = _getValues(transformation, ['x', 'y', 'z'], 'scale', 1, { x: transformation.scale, y: transformation.scale, z: 1 }), scaleX = _getValues2.scaleX, scaleY = _getValues2.scaleY, scaleZ = _getValues2.scaleZ; var _getValues3 = _getValues(transformation, ['x', 'y', 'z'], 'rotate', 0, { x: 0, y: 0, z: transformation.rotate }), rotateX = _getValues3.rotateX, rotateY = _getValues3.rotateY, rotateZ = _getValues3.rotateZ; var _getValues4 = _getValues(transformation, ['x', 'y'], 'skew', 0, { x: transformation.skew, y: transformation.skew }), skewX = _getValues4.skewX, skewY = _getValues4.skewY; var cosRotateX = Math.cos(rotateX); var sinRotateX = Math.sin(rotateX); var cosRotateY = Math.cos(rotateY); var sinRotateY = Math.sin(rotateY); var cosRotateZ = Math.cos(rotateZ); var sinRotateZ = Math.sin(rotateZ); var tanSkewX = Math.tan(skewX); var tanSkewY = Math.tan(skewY); var matrix = [scaleX * cosRotateY * cosRotateZ, sinRotateZ + tanSkewY, -sinRotateY, 0, -sinRotateZ + tanSkewX, scaleY * cosRotateX * cosRotateZ, sinRotateX, 0, sinRotateY, -sinRotateX, scaleZ * cosRotateX * cosRotateY, 0, x, y, z, 1]; forEach(matrix, function (item, index) { matrix[index] = +item.toFixed(2); }); return matrix; } /** * Compute and apply 3d transform matrix from provided transformation to each element of elements. * @param {(string|Array|NodeList|HTMLCollection)} elements - The iterable or selector. * @param {Transformation} transformation - The transformation as an object * @return {Array} domElements - The array of dom elements from elements. * @return {function} domElements.chrshPush - Methods to push dom elements into the array. Accepts same input as getElements. * @example //esnext * import { createElement, setHtml, transform } from 'chirashi' * const wasabiPea = createElement('p') * setHtml(wasabiPea, 'Wasabi') * transform(wasabiPea, {}) // returns: [<p style="transform: "matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)">Wasabi</p>] * transform(wasabiPea, {x: 5, y: 6, z: 7}) // returns: [<p style="transform: "matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,5,6,7,1)">Wasabi</p>] * transform(wasabiPea, {scale: 2}) // returns: [<p style="transform: "matrix3d(2,0,0,0,0,2,0,0,0,0,1,0,0,0,0,1)">Wasabi</p>] * transform(wasabiPea, {scale: {x: 2, y: 3, z: 4}}) // returns: [<p style="transform: "matrix3d(2,0,0,0,0,3,0,0,0,0,4,0,0,0,0,1)">Wasabi</p>] * transform(wasabiPea, {rotate: 45}) // returns: [<p style="transform: "matrix3d(0.53,0.85,0,0,-0.85,0.53,0,0,0,0,1,0,0,0,0,1)">Wasabi</p>] * transform(wasabiPea, {rotate: {x: 45, y: 20, z: 15}}) // returns: [<p style="transform: "matrix3d(-0.31,0.65,-0.91,0,-0.65,-0.4,0.85,0,0.91,-0.85,0.21,0,0,0,0,1)">Wasabi</p>] * transform(wasabiPea, {skew: 45}) // returns: [<p style="transform: "matrix3d(1,1.62,0,0,1.62,1,0,0,0,0,1,0,0,0,0,1)">Wasabi</p>] * transform(wasabiPea, {skew: {x: 25, y: 45}}) // returns: [<p style="transform: "matrix3d(1,1.62,0,0,-0.13,1,0,0,0,0,1,0,0,0,0,1)">Wasabi</p>] * transform(wasabiPea, {x: 5, y: 6, z: 7, scale: {x: 2, y: 3}, rotate: {x: 45, y: 20, z: 15}, skew: {x: 25, y: 45}}) // returns: [<p style="transform: "matrix3d(-0.62,2.27,-0.91,0,-0.78,-1.2,0.85,0,0.91,-0.85,0.21,0,5,6,7,1)">Wasabi</p>] * @example //es5 * var wasabiPea = Chirashi.createElement('p') * Chirashi.setHtml(wasabiPea, 'Wasabi') * Chirashi.transform(wasabiPea, {}) // returns: [<p style="transform: "matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)">Wasabi</p>] * Chirashi.transform(wasabiPea, {x: 5, y: 6, z: 7}) // returns: [<p style="transform: "matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,5,6,7,1)">Wasabi</p>] * Chirashi.transform(wasabiPea, {scale: 2}) // returns: [<p style="transform: "matrix3d(2,0,0,0,0,2,0,0,0,0,1,0,0,0,0,1)">Wasabi</p>] * Chirashi.transform(wasabiPea, {scale: {x: 2, y: 3, z: 4}}) // returns: [<p style="transform: "matrix3d(2,0,0,0,0,3,0,0,0,0,4,0,0,0,0,1)">Wasabi</p>] * Chirashi.transform(wasabiPea, {rotate: 45}) // returns: [<p style="transform: "matrix3d(0.53,0.85,0,0,-0.85,0.53,0,0,0,0,1,0,0,0,0,1)">Wasabi</p>] * Chirashi.transform(wasabiPea, {rotate: {x: 45, y: 20, z: 15}}) // returns: [<p style="transform: "matrix3d(-0.31,0.65,-0.91,0,-0.65,-0.4,0.85,0,0.91,-0.85,0.21,0,0,0,0,1)">Wasabi</p>] * Chirashi.transform(wasabiPea, {skew: 45}) // returns: [<p style="transform: "matrix3d(1,1.62,0,0,1.62,1,0,0,0,0,1,0,0,0,0,1)">Wasabi</p>] * Chirashi.transform(wasabiPea, {skew: {x: 25, y: 45}}) // returns: [<p style="transform: "matrix3d(1,1.62,0,0,-0.13,1,0,0,0,0,1,0,0,0,0,1)">Wasabi</p>] * Chirashi.transform(wasabiPea, {x: 5, y: 6, z: 7, scale: {x: 2, y: 3}, rotate: {x: 45, y: 20, z: 15}, skew: {x: 25, y: 45}}) // returns: [<p style="transform: "matrix3d(-0.62,2.27,-0.91,0,-0.78,-1.2,0.85,0,0.91,-0.85,0.21,0,5,6,7,1)">Wasabi</p>] */ function transform(elements, transformation) { return setStyle(elements, { transform: 'matrix3d(' + _transformMatrix(transformation).join(',') + ')' }); } /** * @typedef {Object} Transformation * @property {number} [x=0] - Translation value on x axis in pixels. * @property {number} [y=0] - Translation value on y axis in pixels. * @property {number} [z=0] - Translation value on z axis in pixels. * @property {(number|object)} [scale=1] - Scale value for x and y axes or object of values for axes. * @property {number} [scale.x=1] - Scale value on x axis. * @property {number} [scale.y=1] - Scale value on y axis. * @property {number} [scale.z=1] - Scale value on z axis. * @property {(number|object)} [rotate=0] - Rotation value for z axis in radians or object of values for axes. * @property {number} [rotate.x=0] - Rotation value on x axis in radians. * @property {number} [rotate.y=0] - Rotation value on y axis in radians. * @property {number} [rotate.z=0] - Rotation value on z axis in radians. * @property {(number|object)} [skew=0] - Skew value for x and y axes in radians or object of values for axes. * @property {number} [skew.x=0] - Skew value on x axis in radians. * @property {number} [skew.y=0] - Skew value on y axis in radians. */ exports.forEach = forEach; exports.forElements = forElements; exports.forIn = forIn; exports.getElement = getElement; exports.getElements = getElements; exports.isDomElement = isDomElement; exports.addClass = addClass; exports.append = append; exports.children = children; exports.clone = clone; exports.closest = closest; exports.createElement = createElement; exports.filter = filter; exports.find = find; exports.findOne = findOne; exports.getAttr = getAttr; exports.getData = getData; exports.getHtml = getHtml; exports.getProp = getProp; exports.hasClass = hasClass; exports.indexInParent = indexInParent; exports.insertAfter = insertAfter; exports.insertBefore = insertBefore; exports.next = next; exports.parent = parent; exports.prev = prev; exports.remove = remove; exports.removeAttr = removeAttr; exports.removeClass = removeClass; exports.removeData = removeData; exports.setAttr = setAttr; exports.setData = setData; exports.setHtml = setHtml; exports.setProp = setProp; exports.toggleClass = toggleClass; exports.bind = bind; exports.on = on; exports.once = once; exports.ready = ready; exports.trigger = trigger; exports.clearStyle = clearStyle; exports.clientRect = clientRect; exports.getHeight = getHeight; exports.getSize = getSize; exports.getStyle = getStyle; exports.getWidth = getWidth; exports.hide = hide; exports.offset = offset; exports.position = position; exports.screenPosition = screenPosition; exports.setHeight = setHeight; exports.setSize = setSize; exports.setStyle = setStyle; exports.setWidth = setWidth; exports.show = show; exports.transform = transform;
/** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMultiChildUpdateTypes */ "use strict"; var keyMirror = require('keyMirror'); /** * When a component's children are updated, a series of update configuration * objects are created in order to batch and serialize the required changes. * * Enumerates all the possible types of update configurations. * * @internal */ var ReactMultiChildUpdateTypes = keyMirror({ INSERT_MARKUP: null, MOVE_EXISTING: null, REMOVE_NODE: null, TEXT_CONTENT: null }); module.exports = ReactMultiChildUpdateTypes;
cordova.define("org.apache.cordova.dialogs.notification", function(require, exports, module) { /* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ var exec = require('cordova/exec'); var platform = require('cordova/platform'); /** * Provides access to notifications on the device. */ module.exports = { /** * Open a native alert dialog, with a customizable title and button text. * * @param {String} message Message to print in the body of the alert * @param {Function} completeCallback The callback that is called when user clicks on a button. * @param {String} title Title of the alert dialog (default: Alert) * @param {String} buttonLabel Label of the close button (default: OK) */ alert: function(message, completeCallback, title, buttonLabel) { var _title = (title || "Alert"); var _buttonLabel = (buttonLabel || "OK"); exec(completeCallback, null, "Notification", "alert", [message, _title, _buttonLabel]); }, /** * Open a native confirm dialog, with a customizable title and button text. * The result that the user selects is returned to the result callback. * * @param {String} message Message to print in the body of the alert * @param {Function} resultCallback The callback that is called when user clicks on a button. * @param {String} title Title of the alert dialog (default: Confirm) * @param {Array} buttonLabels Array of the labels of the buttons (default: ['OK', 'Cancel']) */ confirm: function(message, resultCallback, title, buttonLabels) { var _title = (title || "Confirm"); var _buttonLabels = (buttonLabels || ["OK", "Cancel"]); // Strings are deprecated! if (typeof _buttonLabels === 'string') { console.log("Notification.confirm(string, function, string, string) is deprecated. Use Notification.confirm(string, function, string, array)."); } // Some platforms take an array of button label names. // Other platforms take a comma separated list. // For compatibility, we convert to the desired type based on the platform. if (platform.id == "amazon-fireos" || platform.id == "android" || platform.id == "ios" || platform.id == "windowsphone" || platform.id == "firefoxos" || platform.id == "ubuntu") { if (typeof _buttonLabels === 'string') { var buttonLabelString = _buttonLabels; _buttonLabels = _buttonLabels.split(","); // not crazy about changing the var type here } } else { if (Array.isArray(_buttonLabels)) { var buttonLabelArray = _buttonLabels; _buttonLabels = buttonLabelArray.toString(); } } exec(resultCallback, null, "Notification", "confirm", [message, _title, _buttonLabels]); }, /** * Open a native prompt dialog, with a customizable title and button text. * The following results are returned to the result callback: * buttonIndex Index number of the button selected. * input1 The text entered in the prompt dialog box. * * @param {String} message Dialog message to display (default: "Prompt message") * @param {Function} resultCallback The callback that is called when user clicks on a button. * @param {String} title Title of the dialog (default: "Prompt") * @param {Array} buttonLabels Array of strings for the button labels (default: ["OK","Cancel"]) * @param {String} defaultText Textbox input value (default: empty string) */ prompt: function(message, resultCallback, title, buttonLabels, defaultText) { var _message = (message || "Prompt message"); var _title = (title || "Prompt"); var _buttonLabels = (buttonLabels || ["OK","Cancel"]); var _defaultText = (defaultText || ""); exec(resultCallback, null, "Notification", "prompt", [_message, _title, _buttonLabels, _defaultText]); }, /** * Causes the device to beep. * On Android, the default notification ringtone is played "count" times. * * @param {Integer} count The number of beeps. */ beep: function(count) { exec(null, null, "Notification", "beep", [count]); } }; });
/*! * Bootstrap-select v1.6.2 (http://silviomoreto.github.io/bootstrap-select/) * * Copyright 2013-2014 bootstrap-select * Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE) */ !function(a){a.fn.selectpicker.defaults={noneSelectedText:"No hay selección",noneResultsText:"No hay resultados",countSelectedText:"Seleccionados {0} de {1}",maxOptionsText:["Límite alcanzado ({n} {var} max)","Límite del grupo alcanzado({n} {var} max)",["elementos","element"]],multipleSeparator:", "}}(jQuery);
(function( factory ) { if ( typeof define === "function" && define.amd ) { define( ["jquery", "../jquery.validate"], factory ); } else if (typeof module === "object" && module.exports) { module.exports = factory( require( "jquery" ) ); } else { factory( jQuery ); } }(function( $ ) { /* * Translated default messages for the jQuery validation plugin. * Locale: ZH (Chinese, 中文 (Zhōngwén), 汉语, 漢語) */ $.extend( $.validator.messages, { required: "这是必填字段", remote: "请修正此字段", email: "请输入有效的电子邮件地址", url: "请输入有效的网址", date: "请输入有效的日期", dateISO: "请输入有效的日期 (YYYY-MM-DD)", number: "请输入有效的数字", digits: "只能输入数字", creditcard: "请输入有效的信用卡号码", equalTo: "你的输入不相同", extension: "请输入有效的后缀", maxlength: $.validator.format( "最多可以输入 {0} 个字符" ), minlength: $.validator.format( "最少要输入 {0} 个字符" ), rangelength: $.validator.format( "请输入长度在 {0} 到 {1} 之间的字符串" ), range: $.validator.format( "请输入范围在 {0} 到 {1} 之间的数值" ), max: $.validator.format( "请输入不大于 {0} 的数值" ), min: $.validator.format( "请输入不小于 {0} 的数值" ) } ); return $; }));
/*! * VERSION: 0.5.2 * DATE: 2014-07-17 * UPDATES AND DOCS AT: http://www.greensock.com * * @license Copyright (c) 2008-2015, GreenSock. All rights reserved. * This work is subject to the terms at http://greensock.com/standard-license or for * Club GreenSock members, the software agreement that was issued with your membership. * * @author: Jack Doyle, jack@greensock.com */ var _gsScope = (typeof(module) !== "undefined" && module.exports && typeof(global) !== "undefined") ? global : this || window; //helps ensure compatibility with AMD/RequireJS and CommonJS/Node (_gsScope._gsQueue || (_gsScope._gsQueue = [])).push( function() { "use strict"; var _specialProps = {scale:1, shadowOffset:1, fillPatternOffset:1, offset:1, fill:2, stroke:2, shadowColor:2}, //type 1 is one that has "x" and "y" components that can be split apart but in order to set them, they must be combined into a single object and passed to one setter (like setScale({x:0.5, y:0.6})). Type 2 is for colors. _getterFuncs = {}, _setterFuncs = {}, _numExp = /(\d|\.)+/g, _directionalRotationExp = /(?:_cw|_ccw|_short)/, _plugins = _gsScope._gsDefine.globals.com.greensock.plugins, _colorLookup = {aqua:[0,255,255], lime:[0,255,0], silver:[192,192,192], black:[0,0,0], maroon:[128,0,0], teal:[0,128,128], blue:[0,0,255], navy:[0,0,128], white:[255,255,255], fuchsia:[255,0,255], olive:[128,128,0], yellow:[255,255,0], orange:[255,165,0], gray:[128,128,128], purple:[128,0,128], green:[0,128,0], red:[255,0,0], pink:[255,192,203], cyan:[0,255,255], transparent:[255,255,255,0]}, _hue = function(h, m1, m2) { h = (h < 0) ? h + 1 : (h > 1) ? h - 1 : h; return ((((h * 6 < 1) ? m1 + (m2 - m1) * h * 6 : (h < 0.5) ? m2 : (h * 3 < 2) ? m1 + (m2 - m1) * (2 / 3 - h) * 6 : m1) * 255) + 0.5) | 0; }, _parseColor = function(color) { if (color === "" || color == null || color === "none") { return _colorLookup.transparent; } if (_colorLookup[color]) { return _colorLookup[color]; } if (typeof(color) === "number") { return [color >> 16, (color >> 8) & 255, color & 255]; } if (color.charAt(0) === "#") { if (color.length === 4) { //for shorthand like #9F0 color = "#" + color.charAt(1) + color.charAt(1) + color.charAt(2) + color.charAt(2) + color.charAt(3) + color.charAt(3); } color = parseInt(color.substr(1), 16); return [color >> 16, (color >> 8) & 255, color & 255]; } if (color.substr(0, 3) === "hsl") { color = color.match(_numExp); var h = (Number(color[0]) % 360) / 360, s = Number(color[1]) / 100, l = Number(color[2]) / 100, m2 = (l <= 0.5) ? l * (s + 1) : l + s - l * s, m1 = l * 2 - m2; if (color.length > 3) { color[3] = Number(color[3]); } color[0] = _hue(h + 1 / 3, m1, m2); color[1] = _hue(h, m1, m2); color[2] = _hue(h - 1 / 3, m1, m2); return color; } var a = color.match(_numExp) || _colorLookup.transparent, i = a.length; while (--i > -1) { a[i] = Number(a[i]); } return a; }, ColorProp = function(target, getter, setter, next) { this.getter = getter; this.setter = setter; var val = _parseColor( target[getter]() ); this.proxy = {r:val[0], g:val[1], b:val[2], a:(val.length > 3 ? val[3] : 1)}; if (next) { this._next = next; next._prev = this; } }, _layersToDraw = [], _ticker, _listening, _onTick = function() { var i = _layersToDraw.length; if (i !== 0) { while (--i > -1) { _layersToDraw[i].draw(); _layersToDraw[i]._gsDraw = false; } _layersToDraw.length = 0; } else { _ticker.removeEventListener("tick", _onTick); _listening = false; } }, _prepDimensionProp = function(p, dimension) { var alt = (dimension === "x") ? "y" : "x", proxyName = "_gs_" + p; _getterFuncs[p] = function() { return this["get" + p]()[dimension]; }; _setterFuncs[p] = function(value) { var cur = this["get" + p](), proxy = this[proxyName]; if (!proxy) { proxy = this[proxyName] = {}; } proxy[dimension] = value; proxy[alt] = cur[alt]; this[p](proxy); return this; }; }, _createGetterSetter = function(getter, setter) { return function(value) {return (arguments.length) ? setter(value) : getter(); }; }, //looks at every property in the vars and converts them (when appropriate) to the KineticJS equivalent. If it finds a special property for which "x" and "y" must be split apart (like scale, offset, shadowOffset, etc.), it will do that as well. This method returns an array of any names it had to change (like "x", "y", "scale", etc.) so that they can be used in the overwriteProps array. _convertProps = function(target, vars) { var converted = [], p, val, i, proto; for (p in vars) { val = vars[p]; if (p !== "bezier" && p !== "autoDraw" && p.substr(0,3) !== "set" && target[p] === undefined) { converted.push(p); delete vars[p]; p = "set" + p.charAt(0).toUpperCase() + p.substr(1); vars[p] = val; } if (_specialProps[p]) { if (_specialProps[p] === 1) { vars[p + "X"] = vars[p + "Y"] = vars[p]; delete vars[p]; return _convertProps(target, vars); } else if (!target[p] && _setterFuncs[p]) { proto = target.prototype || target; proto[p] = _createGetterSetter(_getterFuncs[p], _setterFuncs[p]); } } else if (p === "bezier") { val = (val instanceof Array) ? val : val.values || []; i = val.length; while (--i > -1) { if (i === 0) { converted = converted.concat( _convertProps(target, val[i]) ); } else { _convertProps(target, val[i]); } } } } return converted; }, _copy = function(obj) { var result = {}, p; for (p in obj) { result[p] = obj[p]; } return result; }, versionValid, p; for (p in _specialProps) { if (_specialProps[p] === 1) { _prepDimensionProp(p, "x"); _prepDimensionProp(p, "y"); } } var KineticPlugin = _gsScope._gsDefine.plugin({ propName: "kinetic", API: 2, version: "0.5.2", //called when the tween renders for the first time. This is where initial values should be recorded and any setup routines should run. init: function(target, value, tween) { var p, val, gp, sp, bezierPlugin, directionalRotationPlugin; if (!versionValid && (versionValid = (parseInt(Kinetic.version.split(".")[0], 10)) < 5)) { throw ("The GSAP KineticPlugin that's loaded requires KineticJS version 5.0.0 or later. For earlier versions, use KineticPlugin from GSAP 1.11.3 or earlier."); } this._overwriteProps = _convertProps(target, value); //allow users to pass in shorter names like "x" instead of "setX" and "rotationDeg" instead of "setRotationDeg" this._target = target; this._layer = (value.autoDraw !== false) ? target.getLayer() : null; if (!_ticker && this._layer) { _ticker = tween.constructor.ticker; } for (p in value) { val = value[p]; //we must handle colors in a special way, splitting apart the red, green, blue, and alpha. if (_specialProps[p] === 2) { sp = this._firstSP = new ColorProp(target, p, p, this._firstSP); val = _parseColor(val); if (sp.proxy.r !== val[0]) { this._addTween(sp.proxy, "r", sp.proxy.r, val[0], p); } if (sp.proxy.g !== val[1]) { this._addTween(sp.proxy, "g", sp.proxy.g, val[1], p); } if (sp.proxy.b !== val[2]) { this._addTween(sp.proxy, "b", sp.proxy.b, val[2], p); } if ((val.length > 3 || sp.proxy.a !== 1) && sp.proxy.a !== val[3]) { this._addTween(sp.proxy, "a", sp.proxy.a, (val.length > 3 ? val[3] : 1), p); } } else if (p === "bezier") { bezierPlugin = _plugins.BezierPlugin; if (!bezierPlugin) { throw("BezierPlugin not loaded"); } bezierPlugin = this._bezier = new bezierPlugin(); if (typeof(val) === "object" && val.autoRotate === true) { val.autoRotate = ["x","y","rotation",0,false]; } bezierPlugin._onInitTween(target, val, tween); this._overwriteProps = this._overwriteProps.concat(bezierPlugin._overwriteProps); this._addTween(bezierPlugin, "setRatio", 0, 1, p); } else if ((p === "rotation" || p === "rotationDeg") && typeof(val) === "string" && _directionalRotationExp.test(val)) { directionalRotationPlugin = _plugins.DirectionalRotationPlugin; if (!directionalRotationPlugin) { throw("DirectionalRotationPlugin not loaded"); } directionalRotationPlugin = this._directionalRotation = new directionalRotationPlugin(); gp = {useRadians:false}; gp[p] = val; directionalRotationPlugin._onInitTween(target, gp, tween); this._addTween(directionalRotationPlugin, "setRatio", 0, 1, p); } else if (val instanceof Array) { //for array-based values like "points" this._initArrayTween(target[p](), val, p); } else if (p !== "autoDraw") { gp = "get" + p.substr(3); this._addTween(target, p, ((typeof(target[p]) === "function") ? target[( (gp !== "get" && typeof(target[gp]) === "function") ? gp : p)]() : target[p]) || 0, val, p); } this._overwriteProps.push(p); } return true; }, kill: function(lookup) { lookup = _copy(lookup); _convertProps(this._target, lookup); if (this._bezier) { this._bezier._kill(lookup); } if (this._directionalRotation) { this._directionalRotation._kill(lookup); } return this._super._kill.call(this, lookup); }, round:function(lookup, value) { lookup = _copy(lookup); _convertProps(this._target, lookup); if (this._bezier) { this._bezier._roundProps(lookup, value); } return this._super._roundProps.call(this, lookup, value); }, //called each time the values should be updated, and the ratio gets passed as the only parameter (typically it's a value between 0 and 1, but it can exceed those when using an ease like Elastic.easeOut or Back.easeOut, etc.) set: function(ratio) { this._super.setRatio.call(this, ratio); var sp = this._firstSP, layer = this._layer, arrayTweens = this._arrayTweens, i, e, p, val, t, proxy; if (sp) { t = this._target; while (sp) { proxy = sp.proxy; t[sp.setter]( (proxy.a !== 1 ? "rgba(" : "rgb(") + (proxy.r | 0) + ", " + (proxy.g | 0) + ", " + (proxy.b | 0) + (proxy.a !== 1 ? ", " + proxy.a : "") + ")"); sp = sp._next; } } if (arrayTweens) { i = arrayTweens.length; while (--i > -1) { e = arrayTweens[i]; val = e.s + e.c * ratio; e.a[e.i] = (val < 0.000001 && val > -0.000001) ? 0 : val; } for (p in this._arrayProps) { this._target[p](this._arrayProps[p]); } } if (layer && !layer._gsDraw) { _layersToDraw.push(layer); layer._gsDraw = true; //a flag indicating that we need to draw() this layer as soon as all the tweens have finished updating (using a "tick" event listener) if (!_listening) { _ticker.addEventListener("tick", _onTick); _listening = true; } } } }); p = KineticPlugin.prototype; p._initArrayTween = function(a, b, prop) { if (!this._arrayTweens) { this._arrayTweens = []; //stores data about any elements that must tween (ones that match in a and b are ignored (no need to waste resources). For example, {a:array, i:0, s:100, c:50} this._arrayProps = {}; //stores data about which properties are associted with which arrays so that we can apply them in the setRatio() method, like target[property](array), as in target.points([1,2,500,600]); } var i = a.length, tweens = this._arrayTweens, start, end; while (--i > -1) { start = a[i]; end = b[i]; if (start !== end) { tweens.push({a:a, i:i, s:start, c:end - start}); } } if (tweens.length) { this._arrayProps[prop] = a; } }; }); if (_gsScope._gsDefine) { _gsScope._gsQueue.pop()(); }
CKEDITOR.plugins.setLang("image2","zh",{alt:"替代文字",btnUpload:"傳送至伺服器",captioned:"已加標題之圖片",infoTab:"影像資訊",lockRatio:"固定比例",menu:"影像屬性",pathName:"圖片",pathNameCaption:"標題",resetSize:"重設大小",resizer:"拖曳以改變大小",title:"影像屬性",uploadTab:"上傳",urlMissing:"遺失圖片來源之 URL "});
"use strict"; const iconv = require("iconv-lite"); const parseContentType = require("./headers").parseContentType; // https://encoding.spec.whatwg.org/encodings.json const encodings = require("./encodings.json"); const encodingsTable = {}; encodings.forEach(v => v.encodings.forEach(enc => { if (iconv.encodingExists(enc.name)) { enc.labels.forEach(label => { encodingsTable[label] = enc.name; }); } })); function canonicalizeEncoding(enc) { return enc ? enc.trim().toLowerCase() : null; } const normalizeEncoding = exports.normalizeEncoding = function (enc) { return enc ? encodingsTable[canonicalizeEncoding(enc)] || null : null; }; exports.decodeString = function decodeString(buffer, options) { let encoding = options.contentType ? normalizeEncoding(options.contentType.get("charset")) : null; if (buffer.length >= 2) { if (buffer[0] === 0xFE && buffer[1] === 0xFF) { encoding = "UTF-16BE"; } else if (buffer[0] === 0xFF && buffer[1] === 0xFE) { encoding = "UTF-16LE"; } else if (buffer.length >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { encoding = "UTF-8"; } } if (!encoding && options.detectMetaCharset) { encoding = prescanMetaCharset(buffer); } encoding = encoding || options.defaultEncoding; return { data: iconv.decode(buffer, encoding), encoding }; }; // https://html.spec.whatwg.org/multipage/syntax.html#prescan-a-byte-stream-to-determine-its-encoding function prescanMetaCharset(buffer) { const l = Math.min(buffer.length, 1024); for (let i = 0; i < l; i++) { let c = buffer[i]; if (c === 0x3C) { // "<" let c1 = buffer[i + 1]; let c2 = buffer[i + 2]; const c3 = buffer[i + 3]; const c4 = buffer[i + 4]; const c5 = buffer[i + 5]; // !-- (comment start) if (c1 === 0x21 && c2 === 0x2D && c3 === 0x2D) { i += 4; for (; i < l; i++) { c = buffer[i]; c1 = buffer[i + 1]; c2 = buffer[i + 2]; // --> (comment end) if (c === 0x2D && c1 === 0x2D && c2 === 0x3E) { i += 2; break; } } } else if ((c1 === 0x4D || c1 === 0x6D) && (c2 === 0x45 || c2 === 0x65) && (c3 === 0x54 || c3 === 0x74) && (c4 === 0x41 || c4 === 0x61) && (c5 === 0x09 || c5 === 0x0A || c5 === 0x0C || c5 === 0x0D || c5 === 0x20 || c5 === 0x2F)) { // "meta" + space or / i += 6; let gotPragma = false; let needPragma = null; let charset = null; let attrRes; do { attrRes = getAttribute(buffer, i, l); if (attrRes.attr) { if (attrRes.attr.name === "http-equiv") { gotPragma = attrRes.attr.value === "content-type"; } else if (attrRes.attr.name === "content" && !charset) { const contentType = parseContentType(attrRes.attr.value); if (contentType && contentType.get("charset")) { charset = contentType.get("charset"); needPragma = true; } } else if (attrRes.attr.name === "charset") { charset = attrRes.attr.value; needPragma = false; } } i = attrRes.i; } while (attrRes.attr); if (needPragma === null) { continue; } if (needPragma === true && gotPragma === false) { continue; } if (charset === "x-user-defined") { return "windows-1252"; } charset = normalizeEncoding(charset); if (!charset) { continue; } return charset; } else if ((c1 >= 0x41 && c1 <= 0x5A) || (c1 >= 0x61 && c1 <= 0x7A)) { // a-z or A-Z for (i += 2; i < l; i++) { c = buffer[i]; // space or > if (c === 0x09 || c === 0x0A || c === 0x0C || c === 0x0D || c === 0x20 || c === 0x3E) { break; } } let attrRes; do { attrRes = getAttribute(buffer, i, l); i = attrRes.i; } while (attrRes.attr); } else if (c1 === 0x21 || c1 === 0x2F || c1 === 0x3F) { // ! or / or ? for (i += 2; i < l; i++) { c = buffer[i]; // > if (c === 0x3E) { break; } } } } } return null; } // https://html.spec.whatwg.org/multipage/syntax.html#concept-get-attributes-when-sniffing function getAttribute(buffer, i, l) { for (; i < l; i++) { let c = buffer[i]; // space or / if (c === 0x09 || c === 0x0A || c === 0x0C || c === 0x0D || c === 0x20 || c === 0x2F) { continue; } // ">" if (c === 0x3E) { i++; break; } let name = ""; let value = ""; nameLoop:for (; i < l; i++) { c = buffer[i]; // "=" if (c === 0x3D && name !== "") { i++; break; } // space if (c === 0x09 || c === 0x0A || c === 0x0C || c === 0x0D || c === 0x20) { for (i++; i < l; i++) { c = buffer[i]; // space if (c === 0x09 || c === 0x0A || c === 0x0C || c === 0x0D || c === 0x20) { continue; } // not "=" if (c !== 0x3D) { return { attr: { name, value }, i }; } i++; break nameLoop; } break; } // / or > if (c === 0x2F || c === 0x3E) { return { attr: { name, value }, i }; } // A-Z if (c >= 0x41 && c <= 0x5A) { name += String.fromCharCode(c + 0x20); // lowercase } else { name += String.fromCharCode(c); } } c = buffer[i]; // space if (c === 0x09 || c === 0x0A || c === 0x0C || c === 0x0D || c === 0x20) { for (i++; i < l; i++) { c = buffer[i]; // space if (c === 0x09 || c === 0x0A || c === 0x0C || c === 0x0D || c === 0x20) { continue; } else { break; } } } // " or ' if (c === 0x22 || c === 0x27) { const quote = c; for (i++; i < l; i++) { c = buffer[i]; if (c === quote) { i++; return { attr: { name, value }, i }; } // A-Z if (c >= 0x41 && c <= 0x5A) { value += String.fromCharCode(c + 0x20); // lowercase } else { value += String.fromCharCode(c); } } } // > if (c === 0x3E) { return { attr: { name, value }, i }; } // A-Z if (c >= 0x41 && c <= 0x5A) { value += String.fromCharCode(c + 0x20); // lowercase } else { value += String.fromCharCode(c); } for (i++; i < l; i++) { c = buffer[i]; // space or > if (c === 0x09 || c === 0x0A || c === 0x0C || c === 0x0D || c === 0x20 || c === 0x3E) { return { attr: { name, value }, i }; } // A-Z if (c >= 0x41 && c <= 0x5A) { value += String.fromCharCode(c + 0x20); // lowercase } else { value += String.fromCharCode(c); } } } return { i }; }
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'wsc', 'sk', { btnIgnore: 'Ignorovať', btnIgnoreAll: 'Ignorovať všetko', btnReplace: 'Prepísat', btnReplaceAll: 'Prepísat všetko', btnUndo: 'Späť', changeTo: 'Zmeniť na', errorLoading: 'Chyba pri načítaní slovníka z adresy: %s.', ieSpellDownload: 'Kontrola pravopisu nie je naištalovaná. Chcete ju teraz stiahnuť?', manyChanges: 'Kontrola pravopisu dokončená: Bolo zmenených %1 slov', noChanges: 'Kontrola pravopisu dokončená: Neboli zmenené žiadne slová', noMispell: 'Kontrola pravopisu dokončená: Neboli nájdené žiadne chyby pravopisu', noSuggestions: '- Žiadny návrh -', notAvailable: 'Prepáčte, ale služba je momentálne nedostupná.', notInDic: 'Nie je v slovníku', oneChange: 'Kontrola pravopisu dokončená: Bolo zmenené jedno slovo', progress: 'Prebieha kontrola pravopisu...', title: 'Skontrolovať pravopis', toolbar: 'Kontrola pravopisu' });
"use strict"; var foo = "test " + foo + " " + bar;
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "\u0635", "\u0645" ], "DAY": [ "\u0627\u0644\u0623\u062d\u062f", "\u0627\u0644\u0627\u062b\u0646\u064a\u0646", "\u0627\u0644\u062b\u0644\u0627\u062b\u0627\u0621", "\u0627\u0644\u0623\u0631\u0628\u0639\u0627\u0621", "\u0627\u0644\u062e\u0645\u064a\u0633", "\u0627\u0644\u062c\u0645\u0639\u0629", "\u0627\u0644\u0633\u0628\u062a" ], "ERANAMES": [ "\u0642\u0628\u0644 \u0627\u0644\u0645\u064a\u0644\u0627\u062f", "\u0645\u064a\u0644\u0627\u062f\u064a" ], "ERAS": [ "\u0642.\u0645", "\u0645" ], "FIRSTDAYOFWEEK": 5, "MONTH": [ "\u064a\u0646\u0627\u064a\u0631", "\u0641\u0628\u0631\u0627\u064a\u0631", "\u0645\u0627\u0631\u0633", "\u0623\u0628\u0631\u064a\u0644", "\u0645\u0627\u064a", "\u064a\u0648\u0646\u064a\u0648", "\u064a\u0648\u0644\u064a\u0648\u0632", "\u063a\u0634\u062a", "\u0634\u062a\u0646\u0628\u0631", "\u0623\u0643\u062a\u0648\u0628\u0631", "\u0646\u0648\u0646\u0628\u0631", "\u062f\u062c\u0646\u0628\u0631" ], "SHORTDAY": [ "\u0627\u0644\u0623\u062d\u062f", "\u0627\u0644\u0627\u062b\u0646\u064a\u0646", "\u0627\u0644\u062b\u0644\u0627\u062b\u0627\u0621", "\u0627\u0644\u0623\u0631\u0628\u0639\u0627\u0621", "\u0627\u0644\u062e\u0645\u064a\u0633", "\u0627\u0644\u062c\u0645\u0639\u0629", "\u0627\u0644\u0633\u0628\u062a" ], "SHORTMONTH": [ "\u064a\u0646\u0627\u064a\u0631", "\u0641\u0628\u0631\u0627\u064a\u0631", "\u0645\u0627\u0631\u0633", "\u0623\u0628\u0631\u064a\u0644", "\u0645\u0627\u064a", "\u064a\u0648\u0646\u064a\u0648", "\u064a\u0648\u0644\u064a\u0648\u0632", "\u063a\u0634\u062a", "\u0634\u062a\u0646\u0628\u0631", "\u0623\u0643\u062a\u0648\u0628\u0631", "\u0646\u0648\u0646\u0628\u0631", "\u062f\u062c\u0646\u0628\u0631" ], "STANDALONEMONTH": [ "\u064a\u0646\u0627\u064a\u0631", "\u0641\u0628\u0631\u0627\u064a\u0631", "\u0645\u0627\u0631\u0633", "\u0623\u0628\u0631\u064a\u0644", "\u0645\u0627\u064a", "\u064a\u0648\u0646\u064a\u0648", "\u064a\u0648\u0644\u064a\u0648\u0632", "\u063a\u0634\u062a", "\u0634\u062a\u0646\u0628\u0631", "\u0623\u0643\u062a\u0648\u0628\u0631", "\u0646\u0648\u0646\u0628\u0631", "\u062f\u062c\u0646\u0628\u0631" ], "WEEKENDRANGE": [ 4, 5 ], "fullDate": "EEEE\u060c d MMMM\u060c y", "longDate": "d MMMM\u060c y", "medium": "dd\u200f/MM\u200f/y h:mm:ss a", "mediumDate": "dd\u200f/MM\u200f/y", "mediumTime": "h:mm:ss a", "short": "d\u200f/M\u200f/y h:mm a", "shortDate": "d\u200f/M\u200f/y", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "dh", "DECIMAL_SEP": ",", "GROUP_SEP": ".", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-\u00a4\u00a0", "negSuf": "", "posPre": "\u00a4\u00a0", "posSuf": "" } ] }, "id": "ar-ma", "pluralCat": function(n, opt_precision) { if (n == 0) { return PLURAL_CATEGORY.ZERO; } if (n == 1) { return PLURAL_CATEGORY.ONE; } if (n == 2) { return PLURAL_CATEGORY.TWO; } if (n % 100 >= 3 && n % 100 <= 10) { return PLURAL_CATEGORY.FEW; } if (n % 100 >= 11 && n % 100 <= 99) { return PLURAL_CATEGORY.MANY; } return PLURAL_CATEGORY.OTHER;} }); }]);
angular.module('demo.device.ctrl', []) .controller('DeviceCtrl', function ($scope, $state, $cordovaDevice) { var init = function () { console.log("initializing device"); try { document.addEventListener("deviceready", function () { $scope.available = $cordovaDevice.getDevice().available; $scope.cordova = $cordovaDevice.getCordova(); $scope.model = $cordovaDevice.getModel(); $scope.platform = $cordovaDevice.getPlatform(); $scope.uuid = $cordovaDevice.getUUID(); $scope.version = $cordovaDevice.getVersion(); }, false); } catch (err) { console.log("Error " + err.message); alert("error " + err.$$failure.message); } }; init(); });
[/q/]
 Type.registerNamespace("Strings"); Strings.OfficeOM = function() { }; Strings.OfficeOM.registerClass("Strings.OfficeOM"); Strings.OfficeOM.L_InvalidNamedItemForBindingType = "O tipo de vinculación especificada non é compatible co elemento con nome fornecido."; Strings.OfficeOM.L_EventHandlerNotExist = "Non se atopou o indicador de eventos especificado para esta vinculación."; Strings.OfficeOM.L_UnknownBindingType = "O tipo de vinculación non é compatible."; Strings.OfficeOM.L_InvalidNode = "Nodo non válido"; Strings.OfficeOM.L_NotImplemented = "A función {0} non está implementada."; Strings.OfficeOM.L_NoCapability = "Non tes permisos suficientes para esta acción."; Strings.OfficeOM.L_SettingsCannotSave = "Non se pode gardar a configuración."; Strings.OfficeOM.L_DataWriteReminder = "Aviso de escribir datos"; Strings.OfficeOM.L_InvalidBinding = "Vinculación non válida"; Strings.OfficeOM.L_InvalidSetColumns = "As columnas especificadas non son válidas."; Strings.OfficeOM.L_BindingCreationError = "Erro de creación da vinculación"; Strings.OfficeOM.L_FormatValueOutOfRange = "O valor está fóra do intervalo permitido."; Strings.OfficeOM.L_SelectionNotSupportCoercionType = "A selección actual non é compatible co tipo de coerción especificada."; Strings.OfficeOM.L_InvalidBindingError = "Erro de vinculación non válida"; Strings.OfficeOM.L_InvalidGetStartRowColumn = "Os valores de startRow ou startColumn especificados non son válidos."; Strings.OfficeOM.L_InvalidSetRows = "As filas especificadas non son válidas."; Strings.OfficeOM.L_CannotWriteToSelection = "Non se pode escribir na selección actual."; Strings.OfficeOM.L_MissingParameter = "Parámetro ausente"; Strings.OfficeOM.L_IndexOutOfRange = "Índice fóra do intervalo."; Strings.OfficeOM.L_SettingsStaleError = "Erro de configuración obsoleta"; Strings.OfficeOM.L_CannotNavigateTo = "O obxecto está situado nun lugar onde a navegación non é compatible."; Strings.OfficeOM.L_ReadSettingsError = "Erro de configuración da función ler"; Strings.OfficeOM.L_InvalidGetColumns = "As columnas especificadas non son válidas."; Strings.OfficeOM.L_CoercionTypeNotSupported = "O tipo de coerción especificado non é compatible."; Strings.OfficeOM.L_AppNotExistInitializeNotCalled = "A aplicación {0} non existe. Non se chamou a Microsoft.Office.WebExtension.initialize(motivo)."; Strings.OfficeOM.L_OverwriteWorksheetData = "A operación de conxunto fallou porque o obxecto de datos fornecido sobrescribirá ou intercambiará datos."; Strings.OfficeOM.L_RowIndexOutOfRange = "O valor do índice de fila está fóra do intervalo permitido. Utiliza un valor (0 ou superior) menor que o número de filas."; Strings.OfficeOM.L_InvalidReadForBlankRow = "A fila especificada está en branco."; Strings.OfficeOM.L_ColIndexOutOfRange = "O valor do índice de columna está fóra do intervalo permitido. Utiliza un valor (0 ou superior) menor que o número de columnas."; Strings.OfficeOM.L_UnsupportedEnumeration = "Enumeración non compatible"; Strings.OfficeOM.L_InvalidParameters = "A función {0} ten parámetros non válidos."; Strings.OfficeOM.L_SetDataParametersConflict = "Os parámetros especificados teñen conflitos."; Strings.OfficeOM.L_DataNotMatchCoercionType = "O tipo do obxecto de datos especificado non é compatible coa selección actual."; Strings.OfficeOM.L_UnsupportedEnumerationMessage = "A enumeración non é compatible coa aplicación do computador servidor actual."; Strings.OfficeOM.L_InvalidCoercion = "Tipo de coerción non válido"; Strings.OfficeOM.L_NotSupportedEventType = "O tipo de evento especificado {0} non é compatible."; Strings.OfficeOM.L_UnsupportedDataObject = "O tipo de obxecto de datos fornecido non é compatible."; Strings.OfficeOM.L_GetDataIsTooLarge = "O conxunto de datos solicitados é moi grande."; Strings.OfficeOM.L_AppNameNotExist = "AppName para {0} non existe."; Strings.OfficeOM.L_AddBindingFromPromptDefaultText = "Fai unha selección."; Strings.OfficeOM.L_MultipleNamedItemFound = "Atopáronse varios obxectos co mesmo nome."; Strings.OfficeOM.L_InvalidCellsValue = "Un ou máis dos parámetros de celas teñen valores non permitidos. Verifica outra vez os valores e téntao de novo."; Strings.OfficeOM.L_DataNotMatchBindingType = "O obxecto de datos especificado non é compatible co tipo de vinculación."; Strings.OfficeOM.L_InvalidFormatValue = "Un ou máis dos parámetros de formato teñen valores non permitidos. Verifica outra vez os valores e téntao de novo."; Strings.OfficeOM.L_NotSupportedBindingType = "O tipo de vinculación especificado {0} non é compatible."; Strings.OfficeOM.L_InitializeNotReady = "Aínda non se cargou totalmente Office.js. Téntao de novo máis tarde ou asegúrate de engadir o teu código de inicialización na función Office.initialize."; Strings.OfficeOM.L_FormattingReminder = "Aviso de formatación"; Strings.OfficeOM.L_ShuttingDown = "A operación fallou porque os datos no servidor non son actuais."; Strings.OfficeOM.L_OperationNotSupported = "A operación non é compatible."; Strings.OfficeOM.L_DocumentReadOnly = "A operación solicitada non se permite no modo de documento actual."; Strings.OfficeOM.L_NamedItemNotFound = "O elemento con nome non existe."; Strings.OfficeOM.L_InvalidApiCallInContext = "Chamada API non válida no contexto actual."; Strings.OfficeOM.L_InvalidGetRows = "As filas especificadas non son válidas."; Strings.OfficeOM.L_CellFormatAmountBeyondLimits = "Nota: Suxírese que os conxuntos de formatación configurados por unha chamada á API de formatación sexan inferiores a 100."; Strings.OfficeOM.L_SetDataIsTooLarge = "O obxecto de datos especificado é moi grande."; Strings.OfficeOM.L_DataWriteError = "Erro de escritura de datos"; Strings.OfficeOM.L_InvalidBindingOperation = "Operación de vinculación non válida"; Strings.OfficeOM.L_SpecifiedIdNotExist = "O ID especificado non existe."; Strings.OfficeOM.L_FunctionCallFailed = "Erro na chamada da función {0}, código de erro: {1}."; Strings.OfficeOM.L_DataNotMatchBindingSize = "O obxecto de datos fornecido non coincide co tamaño da selección actual."; Strings.OfficeOM.L_SaveSettingsError = "Erro de configuración da función gardar"; Strings.OfficeOM.L_InvalidSetStartRowColumn = "Os valores de startRow ou startColumn especificados non son válidos."; Strings.OfficeOM.L_InvalidFormat = "Erro de formato non válido"; Strings.OfficeOM.L_BindingNotExist = "A vinculación especificada non existe."; Strings.OfficeOM.L_SettingNameNotExist = "O nome de configuración especificada non existe."; Strings.OfficeOM.L_EventHandlerAdditionFailed = "Erro ao engadir o indicador de eventos."; Strings.OfficeOM.L_InvalidAPICall = "Chamada API non válida"; Strings.OfficeOM.L_EventRegistrationError = "Erro do rexistro de eventos"; Strings.OfficeOM.L_ElementMissing = "Non puidemos formatar a cela da táboa porque algúns valores de parámetros están ausentes. Verifica outra vez os parámetros e téntao de novo."; Strings.OfficeOM.L_NonUniformPartialSetNotSupported = "Coordinar parámetros non se pode utilizar co tipo de coerción Táboa cando a táboa contén celas combinadas."; Strings.OfficeOM.L_NavOutOfBound = "A operación fallou porque o índice está fóra do intervalo."; Strings.OfficeOM.L_RedundantCallbackSpecification = "A chamada de retorno non se pode especificar na lista de argumentos e no obxecto opcional."; Strings.OfficeOM.L_CustomXmlError = "Erro de XML personalizado."; Strings.OfficeOM.L_SettingsAreStale = "Non se puido gardar a configuración porque non é actual."; Strings.OfficeOM.L_TooManyOptionalFunction = "múltiples funcións opcionais na lista de parámetros"; Strings.OfficeOM.L_MissingRequiredArguments = "faltan algúns argumentos obrigatorios"; Strings.OfficeOM.L_NonUniformPartialGetNotSupported = "Coordinar parámetros non se pode utilizar co tipo de coerción Táboa cando a táboa contén celas combinadas."; Strings.OfficeOM.L_HostError = "Erro do computador servidor"; Strings.OfficeOM.L_OutOfRange = "Fóra do intervalo"; Strings.OfficeOM.L_InvalidSelectionForBindingType = "Non se pode crear unha vinculación coa selección actual e o tipo de vinculación especificada."; Strings.OfficeOM.L_TooManyOptionalObjects = "múltiples obxectos opcionais na lista de parámetros"; Strings.OfficeOM.L_OperationNotSupportedOnMatrixData = "O contido seleccionado ten que estar en formato de táboa. Formata os datos como unha táboa e téntao de novo."; Strings.OfficeOM.L_EventHandlerRemovalFailed = "Erro ao eliminar o indicador de eventos."; Strings.OfficeOM.L_BindingToMultipleSelection = "As seleccións non contiguas non son compatibles."; Strings.OfficeOM.L_DataReadError = "Erro de lectura de datos"; Strings.OfficeOM.L_InternalErrorDescription = "Houbo un erro interno."; Strings.OfficeOM.L_InvalidDataFormat = "O formato do obxecto de datos especificado non é válido."; Strings.OfficeOM.L_DataStale = "Datos non actuais"; Strings.OfficeOM.L_GetSelectionNotSupported = "A selección actual non é compatible."; Strings.OfficeOM.L_CellDataAmountBeyondLimits = "Nota: Suxírese que o número de celas nunha táboa sexa inferior a 20.000 celas."; Strings.OfficeOM.L_InvalidTableOptionValue = "Un ou máis dos parámetros tableOptions teñen valores non permitidos. Verifica outra vez os valores e téntao de novo."; Strings.OfficeOM.L_PermissionDenied = "Permiso negado"; Strings.OfficeOM.L_InvalidDataObject = "Obxecto de datos non válido"; Strings.OfficeOM.L_UserNotSignedIn = "No user is signed into Office."; Strings.OfficeOM.L_SelectionCannotBound = "Non se pode ligar á selección actual."; Strings.OfficeOM.L_InvalidColumnsForBinding = "As columnas especificadas non son válidas."; Strings.OfficeOM.L_BadSelectorString = "A cadea pasada ao selector non ten o formato correcto ou non é compatible."; Strings.OfficeOM.L_InvalidGetRowColumnCounts = "Os valores de rowCount ou columnCount especificados non son válidos."; Strings.OfficeOM.L_OsfControlTypeNotSupported = "O tipo OsfControl non é compatible."; Strings.OfficeOM.L_InvalidValue = "Valor non válido"; Strings.OfficeOM.L_DataNotMatchSelection = "O obxecto de datos fornecido non é compatible coa forma ou as dimensións da selección actual."; Strings.OfficeOM.L_InternalError = "Erro interno"; Strings.OfficeOM.L_NotSupported = "A función {0} non é compatible."; Strings.OfficeOM.L_CustomXmlNodeNotFound = "Non se atopou o nodo especificado."; Strings.OfficeOM.L_CoercionTypeNotMatchBinding = "O tipo de coerción especificado non é compatible con este tipo de vinculación."; Strings.OfficeOM.L_TooManyArguments = "número excesivo de argumentos"; Strings.OfficeOM.L_OperationNotSupportedOnThisBindingType = "A operación non é compatible neste tipo de vinculación."; Strings.OfficeOM.L_InValidOptionalArgument = "argumento opcional non válido"; Strings.OfficeOM.L_FileTypeNotSupported = "O tipo de ficheiro especificado non é compatible."; Strings.OfficeOM.L_GetDataParametersConflict = "Os parámetros especificados teñen conflitos."; Strings.OfficeOM.L_CallbackNotAFunction = "A chamada de retorno debe ser de tipo función, pero era de tipo {0}."
define( "dojo/cldr/nls/fi/roc", //begin v1.x content { "field-second": "sekunti", "field-year-relative+-1": "viime vuonna", "field-week": "viikko", "field-month-relative+-1": "viime kuussa", "field-day-relative+-1": "eilen", "field-day-relative+-2": "toissapäivänä", "field-year": "vuosi", "field-week-relative+0": "tällä viikolla", "field-week-relative+1": "ensi viikolla", "field-minute": "minuutti", "field-week-relative+-1": "viime viikolla", "field-day-relative+0": "tänään", "field-hour": "tunti", "field-day-relative+1": "huomenna", "field-day-relative+2": "ylihuomenna", "field-day": "päivä", "field-month-relative+0": "tässä kuussa", "field-month-relative+1": "ensi kuussa", "field-dayperiod": "vuorokaudenaika", "field-month": "kuukausi", "field-era": "aikakausi", "field-year-relative+0": "tänä vuonna", "field-year-relative+1": "ensi vuonna", "eraAbbr": [ "Before R.O.C.", "Minguo" ], "field-weekday": "viikonpäivä", "field-zone": "aikavyöhyke" } //end v1.x content );
(function(global) { Ember.libraries.register('Ember Simple Auth Testing', '0.8.0-beta.3'); var define, requireModule; (function() { var registry = {}, seen = {}; define = function(name, deps, callback) { registry[name] = { deps: deps, callback: callback }; }; requireModule = function(name) { if (seen.hasOwnProperty(name)) { return seen[name]; } seen[name] = {}; if (!registry[name]) { throw new Error("Could not find module " + name); } var mod = registry[name], deps = mod.deps, callback = mod.callback, reified = [], exports; for (var i=0, l=deps.length; i<l; i++) { if (deps[i] === 'exports') { reified.push(exports = {}); } else { reified.push(requireModule(resolve(deps[i]))); } } var value = callback.apply(this, reified); return seen[name] = exports || value; function resolve(child) { if (child.charAt(0) !== '.') { return child; } var parts = child.split("/"); var parentBase = name.split("/").slice(0, -1); for (var i=0, l=parts.length; i<l; i++) { var part = parts[i]; if (part === '..') { parentBase.pop(); } else if (part === '.') { continue; } else { parentBase.push(part); } } return parentBase.join("/"); } }; requireModule.registry = registry; })(); define("simple-auth-testing/authenticators/test", ["simple-auth/authenticators/base","exports"], function(__dependency1__, __exports__) { "use strict"; var Base = __dependency1__["default"]; __exports__["default"] = Base.extend({ restore: function(data) { return Ember.RSVP.resolve(); }, authenticate: function(options) { return Ember.RSVP.resolve(); }, invalidate: function(data) { return Ember.RSVP.resolve(); } }); }); define("simple-auth-testing/ember", ["./initializer"], function(__dependency1__) { "use strict"; var initializer = __dependency1__["default"]; Ember.onLoad('Ember.Application', function(Application) { Application.initializer(initializer); }); }); define("simple-auth-testing/initializer", ["simple-auth-testing/authenticators/test","exports"], function(__dependency1__, __exports__) { "use strict"; var TestAuthenticator = __dependency1__["default"]; __exports__["default"] = { name: 'simple-auth-testing', before: 'simple-auth', initialize: function(container, application) { application.register('simple-auth-authenticator:test', TestAuthenticator); } }; }); define("simple-auth-testing/test-helpers", ["simple-auth/configuration","exports"], function(__dependency1__, __exports__) { "use strict"; var Configuration = __dependency1__["default"]; __exports__["default"] = function() { Ember.Test.registerAsyncHelper('authenticateSession', function(app) { var session = app.__container__.lookup(Configuration.session); session.authenticate('simple-auth-authenticator:test'); return wait(); }); Ember.Test.registerHelper('currentSession', function(app) { var session = app.__container__.lookup(Configuration.session); return session; }); Ember.Test.registerAsyncHelper('invalidateSession', function(app) { var session = app.__container__.lookup(Configuration.session); if (session.get('isAuthenticated')) { session.invalidate(); } return wait(); }); } }); define('simple-auth/authenticators/base', ['exports'], function(__exports__) { __exports__['default'] = global.SimpleAuth.Authenticators.Base; }); define('simple-auth/configuration', ['exports'], function(__exports__) { __exports__['default'] = global.SimpleAuth.Configuration; }); requireModule('simple-auth-testing/ember'); requireModule('simple-auth-testing/test-helpers'); })((typeof global !== 'undefined') ? global : window);
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang("codesnippet","en-gb",{button:"Insert Code Snippet",codeContents:"Code content",emptySnippetError:"A code snippet cannot be empty.",language:"Language",title:"Code snippet",pathName:"code snippet"});
import Ember from 'ember'; var FeatureController = Ember.Controller.extend(Ember.PromiseProxyMixin, { init: function () { var promise; promise = this.store.find('setting', {type: 'blog,theme'}).then(function (settings) { return settings.get('firstObject'); }); this.set('promise', promise); }, setting: Ember.computed.alias('content'), labs: Ember.computed('isSettled', 'setting.labs', function () { var value = {}; if (this.get('isFulfilled')) { try { value = JSON.parse(this.get('setting.labs') || {}); } catch (err) { value = {}; } } return value; }) }); export default FeatureController;
/*! Qoopido.js library 3.6.8, 2015-07-09 | https://github.com/dlueth/qoopido.js | (c) 2015 Dirk Lueth */ !function(e){window.qoopido.register("polyfill/document/queryselectorall",e)}(function(e,t,r,s,l,o,n){"use strict";return o.querySelectorAll||(o.querySelectorAll=function(e){var t,r=l.document.getElementsByTagName("script")[0],s=o.createElement("style"),n=[];for(r.parentNode.insertBefore(s,r),o._qsa=[],s.styleSheet.cssText=e+"{x-qsa:expression(document._qsa && document._qsa.push(this))}",l.scrollBy(0,0),s.parentNode.removeChild(s);o._qsa.length;)t=o._qsa.shift(),t.style.removeAttribute("x-qsa"),n.push(t);try{delete o._qsa}catch(c){o._qsa=null}return n}),o.querySelectorAll});
var _ = require('lodash'); var uuid = require('node-uuid'); _.str = require('underscore.string'); var Promise = global.testPromise; var equal = require('assert').equal; var deepEqual = require('assert').deepEqual; module.exports = function(bookshelf) { describe('Model', function() { var Backbone = require('backbone'); var Models = require('./helpers/objects')(bookshelf).Models; var stubSync = { first: function() { return Promise.resolve({}); }, select: function() { return Promise.resolve({}); }, insert: function() { return Promise.resolve({}); }, update: function() { return Promise.resolve(1); }, del: function() { return Promise.resolve({}); } }; describe('extend/constructor/initialize', function() { var User = bookshelf.Model.extend({ idAttribute: 'user_id', getData: function() { return 'test'; } }, { classMethod: function() { return 'test'; } }); var SubUser = User.extend({ otherMethod: function() { return this.getData(); } }, { classMethod2: function() { return 'test2'; } }); it('can be extended', function() { var user = new User(); var subUser = new SubUser(); expect(user.idAttribute).to.equal('user_id'); expect(user.getData()).to.equal('test'); expect(subUser.otherMethod()).to.equal('test'); expect(User.classMethod()).to.equal('test'); expect(SubUser.classMethod()).to.equal('test'); expect(SubUser.classMethod2()).to.equal('test2'); }); it('accepts a custom `constructor` property', function() { var User = bookshelf.Model.extend({ constructor: function() { this.item = 'test'; bookshelf.Model.apply(this, arguments); } }); equal(new User().item, 'test'); }); it('doesnt have ommitted Backbone properties', function() { expect(User.prototype.changedAttributes).to.be.undefined; expect((new User()).changedAttributes).to.be.undefined; }); }); describe('forge', function() { it('should create a new model instance', function() { var User = bookshelf.Model.extend({ tableName: 'users' }); var user = User.forge(); equal(user.tableName, 'users'); }); }); describe('id, idAttribute', function() { it('should attach the id as a property on the model', function() { var test = new bookshelf.Model({id: 1}); equal(test.id, (1)); }); it('should reference idAttribute as the key for model.id', function() { var Test = bookshelf.Model.extend({ idAttribute: '_id' }); var test2 = new Test({_id: 2}); equal(test2.id, (2)); }); }); describe('get', function() { it('should use the same get method as the Backbone library', function() { var attached = ['get']; _.each(attached, function(item) { deepEqual(bookshelf.Model.prototype[item], Backbone.Model.prototype[item]); }); }); }); describe('query', function() { var model; beforeEach(function() { model = new bookshelf.Model(); }); it('returns the Knex builder when no arguments are passed', function() { equal((model.query() instanceof bookshelf.knex.client.QueryBuilder), true); }); it('calls Knex builder method with the first argument, returning the model', function() { var q = model.query('where', {id:1}); equal(q, (model)); }); it('passes along additional arguments to the Knex method in the first argument', function() { var qb = model.resetQuery().query(); equal(_.where(qb._statements, {grouping: 'where'}).length, 0); var q = model.query('where', {id:1}); equal(q, (model)); equal(_.where(qb._statements, {grouping: 'where'}).length, 1); }); it('allows passing an object to query', function() { var qb = model.resetQuery().query(); equal(_.where(qb._statements, {grouping: 'where'}).length, 0); var q = model.query({where: {id: 1}, orWhere: ['id', '>', '10']}); equal(q, model); equal(_.where(qb._statements, {grouping: 'where'}).length, 2); }); it('allows passing an function to query', function() { var qb = model.resetQuery().query(); equal(_.where(qb._statements, {grouping: 'where'}).length, 0); var q = model.query(function(qb) { this.where({id: 1}).orWhere('id', '>', '10'); }); equal(q, model); equal(_.where(qb._statements, {grouping: 'where'}).length, 2); qb = model.resetQuery().query(); equal(_.where(qb._statements, {grouping: 'where'}).length, 0); q = model.query(function(qb) { qb.where({id: 1}).orWhere('id', '>', '10'); }); equal(q, model); equal(_.where(qb._statements, {grouping: 'where'}).length, 2); }); }); describe('tableName', function() { var table = new bookshelf.Model({}, {tableName: 'customers'}); it('can be passed in the initialize options', function() { equal(table.tableName, 'customers'); }); it('should set the tableName for the query builder', function() { // TODO: Make this doable again... // equal(_.findWhere(table.query().statements, {grouping: 'table'}).value, '`customers`'); }); }); describe('toJSON', function() { it('includes the idAttribute in the hash', function() { var m = new (bookshelf.Model.extend({ idAttribute: '_id' }))({'_id': 1, 'name': 'Joe'}); deepEqual(m.toJSON(), {'_id': 1, 'name': 'Joe'}); }); it('includes the relations loaded on the model, unless {shallow: true} is passed.', function() { var m = new bookshelf.Model({id: 1, name: 'Test'}); m.relations = {someList: new bookshelf.Collection([{id:1}, {id:2}])}; var json = m.toJSON(); deepEqual(_.keys(json), ['id', 'name', 'someList']); equal(json.someList.length, 2); var shallow = m.toJSON({shallow:true}); deepEqual(_.keys(shallow), ['id', 'name']); }); }); describe('parse', function() { var ParsedSite = Models.Site.extend({ parse: function (attrs) { attrs.name = 'Test: ' + attrs.name; return attrs; } }); it('parses the model attributes on fetch', function() { return new ParsedSite({id: 1}) .fetch() .then(function(model) { equal(model.get('name').indexOf('Test: '), 0); }); }); it('parses the model attributes on creation if {parse: true} is passed', function() { var one = new ParsedSite({name: 'Site'}); equal(one.get('name'), 'Site'); var two = new ParsedSite({name: 'Site'}, {parse: true}); equal(two.get('name'), 'Test: Site'); }); }); describe('format', function() { // TODO: better way to test this. it('calls format when saving', function() { var M = bookshelf.Model.extend({ tableName: 'test', format: function(attrs) { return _.reduce(attrs, function(memo, val, key) { memo[_.str.underscored(key)] = val; return memo; }, {}); } }); var m = new M({firstName: 'Tim', lastName: 'G'}); m.sync = function() { var data = this.format(_.extend({}, this.attributes)); equal(data.first_name, 'Tim'); equal(data.last_name, 'G'); return stubSync; }; return m.save(); }); it('does not mutate attributes on format', function() { var M = bookshelf.Model.extend({ tableName: 'sites', format: function(attrs) { assert.ok(attrs !== this.attributes); return attrs; } }); return M.forge({id: 1}).fetch().call('load'); }); }); describe('fetch', function() { var Site = Models.Site; it('issues a first (get one) to Knex, triggering a fetched event, returning a promise', function() { var count = 0; var model = Site.forge({id: 1}); model.on('fetched', function() { count++; }); return model.fetch().then(function(model) { equal(model.get('id'), 1); equal(model.get('name'), 'knexjs.org'); equal(count, 1); }); }); it('has a fetching event, which will fail if an error is thrown or if a rejected promise is provided', function() { var model = new Site({id: 1}); model.on('fetching', function() { throw new Error('This failed'); }); return expect(model.fetch()).to.be.rejected; }); it('allows access to the query builder on the options object in the fetching event', function() { var model = new Site({id: 1}); model.on('fetching', function(model, columns, options) { expect(options.query.whereIn).to.be.a.function; }); return model.fetch(); }); it('does not fail, when joining another table having some columns with the same names - #176', function () { var model = new Site({id: 1}); model.query(function (qb) { qb.join('authors', 'authors.site_id', '=', 'sites.id'); }); return expect(model.fetch()).to.be.fulfilled; }); }); describe('save', function() { var Site = Models.Site; it('saves a new object', function() { return new Site({name: 'Fourth Site'}).save().then(function(m) { equal(m.get('id'), 4); return new bookshelf.Collection(null, {model: Site}).fetch(); }) .then(function(c) { equal(c.last().id, 4); equal(c.last().get('name'), 'Fourth Site'); equal(c.length, 4); }); }); it('updates an existing object', function() { return new Site({id: 4, name: 'Fourth Site Updated'}).save() .then(function() { return new bookshelf.Collection(null, {model: Site}).fetch(); }) .then(function(c) { equal(c.last().id, 4); equal(c.last().get('name'), 'Fourth Site Updated'); equal(c.length, 4); }); }); it('allows passing a method to save, to call insert or update explicitly', function() { return new Site({id: 5, name: 'Fifth site, explicity created'}).save(null, {method: 'insert'}) .then(function() { return Site.fetchAll(); }) .then(function(c) { equal(c.length, 5); equal(c.last().id, 5); equal(c.last().get('name'), 'Fifth site, explicity created'); }); }); it('errors if the row was not updated', function() { return new Site({id: 200, name: 'This doesnt exist'}).save().then(function() { throw new Error('This should not succeed'); }, function(err) { expect(err.message).to.equal('No rows were affected in the update, did you mean to pass the {method: "insert"} option?'); }); }); it('should not error if updated row was not affected', function() { return new Site({id: 5, name: 'Fifth site, explicity created'}).save(); }); it('does not constrain on the `id` during update unless defined', function() { var m = new bookshelf.Model({id: null}).query({where: {uuid: 'testing'}}); var query = m.query(); query.update = function() { equal(_.where(this._statements, {grouping: 'where'}).length, 1); return Promise.resolve(1); }; return m.save(null, {method: 'update'}).then(function() { var m2 = new bookshelf.Model({id: 1}).query({where: {uuid: 'testing'}}); var query2 = m2.query(); query2.update = function() { equal(_.where(this._statements, {grouping: 'where'}).length, 2); return {}; }; return m2.save(null, {method: 'update'}); }); }); it('allows {patch: true} as an option for only updating passed data', function() { var user = new bookshelf.Model({id: 1, first_name: 'Testing'}, {tableName: 'users'}); var query = user.query(); query.then = function(onFulfilled, onRejected) { deepEqual(this._single.update, {bio: 'Short user bio'}); equal(_.where(this._statements, {grouping: 'where'}).length, 1); return Promise.resolve(1).then(onFulfilled, onRejected); }; return user .save({bio: 'Short user bio'}, {patch: true}) .then(function(model) { equal(model.id, 1); equal(model.get('bio'), 'Short user bio'); equal(model.get('first_name'), 'Testing'); }); }); it('fires saving and creating and then saves', function() { var user = new bookshelf.Model({first_name: 'Testing'}, {tableName: 'users'}); var query = user.query(); var events = 0; user.sync = function() { return _.extend(stubSync, { insert: function() { equal(events, 2); return Promise.resolve({}); } }); }; user.on('creating saving updating', function() { return Promise.resolve().then(function() { return Promise.resolve().then(function() { events++; }); }); }); return user.save(); }); it('rejects if the saving event throws an error', function() { var Test = bookshelf.Model.extend({ tableName: 'test', initialize: function() { this.on('saving', this.handler, this); }, handler: function() { throw new Error('Test'); } }); var test = new Test; return test.save().catch(function(e) { expect(e.message).to.equal('Test'); }); }); it('Allows setting a uuid, #24 #130', function() { var uuidval = uuid.v4(); var SubSite = Models.Uuid.extend({ initialize: function() { this.on('saving', this._generateId); }, _generateId: function (model, attrs, options) { if (model.isNew()) { model.set(model.idAttribute, uuidval); } } }); var subsite = new SubSite({name: 'testing'}); return subsite.save().then(function(model) { expect(model.id).to.equal(uuidval); expect(model.get('name')).to.equal('testing'); }).then(function() { return new SubSite({uuid: uuidval}).fetch(); }).then(function(model) { expect(model.get('name')).to.equal('testing'); }); }); }); describe('destroy', function() { var Site = Models.Site; it('issues a delete to the Knex, returning a promise', function() { return new Site({id: 5}).destroy().then(function() { return new bookshelf.Collection(null, {model: Site}).fetch(); }) .then(function(c) { equal(c.length, 4); }); }); it('fails if no idAttribute or wheres are defined on the model.', function() { return new Site().destroy().then(null, function(e) { equal(e.toString(), 'Error: A model cannot be destroyed without a "where" clause or an idAttribute.'); }); }); it('triggers a destroying event on the model', function(ok) { var m = new Site({id: 4}); m.on('destroying', function() { m.off(); ok(); }); m.destroy(); }); it('will not destroy the model if an error is thrown during the destroying event', function() { var m = new Site({id: 1}); m.on('destroying', function(model) { if (model.id === 1) { throw new Error("You cannot destroy the first site"); } }); return m.destroy().then(null, function(e) { equal(e.toString(), 'Error: You cannot destroy the first site'); }); }); it('allows access to the query builder on the options object in the destroying event', function() { var m = new Site({id: 1}); m.sync = function () { var sync = stubSync; sync.query = m.query(); return sync; }; m.on('destroying', function(model, options) { expect(options.query.whereIn).to.be.a.function; }); return m.destroy(); }); }); describe('resetQuery', function() { it('deletes the `_builder` property, resetting the model query builder', function() { var m = new bookshelf.Model().query('where', {id: 1}); equal(_.where(m.query()._statements, {grouping: 'where'}).length, 1); m.resetQuery(); equal(_.where(m.query()._statements, {grouping: 'where'}).length, 0); }); }); describe('hasTimestamps', function() { it('will set the created_at and updated_at columns if true', function() { var m = new (bookshelf.Model.extend({hasTimestamps: true}))(); m.sync = function() { equal(this.get('item'), 'test'); equal(_.isDate(this.get('created_at')), true); equal(_.isDate(this.get('updated_at')), true); return stubSync; }; return m.save({item: 'test'}); }); it('only sets the updated_at for existing models', function() { var m1 = new (bookshelf.Model.extend({hasTimestamps: true}))(); m1.sync = function() { equal(this.get('item'), 'test'); equal(_.isDate(this.get('updated_at')), true); return stubSync; }; return m1.save({item: 'test'}); }); it('allows passing hasTimestamps in the options hash', function() { var m = new bookshelf.Model(null, {hasTimestamps: true}); m.sync = function() { equal(this.get('item'), 'test'); equal(_.isDate(this.get('created_at')), true); equal(_.isDate(this.get('updated_at')), true); return stubSync; }; return m.save({item: 'test'}); }); it('allows custom keys for the created at & update at values', function() { var m = new bookshelf.Model(null, {hasTimestamps: ['createdAt', 'updatedAt']}); m.sync = function() { equal(this.get('item'), 'test'); equal(_.isDate(this.get('createdAt')), true); equal(_.isDate(this.get('updatedAt')), true); return stubSync; }; return m.save({item: 'test'}); }); it('does not set created_at when {method: "update"} is passed', function() { var m = new bookshelf.Model(null, {hasTimestamps: true}); m.sync = function() { equal(this.get('item'), 'test'); equal(_.isDate(this.get('created_at')), false); equal(_.isDate(this.get('updated_at')), true); return stubSync; }; return m.save({item: 'test'}, {method: 'update'}); }); it('sets created_at when {method: "insert"} is passed', function() { var m = new bookshelf.Model(null, {hasTimestamps: true}); m.sync = function() { equal(this.id, 1); equal(this.get('item'), 'test'); equal(_.isDate(this.get('created_at')), true); equal(_.isDate(this.get('updated_at')), true); return stubSync; }; return m.save({id: 1, item: 'test'}, {method: 'insert'}); }); it('will accept a falsy value as an option for created and ignore it', function() { var m = new bookshelf.Model(null, {hasTimestamps: ['createdAt', null]}); m.sync = function() { equal(this.get('item'), 'test'); equal(_.isDate(this.get('createdAt')), true); equal(_.isDate(this.get('updatedAt')), false); return stubSync; }; return m.save({item: 'test'}); }); it('will accept a falsy value as an option for updated and ignore it', function() { var m = new bookshelf.Model(null, {hasTimestamps: [null, 'updatedAt']}); m.sync = function() { equal(this.get('item'), 'test'); equal(_.isDate(this.get('updatedAt')), true); equal(_.isDate(this.get('createdAt')), false); return stubSync; }; return m.save({item: 'test'}); }); }); describe('timestamp', function() { it('will set the `updated_at` attribute to a date, and the `created_at` for new entries', function() { var m = new bookshelf.Model(); var m1 = new bookshelf.Model({id: 1}); var ts = m.timestamp(); var ts2 = m1.timestamp(); equal(_.isDate(ts.created_at), true); equal(_.isDate(ts.updated_at), true); equal(_.isEmpty(ts2.created_at), true); equal(_.isDate(ts2.updated_at), true); }); }); describe('defaults', function() { it('assigns defaults on save, rather than initialize', function() { var Item = bookshelf.Model.extend({defaults: {item: 'test'}}); var item = new Item({newItem: 'test2'}); deepEqual(item.toJSON(), {newItem: 'test2'}); item.sync = function() { deepEqual(this.toJSON(), {id: 1, item: 'test', newItem: 'test2'}); return stubSync; }; return item.save({id: 1}); }); it('only assigns defaults when creating a model, unless {defaults: true} is passed in the save options', function() { var Item = bookshelf.Model.extend({defaults: {item: 'test'}}); var item = new Item({id: 1, newItem: 'test2'}); deepEqual(item.toJSON(), {id: 1, newItem: 'test2'}); item.sync = function() { deepEqual(this.toJSON(), {id: 1, newItem: 'test2'}); return stubSync; }; return item.save().then(function() { item.sync = function() { deepEqual(this.toJSON(), {id: 2, item: 'test', newItem: 'test2'}); return stubSync; }; return item.save({id: 2}, {defaults: true}); }); }); }); describe('sync', function() { it('creates a new instance of Sync', function(){ var model = new bookshelf.Model(); equal((model.sync(model) instanceof require('../../lib/sync')), true); }); }); describe('isNew', function() { it('uses the idAttribute to determine if the model isNew', function(){ var model = new bookshelf.Model(); model.id = 1; equal(model.isNew(), false); model.set('id', null); equal(model.isNew(), true); }); }); describe('previous, previousAttributes', function() { it('will return the previous value of an attribute the last time it was synced', function() { var count = 0; var model = new Models.Site({id: 1}); model.on('change', function() { count++; }); equal(model.previous('id'), void 0); return model.fetch().then(function() { deepEqual(model.previousAttributes(), {id: 1, name: 'knexjs.org'}); deepEqual(model.changed, {}); model.set('id', 2); equal(model.previous('id'), 1); deepEqual(model.changed, {id: 2}); model.set('id', 1); equal(count, 1); }); }); }); describe('hasChanged', function() { it('will determine whether an attribute, or the model has changed', function() { return new Models.Site({id: 1}).fetch().then(function(site) { expect(site.hasChanged()).to.be.false; site.set('name', 'Changed site'); equal(site.hasChanged('name'), true); deepEqual(site.changed, {name: 'Changed site'}); }); }); }); describe('Model.collection', function() { it('creates a new collection for the current model', function() { expect(bookshelf.Model.collection()).to.be.an.instanceOf(bookshelf.Collection); var NewModel = bookshelf.Model.extend({test: 1}); var newModelCollection = NewModel.collection([{id: 1}]); expect(newModelCollection).to.be.an.instanceOf(bookshelf.Collection); expect(newModelCollection.at(0)).to.be.an.instanceOf(NewModel); }); }); describe('model.once', function() { var Post = Models.Post; it('event.once return a promise', function() { var p = new Post({id: 1}); p.once('event', function() { return Promise.resolve(1); }); var promise = p.triggerThen('event'); equal(promise instanceof Promise, true); promise.then(function(result) { equal(result, 1); }); return promise; }); }); }); };
YUI.add('event-custom-base', function(Y) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var DO_BEFORE = 0, DO_AFTER = 1, DO = { /** * Cache of objects touched by the utility * @property objs * @static */ objs: {}, /** * <p>Execute the supplied method before the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt> * <dd>Replace the arguments that the original function will be * called with.</dd> * <dt></code>Y.Do.Prevent(message)</code></dt> * <dd>Don't execute the wrapped function. Other before phase * wrappers will be executed.</dd> * </dl> * * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { // Y.log('Do before: ' + sFn, 'info', 'event'); var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_BEFORE, f, obj, sFn); }, /** * <p>Execute the supplied method after the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt> * <dd>Return <code>returnValue</code> instead of the wrapped * method's original return value. This can be further altered by * other after phase wrappers.</dd> * </dl> * * <p>The static properties <code>Y.Do.originalRetVal</code> and * <code>Y.Do.currentRetVal</code> will be populated for reference.</p> * * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method before or after the specified function. * Used by <code>before</code> and <code>after</code>. * * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (! this.objs[id]) { // create a map entry for the obj if it doesn't exist this.objs[id] = {}; } o = this.objs[id]; if (! o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription. * * @method detach * @param handle {string} the subscription handle * @static */ detach: function(handle) { if (handle.detach) { handle.detach(); } }, _unload: function(e, me) { } }; Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property Do.originalRetVal * @static * @since 3.2.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property Do.currentRetVal * @static * @since 3.2.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ DO.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype._delete = function (sid) { // Y.log('Y.Do._delete: ' + sid, 'info', 'Event'); delete this.before[sid]; delete this.after[sid]; }; /** * <p>Execute the wrapped method. All arguments are passed into the wrapping * functions. If any of the before wrappers return an instance of * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped * function nor any after phase subscribers will be executed.</p> * * <p>The return value will be the return value of the wrapped function or one * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or * <code>Y.Do.AlterReturn</code>. * * @method exec * @param arg* {any} Arguments are passed to the wrapping and wrapped functions * @return {any} Return value of wrapped function unless overwritten (see above) */ DO.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case DO.Halt: return ret.retVal; case DO.AlterArgs: args = ret.newArgs; break; case DO.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } DO.originalRetVal = ret; DO.currentRetVal = ret; // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor == DO.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor == DO.AlterReturn) { ret = newRet.newRetVal; // Update the static retval state DO.currentRetVal = ret; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. Useful for Do.before subscribers. An * example would be a service that scrubs out illegal characters prior to * executing the core business logic. * @class Do.AlterArgs * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newArgs {Array} Call parameters to be used for the original method * instead of the arguments originally passed in. */ DO.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller. Useful for Do.after subscribers. * @class Do.AlterReturn * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newRetVal {any} Return value passed to code that invoked the wrapped * function. */ DO.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. Useful for Do.before subscribers. * @class Do.Halt * @constructor * @param msg {String} (optional) Explanation of why the termination was done * @param retVal {any} Return value passed to code that invoked the wrapped * function. */ DO.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute. Useful * for Do.before subscribers. * @class Do.Prevent * @constructor * @param msg {String} (optional) Explanation of why the termination was done */ DO.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param retVal {any} Return value passed to code that invoked the wrapped * function. * @deprecated use Y.Do.Halt or Y.Do.Prevent */ DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// // Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do); /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log'; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} o configuration object. * @class CustomEvent * @constructor */ Y.CustomEvent = function(type, o) { // if (arguments.length > 2) { // this.log('CustomEvent context and silent are now in the config', 'warn', 'Event'); // } o = o || {}; this.id = Y.stamp(this); /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ this.context = Y; /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ // this.monitored = false; this.logSystem = (type == YUI_LOG); /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ // this.broadcast = 0; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = this.logSystem; /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ // this.queuable = false; /** * The subscribers to this event * @property subscribers * @type Subscriber {} */ this.subscribers = {}; /** * 'After' subscribers * @property afters * @type Subscriber {} */ this.afters = {}; /** * This event has fired if true * * @property fired * @type boolean * @default false; */ // this.fired = false; /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ // this.firedWith; /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ // this.fireOnce = false; /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ //this.async = false; /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ // this.stopped = 0; /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ // this.prevented = 0; /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ // this.host = null; /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ // this.defaultFn = null; /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ // this.stoppedFn = null; /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ // this.preventedFn = null; /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ this.preventable = true; /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ this.bubbles = true; /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ this.signature = YUI3_SIGNATURE; this.subCount = 0; this.afterCount = 0; // this.hasSubscribers = false; // this.hasAfters = false; /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ // this.emitFacade = false; this.applyConfig(o, true); // this.log("Creating " + this.type); }; Y.CustomEvent.prototype = { constructor: Y.CustomEvent, /** * Returns the number of subscribers for this event as the sum of the on() * subscribers and after() subscribers. * * @method hasSubs * @return Number */ hasSubs: function(when) { var s = this.subCount, a = this.afterCount, sib = this.sibling; if (sib) { s += sib.subCount; a += sib.afterCount; } if (when) { return (when == 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = Y.Array(arguments, 0, true); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { var s = Y.merge(this.subscribers), a = Y.merge(this.afters), sib = this.sibling; if (sib) { Y.mix(s, sib.subscribers); Y.mix(a, sib.afters); } return [s, a]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { if (o) { Y.mix(this, o, force, CONFIGS); } }, /** * Create the Subscription for subscribing function, context, and bound * arguments. If this is a fireOnce event, the subscriber is immediately * notified. * * @method _on * @param fn {Function} Subscription callback * @param [context] {Object} Override `this` in the callback * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire() * @param [when] {String} "after" to slot into after subscribers * @return {EventHandle} * @protected */ _on: function(fn, context, args, when) { if (!fn) { this.log('Invalid callback for CE: ' + this.type); } var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { if (this.async) { setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } else { this._notify(s, this.firedWith); } } if (when == AFTER) { this.afters[s.id] = s; this.afterCount++; } else { this.subscribers[s.id] = s; this.subCount++; } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { Y.log('ce.subscribe deprecated, use "on"', 'warn', 'deprecated'); var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; if (this.host) { this.host._monitor('attach', this.type, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = Y.merge(this.subscribers, this.afters); for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s); found++; } } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @protected */ _notify: function(s, args, ef) { this.log(this.type + '->' + 'sub: ' + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + ' cancelled by subscriber'); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { if (!this.silent) { Y.log(this.id + ': ' + msg, cat || 'info', 'event'); } }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { var args = Y.Array(arguments, 0, true); // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; this.firedWith = args; if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, /** * Set up for notifying subscribers of non-emitFacade events. * * @method fireSimple * @param args {Array} Arguments passed to fire() * @return Boolean false if a subscriber returned false * @protected */ fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { // this._procSubs(Y.merge(this.subscribers, this.afters), args); var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } this._broadcast(args); return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { Y.log('Missing event-custom-complex needed to emit a facade for: ' + this.type); args[0] = args[0] || {}; return this.fireSimple(args); }, /** * Notifies a list of subscribers. * * @method _procSubs * @param subs {Array} List of subscribers * @param args {Array} Arguments passed to fire() * @param ef {} * @return Boolean false if a subscriber returns false or stops the event * propagation via e.stopPropagation(), * e.stopImmediatePropagation(), or e.halt() * @private */ _procSubs: function(subs, args, ef) { var s, i; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped == 2) { return false; } } } } return true; }, /** * Notifies the YUI instance if the event is configured with broadcast = 1, * and both the YUI instance and Y.Global if configured with broadcast = 2. * * @method _broadcast * @param args {Array} Arguments sent to fire() * @private */ _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = Y.Array(args); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast == 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed. */ detachAll: function() { return this.detach(); }, /** * Deletes the subscriber from the internal store of on() and after() * subscribers. * * @method _delete * @param subscriber object. * @private */ _delete: function(s) { if (s) { if (this.subscribers[s.id]) { delete this.subscribers[s.id]; this.subCount--; } if (this.afters[s.id]) { delete this.afters[s.id]; this.afterCount--; } } if (this.host) { this.host._monitor('detach', this.type, { ce: this, sub: s }); } if (s) { // delete s.fn; // delete s.context; s.deleted = true; } } }; /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.stamp(this); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { constructor: Y.Subscriber, _notify: function(c, args, ce) { if (this.deleted && !this.postponed) { if (this.postponed) { delete this.fn; delete this.context; } else { delete this.postponed; return null; } } var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch (e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn == fn) && this.context == context); } else { return (this.fn == fn); } } }; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ Y.EventHandle = function(evt, sub) { /** * The custom event * * @property evt * @type CustomEvent */ this.evt = evt; /** * The subscriber object * * @property sub * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { batch: function(f, c) { f.call(c || this, this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {int} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { // Y.log('EventHandle.detach: ' + this.sub, 'info', 'Event'); if (Y.Lang.isArray(evt)) { for (i = 0; i < evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {String} the prefix to apply to non-prefixed event names */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', YArray = Y.Array, _wildType = Y.cached(function(type) { return type.replace(/(.*)(:)(.*)/, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = Y.cached(function(type, pre) { if (!pre || !L.isString(type) || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }), /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); // Y.log(t); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t == '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { // Y.log('EventTarget constructor executed: ' + this._yuid); var o = (L.isObject(opts)) ? opts : {}; this._yuievt = this._yuievt || { id: Y.guid(), events: {}, targets: {}, config: o, chain: ('chain' in o) ? o.chain : Y.config.chain, bubbling: false, defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, monitored: o.monitored, broadcast: o.broadcast, defaultTargetOnly: o.defaultTargetOnly, bubbles: ('bubbles' in o) ? o.bubbles : true } }; }; ET.prototype = { constructor: ET, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ once: function() { var handle = this.on.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>after</code> except the * listener is immediatelly detached when it is executed. * @method onceAfter * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ onceAfter: function() { var args = YArray(arguments, 0, true); args[0] = AFTER_PREFIX + args[0]; return this.once.apply(this, args); }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {String} type the type * @param {String} [pre=this._yuievt.config.prefix] the prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { return _parseType(type, pre || this._yuievt.config.prefix); }, /** * For Nodes and NodeLists, subscribe to a DOM event or custom event. * For other subclasses, this subscribes only to custom events. * * DOM event subscribers or subscribers to custom events that are published * to emit an EventFacade can call `e.preventDefault()` to prevent any * default behavior associated with that event. `e.stopPropagation()` will * stop such events from bubbling, and `e.halt()` will do both. * * Subscribers may alternatively return `false` instead of calling * `e.halt()`. It is recommended to use the event methods rather than * returning `false`. * * @method on * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ on: function(type, fn, context) { var parts = _parseType(type, this._yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = YArray(arguments, 0, true); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (this._yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { args = YArray(arguments, 0, true); args.splice(2, 0, Node.getDOMNode(this)); // Y.log("Node detected, redirecting with these args: " + args); return Y.on.apply(Y, args); } type = parts[1]; if (Y.instanceOf(this, YUI)) { adapt = Y.Env.evt.plugins[type]; args = YArray(arguments, 0, true); args[0] = shorttype; if (Node) { n = args[2]; if (Y.instanceOf(n, Y.NodeList)) { n = Y.NodeList.getDOMNodes(n); } else if (Y.instanceOf(n, Node)) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { Y.log('Using adaptor for ' + shorttype + ', ' + n, 'info', 'event'); handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = this._yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? YArray(arguments, 3, true) : null, (after) ? 'after' : true); } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (this._yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { Y.log('EventTarget subscribe() is deprecated, use on()', 'warn', 'deprecated'); return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = YArray(arguments, 0, true); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (Y.instanceOf(this, YUI)) { args = YArray(arguments, 0, true); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { Y.log('EventTarget unsubscribe() is deprecated, use detach()', 'warn', 'deprecated'); return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {String} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {String} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { Y.log('EventTarget unsubscribeAll() is deprecated, use detachAll()', 'warn', 'deprecated'); return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {String} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var events, ce, ret, defaults, edata = this._yuievt, pre = edata.config.prefix; type = (pre) ? _getType(type, pre) : type; this._monitor('publish', type, { args: arguments }); if (L.isObject(type)) { ret = {}; Y.each(type, function(v, k) { ret[k] = this.publish(k, v || opts); }, this); return ret; } events = edata.events; ce = events[type]; if (ce) { // ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event'); if (opts) { ce.applyConfig(opts, true); } } else { defaults = edata.defaults; // apply defaults ce = new Y.CustomEvent(type, (opts) ? Y.merge(defaults, opts) : defaults); events[type] = ce; } // make sure we turn the broadcast flag off if this // event was published as a result of bubbling // if (opts instanceof Y.CustomEvent) { // events[type].broadcast = false; // } return events[type]; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @method _monitor * @param what {String} 'attach', 'detach', 'fire', or 'publish' * @param type {String} Name of the event being monitored * @param o {Object} Information about the event interaction, such as * fire() args, subscription category, publish config * @private */ _monitor: function(what, type, o) { var monitorevt, ce = this.getEvent(type); if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; // Y.log('monitoring: ' + monitorevt); o.monitored = what; this.fire.call(this, monitorevt, o); } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host * */ fire: function(type) { var typeIncluded = L.isString(type), t = (typeIncluded) ? type : (type && type.type), ce, ret, pre = this._yuievt.config.prefix, ce2, args = (typeIncluded) ? YArray(arguments, 1, true) : arguments; t = (pre) ? _getType(t, pre) : t; this._monitor('fire', t, { args: args }); ce = this.getEvent(t, true); ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } // this event has not been published or subscribed to if (!ce) { if (this._yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { ce.sibling = ce2; ret = ce.fire.apply(ce, args); } return (this._yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); // console.log(type); ce2 = this.getEvent(type, true); if (ce2) { // console.log("GOT ONE: " + type); ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; // ret = ce2.fire.apply(ce2, a); } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {String} the type, or name of the event * @param prefixed {String} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * * @method after * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ after: function(type, fn) { var a = YArray(arguments, 0, true); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype); ET.call(Y, { bubbles: false }); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** `Y.on()` can do many things: <ul> <li>Subscribe to custom events `publish`ed and `fire`d from Y</li> <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and `fire`d from any object in the YUI instance sandbox</li> <li>Subscribe to DOM events</li> <li>Subscribe to the execution of a method on any object, effectively treating that method as an event</li> </ul> If a function is passed as the first parameter, the call is relayed to `Y.Do.before(...)`. Otherwise, if the event name passed as the first parameter is a DOM event, and the third parameter is a Node, NodeList, HTMLElement, CSS selector string, or is omitted altogether, the subscription request will be passed to the DOM event system. A missing third argument is defaulted to the `window` for DOM events. In all other cases, a custom event subscription is made. `on` subscribers for DOM events or custom events `publish`ed with a `defaultFn` can prevent the default behavior with `e.preventDefault()` from the event object passed as the first parameter to the subscription callback. NOTE: The subscription signature shown is for events, not for function injection. See `Y.Do.before` for that signature. @method on @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @see Do.before @for YUI **/ /** Listen for an event one time. Equivalent to `on`, except that the listener is immediately detached when executed. @see on @method once @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Listen for an event one time. Equivalent to `once`, except, like `after`, the subscription callback executes after all `on` subscribers and the event's `defaultFn` (if configured) have executed. Like `after` if any `on` phase subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after` subscribers will execute. The listener is immediately detached when executed. @see once @method onceAfter @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Like `on`, this method creates a subscription to a custom event or to the execution of a method on an object. However, for events, `after` subscribers are queued to execute after the event's `defaultFn`, if configured. If any `on` subscriber calls `e.preventDefault()`, the `defaultFn` will not execute, and neither will the `after` subscribers. NOTE: The subscription signature shown is for events, not for function injection. See `Y.Do.after` for that signature. @see on @see Do.after @method after @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ }, '@VERSION@' ,{requires:['oop']});
/* machina Author: Jim Cowart (http://freshbrewedcode.com/jimcowart) License: Dual licensed MIT (http://www.opensource.org/licenses/mit-license) & GPL (http://www.opensource.org/licenses/gpl-license) Version 0.3.2 */ (function ( root, factory ) { if ( typeof module === "object" && module.exports ) { // Node, or CommonJS-Like environments module.exports = function ( _ ) { return factory( _ ); } } else if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( ["underscore"], function ( _ ) { return factory( _, root ); } ); } else { // Browser globals root.machina = factory( root._, root ); } }( this, function ( _, global, undefined ) { var slice = [].slice; var NEXT_TRANSITION = "transition"; var NEXT_HANDLER = "handler"; var HANDLING = "handling"; var HANDLED = "handled"; var NO_HANDLER = "nohandler"; var TRANSITION = "transition"; var INVALID_STATE = "invalidstate"; var DEFERRED = "deferred"; var NEW_FSM = "newfsm"; var utils = { makeFsmNamespace : (function () { var machinaCount = 0; return function () { return "fsm." + machinaCount++; }; })(), getDefaultOptions : function () { return { initialState : "uninitialized", eventListeners : { "*" : [] }, states : {}, eventQueue : [], namespace : utils.makeFsmNamespace(), targetReplayState : "", state : undefined, priorState : undefined, _priorAction : "", _currentAction : "" }; } }; if ( !_.deepExtend ) { var behavior = { "*" : function ( obj, sourcePropKey, sourcePropVal ) { obj[sourcePropKey] = sourcePropVal; }, "object" : function ( obj, sourcePropKey, sourcePropVal ) { obj[sourcePropKey] = deepExtend( {}, obj[sourcePropKey] || {}, sourcePropVal ); }, "array" : function ( obj, sourcePropKey, sourcePropVal ) { obj[sourcePropKey] = []; _.each( sourcePropVal, function ( item, idx ) { behavior[getHandlerName( item )]( obj[sourcePropKey], idx, item ); }, this ); } }, getActualType = function ( val ) { if ( _.isArray( val ) ) { return "array"; } if ( _.isDate( val ) ) { return "date"; } if ( _.isRegExp( val ) ) { return "regex"; } return typeof val; }, getHandlerName = function ( val ) { var propType = getActualType( val ); return behavior[propType] ? propType : "*"; }, deepExtend = function ( obj ) { _.each( slice.call( arguments, 1 ), function ( source ) { _.each( source, function ( sourcePropVal, sourcePropKey ) { behavior[getHandlerName( sourcePropVal )]( obj, sourcePropKey, sourcePropVal ); } ); } ); return obj; }; _.mixin( { deepExtend : deepExtend } ); } var Fsm = function ( options ) { _.extend( this, options ); _.defaults(this, utils.getDefaultOptions()); this.initialize.apply(this, arguments); machina.emit( NEW_FSM, this ); if ( this.initialState ) { this.transition( this.initialState ); } }; _.extend( Fsm.prototype, { initialize: function() { }, emit : function ( eventName ) { var args = arguments; if(this.eventListeners["*"]) { _.each( this.eventListeners["*"], function ( callback ) { try { callback.apply( this, slice.call( args, 0 ) ); } catch ( exception ) { if ( console && typeof console.log !== "undefined" ) { console.log( exception.toString() ); } } } ); } if ( this.eventListeners[eventName] ) { _.each( this.eventListeners[eventName], function ( callback ) { try { callback.apply( this, slice.call( args, 1 ) ); } catch ( exception ) { if ( console && typeof console.log !== "undefined" ) { console.log( exception.toString() ); } } } ); } }, handle : function ( inputType ) { if ( !this.inExitHandler ) { var states = this.states, current = this.state, args = slice.call( arguments, 0 ), handlerName, handler, catchAll; this.currentActionArgs = args; if ( states[current][inputType] || states[current]["*"] || this[ "*" ] ) { handlerName = states[current][inputType] ? inputType : "*"; catchAll = handlerName === "*"; if ( states[current][handlerName] ) { handler = states[current][handlerName]; this._currentAction = current + "." + handlerName; } else { handler = this[ "*" ]; this._currentAction = "*"; } this.emit.call( this, HANDLING, { inputType: inputType, args: args.slice(1) } ); Object.prototype.toString.call( handler ) === "[object String]" ? this.transition( handler ) : handler.apply( this, catchAll ? args : args.slice( 1 ) ); this.emit.call( this, HANDLED, { inputType: inputType, args: args.slice(1) } ); this._priorAction = this._currentAction; this._currentAction = ""; this.processQueue( NEXT_HANDLER ); } else { this.emit.call( this, NO_HANDLER, { inputType: inputType, args: args.slice(1) } ); } this.currentActionArgs = undefined; } }, transition : function ( newState ) { if ( !this.inExitHandler ) { var oldState; if ( this.states[newState] ) { this.targetReplayState = newState; this.priorState = this.state; this.state = newState; oldState = this.priorState; if ( this.states[oldState] && this.states[oldState]._onExit ) { this.inExitHandler = true; this.states[oldState]._onExit.call( this ); this.inExitHandler = false; } this.emit.call( this, TRANSITION, { fromState: oldState, toState: newState } ); if ( this.states[newState]._onEnter ) { this.states[newState]._onEnter.call( this ); } if ( this.targetReplayState === newState ) { this.processQueue( NEXT_TRANSITION ); } return; } this.emit.call( this, INVALID_STATE, { state: this.state, attemptedState: newState } ); } }, processQueue : function ( type ) { var filterFn = type === NEXT_TRANSITION ? function ( item ) { return item.type === NEXT_TRANSITION && ((!item.untilState) || (item.untilState === this.state)); } : function ( item ) { return item.type === NEXT_HANDLER; }; var toProcess = _.filter( this.eventQueue, filterFn, this ); this.eventQueue = _.difference( this.eventQueue, toProcess ); _.each( toProcess, function ( item ) { this.handle.apply( this, item.args ); }, this ); }, clearQueue : function ( type, name ) { if(!type) { this.eventQueue = []; } else {var filter; if ( type === NEXT_TRANSITION ) { filter = function ( evnt ) { return (evnt.type === NEXT_TRANSITION && (name ? evnt.untilState === name : true )); }; } else if ( type === NEXT_HANDLER ) { filter = function ( evnt ) { return evnt.type === NEXT_HANDLER; }; } this.eventQueue = _.filter( this.eventQueue, filter ); } }, deferUntilTransition : function ( stateName ) { if ( this.currentActionArgs ) { var queued = { type : NEXT_TRANSITION, untilState : stateName, args : this.currentActionArgs }; this.eventQueue.push( queued ); this.emit.call( this, DEFERRED, { state: this.state, queuedArgs: queued } ); } }, deferUntilNextHandler : function () { if ( this.currentActionArgs ) { var queued = { type : NEXT_TRANSITION, args : this.currentActionArgs }; this.eventQueue.push( queued ); this.emit.call( this, DEFERRED, { state: this.state, queuedArgs: queued } ); } }, on : function ( eventName, callback ) { var self = this; if ( !self.eventListeners[eventName] ) { self.eventListeners[eventName] = []; } self.eventListeners[eventName].push( callback ); return { eventName: eventName, callback: callback, off: function() { self.off(eventName, callback); } }; }, off : function ( eventName, callback ) { if(!eventName) { this.eventListeners = {}; } else { if ( this.eventListeners[eventName] ) { if(callback) { this.eventListeners[eventName] = _.without( this.eventListeners[eventName], callback ); } else { this.eventListeners[eventName] = []; } } } } } ); Fsm.prototype.trigger = Fsm.prototype.emit; var ctor = function () {}; var inherits = function ( parent, protoProps, staticProps ) { var fsm; // The constructor function for the new subclass is either defined by you // (the "constructor" property in your `extend` definition), or defaulted // by us to simply call the parent's constructor. if ( protoProps && protoProps.hasOwnProperty( 'constructor' ) ) { fsm = protoProps.constructor; } else { fsm = function () { parent.apply( this, arguments ); }; } // Inherit class (static) properties from parent. _.deepExtend( fsm, parent ); // Set the prototype chain to inherit from `parent`, without calling // `parent`'s constructor function. ctor.prototype = parent.prototype; fsm.prototype = new ctor(); // Add prototype properties (instance properties) to the subclass, // if supplied. if ( protoProps ) { _.deepExtend( fsm.prototype, protoProps ); } // Add static properties to the constructor function, if supplied. if ( staticProps ) { _.deepExtend( fsm, staticProps ); } // Correctly set child's `prototype.constructor`. fsm.prototype.constructor = fsm; // Set a convenience property in case the parent's prototype is needed later. fsm.__super__ = parent.prototype; return fsm; }; // The self-propagating extend function that Backbone classes use. Fsm.extend = function ( protoProps, classProps ) { var fsm = inherits( this, protoProps, classProps ); fsm.extend = this.extend; return fsm; }; var machina = { Fsm : Fsm, utils : utils, on : function ( eventName, callback ) { if ( !this.eventListeners[eventName] ) { this.eventListeners[eventName] = []; } this.eventListeners[eventName].push( callback ); return callback; }, off : function ( eventName, callback ) { if ( this.eventListeners[eventName] ) { this.eventListeners[eventName] = _.without( this.eventListeners[eventName], callback ); } }, trigger : function ( eventName ) { var i = 0, len, args = arguments, listeners = this.eventListeners[eventName] || []; if ( listeners && listeners.length ) { _.each( listeners, function ( callback ) { callback.apply( null, slice.call( args, 1 ) ); } ); } }, eventListeners : { newFsm : [] } }; machina.emit = machina.trigger; return machina; } ));
/*! UIkit 2.19.0 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */ (function(UI) { "use strict"; var active = false, $html = UI.$html, body; UI.component('modal', { defaults: { keyboard: true, bgclose: true, minScrollHeight: 150, center: false }, scrollable: false, transition: false, init: function() { if (!body) body = UI.$('body'); var $this = this; this.transition = UI.support.transition; this.paddingdir = "padding-" + (UI.langdirection == 'left' ? "right":"left"); this.dialog = this.find(".uk-modal-dialog"); // Update ARIA this.element.attr('aria-hidden', this.element.hasClass("uk-open")); this.on("click", ".uk-modal-close", function(e) { e.preventDefault(); $this.hide(); }).on("click", function(e) { var target = UI.$(e.target); if (target[0] == $this.element[0] && $this.options.bgclose) { $this.hide(); } }); }, toggle: function() { return this[this.isActive() ? "hide" : "show"](); }, show: function() { var $this = this; if (this.isActive()) return; if (active) active.hide(true); this.element.removeClass("uk-open").show(); this.resize(); active = this; this.element.addClass("uk-open"); $html.addClass("uk-modal-page").height(); // force browser engine redraw // Update ARIA this.element.attr('aria-hidden', 'false'); this.element.trigger("show.uk.modal"); UI.Utils.checkDisplay(this.dialog, true); return this; }, hide: function(force) { if (!this.isActive()) return; if (!force && UI.support.transition) { var $this = this; this.one(UI.support.transition.end, function() { $this._hide(); }).removeClass("uk-open"); } else { this._hide(); } return this; }, resize: function() { var bodywidth = body.width(); this.scrollbarwidth = window.innerWidth - bodywidth; body.css(this.paddingdir, this.scrollbarwidth); this.element.css('overflow-y', this.scrollbarwidth ? 'scroll' : 'auto'); if (!this.updateScrollable() && this.options.center) { var dh = this.dialog.outerHeight(), pad = parseInt(this.dialog.css('margin-top'), 10) + parseInt(this.dialog.css('margin-bottom'), 10); if ((dh + pad) < window.innerHeight) { this.dialog.css({'top': (window.innerHeight/2 - dh/2) - pad }); } else { this.dialog.css({'top': ''}); } } }, updateScrollable: function() { // has scrollable? var scrollable = this.dialog.find('.uk-overflow-container:visible:first'); if (scrollable.length) { scrollable.css("height", 0); var offset = Math.abs(parseInt(this.dialog.css("margin-top"), 10)), dh = this.dialog.outerHeight(), wh = window.innerHeight, h = wh - 2*(offset < 20 ? 20:offset) - dh; scrollable.css("height", h < this.options.minScrollHeight ? "":h); return true; } return false; }, _hide: function() { this.element.hide().removeClass("uk-open"); // Update ARIA this.element.attr('aria-hidden', 'true'); $html.removeClass("uk-modal-page"); body.css(this.paddingdir, ""); if(active===this) active = false; this.trigger("hide.uk.modal"); }, isActive: function() { return (active == this); } }); UI.component('modalTrigger', { boot: function() { // init code UI.$html.on("click.modal.uikit", "[data-uk-modal]", function(e) { var ele = UI.$(this); if (ele.is("a")) { e.preventDefault(); } if (!ele.data("modalTrigger")) { var modal = UI.modalTrigger(ele, UI.Utils.options(ele.attr("data-uk-modal"))); modal.show(); } }); // close modal on esc button UI.$html.on('keydown.modal.uikit', function (e) { if (active && e.keyCode === 27 && active.options.keyboard) { // ESC e.preventDefault(); active.hide(); } }); UI.$win.on("resize orientationchange", UI.Utils.debounce(function(){ if (active) active.resize(); }, 150)); }, init: function() { var $this = this; this.options = UI.$.extend({ "target": $this.element.is("a") ? $this.element.attr("href") : false }, this.options); this.modal = UI.modal(this.options.target, this.options); this.on("click", function(e) { e.preventDefault(); $this.show(); }); //methods this.proxy(this.modal, "show hide isActive"); } }); UI.modal.dialog = function(content, options) { var modal = UI.modal(UI.$(UI.modal.dialog.template).appendTo("body"), options); modal.on("hide.uk.modal", function(){ if (modal.persist) { modal.persist.appendTo(modal.persist.data("modalPersistParent")); modal.persist = false; } modal.element.remove(); }); setContent(content, modal); return modal; }; UI.modal.dialog.template = '<div class="uk-modal"><div class="uk-modal-dialog" style="min-height:0;"></div></div>'; UI.modal.alert = function(content, options) { UI.modal.dialog(([ '<div class="uk-margin uk-modal-content">'+String(content)+'</div>', '<div class="uk-modal-footer uk-text-right"><button class="uk-button uk-button-primary uk-modal-close">Ok</button></div>' ]).join(""), UI.$.extend({bgclose:false, keyboard:false}, options)).show(); }; UI.modal.confirm = function(content, onconfirm, options) { onconfirm = UI.$.isFunction(onconfirm) ? onconfirm : function(){}; var modal = UI.modal.dialog(([ '<div class="uk-margin uk-modal-content">'+String(content)+'</div>', '<div class="uk-modal-footer uk-text-right"><button class="uk-button uk-button-primary js-modal-confirm">Ok</button> <button class="uk-button uk-modal-close">Cancel</button></div>' ]).join(""), UI.$.extend({bgclose:false, keyboard:false}, options)); modal.element.find(".js-modal-confirm").on("click", function(){ onconfirm(); modal.hide(); }); modal.show(); }; // helper functions function setContent(content, modal){ if(!modal) return; if (typeof content === 'object') { // convert DOM object to a jQuery object content = content instanceof jQuery ? content : UI.$(content); if(content.parent().length) { modal.persist = content; modal.persist.data("modalPersistParent", content.parent()); } }else if (typeof content === 'string' || typeof content === 'number') { // just insert the data as innerHTML content = UI.$('<div></div>').html(content); }else { // unsupported data type! content = UI.$('<div></div>').html('UIkit.modal Error: Unsupported data type: ' + typeof content); } content.appendTo(modal.element.find('.uk-modal-dialog')); return modal; } })(UIkit);
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. /** * @fileoverview Defines a {@linkplain Driver WebDriver} client for Microsoft's * Internet Explorer. Before using the IEDriver, you must download the latest * [IEDriverServer](http://selenium-release.storage.googleapis.com/index.html) * and place it on your * [PATH](http://en.wikipedia.org/wiki/PATH_%28variable%29). You must also apply * the system configuration outlined on the Selenium project * [wiki](https://github.com/SeleniumHQ/selenium/wiki/InternetExplorerDriver) */ 'use strict'; var fs = require('fs'), util = require('util'); var webdriver = require('./index'), executors = require('./executors'), io = require('./io'), portprober = require('./net/portprober'), remote = require('./remote'); /** * @const * @final */ var IEDRIVER_EXE = 'IEDriverServer.exe'; /** * IEDriverServer logging levels. * @enum {string} */ var Level = { FATAL: 'FATAL', ERROR: 'ERROR', WARN: 'WARN', INFO: 'INFO', DEBUG: 'DEBUG', TRACE: 'TRACE' }; /** * Option keys: * https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities#ie-specific * @enum {string} */ var Key = { IGNORE_PROTECTED_MODE_SETTINGS: 'ignoreProtectedModeSettings', IGNORE_ZOOM_SETTING: 'ignoreZoomSetting', INITIAL_BROWSER_URL: 'initialBrowserUrl', ENABLE_PERSISTENT_HOVER: 'enablePersistentHover', ENABLE_ELEMENT_CACHE_CLEANUP: 'enableElementCacheCleanup', REQUIRE_WINDOW_FOCUS: 'requireWindowFocus', BROWSER_ATTACH_TIMEOUT: 'browserAttachTimeout', FORCE_CREATE_PROCESS: 'ie.forceCreateProcessApi', BROWSER_COMMAND_LINE_SWITCHES: 'ie.browserCommandLineSwitches', USE_PER_PROCESS_PROXY: 'ie.usePerProcessProxy', ENSURE_CLEAN_SESSION: 'ie.ensureCleanSession', LOG_FILE: 'logFile', LOG_LEVEL: 'logLevel', HOST: 'host', EXTRACT_PATH: 'extractPath', SILENT: 'silent' }; /** * Class for managing IEDriver specific options. * @constructor */ var Options = function() { /** @private {!Object<(boolean|number|string)>} */ this.options_ = {}; /** @private {(webdriver.ProxyConfig|null)} */ this.proxy_ = null; }; /** * Extracts the IEDriver specific options from the given capabilities * object. * @param {!webdriver.Capabilities} capabilities The capabilities object. * @return {!Options} The IEDriver options. */ Options.fromCapabilities = function(capabilities) { var options = new Options(); var map = options.options_; Object.keys(Key).forEach(function(key) { key = Key[key]; if (capabilities.has(key)) { map[key] = capabilities.get(key); } }); if (capabilities.has(webdriver.Capability.PROXY)) { options.setProxy(capabilities.get(webdriver.Capability.PROXY)); } return options; }; /** * Whether to disable the protected mode settings check when the session is * created. Disbling this setting may lead to significant instability as the * browser may become unresponsive/hang. Only "best effort" support is provided * when using this capability. * * For more information, refer to the IEDriver's * [required system configuration](http://goo.gl/eH0Yi3). * * @param {boolean} ignoreSettings Whether to ignore protected mode settings. * @return {!Options} A self reference. */ Options.prototype.introduceFlakinessByIgnoringProtectedModeSettings = function(ignoreSettings) { this.options_[Key.IGNORE_PROTECTED_MODE_SETTINGS] = !!ignoreSettings; return this; }; /** * Indicates whether to skip the check that the browser's zoom level is set to * 100%. * * @parm {boolean} ignore Whether to ignore the browser's zoom level settings. * @return {!Options} A self reference. */ Options.prototype.ignoreZoomSetting = function(ignore) { this.options_[Key.IGNORE_ZOOM_SETTING] = !!ignore; return this; }; /** * Sets the initial URL loaded when IE starts. This is intended to be used with * {@link #ignoreProtectedModeSettings} to allow the user to initialize IE in * the proper Protected Mode zone. Setting this option may cause browser * instability or flaky and unresponsive code. Only "best effort" support is * provided when using this option. * * @param {string} url The initial browser URL. * @return {!Options} A self reference. */ Options.prototype.initialBrowserUrl = function(url) { this.options_[Key.INITIAL_BROWSER_URL] = url; return this; }; /** * Configures whether to enable persistent mouse hovering (true by default). * Persistent hovering is achieved by continuously firing mouse over events at * the last location the mouse cursor has been moved to. * * @param {boolean} enable Whether to enable persistent hovering. * @return {!Options} A self reference. */ Options.prototype.enablePersistentHover = function(enable) { this.options_[Key.ENABLE_PERSISTENT_HOVER] = !!enable; return this; }; /** * Configures whether the driver should attempt to remove obsolete * {@linkplain webdriver.WebElement WebElements} from its internal cache on * page navigation (true by default). Disabling this option will cause the * driver to run with a larger memory footprint. * * @param {boolean} enable Whether to enable element reference cleanup. * @return {!Options} A self reference. */ Options.prototype.enableElementCacheCleanup = function(enable) { this.options_[Key.ENABLE_ELEMENT_CACHE_CLEANUP] = !!enable; return this; }; /** * Configures whether to require the IE window to have input focus before * performing any user interactions (i.e. mouse or keyboard events). This * option is disabled by default, but delivers much more accurate interaction * events when enabled. * * @param {boolean} require Whether to require window focus. * @return {!Options} A self reference. */ Options.prototype.requireWindowFocus = function(require) { this.options_[Key.REQUIRE_WINDOW_FOCUS] = !!require; return this; }; /** * Configures the timeout, in milliseconds, that the driver will attempt to * located and attach to a newly opened instance of Internet Explorer. The * default is zero, which indicates waiting indefinitely. * * @param {number} timeout How long to wait for IE. * @return {!Options} A self reference. */ Options.prototype.browserAttachTimeout = function(timeout) { this.options_[Key.BROWSER_ATTACH_TIMEOUT] = Math.max(timeout, 0); return this; }; /** * Configures whether to launch Internet Explorer using the CreateProcess API. * If this option is not specified, IE is launched using IELaunchURL, if * available. For IE 8 and above, this option requires the TabProcGrowth * registry value to be set to 0. * * @param {boolean} force Whether to use the CreateProcess API. * @return {!Options} A self reference. */ Options.prototype.forceCreateProcessApi = function(force) { this.options_[Key.FORCE_CREATE_PROCESS] = !!force; return this; }; /** * Specifies command-line switches to use when launching Internet Explorer. * This is only valid when used with {@link #forceCreateProcessApi}. * * @param {...(string|!Array.<string>)} var_args The arguments to add. * @return {!Options} A self reference. */ Options.prototype.addArguments = function(var_args) { var args = this.options_[Key.BROWSER_COMMAND_LINE_SWITCHES] || []; args = args.concat.apply(args, arguments); this.options_[Key.BROWSER_COMMAND_LINE_SWITCHES] = args; return this; }; /** * Configures whether proxies should be configured on a per-process basis. If * not set, setting a {@linkplain #setProxy proxy} will configure the system * proxy. The default behavior is to use the system proxy. * * @param {boolean} enable Whether to enable per-process proxy settings. * @return {!Options} A self reference. */ Options.prototype.usePerProcessProxy = function(enable) { this.options_[Key.USE_PER_PROCESS_PROXY] = !!enable; return this; }; /** * Configures whether to clear the cache, cookies, history, and saved form data * before starting the browser. _Using this capability will clear session data * for all running instances of Internet Explorer, including those started * manually._ * * @param {boolean} cleanSession Whether to clear all session data on startup. * @return {!Options} A self reference. */ Options.prototype.ensureCleanSession = function(cleanSession) { this.options_[Key.ENSURE_CLEAN_SESSION] = !!cleanSession; return this; }; /** * Sets the path to the log file the driver should log to. * @param {string} path The log file path. * @return {!Options} A self reference. */ Options.prototype.setLogFile = function(file) { this.options_[Key.LOG_FILE] = file; return this; }; /** * Sets the IEDriverServer's logging {@linkplain Level level}. * @param {Level} level The logging level. * @return {!Options} A self reference. */ Options.prototype.setLogLevel = function(level) { this.options_[Key.LOG_LEVEL] = level; return this; }; /** * Sets the IP address of the driver's host adapter. * @param {string} host The IP address to use. * @return {!Options} A self reference. */ Options.prototype.setHost = function(host) { this.options_[Key.HOST] = host; return this; }; /** * Sets the path of the temporary data directory to use. * @param {string} path The log file path. * @return {!Options} A self reference. */ Options.prototype.setExtractPath = function(path) { this.options_[Key.EXTRACT_PATH] = path; return this; }; /** * Sets whether the driver should start in silent mode. * @param {boolean} silent Whether to run in silent mode. * @return {!Options} A self reference. */ Options.prototype.silent = function(silent) { this.options_[Key.SILENT] = silent; return this; }; /** * Sets the proxy settings for the new session. * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. * @return {!Options} A self reference. */ Options.prototype.setProxy = function(proxy) { this.proxy_ = proxy; return this; }; /** * Converts this options instance to a {@link webdriver.Capabilities} object. * @param {webdriver.Capabilities=} opt_capabilities The capabilities to merge * these options into, if any. * @return {!webdriver.Capabilities} The capabilities. */ Options.prototype.toCapabilities = function(opt_capabilities) { var capabilities = opt_capabilities || webdriver.Capabilities.ie(); if (this.proxy_) { capabilities.set(webdriver.Capability.PROXY, this.proxy_); } Object.keys(this.options_).forEach(function(key) { capabilities.set(key, this.options_[key]); }, this); return capabilities; }; function createServiceFromCapabilities(capabilities) { if (process.platform !== 'win32') { throw Error( 'The IEDriver may only be used on Windows, but you appear to be on ' + process.platform + '. Did you mean to run against a remote ' + 'WebDriver server?'); } var exe = io.findInPath(IEDRIVER_EXE, true); if (!fs.existsSync(exe)) { throw Error('File does not exist: ' + exe); } var args = []; if (capabilities.has(Key.HOST)) { args.push('--host=' + capabilities.get(Key.HOST)); } if (capabilities.has(Key.LOG_FILE)) { args.push('--log-file=' + capabilities.get(Key.LOG_FILE)); } if (capabilities.has(Key.LOG_LEVEL)) { args.push('--log-level=' + capabilities.get(Key.LOG_LEVEL)); } if (capabilities.has(Key.EXTRACT_PATH)) { args.push('--extract-path=' + capabilities.get(Key.EXTRACT_PATH)); } if (capabilities.get(Key.SILENT)) { args.push('--silent'); } var port = portprober.findFreePort(); return new remote.DriverService(exe, { loopback: true, port: port, args: port.then(function(port) { return args.concat('--port=' + port); }), stdio: 'ignore' }); } /** * A WebDriver client for Microsoft's Internet Explorer. * * @param {(webdriver.Capabilities|Options)=} opt_config The configuration * options. * @param {webdriver.promise.ControlFlow=} opt_flow The control flow to use, or * {@code null} to use the currently active flow. * @constructor * @extends {webdriver.WebDriver} */ var Driver = function(opt_config, opt_flow) { var capabilities = opt_config instanceof Options ? opt_config.toCapabilities() : (opt_config || webdriver.Capabilities.ie()); var service = createServiceFromCapabilities(capabilities); var executor = executors.createExecutor(service.start()); var driver = webdriver.WebDriver.createSession( executor, capabilities, opt_flow); webdriver.WebDriver.call( this, driver.getSession(), executor, driver.controlFlow()); var boundQuit = this.quit.bind(this); /** @override */ this.quit = function() { return boundQuit().thenFinally(service.kill.bind(service)); }; }; util.inherits(Driver, webdriver.WebDriver); /** * This function is a no-op as file detectors are not supported by this * implementation. * @override */ Driver.prototype.setFileDetector = function() { }; // PUBLIC API exports.Driver = Driver; exports.Options = Options; exports.Level = Level;
require('babel-core/register.js')({ 'plugins': [ 'babel-plugin-transform-es2015-modules-commonjs' ].map(require.resolve) // fixes the issue with babel loader & linked modules }); let del = require('del'); let gulp = require('gulp'); let babel = require('gulp-babel'); let jasmine = require('gulp-jasmine'); exports.build = gulp.series( clean, gulp.parallel( build_js, copy ) ); function build_js() { return gulp .src('./src/**/!(*Spec).js') .pipe(babel({ moduleIds: true, presets: ['es2015'] })) .pipe(gulp.dest('./dist')); } function copy() { return gulp .src(['./package.json', './LICENSE', './README.md']) .pipe(gulp.dest('./dist')); } function clean() { return del('./dist'); } exports.test = test; function test() { return gulp .src('./src/**/*Spec.js') .pipe(jasmine({ includeStackTrace: true })); } exports.dev = dev; function dev() { return gulp.watch(['./src/**/*.js'], test); }
/* eslint-env mocha */ import expect from 'expect' import postcss from 'postcss' import customProps from '../src' const process = css => postcss([ customProps() ]).process(css) describe('rule', () => { it('should correctly resolve addition expression', () => { const input = 'h1 { line-height: calc(1+1+0.2); }' const expectedOutput = 'h1 { line-height: 2.2; }' return process(input).then(({ css }) => { expect(css).toEqual(expectedOutput) }) }) it('should correctly resolve subtraction expression', () => { const input = 'h1 { line-height: calc(10-7-.5); }' const expectedOutput = 'h1 { line-height: 2.5; }' return process(input).then(({ css }) => { expect(css).toEqual(expectedOutput) }) }) it('should correctly resolve multiplication expression', () => { const input = 'h1 { line-height: calc(0.5*6*.5); }' const expectedOutput = 'h1 { line-height: 1.5; }' return process(input).then(({ css }) => { expect(css).toEqual(expectedOutput) }) }) it('should correctly resolve division expression', () => { const input = 'h1 { line-height: calc(10/2/2); }' const expectedOutput = 'h1 { line-height: 2.5; }' return process(input).then(({ css }) => { expect(css).toEqual(expectedOutput) }) }) it('should correctly resolve mixed expression', () => { const input = 'h1 { padding: calc(1/2-2+3*4); }' const expectedOutput = 'h1 { padding: 10.5; }' return process(input).then(({ css }) => { expect(css).toEqual(expectedOutput) }) }) it('should correctly resolve negative result', () => { const input = 'h1 { left: calc(1-2); }' const expectedOutput = 'h1 { left: -1; }' return process(input).then(({ css }) => { expect(css).toEqual(expectedOutput) }) }) it('should correctly resolve value with multiple `calc` function calls', () => { const input = 'h1 { padding: calc(10px+1) calc(20px+2); }' const expectedOutput = 'h1 { padding: 11px 22px; }' return process(input).then(({ css }) => { expect(css).toEqual(expectedOutput) }) }) it('should correctly resolve value with nested `calc` function calls', () => { const input = 'h1 { padding: calc(10px+calc(5*calc(5+5))) calc(20px+10px); }' const expectedOutput = 'h1 { padding: 60px 30px; }' return process(input).then(({ css }) => { expect(css).toEqual(expectedOutput) }) }) it('should only resolve `calc` function call within value', () => { const input = 'h1 { color: color(red l(+calc(10%*2.5))); }' const expectedOutput = 'h1 { color: color(red l(+25%)); }' return process(input).then(({ css }) => { expect(css).toEqual(expectedOutput) }) }) it('should prepend correct unit to result', () => { const input = 'h1 { font-size: calc(10px*2); }' const expectedOutput = 'h1 { font-size: 20px; }' return process(input).then(({ css }) => { expect(css).toEqual(expectedOutput) }) }) it('should allow multiple terms of the same unit', () => { const input = 'h1 { padding: calc(20px+5px); }' const expectedOutput = 'h1 { padding: 25px; }' return process(input).then(({ css }) => { expect(css).toEqual(expectedOutput) }) }) it('should leave mixed unit expression as is', () => { const input = 'h1 { font-size: calc(10px*2em); }' const expectedOutput = 'h1 { font-size: calc(10px*2em); }' return process(input).then(({ css }) => { expect(css).toEqual(expectedOutput) }) }) it('should leave expression as is if calculation errors', () => { const input = 'h1 { font-size: calc(foo+bar); }' const expectedOutput = 'h1 { font-size: calc(foo+bar); }' return process(input).then(({ css }) => { expect(css).toEqual(expectedOutput) }) }) it('should allow whitespace within `calc` function call', () => { const input = 'h1 { line-height: calc( 1 + 1 ); }' const expectedOutput = 'h1 { line-height: 2; }' return process(input).then(({ css }) => { expect(css).toEqual(expectedOutput) }) }) it('should allow parenthesis within `calc` function calls', () => { const input = 'h1 { padding: calc(5px*(10px+2px)) calc(0.5*(10+20px)); }' const expectedOutput = 'h1 { padding: 60px 15px; }' return process(input).then(({ css }) => { expect(css).toEqual(expectedOutput) }) }) })
var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); switch (arguments.length) { case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target); case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0); case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc); } }; var example; (function (example) { var components; (function (components) { var PooledComponent = artemis.PooledComponent; var Pooled = artemis.annotations.Pooled; var Displacement = (function (_super) { __extends(Displacement, _super); function Displacement() { _super.apply(this, arguments); } Displacement.prototype.initialize = function (path, lambda) { var displacementTexture = PIXI.Sprite.fromImage(path); this.filter = new PIXI.filters.DisplacementFilter(displacementTexture); if (lambda) lambda(this); }; Displacement.className = 'Displacement'; Displacement = __decorate([ Pooled() ], Displacement); return Displacement; })(PooledComponent); components.Displacement = Displacement; Displacement.prototype.filter = null; })(components = example.components || (example.components = {})); })(example || (example = {})); //# sourceMappingURL=Displacement.js.map
// Libraries var https = require('https'); var url = require('url'); var uuid = require('node-uuid'); var querystring = require('querystring'); var util = require('util'); var db = require('redis').createClient(); // The methods on this object will be exported as the public api var public_api = {}; /****************************************************************************** * Handle DB errors * ******************************************************************************/ db.on('error', function (err) { console.error('DB Error: ' + err); }); /****************************************************************************** * Helper Functions * ******************************************************************************/ function success(response, ob) { response.writeHead(200, { 'Content-Type': 'application/json' }); response.write(JSON.stringify(ob)); response.end(); } function error(response, errno, errtext) { console.error('===ERROR===', errno, errtext); response.writeHead(errno, {'Content-Type': 'application/json'}); response.write(JSON.stringify({error:errtext})); response.end(); } function isUndefined(x) { return x === undefined; } function isString(x) { return (typeof x) === 'string'; } function isBlank(str) { return str.trim() === ''; } function isValidString(x) { return !isUndefined(x) && isString(x) && !isBlank(x); } function isValidPositiveIntegerString(x) { return isValidString(x) && x.trim().match(/^\d+$/) !== null; } /****************************************************************************** * Getters * ******************************************************************************/ public_api.codeByID = function codeByID(request, response) { var query = url.parse(request.url, true).query; var id = query.id; if (id === undefined) { return error(response, 400, 'Invalid code id'); } db.get('code:' + id, function(err, reply) { if (err !== null) { return error(response, 500, 'Error while reading from database'); } if (reply === null) { return error(response, 404, 'Code not found'); } try { var data = JSON.parse(reply); } catch(err) { return error(response, 500, 'Error while parsing database reply'); } return success(response, data); }); }; public_api.commentsOnLine = function commentsOnLine(request, response) { var query = url.parse(request.url, true).query; var code_id = query.code_id; var line = query.line; if (code_id === undefined) { return error(response, 400, 'Invalid code id'); } if (line === undefined) { return error(response, 400, 'Invalid line number'); } db.lrange('comment:' + code_id + ':' + line, 0, -1, function(err, reply) { if (err !== null) { return error(response, 500, 'Error while reading from database'); } if (reply === null) { return error(response, 404, 'Comment not found'); } var out = []; reply.forEach(function(value) { try { out.push(JSON.parse(value)); } catch(err) { return error(response, 500, 'Error while parsing database reply'); } }); return success(response, out); }); }; // Retrieves from the database the hashtable mapping line numbers to number of // comments that start on that line public_api.commentCount = function commentCount(request, response) { var query = url.parse(request.url, true).query; var code_id = query.code_id; if(code_id === undefined) { return error(response, 400, 'Invalid code id'); } db.hgetall('comment:' + code_id + ':indices', function(err, indices) { if (err !== null) { return error(response, 500, 'Error while reading from database'); } if (indices === null) { return error(response, 404, 'Comments not found'); } return success(response, indices); }); }; /****************************************************************************** * Setters * ******************************************************************************/ // Return the anti-CSRF token the client needs to send with POST requests. Since // this URI is not CORS-whitelisted, only same-origin scripts can get it. // Intended to respond to GET requests (but Connect dependencies put it here). public_api.anticsrf = function anticsrf(request, response) { return success(response, {csrf_token: request.session._csrf}); } public_api.newcode = function newcode(request, response) { // do some basic validation var fields = request.body; if (!fields || !fields.text || !isValidString(fields.text)) { return error(response, 400, 'Invalid code text.'); } if(!fields.lang || !isValidString(fields.lang)) { return error(response, 400, 'Invalid code lang.'); } var id=uuid.v4(); // whitelist the data fields var data = { text: fields.text, lang: fields.lang }; db.set('code:' + id, JSON.stringify(data), function(err) { if (err !== null) { return error(response, 500, 'Error while writing code to database.'); } return success(response, {id:id}); }); }; // Add the comment to the database and also update the hashtable that maps line // numbers to number of comments that start on that line public_api.newcomment = function newcomment(request, response) { // reject if no referer if (!request.headers || !request.headers.referer) { return error(response, 400, 'Invalid referer'); } // do some basic validation var fields = request.body; if (!(fields && isValidString(fields.text) && isValidPositiveIntegerString(fields.line_start) && isValidPositiveIntegerString(fields.line_end))) { return error(response, 400, 'Invalid field'); } // make sure the line numbers are sane if (Number(fields.line_start) > Number(fields.line_end)) { return error(response, 400, 'Invalid line numbers'); } // whitelist the data fields var data = { user: 'Anonymous', code_id: fields.code_id, text: fields.text, line_start: parseInt(fields.line_start), line_end: parseInt(fields.line_end), diffs: fields.diffs }; if(request.session.email) { data.user = request.session.email; } var comment_key = 'comment:' + data.code_id + ':' + data.line_start; var transaction = db.multi(); transaction.rpush(comment_key, JSON.stringify(data)); var indices_key = 'comment:' + data.code_id + ':indices'; transaction.hincrby(indices_key, data.line_start, 1); return transaction.exec(function(err) { if (err !== null) { return error(response, 500, 'Error writing comment to database.'); } return success(response, data); }); }; /****************************************************************************** * Authentication * * * * In the event of implementing more than just persona for authentication, you * * should replace most of the following code with a library like * * * * passport http://passportjs.org/ * * passport-browserid https://github.com/jaredhanson/passport-browserid * * * ******************************************************************************/ module.exports = function(host, clientPort) { public_api.login = function login(request, response) { if ( !( request.body && request.body.assertion )) { return error(response, 400, 'Invalid assertion'); } var assertion = request.body.assertion; var content = querystring.stringify({ assertion: assertion, audience: util.format('http://%s:%s',host,clientPort) }); var auth_request = https.request({ host: 'verifier.login.persona.org', port: 443, path: '/verify', method: 'POST', headers: {'Content-Length': content.length, 'Content-Type': 'application/x-www-form-urlencoded'} },function(auth_response) { var data_str = ''; // assume uft8 auth_response.setEncoding('utf8'); auth_response.on('data',function(data) { data_str += data; }); auth_response.on('end',function() { try { var data_ob = JSON.parse(data_str); } catch(err) { return error(response, 500, 'Invalid verification server response'); } if (auth_response.statusCode === 200 && data_ob && data_ob.status === 'okay') { request.session.email = data_ob.email; return success(response, {email: data_ob.email}); } else { return error(response,401,'Error validating assertion'); } }); }); auth_request.write(content); auth_request.end(); }; public_api.logout = function logout(request, response) { delete request.session.email; return success(response, {}); }; return public_api; }; /* vim: set softtabstop=2 shiftwidth=2 tabstop=8 expandtab textwidth=80: */
'use strict' const dateTime = { parse: (date, time) => new Date(date + ' ' + time) , stringifyToDate: (when) => [ when.getFullYear(), ('0' + (1 + when.getMonth())).slice(-2), ('0' + when.getDate()).slice(-2) ].join('-') , stringifyToTime: (when) => [ ('0' + when.getHours()).slice(-2), ('0' + when.getMinutes()).slice(-2), ('0' + when.getSeconds()).slice(-2) ].join(':') } module.exports = dateTime
/** * * @module events/master * @author Greg Babula [greg.babula@mlb.com] * @description event communication hub, mediates events between master, model, and viewModel * */ 'use strict'; const size = require('lodash.size'); const each = require('lodash.foreach'); const every = require('lodash.every'); const utils = require('./../utils/master'); const EventEmitter = require('events').EventEmitter; /** * * @function hasEventEmitter * @param {Object} obj * @returns {Boolean} * @description returns true if given obj has an instance of EventEmitter * */ function hasEventEmitter(obj) { return obj && obj instanceof EventEmitter; } /** * * @function detachEvents * @param {Object} target * @description checks if a given target has events, proceeds to remove if true * */ function detachEvents(target) { let hasEvents = target && hasEventEmitter(target) && size(target._events); if (hasEvents) { target.removeAllListeners(); } } /** * * @constructor EventTower * @param {Object} master * @description mediates events between master, model and viewModel * */ function EventTower(master) { if (!(this instanceof EventTower)) { return new EventTower(master); } this.master = master; this.model = master && master.model || {}; this.viewModel = master && master.viewModel || {}; // // ensure all targets have an instance of // EventEmitter before proceeding to attach events // if (every([this.master, this.model, this.viewModel], hasEventEmitter)) { // // attach events to a single instnace // if (!this.master.hasInstance()) { this.attachEvents(); } } else { if (this.master) { throw Error('EventEmitter is required on all main Constructors'); } } } /** * * @method attachEvents * @description core attachEvents method, attaches core and extender events * @returns {Object} this * */ EventTower.prototype.attachEvents = function() { let { master, model, viewModel } = this; utils.log('attach events'); try { require('eventGroup')(master, model, viewModel); require('eventGroupExtender')(master, model, viewModel); } catch (e) { require('./group/group')(master, model, viewModel); require('./group/extender')(master, model, viewModel); utils.log(e, 'the override eventGroup/eventGroupExtender were not imported.'); } return this; }; /** * * @method detachEvents * @description detaches all events * @returns {Object} this * */ EventTower.prototype.detachEvents = function() { let _eventGroup = [this.master, this.model, this.viewModel]; utils.log('detach events'); each(_eventGroup, (obj) => { detachEvents(obj); }); return this; }; module.exports = EventTower;
module.exports = minixhr function minixhr (params, done) { var url = typeof params === 'string' ? params : params.url var body = params.data var method = params.method || body ? 'POST' : 'GET' var headers = params.headers || method !== 'POST' ? {} : { 'X-Requested-With' :'XMLHttpRequest', 'Content-Type' :'application/x-www-form-urlencoded' } var timeout = params.timeout || 0 var xhr = new XMLHttpRequest() var async = timeout !== 'sync' async && (xhr.timeout = timeout) async && (xhr.ontimeout = e => finish((e.info = e.type, e))) xhr.open(method, url, async) for (var key in headers) xhr.setRequestHeader(key, headers[key]) if (typeof done === 'function') xhr.onload = xhr.onerror = finish function finish ({ type, path, info = xhr.statusText }) { var Hjson = {}, h = xhr.getAllResponseHeaders() ;(h.match(/([^\n\r:]+):([^\n\r]+)/g)||[]).forEach(function(item){ var tmp = item.split(': ') Hjson[tmp[0]] = tmp[1] }) if (type === 'error' || type === 'timeout') { var { status, responseURL: sender } = xhr done({ type: 'error', status, info, sender, path }, null, Hjson) } else done(null, xhr.responseText, Hjson) done = xhr = xhr.response = xhr.responseText = xhr.onload = xhr.onerror = 0 } body = xhr.send(body) }
"use strict"; // deps const path = require("path"); const assert = require("assert"); const http = require("http"); const https = require("https"); const express = require("express"); const fs = require("node-promfs"); const SimpleSSL = require("simplessl"); const MultiServers = require(path.join(__dirname, "..", "lib", "main.js")); // private const SSL = new SimpleSSL(); const CRTPATH = path.join(__dirname, "crt"); const SERVER_KEY = path.join(CRTPATH, "server.key"); const SERVER_CSR = path.join(CRTPATH, "server.csr"); const SERVER_CRT = path.join(CRTPATH, "server.crt"); const MESSAGE = "Hello World"; const CONTENT_TYPE = "text/plain"; // tests (0, process).env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; describe("test wrong using", () => { const servers = new MultiServers(); after(() => { return servers.release(); }); describe("timeout", () => { it("should fail on missing timeout", (done) => { servers.setTimeout().then(() => { done(new Error("run with missing timeout")); }).catch((err) => { assert.strictEqual("object", typeof err, "err is not an object"); assert.strictEqual(true, err instanceof ReferenceError, "err is not an ReferenceError"); done(); }); }); it("should fail on wrong timeout", (done) => { servers.setTimeout("test").then(() => { done(new Error("run with wrong timeout")); }).catch((err) => { assert.strictEqual("object", typeof err, "err is not an object"); assert.strictEqual(true, err instanceof TypeError, "err is not an TypeError"); done(); }); }); }); describe("addServer", () => { afterEach(() => { return servers.release(); }); it("should fail on missing data", (done) => { servers.addServer().then(() => { done(new Error("run with missing data")); }).catch((err) => { assert.strictEqual("object", typeof err, "err is not an object"); assert.strictEqual(true, err instanceof ReferenceError, "err is not an ReferenceError"); done(); }); }); it("should fail on wrong data", (done) => { servers.addServer(false).then(() => { done(new Error("run with wrong data")); }).catch((err) => { assert.strictEqual("object", typeof err, "err is not an object"); assert.strictEqual(true, err instanceof TypeError, "err is not an TypeError"); done(); }); }); it("should fail on missing name data", (done) => { servers.addServer({}).then(() => { done(new Error("run with missing name data")); }).catch((err) => { assert.strictEqual("object", typeof err, "err is not an object"); assert.strictEqual(true, err instanceof ReferenceError, "err is not an ReferenceError"); done(); }); }); it("should fail on wrong name data", (done) => { servers.addServer({ "name": 5 }).then(() => { done(new Error("run with wrong name data")); }).catch((err) => { assert.strictEqual("object", typeof err, "err is not an object"); assert.strictEqual(true, err instanceof TypeError, "err is not an TypeError"); done(); }); }); it("should fail on missing port data", (done) => { servers.addServer({ "name": "test" }).then(() => { done(new Error("run with missing port data")); }).catch((err) => { assert.strictEqual("object", typeof err, "err is not an object"); assert.strictEqual(true, err instanceof ReferenceError, "err is not an ReferenceError"); done(); }); }); it("should fail on wrong port data", (done) => { servers.addServer({ "name": "test", "port": "cinq" }).then(() => { done(new Error("run with wrong port data")); }).catch((err) => { assert.strictEqual("object", typeof err, "err is not an object"); assert.strictEqual(true, err instanceof TypeError, "err is not an TypeError"); done(); }); }); it("should fail on missing key data", (done) => { servers.addServer({ "name": "test", "port": 1337, "ssl": true }).then(() => { done(new Error("run with missing key data")); }).catch((err) => { assert.strictEqual("object", typeof err, "err is not an object"); assert.strictEqual(true, err instanceof ReferenceError, "err is not an ReferenceError"); done(); }); }); it("should fail on wrong key data", (done) => { servers.addServer({ "name": "test", "port": 1337, "ssl": true, "key": false }).then(() => { done(new Error("run with wrong key data")); }).catch((err) => { assert.strictEqual("object", typeof err, "err is not an object"); assert.strictEqual(true, err instanceof TypeError, "err is not an TypeError"); done(); }); }); it("should fail on missing cert data", (done) => { servers.addServer({ "name": "test", "port": 1337, "ssl": true, "key": "test" }).then(() => { done(new Error("run with missing cert data")); }).catch((err) => { assert.strictEqual("object", typeof err, "err is not an object"); assert.strictEqual(true, err instanceof ReferenceError, "err is not an ReferenceError"); done(); }); }); it("should fail on wrong cert data", (done) => { servers.addServer({ "name": "test", "port": 1337, "ssl": true, "key": "test", "cert": false }).then(() => { done(new Error("run with wrong cert data")); }).catch((err) => { assert.strictEqual("object", typeof err, "err is not an object"); assert.strictEqual(true, err instanceof TypeError, "err is not an TypeError"); done(); }); }); it("should fail on already used port", (done) => { servers.addServer({ "name": "test", "port": 1337 }).then(() => { return servers.addServer({ "name": "test2", "port": 1337 }); }).then(() => { done(new Error("run with already used port")); }).catch((err) => { assert.strictEqual("object", typeof err, "err is not an object"); assert.strictEqual(true, err instanceof Error, "err is not an Error"); done(); }); }); it("should fail on already used name", (done) => { servers.addServer({ "name": "test", "port": 1338 }).then(() => { return servers.addServer({ "name": "test", "port": 1337 }); }).then(() => { done(new Error("run with already used name")); }).catch((err) => { assert.strictEqual("object", typeof err, "err is not an object"); assert.strictEqual(true, err instanceof Error, "err is not an Error"); done(); }); }); }); describe("listen", () => { it("should fail on missing requestListener", (done) => { servers.listen().then(() => { done(new Error("run with missing requestListener")); }).catch((err) => { assert.strictEqual("object", typeof err, "err is not an object"); assert.strictEqual(true, err instanceof ReferenceError, "err is not an ReferenceError"); done(); }); }); it("should fail on wrong requestListener", (done) => { servers.listen(false).then(() => { done(new Error("run with wrong requestListener")); }).catch((err) => { assert.strictEqual("object", typeof err, "err is not an object"); assert.strictEqual(true, err instanceof TypeError, "err is not an TypeError"); done(); }); }); }); }); describe("create one http server", () => { const servers = new MultiServers(); after(() => { return servers.release(); }); it("should create http server", () => { return servers.addServer({ "port": 1337, "name": "basic http server", "ssl": false }).then(() => { return servers.listen((req, res) => { res.writeHead(200, { "Content-Type": CONTENT_TYPE }); res.end(MESSAGE); }); }).then(() => { return servers.listen((req, res) => { res.writeHead(200, { "Content-Type": CONTENT_TYPE }); res.end(MESSAGE); }); }).then(() => { assert.strictEqual(1, servers.servers.length, "server number is incorrect"); assert.strictEqual(true, servers.listening(), "server is not listening"); assert.strictEqual(1337, servers.servers[0].options.port, "first server name is incorrect"); assert.strictEqual("basic http server", servers.servers[0].options.name, "first server name is incorrect"); assert.strictEqual(false, servers.servers[0].options.ssl, "first server ssl is incorrect"); return Promise.resolve(); }); }); it("should request this server with wrong port", (done) => { http.request({ "port": 1338, "hostname": "127.0.0.1" }, (res) => { res.on("error", () => { done(); }).on("end", () => { done("Request passed"); }); }).on("error", () => { done(); }).end(); }).timeout(5000); it("should request this server with right data", (done) => { http.request({ "port": 1337, "hostname": "127.0.0.1" }, (res) => { res.setEncoding("utf8"); assert.strictEqual(200, res.statusCode, "request statusCode is incorrect"); assert.strictEqual(CONTENT_TYPE, res.headers["content-type"], "request content-type is incorrect"); let str = ""; res.on("data", (chunk) => { str += chunk; }).on("error", (err) => { done(err); }).on("end", () => { assert.strictEqual(MESSAGE, str, "request response is incorrect"); done(); }); }).on("error", (err) => { done(err); }).end(); }).timeout(5000); it("should stop the server", () => { return servers.release(); }); }); describe("create two http servers", () => { const servers = new MultiServers(); after(() => { return servers.release(); }); it("should create servers", () => { return servers.addServer({ "port": 1337, "name": "basic http server", "ssl": false }).then(() => { return servers.addServer({ "port": 1338, "name": "admin server", "ssl": false }); }).then(() => { return servers.listen((req, res) => { res.writeHead(200, { "Content-Type": CONTENT_TYPE }); res.end(MESSAGE); }); }).then(() => { assert.strictEqual(2, servers.servers.length, "server number is incorrect"); assert.strictEqual(true, servers.listening(), "servers are not listening"); assert.strictEqual(1337, servers.servers[0].options.port, "first server name is incorrect"); assert.strictEqual("basic http server", servers.servers[0].options.name, "first server name is incorrect"); assert.strictEqual(false, servers.servers[0].options.ssl, "first server ssl is incorrect"); assert.strictEqual(1338, servers.servers[1].options.port, "second server name is incorrect"); assert.strictEqual("admin server", servers.servers[1].options.name, "second server name is incorrect"); assert.strictEqual(false, servers.servers[1].options.ssl, "second server ssl is incorrect"); return Promise.resolve(); }); }).timeout(5000); it("should request these servers with wrong port", (done) => { http.request({ "port": 1339, "hostname": "127.0.0.1" }, (res) => { res.on("error", () => { done(); }).on("end", () => { done("Request passed"); }); }).on("error", () => { done(); }).end(); }).timeout(5000); it("should request first server", (done) => { http.request({ "port": 1337, "hostname": "127.0.0.1" }, (res) => { res.setEncoding("utf8"); assert.strictEqual(200, res.statusCode, "request statusCode is incorrect"); assert.strictEqual(CONTENT_TYPE, res.headers["content-type"], "request content-type is incorrect"); let str = ""; res.on("data", (chunk) => { str += chunk; }).on("error", (err) => { done(err); }).on("end", () => { assert.strictEqual(MESSAGE, str, "request response is incorrect"); done(); }); }).on("error", (err) => { done(err); }).end(); }).timeout(5000); it("should request second server", (done) => { http.request({ "port": 1338, "hostname": "127.0.0.1" }, (res) => { res.setEncoding("utf8"); assert.strictEqual(200, res.statusCode, "request statusCode is incorrect"); assert.strictEqual(CONTENT_TYPE, res.headers["content-type"], "request content-type is incorrect"); let str = ""; res.on("data", (chunk) => { str += chunk; }).on("error", (err) => { done(err); }).on("end", () => { assert.strictEqual(MESSAGE, str, "request response is incorrect"); done(); }); }).on("error", (err) => { done(err); }).end(); }).timeout(5000); it("should stop the server", () => { return servers.release(); }); }); describe("setTimeout", () => { const servers = new MultiServers(); afterEach(() => { return servers.release(); }); it("should test setTimeout without servers", () => { return servers.setTimeout(5000); }); it("should test setTimeout with one server", () => { return servers.addServer({ "port": 1337, "name": "basic http server", "ssl": false }).then(() => { return servers.setTimeout(5000); }); }); it("should test setTimeout with two servers", () => { return servers.addServer({ "port": 1337, "name": "basic http server", "ssl": false }).then(() => { return servers.addServer({ "port": 1338, "name": "basic http server 2", "ssl": false }); }).then(() => { return servers.listen((req, res) => { res.writeHead(200, { "Content-Type": CONTENT_TYPE }); res.end(MESSAGE); }); }).then(() => { return servers.setTimeout(5000); }); }); }); describe("create two http servers with express", () => { const servers = new MultiServers(); const app = express().get("/", (req, res) => { res.set("Content-Type", CONTENT_TYPE).send(MESSAGE); }).get("/test", (req, res) => { res.set("Content-Type", CONTENT_TYPE).send("Hello World 2"); }); before(() => { return fs.mkdirpProm(CRTPATH); }); after(() => { return servers.release().then(() => { return fs.rmdirpProm(CRTPATH); }); }); it("should create servers", () => { return servers.addServer({ "port": 1337, "name": "basic http server", "ssl": false }).then(() => { return servers.addServer({ "port": 1338, "name": "basic https server" }); }).then(() => { return servers.listen(app); }).then(() => { assert.strictEqual(2, servers.servers.length, "server number is incorrect"); assert.strictEqual(true, servers.listening(), "servers are not listening"); assert.strictEqual(1337, servers.servers[0].options.port, "first server name is incorrect"); assert.strictEqual("basic http server", servers.servers[0].options.name, "first server name is incorrect"); assert.strictEqual(false, servers.servers[0].options.ssl, "first server ssl is incorrect"); assert.strictEqual(1338, servers.servers[1].options.port, "second server name is incorrect"); assert.strictEqual("basic https server", servers.servers[1].options.name, "second server name is incorrect"); assert.strictEqual(false, servers.servers[1].options.ssl, "second server ssl is incorrect"); return Promise.resolve(); }); }).timeout(5000); it("should request these servers with wrong port", (done) => { http.request({ "port": 1339, "hostname": "127.0.0.1" }, (res) => { res.on("error", () => { done(); }).on("end", () => { done("Request passed"); }); }).on("error", () => { done(); }).end(); }).timeout(5000); it("should request first server", (done) => { http.request({ "port": 1337, "hostname": "127.0.0.1" }, (res) => { res.setEncoding("utf8"); assert.strictEqual(200, res.statusCode, "request statusCode is incorrect"); let str = ""; res.on("data", (chunk) => { str += chunk; }).on("error", (err) => { done(err); }).on("end", () => { assert.strictEqual(MESSAGE, str, "request response is incorrect"); done(); }); }).on("error", (err) => { done(err); }).end(); }).timeout(5000); it("should request second server", (done) => { http.request({ "port": 1338, "hostname": "127.0.0.1" }, (res) => { res.setEncoding("utf8"); assert.strictEqual(200, res.statusCode, "request statusCode is incorrect"); let str = ""; res.on("data", (chunk) => { str += chunk; }).on("error", (err) => { done(err); }).on("end", () => { assert.strictEqual(MESSAGE, str, "request response is incorrect"); done(); }); }).on("error", (err) => { done(err); }).end(); }).timeout(5000); it("should request second server with path", (done) => { http.request({ "port": 1338, "path": "/test", "hostname": "127.0.0.1" }, (res) => { res.setEncoding("utf8"); assert.strictEqual(200, res.statusCode, "request statusCode is incorrect"); let str = ""; res.on("data", (chunk) => { str += chunk; }).on("error", (err) => { done(err); }).on("end", () => { assert.strictEqual("Hello World 2", str, "request response is incorrect"); done(); }); }).on("error", (err) => { done(err); }).end(); }).timeout(5000); it("should stop the server", () => { return servers.release(); }); }); const PATH = (0, process).env.Path || (0, process).env.PATH || {}; if (-1 < PATH.indexOf("openssl")) { SimpleSSL.setOpenSSLConfPath(path.join(__dirname, "openssl.cnf")); describe("create http server and https server", () => { const servers = new MultiServers(); before(() => { return fs.mkdirpProm(CRTPATH); }); after(() => { return servers.release().then(() => { return fs.rmdirpProm(CRTPATH); }); }); it("should create servers", () => { return servers.addServer({ "port": 1337, "name": "basic http server", "ssl": false }).then(() => { return SSL.createCertificate(SERVER_KEY, SERVER_CSR, SERVER_CRT); }).then((data) => { return servers.addServer({ "port": 1338, "name": "basic https server", "ssl": true, "key": data.privateKey, "cert": data.certificate }); }).then(() => { return servers.listen((req, res) => { res.writeHead(200, { "Content-Type": CONTENT_TYPE }); res.end(MESSAGE); }); }).then(() => { assert.strictEqual(2, servers.servers.length, "server number is incorrect"); assert.strictEqual(true, servers.listening(), "servers are not listening"); assert.strictEqual(1337, servers.servers[0].options.port, "first server name is incorrect"); assert.strictEqual("basic http server", servers.servers[0].options.name, "first server name is incorrect"); assert.strictEqual(false, servers.servers[0].options.ssl, "first server ssl is incorrect"); assert.strictEqual(1338, servers.servers[1].options.port, "second server name is incorrect"); assert.strictEqual("basic https server", servers.servers[1].options.name, "second server name is incorrect"); assert.strictEqual(true, servers.servers[1].options.ssl, "second server ssl is incorrect"); return Promise.resolve(); }); }).timeout(5000); it("should request these servers with wrong port", (done) => { http.request({ "port": 1339, "hostname": "127.0.0.1" }, (res) => { res.on("error", () => { done(); }).on("end", () => { done("Request passed"); }); }).on("error", () => { done(); }).end(); }).timeout(5000); it("should request first server", (done) => { http.request({ "port": 1337, "hostname": "127.0.0.1" }, (res) => { res.setEncoding("utf8"); assert.strictEqual(200, res.statusCode, "request statusCode is incorrect"); assert.strictEqual(CONTENT_TYPE, res.headers["content-type"], "request content-type is incorrect"); let str = ""; res.on("data", (chunk) => { str += chunk; }).on("error", (err) => { done(err); }).on("end", () => { assert.strictEqual(MESSAGE, str, "request response is incorrect"); done(); }); }).on("error", (err) => { done(err); }).end(); }).timeout(5000); it("should request second server", (done) => { https.request({ "port": 1338, "hostname": "127.0.0.1", "rejectUnauthorized": false, "requestCert": true, "agent": false }, (res) => { res.setEncoding("utf8"); assert.strictEqual(200, res.statusCode, "request statusCode is incorrect"); assert.strictEqual(CONTENT_TYPE, res.headers["content-type"], "request content-type is incorrect"); let str = ""; res.on("data", (chunk) => { str += chunk; }).on("error", (err) => { done(err); }).on("end", () => { assert.strictEqual(MESSAGE, str, "request response is incorrect"); done(); }); }).on("error", (err) => { done(err); }).end(); }).timeout(5000); it("should stop the server", () => { return servers.release(); }); }); }
/** * Jest test definition to test targaryen Jest integration. */ 'use strict'; const targaryen = require('../../plugins/jest'); expect.extend({ toBeAllowed: targaryen.toBeAllowed }); test('getDebugDatabase()', () => { const emptyRules = {rules: {}}; const database = targaryen.getDebugDatabase(emptyRules, {}); expect(database.debug).toBe(true); }); test('getDatabase()', () => { const emptyRules = {rules: {}}; const database = targaryen.getDatabase(emptyRules, {}); expect(database.debug).toBe(false); }); describe('generic matchers', () => { test('toBeAllowed', () => { const rules = { rules: { user: { $uid: { '.read': 'auth.uid !== null', '.write': 'auth.uid === $uid' } } } }; const initialData = {}; // NOTE: Create a database with debug set to true for detailed errors const database = targaryen.getDebugDatabase(rules, initialData); expect(() => { expect(database.as(null).read('/user')).not.toBeAllowed(); }).not.toThrow(); expect(() => { expect(database.as(null).read('/user')).toBeAllowed(); }).toThrowErrorMatchingSnapshot(); expect(() => { expect(database.as({uid: '1234'}).write('/user/1234', { name: 'Anna' })).toBeAllowed(); }).not.toThrow(); expect(() => { expect(database.as({uid: '1234'}).write('/user/1234', { name: 'Anna' })).not.toBeAllowed(); }).toThrowErrorMatchingSnapshot(); }); });
'use strict'; /** * Module dependencies. */ var config = require('../config'), mongoose = require('./mongoose'), express = require('./express'), chalk = require('chalk'), seed = require('./seed'); function seedDB() { if (config.seedDB && config.seedDB.seed) { console.log(chalk.bold.red('Warning: Database seeding is turned on')); seed.start(); } } // Initialize Models mongoose.loadModels(seedDB); module.exports.loadModels = function loadModels() { mongoose.loadModels(); }; module.exports.init = function init(callback) { mongoose.connect(function (db) { // Initialize express var app = express.init(db); if (callback) callback(app, db, config); }); }; module.exports.start = function start(callback) { var _this = this; _this.init(function (app, db, config) { // Start the app by listening on <port> app.listen(process.env.PORT || config.port, function () { // Logging initialization console.log('--'); console.log(chalk.green(config.app.title)); console.log(chalk.green('Environment:\t\t\t' + process.env.NODE_ENV)); console.log(chalk.green('Port:\t\t\t\t' + config.port)); console.log(chalk.green('Database:\t\t\t\t' + config.db.uri)); if (process.env.NODE_ENV === 'secure') { console.log(chalk.green('HTTPs:\t\t\t\ton')); } console.log(chalk.green('App version:\t\t\t' + config.meanjs.version)); if (config.meanjs['meanjs-version']) console.log(chalk.green('MEAN.JS version:\t\t\t' + config.meanjs['meanjs-version'])); console.log('--'); if (callback) callback(app, db, config); }); }); };
"use strict"; const Telegram = require("telegram-node-bot"); class KickController extends Telegram.TelegramBaseController { kickHandler($) { let userToKick = $.message.text.split(" ").slice(1); if (!userToKick) { $.sendMessage("Please include the username after /kick"); } else { console.log($); } } get routes() { return { kickCommand: "kickHandler" }; } } module.exports = KickController;
import theme from '../theme.less'; import css from './customStyles.less'; import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { updateInputValue, updateFocusedItem } from 'actions/app'; import Autowhatever from 'Autowhatever'; import SourceCodeLink from 'SourceCodeLink/SourceCodeLink'; const exampleId = '8'; const file = `demo/src/components/App/components/Example${exampleId}/Example${exampleId}.js`; const items = [{ text: 'Apple' }, { text: 'Banana' }, { text: 'Cherry' }, { text: 'Grapefruit' }, { text: 'Lemon' }]; function mapStateToProps(state) { return { value: state[exampleId].value, focusedSectionIndex: state[exampleId].focusedSectionIndex, focusedItemIndex: state[exampleId].focusedItemIndex }; } function mapDispatchToProps(dispatch) { return { onChange: event => { dispatch(updateInputValue(exampleId, event.target.value)); }, onMouseEnter: (event, { sectionIndex, itemIndex }) => { dispatch(updateFocusedItem(exampleId, sectionIndex, itemIndex)); }, onMouseLeave: () => { dispatch(updateFocusedItem(exampleId, null, null)); }, onMouseDown: (event, { itemIndex }) => { dispatch(updateInputValue(exampleId, items[itemIndex].text + ' clicked')); } }; } function renderItem(item) { return ( <span>{item.text}</span> ); } function renderInput(inputProps) { return ( <div {...inputProps} className={`${inputProps.className} ${css.input}`}>{inputProps.value}</div> ); } class Example extends Component { static propTypes = { value: PropTypes.string.isRequired, focusedSectionIndex: PropTypes.number, focusedItemIndex: PropTypes.number, onChange: PropTypes.func.isRequired, onMouseEnter: PropTypes.func.isRequired, onMouseLeave: PropTypes.func.isRequired, onMouseDown: PropTypes.func.isRequired }; render() { const { value, focusedSectionIndex, focusedItemIndex, onChange, onMouseEnter, onMouseLeave, onMouseDown } = this.props; const inputProps = { value, onChange, tabIndex: 0, autoComplete: null, type: null, ref: null }; const itemProps = { onMouseEnter, onMouseLeave, onMouseDown }; return ( <div> <Autowhatever id={exampleId} items={items} renderItem={renderItem} renderInput={renderInput} inputProps={inputProps} itemProps={itemProps} focusedSectionIndex={focusedSectionIndex} focusedItemIndex={focusedItemIndex} theme={theme} /> <SourceCodeLink file={file} /> </div> ); } } export default connect(mapStateToProps, mapDispatchToProps)(Example);
version https://git-lfs.github.com/spec/v1 oid sha256:21cf4dc341ee3905c0f877b8a679197de8bb50b58421cd740858b05e610376fd size 5799
module.exports = function ($) { const $metaTags = $('meta') var extracted = {} $metaTags.each(function (index, el) { if ($(this).attr('content')) { if ($(this).attr('name')) { extracted[$(this).attr('name')] = $(this).attr('content') } if ($(this).attr('property')) { extracted[$(this).attr('property')] = $(this).attr('content') } if ($(this).attr('itemprop')) { extracted[$(this).attr('itemprop')] = $(this).attr('content') } } }) return extracted }
'use strict'; const router = require('express').Router(); const logRepo = require('app/repositories/log'); router.get('/latest', (req, res, next) => { (req.query.hasOwnProperty('after') ? logRepo.latestAfter(req.query.after) : logRepo.latest(req.query.limit) ) .then((results) => { res.send({ entries: results.map((result) => { result.params.id = result._id; return result.params; }) }); }, next); }); router.get('/clear', (req, res, next) => { logRepo.clear() .then(() => { res.send(true); }, next); }); module.exports = router;
/** * Created by 斌 on 2017/3/16. */ import _ from 'lodash' /** * localStorage * @type {{putValue: ((key?, value?)), getValue: ((key?)), remove: ((key?))}} */ export const Ls = { putValue (key, value) { localStorage.removeItem(key) if (_.isObject(value)) { localStorage.setItem(key, JSON.stringify(value)) } else { localStorage.setItem(key, value) } }, getValue (key) { let _value = '' try { _value = JSON.parse(localStorage.getItem(key)) } catch (err) { _value = localStorage.getItem(key) } return _value }, remove (key) { localStorage.removeItem(key) } } /** * sessionStorage * @type {{putValue: ((key?, value?)), getValue: ((key?)), remove: ((key?))}} */ export const Ss = { putValue (key, value) { sessionStorage.removeItem(key) if (_.isObject(value)) { sessionStorage.setItem(key, JSON.stringify(value)) } else { sessionStorage.setItem(key, value) } }, getValue (key) { let _value = '' try { _value = JSON.parse(sessionStorage.getItem(key)) } catch (err) { _value = sessionStorage.getItem(key) } return _value }, remove (key) { sessionStorage.removeItem(key) } } /** * 城市数据 * @type {[*]} */ export const citiesData = { '安徽': ['安庆市', '蚌埠市', '池州市', '滁州市', '芜湖市', '阜阳市', '淮北市', '淮南市', '合肥市', '亳州市', '黄山市', '六安市', '马鞍山市', '宿州市', '铜陵市', '宣城市'], '北京': ['北京市'], '重庆市': ['重庆市'], '福建': ['福州市', '龙岩市', '南平市', '宁德市', '莆田市', '泉州市', '三明市', '厦门市', '漳州市'], '甘肃': ['庆阳市', '白银市', '定西市', '甘南藏族自治州', '嘉峪关市', '酒泉市', '金昌市', '兰州市', '陇南市', '临夏回族自治州', '平凉市', '天水市', '武威市', '张掖市'], '广东': ['东莞市', '佛山市', '广州市', '惠州市', '河源市', '鹤山市', '揭阳市', '江门市', '开平市', '梅州市', '茂名市', '清远市', '汕头市', '深圳市', '韶关市', '肇庆市', '云浮市', '阳江市', '中山市', '湛江市', '珠海市'], '广西': ['北海市', '百色市', '崇左市', '防城港市', '桂林市', '贵港市', '河池市', '贺州市', '来宾市', '柳州市', '南宁市', '钦州市', '梧州市', '玉林市'], '贵州': ['安顺市', '毕节市', '贵阳市', '六盘水市', '黔东南苗族侗族自治州', '黔南布依族苗族自治州', '黔西南布依族苗族自治州', '仁怀市', '铜仁市', '威宁县', '遵义市'], '海南': ['儋州市', '海口市', '三亚市', '三沙市'], '河北': ['保定市', '承德市', '沧州市', '定州市', '衡水市', '邯郸市', '廊坊市', '秦皇岛市', '唐山市', '石家庄市', '邢台市', '辛集市', '张家口市'], '河南': ['安阳市', '鹤壁市', '济源市', '焦作市', '开封市', '洛阳市', '漯河市', '南阳市', '平顶山市', '濮阳市', '三门峡市', '商丘市', '信阳市', '新乡市', '许昌市', '周口市', '郑州市', '驻马店市'], '黑龙江': ['大庆市', '大兴安岭地区', '哈尔滨市', '鹤岗市', '黑河市', '佳木斯市', '鸡西市', '牡丹江市', '齐齐哈尔市', '七台河市', '绥化市', '双鸭山市', '伊春市'], '湖北': ['恩施市', '鄂州市', '黄冈市', '黄石市', '荆州市', '荆门市', '潜江市', '十堰市', '随州市', '神农架林区', '天门市', '武汉市', '仙桃市', '咸宁市', '孝感市', '襄阳市', '宜昌市'], '湖南': ['郴州市', '常德市', '长沙市', '怀化市', '衡阳市', '娄底市', '邵阳市', '湘潭市', '湘西土家族苗族自治州', '益阳市', '岳阳市', '永州市', '张家界市', '株洲市'], '吉林': ['白山市', '白城市', '长春市', '长白山保护开发区', '公主岭', '吉林市', '辽源市', '梅河口', '松原市', '四平市', '通化市', '延边朝鲜族自治区'], '江苏': ['常州市', '常熟市', '淮安市', '江阴市', '昆山市', '连云港市', '南京市', '南通市', '邳州市', '苏州市', '宿迁市', '太仓市', '泰州市', '无锡市', '徐州市', '扬州市', '盐城市', '张家港市', '镇江市'], '江西': ['抚州市', '赣州市', '高安市', '九江市', '吉安市', '景德镇市', '南昌市', '萍乡市', '上饶市', '新余市', '宜春市', '鹰潭市'], '辽宁': ['鞍山市', '本溪市', '朝阳市', '丹东市', '大连市', '抚顺市', '阜新市', '葫芦岛市', '锦州市', '辽阳市', '盘锦市', '沈阳市', '铁岭市', '营口市'], '内蒙古': ['阿拉善盟', '包头市', '巴彦淖尔市', '赤峰市', '鄂尔多斯市', '呼伦贝尔市', '呼和浩特市', '乌海市', '通辽市', '乌兰察布市', '兴安盟', '锡林郭勒盟'], '宁夏': ['固原市', '石嘴山市', '吴忠市', '银川市', '中卫市'], '青海': ['黄南州', '果洛州', '海南州', '海东市', '海西州', '海北州', '西宁市', '玉树州'], '山东': ['滨州市', '东营市', '德州市', '荷泽市', '即墨市', '济南市', '济宁市', '胶州市', '龙口市', '临沂市', '梁山市', '聊城市', '莱芜市', '青岛市', '荣成市', '日照市', '潍坊市', '泰安市', '威海市', '烟台市', '枣庄市', '淄博市', '邹城市'], '山西': ['长治市', '大同市', '晋中市', '晋城市', '临汾市', '吕梁市', '朔州市', '太原市', '忻州市', '运城市', '阳泉市'], '陕西': ['安康市', '宝鸡市', '都匀市', '汉中市', '商洛市', '铜川市', '渭南市', '西安市', '咸阳市', '延安市', '榆林市'], '上海': ['上海市'], '四川': ['成都市', '德阳市', '达州市', '广元市', '广安市', '乐山市', '泸州市', '眉山市', '绵阳市', '内江市', '南充市', '攀枝花市', '遂宁市', '宜宾市', '雅安市', '自贡市', '资阳市'], '天津': ['天津市'], '西藏': ['阿里地区', '昌都市', '拉萨市', '林芝市', '那曲地区', '日喀则市', '山南市'], '新疆': ['阿克苏地区', '阿拉尔市', '博尔塔拉蒙古州', '巴音郭楞蒙古州', '北屯市', '昌吉州', '哈密市', '和田地区', '克拉玛依市', '克孜勒苏柯尔克孜州', '喀什地区', '可克达拉市', '昆玉市', '石河子市', '吐鲁番市', '图木舒克市', '铁门关市', '乌鲁木齐市', '五家渠市', '伊犁哈萨克州'], '云南': ['保山市', '楚雄彝族自治州', '德宏傣族景颇族自治州', '迪庆藏族自治州', '大理白族自治州', '红河哈尼族彝族自治州', '昆明市', '丽江市', '临沧市', '怒江傈僳族自治州', '普洱市', '曲靖市', '昭通市', '西双版纳傣族自治州', '文山壮族苗族自治州', '玉溪市'], '浙江': ['杭州市', '湖州市', '嘉兴市', '金华市', '丽水市', '宁波市', '衢州市', '绍兴市', '台州市', '温州市', '舟山市'] } export const address = { '北京': ['北京'], '广东': ['广州', '深圳', '珠海', '汕头', '韶关', '佛山', '江门', '湛江', '茂名', '肇庆', '惠州', '梅州', '汕尾', '河源', '阳江', '清远', '东莞', '中山', '潮州', '揭阳', '云浮'], '上海': ['上海'], '天津': ['天津'], '重庆': ['重庆'], '辽宁': ['沈阳', '大连', '鞍山', '抚顺', '本溪', '丹东', '锦州', '营口', '阜新', '辽阳', '盘锦', '铁岭', '朝阳', '葫芦岛'], '江苏': ['南京', '苏州', '无锡', '常州', '镇江', '南通', '泰州', '扬州', '盐城', '连云港', '徐州', '淮安', '宿迁'], '湖北': ['武汉', '黄石', '十堰', '荆州', '宜昌', '襄樊', '鄂州', '荆门', '孝感', '黄冈', '咸宁', '随州', '恩施土家族苗族自治州', '仙桃', '天门', '潜江', '神农架林区'], '四川': ['成都', '自贡', '攀枝花', '泸州', '德阳', '绵阳', '广元', '遂宁', '内江', '乐山', '南充', '眉山', '宜宾', '广安', '达州', '雅安', '巴中', '资阳', '阿坝藏族羌族自治州', '甘孜藏族自治州', '凉山彝族自治州'], '陕西': ['西安', '铜川', '宝鸡', '咸阳', '渭南', '延安', '汉中', '榆林', '安康', '商洛'], '河北': ['石家庄', '唐山', '秦皇岛', '邯郸', '邢台', '保定', '张家口', '承德', '沧州', '廊坊', '衡水'], '山西': ['太原', '大同', '阳泉', '长治', '晋城', '朔州', '晋中', '运城', '忻州', '临汾', '吕梁'], '河南': ['郑州', '开封', '洛阳', '平顶山', '安阳', '鹤壁', '新乡', '焦作', '濮阳', '许昌', '漯河', '三门峡', '南阳', '商丘', '信阳', '周口', '驻马店'], '吉林': ['长春', '吉林', '四平', '辽源', '通化', '白山', '松原', '白城', '延边朝鲜族自治州'], '黑龙江': ['哈尔滨', '齐齐哈尔', '鹤岗', '双鸭山', '鸡西', '大庆', '伊春', '牡丹江', '佳木斯', '七台河', '黑河', '绥化', '大兴安岭地区'], '内蒙古': ['呼和浩特', '包头', '乌海', '赤峰', '通辽', '鄂尔多斯', '呼伦贝尔', '巴彦淖尔', '乌兰察布', '锡林郭勒盟', '兴安盟', '阿拉善盟'], '山东': ['济南', '青岛', '淄博', '枣庄', '东营', '烟台', '潍坊', '济宁', '泰安', '威海', '日照', '莱芜', '临沂', '德州', '聊城', '滨州', '菏泽'], '安徽': ['合肥', '芜湖', '蚌埠', '淮南', '马鞍山', '淮北', '铜陵', '安庆', '黄山', '滁州', '阜阳', '宿州', '巢湖', '六安', '亳州', '池州', '宣城'], '浙江': ['杭州', '宁波', '温州', '嘉兴', '湖州', '绍兴', '金华', '衢州', '舟山', '台州', '丽水'], '福建': ['福州', '厦门', '莆田', '三明', '泉州', '漳州', '南平', '龙岩', '宁德'], '湖南': ['长沙', '株洲', '湘潭', '衡阳', '邵阳', '岳阳', '常德', '张家界', '益阳', '郴州', '永州', '怀化', '娄底', '湘西土家族苗族自治州'], '广西': ['南宁', '柳州', '桂林', '梧州', '北海', '防城港', '钦州', '贵港', '玉林', '百色', '贺州', '河池', '来宾', '崇左'], '江西': ['南昌', '景德镇', '萍乡', '九江', '新余', '鹰潭', '赣州', '吉安', '宜春', '抚州', '上饶'], '贵州': ['贵阳', '六盘水', '遵义', '安顺', '铜仁地区', '毕节地区', '黔西南布依族苗族自治州', '黔东南苗族侗族自治州', '黔南布依族苗族自治州'], '云南': ['昆明', '曲靖', '玉溪', '保山', '昭通', '丽江', '普洱', '临沧', '德宏傣族景颇族自治州', '怒江傈僳族自治州', '迪庆藏族自治州', '大理白族自治州', '楚雄彝族自治州', '红河哈尼族彝族自治州', '文山壮族苗族自治州', '西双版纳傣族自治州'], '西藏': ['拉萨', '那曲地区', '昌都地区', '林芝地区', '山南地区', '日喀则地区', '阿里地区'], '海南': ['海口', '三亚', '五指山', '琼海', '儋州', '文昌', '万宁', '东方', '澄迈县', '定安县', '屯昌县', '临高县', '白沙黎族自治县', '昌江黎族自治县', '乐东黎族自治县', '陵水黎族自治县', '保亭黎族苗族自治县', '琼中黎族苗族自治县'], '甘肃': ['兰州', '嘉峪关', '金昌', '白银', '天水', '武威', '酒泉', '张掖', '庆阳', '平凉', '定西', '陇南', '临夏回族自治州', '甘南藏族自治州'], '宁夏': ['银川', '石嘴山', '吴忠', '固原', '中卫'], '青海': ['西宁', '海东地区', '海北藏族自治州', '海南藏族自治州', '黄南藏族自治州', '果洛藏族自治州', '玉树藏族自治州', '海西蒙古族藏族自治州'], '新疆': ['乌鲁木齐', '克拉玛依', '吐鲁番地区', '哈密地区', '和田地区', '阿克苏地区', '喀什地区', '克孜勒苏柯尔克孜自治州', '巴音郭楞蒙古自治州', '昌吉回族自治州', '博尔塔拉蒙古自治州', '石河子', '阿拉尔', '图木舒克', '五家渠', '伊犁哈萨克自治州'], '香港': ['香港'], '澳门': ['澳门'], '台湾': ['台北市', '高雄市', '台北县', '桃园县', '新竹县', '苗栗县', '台中县', '彰化县', '南投县', '云林县', '嘉义县', '台南县', '高雄县', '屏东县', '宜兰县', '花莲县', '台东县', '澎湖县', '基隆市', '新竹市', '台中市', '嘉义市', '台南市'] } let timer = null export function timeout (cb, delay) { if (timer) { clearTimeout(timer) timer = null } timer = setTimeout(function () { cb() timer = null }, delay) }
// Copyright (c) 2014 Titanium I.T. LLC. All rights reserved. For license, see "README" or "LICENSE" file. "use strict"; var ensure = require("../util/ensure.js"); var SizeDescriptor = require("./size_descriptor.js"); var Size = require("../values/size.js"); var RelativeSize = require("./relative_size.js"); var SizeMultiple = require("./size_multiple.js"); var X_DIMENSION = "width"; var Y_DIMENSION = "height"; var Me = module.exports = function ElementSize(dimension, element) { var QElement = require("../q_element.js"); // break circular dependency ensure.signature(arguments, [ String, QElement ]); ensure.that(dimension === X_DIMENSION || dimension === Y_DIMENSION, "Unrecognized dimension: " + dimension); this._dimension = dimension; this._element = element; }; SizeDescriptor.extend(Me); Me.x = factoryFn(X_DIMENSION); Me.y = factoryFn(Y_DIMENSION); Me.prototype.value = function value() { ensure.signature(arguments, []); var position = this._element.getRawPosition(); return Size.create(position[this._dimension]); }; Me.prototype.toString = function toString() { ensure.signature(arguments, []); return this._dimension + " of " + this._element; }; function factoryFn(dimension) { return function factory(element) { return new Me(dimension, element); }; }