code
stringlengths
2
1.05M
nv.models.lineWithFocusChart = function() { "use strict"; //============================================================ // Public Variables with Default Settings //------------------------------------------------------------ var lines = nv.models.line() , lines2 = nv.models.line() , xAxis = nv.models.axis() , yAxis = nv.models.axis() , x2Axis = nv.models.axis() , y2Axis = nv.models.axis() , legend = nv.models.legend() , brush = d3.svg.brush() ; var margin = {top: 30, right: 30, bottom: 30, left: 60} , margin2 = {top: 0, right: 30, bottom: 20, left: 60} , color = nv.utils.defaultColor() , width = null , height = null , height2 = 100 , x , y , x2 , y2 , showLegend = true , brushExtent = null , tooltips = true , tooltip = function(key, x, y, e, graph) { return '<h3>' + key + '</h3>' + '<p>' + y + ' at ' + x + '</p>' } , noData = "No Data Available." , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'brush', 'stateChange', 'changeState') , transitionDuration = 250 , state = nv.utils.state() , defaultState = null ; lines .clipEdge(true) ; lines2 .interactive(false) ; xAxis .orient('bottom') .tickPadding(5) ; yAxis .orient('left') ; x2Axis .orient('bottom') .tickPadding(5) ; y2Axis .orient('left') ; //============================================================ // Private Variables //------------------------------------------------------------ var showTooltip = function(e, offsetElement) { var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), top = e.pos[1] + ( offsetElement.offsetTop || 0), x = xAxis.tickFormat()(lines.x()(e.point, e.pointIndex)), y = yAxis.tickFormat()(lines.y()(e.point, e.pointIndex)), content = tooltip(e.series.key, x, y, e, chart); nv.tooltip.show([left, top], content, null, null, offsetElement); }; var stateGetter = function(data) { return function(){ return { active: data.map(function(d) { return !d.disabled }) }; } }; var stateSetter = function(data) { return function(state) { if (state.active !== undefined) data.forEach(function(series,i) { series.disabled = !state.active[i]; }); } }; function chart(selection) { selection.each(function(data) { var container = d3.select(this), that = this; nv.utils.initSVG(container); var availableWidth = (width || parseInt(container.style('width')) || 960) - margin.left - margin.right, availableHeight1 = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom - height2, availableHeight2 = height2 - margin2.top - margin2.bottom; chart.update = function() { container.transition().duration(transitionDuration).call(chart) }; chart.container = this; state .setter(stateSetter(data), chart.update) .getter(stateGetter(data)) .update(); // DEPRECATED set state.disableddisabled state.disabled = data.map(function(d) { return !!d.disabled }); if (!defaultState) { var key; defaultState = {}; for (key in state) { if (state[key] instanceof Array) defaultState[key] = state[key].slice(0); else defaultState[key] = state[key]; } } // Display No Data message if there's nothing to show. if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { var noDataText = container.selectAll('.nv-noData').data([noData]); noDataText.enter().append('text') .attr('class', 'nvd3 nv-noData') .attr('dy', '-.7em') .style('text-anchor', 'middle'); noDataText .attr('x', margin.left + availableWidth / 2) .attr('y', margin.top + availableHeight1 / 2) .text(function(d) { return d }); return chart; } else { container.selectAll('.nv-noData').remove(); } // Setup Scales x = lines.xScale(); y = lines.yScale(); x2 = lines2.xScale(); y2 = lines2.yScale(); // Setup containers and skeleton of chart var wrap = container.selectAll('g.nv-wrap.nv-lineWithFocusChart').data([data]); var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-lineWithFocusChart').append('g'); var g = wrap.select('g'); gEnter.append('g').attr('class', 'nv-legendWrap'); var focusEnter = gEnter.append('g').attr('class', 'nv-focus'); focusEnter.append('g').attr('class', 'nv-x nv-axis'); focusEnter.append('g').attr('class', 'nv-y nv-axis'); focusEnter.append('g').attr('class', 'nv-linesWrap'); var contextEnter = gEnter.append('g').attr('class', 'nv-context'); contextEnter.append('g').attr('class', 'nv-x nv-axis'); contextEnter.append('g').attr('class', 'nv-y nv-axis'); contextEnter.append('g').attr('class', 'nv-linesWrap'); contextEnter.append('g').attr('class', 'nv-brushBackground'); contextEnter.append('g').attr('class', 'nv-x nv-brush'); // Legend if (showLegend) { legend.width(availableWidth); g.select('.nv-legendWrap') .datum(data) .call(legend); if ( margin.top != legend.height()) { margin.top = legend.height(); availableHeight1 = (height || parseInt(container.style('height')) || 400) - margin.top - margin.bottom - height2; } g.select('.nv-legendWrap') .attr('transform', 'translate(0,' + (-margin.top) +')') } wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); // Main Chart Component(s) lines .width(availableWidth) .height(availableHeight1) .color( data .map(function(d,i) { return d.color || color(d, i); }) .filter(function(d,i) { return !data[i].disabled; }) ); lines2 .defined(lines.defined()) .width(availableWidth) .height(availableHeight2) .color( data .map(function(d,i) { return d.color || color(d, i); }) .filter(function(d,i) { return !data[i].disabled; }) ); g.select('.nv-context') .attr('transform', 'translate(0,' + ( availableHeight1 + margin.bottom + margin2.top) + ')') var contextLinesWrap = g.select('.nv-context .nv-linesWrap') .datum(data.filter(function(d) { return !d.disabled })) d3.transition(contextLinesWrap).call(lines2); // Setup Main (Focus) Axes xAxis .scale(x) .ticks( nv.utils.calcTicksX(availableWidth/100, data) ) .tickSize(-availableHeight1, 0); yAxis .scale(y) .ticks( nv.utils.calcTicksY(availableHeight1/36, data) ) .tickSize( -availableWidth, 0); g.select('.nv-focus .nv-x.nv-axis') .attr('transform', 'translate(0,' + availableHeight1 + ')'); // Setup Brush brush .x(x2) .on('brush', function() { //When brushing, turn off transitions because chart needs to change immediately. var oldTransition = chart.duration(); chart.duration(0); onBrush(); chart.duration(oldTransition); }); if (brushExtent) brush.extent(brushExtent); var brushBG = g.select('.nv-brushBackground').selectAll('g') .data([brushExtent || brush.extent()]) var brushBGenter = brushBG.enter() .append('g'); brushBGenter.append('rect') .attr('class', 'left') .attr('x', 0) .attr('y', 0) .attr('height', availableHeight2); brushBGenter.append('rect') .attr('class', 'right') .attr('x', 0) .attr('y', 0) .attr('height', availableHeight2); var gBrush = g.select('.nv-x.nv-brush') .call(brush); gBrush.selectAll('rect') //.attr('y', -5) .attr('height', availableHeight2); gBrush.selectAll('.resize').append('path').attr('d', resizePath); onBrush(); // Setup Secondary (Context) Axes x2Axis .scale(x2) .ticks( nv.utils.calcTicksX(availableWidth/100, data) ) .tickSize(-availableHeight2, 0); g.select('.nv-context .nv-x.nv-axis') .attr('transform', 'translate(0,' + y2.range()[0] + ')'); d3.transition(g.select('.nv-context .nv-x.nv-axis')) .call(x2Axis); y2Axis .scale(y2) .ticks( nv.utils.calcTicksY(availableHeight2/36, data) ) .tickSize( -availableWidth, 0); d3.transition(g.select('.nv-context .nv-y.nv-axis')) .call(y2Axis); g.select('.nv-context .nv-x.nv-axis') .attr('transform', 'translate(0,' + y2.range()[0] + ')'); //============================================================ // Event Handling/Dispatching (in chart's scope) //------------------------------------------------------------ legend.dispatch.on('stateChange', function(newState) { for (var key in newState) state[key] = newState[key]; dispatch.stateChange(state); chart.update(); }); dispatch.on('tooltipShow', function(e) { if (tooltips) showTooltip(e, that.parentNode); }); dispatch.on('changeState', function(e) { if (typeof e.disabled !== 'undefined') { data.forEach(function(series,i) { series.disabled = e.disabled[i]; }); } chart.update(); }); //============================================================ // Functions //------------------------------------------------------------ // Taken from crossfilter (http://square.github.com/crossfilter/) function resizePath(d) { var e = +(d == 'e'), x = e ? 1 : -1, y = availableHeight2 / 3; return 'M' + (.5 * x) + ',' + y + 'A6,6 0 0 ' + e + ' ' + (6.5 * x) + ',' + (y + 6) + 'V' + (2 * y - 6) + 'A6,6 0 0 ' + e + ' ' + (.5 * x) + ',' + (2 * y) + 'Z' + 'M' + (2.5 * x) + ',' + (y + 8) + 'V' + (2 * y - 8) + 'M' + (4.5 * x) + ',' + (y + 8) + 'V' + (2 * y - 8); } function updateBrushBG() { if (!brush.empty()) brush.extent(brushExtent); brushBG .data([brush.empty() ? x2.domain() : brushExtent]) .each(function(d,i) { var leftWidth = x2(d[0]) - x.range()[0], rightWidth = x.range()[1] - x2(d[1]); d3.select(this).select('.left') .attr('width', leftWidth < 0 ? 0 : leftWidth); d3.select(this).select('.right') .attr('x', x2(d[1])) .attr('width', rightWidth < 0 ? 0 : rightWidth); }); } function onBrush() { brushExtent = brush.empty() ? null : brush.extent(); var extent = brush.empty() ? x2.domain() : brush.extent(); //The brush extent cannot be less than one. If it is, don't update the line chart. if (Math.abs(extent[0] - extent[1]) <= 1) { return; } dispatch.brush({extent: extent, brush: brush}); updateBrushBG(); // Update Main (Focus) var focusLinesWrap = g.select('.nv-focus .nv-linesWrap') .datum( data .filter(function(d) { return !d.disabled }) .map(function(d,i) { return { key: d.key, area: d.area, values: d.values.filter(function(d,i) { return lines.x()(d,i) >= extent[0] && lines.x()(d,i) <= extent[1]; }) } }) ); focusLinesWrap.transition().duration(transitionDuration).call(lines); // Update Main (Focus) Axes g.select('.nv-focus .nv-x.nv-axis').transition().duration(transitionDuration) .call(xAxis); g.select('.nv-focus .nv-y.nv-axis').transition().duration(transitionDuration) .call(yAxis); } }); return chart; } //============================================================ // Event Handling/Dispatching (out of chart's scope) //------------------------------------------------------------ lines.dispatch.on('elementMouseover.tooltip', function(e) { e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; dispatch.tooltipShow(e); }); lines.dispatch.on('elementMouseout.tooltip', function(e) { dispatch.tooltipHide(e); }); dispatch.on('tooltipHide', function() { if (tooltips) nv.tooltip.cleanup(); }); //============================================================ // Expose Public Variables //------------------------------------------------------------ // expose chart's sub-components chart.dispatch = dispatch; chart.legend = legend; chart.lines = lines; chart.lines2 = lines2; chart.xAxis = xAxis; chart.yAxis = yAxis; chart.x2Axis = x2Axis; chart.y2Axis = y2Axis; chart.options = nv.utils.optionsFunc.bind(chart); chart._options = Object.create({}, { // simple options, just get/set the necessary values width: {get: function(){return width;}, set: function(_){width=_;}}, height: {get: function(){return height;}, set: function(_){height=_;}}, focusHeight: {get: function(){return height2;}, set: function(_){height2=_;}}, showLegend: {get: function(){return showLegend;}, set: function(_){showLegend=_;}}, brushExtent: {get: function(){return brushExtent;}, set: function(_){brushExtent=_;}}, tooltips: {get: function(){return tooltips;}, set: function(_){tooltips=_;}}, tooltipContent: {get: function(){return tooltip;}, set: function(_){tooltip=_;}}, defaultState: {get: function(){return defaultState;}, set: function(_){defaultState=_;}}, noData: {get: function(){return noData;}, set: function(_){noData=_;}}, // options that require extra logic in the setter margin: {get: function(){return margin;}, set: function(_){ margin.top = _.top !== undefined ? _.top : margin.top; margin.right = _.right !== undefined ? _.right : margin.right; margin.bottom = _.bottom !== undefined ? _.bottom : margin.bottom; margin.left = _.left !== undefined ? _.left : margin.left; }}, color: {get: function(){return color;}, set: function(_){ color = nv.utils.getColor(_); legend.color(color); // line color is handled above? }}, interpolate: {get: function(){return lines.interpolate();}, set: function(_){ lines.interpolate(_); lines2.interpolate(_); }}, xTickFormat: {get: function(){return xAxis.xTickFormat();}, set: function(_){ xAxis.xTickFormat(_); x2Axis.xTickFormat(_); }}, yTickFormat: {get: function(){return yAxis.yTickFormat();}, set: function(_){ yAxis.yTickFormat(_); y2Axis.yTickFormat(_); }}, duration: {get: function(){return transitionDuration;}, set: function(_){ transitionDuration=_; yAxis.duration(transitionDuration); xAxis.duration(transitionDuration); }}, x: {get: function(){return lines.x();}, set: function(_){ lines.x(_); lines2.x(_); }}, y: {get: function(){return lines.y();}, set: function(_){ lines.y(_); lines2.y(_); }} }); nv.utils.inheritOptions(chart, lines); nv.utils.initOptions(chart); return chart; };
import Mmenu from './../oncanvas/mmenu.oncanvas'; import OPTIONS from './options'; import CONFIGS from './configs'; import * as DOM from '../../_modules/dom'; import { extend, uniqueId, cloneId, originalId, } from '../../_modules/helpers'; export default function () { this.opts.offCanvas = this.opts.offCanvas || {}; this.conf.offCanvas = this.conf.offCanvas || {}; // Extend options. const options = extend(this.opts.offCanvas, OPTIONS); const configs = extend(this.conf.offCanvas, CONFIGS); if (!options.use) { return; } // Add methods to the API. this._api.push('open', 'close', 'setPage'); // Setup the UI blocker. if (!Mmenu.node.blck) { this.bind('initMenu:before', () => { /** The UI blocker node. */ const blocker = DOM.create('a.mm-wrapper__blocker.mm-slideout'); blocker.id = uniqueId(); blocker.title = this.i18n(configs.screenReader.closeMenu); // Make the blocker able to receive focus. blocker.setAttribute('tabindex', '-1'); // Append the blocker node to the body. document.querySelector(configs.menu.insertSelector).append(blocker); // Store the blocker node. Mmenu.node.blck = blocker; }); } // Clone menu and prepend it to the <body>. this.bind('initMenu:before', () => { // Clone if needed. if (configs.clone) { // Clone the original menu and store it. this.node.menu = this.node.menu.cloneNode(true); // Prefix all ID's in the cloned menu. if (this.node.menu.id) { this.node.menu.id = cloneId(this.node.menu.id); } DOM.find(this.node.menu, '[id]').forEach((elem) => { elem.id = cloneId(elem.id); }); } this.node.wrpr = document.querySelector(configs.menu.insertSelector); // Prepend to the <body> document.querySelector(configs.menu.insertSelector)[configs.menu.insertMethod](this.node.menu); }); this.bind('initMenu:after', () => { // Setup the page. this.setPage(Mmenu.node.page); // Setup the menu. this.node.menu.classList.add('mm-menu--offcanvas'); // Open if url hash equals menu id (usefull when user clicks the hamburger icon before the menu is created) let hash = window.location.hash; if (hash) { let id = originalId(this.node.menu.id); if (id && id == hash.slice(1)) { setTimeout(() => { this.open(); }, 1000); } } }); // Open / close the menu. document.addEventListener('click', event => { var _a; /** THe href attribute for the clicked anchor. */ const href = (_a = event.target.closest('a')) === null || _a === void 0 ? void 0 : _a.getAttribute('href'); switch (href) { // Open menu if the clicked anchor links to the menu. case `#${originalId(this.node.menu.id)}`: event.preventDefault(); this.open(); break; // Close menu if the clicked anchor links to the page. case `#${originalId(Mmenu.node.page.id)}`: event.preventDefault(); this.close(); break; } }); // Close the menu with ESC key. document.addEventListener('keyup', (event) => { if (event.key == 'Escape') { this.close(); } }); // Prevent tabbing outside the menu, // close the menu when: // 1) the menu is opened, // 2) the focus is not inside the menu, document.addEventListener('keyup', (event) => { var _a; if (event.key == 'Tab' && /* 1 */ this.node.menu.matches('.mm-menu--opened') && /* 2 */ !((_a = document.activeElement) === null || _a === void 0 ? void 0 : _a.closest(`#${this.node.menu.id}`))) { console.log(document.activeElement); this.close(); } }); } /** * Open the menu. */ Mmenu.prototype.open = function () { if (this.node.menu.matches('.mm-menu--opened')) { return; } // Invoke "before" hook. this.trigger('open:before'); var clsn = ['mm-wrapper--opened']; this.node.wrpr.classList.add(...clsn); // Open this.node.menu.classList.add('mm-menu--opened'); this.node.wrpr.classList.add('mm-wrapper--opened'); // Focus the menu. this.node.menu.focus(); // Invoke "after" hook. this.trigger('open:after'); }; Mmenu.prototype.close = function () { var _a; if (!this.node.menu.matches('.mm-menu--opened')) { return; } // Invoke "before" hook. this.trigger('close:before'); this.node.menu.classList.remove('mm-menu--opened'); this.node.wrpr.classList.remove('mm-wrapper--opened'); // Focus opening link or page. const focus = document.querySelector(`[href="#${this.node.menu.id}"]`) || this.node.page || null; (_a = focus) === null || _a === void 0 ? void 0 : _a.focus(); // Invoke "after" hook. this.trigger('close:after'); }; /** * Set the "page" node. * * @param {HTMLElement} page Element to set as the page. */ Mmenu.prototype.setPage = function (page) { var configs = this.conf.offCanvas; // If no page was specified, find it. if (!page) { /** Array of elements that are / could be "the page". */ let pages = typeof configs.page.selector == 'string' ? DOM.find(document.body, configs.page.selector) : DOM.children(document.body, configs.page.nodetype); // Filter out elements that are absolutely not "the page". pages = pages.filter((page) => !page.matches('.mm-menu, .mm-wrapper__blocker')); // Filter out elements that are configured to not be "the page". if (configs.page.noSelector.length) { pages = pages.filter((page) => !page.matches(configs.page.noSelector.join(', '))); } // Wrap multiple pages in a single element. if (pages.length > 1) { let wrapper = DOM.create('div'); pages[0].before(wrapper); pages.forEach((page) => { wrapper.append(page); }); pages = [wrapper]; } page = pages[0]; } // Invoke "before" hook. this.trigger('setPage:before', [page]); // Make the page able to receive focus. page.setAttribute('tabindex', '-1'); // Set the classes page.classList.add('mm-page', 'mm-slideout'); // Set the ID. page.id = page.id || uniqueId(); // Sync the blocker to target the page. Mmenu.node.blck.setAttribute('href', `#${page.id}`); // Store the page node. Mmenu.node.page = page; // Invoke "after" hook. this.trigger('setPage:after', [page]); };
var assert = require("assert"); var path = require("path"); var local = path.join.bind(path, __dirname); describe("Cred", function() { var NodeGit = require("../../"); var sshPublicKey = local("../id_rsa.pub"); var sshPrivateKey = local("../id_rsa"); it("can create default credentials", function() { var defaultCreds = NodeGit.Cred.defaultNew(); assert.ok(defaultCreds instanceof NodeGit.Cred); }); it("can create ssh credentials using passed keys", function() { var cred = NodeGit.Cred.sshKeyNew( "username", sshPublicKey, sshPrivateKey, ""); assert.ok(cred instanceof NodeGit.Cred); }); it("can create credentials using plaintext", function() { var plaintextCreds = NodeGit.Cred.userpassPlaintextNew ("username", "password"); assert.ok(plaintextCreds instanceof NodeGit.Cred); }); it("can create credentials using agent", function() { var fromAgentCreds = NodeGit.Cred.sshKeyFromAgent ("username"); assert.ok(fromAgentCreds instanceof NodeGit.Cred); }); it("can create credentials using username", function() { return NodeGit.Cred.usernameNew ("username").then(function(cred) { assert.ok(cred instanceof NodeGit.Cred); }); }); it("can return 1 if a username exists", function() { var plaintextCreds = NodeGit.Cred.userpassPlaintextNew ("username", "password"); assert.ok(plaintextCreds.hasUsername() === 1); }); it("can return 0 if a username does not exist", function() { var defaultCreds = NodeGit.Cred.defaultNew(); assert.ok(defaultCreds.hasUsername() === 0); }); });
const BaseChecker = require('./../base-checker') const naming = require('./../../common/identifier-naming') const ruleId = 'func-name-mixedcase' const meta = { type: 'naming', docs: { description: 'Function name must be in camelCase.', category: 'Style Guide Rules' }, isDefault: false, recommended: true, defaultSetup: 'warn', schema: null } class FuncNameMixedcaseChecker extends BaseChecker { constructor(reporter) { super(reporter, ruleId, meta) } FunctionDefinition(node) { if (naming.isNotMixedCase(node.name) && !node.isConstructor) { this.error(node, 'Function name must be in mixedCase') } } } module.exports = FuncNameMixedcaseChecker
/** * @author mrdoob / http://mrdoob.com/ */ import { REVISION } from '../constants.js'; import { WebGLExtensions } from './webgl/WebGLExtensions.js'; import { WebGLState } from './webgl/WebGLState.js'; import { Color } from '../math/Color.js'; import { Vector4 } from '../math/Vector4.js'; function WebGL2Renderer( parameters ) { console.log( 'THREE.WebGL2Renderer', REVISION ); parameters = parameters || {}; var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ), _context = parameters.context !== undefined ? parameters.context : null, _alpha = parameters.alpha !== undefined ? parameters.alpha : false, _depth = parameters.depth !== undefined ? parameters.depth : true, _stencil = parameters.stencil !== undefined ? parameters.stencil : true, _antialias = parameters.antialias !== undefined ? parameters.antialias : false, _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true, _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false, _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default', _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false; // initialize var gl; try { var attributes = { alpha: _alpha, depth: _depth, stencil: _stencil, antialias: _antialias, premultipliedAlpha: _premultipliedAlpha, preserveDrawingBuffer: _preserveDrawingBuffer, powerPreference: _powerPreference, failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat }; // event listeners must be registered before WebGL context is created, see #12753 _canvas.addEventListener( 'webglcontextlost', onContextLost, false ); _canvas.addEventListener( 'webglcontextrestored', function () { } ); gl = _context || _canvas.getContext( 'webgl2', attributes ); if ( gl === null ) { if ( _canvas.getContext( 'webgl2' ) !== null ) { throw new Error( 'Error creating WebGL2 context with your selected attributes.' ); } else { throw new Error( 'Error creating WebGL2 context.' ); } } } catch ( error ) { console.error( 'THREE.WebGL2Renderer: ' + error.message ); } // var _autoClear = true, _autoClearColor = true, _autoClearDepth = true, _autoClearStencil = true, _clearColor = new Color( 0x000000 ), _clearAlpha = 0, _width = _canvas.width, _height = _canvas.height, _pixelRatio = 1, _viewport = new Vector4( 0, 0, _width, _height ); var extensions = new WebGLExtensions( gl ); var state = new WebGLState( gl, extensions, function () {} ); // function clear( color, depth, stencil ) { var bits = 0; if ( color === undefined || color ) bits |= gl.COLOR_BUFFER_BIT; if ( depth === undefined || depth ) bits |= gl.DEPTH_BUFFER_BIT; if ( stencil === undefined || stencil ) bits |= gl.STENCIL_BUFFER_BIT; gl.clear( bits ); } function setPixelRatio( value ) { if ( value === undefined ) return; _pixelRatio = value; setSize( _viewport.z, _viewport.w, false ); } function setSize( width, height, updateStyle ) { _width = width; _height = height; _canvas.width = width * _pixelRatio; _canvas.height = height * _pixelRatio; if ( updateStyle !== false ) { _canvas.style.width = width + 'px'; _canvas.style.height = height + 'px'; } setViewport( 0, 0, width, height ); } function setViewport( x, y, width, height ) { state.viewport( _viewport.set( x, y, width, height ) ); } function render( scene, camera ) { if ( camera !== undefined && camera.isCamera !== true ) { console.error( 'THREE.WebGL2Renderer.render: camera is not an instance of THREE.Camera.' ); return; } var background = scene.background; var forceClear = false; if ( background === null ) { state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha ); } else if ( background && background.isColor ) { state.buffers.color.setClear( background.r, background.g, background.b, 1, _premultipliedAlpha ); forceClear = true; } if ( _autoClear || forceClear ) { this.clear( _autoClearColor, _autoClearDepth, _autoClearStencil ); } } function onContextLost( event ) { event.preventDefault(); } return { domElement: _canvas, clear: clear, setPixelRatio: setPixelRatio, setSize: setSize, render: render }; } export { WebGL2Renderer };
'use strict'; exports.name = 'addClassesToSVGElement'; exports.type = 'visitor'; exports.active = false; exports.description = 'adds classnames to an outer <svg> element'; var ENOCLS = `Error in plugin "addClassesToSVGElement": absent parameters. It should have a list of classes in "classNames" or one "className". Config example: plugins: [ { name: "addClassesToSVGElement", params: { className: "mySvg" } } ] plugins: [ { name: "addClassesToSVGElement", params: { classNames: ["mySvg", "size-big"] } } ] `; /** * Add classnames to an outer <svg> element. Example config: * * plugins: [ * { * name: "addClassesToSVGElement", * params: { * className: "mySvg" * } * } * ] * * plugins: [ * { * name: "addClassesToSVGElement", * params: { * classNames: ["mySvg", "size-big"] * } * } * ] * * @author April Arcus * * @type {import('../lib/types').Plugin<{ * className?: string, * classNames?: Array<string> * }>} */ exports.fn = (root, params) => { if ( !(Array.isArray(params.classNames) && params.classNames.some(String)) && !params.className ) { console.error(ENOCLS); return null; } const classNames = params.classNames || [params.className]; return { element: { enter: (node, parentNode) => { if (node.name === 'svg' && parentNode.type === 'root') { const classList = new Set( node.attributes.class == null ? null : node.attributes.class.split(' ') ); for (const className of classNames) { if (className != null) { classList.add(className); } } node.attributes.class = Array.from(classList).join(' '); } }, }, }; };
define({main:{"en-MT":{identity:{version:{_number:"$Revision: 11914 $",_cldrVersion:"29"},language:"en",territory:"MT"},dates:{timeZoneNames:{hourFormat:"+HH:mm;-HH:mm",gmtFormat:"GMT{0}",gmtZeroFormat:"GMT",regionFormat:"{0} Time","regionFormat-type-daylight":"{0} Daylight Time","regionFormat-type-standard":"{0} Standard Time",fallbackFormat:"{1} ({0})",zone:{America:{Anchorage:{exemplarCity:"Anchorage"},Bogota:{exemplarCity:"Bogota"},Buenos_Aires:{exemplarCity:"Buenos Aires"},Caracas:{exemplarCity:"Caracas"}, Chicago:{exemplarCity:"Chicago"},Chihuahua:{exemplarCity:"Chihuahua"},Costa_Rica:{exemplarCity:"Costa Rica"},Denver:{exemplarCity:"Denver"},Edmonton:{exemplarCity:"Edmonton"},El_Salvador:{exemplarCity:"El Salvador"},Godthab:{exemplarCity:"Nuuk"},Guatemala:{exemplarCity:"Guatemala"},Guayaquil:{exemplarCity:"Guayaquil"},Halifax:{exemplarCity:"Halifax"},Indianapolis:{exemplarCity:"Indianapolis"},Lima:{exemplarCity:"Lima"},Los_Angeles:{exemplarCity:"Los Angeles"},Managua:{exemplarCity:"Managua"},Mazatlan:{exemplarCity:"Mazatlan"}, Mexico_City:{exemplarCity:"Mexico City"},New_York:{exemplarCity:"New York"},Noronha:{exemplarCity:"Noronha"},Panama:{exemplarCity:"Panama"},Phoenix:{exemplarCity:"Phoenix"},Puerto_Rico:{exemplarCity:"Puerto Rico"},Regina:{exemplarCity:"Regina"},Santiago:{exemplarCity:"Santiago"},Sao_Paulo:{exemplarCity:"Sao Paulo"},St_Johns:{exemplarCity:"St. John’s"},Tijuana:{exemplarCity:"Tijuana"},Toronto:{exemplarCity:"Toronto"},Vancouver:{exemplarCity:"Vancouver"},Winnipeg:{exemplarCity:"Winnipeg"}},Atlantic:{Azores:{exemplarCity:"Azores"}, Cape_Verde:{exemplarCity:"Cape Verde"},Reykjavik:{exemplarCity:"Reykjavik"}},Europe:{Amsterdam:{exemplarCity:"Amsterdam"},Athens:{exemplarCity:"Athens"},Belgrade:{exemplarCity:"Belgrade"},Berlin:{exemplarCity:"Berlin"},Brussels:{exemplarCity:"Brussels"},Bucharest:{exemplarCity:"Bucharest"},Budapest:{exemplarCity:"Budapest"},Copenhagen:{exemplarCity:"Copenhagen"},Dublin:{"long":{daylight:"Irish Standard Time"},exemplarCity:"Dublin"},Helsinki:{exemplarCity:"Helsinki"},Istanbul:{exemplarCity:"Istanbul"}, Kiev:{exemplarCity:"Kiev"},Lisbon:{exemplarCity:"Lisbon"},London:{"long":{daylight:"British Summer Time"},exemplarCity:"London"},Luxembourg:{exemplarCity:"Luxembourg"},Madrid:{exemplarCity:"Madrid"},Moscow:{exemplarCity:"Moscow"},Oslo:{exemplarCity:"Oslo"},Paris:{exemplarCity:"Paris"},Prague:{exemplarCity:"Prague"},Riga:{exemplarCity:"Riga"},Rome:{exemplarCity:"Rome"},Sofia:{exemplarCity:"Sofia"},Stockholm:{exemplarCity:"Stockholm"},Tallinn:{exemplarCity:"Tallinn"},Tirane:{exemplarCity:"Tirane"}, Vienna:{exemplarCity:"Vienna"},Vilnius:{exemplarCity:"Vilnius"},Warsaw:{exemplarCity:"Warsaw"},Zurich:{exemplarCity:"Zurich"}},Africa:{Algiers:{exemplarCity:"Algiers"},Cairo:{exemplarCity:"Cairo"},Casablanca:{exemplarCity:"Casablanca"},Djibouti:{exemplarCity:"Djibouti"},Harare:{exemplarCity:"Harare"},Johannesburg:{exemplarCity:"Johannesburg"},Khartoum:{exemplarCity:"Khartoum"},Lagos:{exemplarCity:"Lagos"},Mogadishu:{exemplarCity:"Mogadishu"},Nairobi:{exemplarCity:"Nairobi"},Nouakchott:{exemplarCity:"Nouakchott"}, Tripoli:{exemplarCity:"Tripoli"},Tunis:{exemplarCity:"Tunis"}},Asia:{Aden:{exemplarCity:"Aden"},Almaty:{exemplarCity:"Almaty"},Amman:{exemplarCity:"Amman"},Baghdad:{exemplarCity:"Baghdad"},Bahrain:{exemplarCity:"Bahrain"},Baku:{exemplarCity:"Baku"},Bangkok:{exemplarCity:"Bangkok"},Beirut:{exemplarCity:"Beirut"},Calcutta:{exemplarCity:"Kolkata"},Colombo:{exemplarCity:"Colombo"},Damascus:{exemplarCity:"Damascus"},Dhaka:{exemplarCity:"Dhaka"},Dubai:{exemplarCity:"Dubai"},Hong_Kong:{exemplarCity:"Hong Kong"}, Irkutsk:{exemplarCity:"Irkutsk"},Jakarta:{exemplarCity:"Jakarta"},Jerusalem:{exemplarCity:"Jerusalem"},Kabul:{exemplarCity:"Kabul"},Kamchatka:{exemplarCity:"Kamchatka"},Karachi:{exemplarCity:"Karachi"},Krasnoyarsk:{exemplarCity:"Krasnoyarsk"},Kuala_Lumpur:{exemplarCity:"Kuala Lumpur"},Kuwait:{exemplarCity:"Kuwait"},Magadan:{exemplarCity:"Magadan"},Manila:{exemplarCity:"Manila"},Muscat:{exemplarCity:"Muscat"},Nicosia:{exemplarCity:"Nicosia"},Novosibirsk:{exemplarCity:"Novosibirsk"},Qatar:{exemplarCity:"Qatar"}, Rangoon:{exemplarCity:"Rangoon"},Riyadh:{exemplarCity:"Riyadh"},Saigon:{exemplarCity:"Ho Chi Minh City"},Seoul:{exemplarCity:"Seoul"},Shanghai:{exemplarCity:"Shanghai"},Singapore:{exemplarCity:"Singapore"},Taipei:{exemplarCity:"Taipei"},Tashkent:{exemplarCity:"Tashkent"},Tehran:{exemplarCity:"Tehran"},Tokyo:{exemplarCity:"Tokyo"},Vladivostok:{exemplarCity:"Vladivostok"},Yakutsk:{exemplarCity:"Yakutsk"},Yekaterinburg:{exemplarCity:"Yekaterinburg"}},Australia:{Adelaide:{exemplarCity:"Adelaide"},Brisbane:{exemplarCity:"Brisbane"}, Darwin:{exemplarCity:"Darwin"},Hobart:{exemplarCity:"Hobart"},Perth:{exemplarCity:"Perth"},Sydney:{exemplarCity:"Sydney"}},Pacific:{Auckland:{exemplarCity:"Auckland"},Fiji:{exemplarCity:"Fiji"},Guam:{exemplarCity:"Guam"},Honolulu:{exemplarCity:"Honolulu"},Midway:{exemplarCity:"Midway"},Pago_Pago:{exemplarCity:"Pago Pago"},Tongatapu:{exemplarCity:"Tongatapu"}}},metazone:{Afghanistan:{"long":{standard:"Afghanistan Time"}},Africa_Central:{"long":{standard:"Central Africa Time"}},Africa_Eastern:{"long":{standard:"East Africa Time"}}, Africa_Southern:{"long":{standard:"South Africa Standard Time"}},Africa_Western:{"long":{generic:"West Africa Time",standard:"West Africa Standard Time",daylight:"West Africa Summer Time"}},Alaska:{"long":{generic:"Alaska Time",standard:"Alaska Standard Time",daylight:"Alaska Daylight Time"}},Almaty:{"long":{generic:"Almaty Time",standard:"Almaty Standard Time",daylight:"Almaty Summer Time"}},America_Central:{"long":{generic:"Central Time",standard:"Central Standard Time",daylight:"Central Daylight Time"}}, America_Eastern:{"long":{generic:"Eastern Time",standard:"Eastern Standard Time",daylight:"Eastern Daylight Time"}},America_Mountain:{"long":{generic:"Mountain Time",standard:"Mountain Standard Time",daylight:"Mountain Daylight Time"}},America_Pacific:{"long":{generic:"Pacific Time",standard:"Pacific Standard Time",daylight:"Pacific Daylight Time"}},Arabian:{"long":{generic:"Arabian Time",standard:"Arabian Standard Time",daylight:"Arabian Daylight Time"}},Argentina:{"long":{generic:"Argentina Time", standard:"Argentina Standard Time",daylight:"Argentina Summer Time"}},Atlantic:{"long":{generic:"Atlantic Time",standard:"Atlantic Standard Time",daylight:"Atlantic Daylight Time"}},Australia_Central:{"long":{generic:"Central Australia Time",standard:"Australian Central Standard Time",daylight:"Australian Central Daylight Time"}},Australia_Eastern:{"long":{generic:"Eastern Australia Time",standard:"Australian Eastern Standard Time",daylight:"Australian Eastern Daylight Time"}},Australia_Western:{"long":{generic:"Western Australia Time", standard:"Australian Western Standard Time",daylight:"Australian Western Daylight Time"}},Azerbaijan:{"long":{generic:"Azerbaijan Time",standard:"Azerbaijan Standard Time",daylight:"Azerbaijan Summer Time"}},Azores:{"long":{generic:"Azores Time",standard:"Azores Standard Time",daylight:"Azores Summer Time"}},Bangladesh:{"long":{generic:"Bangladesh Time",standard:"Bangladesh Standard Time",daylight:"Bangladesh Summer Time"}},Brasilia:{"long":{generic:"Brasilia Time",standard:"Brasilia Standard Time", daylight:"Brasilia Summer Time"}},Cape_Verde:{"long":{generic:"Cape Verde Time",standard:"Cape Verde Standard Time",daylight:"Cape Verde Summer Time"}},Chamorro:{"long":{standard:"Chamorro Standard Time"}},Chile:{"long":{generic:"Chile Time",standard:"Chile Standard Time",daylight:"Chile Summer Time"}},China:{"long":{generic:"China Time",standard:"China Standard Time",daylight:"China Daylight Time"}},Colombia:{"long":{generic:"Colombia Time",standard:"Colombia Standard Time",daylight:"Colombia Summer Time"}}, Ecuador:{"long":{standard:"Ecuador Time"}},Europe_Central:{"long":{generic:"Central European Time",standard:"Central European Standard Time",daylight:"Central European Summer Time"}},Europe_Eastern:{"long":{generic:"Eastern European Time",standard:"Eastern European Standard Time",daylight:"Eastern European Summer Time"}},Europe_Western:{"long":{generic:"Western European Time",standard:"Western European Standard Time",daylight:"Western European Summer Time"}},Fiji:{"long":{generic:"Fiji Time",standard:"Fiji Standard Time", daylight:"Fiji Summer Time"}},GMT:{"long":{standard:"Greenwich Mean Time"},"short":{standard:"GMT"}},Greenland_Western:{"long":{generic:"West Greenland Time",standard:"West Greenland Standard Time",daylight:"West Greenland Summer Time"}},Guam:{"long":{standard:"Guam Standard Time"}},Gulf:{"long":{standard:"Gulf Standard Time"}},Hawaii_Aleutian:{"long":{generic:"Hawaii-Aleutian Time",standard:"Hawaii-Aleutian Standard Time",daylight:"Hawaii-Aleutian Daylight Time"}},Hong_Kong:{"long":{generic:"Hong Kong Time", standard:"Hong Kong Standard Time",daylight:"Hong Kong Summer Time"}},India:{"long":{standard:"India Standard Time"}},Indochina:{"long":{standard:"Indochina Time"}},Indonesia_Western:{"long":{standard:"Western Indonesia Time"}},Iran:{"long":{generic:"Iran Time",standard:"Iran Standard Time",daylight:"Iran Daylight Time"}},Irkutsk:{"long":{generic:"Irkutsk Time",standard:"Irkutsk Standard Time",daylight:"Irkutsk Summer Time"}},Israel:{"long":{generic:"Israel Time",standard:"Israel Standard Time",daylight:"Israel Daylight Time"}}, Japan:{"long":{generic:"Japan Time",standard:"Japan Standard Time",daylight:"Japan Daylight Time"}},Kamchatka:{"long":{generic:"Petropavlovsk-Kamchatski Time",standard:"Petropavlovsk-Kamchatski Standard Time",daylight:"Petropavlovsk-Kamchatski Summer Time"}},Kazakhstan_Eastern:{"long":{standard:"East Kazakhstan Time"}},Korea:{"long":{generic:"Korean Time",standard:"Korean Standard Time",daylight:"Korean Daylight Time"}},Krasnoyarsk:{"long":{generic:"Krasnoyarsk Time",standard:"Krasnoyarsk Standard Time", daylight:"Krasnoyarsk Summer Time"}},Lanka:{"long":{standard:"Lanka Time"}},Magadan:{"long":{generic:"Magadan Time",standard:"Magadan Standard Time",daylight:"Magadan Summer Time"}},Malaysia:{"long":{standard:"Malaysia Time"}},Moscow:{"long":{generic:"Moscow Time",standard:"Moscow Standard Time",daylight:"Moscow Summer Time"}},Myanmar:{"long":{standard:"Myanmar Time"}},New_Zealand:{"long":{generic:"New Zealand Time",standard:"New Zealand Standard Time",daylight:"New Zealand Daylight Time"}},Newfoundland:{"long":{generic:"Newfoundland Time", standard:"Newfoundland Standard Time",daylight:"Newfoundland Daylight Time"}},Noronha:{"long":{generic:"Fernando de Noronha Time",standard:"Fernando de Noronha Standard Time",daylight:"Fernando de Noronha Summer Time"}},Novosibirsk:{"long":{generic:"Novosibirsk Time",standard:"Novosibirsk Standard Time",daylight:"Novosibirsk Summer Time"}},Pakistan:{"long":{generic:"Pakistan Time",standard:"Pakistan Standard Time",daylight:"Pakistan Summer Time"}},Peru:{"long":{generic:"Peru Time",standard:"Peru Standard Time", daylight:"Peru Summer Time"}},Philippines:{"long":{generic:"Philippine Time",standard:"Philippine Standard Time",daylight:"Philippine Summer Time"}},Samoa:{"long":{generic:"Samoa Time",standard:"Samoa Standard Time",daylight:"Samoa Daylight Time"}},Singapore:{"long":{standard:"Singapore Standard Time"}},Taipei:{"long":{generic:"Taipei Time",standard:"Taipei Standard Time",daylight:"Taipei Daylight Time"}},Tonga:{"long":{generic:"Tonga Time",standard:"Tonga Standard Time",daylight:"Tonga Summer Time"}}, Uzbekistan:{"long":{generic:"Uzbekistan Time",standard:"Uzbekistan Standard Time",daylight:"Uzbekistan Summer Time"}},Venezuela:{"long":{standard:"Venezuela Time"}},Vladivostok:{"long":{generic:"Vladivostok Time",standard:"Vladivostok Standard Time",daylight:"Vladivostok Summer Time"}},Yakutsk:{"long":{generic:"Yakutsk Time",standard:"Yakutsk Standard Time",daylight:"Yakutsk Summer Time"}},Yekaterinburg:{"long":{generic:"Yekaterinburg Time",standard:"Yekaterinburg Standard Time",daylight:"Yekaterinburg Summer Time"}}}}}}}});
/** File: candy.js * Candy - Chats are not dead yet. * * Authors: * - Troy McCabe <troy.mccabe@geeksquad.com> * * Copyright: * (c) 2012 Geek Squad. All rights reserved. */ /* global Candy, jQuery */ var CandyShop = (function(self) { return self; }(CandyShop || {})); /** Class: CandyShop.StickySubject * This plugin makes it so the room subject is always visible */ CandyShop.StickySubject = (function(self, Candy, $) { /** Function: init * Initialize the StickySubject plugin */ self.init = function() { // Listen for a subject change in the room $(Candy).on('candy:view.room.after-subject-change', function(e, data) { // get the current message pane and create the text var $messagePane = $(Candy.View.Pane.Room.getPane(Candy.View.getCurrent().roomJid)), subjectText = $.i18n._('roomSubject') + ' ' + data.subject; // if we don't have the subject container yet, add it // else just update the content if ($('.candy-subject-container:visible').length === 0) { $messagePane.prepend('<div class="candy-subject-container">' + subjectText + '</div>'); $messagePane.find('.message-pane-wrapper').addClass('candy-has-subject'); } else { $messagePane.find('.candy-subject-container').html(subjectText); } }); }; return self; }(CandyShop.StickySubject || {}, Candy, jQuery));
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S11.7.1_A2.4_T2; * @section: 11.7.1; * @assertion: First expression is evaluated first, and then second expression; * @description: Checking with "throw"; */ //CHECK#1 var x = function () { throw "x"; }; var y = function () { throw "y"; }; try { x() << y(); $ERROR('#1.1: var x = function () { throw "x"; }; var y = function () { throw "y"; }; x() << y() throw "x". Actual: ' + (x() << y())); } catch (e) { if (e === "y") { $ERROR('#1.2: First expression is evaluated first, and then second expression'); } else { if (e !== "x") { $ERROR('#1.3: var x = function () { throw "x"; }; var y = function () { throw "y"; }; x() << y() throw "x". Actual: ' + (e)); } } }
var traceur = require('traceur'); var traceurVersion = traceur.loader.NodeTraceurLoader.prototype.version; function traceurGet (module) { return $traceurRuntime.ModuleStore.get('traceur@' + traceurVersion + '/src/' + module); } var ParseTreeTransformer = traceurGet('codegeneration/ParseTreeTransformer.js').ParseTreeTransformer; var ScopeTransformer = traceurGet('codegeneration/ScopeTransformer.js').ScopeTransformer; var Script = traceurGet('syntax/trees/ParseTrees.js').Script; var parseStatements = traceurGet('codegeneration/PlaceholderParser.js').parseStatements; var STRING = traceurGet('syntax/TokenType.js').STRING; var LiteralExpression = traceurGet('syntax/trees/ParseTrees.js').LiteralExpression; var LiteralToken = traceurGet('syntax/LiteralToken.js').LiteralToken; // format detection regexes var leadingCommentAndMetaRegEx = /^\s*(\/\*[^\*]*(\*(?!\/)[^\*]*)*\*\/|\s*\/\/[^\n]*|\s*"[^"]+"\s*;?|\s*'[^']+'\s*;?)*\s*/; var cjsRequireRegEx = /(?:^\uFEFF?|[^$_a-zA-Z\xA0-\uFFFF."'])require\s*\(\s*("[^"\\]*(?:\\.[^"\\]*)*"|'[^'\\]*(?:\\.[^'\\]*)*')\s*\)/g; var cjsExportsRegEx = /(?:^\uFEFF?|[^$_a-zA-Z\xA0-\uFFFF.])(exports\s*(\[['"]|\.)|module(\.exports|\['exports'\]|\["exports"\])\s*(\[['"]|[=,\.]))/; var amdRegEx = /(?:^\uFEFF?|[^$_a-zA-Z\xA0-\uFFFF.])define\s*\(\s*("[^"]+"\s*,\s*|'[^']+'\s*,\s*)?\s*(\[(\s*(("[^"]+"|'[^']+')\s*,|\/\/.*\r?\n|\/\*(.|\s)*?\*\/))*(\s*("[^"]+"|'[^']+')\s*,?)?(\s*(\/\/.*\r?\n|\/\*(.|\s)*?\*\/))*\s*\]|function\s*|{|[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*\))/; var metaRegEx = /^(\s*\/\*[^\*]*(\*(?!\/)[^\*]*)*\*\/|\s*\/\/[^\n]*|\s*"[^"]+"\s*;?|\s*'[^']+'\s*;?)+/; var metaPartRegEx = /\/\*[^\*]*(\*(?!\/)[^\*]*)*\*\/|\/\/[^\n]*|"[^"]+"\s*;?|'[^']+'\s*;?/g; exports.detectFormat = function(source) { // read any SystemJS meta syntax var meta = source.match(metaRegEx); if (meta) { var metaParts = meta[0].match(metaPartRegEx); for (var i = 0; i < metaParts.length; i++) { var curPart = metaParts[i]; var len = curPart.length; var firstChar = curPart.substr(0, 1); if (curPart.substr(len - 1, 1) == ';') len--; if (firstChar != '"' && firstChar != "'") continue; var metaString = curPart.substr(1, curPart.length - 3); if (metaString.substr(0, 7) == 'format ') return metaString.substr(7); else if (metaString == 'bundle') return 'register'; } } // detect register var leadingCommentAndMeta = source.match(leadingCommentAndMetaRegEx); if (leadingCommentAndMeta && source.substr(leadingCommentAndMeta[0].length, 15) == 'System.register') return 'register'; // esm try { var compiler = new traceur.Compiler({ script: false }); var tree = compiler.parse(source); var transformer = new ESMDetectionTransformer(); transformer.transformAny(tree); if (transformer.isESModule) return 'esm'; else compiler = tree = undefined; } catch(e) { compiler = tree = undefined; } // cjs // (NB this should be updated to be parser based, with caching by name to parseCJS below) if (source.match(cjsRequireRegEx) || source.match(cjsExportsRegEx)) return 'cjs'; // amd if (source.match(amdRegEx)) return 'amd'; // fallback is cjs (not global) return 'cjs'; }; exports.parseCJS = function(source, detectProcess) { var output = { requires: [], usesBuffer: false, usesProcess: false, requireDetect: true }; var compiler, tree, transformer; // if this is a browserified module, then we skip require detection entirely // (webpack and SystemJS builds rename internal hidden require statements so aren't a problem) if (source.indexOf('(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;') != -1) { output.requireDetect = false; return output; } // CJS Buffer detection and require extraction try { compiler = new traceur.Compiler({ script: true }); tree = tree || compiler.parse(source); } catch(e) { return output; } // sets output.requires transformer = new CJSDepsTransformer(); try { transformer.transformAny(tree); } catch(e) {} output.requires = transformer.requires; // sets output.usesBuffer transformer = new GlobalUsageTransformer('Buffer'); try { transformer.transformAny(tree); } catch(e) {} output.usesBuffer = !!transformer.usesGlobal; // sets output.usesProcess transformer = new GlobalUsageTransformer('process'); try { transformer.transformAny(tree); } catch(e) {} output.usesProcess = !!transformer.usesGlobal; return output; }; function ESMDetectionTransformer() { this.isESModule = false; return ParseTreeTransformer.apply(this, arguments); } ESMDetectionTransformer.prototype = Object.create(ParseTreeTransformer.prototype); ESMDetectionTransformer.prototype.transformExportDeclaration = function(tree) { this.isESModule = true; return ParseTreeTransformer.prototype.transformExportDeclaration.call(this, tree); }; ESMDetectionTransformer.prototype.transformImportDeclaration = function(tree) { this.isESModule = true; return ParseTreeTransformer.prototype.transformImportDeclaration.call(this, tree); }; // esm remapping not currently in use /* function ESMImportsTransformer() { this.imports = []; return ParseTreeTransformer.apply(this, arguments); } ESMImportsTransformer.prototype = Object.create(ParseTreeTransformer.prototype); ESMImportsTransformer.prototype.transformModuleSpecifier = function(tree) { if (this.imports.indexOf(tree.token.processedValue) == -1) this.imports.push(tree.token.processedValue); return ParseTreeTransformer.prototype.transformModuleSpecifier.call(this, tree); }; */ function CJSDepsTransformer() { this.requires = []; return ParseTreeTransformer.apply(this, arguments); } CJSDepsTransformer.prototype = Object.create(ParseTreeTransformer.prototype); CJSDepsTransformer.prototype.transformCallExpression = function(tree) { if (!tree.operand.identifierToken || tree.operand.identifierToken.value != 'require') return ParseTreeTransformer.prototype.transformCallExpression.call(this, tree); // found a require var args = tree.args.args; if (args.length && args[0].type == 'LITERAL_EXPRESSION' && args.length == 1) { if (this.requires.indexOf(args[0].literalToken.processedValue) == -1 && typeof args[0].literalToken.processedValue == 'string') this.requires.push(args[0].literalToken.processedValue); } return ParseTreeTransformer.prototype.transformCallExpression.call(this, tree); }; function GlobalUsageTransformer(varName) { this.usesGlobal = undefined; return ScopeTransformer.apply(this, arguments); } GlobalUsageTransformer.prototype = Object.create(ScopeTransformer.prototype); GlobalUsageTransformer.prototype.transformIdentifierExpression = function(tree) { if (tree.identifierToken.value == this.varName_ && this.usesGlobal !== false) this.usesGlobal = true; return ScopeTransformer.prototype.transformIdentifierExpression.apply(this, arguments); }; GlobalUsageTransformer.prototype.transformBindingIdentifier = function(tree) { if (tree.identifierToken.value == this.varName_ && this.usesGlobal !== false) this.usesGlobal = true; return ScopeTransformer.prototype.transformBindingIdentifier.apply(this, arguments); }; GlobalUsageTransformer.prototype.sameTreeIfNameInLoopInitializer_ = function(tree) { try { tree = ScopeTransformer.prototype.sameTreeIfNameInLoopInitializer_.call(this, tree); } catch(e) {} return tree; }; GlobalUsageTransformer.prototype.transformVariableDeclaration = function(tree) { if (tree.lvalue.identifierToken.value == this.varName_) return tree; return ScopeTransformer.prototype.transformVariableDeclaration.call(this, tree); }; // NB incorrect handling for function Buffer() {}, but we don't have better scope analysis available // until a shift to Babel :( GlobalUsageTransformer.prototype.transformFunctionDeclaration = function(tree) { if (tree.name && tree.name.identifierToken && tree.name.identifierToken.value == this.varName_) this.usesGlobal = false; return ScopeTransformer.prototype.transformFunctionDeclaration.apply(this, arguments); } GlobalUsageTransformer.prototype.getDoNotRecurse = function(tree) { var doNotRecurse; try { doNotRecurse = ScopeTransformer.prototype.getDoNotRecurse.call(this, tree); } catch(e) {} return doNotRecurse; }; GlobalUsageTransformer.prototype.transformBlock = function(tree) { try { tree = ScopeTransformer.prototype.transformBlock.call(this, tree); } catch(e) {} return tree; };
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: Operator x === y uses GetValue es5id: 11.9.4_A2.1_T1 description: Either Type is not Reference or GetBase is not null ---*/ //CHECK#1 if (!(1 === 1)) { $ERROR('#1: 1 === 1'); } //CHECK#2 var x = 1; if (!(x === 1)) { $ERROR('#2: var x = 1; x === 1'); } //CHECK#3 var y = 1; if (!(1 === y)) { $ERROR('#3: var y = 1; 1 === y'); } //CHECK#4 var x = 1; var y = 1; if (!(x === y)) { $ERROR('#4: var x = 1; var y = 1; x === y'); } //CHECK#5 var objectx = new Object(); var objecty = new Object(); objectx.prop = 1; objecty.prop = 1; if (!(objectx.prop === objecty.prop)) { $ERROR('#5: var objectx = new Object(); var objecty = new Object(); objectx.prop = 1; objecty.prop = 1; objectx.prop === objecty.prop'); }
'use strict'; const assert = require('./../../assert'); const common = require('./../../common'); let battle; describe("Screen Cleaner", function () { afterEach(function () { battle.destroy(); }); it("should remove screens from both sides when sent out", function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [ {species: 'Mew', ability: 'synchronize', moves: ['reflect']}, {species: 'Mr. Mime-Galar', ability: 'screencleaner', moves: ['psychic']}, ]}); battle.setPlayer('p2', {team: [ {species: 'Mew', ability: 'synchronize', moves: ['lightscreen', 'reflecttype']}, ]}); battle.makeChoices('move reflect', 'move lightscreen'); battle.makeChoices('switch 2', 'move reflecttype'); assert(!battle.p1.sideConditions.reflect); assert(!battle.p2.sideConditions.lightscreen); }); });
describe('options', function () { beforeEach(function () { jasmine.Ajax.install(); }); afterEach(function () { jasmine.Ajax.uninstall(); }); it('should default method to get', function (done) { axios('/foo'); getAjaxRequest().then(function (request) { expect(request.method).toBe('GET'); done(); }); }); it('should accept headers', function (done) { axios('/foo', { headers: { 'X-Requested-With': 'XMLHttpRequest' } }); getAjaxRequest().then(function (request) { expect(request.requestHeaders['X-Requested-With']).toEqual('XMLHttpRequest'); done(); }); }); it('should accept params', function (done) { axios('/foo', { params: { foo: 123, bar: 456 } }); getAjaxRequest().then(function (request) { expect(request.url).toBe('/foo?foo=123&bar=456'); done(); }); }); it('should allow overriding default headers', function (done) { axios('/foo', { headers: { 'Accept': 'foo/bar' } }); getAjaxRequest().then(function (request) { expect(request.requestHeaders['Accept']).toEqual('foo/bar'); done(); }); }); it('should accept base URL', function (done) { var instance = axios.create({ baseURL: 'http://test.com/' }); instance.get('/foo'); getAjaxRequest().then(function (request) { expect(request.url).toBe('http://test.com/foo'); done(); }); }); it('should ignore base URL if request URL is absolute', function (done) { var instance = axios.create({ baseURL: 'http://someurl.com/' }); instance.get('http://someotherurl.com/'); getAjaxRequest().then(function (request) { expect(request.url).toBe('http://someotherurl.com/'); done(); }); }); });
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v0.11.1 */ goog.provide('ng.material.components.toolbar'); goog.require('ng.material.components.content'); goog.require('ng.material.core'); /** * @ngdoc module * @name material.components.toolbar */ angular.module('material.components.toolbar', [ 'material.core', 'material.components.content' ]) .directive('mdToolbar', mdToolbarDirective); /** * @ngdoc directive * @name mdToolbar * @module material.components.toolbar * @restrict E * @description * `md-toolbar` is used to place a toolbar in your app. * * Toolbars are usually used above a content area to display the title of the * current page, and show relevant action buttons for that page. * * You can change the height of the toolbar by adding either the * `md-medium-tall` or `md-tall` class to the toolbar. * * @usage * <hljs lang="html"> * <div layout="column" layout-fill> * <md-toolbar> * * <div class="md-toolbar-tools"> * <span>My App's Title</span> * * <!-- fill up the space between left and right area --> * <span flex></span> * * <md-button> * Right Bar Button * </md-button> * </div> * * </md-toolbar> * <md-content> * Hello! * </md-content> * </div> * </hljs> * * @param {boolean=} md-scroll-shrink Whether the header should shrink away as * the user scrolls down, and reveal itself as the user scrolls up. * _**Note (1):** for scrollShrink to work, the toolbar must be a sibling of a * `md-content` element, placed before it. See the scroll shrink demo._ * _**Note (2):** The `md-scroll-shrink` attribute is only parsed on component * initialization, it does not watch for scope changes._ * * * @param {number=} md-shrink-speed-factor How much to change the speed of the toolbar's * shrinking by. For example, if 0.25 is given then the toolbar will shrink * at one fourth the rate at which the user scrolls down. Default 0.5. */ function mdToolbarDirective($$rAF, $mdConstant, $mdUtil, $mdTheming, $animate) { var translateY = angular.bind(null, $mdUtil.supplant, 'translate3d(0,{0}px,0)'); return { restrict: 'E', link: function(scope, element, attr) { $mdTheming(element); if (angular.isDefined(attr.mdScrollShrink)) { setupScrollShrink(); } function setupScrollShrink() { var toolbarHeight; var contentElement; var disableScrollShrink = angular.noop; // Current "y" position of scroll // Store the last scroll top position var y = 0; var prevScrollTop = 0; var shrinkSpeedFactor = attr.mdShrinkSpeedFactor || 0.5; var debouncedContentScroll = $$rAF.throttle(onContentScroll); var debouncedUpdateHeight = $mdUtil.debounce(updateToolbarHeight, 5 * 1000); // Wait for $mdContentLoaded event from mdContent directive. // If the mdContent element is a sibling of our toolbar, hook it up // to scroll events. scope.$on('$mdContentLoaded', onMdContentLoad); // If the toolbar is used inside an ng-if statement, we may miss the // $mdContentLoaded event, so we attempt to fake it if we have a // md-content close enough. attr.$observe('mdScrollShrink', onChangeScrollShrink); // If the scope is destroyed (which could happen with ng-if), make sure // to disable scroll shrinking again scope.$on('$destroy', disableScrollShrink); /** * */ function onChangeScrollShrink(shrinkWithScroll) { var closestContent = element.parent().find('md-content'); // If we have a content element, fake the call; this might still fail // if the content element isn't a sibling of the toolbar if (!contentElement && closestContent.length) { onMdContentLoad(null, closestContent); } // Evaluate the expression shrinkWithScroll = scope.$eval(shrinkWithScroll); // Disable only if the attribute's expression evaluates to false if (shrinkWithScroll === false) { disableScrollShrink(); } else { disableScrollShrink = enableScrollShrink(); } } /** * */ function onMdContentLoad($event, newContentEl) { // Toolbar and content must be siblings if (newContentEl && element.parent()[0] === newContentEl.parent()[0]) { // unhook old content event listener if exists if (contentElement) { contentElement.off('scroll', debouncedContentScroll); } contentElement = newContentEl; disableScrollShrink = enableScrollShrink(); } } /** * */ function onContentScroll(e) { var scrollTop = e ? e.target.scrollTop : prevScrollTop; debouncedUpdateHeight(); y = Math.min( toolbarHeight / shrinkSpeedFactor, Math.max(0, y + scrollTop - prevScrollTop) ); element.css($mdConstant.CSS.TRANSFORM, translateY([-y * shrinkSpeedFactor])); contentElement.css($mdConstant.CSS.TRANSFORM, translateY([(toolbarHeight - y) * shrinkSpeedFactor])); prevScrollTop = scrollTop; $mdUtil.nextTick(function() { var hasWhiteFrame = element.hasClass('md-whiteframe-z1'); if (hasWhiteFrame && !y) { $animate.removeClass(element, 'md-whiteframe-z1'); } else if (!hasWhiteFrame && y) { $animate.addClass(element, 'md-whiteframe-z1'); } }); } /** * */ function enableScrollShrink() { if (!contentElement) return angular.noop; // no md-content contentElement.on('scroll', debouncedContentScroll); contentElement.attr('scroll-shrink', 'true'); $$rAF(updateToolbarHeight); return function disableScrollShrink() { contentElement.off('scroll', debouncedContentScroll); contentElement.attr('scroll-shrink', 'false'); $$rAF(updateToolbarHeight); } } /** * */ function updateToolbarHeight() { toolbarHeight = element.prop('offsetHeight'); // Add a negative margin-top the size of the toolbar to the content el. // The content will start transformed down the toolbarHeight amount, // so everything looks normal. // // As the user scrolls down, the content will be transformed up slowly // to put the content underneath where the toolbar was. var margin = (-toolbarHeight * shrinkSpeedFactor) + 'px'; contentElement.css({ "margin-top": margin, "margin-bottom": margin }); onContentScroll(); } } } }; } mdToolbarDirective.$inject = ["$$rAF", "$mdConstant", "$mdUtil", "$mdTheming", "$animate"]; ng.material.components.toolbar = angular.module("material.components.toolbar");
// gm - Copyright Aaron Heckmann <aaron.heckmann+github@gmail.com> (MIT Licensed) var gm = require('../') , dir = __dirname + '/imgs' gm(dir + '/original.png') .write(dir + '/original.jpg', function(err){ if (err) return console.dir(arguments) console.log(this.outname + " created :: " + arguments[3]) } )
JSIL.EscapeJSRegex = function (regexText) { return regexText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); };
require({cache:{ 'url:p3/widget/app/templates/Date.html':"<form dojoAttachPoint=\"containerNode\" class=\"PanelForm\"\n dojoAttachEvent=\"onreset:_onReset,onsubmit:_onSubmit,onchange:validate\">\n\n <div style=\"width: 420px;margin:auto;margin-top: 10px;padding:10px;\">\n <h2>Date App</h2>\n <p>Date Application For Testing Purposes</p>\n <div style=\"margin-top: 10px; text-align:center;\">\n <div data-dojo-attach-point=\"cancelButton\" data-dojo-attach-event=\"onClick:onCancel\" data-dojo-type=\"dijit/form/Button\">Cancel</div>\n <div data-dojo-attach-point=\"saveButton\" type=\"submit\" data-dojo-type=\"dijit/form/Button\">Run</div>\n </div>\n </div>\n</form>\n\n"}}); define("p3/widget/app/Date", [ 'dojo/_base/declare', 'dijit/_WidgetBase', 'dojo/on', 'dojo/dom-class', 'dijit/_TemplatedMixin', 'dijit/_WidgetsInTemplateMixin', 'dojo/text!./templates/Date.html', 'dijit/form/Form' ], function ( declare, WidgetBase, on, domClass, Templated, WidgetsInTemplate, Template, FormMixin ) { return declare([WidgetBase, FormMixin, Templated, WidgetsInTemplate], { baseClass: 'CreateWorkspace', templateString: Template, path: '', validate: function () { console.log('this.validate()', this); var valid = this.inherited(arguments); if (valid) { this.saveButton.set('disabled', false); } else { this.saveButton.set('disabled', true); } return valid; }, onSubmit: function (evt) { var _self = this; if (this.validate()) { var values = this.getValues(); console.log('Submission Values', values); domClass.add(this.domNode, 'Working'); window.App.api.service('AppService.start_app', ['Date', {}]).then(function (results) { }, function (err) { console.log('Error:', err); domClass.remove(_self.domNode, 'Working'); domClass.add(_self.domNode, 'Error'); _self.errorMessage.innerHTML = err; }); } else { console.log('Form is incomplete'); } evt.preventDefault(); evt.stopPropagation(); }, onCancel: function (evt) { console.log('Cancel/Close Dialog', evt); on.emit(this.domNode, 'dialogAction', { action: 'close', bubbles: true }); } }); });
/** * @author Temdog007 / http://github.com/Temdog007 */ import * as THREE from '../../build/three.module.js'; import { UIRow, UIText, UIInteger, UISelect, UICheckbox, UINumber } from './libs/ui.js'; import { UIPoints3 } from './libs/ui.three.js'; import { SetGeometryCommand } from './commands/SetGeometryCommand.js'; var SidebarGeometryTubeGeometry = function ( editor, object ) { var strings = editor.strings; var container = new UIRow(); var geometry = object.geometry; var parameters = geometry.parameters; // points var pointsRow = new UIRow(); pointsRow.add( new UIText( strings.getKey( 'sidebar/geometry/tube_geometry/path' ) ).setWidth( '90px' ) ); var points = new UIPoints3().setValue( parameters.path.points ).onChange( update ); pointsRow.add( points ); container.add( pointsRow ); // radius var radiusRow = new UIRow(); var radius = new UINumber( parameters.radius ).onChange( update ); radiusRow.add( new UIText( strings.getKey( 'sidebar/geometry/tube_geometry/radius' ) ).setWidth( '90px' ) ); radiusRow.add( radius ); container.add( radiusRow ); // tubularSegments var tubularSegmentsRow = new UIRow(); var tubularSegments = new UIInteger( parameters.tubularSegments ).onChange( update ); tubularSegmentsRow.add( new UIText( strings.getKey( 'sidebar/geometry/tube_geometry/tubularsegments' ) ).setWidth( '90px' ) ); tubularSegmentsRow.add( tubularSegments ); container.add( tubularSegmentsRow ); // radialSegments var radialSegmentsRow = new UIRow(); var radialSegments = new UIInteger( parameters.radialSegments ).onChange( update ); radialSegmentsRow.add( new UIText( strings.getKey( 'sidebar/geometry/tube_geometry/radialsegments' ) ).setWidth( '90px' ) ); radialSegmentsRow.add( radialSegments ); container.add( radialSegmentsRow ); // closed var closedRow = new UIRow(); var closed = new UICheckbox( parameters.closed ).onChange( update ); closedRow.add( new UIText( strings.getKey( 'sidebar/geometry/tube_geometry/closed' ) ).setWidth( '90px' ) ); closedRow.add( closed ); container.add( closedRow ); // curveType var curveTypeRow = new UIRow(); var curveType = new UISelect().setOptions( { centripetal: 'centripetal', chordal: 'chordal', catmullrom: 'catmullrom' } ).setValue( parameters.path.curveType ).onChange( update ); curveTypeRow.add( new UIText( strings.getKey( 'sidebar/geometry/tube_geometry/curvetype' ) ).setWidth( '90px' ), curveType ); container.add( curveTypeRow ); // tension var tensionRow = new UIRow().setDisplay( curveType.getValue() == 'catmullrom' ? '' : 'none' ); var tension = new UINumber( parameters.path.tension ).setStep( 0.01 ).onChange( update ); tensionRow.add( new UIText( strings.getKey( 'sidebar/geometry/tube_geometry/tension' ) ).setWidth( '90px' ), tension ); container.add( tensionRow ); // function update() { tensionRow.setDisplay( curveType.getValue() == 'catmullrom' ? '' : 'none' ); editor.execute( new SetGeometryCommand( editor, object, new THREE.TubeBufferGeometry( new THREE.CatmullRomCurve3( points.getValue(), closed.getValue(), curveType.getValue(), tension.getValue() ), tubularSegments.getValue(), radius.getValue(), radialSegments.getValue(), closed.getValue() ) ) ); } return container; }; export { SidebarGeometryTubeGeometry };
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var strings={prefixAgo:null,prefixFromNow:null,suffixAgo:"sitten",suffixFromNow:"tulevaisuudessa",seconds:"alle minuutti",minute:"minuutti",minutes:"%d minuuttia",hour:"tunti",hours:"%d tuntia",day:"päivä",days:"%d päivää",month:"kuukausi",months:"%d kuukautta",year:"vuosi",years:"%d vuotta"},_default=strings;exports.default=_default;
define({ "instruction": "หน้าจอจะปรากฏขึ้นก่อนที่เข้าถึงโปรแกรมประยุกต์", "defaultContent": "เพิ่มข้อความ, ลิงค์, และกราฟฟิคเล็กๆ ที่นี่", "requireConfirm": "ต้องการการยืนยันเพื่อดำเนินการต่อ", "noRequireConfirm": "ไม่จำเป็นต้องยืนยันที่จะดำเนินการ", "optionText": "การตั้งค่าสำหรับผู้ใช้งานในการปิดการแสดงผลสกรีนบนแอพพลิเคชั่นเริ่มต้น", "confirmLabel": "ข้อความยืนยัน: ", "confirmLabelColor": "ยืนยันสีของตัวอักษร", "defaultConfirmText": "ฉันยอมรับในข้อตกลงและข้อกำหนดต่างๆ ด้านบน", "confirmOption": "แสดง Splash screen ทุกครั้งที่เปิดแอพพลิเคชัน", "backgroundColor": "สีพื้นหลัง", "content": "เนื้อหา", "contentDescription": "กำหนดเนื้อหาที่แสดงบนหน้าจอ", "appearance": "รูปลักษณ์", "appearanceDescription": "ตั้งลักษณะของหน้าจอในขณะเริ่ม", "size": "ขนาด", "width": "ความกว้าง", "height": "ความสูง", "custom": "แก้ไขเอง", "background": "พื้นหลัง", "colorFill": "เติมสี", "imageFill": "เติมภาพ", "chooseFile": "เลือกไฟล์", "noFileChosen": "ไม่มีไฟล์ที่ถูกเลือก", "transparency": "โปร่งแสง", "sizeFill": "กรอก", "sizeFit": "พอดี", "sizeStretch": "ยืดเพื่อเติม", "sizeCenter": "ศูนย์กลาง", "sizeTile": "ข้อมูล tile", "buttonColor": "สีของปุ่ม", "buttonText": "ตัวอักษรของปุ่ม", "buttonTextColor": "ตัวอักษร", "contentAlign": "การจัดเนื้อหา", "alignTop": "บน", "alignMiddle": "กลาง", "maskColor": "สีของหน้ากาก", "options": "ตัวเลือก", "optionsDescription": "ตั้งค่าการทำงานของหน้าจอในขณะเริ่ม" });
import syntaxTrailingFunctionCommas from "babel-plugin-syntax-trailing-function-commas"; import transformAsyncToGenerator from "babel-plugin-transform-async-to-generator"; import transformExponentiationOperator from "babel-plugin-transform-exponentiation-operator"; import transformObjectRestSpread from "babel-plugin-transform-object-rest-spread"; import transformAsyncGeneratorFunctions from "babel-plugin-transform-async-generator-functions"; export default { plugins: [ syntaxTrailingFunctionCommas, // in ES2017 (remove as a breaking change) transformAsyncToGenerator, // in ES2017 (remove as a breaking change) transformExponentiationOperator, // in ES2016 (remove as a breaking change) transformAsyncGeneratorFunctions, transformObjectRestSpread ] };
var path = require('path') var webpack = require('webpack') module.exports = { devtool: 'eval', entry: [ 'webpack-hot-middleware/client', './src/index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], module: { loaders: [{ test: /\.js$/, loaders: ['babel'], include: path.join(__dirname, 'src') }, { test: /\.jpg/, loader: 'file' }] } }
function startApp() { showHideMenuLinks() showView('viewHome') attachAllEvents() }
import React from 'react'; import classNames from 'classnames'; import elementType from 'react-prop-types/lib/elementType'; const Jumbotron = React.createClass({ propTypes: { /** * You can use a custom element for this component */ componentClass: elementType }, getDefaultProps() { return { componentClass: 'div' }; }, render() { const ComponentClass = this.props.componentClass; return ( <ComponentClass {...this.props} className={classNames(this.props.className, 'jumbotron')}> {this.props.children} </ComponentClass> ); } }); export default Jumbotron;
/** * Comment Filters Module * @license MIT * @author Jim Chen */ function CommentFilter(){ this.rulebook = {"all":[]}; this.modifiers = []; this.runtime = null; this.allowTypes = { "1":true, "4":true, "5":true, "6":true, "7":true, "8":true, "17":true }; this.doModify = function(cmt){ for(var k=0;k<this.modifiers.length;k++){ cmt = this.modifiers[k](cmt); } return cmt; }; this.isMatchRule = function(cmtData,rule){ switch(rule['operator']){ case '==':if(cmtData[rule['subject']] == rule['value']){return false;};break; case '>':if(cmtData[rule['subject']] > rule['value']){return false;};break; case '<':if(cmtData[rule['subject']] < rule['value']){return false;};break; case 'range':if(cmtData[rule['subject']] > rule.value.min && cmtData[rule['subject']] < rule.value.max){return false;};break; case '!=':if(cmtData[rule['subject']] != rule.value){return false;}break; case '~':if(new RegExp(rule.value).test(cmtData[rule[subject]])){return false;}break; case '!~':if(!(new RegExp(rule.value).test(cmtData[rule[subject]]))){return false;}break; } return true; }; this.beforeSend = function(cmt){ //Check with the rules upon size var cmtMode = cmt.data.mode; if(this.rulebook[cmtMode]!=null){ for(var i=0;i<this.rulebook[cmtMode].length;i++){ if(this.rulebook[cmtMode][i].subject == 'width' || this.rulebook[cmtMode][i].subject == 'height'){ if(this.rulebook[cmtMode][i].subject == 'width'){ switch(this.rulebook[cmtMode][i].operator){ case '>':if(this.rulebook[cmtMode][i].value < cmt.offsetWidth)return false;break; case '<':if(this.rulebook[cmtMode][i].value > cmt.offsetWidth)return false;break; case 'range':if(this.rulebook[cmtMode][i].value.max > cmt.offsetWidth && this.rulebook[cmtMode][i].min < cmt.offsetWidth)return false;break; case '==':if(this.rulebook[cmtMode][i].value == cmt.offsetWidth)return false;break; default:break; } }else{ switch(this.rulebook[cmtMode][i].operator){ case '>':if(this.rulebook[cmtMode][i].value < cmt.offsetHeight)return false;break; case '<':if(this.rulebook[cmtMode][i].value > cmt.offsetHeight)return false;break; case 'range':if(this.rulebook[cmtMode][i].value.max > cmt.offsetHeight && this.rulebook[cmtMode][i].min < cmt.offsetHeight)return false;break; case '==':if(this.rulebook[cmtMode][i].value == cmt.offsetHeight)return false;break; default:break; } } } } return true; }else{return true;} } this.doValidate = function(cmtData){ if(!this.allowTypes[cmtData.mode]) return false; /** Create abstract cmt data **/ var abstCmtData = { text:cmtData.text, mode:cmtData.mode, color:cmtData.color, size:cmtData.size, stime:cmtData.stime, hash:cmtData.hash, }; if(this.rulebook[cmtData.mode] != null && this.rulebook[cmtData.mode].length > 0){ for(var i=0;i<this.rulebook[cmtData.mode];i++){ if(!this.isMatchRule(abstCmtData,this.rulebook[cmtData.mode][i])) return false; } } for(var i=0;i<this.rulebook[cmtData.mode];i++){ if(!this.isMatchRule(abstCmtData,this.rulebook[cmtData.mode][i])) return false; } return true; }; this.addRule = function(rule){ if(this.rulebook[rule.mode + ""] == null) this.rulebook[rule.mode + ""] = []; /** Normalize Operators **/ switch(rule.operator){ case 'eq': case 'equals': case '=':rule.operator='==';break; case 'ineq':rule.operator='!=';break; case 'regex': case 'matches':rule.operator='~';break; case 'notmatch': case 'iregex':rule.operator='!~';break; } this.rulebook[rule.mode].push(rule); return (this.rulebook[rule.mode].length - 1); }; this.addModifier = function(f){ this.modifiers.push(f); }; this.runtimeFilter = function(cmt){ if(this.runtime == null) return cmt; return this.runtime(cmt); }; this.setRuntimeFilter = function(f){ this.runtime = f; } }
var path = require("path"), fs = require("fs"), binding = require("bcrypt"), bcrypt = require(path.join(__dirname, '..', 'index.js'))/*, isaac = eval( fs.readFileSync(path.join(__dirname, "..", "src", "bcrypt", "prng", "accum.js"))+ fs.readFileSync(path.join(__dirname, "..", "src", "bcrypt", "prng", "isaac.js"))+ " accum.start();"+ " isaac" )*/; module.exports = { "encodeBase64": function(test) { var str = bcrypt.encodeBase64([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10], 16); test.strictEqual(str, "..CA.uOD/eaGAOmJB.yMBu"); test.done(); }, "decodeBase64": function(test) { var bytes = bcrypt.decodeBase64("..CA.uOD/eaGAOmJB.yMBv.", 16); test.deepEqual(bytes, [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F]); test.done(); }, "genSaltSync": function(test) { var salt = bcrypt.genSaltSync(10); test.ok(salt); test.ok(typeof salt == 'string'); test.ok(salt.length > 0); test.done(); }, "genSalt": function(test) { bcrypt.genSalt(10, function(err, salt) { test.ok(salt); test.ok(typeof salt == 'string'); test.ok(salt.length > 0); test.done(); }); }, "hashSync": function(test) { test.doesNotThrow(function() { bcrypt.hashSync("hello", 10); }); test.notEqual(bcrypt.hashSync("hello", 10), bcrypt.hashSync("hello", 10)); test.done(); }, "hash": function(test) { bcrypt.hash("hello", 10, function(err, hash) { test.notOk(err); test.ok(hash); test.done(); }); }, "compareSync": function(test) { var salt1 = bcrypt.genSaltSync(), hash1 = bcrypt.hashSync("hello", salt1); // $2a$ var salt2 = bcrypt.genSaltSync().replace(/\$2a\$/, "$2y$"), hash2 = bcrypt.hashSync("world", salt2); var salt3 = bcrypt.genSaltSync().replace(/\$2a\$/, "$2b$"), hash3 = bcrypt.hashSync("hello world", salt3); test.strictEqual(hash1.substring(0,4), "$2a$"); test.ok(bcrypt.compareSync("hello", hash1)); test.notOk(bcrypt.compareSync("hello", hash2)); test.notOk(bcrypt.compareSync("hello", hash3)); test.strictEqual(hash2.substring(0,4), "$2y$"); test.ok(bcrypt.compareSync("world", hash2)); test.notOk(bcrypt.compareSync("world", hash1)); test.notOk(bcrypt.compareSync("world", hash3)); test.strictEqual(hash3.substring(0,4), "$2b$"); test.ok(bcrypt.compareSync("hello world", hash3)); test.notOk(bcrypt.compareSync("hello world", hash1)); test.notOk(bcrypt.compareSync("hello world", hash2)); test.done(); }, "compare": function(test) { var salt1 = bcrypt.genSaltSync(), hash1 = bcrypt.hashSync("hello", salt1); // $2a$ var salt2 = bcrypt.genSaltSync(); salt2 = salt2.substring(0,2)+'y'+salt2.substring(3); // $2y$ var hash2 = bcrypt.hashSync("world", salt2); bcrypt.compare("hello", hash1, function(err, same) { test.notOk(err); test.ok(same); bcrypt.compare("hello", hash2, function(err, same) { test.notOk(err); test.notOk(same); bcrypt.compare("world", hash2, function(err, same) { test.notOk(err); test.ok(same); bcrypt.compare("world", hash1, function(err, same) { test.notOk(err); test.notOk(same); test.done(); }); }); }); }); }, "getSalt": function(test) { var hash1 = bcrypt.hashSync("hello", bcrypt.genSaltSync()); var salt = bcrypt.getSalt(hash1); var hash2 = bcrypt.hashSync("hello", salt); test.equal(hash1, hash2); test.done(); }, "getRounds": function(test) { var hash1 = bcrypt.hashSync("hello", bcrypt.genSaltSync()); test.equal(bcrypt.getRounds(hash1), 10); test.done(); }, "progress": function(test) { bcrypt.genSalt(12, function(err, salt) { test.ok(!err); var progress = []; bcrypt.hash("hello world", salt, function(err, hash) { test.ok(!err); test.ok(typeof hash === 'string'); test.ok(progress.length >= 2); test.strictEqual(progress[0], 0); test.strictEqual(progress[progress.length-1], 1); test.done(); }, function(n) { progress.push(n); }); }); }, "promise": function(test) { bcrypt.genSalt(10) .then(function(salt) { bcrypt.hash("hello", salt) .then(function(hash) { test.ok(hash); bcrypt.compare("hello", hash) .then(function(result) { test.ok(result); test.done(); }, function(err) { test.fail(err, null, "promise rejected"); }); }, function(err) { test.fail(err, null, 'promise rejected'); }); }, function(err) { test.fail(err, null, "promise rejected"); }); }, "compat": { "quickbrown": function(test) { var pass = fs.readFileSync(path.join(__dirname, "quickbrown.txt"))+"", salt = bcrypt.genSaltSync(), hash1 = binding.hashSync(pass, salt), hash2 = bcrypt.hashSync(pass, salt); test.equal(hash1, hash2); test.done(); }, "roundsOOB": function(test) { var salt1 = bcrypt.genSaltSync(0), // $10$ like not set salt2 = binding.genSaltSync(0); test.strictEqual(salt1.substring(0, 7), "$2a$10$"); test.strictEqual(salt2.substring(0, 7), "$2a$10$"); salt1 = bcrypt.genSaltSync(3); // $04$ is lower cap salt2 = bcrypt.genSaltSync(3); test.strictEqual(salt1.substring(0, 7), "$2a$04$"); test.strictEqual(salt2.substring(0, 7), "$2a$04$"); salt1 = bcrypt.genSaltSync(32); // $31$ is upper cap salt2 = bcrypt.genSaltSync(32); test.strictEqual(salt1.substring(0, 7), "$2a$31$"); test.strictEqual(salt2.substring(0, 7), "$2a$31$"); test.done(); } } };
const EmberApp = require('ember-cli/lib/broccoli/ember-app'); const { isExperimentEnabled } = require('ember-cli/lib/experiments'); module.exports = function (defaults) { var app = new EmberApp(defaults, {}); app.import('vendor/custom-output-file.js', {outputFile: '/assets/output-file.js'}); app.import('vendor/custom-output-file.css', {outputFile: '/assets/output-file.css'}); if (isExperimentEnabled('EMBROIDER')) { const { Webpack } = require('@embroider/webpack'); return require('@embroider/compat').compatBuild(app, Webpack); } return app.toTree(); };
var moment = require( 'moment' ) , chai = require( 'chai' ); moment.suppressDeprecationWarnings = true; chai.use( require( 'sinon-chai') ); chai.config.includeStack = true; global.should = chai.should(); global.expect = chai.expect; global.AssertionError = chai.AssertionError;
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 __()); }; import { Animation } from '../../animations/animation'; import { PageTransition } from '../../transitions/page-transition'; /** * Animations for popover */ export var PopoverTransition = (function (_super) { __extends(PopoverTransition, _super); function PopoverTransition() { _super.apply(this, arguments); } PopoverTransition.prototype.mdPositionView = function (nativeEle, ev) { var originY = 'top'; var originX = 'left'; var popoverWrapperEle = nativeEle.querySelector('.popover-wrapper'); // Popover content width and height var popoverEle = nativeEle.querySelector('.popover-content'); var popoverDim = popoverEle.getBoundingClientRect(); var popoverWidth = popoverDim.width; var popoverHeight = popoverDim.height; // Window body width and height var bodyWidth = this.plt.width(); var bodyHeight = this.plt.height(); // If ev was passed, use that for target element var targetDim = ev && ev.target && ev.target.getBoundingClientRect(); var targetTop = (targetDim && 'top' in targetDim) ? targetDim.top : (bodyHeight / 2) - (popoverHeight / 2); var targetLeft = (targetDim && 'left' in targetDim) ? targetDim.left : (bodyWidth / 2) - (popoverWidth / 2); var targetHeight = targetDim && targetDim.height || 0; var popoverCSS = { top: targetTop, left: targetLeft }; // If the popover left is less than the padding it is off screen // to the left so adjust it, else if the width of the popover // exceeds the body width it is off screen to the right so adjust if (popoverCSS.left < POPOVER_MD_BODY_PADDING) { popoverCSS.left = POPOVER_MD_BODY_PADDING; } else if (popoverWidth + POPOVER_MD_BODY_PADDING + popoverCSS.left > bodyWidth) { popoverCSS.left = bodyWidth - popoverWidth - POPOVER_MD_BODY_PADDING; originX = 'right'; } // If the popover when popped down stretches past bottom of screen, // make it pop up if there's room above if (targetTop + targetHeight + popoverHeight > bodyHeight && targetTop - popoverHeight > 0) { popoverCSS.top = targetTop - popoverHeight; nativeEle.className = nativeEle.className + ' popover-bottom'; originY = 'bottom'; } else if (targetTop + targetHeight + popoverHeight > bodyHeight) { popoverEle.style.bottom = POPOVER_MD_BODY_PADDING + 'px'; } popoverEle.style.top = popoverCSS.top + 'px'; popoverEle.style.left = popoverCSS.left + 'px'; popoverEle.style[this.plt.Css.transformOrigin] = originY + ' ' + originX; // Since the transition starts before styling is done we // want to wait for the styles to apply before showing the wrapper popoverWrapperEle.style.opacity = '1'; }; PopoverTransition.prototype.iosPositionView = function (nativeEle, ev) { var originY = 'top'; var originX = 'left'; var popoverWrapperEle = nativeEle.querySelector('.popover-wrapper'); // Popover content width and height var popoverEle = nativeEle.querySelector('.popover-content'); var popoverDim = popoverEle.getBoundingClientRect(); var popoverWidth = popoverDim.width; var popoverHeight = popoverDim.height; // Window body width and height var bodyWidth = this.plt.width(); var bodyHeight = this.plt.height(); // If ev was passed, use that for target element var targetDim = ev && ev.target && ev.target.getBoundingClientRect(); var targetTop = (targetDim && 'top' in targetDim) ? targetDim.top : (bodyHeight / 2) - (popoverHeight / 2); var targetLeft = (targetDim && 'left' in targetDim) ? targetDim.left : (bodyWidth / 2); var targetWidth = targetDim && targetDim.width || 0; var targetHeight = targetDim && targetDim.height || 0; // The arrow that shows above the popover on iOS var arrowEle = nativeEle.querySelector('.popover-arrow'); var arrowDim = arrowEle.getBoundingClientRect(); var arrowWidth = arrowDim.width; var arrowHeight = arrowDim.height; // If no ev was passed, hide the arrow if (!targetDim) { arrowEle.style.display = 'none'; } var arrowCSS = { top: targetTop + targetHeight, left: targetLeft + (targetWidth / 2) - (arrowWidth / 2) }; var popoverCSS = { top: targetTop + targetHeight + (arrowHeight - 1), left: targetLeft + (targetWidth / 2) - (popoverWidth / 2) }; // If the popover left is less than the padding it is off screen // to the left so adjust it, else if the width of the popover // exceeds the body width it is off screen to the right so adjust if (popoverCSS.left < POPOVER_IOS_BODY_PADDING) { popoverCSS.left = POPOVER_IOS_BODY_PADDING; } else if (popoverWidth + POPOVER_IOS_BODY_PADDING + popoverCSS.left > bodyWidth) { popoverCSS.left = bodyWidth - popoverWidth - POPOVER_IOS_BODY_PADDING; originX = 'right'; } // If the popover when popped down stretches past bottom of screen, // make it pop up if there's room above if (targetTop + targetHeight + popoverHeight > bodyHeight && targetTop - popoverHeight > 0) { arrowCSS.top = targetTop - (arrowHeight + 1); popoverCSS.top = targetTop - popoverHeight - (arrowHeight - 1); nativeEle.className = nativeEle.className + ' popover-bottom'; originY = 'bottom'; } else if (targetTop + targetHeight + popoverHeight > bodyHeight) { popoverEle.style.bottom = POPOVER_IOS_BODY_PADDING + '%'; } arrowEle.style.top = arrowCSS.top + 'px'; arrowEle.style.left = arrowCSS.left + 'px'; popoverEle.style.top = popoverCSS.top + 'px'; popoverEle.style.left = popoverCSS.left + 'px'; popoverEle.style[this.plt.Css.transformOrigin] = originY + ' ' + originX; // Since the transition starts before styling is done we // want to wait for the styles to apply before showing the wrapper popoverWrapperEle.style.opacity = '1'; }; return PopoverTransition; }(PageTransition)); export var PopoverPopIn = (function (_super) { __extends(PopoverPopIn, _super); function PopoverPopIn() { _super.apply(this, arguments); } PopoverPopIn.prototype.init = function () { var ele = this.enteringView.pageRef().nativeElement; var backdrop = new Animation(this.plt, ele.querySelector('ion-backdrop')); var wrapper = new Animation(this.plt, ele.querySelector('.popover-wrapper')); wrapper.fromTo('opacity', 0.01, 1); backdrop.fromTo('opacity', 0.01, 0.08); this .easing('ease') .duration(100) .add(backdrop) .add(wrapper); }; PopoverPopIn.prototype.play = function () { var _this = this; this.plt.raf(function () { _this.iosPositionView(_this.enteringView.pageRef().nativeElement, _this.opts.ev); _super.prototype.play.call(_this); }); }; return PopoverPopIn; }(PopoverTransition)); export var PopoverPopOut = (function (_super) { __extends(PopoverPopOut, _super); function PopoverPopOut() { _super.apply(this, arguments); } PopoverPopOut.prototype.init = function () { var ele = this.leavingView.pageRef().nativeElement; var backdrop = new Animation(this.plt, ele.querySelector('ion-backdrop')); var wrapper = new Animation(this.plt, ele.querySelector('.popover-wrapper')); wrapper.fromTo('opacity', 0.99, 0); backdrop.fromTo('opacity', 0.08, 0); this .easing('ease') .duration(500) .add(backdrop) .add(wrapper); }; return PopoverPopOut; }(PopoverTransition)); export var PopoverMdPopIn = (function (_super) { __extends(PopoverMdPopIn, _super); function PopoverMdPopIn() { _super.apply(this, arguments); } PopoverMdPopIn.prototype.init = function () { var ele = this.enteringView.pageRef().nativeElement; var content = new Animation(this.plt, ele.querySelector('.popover-content')); var viewport = new Animation(this.plt, ele.querySelector('.popover-viewport')); content.fromTo('scale', 0.001, 1); viewport.fromTo('opacity', 0.01, 1); this .easing('cubic-bezier(0.36,0.66,0.04,1)') .duration(300) .add(content) .add(viewport); }; PopoverMdPopIn.prototype.play = function () { var _this = this; this.plt.raf(function () { _this.mdPositionView(_this.enteringView.pageRef().nativeElement, _this.opts.ev); _super.prototype.play.call(_this); }); }; return PopoverMdPopIn; }(PopoverTransition)); export var PopoverMdPopOut = (function (_super) { __extends(PopoverMdPopOut, _super); function PopoverMdPopOut() { _super.apply(this, arguments); } PopoverMdPopOut.prototype.init = function () { var ele = this.leavingView.pageRef().nativeElement; var wrapper = new Animation(this.plt, ele.querySelector('.popover-wrapper')); wrapper.fromTo('opacity', 0.99, 0); this .easing('ease') .duration(500) .fromTo('opacity', 0.01, 1) .add(wrapper); }; return PopoverMdPopOut; }(PopoverTransition)); var POPOVER_IOS_BODY_PADDING = 2; var POPOVER_MD_BODY_PADDING = 12; //# sourceMappingURL=popover-transitions.js.map
import React from "react" import { mount } from "enzyme" import FeaturedGene from "../FeaturedGene" xdescribe("FeaturedGene", () => { let rendered let featuredGene beforeEach(() => { featuredGene = { title: "Gold", href: "/gene/gold", image: { url: "gold.jpg", }, } rendered = mount(<FeaturedGene {...featuredGene} />) }) it("renders a link to the gene", () => { rendered .find("a") .text() .should.containEql("Gold") rendered .find("a") .props() .href.should.equal("/gene/gold") }) it("renders an image for the gene", () => { rendered .find("img") .props() .src.should.equal("gold.jpg") }) })
function timeout(time) { return new Promise(function (resolve) { setTimeout(resolve, time); }); } module.exports = timeout;
define({ "_widgetLabel": "Bilah skala" });
/** * redbasic theme specific JavaScript */ $(document).ready(function() { // CSS3 calc() fallback (for unsupported browsers) $('body').append('<div id="css3-calc" style="width: 10px; width: calc(10px + 10px); display: none;"></div>'); if( $('#css3-calc').width() == 10) { $(window).resize(function() { if($(window).width() < 767) { $('main').css('width', $(window).width() + 285 ); } else { $('main').css('width', '100%' ); } }); } $('#css3-calc').remove(); // Remove the test element $('#expand-aside').click(function() { $('#expand-aside-icon').toggleClass('icon-circle-arrow-right').toggleClass('icon-circle-arrow-left'); $('main').toggleClass('region_1-on'); }); if($('aside').length && $('aside').html().length === 0) { $('#expand-aside').hide(); } $('#expand-tabs').click(function() { if(!$('#tabs-collapse-1').hasClass('in')){ $('html, body').animate({ scrollTop: 0 }, 'slow'); } $('#expand-tabs-icon').toggleClass('icon-circle-arrow-down').toggleClass('icon-circle-arrow-up'); }); if($('#tabs-collapse-1').length === 0) { $('#expand-tabs').hide(); } $("input[data-role=cat-tagsinput]").tagsinput({ tagClass: 'label label-primary' }); }); $(document).ready(function(){ var doctitle = document.title; function checkNotify() { var notifyUpdateElem = document.getElementById('notify-update'); if(notifyUpdateElem !== null) { if(notifyUpdateElem.innerHTML !== "") document.title = "(" + notifyUpdateElem.innerHTML + ") " + doctitle; else document.title = doctitle; } } setInterval(function () {checkNotify();}, 10 * 1000); });
type T = { foo<U>(x: U): number; }
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ // Add an extra properties to p2 that we need p2.Body.prototype.parent = null; p2.Spring.prototype.parent = null; /** * @class Phaser.Physics.P2 * @classdesc Physics World Constructor * @constructor * @param {Phaser.Game} game - Reference to the current game instance. * @param {object} [config] - Physics configuration object passed in from the game constructor. */ Phaser.Physics.P2 = function (game, config) { /** * @property {Phaser.Game} game - Local reference to game. */ this.game = game; if (typeof config === 'undefined' || !config.hasOwnProperty('gravity') || !config.hasOwnProperty('broadphase')) { config = { gravity: [0, 0], broadphase: new p2.SAPBroadphase() }; } /** * @property {object} config - The p2 World configuration object. * @protected */ this.config = config; /** * @property {p2.World} world - The p2 World in which the simulation is run. * @protected */ this.world = new p2.World(this.config); /** * @property {number} frameRate - The frame rate the world will be stepped at. Defaults to 1 / 60, but you can change here. Also see useElapsedTime property. * @default */ this.frameRate = 1 / 60; /** * @property {boolean} useElapsedTime - If true the frameRate value will be ignored and instead p2 will step with the value of Game.Time.physicsElapsed, which is a delta time value. * @default */ this.useElapsedTime = false; /** * @property {boolean} paused - The paused state of the P2 World. * @default */ this.paused = false; /** * @property {array<Phaser.Physics.P2.Material>} materials - A local array of all created Materials. * @protected */ this.materials = []; /** * @property {Phaser.Physics.P2.InversePointProxy} gravity - The gravity applied to all bodies each step. */ this.gravity = new Phaser.Physics.P2.InversePointProxy(this, this.world.gravity); /** * @property {object} walls - An object containing the 4 wall bodies that bound the physics world. */ this.walls = { left: null, right: null, top: null, bottom: null }; /** * @property {Phaser.Signal} onBodyAdded - Dispatched when a new Body is added to the World. */ this.onBodyAdded = new Phaser.Signal(); /** * @property {Phaser.Signal} onBodyRemoved - Dispatched when a Body is removed from the World. */ this.onBodyRemoved = new Phaser.Signal(); /** * @property {Phaser.Signal} onSpringAdded - Dispatched when a new Spring is added to the World. */ this.onSpringAdded = new Phaser.Signal(); /** * @property {Phaser.Signal} onSpringRemoved - Dispatched when a Spring is removed from the World. */ this.onSpringRemoved = new Phaser.Signal(); /** * @property {Phaser.Signal} onConstraintAdded - Dispatched when a new Constraint is added to the World. */ this.onConstraintAdded = new Phaser.Signal(); /** * @property {Phaser.Signal} onConstraintRemoved - Dispatched when a Constraint is removed from the World. */ this.onConstraintRemoved = new Phaser.Signal(); /** * @property {Phaser.Signal} onContactMaterialAdded - Dispatched when a new ContactMaterial is added to the World. */ this.onContactMaterialAdded = new Phaser.Signal(); /** * @property {Phaser.Signal} onContactMaterialRemoved - Dispatched when a ContactMaterial is removed from the World. */ this.onContactMaterialRemoved = new Phaser.Signal(); /** * @property {function} postBroadphaseCallback - A postBroadphase callback. */ this.postBroadphaseCallback = null; /** * @property {object} callbackContext - The context under which the callbacks are fired. */ this.callbackContext = null; /** * @property {Phaser.Signal} onBeginContact - Dispatched when a first contact is created between two bodies. This event is fired before the step has been done. */ this.onBeginContact = new Phaser.Signal(); /** * @property {Phaser.Signal} onEndContact - Dispatched when final contact occurs between two bodies. This event is fired before the step has been done. */ this.onEndContact = new Phaser.Signal(); // Pixel to meter function overrides if (config.hasOwnProperty('mpx') && config.hasOwnProperty('pxm') && config.hasOwnProperty('mpxi') && config.hasOwnProperty('pxmi')) { this.mpx = config.mpx; this.mpxi = config.mpxi; this.pxm = config.pxm; this.pxmi = config.pxmi; } // Hook into the World events this.world.on("beginContact", this.beginContactHandler, this); this.world.on("endContact", this.endContactHandler, this); /** * @property {array} collisionGroups - An array containing the collision groups that have been defined in the World. */ this.collisionGroups = []; /** * @property {Phaser.Physics.P2.CollisionGroup} nothingCollisionGroup - A default collision group. */ this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1); /** * @property {Phaser.Physics.P2.CollisionGroup} boundsCollisionGroup - A default collision group. */ this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2); /** * @property {Phaser.Physics.P2.CollisionGroup} everythingCollisionGroup - A default collision group. */ this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648); /** * @property {array} boundsCollidesWith - An array of the bodies the world bounds collides with. */ this.boundsCollidesWith = []; /** * @property {array} _toRemove - Internal var used to hold references to bodies to remove from the world on the next step. * @private */ this._toRemove = []; /** * @property {number} _collisionGroupID - Internal var. * @private */ this._collisionGroupID = 2; // By default we want everything colliding with everything this.setBoundsToWorld(true, true, true, true, false); }; Phaser.Physics.P2.prototype = { /** * This will add a P2 Physics body into the removal list for the next step. * * @method Phaser.Physics.P2#removeBodyNextStep * @param {Phaser.Physics.P2.Body} body - The body to remove at the start of the next step. */ removeBodyNextStep: function (body) { this._toRemove.push(body); }, /** * Called at the start of the core update loop. Purges flagged bodies from the world. * * @method Phaser.Physics.P2#preUpdate */ preUpdate: function () { var i = this._toRemove.length; while (i--) { this.removeBody(this._toRemove[i]); } this._toRemove.length = 0; }, /** * This will create a P2 Physics body on the given game object or array of game objects. * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. * Note: When the game object is enabled for P2 physics it has its anchor x/y set to 0.5 so it becomes centered. * * @method Phaser.Physics.P2#enable * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. * @param {boolean} [debug=false] - Create a debug object to go with this body? * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. */ enable: function (object, debug, children) { if (typeof debug === 'undefined') { debug = false; } if (typeof children === 'undefined') { children = true; } var i = 1; if (Array.isArray(object)) { i = object.length; while (i--) { if (object[i] instanceof Phaser.Group) { // If it's a Group then we do it on the children regardless this.enable(object[i].children, debug, children); } else { this.enableBody(object[i], debug); if (children && object[i].hasOwnProperty('children') && object[i].children.length > 0) { this.enable(object[i], debug, true); } } } } else { if (object instanceof Phaser.Group) { // If it's a Group then we do it on the children regardless this.enable(object.children, debug, children); } else { this.enableBody(object, debug); if (children && object.hasOwnProperty('children') && object.children.length > 0) { this.enable(object.children, debug, true); } } } }, /** * Creates a P2 Physics body on the given game object. * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled. * * @method Phaser.Physics.P2#enableBody * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property. * @param {boolean} debug - Create a debug object to go with this body? */ enableBody: function (object, debug) { if (object.hasOwnProperty('body') && object.body === null) { object.body = new Phaser.Physics.P2.Body(this.game, object, object.x, object.y, 1); object.body.debug = debug; object.anchor.set(0.5); } }, /** * Impact event handling is disabled by default. Enable it before any impact events will be dispatched. * In a busy world hundreds of impact events can be generated every step, so only enable this if you cannot do what you need via beginContact or collision masks. * * @method Phaser.Physics.P2#setImpactEvents * @param {boolean} state - Set to true to enable impact events, or false to disable. */ setImpactEvents: function (state) { if (state) { this.world.on("impact", this.impactHandler, this); } else { this.world.off("impact", this.impactHandler, this); } }, /** * Sets a callback to be fired after the Broadphase has collected collision pairs in the world. * Just because a pair exists it doesn't mean they *will* collide, just that they potentially could do. * If your calback returns `false` the pair will be removed from the narrowphase. This will stop them testing for collision this step. * Returning `true` from the callback will ensure they are checked in the narrowphase. * * @method Phaser.Physics.P2#setPostBroadphaseCallback * @param {function} callback - The callback that will receive the postBroadphase event data. It must return a boolean. Set to null to disable an existing callback. * @param {object} context - The context under which the callback will be fired. */ setPostBroadphaseCallback: function (callback, context) { this.postBroadphaseCallback = callback; this.callbackContext = context; if (callback !== null) { this.world.on("postBroadphase", this.postBroadphaseHandler, this); } else { this.world.off("postBroadphase", this.postBroadphaseHandler, this); } }, /** * Internal handler for the postBroadphase event. * * @method Phaser.Physics.P2#postBroadphaseHandler * @private * @param {object} event - The event data. */ postBroadphaseHandler: function (event) { var i = event.pairs.length; if (this.postBroadphaseCallback && i > 0) { while (i -= 2) { if (event.pairs[i].parent && event.pairs[i+1].parent && !this.postBroadphaseCallback.call(this.callbackContext, event.pairs[i].parent, event.pairs[i+1].parent)) { event.pairs.splice(i, 2); } } } }, /** * Handles a p2 impact event. * * @method Phaser.Physics.P2#impactHandler * @private * @param {object} event - The event data. */ impactHandler: function (event) { if (event.bodyA.parent && event.bodyB.parent) { // Body vs. Body callbacks var a = event.bodyA.parent; var b = event.bodyB.parent; if (a._bodyCallbacks[event.bodyB.id]) { a._bodyCallbacks[event.bodyB.id].call(a._bodyCallbackContext[event.bodyB.id], a, b, event.shapeA, event.shapeB); } if (b._bodyCallbacks[event.bodyA.id]) { b._bodyCallbacks[event.bodyA.id].call(b._bodyCallbackContext[event.bodyA.id], b, a, event.shapeB, event.shapeA); } // Body vs. Group callbacks if (a._groupCallbacks[event.shapeB.collisionGroup]) { a._groupCallbacks[event.shapeB.collisionGroup].call(a._groupCallbackContext[event.shapeB.collisionGroup], a, b, event.shapeA, event.shapeB); } if (b._groupCallbacks[event.shapeA.collisionGroup]) { b._groupCallbacks[event.shapeA.collisionGroup].call(b._groupCallbackContext[event.shapeA.collisionGroup], b, a, event.shapeB, event.shapeA); } } }, /** * Handles a p2 begin contact event. * * @method Phaser.Physics.P2#beginContactHandler * @param {object} event - The event data. */ beginContactHandler: function (event) { this.onBeginContact.dispatch(event.bodyA, event.bodyB, event.shapeA, event.shapeB, event.contactEquations); if (event.bodyA.parent) { event.bodyA.parent.onBeginContact.dispatch(event.bodyB.parent, event.shapeA, event.shapeB, event.contactEquations); } if (event.bodyB.parent) { event.bodyB.parent.onBeginContact.dispatch(event.bodyA.parent, event.shapeB, event.shapeA, event.contactEquations); } }, /** * Handles a p2 end contact event. * * @method Phaser.Physics.P2#endContactHandler * @param {object} event - The event data. */ endContactHandler: function (event) { this.onEndContact.dispatch(event.bodyA, event.bodyB, event.shapeA, event.shapeB); if (event.bodyA.parent) { event.bodyA.parent.onEndContact.dispatch(event.bodyB.parent, event.shapeA, event.shapeB); } if (event.bodyB.parent) { event.bodyB.parent.onEndContact.dispatch(event.bodyA.parent, event.shapeB, event.shapeA); } }, /** * Sets the bounds of the Physics world to match the Game.World dimensions. * You can optionally set which 'walls' to create: left, right, top or bottom. * * @method Phaser.Physics#setBoundsToWorld * @param {boolean} [left=true] - If true will create the left bounds wall. * @param {boolean} [right=true] - If true will create the right bounds wall. * @param {boolean} [top=true] - If true will create the top bounds wall. * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. */ setBoundsToWorld: function (left, right, top, bottom, setCollisionGroup) { this.setBounds(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, left, right, top, bottom, setCollisionGroup); }, /** * Sets the given material against the 4 bounds of this World. * * @method Phaser.Physics#setWorldMaterial * @param {Phaser.Physics.P2.Material} material - The material to set. * @param {boolean} [left=true] - If true will set the material on the left bounds wall. * @param {boolean} [right=true] - If true will set the material on the right bounds wall. * @param {boolean} [top=true] - If true will set the material on the top bounds wall. * @param {boolean} [bottom=true] - If true will set the material on the bottom bounds wall. */ setWorldMaterial: function (material, left, right, top, bottom) { if (typeof left === 'undefined') { left = true; } if (typeof right === 'undefined') { right = true; } if (typeof top === 'undefined') { top = true; } if (typeof bottom === 'undefined') { bottom = true; } if (left && this.walls.left) { this.walls.left.shapes[0].material = material; } if (right && this.walls.right) { this.walls.right.shapes[0].material = material; } if (top && this.walls.top) { this.walls.top.shapes[0].material = material; } if (bottom && this.walls.bottom) { this.walls.bottom.shapes[0].material = material; } }, /** * By default the World will be set to collide everything with everything. The bounds of the world is a Body with 4 shapes, one for each face. * If you start to use your own collision groups then your objects will no longer collide with the bounds. * To fix this you need to adjust the bounds to use its own collision group first BEFORE changing your Sprites collision group. * * @method Phaser.Physics.P2#updateBoundsCollisionGroup * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. */ updateBoundsCollisionGroup: function (setCollisionGroup) { var mask = this.everythingCollisionGroup.mask; if (typeof setCollisionGroup === 'undefined') { mask = this.boundsCollisionGroup.mask; } if (this.walls.left) { this.walls.left.shapes[0].collisionGroup = mask; } if (this.walls.right) { this.walls.right.shapes[0].collisionGroup = mask; } if (this.walls.top) { this.walls.top.shapes[0].collisionGroup = mask; } if (this.walls.bottom) { this.walls.bottom.shapes[0].collisionGroup = mask; } }, /** * Sets the bounds of the Physics world to match the given world pixel dimensions. * You can optionally set which 'walls' to create: left, right, top or bottom. * * @method Phaser.Physics.P2#setBounds * @param {number} x - The x coordinate of the top-left corner of the bounds. * @param {number} y - The y coordinate of the top-left corner of the bounds. * @param {number} width - The width of the bounds. * @param {number} height - The height of the bounds. * @param {boolean} [left=true] - If true will create the left bounds wall. * @param {boolean} [right=true] - If true will create the right bounds wall. * @param {boolean} [top=true] - If true will create the top bounds wall. * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. */ setBounds: function (x, y, width, height, left, right, top, bottom, setCollisionGroup) { if (typeof left === 'undefined') { left = true; } if (typeof right === 'undefined') { right = true; } if (typeof top === 'undefined') { top = true; } if (typeof bottom === 'undefined') { bottom = true; } if (typeof setCollisionGroup === 'undefined') { setCollisionGroup = true; } if (this.walls.left) { this.world.removeBody(this.walls.left); } if (this.walls.right) { this.world.removeBody(this.walls.right); } if (this.walls.top) { this.world.removeBody(this.walls.top); } if (this.walls.bottom) { this.world.removeBody(this.walls.bottom); } if (left) { this.walls.left = new p2.Body({ mass: 0, position: [ this.pxmi(x), this.pxmi(y) ], angle: 1.5707963267948966 }); this.walls.left.addShape(new p2.Plane()); if (setCollisionGroup) { this.walls.left.shapes[0].collisionGroup = this.boundsCollisionGroup.mask; } this.world.addBody(this.walls.left); } if (right) { this.walls.right = new p2.Body({ mass: 0, position: [ this.pxmi(x + width), this.pxmi(y) ], angle: -1.5707963267948966 }); this.walls.right.addShape(new p2.Plane()); if (setCollisionGroup) { this.walls.right.shapes[0].collisionGroup = this.boundsCollisionGroup.mask; } this.world.addBody(this.walls.right); } if (top) { this.walls.top = new p2.Body({ mass: 0, position: [ this.pxmi(x), this.pxmi(y) ], angle: -3.141592653589793 }); this.walls.top.addShape(new p2.Plane()); if (setCollisionGroup) { this.walls.top.shapes[0].collisionGroup = this.boundsCollisionGroup.mask; } this.world.addBody(this.walls.top); } if (bottom) { this.walls.bottom = new p2.Body({ mass: 0, position: [ this.pxmi(x), this.pxmi(y + height) ] }); this.walls.bottom.addShape(new p2.Plane()); if (setCollisionGroup) { this.walls.bottom.shapes[0].collisionGroup = this.boundsCollisionGroup.mask; } this.world.addBody(this.walls.bottom); } }, /** * Pauses the P2 World independent of the game pause state. * * @method Phaser.Physics.P2#pause */ pause: function() { this.paused = true; }, /** * Resumes a paused P2 World. * * @method Phaser.Physics.P2#resume */ resume: function() { this.paused = false; }, /** * Internal P2 update loop. * * @method Phaser.Physics.P2#update */ update: function () { // Do nothing when the pysics engine was paused before if (this.paused) { return; } if (this.useElapsedTime) { this.world.step(this.game.time.physicsElapsed); } else { this.world.step(this.frameRate); } }, /** * Clears all bodies from the simulation, resets callbacks and resets the collision bitmask. * * @method Phaser.Physics.P2#clear */ clear: function () { this.world.clear(); this.world.off("beginContact", this.beginContactHandler, this); this.world.off("endContact", this.endContactHandler, this); this.postBroadphaseCallback = null; this.callbackContext = null; this.impactCallback = null; this.collisionGroups = []; this._toRemove = []; this._collisionGroupID = 2; this.boundsCollidesWith = []; }, /** * Clears all bodies from the simulation and unlinks World from Game. Should only be called on game shutdown. Call `clear` on a State change. * * @method Phaser.Physics.P2#destroy */ destroy: function () { this.clear(); this.game = null; }, /** * Add a body to the world. * * @method Phaser.Physics.P2#addBody * @param {Phaser.Physics.P2.Body} body - The Body to add to the World. * @return {boolean} True if the Body was added successfully, otherwise false. */ addBody: function (body) { if (body.data.world) { return false; } else { this.world.addBody(body.data); this.onBodyAdded.dispatch(body); return true; } }, /** * Removes a body from the world. This will silently fail if the body wasn't part of the world to begin with. * * @method Phaser.Physics.P2#removeBody * @param {Phaser.Physics.P2.Body} body - The Body to remove from the World. * @return {Phaser.Physics.P2.Body} The Body that was removed. */ removeBody: function (body) { if (body.data.world == this.world) { this.world.removeBody(body.data); this.onBodyRemoved.dispatch(body); } return body; }, /** * Adds a Spring to the world. * * @method Phaser.Physics.P2#addSpring * @param {Phaser.Physics.P2.Spring|p2.LinearSpring|p2.RotationalSpring} spring - The Spring to add to the World. * @return {Phaser.Physics.P2.Spring} The Spring that was added. */ addSpring: function (spring) { if (spring instanceof Phaser.Physics.P2.Spring || spring instanceof Phaser.Physics.P2.RotationalSpring) { this.world.addSpring(spring.data); } else { this.world.addSpring(spring); } this.onSpringAdded.dispatch(spring); return spring; }, /** * Removes a Spring from the world. * * @method Phaser.Physics.P2#removeSpring * @param {Phaser.Physics.P2.Spring} spring - The Spring to remove from the World. * @return {Phaser.Physics.P2.Spring} The Spring that was removed. */ removeSpring: function (spring) { if (spring instanceof Phaser.Physics.P2.Spring || spring instanceof Phaser.Physics.P2.RotationalSpring) { this.world.removeSpring(spring.data); } else { this.world.removeSpring(spring); } this.onSpringRemoved.dispatch(spring); return spring; }, /** * Creates a constraint that tries to keep the distance between two bodies constant. * * @method Phaser.Physics.P2#createDistanceConstraint * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. * @param {number} distance - The distance to keep between the bodies. * @param {Array} [localAnchorA] - The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0]. * @param {Array} [localAnchorB] - The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0]. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. * @return {Phaser.Physics.P2.DistanceConstraint} The constraint */ createDistanceConstraint: function (bodyA, bodyB, distance, localAnchorA, localAnchorB, maxForce) { bodyA = this.getBody(bodyA); bodyB = this.getBody(bodyB); if (!bodyA || !bodyB) { console.warn('Cannot create Constraint, invalid body objects given'); } else { return this.addConstraint(new Phaser.Physics.P2.DistanceConstraint(this, bodyA, bodyB, distance, localAnchorA, localAnchorB, maxForce)); } }, /** * Creates a constraint that tries to keep the distance between two bodies constant. * * @method Phaser.Physics.P2#createGearConstraint * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. * @param {number} [angle=0] - The relative angle * @param {number} [ratio=1] - The gear ratio. * @return {Phaser.Physics.P2.GearConstraint} The constraint */ createGearConstraint: function (bodyA, bodyB, angle, ratio) { bodyA = this.getBody(bodyA); bodyB = this.getBody(bodyB); if (!bodyA || !bodyB) { console.warn('Cannot create Constraint, invalid body objects given'); } else { return this.addConstraint(new Phaser.Physics.P2.GearConstraint(this, bodyA, bodyB, angle, ratio)); } }, /** * Connects two bodies at given offset points, letting them rotate relative to each other around this point. * The pivot points are given in world (pixel) coordinates. * * @method Phaser.Physics.P2#createRevoluteConstraint * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. * @param {Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. * @param {Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies. * @param {Float32Array} [worldPivot=null] - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value. * @return {Phaser.Physics.P2.RevoluteConstraint} The constraint */ createRevoluteConstraint: function (bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) { bodyA = this.getBody(bodyA); bodyB = this.getBody(bodyB); if (!bodyA || !bodyB) { console.warn('Cannot create Constraint, invalid body objects given'); } else { return this.addConstraint(new Phaser.Physics.P2.RevoluteConstraint(this, bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot)); } }, /** * Locks the relative position between two bodies. * * @method Phaser.Physics.P2#createLockConstraint * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. * @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {number} [angle=0] - The angle of bodyB in bodyA's frame. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. * @return {Phaser.Physics.P2.LockConstraint} The constraint */ createLockConstraint: function (bodyA, bodyB, offset, angle, maxForce) { bodyA = this.getBody(bodyA); bodyB = this.getBody(bodyB); if (!bodyA || !bodyB) { console.warn('Cannot create Constraint, invalid body objects given'); } else { return this.addConstraint(new Phaser.Physics.P2.LockConstraint(this, bodyA, bodyB, offset, angle, maxForce)); } }, /** * Constraint that only allows bodies to move along a line, relative to each other. * See http://www.iforce2d.net/b2dtut/joints-prismatic * * @method Phaser.Physics.P2#createPrismaticConstraint * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. * @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point. * @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. * @return {Phaser.Physics.P2.PrismaticConstraint} The constraint */ createPrismaticConstraint: function (bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce) { bodyA = this.getBody(bodyA); bodyB = this.getBody(bodyB); if (!bodyA || !bodyB) { console.warn('Cannot create Constraint, invalid body objects given'); } else { return this.addConstraint(new Phaser.Physics.P2.PrismaticConstraint(this, bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce)); } }, /** * Adds a Constraint to the world. * * @method Phaser.Physics.P2#addConstraint * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to add to the World. * @return {Phaser.Physics.P2.Constraint} The Constraint that was added. */ addConstraint: function (constraint) { this.world.addConstraint(constraint); this.onConstraintAdded.dispatch(constraint); return constraint; }, /** * Removes a Constraint from the world. * * @method Phaser.Physics.P2#removeConstraint * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to be removed from the World. * @return {Phaser.Physics.P2.Constraint} The Constraint that was removed. */ removeConstraint: function (constraint) { this.world.removeConstraint(constraint); this.onConstraintRemoved.dispatch(constraint); return constraint; }, /** * Adds a Contact Material to the world. * * @method Phaser.Physics.P2#addContactMaterial * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be added to the World. * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was added. */ addContactMaterial: function (material) { this.world.addContactMaterial(material); this.onContactMaterialAdded.dispatch(material); return material; }, /** * Removes a Contact Material from the world. * * @method Phaser.Physics.P2#removeContactMaterial * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be removed from the World. * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was removed. */ removeContactMaterial: function (material) { this.world.removeContactMaterial(material); this.onContactMaterialRemoved.dispatch(material); return material; }, /** * Gets a Contact Material based on the two given Materials. * * @method Phaser.Physics.P2#getContactMaterial * @param {Phaser.Physics.P2.Material} materialA - The first Material to search for. * @param {Phaser.Physics.P2.Material} materialB - The second Material to search for. * @return {Phaser.Physics.P2.ContactMaterial|boolean} The Contact Material or false if none was found matching the Materials given. */ getContactMaterial: function (materialA, materialB) { return this.world.getContactMaterial(materialA, materialB); }, /** * Sets the given Material against all Shapes owned by all the Bodies in the given array. * * @method Phaser.Physics.P2#setMaterial * @param {Phaser.Physics.P2.Material} material - The Material to be applied to the given Bodies. * @param {array<Phaser.Physics.P2.Body>} bodies - An Array of Body objects that the given Material will be set on. */ setMaterial: function (material, bodies) { var i = bodies.length; while (i--) { bodies[i].setMaterial(material); } }, /** * Creates a Material. Materials are applied to Shapes owned by a Body and can be set with Body.setMaterial(). * Materials are a way to control what happens when Shapes collide. Combine unique Materials together to create Contact Materials. * Contact Materials have properties such as friction and restitution that allow for fine-grained collision control between different Materials. * * @method Phaser.Physics.P2#createMaterial * @param {string} [name] - Optional name of the Material. Each Material has a unique ID but string names are handy for debugging. * @param {Phaser.Physics.P2.Body} [body] - Optional Body. If given it will assign the newly created Material to the Body shapes. * @return {Phaser.Physics.P2.Material} The Material that was created. This is also stored in Phaser.Physics.P2.materials. */ createMaterial: function (name, body) { name = name || ''; var material = new Phaser.Physics.P2.Material(name); this.materials.push(material); if (typeof body !== 'undefined') { body.setMaterial(material); } return material; }, /** * Creates a Contact Material from the two given Materials. You can then edit the properties of the Contact Material directly. * * @method Phaser.Physics.P2#createContactMaterial * @param {Phaser.Physics.P2.Material} [materialA] - The first Material to create the ContactMaterial from. If undefined it will create a new Material object first. * @param {Phaser.Physics.P2.Material} [materialB] - The second Material to create the ContactMaterial from. If undefined it will create a new Material object first. * @param {object} [options] - Material options object. * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was created. */ createContactMaterial: function (materialA, materialB, options) { if (typeof materialA === 'undefined') { materialA = this.createMaterial(); } if (typeof materialB === 'undefined') { materialB = this.createMaterial(); } var contact = new Phaser.Physics.P2.ContactMaterial(materialA, materialB, options); return this.addContactMaterial(contact); }, /** * Populates and returns an array with references to of all current Bodies in the world. * * @method Phaser.Physics.P2#getBodies * @return {array<Phaser.Physics.P2.Body>} An array containing all current Bodies in the world. */ getBodies: function () { var output = []; var i = this.world.bodies.length; while (i--) { output.push(this.world.bodies[i].parent); } return output; }, /** * Checks the given object to see if it has a p2.Body and if so returns it. * * @method Phaser.Physics.P2#getBody * @param {object} object - The object to check for a p2.Body on. * @return {p2.Body} The p2.Body, or null if not found. */ getBody: function (object) { if (object instanceof p2.Body) { // Native p2 body return object; } else if (object instanceof Phaser.Physics.P2.Body) { // Phaser P2 Body return object.data; } else if (object['body'] && object['body'].type === Phaser.Physics.P2JS) { // Sprite, TileSprite, etc return object.body.data; } return null; }, /** * Populates and returns an array of all current Springs in the world. * * @method Phaser.Physics.P2#getSprings * @return {array<Phaser.Physics.P2.Spring>} An array containing all current Springs in the world. */ getSprings: function () { var output = []; var i = this.world.springs.length; while (i--) { output.push(this.world.springs[i].parent); } return output; }, /** * Populates and returns an array of all current Constraints in the world. * * @method Phaser.Physics.P2#getConstraints * @return {array<Phaser.Physics.P2.Constraint>} An array containing all current Constraints in the world. */ getConstraints: function () { var output = []; var i = this.world.constraints.length; while (i--) { output.push(this.world.constraints[i].parent); } return output; }, /** * Test if a world point overlaps bodies. You will get an array of actual P2 bodies back. You can find out which Sprite a Body belongs to * (if any) by checking the Body.parent.sprite property. Body.parent is a Phaser.Physics.P2.Body property. * * @method Phaser.Physics.P2#hitTest * @param {Phaser.Point} worldPoint - Point to use for intersection tests. The points values must be in world (pixel) coordinates. * @param {Array<Phaser.Physics.P2.Body|Phaser.Sprite|p2.Body>} [bodies] - A list of objects to check for intersection. If not given it will check Phaser.Physics.P2.world.bodies (i.e. all world bodies) * @param {number} [precision=5] - Used for matching against particles and lines. Adds some margin to these infinitesimal objects. * @param {boolean} [filterStatic=false] - If true all Static objects will be removed from the results array. * @return {Array} Array of bodies that overlap the point. */ hitTest: function (worldPoint, bodies, precision, filterStatic) { if (typeof bodies === 'undefined') { bodies = this.world.bodies; } if (typeof precision === 'undefined') { precision = 5; } if (typeof filterStatic === 'undefined') { filterStatic = false; } var physicsPosition = [ this.pxmi(worldPoint.x), this.pxmi(worldPoint.y) ]; var query = []; var i = bodies.length; while (i--) { if (bodies[i] instanceof Phaser.Physics.P2.Body && !(filterStatic && bodies[i].data.type === p2.Body.STATIC)) { query.push(bodies[i].data); } else if (bodies[i] instanceof p2.Body && bodies[i].parent && !(filterStatic && bodies[i].type === p2.Body.STATIC)) { query.push(bodies[i]); } else if (bodies[i] instanceof Phaser.Sprite && bodies[i].hasOwnProperty('body') && !(filterStatic && bodies[i].body.data.type === p2.Body.STATIC)) { query.push(bodies[i].body.data); } } return this.world.hitTest(physicsPosition, query, precision); }, /** * Converts the current world into a JSON object. * * @method Phaser.Physics.P2#toJSON * @return {object} A JSON representation of the world. */ toJSON: function () { return this.world.toJSON(); }, /** * Creates a new Collision Group and optionally applies it to the given object. * Collision Groups are handled using bitmasks, therefore you have a fixed limit you can create before you need to re-use older groups. * * @method Phaser.Physics.P2#createCollisionGroup * @param {Phaser.Group|Phaser.Sprite} [object] - An optional Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children. */ createCollisionGroup: function (object) { var bitmask = Math.pow(2, this._collisionGroupID); if (this.walls.left) { this.walls.left.shapes[0].collisionMask = this.walls.left.shapes[0].collisionMask | bitmask; } if (this.walls.right) { this.walls.right.shapes[0].collisionMask = this.walls.right.shapes[0].collisionMask | bitmask; } if (this.walls.top) { this.walls.top.shapes[0].collisionMask = this.walls.top.shapes[0].collisionMask | bitmask; } if (this.walls.bottom) { this.walls.bottom.shapes[0].collisionMask = this.walls.bottom.shapes[0].collisionMask | bitmask; } this._collisionGroupID++; var group = new Phaser.Physics.P2.CollisionGroup(bitmask); this.collisionGroups.push(group); if (object) { this.setCollisionGroup(object, group); } return group; }, /** * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified. * Note that this resets the collisionMask and any previously set groups. See Body.collides() for appending them. * * @method Phaser.Physics.P2y#setCollisionGroup * @param {Phaser.Group|Phaser.Sprite} object - A Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children. * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use. */ setCollisionGroup: function (object, group) { if (object instanceof Phaser.Group) { for (var i = 0; i < object.total; i++) { if (object.children[i]['body'] && object.children[i]['body'].type === Phaser.Physics.P2JS) { object.children[i].body.setCollisionGroup(group); } } } else { object.body.setCollisionGroup(group); } }, /** * Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. * * @method Phaser.Physics.P2#createSpring * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. * @param {number} [restLength=1] - Rest length of the spring. A number > 0. * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. * @param {number} [damping=1] - Damping of the spring. A number >= 0. * @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. * @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. * @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. * @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. * @return {Phaser.Physics.P2.Spring} The spring */ createSpring: function (bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) { bodyA = this.getBody(bodyA); bodyB = this.getBody(bodyB); if (!bodyA || !bodyB) { console.warn('Cannot create Spring, invalid body objects given'); } else { return this.addSpring(new Phaser.Physics.P2.Spring(this, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB)); } }, /** * Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. * * @method Phaser.Physics.P2#createRotationalSpring * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. * @param {number} [restAngle] - The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies. * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. * @param {number} [damping=1] - Damping of the spring. A number >= 0. * @return {Phaser.Physics.P2.RotationalSpring} The spring */ createRotationalSpring: function (bodyA, bodyB, restAngle, stiffness, damping) { bodyA = this.getBody(bodyA); bodyB = this.getBody(bodyB); if (!bodyA || !bodyB) { console.warn('Cannot create Rotational Spring, invalid body objects given'); } else { return this.addSpring(new Phaser.Physics.P2.RotationalSpring(this, bodyA, bodyB, restAngle, stiffness, damping)); } }, /** * Creates a new Body and adds it to the World. * * @method Phaser.Physics.P2#createBody * @param {number} x - The x coordinate of Body. * @param {number} y - The y coordinate of Body. * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created. * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction). * @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 {Phaser.Physics.P2.Body} The body */ createBody: function (x, y, mass, addToWorld, options, data) { if (typeof addToWorld === 'undefined') { addToWorld = false; } var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass); if (data) { var result = body.addPolygon(options, data); if (!result) { return false; } } if (addToWorld) { this.world.addBody(body.data); } return body; }, /** * Creates a new Particle and adds it to the World. * * @method Phaser.Physics.P2#createParticle * @param {number} x - The x coordinate of Body. * @param {number} y - The y coordinate of Body. * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created. * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction). * @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. */ createParticle: function (x, y, mass, addToWorld, options, data) { if (typeof addToWorld === 'undefined') { addToWorld = false; } var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass); if (data) { var result = body.addPolygon(options, data); if (!result) { return false; } } if (addToWorld) { this.world.addBody(body.data); } return body; }, /** * Converts all of the polylines objects inside a Tiled ObjectGroup into physics bodies that are added to the world. * Note that the polylines must be created in such a way that they can withstand polygon decomposition. * * @method Phaser.Physics.P2#convertCollisionObjects * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world. * @return {array} An array of the Phaser.Physics.Body objects that have been created. */ convertCollisionObjects: function (map, layer, addToWorld) { if (typeof addToWorld === 'undefined') { addToWorld = true; } var output = []; for (var i = 0, len = map.collision[layer].length; i < len; i++) { // name: json.layers[i].objects[v].name, // x: json.layers[i].objects[v].x, // y: json.layers[i].objects[v].y, // width: json.layers[i].objects[v].width, // height: json.layers[i].objects[v].height, // visible: json.layers[i].objects[v].visible, // properties: json.layers[i].objects[v].properties, // polyline: json.layers[i].objects[v].polyline var object = map.collision[layer][i]; var body = this.createBody(object.x, object.y, 0, addToWorld, {}, object.polyline); if (body) { output.push(body); } } return output; }, /** * Clears all physics bodies from the given TilemapLayer that were created with `World.convertTilemap`. * * @method Phaser.Physics.P2#clearTilemapLayerBodies * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. */ clearTilemapLayerBodies: function (map, layer) { layer = map.getLayer(layer); var i = map.layers[layer].bodies.length; while (i--) { map.layers[layer].bodies[i].destroy(); } map.layers[layer].bodies.length = 0; }, /** * Goes through all tiles in the given Tilemap and TilemapLayer and converts those set to collide into physics bodies. * Only call this *after* you have specified all of the tiles you wish to collide with calls like Tilemap.setCollisionBetween, etc. * Every time you call this method it will destroy any previously created bodies and remove them from the world. * Therefore understand it's a very expensive operation and not to be done in a core game update loop. * * @method Phaser.Physics.P2#convertTilemap * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world, otherwise it's up to you to do so. * @param {boolean} [optimize=true] - If true adjacent colliding tiles will be combined into a single body to save processing. However it means you cannot perform specific Tile to Body collision responses. * @return {array} An array of the Phaser.Physics.P2.Body objects that were created. */ convertTilemap: function (map, layer, addToWorld, optimize) { layer = map.getLayer(layer); if (typeof addToWorld === 'undefined') { addToWorld = true; } if (typeof optimize === 'undefined') { optimize = true; } // If the bodies array is already populated we need to nuke it this.clearTilemapLayerBodies(map, layer); var width = 0; var sx = 0; var sy = 0; for (var y = 0, h = map.layers[layer].height; y < h; y++) { width = 0; for (var x = 0, w = map.layers[layer].width; x < w; x++) { var tile = map.layers[layer].data[y][x]; if (tile && tile.index > -1 && tile.collides) { if (optimize) { var right = map.getTileRight(layer, x, y); if (width === 0) { sx = tile.x * tile.width; sy = tile.y * tile.height; width = tile.width; } if (right && right.collides) { width += tile.width; } else { var body = this.createBody(sx, sy, 0, false); body.addRectangle(width, tile.height, width / 2, tile.height / 2, 0); if (addToWorld) { this.addBody(body); } map.layers[layer].bodies.push(body); width = 0; } } else { var body = this.createBody(tile.x * tile.width, tile.y * tile.height, 0, false); body.addRectangle(tile.width, tile.height, tile.width / 2, tile.height / 2, 0); if (addToWorld) { this.addBody(body); } map.layers[layer].bodies.push(body); } } } } return map.layers[layer].bodies; }, /** * Convert p2 physics value (meters) to pixel scale. * By default Phaser uses a scale of 20px per meter. * If you need to modify this you can over-ride these functions via the Physics Configuration object. * * @method Phaser.Physics.P2#mpx * @param {number} v - The value to convert. * @return {number} The scaled value. */ mpx: function (v) { return v *= 20; }, /** * Convert pixel value to p2 physics scale (meters). * By default Phaser uses a scale of 20px per meter. * If you need to modify this you can over-ride these functions via the Physics Configuration object. * * @method Phaser.Physics.P2#pxm * @param {number} v - The value to convert. * @return {number} The scaled value. */ pxm: function (v) { return v * 0.05; }, /** * Convert p2 physics value (meters) to pixel scale and inverses it. * By default Phaser uses a scale of 20px per meter. * If you need to modify this you can over-ride these functions via the Physics Configuration object. * * @method Phaser.Physics.P2#mpxi * @param {number} v - The value to convert. * @return {number} The scaled value. */ mpxi: function (v) { return v *= -20; }, /** * Convert pixel value to p2 physics scale (meters) and inverses it. * By default Phaser uses a scale of 20px per meter. * If you need to modify this you can over-ride these functions via the Physics Configuration object. * * @method Phaser.Physics.P2#pxmi * @param {number} v - The value to convert. * @return {number} The scaled value. */ pxmi: function (v) { return v * -0.05; } }; /** * @name Phaser.Physics.P2#friction * @property {number} friction - Friction between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair. */ Object.defineProperty(Phaser.Physics.P2.prototype, "friction", { get: function () { return this.world.defaultContactMaterial.friction; }, set: function (value) { this.world.defaultContactMaterial.friction = value; } }); /** * @name Phaser.Physics.P2#restitution * @property {number} restitution - Default coefficient of restitution between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair. */ Object.defineProperty(Phaser.Physics.P2.prototype, "restitution", { get: function () { return this.world.defaultContactMaterial.restitution; }, set: function (value) { this.world.defaultContactMaterial.restitution = value; } }); /** * @name Phaser.Physics.P2#contactMaterial * @property {p2.ContactMaterial} contactMaterial - The default Contact Material being used by the World. */ Object.defineProperty(Phaser.Physics.P2.prototype, "contactMaterial", { get: function () { return this.world.defaultContactMaterial; }, set: function (value) { this.world.defaultContactMaterial = value; } }); /** * @name Phaser.Physics.P2#applySpringForces * @property {boolean} applySpringForces - Enable to automatically apply spring forces each step. */ Object.defineProperty(Phaser.Physics.P2.prototype, "applySpringForces", { get: function () { return this.world.applySpringForces; }, set: function (value) { this.world.applySpringForces = value; } }); /** * @name Phaser.Physics.P2#applyDamping * @property {boolean} applyDamping - Enable to automatically apply body damping each step. */ Object.defineProperty(Phaser.Physics.P2.prototype, "applyDamping", { get: function () { return this.world.applyDamping; }, set: function (value) { this.world.applyDamping = value; } }); /** * @name Phaser.Physics.P2#applyGravity * @property {boolean} applyGravity - Enable to automatically apply gravity each step. */ Object.defineProperty(Phaser.Physics.P2.prototype, "applyGravity", { get: function () { return this.world.applyGravity; }, set: function (value) { this.world.applyGravity = value; } }); /** * @name Phaser.Physics.P2#solveConstraints * @property {boolean} solveConstraints - Enable/disable constraint solving in each step. */ Object.defineProperty(Phaser.Physics.P2.prototype, "solveConstraints", { get: function () { return this.world.solveConstraints; }, set: function (value) { this.world.solveConstraints = value; } }); /** * @name Phaser.Physics.P2#time * @property {boolean} time - The World time. * @readonly */ Object.defineProperty(Phaser.Physics.P2.prototype, "time", { get: function () { return this.world.time; } }); /** * @name Phaser.Physics.P2#emitImpactEvent * @property {boolean} emitImpactEvent - Set to true if you want to the world to emit the "impact" event. Turning this off could improve performance. */ Object.defineProperty(Phaser.Physics.P2.prototype, "emitImpactEvent", { get: function () { return this.world.emitImpactEvent; }, set: function (value) { this.world.emitImpactEvent = value; } }); /** * How to deactivate bodies during simulation. Possible modes are: World.NO_SLEEPING, World.BODY_SLEEPING and World.ISLAND_SLEEPING. * If sleeping is enabled, you might need to wake up the bodies if they fall asleep when they shouldn't. If you want to enable sleeping in the world, but want to disable it for a particular body, see Body.allowSleep. * @name Phaser.Physics.P2#sleepMode * @property {number} sleepMode */ Object.defineProperty(Phaser.Physics.P2.prototype, "sleepMode", { get: function () { return this.world.sleepMode; }, set: function (value) { this.world.sleepMode = value; } }); /** * @name Phaser.Physics.P2#total * @property {number} total - The total number of bodies in the world. * @readonly */ Object.defineProperty(Phaser.Physics.P2.prototype, "total", { get: function () { return this.world.bodies.length; } });
module.exports={A:{A:{"1":"E B A","2":"J C G VB"},B:{"1":"D Y g H L"},C:{"1":"0 1 3 4 5 6 F I J C G E B A D Y g H L M N O P Q R S T U V W X v Z a b c d e f K h i j k l m n o p q r s x y u t","2":"TB z RB QB"},D:{"1":"0 1 3 4 5 6 X v Z a b c d e f K h i j k l m n o p q r s x y u t FB AB CB UB DB","132":"F I J C G E B A D Y g H L M N O P Q R S T U V W"},E:{"1":"E B A JB KB LB","2":"EB","4":"9","132":"F I J C G GB HB IB"},F:{"1":"7 8 E A D H L M N O P Q R S T U V W X v Z a b c d e f K h i j k l m n o p q r s MB NB OB PB SB w"},G:{"1":"A aB bB cB dB","132":"2 9 G BB WB XB YB ZB"},H:{"1":"eB"},I:{"1":"t jB kB","2":"fB gB hB","132":"2 z F iB"},J:{"1":"C B"},K:{"1":"7 8 B A D K w"},L:{"1":"AB"},M:{"1":"u"},N:{"1":"B A"},O:{"1":"lB"},P:{"1":"F I"},Q:{"1":"mB"},R:{"1":"nB"}},B:1,C:"SVG in HTML img element"};
goog.require('ol.Attribution'); goog.require('ol.Map'); goog.require('ol.View'); goog.require('ol.control'); goog.require('ol.extent'); goog.require('ol.layer.Tile'); goog.require('ol.proj'); goog.require('ol.source.WMTS'); goog.require('ol.tilegrid.WMTS'); var map = new ol.Map({ target: 'map', controls: ol.control.defaults({ attributionOptions: /** @type {olx.control.AttributionOptions} */ ({ collapsible: false }) }), view: new ol.View({ zoom: 5, center: ol.proj.transform([5, 45], 'EPSG:4326', 'EPSG:3857') }) }); var resolutions = []; var matrixIds = []; var proj3857 = ol.proj.get('EPSG:3857'); var maxResolution = ol.extent.getWidth(proj3857.getExtent()) / 256; for (var i = 0; i < 18; i++) { matrixIds[i] = i.toString(); resolutions[i] = maxResolution / Math.pow(2, i); } var tileGrid = new ol.tilegrid.WMTS({ origin: [-20037508, 20037508], resolutions: resolutions, matrixIds: matrixIds }); // API key valid for 'openlayers.org' and 'localhost'. // Expiration date is 06/29/2018. var key = '2mqbg0z6cx7ube8gsou10nrt'; var ign_source = new ol.source.WMTS({ url: 'https://wxs.ign.fr/' + key + '/wmts', layer: 'GEOGRAPHICALGRIDSYSTEMS.MAPS', matrixSet: 'PM', format: 'image/jpeg', projection: 'EPSG:3857', tileGrid: tileGrid, style: 'normal', attributions: [new ol.Attribution({ html: '<a href="http://www.geoportail.fr/" target="_blank">' + '<img src="https://api.ign.fr/geoportail/api/js/latest/' + 'theme/geoportal/img/logo_gp.gif"></a>' })] }); var ign = new ol.layer.Tile({ source: ign_source }); map.addLayer(ign);
/*! * @atlassian/aui - Atlassian User Interface Framework * @version v7.5.0-rc-3 * @link https://docs.atlassian.com/aui/latest/ * @license SEE LICENSE IN LICENSE.md * @author Atlassian Pty Ltd. */ // src/js/aui/header-async.js (typeof window === 'undefined' ? global : window).__2099962405af1a8893c5b00b1120bf59 = (function () { var module = { exports: {} }; var exports = module.exports; 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createHeader = __fb3fd0e488fb6e56f8392c8bc7434da4; var _createHeader2 = _interopRequireDefault(_createHeader); var _skate = __bb6ec7268c91759bbe10bd46d924551e; var _skate2 = _interopRequireDefault(_skate); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Header = (0, _skate2.default)('aui-header', { type: _skate2.default.type.CLASSNAME, created: function created(element) { (0, _createHeader2.default)(element); } }); exports.default = Header; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui-header-async.js (typeof window === 'undefined' ? global : window).__d1bf2850f98e3b981a4cc4cffe7c22fd = (function () { var module = { exports: {} }; var exports = module.exports; 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); __2099962405af1a8893c5b00b1120bf59; exports.default = window.AJS; module.exports = exports['default']; return module.exports; }).call(this);
(function (window) { 'use strict'; var patternfly = { version: "3.37.0" }; // definition of breakpoint sizes for tablet and desktop modes patternfly.pfBreakpoints = { 'tablet': 768, 'desktop': 1200 }; window.patternfly = patternfly; })(window);
'use strict'; // Refs: https://github.com/nodejs/node/issues/548 require('../common'); const assert = require('assert'); const vm = require('vm'); const context = vm.createContext(); vm.runInContext('function test() { return 0; }', context); vm.runInContext('function test() { return 1; }', context); const result = vm.runInContext('test()', context); assert.strictEqual(result, 1);
// Create namespaces // window.ionic = { controllers: {}, views: {}, version: '<%= pkg.version %>' };
// Generated by CoffeeScript 1.7.1 var DEFAULT_ENCODING, MAX, MONEY_DIVISOR, NULL, PLP_NULL, THREE_AND_A_THIRD, UNKNOWN_PLP_LEN, guidParser, iconv, parse, readBinary, readChars, readDate, readDateTime, readDateTime2, readDateTimeOffset, readMax, readMaxBinary, readMaxChars, readMaxNChars, readNChars, readSmallDateTime, readTime, sprintf; iconv = require('iconv-lite'); sprintf = require('sprintf').sprintf; guidParser = require('./guid-parser'); require('./buffertools'); NULL = (1 << 16) - 1; MAX = (1 << 16) - 1; THREE_AND_A_THIRD = 3 + (1 / 3); MONEY_DIVISOR = 10000; PLP_NULL = new Buffer([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]); UNKNOWN_PLP_LEN = new Buffer([0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]); DEFAULT_ENCODING = 'utf8'; parse = function(buffer, metaData, options) { var codepage, dataLength, high, low, sign, textPointerLength, textPointerNull, type, value; value = void 0; dataLength = void 0; textPointerNull = void 0; type = metaData.type; if (type.hasTextPointerAndTimestamp) { textPointerLength = buffer.readUInt8(); if (textPointerLength !== 0) { buffer.readBuffer(textPointerLength); buffer.readBuffer(8); } else { dataLength = 0; textPointerNull = true; } } if (!dataLength && dataLength !== 0) { switch (type.id & 0x30) { case 0x10: dataLength = 0; break; case 0x20: if (metaData.dataLength !== MAX) { switch (type.dataLengthLength) { case 0: dataLength = void 0; break; case 1: dataLength = buffer.readUInt8(); break; case 2: dataLength = buffer.readUInt16LE(); break; case 4: dataLength = buffer.readUInt32LE(); break; default: throw Error("Unsupported dataLengthLength " + type.dataLengthLength + " for data type " + type.name); } } break; case 0x30: dataLength = 1 << ((type.id & 0x0C) >> 2); } } switch (type.name) { case 'Null': value = null; break; case 'TinyInt': value = buffer.readUInt8(); break; case 'Int': value = buffer.readInt32LE(); break; case 'SmallInt': value = buffer.readInt16LE(); break; case 'BigInt': value = buffer.readAsStringInt64LE(); break; case 'IntN': switch (dataLength) { case 0: value = null; break; case 1: value = buffer.readUInt8(); break; case 2: value = buffer.readInt16LE(); break; case 4: value = buffer.readInt32LE(); break; case 8: value = buffer.readAsStringInt64LE(); break; default: throw new Error("Unsupported dataLength " + dataLength + " for IntN"); } break; case 'Real': value = buffer.readFloatLE(); break; case 'Float': value = buffer.readDoubleLE(); break; case 'FloatN': switch (dataLength) { case 0: value = null; break; case 4: value = buffer.readFloatLE(); break; case 8: value = buffer.readDoubleLE(); break; default: throw new Error("Unsupported dataLength " + dataLength + " for FloatN"); } break; case 'Money': case 'SmallMoney': case 'MoneyN': switch (dataLength) { case 0: value = null; break; case 4: value = buffer.readInt32LE() / MONEY_DIVISOR; break; case 8: high = buffer.readInt32LE(); low = buffer.readUInt32LE(); value = low + (0x100000000 * high); value /= MONEY_DIVISOR; break; default: throw new Error("Unsupported dataLength " + dataLength + " for MoneyN"); } break; case 'Bit': value = !!buffer.readUInt8(); break; case 'BitN': switch (dataLength) { case 0: value = null; break; case 1: value = !!buffer.readUInt8(); } break; case 'VarChar': case 'Char': codepage = metaData.collation.codepage; if (metaData.dataLength === MAX) { value = readMaxChars(buffer, codepage); } else { value = readChars(buffer, dataLength, codepage); } break; case 'NVarChar': case 'NChar': if (metaData.dataLength === MAX) { value = readMaxNChars(buffer); } else { value = readNChars(buffer, dataLength); } break; case 'VarBinary': case 'Binary': if (metaData.dataLength === MAX) { value = readMaxBinary(buffer); } else { value = readBinary(buffer, dataLength); } break; case 'Text': if (textPointerNull) { value = null; } else { value = readChars(buffer, dataLength, metaData.collation.codepage); } break; case 'NText': if (textPointerNull) { value = null; } else { value = readNChars(buffer, dataLength); } break; case 'Image': if (textPointerNull) { value = null; } else { value = readBinary(buffer, dataLength); } break; case 'Xml': value = readMaxNChars(buffer); break; case 'SmallDateTime': value = readSmallDateTime(buffer, options.useUTC); break; case 'DateTime': value = readDateTime(buffer, options.useUTC); break; case 'DateTimeN': switch (dataLength) { case 0: value = null; break; case 4: value = readSmallDateTime(buffer, options.useUTC); break; case 8: value = readDateTime(buffer, options.useUTC); } break; case 'TimeN': if ((dataLength = buffer.readUInt8()) === 0) { value = null; } else { value = readTime(buffer, dataLength, metaData.scale); } break; case 'DateN': if ((dataLength = buffer.readUInt8()) === 0) { value = null; } else { value = readDate(buffer); } break; case 'DateTime2N': if ((dataLength = buffer.readUInt8()) === 0) { value = null; } else { value = readDateTime2(buffer, dataLength, metaData.scale); } break; case 'DateTimeOffsetN': if ((dataLength = buffer.readUInt8()) === 0) { value = null; } else { value = readDateTimeOffset(buffer, dataLength, metaData.scale); } break; case 'NumericN': case 'DecimalN': if (dataLength === 0) { value = null; } else { sign = buffer.readUInt8() === 1 ? 1 : -1; switch (dataLength - 1) { case 4: value = buffer.readUInt32LE(); break; case 8: value = buffer.readUNumeric64LE(); break; case 12: value = buffer.readUNumeric96LE(); break; case 16: value = buffer.readUNumeric128LE(); break; default: throw new Error(sprintf('Unsupported numeric size %d at offset 0x%04X', dataLength - 1, buffer.position)); break; } value *= sign; value /= Math.pow(10, metaData.scale); } break; case 'UniqueIdentifierN': switch (dataLength) { case 0: value = null; break; case 0x10: value = guidParser.arrayToGuid(buffer.readArray(0x10)); break; default: throw new Error(sprintf('Unsupported guid size %d at offset 0x%04X', dataLength - 1, buffer.position)); } break; case 'UDT': value = readMaxBinary(buffer); break; default: throw new Error(sprintf('Unrecognised type %s at offset 0x%04X', type.name, buffer.position)); break; } return value; }; readBinary = function(buffer, dataLength) { if (dataLength === NULL) { return null; } else { return buffer.readBuffer(dataLength); } }; readChars = function(buffer, dataLength, codepage) { if (codepage == null) { codepage = DEFAULT_ENCODING; } if (dataLength === NULL) { return null; } else { return iconv.decode(buffer.readBuffer(dataLength), codepage); } }; readNChars = function(buffer, dataLength) { if (dataLength === NULL) { return null; } else { return buffer.readString(dataLength, 'ucs2'); } }; readMaxBinary = function(buffer) { return readMax(buffer, function(valueBuffer) { return valueBuffer; }); }; readMaxChars = function(buffer, codepage) { if (codepage == null) { codepage = DEFAULT_ENCODING; } return readMax(buffer, function(valueBuffer) { return iconv.decode(valueBuffer, codepage); }); }; readMaxNChars = function(buffer) { return readMax(buffer, function(valueBuffer) { return valueBuffer.toString('ucs2'); }); }; readMax = function(buffer, decodeFunction) { var chunk, chunkLength, chunks, expectedLength, length, position, type, valueBuffer, _i, _len; type = buffer.readBuffer(8); if (type.equals(PLP_NULL)) { return null; } else { if (type.equals(UNKNOWN_PLP_LEN)) { expectedLength = void 0; } else { buffer.rollback(); expectedLength = buffer.readUInt64LE(); } length = 0; chunks = []; chunkLength = buffer.readUInt32LE(); while (chunkLength !== 0) { length += chunkLength; chunks.push(buffer.readBuffer(chunkLength)); chunkLength = buffer.readUInt32LE(); } if (expectedLength) { if (length !== expectedLength) { throw new Error("Partially Length-prefixed Bytes unmatched lengths : expected " + expectedLength + ", but got " + length + " bytes"); } } valueBuffer = new Buffer(length); position = 0; for (_i = 0, _len = chunks.length; _i < _len; _i++) { chunk = chunks[_i]; chunk.copy(valueBuffer, position, 0); position += chunk.length; } return decodeFunction(valueBuffer); } }; readSmallDateTime = function(buffer, useUTC) { var days, minutes, value; days = buffer.readUInt16LE(); minutes = buffer.readUInt16LE(); if (useUTC) { value = new Date(Date.UTC(1900, 0, 1)); value.setUTCDate(value.getUTCDate() + days); value.setUTCMinutes(value.getUTCMinutes() + minutes); } else { value = new Date(1900, 0, 1); value.setDate(value.getDate() + days); value.setMinutes(value.getMinutes() + minutes); } return value; }; readDateTime = function(buffer, useUTC) { var days, milliseconds, threeHundredthsOfSecond, value; days = buffer.readInt32LE(); threeHundredthsOfSecond = buffer.readUInt32LE(); milliseconds = threeHundredthsOfSecond * THREE_AND_A_THIRD; if (useUTC) { value = new Date(Date.UTC(1900, 0, 1)); value.setUTCDate(value.getUTCDate() + days); value.setUTCMilliseconds(value.getUTCMilliseconds() + milliseconds); } else { value = new Date(1900, 0, 1); value.setDate(value.getDate() + days); value.setMilliseconds(value.getMilliseconds() + milliseconds); } return value; }; readTime = function(buffer, dataLength, scale) { var date, i, value, _i, _ref; switch (dataLength) { case 3: value = buffer.readUInt24LE(); break; case 4: value = buffer.readUInt32LE(); break; case 5: value = buffer.readUInt40LE(); } if (scale < 7) { for (i = _i = _ref = scale + 1; _ref <= 7 ? _i <= 7 : _i >= 7; i = _ref <= 7 ? ++_i : --_i) { value *= 10; } } date = new Date(Date.UTC(1970, 0, 1, 0, 0, 0, value / 10000)); Object.defineProperty(date, "nanosecondsDelta", { enumerable: false, value: (value % 10000) / Math.pow(10, 7) }); return date; }; readDate = function(buffer) { var days; days = buffer.readUInt24LE(); return new Date(Date.UTC(2000, 0, days - 730118)); }; readDateTime2 = function(buffer, dataLength, scale) { var date, days, time; time = readTime(buffer, dataLength - 3, scale); days = buffer.readUInt24LE(); date = new Date(Date.UTC(2000, 0, days - 730118, 0, 0, 0, +time)); Object.defineProperty(date, "nanosecondsDelta", { enumerable: false, value: time.nanosecondsDelta }); return date; }; readDateTimeOffset = function(buffer, dataLength, scale) { var date, days, offset, time; time = readTime(buffer, dataLength - 5, scale); days = buffer.readUInt24LE(); offset = buffer.readInt16LE(); date = new Date(Date.UTC(2000, 0, days - 730118, 0, 0, 0, +time)); Object.defineProperty(date, "nanosecondsDelta", { enumerable: false, value: time.nanosecondsDelta }); return date; }; module.exports = parse;
'use strict'; const EventEmitter = require('events'); const shared = require('../shared'); const mimeTypes = require('../mime-funcs/mime-types'); const MailComposer = require('../mail-composer'); const DKIM = require('../dkim'); const httpProxyClient = require('../smtp-connection/http-proxy-client'); const util = require('util'); const urllib = require('url'); const packageData = require('../../package.json'); const MailMessage = require('./mail-message'); const net = require('net'); const dns = require('dns'); const crypto = require('crypto'); /** * Creates an object for exposing the Mail API * * @constructor * @param {Object} transporter Transport object instance to pass the mails to */ class Mail extends EventEmitter { constructor(transporter, options, defaults) { super(); this.options = options || {}; this._defaults = defaults || {}; this._defaultPlugins = { compile: [(...args) => this._convertDataImages(...args)], stream: [] }; this._userPlugins = { compile: [], stream: [] }; this.meta = new Map(); this.dkim = this.options.dkim ? new DKIM(this.options.dkim) : false; this.transporter = transporter; this.transporter.mailer = this; this.logger = shared.getLogger(this.options, { component: this.options.component || 'mail' }); this.logger.debug( { tnx: 'create' }, 'Creating transport: %s', this.getVersionString() ); // setup emit handlers for the transporter if (typeof transporter.on === 'function') { // deprecated log interface this.transporter.on('log', log => { this.logger.debug( { tnx: 'transport' }, '%s: %s', log.type, log.message ); }); // transporter errors this.transporter.on('error', err => { this.logger.error( { err, tnx: 'transport' }, 'Transport Error: %s', err.message ); this.emit('error', err); }); // indicates if the sender has became idle this.transporter.on('idle', (...args) => { this.emit('idle', ...args); }); } /** * Optional methods passed to the underlying transport object */ ['close', 'isIdle', 'verify'].forEach(method => { this[method] = (...args) => { if (typeof this.transporter[method] === 'function') { return this.transporter[method](...args); } else { this.logger.warn( { tnx: 'transport', methodName: method }, 'Non existing method %s called for transport', method ); return false; } }; }); // setup proxy handling if (this.options.proxy && typeof this.options.proxy === 'string') { this.setupProxy(this.options.proxy); } } use(step, plugin) { step = (step || '').toString(); if (!this._userPlugins.hasOwnProperty(step)) { this._userPlugins[step] = [plugin]; } else { this._userPlugins[step].push(plugin); } } /** * Sends an email using the preselected transport object * * @param {Object} data E-data description * @param {Function?} callback Callback to run once the sending succeeded or failed */ sendMail(data, callback) { let promise; if (!callback && typeof Promise === 'function') { promise = new Promise((resolve, reject) => { callback = shared.callbackPromise(resolve, reject); }); } if (typeof this.getSocket === 'function') { this.transporter.getSocket = this.getSocket; this.getSocket = false; } let mail = new MailMessage(this, data); this.logger.debug( { tnx: 'transport', name: this.transporter.name, version: this.transporter.version, action: 'send' }, 'Sending mail using %s/%s', this.transporter.name, this.transporter.version ); this._processPlugins('compile', mail, err => { if (err) { this.logger.error( { err, tnx: 'plugin', action: 'compile' }, 'PluginCompile Error: %s', err.message ); return callback(err); } mail.message = new MailComposer(mail.data).compile(); mail.setMailerHeader(); mail.setPriorityHeaders(); mail.setListHeaders(); this._processPlugins('stream', mail, err => { if (err) { this.logger.error( { err, tnx: 'plugin', action: 'stream' }, 'PluginStream Error: %s', err.message ); return callback(err); } if (mail.data.dkim || this.dkim) { mail.message.processFunc(input => { let dkim = mail.data.dkim ? new DKIM(mail.data.dkim) : this.dkim; this.logger.debug( { tnx: 'DKIM', messageId: mail.message.messageId(), dkimDomains: dkim.keys.map(key => key.keySelector + '.' + key.domainName).join(', ') }, 'Signing outgoing message with %s keys', dkim.keys.length ); return dkim.sign(input, mail.data._dkim); }); } this.transporter.send(mail, (...args) => { if (args[0]) { this.logger.error( { err: args[0], tnx: 'transport', action: 'send' }, 'Send Error: %s', args[0].message ); } callback(...args); }); }); }); return promise; } getVersionString() { return util.format('%s (%s; +%s; %s/%s)', packageData.name, packageData.version, packageData.homepage, this.transporter.name, this.transporter.version); } _processPlugins(step, mail, callback) { step = (step || '').toString(); if (!this._userPlugins.hasOwnProperty(step)) { return callback(); } let userPlugins = this._userPlugins[step] || []; let defaultPlugins = this._defaultPlugins[step] || []; if (userPlugins.length) { this.logger.debug( { tnx: 'transaction', pluginCount: userPlugins.length, step }, 'Using %s plugins for %s', userPlugins.length, step ); } if (userPlugins.length + defaultPlugins.length === 0) { return callback(); } let pos = 0; let block = 'default'; let processPlugins = () => { let curplugins = block === 'default' ? defaultPlugins : userPlugins; if (pos >= curplugins.length) { if (block === 'default' && userPlugins.length) { block = 'user'; pos = 0; curplugins = userPlugins; } else { return callback(); } } let plugin = curplugins[pos++]; plugin(mail, err => { if (err) { return callback(err); } processPlugins(); }); }; processPlugins(); } /** * Sets up proxy handler for a Nodemailer object * * @param {String} proxyUrl Proxy configuration url */ setupProxy(proxyUrl) { let proxy = urllib.parse(proxyUrl); // setup socket handler for the mailer object this.getSocket = (options, callback) => { let protocol = proxy.protocol.replace(/:$/, '').toLowerCase(); if (this.meta.has('proxy_handler_' + protocol)) { return this.meta.get('proxy_handler_' + protocol)(proxy, options, callback); } switch (protocol) { // Connect using a HTTP CONNECT method case 'http': case 'https': httpProxyClient(proxy.href, options.port, options.host, (err, socket) => { if (err) { return callback(err); } return callback(null, { connection: socket }); }); return; case 'socks': case 'socks5': case 'socks4': case 'socks4a': { if (!this.meta.has('proxy_socks_module')) { return callback(new Error('Socks module not loaded')); } let connect = ipaddress => { this.meta.get('proxy_socks_module').createConnection({ proxy: { ipaddress, port: proxy.port, type: Number(proxy.protocol.replace(/\D/g, '')) || 5 }, target: { host: options.host, port: options.port }, command: 'connect', authentication: !proxy.auth ? false : { username: decodeURIComponent(proxy.auth.split(':').shift()), password: decodeURIComponent(proxy.auth.split(':').pop()) } }, (err, socket) => { if (err) { return callback(err); } return callback(null, { connection: socket }); }); }; if (net.isIP(proxy.hostname)) { return connect(proxy.hostname); } return dns.resolve(proxy.hostname, (err, address) => { if (err) { return callback(err); } connect(address); }); } } callback(new Error('Unknown proxy configuration')); }; } _convertDataImages(mail, callback) { if ((!this.options.attachDataUrls && !mail.data.attachDataUrls) || !mail.data.html) { return callback(); } mail.resolveContent(mail.data, 'html', (err, html) => { if (err) { return callback(err); } let cidCounter = 0; html = (html || '').toString().replace(/(<img\b[^>]* src\s*=[\s"']*)(data:([^;]+);[^"'>\s]+)/gi, (match, prefix, dataUri, mimeType) => { let cid = crypto.randomBytes(10).toString('hex') + '@localhost'; if (!mail.data.attachments) { mail.data.attachments = []; } if (!Array.isArray(mail.data.attachments)) { mail.data.attachments = [].concat(mail.data.attachments || []); } mail.data.attachments.push({ path: dataUri, cid, filename: 'image-' + ++cidCounter + '.' + mimeTypes.detectExtension(mimeType) }); return prefix + 'cid:' + cid; }); mail.data.html = html; callback(); }); } set(key, value) { return this.meta.set(key, value); } get(key) { return this.meta.get(key); } } module.exports = Mail;
/* jshint esversion: 6 */ "use strict"; const Server = require(__dirname + "/server.js"); const electron = require("electron"); const core = require(__dirname + "/app.js"); // Config var config = {}; // Module to control application life. const app = electron.app; // Module to create native browser window. const BrowserWindow = electron.BrowserWindow; // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. let mainWindow; function createWindow() { var electronOptionsDefaults = { width: 800, height: 600, x: 0, y: 0, darkTheme: true, webPreferences: { nodeIntegration: false, zoomFactor: config.zoom } } // DEPRECATED: "kioskmode" backwards compatibility, to be removed // settings these options directly instead provides cleaner interface if (config.kioskmode) { electronOptionsDefaults.kiosk = true; } else { electronOptionsDefaults.fullscreen = true; electronOptionsDefaults.autoHideMenuBar = true; } var electronOptions = Object.assign({}, electronOptionsDefaults, config.electronOptions); // Create the browser window. mainWindow = new BrowserWindow(electronOptions); // and load the index.html of the app. //mainWindow.loadURL('file://' + __dirname + '../../index.html'); mainWindow.loadURL("http://localhost:" + config.port); // Open the DevTools if run with "npm start dev" if(process.argv[2] == "dev") { mainWindow.webContents.openDevTools(); } // Set responders for window events. mainWindow.on("closed", function() { mainWindow = null; }); if (config.kioskmode) { mainWindow.on("blur", function() { mainWindow.focus(); }); mainWindow.on("leave-full-screen", function() { mainWindow.setFullScreen(true); }); mainWindow.on("resize", function() { setTimeout(function() { mainWindow.reload(); }, 1000); }); } } // This method will be called when Electron has finished // initialization and is ready to create browser windows. app.on("ready", function() { console.log("Launching application."); createWindow(); }); // Quit when all windows are closed. app.on("window-all-closed", function() { createWindow(); }); app.on("activate", function() { // On OS X it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (mainWindow === null) { createWindow(); } }); // Start the core application. // This starts all node helpers and starts the webserver. core.start(function(c) { config = c; });
'use strict'; exports.__esModule = true; var _extends2 = require('babel-runtime/helpers/extends'); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties'); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = require('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = require('classnames'); var _classnames2 = _interopRequireDefault(_classnames); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _elementType = require('prop-types-extra/lib/elementType'); var _elementType2 = _interopRequireDefault(_elementType); var _warning = require('warning'); var _warning2 = _interopRequireDefault(_warning); var _FormControlFeedback = require('./FormControlFeedback'); var _FormControlFeedback2 = _interopRequireDefault(_FormControlFeedback); var _FormControlStatic = require('./FormControlStatic'); var _FormControlStatic2 = _interopRequireDefault(_FormControlStatic); var _bootstrapUtils = require('./utils/bootstrapUtils'); var _StyleConfig = require('./utils/StyleConfig'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { componentClass: _elementType2['default'], /** * Only relevant if `componentClass` is `'input'`. */ type: _propTypes2['default'].string, /** * Uses `controlId` from `<FormGroup>` if not explicitly specified. */ id: _propTypes2['default'].string, /** * Attaches a ref to the `<input>` element. Only functions can be used here. * * ```js * <FormControl inputRef={ref => { this.input = ref; }} /> * ``` */ inputRef: _propTypes2['default'].func }; var defaultProps = { componentClass: 'input' }; var contextTypes = { $bs_formGroup: _propTypes2['default'].object }; var FormControl = function (_React$Component) { (0, _inherits3['default'])(FormControl, _React$Component); function FormControl() { (0, _classCallCheck3['default'])(this, FormControl); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } FormControl.prototype.render = function render() { var formGroup = this.context.$bs_formGroup; var controlId = formGroup && formGroup.controlId; var _props = this.props, Component = _props.componentClass, type = _props.type, _props$id = _props.id, id = _props$id === undefined ? controlId : _props$id, inputRef = _props.inputRef, className = _props.className, bsSize = _props.bsSize, props = (0, _objectWithoutProperties3['default'])(_props, ['componentClass', 'type', 'id', 'inputRef', 'className', 'bsSize']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; process.env.NODE_ENV !== 'production' ? (0, _warning2['default'])(controlId == null || id === controlId, '`controlId` is ignored on `<FormControl>` when `id` is specified.') : void 0; // input[type="file"] should not have .form-control. var classes = void 0; if (type !== 'file') { classes = (0, _bootstrapUtils.getClassSet)(bsProps); } // If user provides a size, make sure to append it to classes as input- // e.g. if bsSize is small, it will append input-sm if (bsSize) { var size = _StyleConfig.SIZE_MAP[bsSize] || bsSize; classes[(0, _bootstrapUtils.prefix)({ bsClass: 'input' }, size)] = true; } return _react2['default'].createElement(Component, (0, _extends3['default'])({}, elementProps, { type: type, id: id, ref: inputRef, className: (0, _classnames2['default'])(className, classes) })); }; return FormControl; }(_react2['default'].Component); FormControl.propTypes = propTypes; FormControl.defaultProps = defaultProps; FormControl.contextTypes = contextTypes; FormControl.Feedback = _FormControlFeedback2['default']; FormControl.Static = _FormControlStatic2['default']; exports['default'] = (0, _bootstrapUtils.bsClass)('form-control', (0, _bootstrapUtils.bsSizes)([_StyleConfig.Size.SMALL, _StyleConfig.Size.LARGE], FormControl)); module.exports = exports['default'];
'use strict'; angular.module('slickExampleApp', ['slickCarousel', 'ngRoute']) .config(['$routeProvider', function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/home.html', controller: 'SlickController' }) .otherwise({ redirectTo: '/' }); }]) .config(['slickCarouselConfig', function (slickCarouselConfig) { slickCarouselConfig.dots = true; slickCarouselConfig.autoplay = false; }]) .controller('SlickController', function ($scope, $timeout) { //==================================== // Slick 1 //==================================== $scope.number1 = [1, 2, 3, 4, 5, 6, 7, 8]; $scope.slickConfig1Loaded = true; $scope.updateNumber1 = function () { $scope.slickConfig1Loaded = false; $scope.number1[2] = '123'; $scope.number1.push(Math.floor((Math.random() * 10) + 100)); $timeout(function () { $scope.slickConfig1Loaded = true; }, 5); }; $scope.slickCurrentIndex = 0; $scope.slickConfig = { dots: true, autoplay: true, initialSlide: 3, infinite: true, autoplaySpeed: 1000, method: {}, event: { beforeChange: function (event, slick, currentSlide, nextSlide) { console.log('before change', Math.floor((Math.random() * 10) + 100)); }, afterChange: function (event, slick, currentSlide, nextSlide) { $scope.slickCurrentIndex = currentSlide; }, breakpoint: function (event, slick, breakpoint) { console.log('breakpoint'); }, destroy: function (event, slick) { console.log('destroy'); }, edge: function (event, slick, direction) { console.log('edge'); }, reInit: function (event, slick) { console.log('re-init'); }, init: function (event, slick) { console.log('init'); }, setPosition: function (evnet, slick) { console.log('setPosition'); }, swipe: function (event, slick, direction) { console.log('swipe'); } } }; //==================================== // Slick 2 //==================================== $scope.number2 = [{label: 1, otherLabel: 1}, {label: 2, otherLabel: 2}, {label: 3, otherLabel: 3}, { label: 4, otherLabel: 4 }, {label: 5, otherLabel: 5}, {label: 6, otherLabel: 6}, {label: 7, otherLabel: 7}, {label: 8, otherLabel: 8}]; $scope.slickConfig2Loaded = true; $scope.updateNumber2 = function () { $scope.slickConfig2Loaded = false; $scope.number2[2] = 'ggg'; $scope.number2.push(Math.floor((Math.random() * 10) + 100)); $timeout(function () { $scope.slickConfig2Loaded = true; }); }; $scope.slickConfig2 = { autoplay: true, infinite: true, autoplaySpeed: 1000, slidesToShow: 3, slidesToScroll: 3, method: {} }; //==================================== // Slick 3 //==================================== $scope.number3 = [{label: 1}, {label: 2}, {label: 3}, {label: 4}, {label: 5}, {label: 6}, {label: 7}, {label: 8}]; $scope.slickConfig3Loaded = true; $scope.slickConfig3 = { method: {}, dots: true, infinite: false, speed: 300, slidesToShow: 4, slidesToScroll: 4, responsive: [ { breakpoint: 1024, settings: { slidesToShow: 3, slidesToScroll: 3, infinite: true, dots: true } }, { breakpoint: 600, settings: { slidesToShow: 2, slidesToScroll: 2 } }, { breakpoint: 480, settings: { slidesToShow: 1, slidesToScroll: 1 } } ] }; //==================================== // Slick 4 //==================================== $scope.number4 = [{label: 225}, {label: 125}, {label: 200}, {label: 175}, {label: 150}, {label: 180}, {label: 300}, {label: 400}]; $scope.slickConfig4Loaded = true; $scope.updateNumber4 = function () { $scope.slickConfig4Loaded = false; $scope.number4[2].label = 123; $scope.number4.push({label: Math.floor((Math.random() * 10) + 100)}); $timeout(function () { $scope.slickConfig4Loaded = true; }); }; $scope.slickConfig4 = { method: {}, dots: true, infinite: true, speed: 300, slidesToShow: 1, centerMode: true, variableWidth: true }; });
"use strict"; var Test = function Test() {};
/** * Virtual DOM patching algorithm based on Snabbdom by * Simon Friis Vindum (@paldepind) * Licensed under the MIT License * https://github.com/paldepind/snabbdom/blob/master/LICENSE * * modified by Evan You (@yyx990803) * /* * Not type-checking this because this file is perf-critical and the cost * of making flow understand it is not worth it. */ import VNode from './vnode' import config from '../config' import { SSR_ATTR } from 'shared/constants' import { registerRef } from './modules/ref' import { activeInstance } from '../instance/lifecycle' import { warn, isDef, isUndef, isTrue, makeMap, isPrimitive } from '../util/index' export const emptyNode = new VNode('', {}, []) const hooks = ['create', 'activate', 'update', 'remove', 'destroy'] function sameVnode (a, b) { return ( a.key === b.key && a.tag === b.tag && a.isComment === b.isComment && isDef(a.data) === isDef(b.data) && sameInputType(a, b) ) } // Some browsers do not support dynamically changing type for <input> // so they need to be treated as different nodes function sameInputType (a, b) { if (a.tag !== 'input') return true let i const typeA = isDef(i = a.data) && isDef(i = i.attrs) && i.type const typeB = isDef(i = b.data) && isDef(i = i.attrs) && i.type return typeA === typeB } function createKeyToOldIdx (children, beginIdx, endIdx) { let i, key const map = {} for (i = beginIdx; i <= endIdx; ++i) { key = children[i].key if (isDef(key)) map[key] = i } return map } export function createPatchFunction (backend) { let i, j const cbs = {} const { modules, nodeOps } = backend for (i = 0; i < hooks.length; ++i) { cbs[hooks[i]] = [] for (j = 0; j < modules.length; ++j) { if (isDef(modules[j][hooks[i]])) { cbs[hooks[i]].push(modules[j][hooks[i]]) } } } function emptyNodeAt (elm) { return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm) } function createRmCb (childElm, listeners) { function remove () { if (--remove.listeners === 0) { removeNode(childElm) } } remove.listeners = listeners return remove } function removeNode (el) { const parent = nodeOps.parentNode(el) // element may have already been removed due to v-html / v-text if (isDef(parent)) { nodeOps.removeChild(parent, el) } } let inPre = 0 function createElm (vnode, insertedVnodeQueue, parentElm, refElm, nested) { vnode.isRootInsert = !nested // for transition enter check if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) { return } const data = vnode.data const children = vnode.children const tag = vnode.tag if (isDef(tag)) { if (process.env.NODE_ENV !== 'production') { if (data && data.pre) { inPre++ } if ( !inPre && !vnode.ns && !(config.ignoredElements.length && config.ignoredElements.indexOf(tag) > -1) && config.isUnknownElement(tag) ) { warn( 'Unknown custom element: <' + tag + '> - did you ' + 'register the component correctly? For recursive components, ' + 'make sure to provide the "name" option.', vnode.context ) } } vnode.elm = vnode.ns ? nodeOps.createElementNS(vnode.ns, tag) : nodeOps.createElement(tag, vnode) setScope(vnode) /* istanbul ignore if */ if (__WEEX__) { // in Weex, the default insertion order is parent-first. // List items can be optimized to use children-first insertion // with append="tree". const appendAsTree = isDef(data) && isTrue(data.appendAsTree) if (!appendAsTree) { if (isDef(data)) { invokeCreateHooks(vnode, insertedVnodeQueue) } insert(parentElm, vnode.elm, refElm) } createChildren(vnode, children, insertedVnodeQueue) if (appendAsTree) { if (isDef(data)) { invokeCreateHooks(vnode, insertedVnodeQueue) } insert(parentElm, vnode.elm, refElm) } } else { createChildren(vnode, children, insertedVnodeQueue) if (isDef(data)) { invokeCreateHooks(vnode, insertedVnodeQueue) } insert(parentElm, vnode.elm, refElm) } if (process.env.NODE_ENV !== 'production' && data && data.pre) { inPre-- } } else if (isTrue(vnode.isComment)) { vnode.elm = nodeOps.createComment(vnode.text) insert(parentElm, vnode.elm, refElm) } else { vnode.elm = nodeOps.createTextNode(vnode.text) insert(parentElm, vnode.elm, refElm) } } function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) { let i = vnode.data if (isDef(i)) { const isReactivated = isDef(vnode.componentInstance) && i.keepAlive if (isDef(i = i.hook) && isDef(i = i.init)) { i(vnode, false /* hydrating */, parentElm, refElm) } // after calling the init hook, if the vnode is a child component // it should've created a child instance and mounted it. the child // component also has set the placeholder vnode's elm. // in that case we can just return the element and be done. if (isDef(vnode.componentInstance)) { initComponent(vnode, insertedVnodeQueue) if (isTrue(isReactivated)) { reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm) } return true } } } function initComponent (vnode, insertedVnodeQueue) { if (isDef(vnode.data.pendingInsert)) { insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert) } vnode.elm = vnode.componentInstance.$el if (isPatchable(vnode)) { invokeCreateHooks(vnode, insertedVnodeQueue) setScope(vnode) } else { // empty component root. // skip all element-related modules except for ref (#3455) registerRef(vnode) // make sure to invoke the insert hook insertedVnodeQueue.push(vnode) } } function reactivateComponent (vnode, insertedVnodeQueue, parentElm, refElm) { let i // hack for #4339: a reactivated component with inner transition // does not trigger because the inner node's created hooks are not called // again. It's not ideal to involve module-specific logic in here but // there doesn't seem to be a better way to do it. let innerNode = vnode while (innerNode.componentInstance) { innerNode = innerNode.componentInstance._vnode if (isDef(i = innerNode.data) && isDef(i = i.transition)) { for (i = 0; i < cbs.activate.length; ++i) { cbs.activate[i](emptyNode, innerNode) } insertedVnodeQueue.push(innerNode) break } } // unlike a newly created component, // a reactivated keep-alive component doesn't insert itself insert(parentElm, vnode.elm, refElm) } function insert (parent, elm, ref) { if (isDef(parent)) { if (isDef(ref)) { if (ref.parentNode === parent) { nodeOps.insertBefore(parent, elm, ref) } } else { nodeOps.appendChild(parent, elm) } } } function createChildren (vnode, children, insertedVnodeQueue) { if (Array.isArray(children)) { for (let i = 0; i < children.length; ++i) { createElm(children[i], insertedVnodeQueue, vnode.elm, null, true) } } else if (isPrimitive(vnode.text)) { nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(vnode.text)) } } function isPatchable (vnode) { while (vnode.componentInstance) { vnode = vnode.componentInstance._vnode } return isDef(vnode.tag) } function invokeCreateHooks (vnode, insertedVnodeQueue) { for (let i = 0; i < cbs.create.length; ++i) { cbs.create[i](emptyNode, vnode) } i = vnode.data.hook // Reuse variable if (isDef(i)) { if (isDef(i.create)) i.create(emptyNode, vnode) if (isDef(i.insert)) insertedVnodeQueue.push(vnode) } } // set scope id attribute for scoped CSS. // this is implemented as a special case to avoid the overhead // of going through the normal attribute patching process. function setScope (vnode) { let i let ancestor = vnode while (ancestor) { if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) { nodeOps.setAttribute(vnode.elm, i, '') } ancestor = ancestor.parent } // for slot content they should also get the scopeId from the host instance. if (isDef(i = activeInstance) && i !== vnode.context && isDef(i = i.$options._scopeId) ) { nodeOps.setAttribute(vnode.elm, i, '') } } function addVnodes (parentElm, refElm, vnodes, startIdx, endIdx, insertedVnodeQueue) { for (; startIdx <= endIdx; ++startIdx) { createElm(vnodes[startIdx], insertedVnodeQueue, parentElm, refElm) } } function invokeDestroyHook (vnode) { let i, j const data = vnode.data if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.destroy)) i(vnode) for (i = 0; i < cbs.destroy.length; ++i) cbs.destroy[i](vnode) } if (isDef(i = vnode.children)) { for (j = 0; j < vnode.children.length; ++j) { invokeDestroyHook(vnode.children[j]) } } } function removeVnodes (parentElm, vnodes, startIdx, endIdx) { for (; startIdx <= endIdx; ++startIdx) { const ch = vnodes[startIdx] if (isDef(ch)) { if (isDef(ch.tag)) { removeAndInvokeRemoveHook(ch) invokeDestroyHook(ch) } else { // Text node removeNode(ch.elm) } } } } function removeAndInvokeRemoveHook (vnode, rm) { if (isDef(rm) || isDef(vnode.data)) { let i const listeners = cbs.remove.length + 1 if (isDef(rm)) { // we have a recursively passed down rm callback // increase the listeners count rm.listeners += listeners } else { // directly removing rm = createRmCb(vnode.elm, listeners) } // recursively invoke hooks on child component root node if (isDef(i = vnode.componentInstance) && isDef(i = i._vnode) && isDef(i.data)) { removeAndInvokeRemoveHook(i, rm) } for (i = 0; i < cbs.remove.length; ++i) { cbs.remove[i](vnode, rm) } if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) { i(vnode, rm) } else { rm() } } else { removeNode(vnode.elm) } } function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) { let oldStartIdx = 0 let newStartIdx = 0 let oldEndIdx = oldCh.length - 1 let oldStartVnode = oldCh[0] let oldEndVnode = oldCh[oldEndIdx] let newEndIdx = newCh.length - 1 let newStartVnode = newCh[0] let newEndVnode = newCh[newEndIdx] let oldKeyToIdx, idxInOld, elmToMove, refElm // removeOnly is a special flag used only by <transition-group> // to ensure removed elements stay in correct relative positions // during leaving transitions const canMove = !removeOnly while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) { if (isUndef(oldStartVnode)) { oldStartVnode = oldCh[++oldStartIdx] // Vnode has been moved left } else if (isUndef(oldEndVnode)) { oldEndVnode = oldCh[--oldEndIdx] } else if (sameVnode(oldStartVnode, newStartVnode)) { patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue) oldStartVnode = oldCh[++oldStartIdx] newStartVnode = newCh[++newStartIdx] } else if (sameVnode(oldEndVnode, newEndVnode)) { patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue) oldEndVnode = oldCh[--oldEndIdx] newEndVnode = newCh[--newEndIdx] } else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue) canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm)) oldStartVnode = oldCh[++oldStartIdx] newEndVnode = newCh[--newEndIdx] } else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue) canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm) oldEndVnode = oldCh[--oldEndIdx] newStartVnode = newCh[++newStartIdx] } else { if (isUndef(oldKeyToIdx)) oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx) idxInOld = isDef(newStartVnode.key) ? oldKeyToIdx[newStartVnode.key] : null if (isUndef(idxInOld)) { // New element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm) newStartVnode = newCh[++newStartIdx] } else { elmToMove = oldCh[idxInOld] /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && !elmToMove) { warn( 'It seems there are duplicate keys that is causing an update error. ' + 'Make sure each v-for item has a unique key.' ) } if (sameVnode(elmToMove, newStartVnode)) { patchVnode(elmToMove, newStartVnode, insertedVnodeQueue) oldCh[idxInOld] = undefined canMove && nodeOps.insertBefore(parentElm, newStartVnode.elm, oldStartVnode.elm) newStartVnode = newCh[++newStartIdx] } else { // same key but different element. treat as new element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm) newStartVnode = newCh[++newStartIdx] } } } } if (oldStartIdx > oldEndIdx) { refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue) } else if (newStartIdx > newEndIdx) { removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx) } } function patchVnode (oldVnode, vnode, insertedVnodeQueue, removeOnly) { if (oldVnode === vnode) { return } // reuse element for static trees. // note we only do this if the vnode is cloned - // if the new node is not cloned it means the render functions have been // reset by the hot-reload-api and we need to do a proper re-render. if (isTrue(vnode.isStatic) && isTrue(oldVnode.isStatic) && vnode.key === oldVnode.key && (isTrue(vnode.isCloned) || isTrue(vnode.isOnce)) ) { vnode.elm = oldVnode.elm vnode.componentInstance = oldVnode.componentInstance return } let i const data = vnode.data if (isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch)) { i(oldVnode, vnode) } const elm = vnode.elm = oldVnode.elm const oldCh = oldVnode.children const ch = vnode.children if (isDef(data) && isPatchable(vnode)) { for (i = 0; i < cbs.update.length; ++i) cbs.update[i](oldVnode, vnode) if (isDef(i = data.hook) && isDef(i = i.update)) i(oldVnode, vnode) } if (isUndef(vnode.text)) { if (isDef(oldCh) && isDef(ch)) { if (oldCh !== ch) updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly) } else if (isDef(ch)) { if (isDef(oldVnode.text)) nodeOps.setTextContent(elm, '') addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue) } else if (isDef(oldCh)) { removeVnodes(elm, oldCh, 0, oldCh.length - 1) } else if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, '') } } else if (oldVnode.text !== vnode.text) { nodeOps.setTextContent(elm, vnode.text) } if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.postpatch)) i(oldVnode, vnode) } } function invokeInsertHook (vnode, queue, initial) { // delay insert hooks for component root nodes, invoke them after the // element is really inserted if (isTrue(initial) && isDef(vnode.parent)) { vnode.parent.data.pendingInsert = queue } else { for (let i = 0; i < queue.length; ++i) { queue[i].data.hook.insert(queue[i]) } } } let bailed = false // list of modules that can skip create hook during hydration because they // are already rendered on the client or has no need for initialization const isRenderedModule = makeMap('attrs,style,class,staticClass,staticStyle,key') // Note: this is a browser-only function so we can assume elms are DOM nodes. function hydrate (elm, vnode, insertedVnodeQueue) { if (process.env.NODE_ENV !== 'production') { if (!assertNodeMatch(elm, vnode)) { return false } } vnode.elm = elm const { tag, data, children } = vnode if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.init)) i(vnode, true /* hydrating */) if (isDef(i = vnode.componentInstance)) { // child component. it should have hydrated its own tree. initComponent(vnode, insertedVnodeQueue) return true } } if (isDef(tag)) { if (isDef(children)) { // empty element, allow client to pick up and populate children if (!elm.hasChildNodes()) { createChildren(vnode, children, insertedVnodeQueue) } else { let childrenMatch = true let childNode = elm.firstChild for (let i = 0; i < children.length; i++) { if (!childNode || !hydrate(childNode, children[i], insertedVnodeQueue)) { childrenMatch = false break } childNode = childNode.nextSibling } // if childNode is not null, it means the actual childNodes list is // longer than the virtual children list. if (!childrenMatch || childNode) { if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined' && !bailed ) { bailed = true console.warn('Parent: ', elm) console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children) } return false } } } if (isDef(data)) { for (const key in data) { if (!isRenderedModule(key)) { invokeCreateHooks(vnode, insertedVnodeQueue) break } } } } else if (elm.data !== vnode.text) { elm.data = vnode.text } return true } function assertNodeMatch (node, vnode) { if (isDef(vnode.tag)) { return ( vnode.tag.indexOf('vue-component') === 0 || vnode.tag.toLowerCase() === (node.tagName && node.tagName.toLowerCase()) ) } else { return node.nodeType === (vnode.isComment ? 8 : 3) } } return function patch (oldVnode, vnode, hydrating, removeOnly, parentElm, refElm) { if (isUndef(vnode)) { if (isDef(oldVnode)) invokeDestroyHook(oldVnode) return } let isInitialPatch = false const insertedVnodeQueue = [] if (isUndef(oldVnode)) { // empty mount (likely as component), create new root element isInitialPatch = true createElm(vnode, insertedVnodeQueue, parentElm, refElm) } else { const isRealElement = isDef(oldVnode.nodeType) if (!isRealElement && sameVnode(oldVnode, vnode)) { // patch existing root node patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly) } else { if (isRealElement) { // mounting to a real element // check if this is server-rendered content and if we can perform // a successful hydration. if (oldVnode.nodeType === 1 && oldVnode.hasAttribute(SSR_ATTR)) { oldVnode.removeAttribute(SSR_ATTR) hydrating = true } if (isTrue(hydrating)) { if (hydrate(oldVnode, vnode, insertedVnodeQueue)) { invokeInsertHook(vnode, insertedVnodeQueue, true) return oldVnode } else if (process.env.NODE_ENV !== 'production') { warn( 'The client-side rendered virtual DOM tree is not matching ' + 'server-rendered content. This is likely caused by incorrect ' + 'HTML markup, for example nesting block-level elements inside ' + '<p>, or missing <tbody>. Bailing hydration and performing ' + 'full client-side render.' ) } } // either not server-rendered, or hydration failed. // create an empty node and replace it oldVnode = emptyNodeAt(oldVnode) } // replacing existing element const oldElm = oldVnode.elm const parentElm = nodeOps.parentNode(oldElm) createElm( vnode, insertedVnodeQueue, // extremely rare edge case: do not insert if old element is in a // leaving transition. Only happens when combining transition + // keep-alive + HOCs. (#4590) oldElm._leaveCb ? null : parentElm, nodeOps.nextSibling(oldElm) ) if (isDef(vnode.parent)) { // component root element replaced. // update parent placeholder node element, recursively let ancestor = vnode.parent while (ancestor) { ancestor.elm = vnode.elm ancestor = ancestor.parent } if (isPatchable(vnode)) { for (let i = 0; i < cbs.create.length; ++i) { cbs.create[i](emptyNode, vnode.parent) } } } if (isDef(parentElm)) { removeVnodes(parentElm, [oldVnode], 0, 0) } else if (isDef(oldVnode.tag)) { invokeDestroyHook(oldVnode) } } } invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch) return vnode.elm } }
console.log(1)
/** * @ngdoc directive * @function * @name umbraco.directives.directive:umbPropertyEditor * @requires formController * @restrict E **/ //share property editor directive function function umbPropEditor(umbPropEditorHelper) { return { scope: { model: "=", isPreValue: "@", preview: "<" }, require: ["^^form", "?^umbProperty"], restrict: 'E', replace: true, templateUrl: 'views/components/property/umb-property-editor.html', link: function (scope, element, attrs, ctrl) { //we need to copy the form controller val to our isolated scope so that //it get's carried down to the child scopes of this! //we'll also maintain the current form name. scope[ctrl[0].$name] = ctrl[0]; // We will capture a reference to umbProperty in this Directive and pass it on to the Scope, so Property-Editor controllers can use it. scope["umbProperty"] = ctrl[1]; if(!scope.model.alias){ scope.model.alias = Math.random().toString(36).slice(2); } var unbindWatcher = scope.$watch("model.view", function() { scope.propertyEditorView = umbPropEditorHelper.getViewPath(scope.model.view, scope.isPreValue); } ); scope.$on("$destroy", function () { unbindWatcher(); }); } }; }; angular.module("umbraco.directives").directive('umbPropertyEditor', umbPropEditor);
export * from "./e1"; export * from "./ee2";
'use strict'; var SVGO = require(process.env.COVERAGE ? '../../lib-cov/svgo.js' : '../../lib/svgo.js'); var JSAPI = require(process.env.COVERAGE ? '../../lib-cov/svgo/jsAPI.js' : '../../lib/svgo/jsAPI.js'); describe('svgo object', function() { it('should has createContentItem method', function() { var svgo = new SVGO(); svgo.createContentItem.should.be.a.Function; }); it('should be able to create content item', function() { var svgo = new SVGO(); var item = svgo.createContentItem({ elem: 'elementName', prefix: 'prefixName', local: 'localName' }); item.should.be.instanceof(JSAPI); item.should.have.ownProperty('elem').equal('elementName'); item.should.have.ownProperty('prefix').equal('prefixName'); item.should.have.ownProperty('local').equal('localName'); }); it('should be able create content item without argument', function() { var svgo = new SVGO(); var item = svgo.createContentItem(); item.should.be.instanceof(JSAPI); item.should.be.empty; }); });
class UserRolesAddController { constructor (API, $state, $stateParams) { 'ngInject' this.$state = $state this.formSubmitted = false this.API = API this.alerts = [] if ($stateParams.alerts) { this.alerts.push($stateParams.alerts) } } save (isValid) { this.$state.go(this.$state.current, {}, { alerts: 'test' }) if (isValid) { let Roles = this.API.service('roles', this.API.all('users')) let $state = this.$state Roles.post({ 'role': this.role, 'slug': this.slug, 'description': this.description }).then(function () { let alert = { type: 'success', 'title': 'Success!', msg: 'Role has been added.' } $state.go($state.current, { alerts: alert}) }, function (response) { let alert = { type: 'error', 'title': 'Error!', msg: response.data.message } $state.go($state.current, { alerts: alert}) }) } else { this.formSubmitted = true } } $onInit () {} } export const UserRolesAddComponent = { templateUrl: './views/app/components/user-roles-add/user-roles-add.component.html', controller: UserRolesAddController, controllerAs: 'vm', bindings: {} }
var JSONStreamParser = require('./lib/JSONStreamParser'); var util = require('util'); function respondWithError(err) { if (util.isError(err)) { err = err.stack; } console.log(JSON.stringify({error: err}, null, 2)); } function respondWithResult(result) { console.log(JSON.stringify({response: result}, null, 2)); } function startWorker(onInitialize, onMessageReceived, onShutdown) { process.stdin.resume(); process.stdin.setEncoding('utf8'); var inputStreamParser = new JSONStreamParser(); var initialized = false; var initData = null; process.stdin.on('data', function(data) { var rcvdMsg = inputStreamParser.parse(data); if (rcvdMsg.length === 1) { if (initialized === false) { try { onInitialize && onInitialize(rcvdMsg[0].initData); initialized = true; console.log(JSON.stringify({initSuccess: true})); } catch (e) { console.log(JSON.stringify({initError: e.stack || e.message})); throw e; } } else { try { var message = rcvdMsg[0].message; onMessageReceived(message).then(function(response) { if (!response || typeof response !== 'object') { throw new Error( 'Invalid response returned by worker function: ' + JSON.stringify(response, null, 2) ); } return response; }).then(respondWithResult, respondWithError); } catch (e) { respondWithError(e.stack || e.message); } } } else if (rcvdMsg.length > 1) { throw new Error( 'Received multiple messages at once! Not sure what to do, so bailing ' + 'out!' ); } }); onShutdown && process.stdin.on('end', onShutdown); } exports.respondWithError = respondWithError; exports.respondWithResult = respondWithResult; exports.startWorker = startWorker;
/** * (c) 2010-2017 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; import H from '../parts/Globals.js'; import '../parts/Utilities.js'; /** * Mathematical Functionility */ var deg2rad = H.deg2rad, pick = H.pick; /* eslint-disable max-len */ /** * Apply 3-D rotation * Euler Angles (XYZ): * cosA = cos(Alfa|Roll) * cosB = cos(Beta|Pitch) * cosG = cos(Gamma|Yaw) * * Composite rotation: * | cosB * cosG | cosB * sinG | -sinB | * | sinA * sinB * cosG - cosA * sinG | sinA * sinB * sinG + cosA * cosG | sinA * cosB | * | cosA * sinB * cosG + sinA * sinG | cosA * sinB * sinG - sinA * cosG | cosA * cosB | * * Now, Gamma/Yaw is not used (angle=0), so we assume cosG = 1 and sinG = 0, so * we get: * | cosB | 0 | - sinB | * | sinA * sinB | cosA | sinA * cosB | * | cosA * sinB | - sinA | cosA * cosB | * * But in browsers, y is reversed, so we get sinA => -sinA. The general result * is: * | cosB | 0 | - sinB | | x | | px | * | - sinA * sinB | cosA | - sinA * cosB | x | y | = | py | * | cosA * sinB | sinA | cosA * cosB | | z | | pz | */ /* eslint-enable max-len */ function rotate3D(x, y, z, angles) { return { x: angles.cosB * x - angles.sinB * z, y: -angles.sinA * angles.sinB * x + angles.cosA * y - angles.cosB * angles.sinA * z, z: angles.cosA * angles.sinB * x + angles.sinA * y + angles.cosA * angles.cosB * z }; } function perspective3D(coordinate, origin, distance) { var projection = ((distance > 0) && (distance < Number.POSITIVE_INFINITY)) ? distance / (coordinate.z + origin.z + distance) : 1; return { x: coordinate.x * projection, y: coordinate.y * projection }; } /** * Transforms a given array of points according to the angles in chart.options. * Parameters: * - points: the array of points * - chart: the chart * - insidePlotArea: wether to verifiy the points are inside the plotArea * Returns: * - an array of transformed points */ H.perspective = function (points, chart, insidePlotArea) { var options3d = chart.options.chart.options3d, inverted = insidePlotArea ? chart.inverted : false, origin = { x: chart.plotWidth / 2, y: chart.plotHeight / 2, z: options3d.depth / 2, vd: pick(options3d.depth, 1) * pick(options3d.viewDistance, 0) }, scale = chart.scale3d || 1, beta = deg2rad * options3d.beta * (inverted ? -1 : 1), alpha = deg2rad * options3d.alpha * (inverted ? -1 : 1), angles = { cosA: Math.cos(alpha), cosB: Math.cos(-beta), sinA: Math.sin(alpha), sinB: Math.sin(-beta) }; if (!insidePlotArea) { origin.x += chart.plotLeft; origin.y += chart.plotTop; } // Transform each point return H.map(points, function (point) { var rotated = rotate3D( (inverted ? point.y : point.x) - origin.x, (inverted ? point.x : point.y) - origin.y, (point.z || 0) - origin.z, angles ), // Apply perspective coordinate = perspective3D(rotated, origin, origin.vd); // Apply translation coordinate.x = coordinate.x * scale + origin.x; coordinate.y = coordinate.y * scale + origin.y; coordinate.z = rotated.z * scale + origin.z; return { x: (inverted ? coordinate.y : coordinate.x), y: (inverted ? coordinate.x : coordinate.y), z: coordinate.z }; }); }; /** * Calculate a distance from camera to points - made for calculating zIndex of * scatter points. * Parameters: * - coordinates: The coordinates of the specific point * - chart: the chart * Returns: * - a distance from camera to point */ H.pointCameraDistance = function (coordinates, chart) { var options3d = chart.options.chart.options3d, cameraPosition = { x: chart.plotWidth / 2, y: chart.plotHeight / 2, z: pick(options3d.depth, 1) * pick(options3d.viewDistance, 0) + options3d.depth }, distance = Math.sqrt( Math.pow(cameraPosition.x - coordinates.plotX, 2) + Math.pow(cameraPosition.y - coordinates.plotY, 2) + Math.pow(cameraPosition.z - coordinates.plotZ, 2) ); return distance; }; /** * Calculate area of a 2D polygon using Shoelace algorithm * http://en.wikipedia.org/wiki/Shoelace_formula */ H.shapeArea = function (vertexes) { var area = 0, i, j; for (i = 0; i < vertexes.length; i++) { j = (i + 1) % vertexes.length; area += vertexes[i].x * vertexes[j].y - vertexes[j].x * vertexes[i].y; } return area / 2; }; /** * Calculate area of a 3D polygon after perspective projection */ H.shapeArea3d = function (vertexes, chart, insidePlotArea) { return H.shapeArea(H.perspective(vertexes, chart, insidePlotArea)); };
import React, {Component} from 'react'; import Draggable from 'react-draggable'; import ReactNoop from 'react-noop-renderer'; import Editor from './Editor'; import Fibers from './Fibers'; import describeFibers from './describeFibers'; // The only place where we use it. const ReactFiberInstrumentation = ReactNoop.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED .ReactFiberInstrumentation; function getFiberState(root, workInProgress) { if (!root) { return null; } return describeFibers(root.current, workInProgress); } const defaultCode = ` log('Render <div>Hello</div>'); ReactNoop.render(<div>Hello</div>); ReactNoop.flush(); log('Render <h1>Goodbye</h1>'); ReactNoop.render(<h1>Goodbye</h1>); ReactNoop.flush(); `; class App extends Component { constructor(props) { super(props); this.state = { code: localStorage.getItem('fiber-debugger-code') || defaultCode, isEditing: false, history: [], currentStep: 0, show: { alt: false, child: true, sibling: true, return: false, fx: false, }, graphSettings: { rankdir: 'TB', trackActive: true, }, }; } componentDidMount() { this.runCode(this.state.code); } runCode(code) { let currentStage; let currentRoot; ReactFiberInstrumentation.debugTool = null; ReactNoop.render(null); ReactNoop.flush(); ReactFiberInstrumentation.debugTool = { onMountContainer: root => { currentRoot = root; }, onUpdateContainer: root => { currentRoot = root; }, onBeginWork: fiber => { const fibers = getFiberState(currentRoot, fiber); const stage = currentStage; this.setState(({history}) => ({ history: [ ...history, { action: 'BEGIN', fibers, stage, }, ], })); }, onCompleteWork: fiber => { const fibers = getFiberState(currentRoot, fiber); const stage = currentStage; this.setState(({history}) => ({ history: [ ...history, { action: 'COMPLETE', fibers, stage, }, ], })); }, onCommitWork: fiber => { const fibers = getFiberState(currentRoot, fiber); const stage = currentStage; this.setState(({history}) => ({ history: [ ...history, { action: 'COMMIT', fibers, stage, }, ], })); }, }; window.React = React; window.ReactNoop = ReactNoop; window.expect = () => ({ toBe() {}, toContain() {}, toEqual() {}, }); window.log = s => (currentStage = s); // eslint-disable-next-line eval( window.Babel.transform(code, { presets: ['react', 'es2015'], }).code ); } handleEdit = e => { e.preventDefault(); this.setState({ isEditing: true, }); }; handleCloseEdit = nextCode => { localStorage.setItem('fiber-debugger-code', nextCode); this.setState({ isEditing: false, history: [], currentStep: 0, code: nextCode, }); this.runCode(nextCode); }; render() { const {history, currentStep, isEditing, code} = this.state; if (isEditing) { return <Editor code={code} onClose={this.handleCloseEdit} />; } const {fibers, action, stage} = history[currentStep] || {}; let friendlyAction; if (fibers) { let wipFiber = fibers.descriptions[fibers.workInProgressID]; let friendlyFiber = wipFiber.type || wipFiber.tag + ' #' + wipFiber.id; friendlyAction = `After ${action} on ${friendlyFiber}`; } return ( <div style={{height: '100%'}}> {fibers && ( <Draggable> <Fibers fibers={fibers} show={this.state.show} graphSettings={this.state.graphSettings} /> </Draggable> )} <div style={{ width: '100%', textAlign: 'center', position: 'fixed', bottom: 0, padding: 10, zIndex: 1, backgroundColor: '#fafafa', border: '1px solid #ccc', }}> <div style={{width: '50%', float: 'left'}}> <input type="range" style={{width: '25%'}} min={0} max={history.length - 1} value={currentStep} onChange={e => this.setState({currentStep: Number(e.target.value)}) } /> <p> Step {currentStep}: {friendlyAction} ( <a style={{color: 'gray'}} onClick={this.handleEdit} href="#"> Edit </a> ) </p> {stage && <p>Stage: {stage}</p>} {Object.keys(this.state.show).map(key => ( <label style={{marginRight: '10px'}} key={key}> <input type="checkbox" checked={this.state.show[key]} onChange={e => { this.setState(({show}) => ({ show: {...show, [key]: !show[key]}, })); }} /> {key} </label> ))} </div> <div style={{width: '50%', float: 'right'}}> <h5>Graph Settings</h5> <p> <label style={{display: ''}}> Direction: <select onChange={e => { const rankdir = e.target.value; this.setState(({graphSettings}) => ({ graphSettings: {...graphSettings, rankdir}, })); }}> <option value="TB">top-down</option> <option value="BT">down-top</option> <option value="LR">left-right</option> <option value="RL">right-left</option> </select> </label> </p> <p> <label style={{marginRight: '10px'}}> <input type="checkbox" checked={this.state.graphSettings.trackActive} onChange={e => { this.setState(({graphSettings}) => ({ graphSettings: { ...graphSettings, trackActive: !graphSettings.trackActive, }, })); }} /> Track active fiber </label> </p> </div> </div> </div> ); } } export default App;
import demoTest from '../../../tests/shared/demoTest'; demoTest('badge');
/** * Copyright (c) 2008-2011 The Open Planning Project * * Published under the GPL license. * See https://github.com/opengeo/gxp/raw/master/license.txt for the full text * of the license. */ /** api: (define) * module = gxp * class = GoogleEarthPanel * base_link = `Ext.Panel <http://extjs.com/deploy/dev/docs/?class=Ext.Panel>`_ */ Ext.namespace("gxp"); /** api: constructor * .. class:: GoogleEarthPanel(config) * * Create a panel for showing a 3D visualization of * a map with the Google Earth plugin. * See http://code.google.com/apis/earth/ for plugin api * documentation. */ gxp.GoogleEarthPanel = Ext.extend(Ext.Panel, { /** * Google Earth's horizontal field of view, in radians. (30 degrees) * This was not pulled from any documentation; it was chosen simply * by it's nice, even number, as well as its appearance to actually * work. */ HORIZONTAL_FIELD_OF_VIEW: (30 * Math.PI) / 180, /** api: config[flyToSpeed] * ``Number`` * Specifies the speed (0.0 to 5.0) at which the camera moves to the * target extent. Set to null to use the Google Earth default. By default * we show the target extent immediately, without flying to it. */ /** private: property[map] * ``OpenLayers.Map`` * The OpenLayers map associated with this panel. Defaults * to the map of the configured MapPanel */ map: null, /** api: config[mapPanel] * ``GeoExt.MapPanel | String`` * The map panel associated with this panel. If a MapPanel instance is * not provided, a MapPanel id must be provided. */ mapPanel: null, /** private: property[layers] * :class:`GeoExt.data.LayerStore` A store containing * :class:`GeoExt.data.LayerRecord` objects. */ layers: null, /** private: property[earth] * The Google Earth object. */ earth: null, //currently always set to 4326? projection: null, layerCache: null, /** private: method[initComponent] * Initializes the Google Earth panel. */ initComponent: function() { this.addEvents( /** api: event[beforeadd] * Fires before a layer is added to the 3D view. If a listener * returns ``false``, the layer will not be added. Listeners * will be called with a single argument: the layer record. */ "beforeadd", /** api: event[pluginfailure] * Fires when there is a failure creating the instance. Listeners * will receive two arguments: this plugin and the failure code * (see the Google Earth API docs for details on the failure codes). */ "pluginfailure", /** api: event[pluginready] * Fires when the instance is ready. Listeners will receive one * argument: the GEPlugin instance. */ "pluginready" ); gxp.GoogleEarthPanel.superclass.initComponent.call(this); var mapPanel = this.mapPanel; if (mapPanel && !(mapPanel instanceof GeoExt.MapPanel)) { mapPanel = Ext.getCmp(mapPanel); } if (!mapPanel) { throw new Error("Could not get map panel from config: " + this.mapPanel); } this.map = mapPanel.map; this.layers = mapPanel.layers; this.projection = new OpenLayers.Projection("EPSG:4326"); this.on("render", this.onRenderEvent, this); this.on("show", this.onShowEvent, this); this.on("hide", function() { if (this.earth != null) { this.updateMap(); } // Remove the plugin from the dom. this.body.dom.innerHTML = ""; this.earth = null; }, this); }, /** private: method[onEarthReady] * Runs when Google Earth instance is ready. Adds layer * store handlers. */ onEarthReady: function(object){ this.earth = object; if (this.flyToSpeed === undefined) { // We don't want to fly. Just go to the right spot immediately. this.earth.getOptions().setFlyToSpeed(this.earth.SPEED_TELEPORT); } else if (this.flyToSpeed !== null) { this.earth.getOptions().setFlyToSpeed(this.flyToSpeed); } // Set the extent of the earth to be that shown in OpenLayers. this.resetCamera(); this.setExtent(this.map.getExtent()); // Show the navigation control, and make it so it is on the left. // Not actually sure how the second to fourth lines make that happen, // but hey -- it works. :) this.earth.getNavigationControl().setVisibility(this.earth.VISIBILITY_SHOW); var screenXY = this.earth.getNavigationControl().getScreenXY(); screenXY.setXUnits(this.earth.UNITS_PIXELS); screenXY.setYUnits(this.earth.UNITS_INSET_PIXELS); // Show the plugin. this.earth.getWindow().setVisibility(true); this.layers.each(function(record) { this.addLayer(record); }, this); this.layers.on("remove", this.updateLayers, this); this.layers.on("update", this.updateLayers, this); this.layers.on("add", this.updateLayers, this); this.fireEvent("pluginready", this.earth); // Set up events. Notice global google namespace. // google.earth.addEventListener(this.earth.getView(), // "viewchangeend", // this.updateMap.createDelegate(this)); }, /** private: method[onRenderEvent] * Unfortunately, Ext does not call show() if the component is initally * displayed, so we need to fake it. * We can't call this method onRender because Ext has already stolen * the name for internal use :-( */ onRenderEvent: function() { var isCard = this.ownerCt && this.ownerCt.layout instanceof Ext.layout.CardLayout; if (!this.hidden && !isCard) { this.onShowEvent(); } }, /** private: method[onShowEvent] * Unfortunately, the Google Earth plugin does not like to be hidden. * No matter whether you hide it through CSS visibility, CSS offsets, * or CSS display = none, the Google Earth plugin will show an error * message when it is re-enabled. To counteract this, we delete * the instance and create a new one each time. * We can't call this method onShow because Ext has already stolen * the name for internal use :-( */ onShowEvent: function() { if (this.rendered) { this.layerCache = {}; // Wrap in try/catch to ensure can use rest of map offline try { google.earth.createInstance( this.body.dom, this.onEarthReady.createDelegate(this), (function(code) { this.fireEvent("pluginfailure", this, code); }).createDelegate(this) ); } catch(err) {} } }, /** */ beforeDestroy: function() { this.layers.un("remove", this.updateLayers, this); this.layers.un("update", this.updateLayers, this); this.layers.un("add", this.updateLayers, this); gxp.GoogleEarthPanel.superclass.beforeDestroy.call(this); }, /** private: method[updateLayers] * Synchronizes the 3D visualization with the * configured layer store. */ updateLayers: function() { if (!this.earth) return; // Wrap in try/catch to avoid "Bad NPObject as private data!" try { var features = this.earth.getFeatures(); } catch(err) { return; } var f = features.getFirstChild(); while (f != null) { features.removeChild(f); f = features.getFirstChild(); } this.layers.each(function(record) { this.addLayer(record); }, this); }, /** private: method[addLayer] * Adds a layer to the 3D visualization. */ addLayer: function(layer, order) { var lyr = layer.getLayer(); var ows = (lyr && lyr.url); if (this.earth && lyr instanceof OpenLayers.Layer.WMS && typeof ows == "string") { var add = this.fireEvent("beforeadd", layer); if (add !== false) { var name = lyr.id; var networkLink; if (this.layerCache[name]) { networkLink = this.layerCache[name]; } else { var link = this.earth.createLink('kl_' + name); ows = ows.replace(/\?.*/, ''); var params = lyr.params; var kmlPath = '/kml?mode=refresh&layers=' + params.LAYERS + "&styles=" + params.STYLES; link.setHref(ows + kmlPath); networkLink = this.earth.createNetworkLink('nl_' + name); networkLink.setName(name); networkLink.set(link, false, false); this.layerCache[name] = networkLink; } networkLink.setVisibility(lyr.getVisibility()); if (order !== undefined && order < this.earth.getFeatures().getChildNodes().getLength()) { this.earth.getFeatures(). insertBefore(this.earth.getFeatures().getChildNodes().item(order)); } else { this.earth.getFeatures().appendChild(networkLink); } } } }, /** private: method[setExtent] * Sets the view of the 3D visualization to approximate an OpenLayers extent. */ setExtent: function(extent) { extent = extent.transform(this.map.getProjectionObject(), this.projection); var center = extent.getCenterLonLat(); var width = this.getExtentWidth(extent); // Calculate height of the camera from the ground, in meters. var height = width / (2 * Math.tan(this.HORIZONTAL_FIELD_OF_VIEW)); var lookAt = this.earth.getView().copyAsLookAt(this.earth.ALTITUDE_RELATIVE_TO_GROUND); lookAt.setLatitude(center.lat); lookAt.setLongitude(center.lon); lookAt.setRange(height); this.earth.getView().setAbstractView(lookAt); }, resetCamera: function() { var camera = this.earth.getView().copyAsCamera(this.earth.ALTITUDE_RELATIVE_TO_GROUND); camera.setRoll(0); camera.setHeading(0); camera.setTilt(0); this.earth.getView().setAbstractView(camera); }, /** private: method[getExtent] * Gets an OpenLayers.Bounds that approximates the visable area of * 3D visualization. */ getExtent: function() { var geBounds = this.earth.getView().getViewportGlobeBounds(); var olBounds = new OpenLayers.Bounds( geBounds.getWest(), geBounds.getSouth(), geBounds.getEast(), geBounds.getNorth() ); return olBounds; }, /** private: method[updateMap] */ updateMap: function() { // Get the center of the map from GE. We let GE get the center (as opposed to getting // the extent and then finding the center) because it'll find the correct visual // center represented by the globe, taking into account spherical calculations. var lookAt = this.earth.getView().copyAsLookAt(this.earth.ALTITUDE_RELATIVE_TO_GROUND); var center = this.reprojectToMap( new OpenLayers.LonLat(lookAt.getLongitude(), lookAt.getLatitude()) ); // Zoom to the closest zoom level for the extent given by GE's getViewPortGlobeBounds(). // Then recenter based on the visual center shown in GE. var geExtent = this.reprojectToMap(this.getExtent()); this.map.zoomToExtent(geExtent, true); this.map.setCenter(center); // Slight dirty hack -- // GE's getViewPortGlobeBounds() function gives us an extent larger than what OL // should show, sometimes with more data. This extent works most of the time when OL // tries to find the closest zoom level, but on some edge cases it zooms out // one zoom level too far. To counteract this, we calculate the geodetic width that // we expect GE to show (note: this is the opposite of the setExtent() calculations), // and then compare that width to that of the current zoom level and one zoom level // closer. If the next zoom level shows a geodetic width that's nearer to the width // we expect, then we zoom to that zoom level. // // Big note: This expects a map that has fractional zoom disabled! var height = lookAt.getRange(); var width = 2 * height * Math.tan(this.HORIZONTAL_FIELD_OF_VIEW); var nextResolution = this.map.getResolutionForZoom(this.map.getZoom() + 1); var currentExtent = this.map.getExtent(); var nextExtent = new OpenLayers.Bounds( center.lon - (this.map.getSize().w / 2 * nextResolution), center.lat + (this.map.getSize().h / 2 * nextResolution), center.lon + (this.map.getSize().w / 2 * nextResolution), center.lat - (this.map.getSize().h / 2 * nextResolution) ); var currentWidthDiff = Math.abs(this.getExtentWidth(currentExtent) - width); var nextWidthDiff = Math.abs(this.getExtentWidth(nextExtent) - width); if (nextWidthDiff < currentWidthDiff) { this.map.zoomTo(this.map.getZoom() + 1); } }, /** private: method[getExentWidth] */ getExtentWidth: function(extent) { var center = extent.getCenterLonLat(); var middleLeft = new OpenLayers.LonLat(extent.left, center.lat); var middleRight = new OpenLayers.LonLat(extent.right, center.lat); return OpenLayers.Util.distVincenty(middleLeft, middleRight) * 1000; }, /** private: method[reprojectToGE] */ reprojectToGE: function(data) { return data.clone().transform(this.map.getProjectionObject(), this.projection); }, /** private: method[reprojectToMap] */ reprojectToMap: function(data) { return data.clone().transform(this.projection, this.map.getProjectionObject()); } }); /** api: xtype = gxp_googleearthpanel */ Ext.reg("gxp_googleearthpanel", gxp.GoogleEarthPanel);
// Duplicate exports are an early/parse error export function foo() {}; export class foo {};
/*! * React Popper 0.5.0 * https://github.com/souporserious/react-popper * Copyright (c) 2017 React Popper Authors */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react")); else if(typeof define === 'function' && define.amd) define(["react"], factory); else if(typeof exports === 'object') exports["ReactPopper"] = factory(require("react")); else root["ReactPopper"] = factory(root["React"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_2__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Arrow = exports.Popper = exports.Target = exports.Manager = undefined; var _Manager2 = __webpack_require__(1); var _Manager3 = _interopRequireDefault(_Manager2); var _Target2 = __webpack_require__(12); var _Target3 = _interopRequireDefault(_Target2); var _Popper2 = __webpack_require__(13); var _Popper3 = _interopRequireDefault(_Popper2); var _Arrow2 = __webpack_require__(17); var _Arrow3 = _interopRequireDefault(_Arrow2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.Manager = _Manager3.default; exports.Target = _Target3.default; exports.Popper = _Popper3.default; exports.Arrow = _Arrow3.default; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { '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 _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(3); var _propTypes2 = _interopRequireDefault(_propTypes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Manager = function (_Component) { _inherits(Manager, _Component); function Manager() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Manager); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Manager.__proto__ || Object.getPrototypeOf(Manager)).call.apply(_ref, [this].concat(args))), _this), _this._setTargetNode = function (node) { _this._targetNode = node; }, _this._getTargetNode = function () { return _this._targetNode; }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Manager, [{ key: 'getChildContext', value: function getChildContext() { return { popperManager: { setTargetNode: this._setTargetNode, getTargetNode: this._getTargetNode } }; } }, { key: 'render', value: function render() { var _props = this.props, tag = _props.tag, children = _props.children, restProps = _objectWithoutProperties(_props, ['tag', 'children']); if (tag !== false) { return (0, _react.createElement)(tag, restProps, children); } else { return children; } } }]); return Manager; }(_react.Component); Manager.childContextTypes = { popperManager: _propTypes2.default.object.isRequired }; Manager.propTypes = { tag: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.bool]) }; Manager.defaultProps = { tag: 'div' }; exports.default = Manager; /***/ }, /* 2 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_2__; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; 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; }; /** * Copyright 2013-present, 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. */ if (process.env.NODE_ENV !== 'production') { var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol.for && Symbol.for('react.element') || 0xeac7; var isValidElement = function isValidElement(object) { return (typeof object === 'undefined' ? 'undefined' : _typeof(object)) === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; // By explicitly using `prop-types` you are opting into new development behavior. // http://fb.me/prop-types-in-prod var throwOnDirectAccess = true; module.exports = __webpack_require__(5)(isValidElement, throwOnDirectAccess); } else { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod module.exports = __webpack_require__(11)(); } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4))) /***/ }, /* 4 */ /***/ function(module, exports) { 'use strict'; // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout() { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } })(); function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch (e) { try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch (e) { // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e) { try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e) { // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while (len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/'; }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function () { return 0; }; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, 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. */ 'use strict'; 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 emptyFunction = __webpack_require__(6); var invariant = __webpack_require__(7); var warning = __webpack_require__(8); var ReactPropTypesSecret = __webpack_require__(9); var checkPropTypes = __webpack_require__(10); module.exports = function (isValidElement, throwOnDirectAccess) { /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; // Important! // Keep this list in sync with production version in `./factoryWithThrowingShims.js`. var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), symbol: createPrimitiveTypeChecker('symbol'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker }; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ /*eslint-disable no-self-compare*/ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /*eslint-enable no-self-compare*/ /** * We use an Error-like object for backward compatibility as people may call * PropTypes directly and inspect their output. However, we don't use real * Errors anymore. We don't inspect their stack anyway, and creating them * is prohibitively expensive if they are created too often, such as what * happens in oneOfType() for any type before the one that matched. */ function PropTypeError(message) { this.message = message; this.stack = ''; } // Make `instanceof Error` still work for returned errors. PropTypeError.prototype = Error.prototype; function createChainableTypeChecker(validate) { if (process.env.NODE_ENV !== 'production') { var manualPropTypeCallCache = {}; var manualPropTypeWarningCount = 0; } function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (secret !== ReactPropTypesSecret) { if (throwOnDirectAccess) { // New behavior only for users of `prop-types` package invariant(false, 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use `PropTypes.checkPropTypes()` to call them. ' + 'Read more at http://fb.me/use-check-prop-types'); } else if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined') { // Old behavior for people using React.PropTypes var cacheKey = componentName + ':' + propName; if (!manualPropTypeCallCache[cacheKey] && // Avoid spamming the console because they are often not actionable except for lib authors manualPropTypeWarningCount < 3) { warning(false, 'You are manually calling a React.PropTypes validation ' + 'function for the `%s` prop on `%s`. This is deprecated ' + 'and will throw in the standalone `prop-types` package. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.', propFullName, componentName); manualPropTypeCallCache[cacheKey] = true; manualPropTypeWarningCount++; } } } if (props[propName] == null) { if (isRequired) { if (props[propName] === null) { return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.')); } return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName, secret) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunction.thatReturnsNull); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!isValidElement(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.')); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0; return emptyFunction.thatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (is(propValue, expectedValues[i])) { return null; } } var valuesString = JSON.stringify(expectedValues); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (propValue.hasOwnProperty(key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0; return emptyFunction.thatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) { return null; } } return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue === 'undefined' ? 'undefined' : _typeof(propValue)) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } function isSymbol(propType, propValue) { // Native Symbol. if (propType === 'symbol') { return true; } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' if (propValue['@@toStringTag'] === 'Symbol') { return true; } // Fallback for non-spec compliant Symbols which are polyfilled. if (typeof Symbol === 'function' && propValue instanceof Symbol) { return true; } return false; } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue === 'undefined' ? 'undefined' : _typeof(propValue); if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } if (isSymbol(propType, propValue)) { return 'symbol'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } ReactPropTypes.checkPropTypes = checkPropTypes; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4))) /***/ }, /* 6 */ /***/ function(module, exports) { "use strict"; /** * Copyright (c) 2013-present, 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. * * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ var emptyFunction = function emptyFunction() {}; emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; module.exports = emptyFunction; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright (c) 2013-present, 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. * */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var validateFormat = function validateFormat(format) {}; if (process.env.NODE_ENV !== 'production') { validateFormat = function validateFormat(format) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } }; } function invariant(condition, format, a, b, c, d, e, f) { validateFormat(format); if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } module.exports = invariant; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4))) /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-2015, 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. * */ 'use strict'; var emptyFunction = __webpack_require__(6); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if (process.env.NODE_ENV !== 'production') { (function () { var printWarning = function printWarning(format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; warning = function warning(condition, format) { if (format === undefined) { throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; })(); } module.exports = warning; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4))) /***/ }, /* 9 */ /***/ function(module, exports) { /** * Copyright 2013-present, 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. */ 'use strict'; var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, 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. */ 'use strict'; 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; }; if (process.env.NODE_ENV !== 'production') { var invariant = __webpack_require__(7); var warning = __webpack_require__(8); var ReactPropTypesSecret = __webpack_require__(9); var loggedTypeFailures = {}; } /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?Function} getStack Returns the component stack. * @private */ function checkPropTypes(typeSpecs, values, location, componentName, getStack) { if (process.env.NODE_ENV !== 'production') { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. invariant(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', location, typeSpecName); error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error === 'undefined' ? 'undefined' : _typeof(error)); if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var stack = getStack ? getStack() : ''; warning(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : ''); } } } } } module.exports = checkPropTypes; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4))) /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, 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. */ 'use strict'; var emptyFunction = __webpack_require__(6); var invariant = __webpack_require__(7); module.exports = function () { // Important! // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. function shim() { invariant(false, 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use PropTypes.checkPropTypes() to call them. ' + 'Read more at http://fb.me/use-check-prop-types'); }; shim.isRequired = shim; function getShim() { return shim; }; var ReactPropTypes = { array: shim, bool: shim, func: shim, number: shim, object: shim, string: shim, symbol: shim, any: shim, arrayOf: getShim, element: shim, instanceOf: getShim, node: shim, objectOf: getShim, oneOf: getShim, oneOfType: getShim, shape: getShim }; ReactPropTypes.checkPropTypes = emptyFunction; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); 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 _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(3); var _propTypes2 = _interopRequireDefault(_propTypes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var Target = function Target(props, context) { var _props$tag = props.tag, tag = _props$tag === undefined ? 'div' : _props$tag, innerRef = props.innerRef, children = props.children, restProps = _objectWithoutProperties(props, ['tag', 'innerRef', 'children']); var popperManager = context.popperManager; var targetRef = function targetRef(node) { return popperManager.setTargetNode(node); }; if (typeof children === 'function') { return children({ targetRef: targetRef }); } return (0, _react.createElement)(tag, _extends({ ref: function ref(node) { targetRef(node); if (typeof innerRef === 'function') { innerRef(node); } } }, restProps), children); }; Target.contextTypes = { popperManager: _propTypes2.default.object.isRequired }; Target.propTypes = { tag: _propTypes2.default.string, innerRef: _propTypes2.default.func, children: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func]) }; exports.default = Target; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); 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 _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 _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(3); var _propTypes2 = _interopRequireDefault(_propTypes); var _popper = __webpack_require__(14); var _popper2 = _interopRequireDefault(_popper); var _lodash = __webpack_require__(15); var _lodash2 = _interopRequireDefault(_lodash); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var noop = function noop() { return null; }; var Popper = function (_Component) { _inherits(Popper, _Component); function Popper() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Popper); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Popper.__proto__ || Object.getPrototypeOf(Popper)).call.apply(_ref, [this].concat(args))), _this), _this.state = {}, _this._setArrowNode = function (node) { _this._arrowNode = node; }, _this._getTargetNode = function () { return _this.context.popperManager.getTargetNode(); }, _this._updateStateModifier = { enabled: true, order: 900, function: function _function(data) { if (_this.state.data && !(0, _lodash2.default)(data.offsets, _this.state.data.offsets) || !_this.state.data) { _this.setState({ data: data }); } return data; } }, _this._getPopperStyle = function () { var data = _this.state.data; // If Popper isn't instantiated, hide the popperElement // to avoid flash of unstyled content if (!_this._popper || !data) { return { position: 'absolute', pointerEvents: 'none', opacity: 0 }; } var _data$offsets$popper = data.offsets.popper, top = _data$offsets$popper.top, left = _data$offsets$popper.left, position = _data$offsets$popper.position; return _extends({ position: position, top: 0, left: 0, transform: 'translate3d(' + Math.round(left) + 'px, ' + Math.round(top) + 'px, 0px)', willChange: 'transform' }, data.styles); }, _this._getPopperPlacement = function () { return !!_this.state.data ? _this.state.data.placement : undefined; }, _this._getArrowStyle = function () { if (!_this.state.data || !_this.state.data.offsets.arrow) { return {}; } else { var _this$state$data$offs = _this.state.data.offsets.arrow, top = _this$state$data$offs.top, left = _this$state$data$offs.left; if (!left) { return { top: +top }; } else { return { left: +left }; } } }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Popper, [{ key: 'getChildContext', value: function getChildContext() { return { popper: { setArrowNode: this._setArrowNode, getArrowStyle: this._getArrowStyle } }; } }, { key: 'componentDidMount', value: function componentDidMount() { this._updatePopper(); } }, { key: 'componentDidUpdate', value: function componentDidUpdate(lastProps) { if (lastProps.placement !== this.props.placement || lastProps.eventsEnabled !== this.props.eventsEnabled) { this._updatePopper(); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this._destroyPopper(); } }, { key: '_updatePopper', value: function _updatePopper() { this._destroyPopper(); if (this._node) { this._createPopper(); } } }, { key: '_createPopper', value: function _createPopper() { var _props = this.props, placement = _props.placement, eventsEnabled = _props.eventsEnabled; var modifiers = _extends({}, this.props.modifiers, { applyStyle: { enabled: false }, updateState: this._updateStateModifier }); if (this._arrowNode) { modifiers.arrow = { element: this._arrowNode }; } this._popper = new _popper2.default(this._getTargetNode(), this._node, { placement: placement, eventsEnabled: eventsEnabled, modifiers: modifiers }); // schedule an update to make sure everything gets positioned correct // after being instantiated this._popper.scheduleUpdate(); } }, { key: '_destroyPopper', value: function _destroyPopper() { if (this._popper) { this._popper.destroy(); } } }, { key: 'render', value: function render() { var _this2 = this; var _props2 = this.props, tag = _props2.tag, innerRef = _props2.innerRef, placement = _props2.placement, eventsEnabled = _props2.eventsEnabled, modifiers = _props2.modifiers, style = _props2.style, children = _props2.children, restProps = _objectWithoutProperties(_props2, ['tag', 'innerRef', 'placement', 'eventsEnabled', 'modifiers', 'style', 'children']); var popperRef = function popperRef(node) { _this2._node = node; }; var popperStyle = _extends({}, this._getPopperStyle(), style); var popperPlacement = this._getPopperPlacement(); if (typeof children === 'function') { return children({ popperRef: popperRef, popperStyle: popperStyle, popperPlacement: popperPlacement }); } return (0, _react.createElement)(tag, _extends({ ref: function ref(node) { popperRef(node); if (typeof innerRef === 'function') { innerRef(node); } }, style: popperStyle, 'data-placement': popperPlacement }, restProps), children); } }]); return Popper; }(_react.Component); Popper.contextTypes = { popperManager: _propTypes2.default.object.isRequired }; Popper.childContextTypes = { popper: _propTypes2.default.object.isRequired }; Popper.propTypes = { tag: _propTypes2.default.string, innerRef: _propTypes2.default.func, placement: _propTypes2.default.oneOf(_popper2.default.placements), eventsEnabled: _propTypes2.default.bool, modifiers: _propTypes2.default.object, children: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func]) }; Popper.defaultProps = { tag: 'div', placement: 'bottom', eventsEnabled: true, modifiers: {} }; exports.default = Popper; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict'; 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; }; /**! * @fileOverview Kickass library to create and place poppers near their reference elements. * @version 1.0.8 * @license * Copyright (c) 2016 Federico Zivolo and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ (function (global, factory) { ( false ? 'undefined' : _typeof(exports)) === 'object' && typeof module !== 'undefined' ? module.exports = factory() : true ? !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) : global.Popper = factory(); })(undefined, function () { 'use strict'; /** * Returns the offset parent of the given element * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Element} offset parent */ function getOffsetParent(element) { // NOTE: 1 DOM access here var offsetParent = element.offsetParent; var nodeName = offsetParent && offsetParent.nodeName; if (!nodeName || nodeName === 'BODY' || nodeName === 'HTML') { return window.document.documentElement; } return offsetParent; } /** * Get CSS computed property of the given element * @method * @memberof Popper.Utils * @argument {Eement} element * @argument {String} property */ function getStyleComputedProperty(element, property) { if (element.nodeType !== 1) { return []; } // NOTE: 1 DOM access here var css = window.getComputedStyle(element, null); return property ? css[property] : css; } /** * Returns the parentNode or the host of the element * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Element} parent */ function getParentNode(element) { if (element.nodeName === 'HTML') { return element; } return element.parentNode || element.host; } /** * Returns the scrolling parent of the given element * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Element} scroll parent */ function getScrollParent(element) { // Return body, `getScroll` will take care to get the correct `scrollTop` from it if (!element || ['HTML', 'BODY', '#document'].indexOf(element.nodeName) !== -1) { return window.document.body; } // Firefox want us to check `-x` and `-y` variations as well var _getStyleComputedProp = getStyleComputedProperty(element), overflow = _getStyleComputedProp.overflow, overflowX = _getStyleComputedProp.overflowX, overflowY = _getStyleComputedProp.overflowY; if (/(auto|scroll)/.test(overflow + overflowY + overflowX)) { return element; } return getScrollParent(getParentNode(element)); } /** * Check if the given element is fixed or is inside a fixed parent * @method * @memberof Popper.Utils * @argument {Element} element * @argument {Element} customContainer * @returns {Boolean} answer to "isFixed?" */ function isFixed(element) { var nodeName = element.nodeName; if (nodeName === 'BODY' || nodeName === 'HTML') { return false; } if (getStyleComputedProperty(element, 'position') === 'fixed') { return true; } return isFixed(getParentNode(element)); } /** * Helper used to get the position which will be applied to the popper * @method * @memberof Popper.Utils * @param {HTMLElement} element - popper element * @returns {String} position */ function getPosition(element) { var container = getOffsetParent(element); // Decide if the popper will be fixed // If the reference element is inside a fixed context, the popper will be fixed as well to allow them to scroll together var isParentFixed = isFixed(container); return isParentFixed ? 'fixed' : 'absolute'; } /* * Helper to detect borders of a given element * @method * @memberof Popper.Utils * @param {CSSStyleDeclaration} styles - result of `getStyleComputedProperty` on the given element * @param {String} axis - `x` or `y` * @return {Number} borders - the borders size of the given axis */ function getBordersSize(styles, axis) { var sideA = axis === 'x' ? 'Left' : 'Top'; var sideB = sideA === 'Left' ? 'Right' : 'Bottom'; return Number(styles['border' + sideA + 'Width'].split('px')[0]) + Number(styles['border' + sideB + 'Width'].split('px')[0]); } /** * Get bounding client rect of given element * @method * @memberof Popper.Utils * @param {HTMLElement} element * @return {Object} client rect */ function getBoundingClientRect(element) { var isIE10 = navigator.appVersion.indexOf('MSIE 10') !== -1; var rect = void 0; // IE10 10 FIX: Please, don't ask, the element isn't // considered in DOM in some circumstances... // This isn't reproducible in IE10 compatibility mode of IE11 if (isIE10) { try { rect = element.getBoundingClientRect(); } catch (err) { rect = {}; } } else { rect = element.getBoundingClientRect(); } var result = { left: rect.left, top: rect.top, right: rect.right, bottom: rect.bottom, width: rect.right - rect.left, height: rect.bottom - rect.top }; // IE10 FIX: `getBoundingClientRect`, when executed on `documentElement` // will not take in account the `scrollTop` and `scrollLeft` if (element.nodeName === 'HTML' && isIE10) { var _window$document$docu = window.document.documentElement, scrollTop = _window$document$docu.scrollTop, scrollLeft = _window$document$docu.scrollLeft; result.top -= scrollTop; result.bottom -= scrollTop; result.left -= scrollLeft; result.right -= scrollLeft; } // subtract scrollbar size from sizes var horizScrollbar = rect.width - (element.clientWidth || rect.right - rect.left); var vertScrollbar = rect.height - (element.clientHeight || rect.bottom - rect.top); // if an hypothetical scrollbar is detected, we must be sure it's not a `border` // we make this check conditional for performance reasons if (horizScrollbar || vertScrollbar) { var styles = getStyleComputedProperty(element); horizScrollbar -= getBordersSize(styles, 'x'); vertScrollbar -= getBordersSize(styles, 'y'); } result.right -= horizScrollbar; result.width -= horizScrollbar; result.bottom -= vertScrollbar; result.height -= vertScrollbar; return result; } function getScroll(element) { var side = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'top'; var upperSide = side === 'top' ? 'scrollTop' : 'scrollLeft'; var nodeName = element.nodeName; if (nodeName === 'BODY' || nodeName === 'HTML') { var html = window.document.documentElement; var scrollingElement = window.document.scrollingElement || html; return scrollingElement[upperSide]; } return element[upperSide]; } /* * Sum or subtract the element scroll values (left and top) from a given rect object * @method * @memberof Popper.Utils * @param {Object} rect - Rect object you want to change * @param {HTMLElement} element - The element from the function reads the scroll values * @param {Boolean} subtract - set to true if you want to subtract the scroll values * @return {Object} rect - The modifier rect object */ function includeScroll(rect, element) { var subtract = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var scrollTop = getScroll(element, 'top'); var scrollLeft = getScroll(element, 'left'); var modifier = subtract ? -1 : 1; rect.top += scrollTop * modifier; rect.bottom += scrollTop * modifier; rect.left += scrollLeft * modifier; rect.right += scrollLeft * modifier; return rect; } /** * Given an element and one of its parents, return the offset * @method * @memberof Popper.Utils * @param {HTMLElement} element * @param {HTMLElement} parent * @return {Object} rect */ function getOffsetRectRelativeToCustomParent(element, parent) { var fixed = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var transformed = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; var scrollParent = getScrollParent(parent); var elementRect = getBoundingClientRect(element); var parentRect = getBoundingClientRect(parent); var rect = { top: elementRect.top - parentRect.top, left: elementRect.left - parentRect.left, bottom: elementRect.top - parentRect.top + elementRect.height, right: elementRect.left - parentRect.left + elementRect.width, width: elementRect.width, height: elementRect.height }; if (fixed && !transformed) { rect = includeScroll(rect, scrollParent, true); } // When a popper doesn't have any positioned or scrollable parents, `offsetParent.contains(scrollParent)` // will return a "false positive". This is happening because `getOffsetParent` returns `html` node, // and `scrollParent` is the `body` node. Hence the additional check. else if (getOffsetParent(element).contains(scrollParent) && scrollParent.nodeName !== 'BODY') { rect = includeScroll(rect, parent); } // subtract borderTopWidth and borderTopWidth from final result var styles = getStyleComputedProperty(parent); var borderTopWidth = Number(styles.borderTopWidth.split('px')[0]); var borderLeftWidth = Number(styles.borderLeftWidth.split('px')[0]); rect.top -= borderTopWidth; rect.bottom -= borderTopWidth; rect.left -= borderLeftWidth; rect.right -= borderLeftWidth; return rect; } function getWindowSizes() { var body = window.document.body; var html = window.document.documentElement; return { height: Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight), width: Math.max(body.scrollWidth, body.offsetWidth, html.clientWidth, html.scrollWidth, html.offsetWidth) }; } /** * Get the position of the given element, relative to its offset parent * @method * @memberof Popper.Utils * @param {Element} element * @return {Object} position - Coordinates of the element and its `scrollTop` */ function getOffsetRect(element) { var elementRect = void 0; if (element.nodeName === 'HTML') { var _getWindowSizes = getWindowSizes(), width = _getWindowSizes.width, height = _getWindowSizes.height; elementRect = { width: width, height: height, left: 0, top: 0 }; } else { elementRect = { width: element.offsetWidth, height: element.offsetHeight, left: element.offsetLeft, top: element.offsetTop }; } elementRect.right = elementRect.left + elementRect.width; elementRect.bottom = elementRect.top + elementRect.height; // position return elementRect; } function getOffsetRectRelativeToViewport(element) { // Offset relative to offsetParent var relativeOffset = getOffsetRect(element); if (element.nodeName !== 'HTML') { var offsetParent = getOffsetParent(element); var parentOffset = getOffsetRectRelativeToViewport(offsetParent); var offset = { width: relativeOffset.offsetWidth, height: relativeOffset.offsetHeight, left: relativeOffset.left + parentOffset.left, top: relativeOffset.top + parentOffset.top, right: relativeOffset.right - parentOffset.right, bottom: relativeOffset.bottom - parentOffset.bottom }; return offset; } return relativeOffset; } function getTotalScroll(element) { var side = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'top'; var scrollParent = getScrollParent(element); var scroll = getScroll(scrollParent, side); if (['BODY', 'HTML'].indexOf(scrollParent.nodeName) === -1) { return scroll + getTotalScroll(getParentNode(scrollParent), side); } return scroll; } /** * Computed the boundaries limits and return them * @method * @memberof Popper.Utils * @param {Object} data - Object containing the property "offsets" generated by `_getOffsets` * @param {Number} padding - Boundaries padding * @param {Element} boundariesElement - Element used to define the boundaries * @returns {Object} Coordinates of the boundaries */ function getBoundaries(popper, padding, boundariesElement) { // NOTE: 1 DOM access here var boundaries = { top: 0, left: 0 }; var offsetParent = getOffsetParent(popper); // Handle viewport case if (boundariesElement === 'viewport') { var _getOffsetRectRelativ = getOffsetRectRelativeToViewport(offsetParent), left = _getOffsetRectRelativ.left, top = _getOffsetRectRelativ.top; var _window$document$docu = window.document.documentElement, width = _window$document$docu.clientWidth, height = _window$document$docu.clientHeight; if (getPosition(popper) === 'fixed') { boundaries.right = width; boundaries.bottom = height; } else { var scrollLeft = getTotalScroll(popper, 'left'); var scrollTop = getTotalScroll(popper, 'top'); boundaries = { top: 0 - top, right: width - left + scrollLeft, bottom: height - top + scrollTop, left: 0 - left }; } } // Handle other cases based on DOM element used as boundaries else { var boundariesNode = void 0; if (boundariesElement === 'scrollParent') { boundariesNode = getScrollParent(getParentNode(popper)); } else if (boundariesElement === 'window') { boundariesNode = window.document.body; } else { boundariesNode = boundariesElement; } // In case of BODY, we need a different computation if (boundariesNode.nodeName === 'BODY') { var _getWindowSizes = getWindowSizes(), _height = _getWindowSizes.height, _width = _getWindowSizes.width; boundaries.right = _width; boundaries.bottom = _height; } // for all the other DOM elements, this one is good else { boundaries = getOffsetRectRelativeToCustomParent(boundariesNode, offsetParent, isFixed(popper)); } } // Add paddings boundaries.left += padding; boundaries.top += padding; boundaries.right -= padding; boundaries.bottom -= padding; return boundaries; } /** * Utility used to transform the `auto` placement to the placement with more * available space. * @method * @memberof Popper.Utils * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function computeAutoPlacement(placement, refRect, popper) { if (placement.indexOf('auto') === -1) { return placement; } var boundaries = getBoundaries(popper, 0, 'scrollParent'); var sides = { top: refRect.top - boundaries.top, right: boundaries.right - refRect.right, bottom: boundaries.bottom - refRect.bottom, left: refRect.left - boundaries.left }; var computedPlacement = Object.keys(sides).sort(function (a, b) { return sides[b] - sides[a]; })[0]; var variation = placement.split('-')[1]; return computedPlacement + (variation ? '-' + variation : ''); } var nativeHints = ['native code', '[object MutationObserverConstructor]' // for mobile safari iOS 9.0 ]; /** * Determine if a function is implemented natively (as opposed to a polyfill). * @argument {Function | undefined} fn the function to check * @returns {boolean} */ var isNative = function isNative(fn) { return nativeHints.some(function (hint) { return (fn || '').toString().indexOf(hint) > -1; }); }; var isBrowser = typeof window !== 'undefined'; var longerTimeoutBrowsers = ['Edge', 'Trident', 'Firefox']; var timeoutDuration = 0; for (var i = 0; i < longerTimeoutBrowsers.length; i += 1) { if (isBrowser && navigator.userAgent.indexOf(longerTimeoutBrowsers[i]) >= 0) { timeoutDuration = 1; break; } } function microtaskDebounce(fn) { var scheduled = false; var i = 0; var elem = document.createElement('span'); // MutationObserver provides a mechanism for scheduling microtasks, which // are scheduled *before* the next task. This gives us a way to debounce // a function but ensure it's called *before* the next paint. var observer = new MutationObserver(function () { fn(); scheduled = false; }); observer.observe(elem, { attributes: true }); return function () { if (!scheduled) { scheduled = true; elem.setAttribute('x-index', i); i = i + 1; // don't use compund (+=) because it doesn't get optimized in V8 } }; } function taskDebounce(fn) { var scheduled = false; return function () { if (!scheduled) { scheduled = true; setTimeout(function () { scheduled = false; fn(); }, timeoutDuration); } }; } // It's common for MutationObserver polyfills to be seen in the wild, however // these rely on Mutation Events which only occur when an element is connected // to the DOM. The algorithm used in this module does not use a connected element, // and so we must ensure that a *native* MutationObserver is available. var supportsNativeMutationObserver = isBrowser && isNative(window.MutationObserver); /** * Create a debounced version of a method, that's asynchronously deferred * but called in the minimum time possible. * * @method * @memberof Popper.Utils * @argument {Function} fn * @returns {Function} */ var debounce = supportsNativeMutationObserver ? microtaskDebounce : taskDebounce; /** * Mimics the `find` method of Array * @method * @memberof Popper.Utils * @argument {Array} arr * @argument prop * @argument value * @returns index or -1 */ function find(arr, check) { // use native find if supported if (Array.prototype.find) { return arr.find(check); } // use `filter` to obtain the same behavior of `find` return arr.filter(check)[0]; } /** * Return the index of the matching object * @method * @memberof Popper.Utils * @argument {Array} arr * @argument prop * @argument value * @returns index or -1 */ function findIndex(arr, prop, value) { // use native findIndex if supported if (Array.prototype.findIndex) { return arr.findIndex(function (cur) { return cur[prop] === value; }); } // use `find` + `indexOf` if `findIndex` isn't supported var match = find(arr, function (obj) { return obj[prop] === value; }); return arr.indexOf(match); } var classCallCheck = function classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; 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 defineProperty = function defineProperty(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; }; /** * Given the popper offsets, generate an output similar to getBoundingClientRect * @method * @memberof Popper.Utils * @argument {Object} popperOffsets * @returns {Object} ClientRect like output */ function getClientRect(popperOffsets) { return _extends({}, popperOffsets, { right: popperOffsets.left + popperOffsets.width, bottom: popperOffsets.top + popperOffsets.height }); } /** * Get the outer sizes of the given element (offset size + margins) * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Object} object containing width and height properties */ function getOuterSizes(element) { var styles = window.getComputedStyle(element); var x = parseFloat(styles.marginTop) + parseFloat(styles.marginBottom); var y = parseFloat(styles.marginLeft) + parseFloat(styles.marginRight); var result = { width: element.offsetWidth + y, height: element.offsetHeight + x }; return result; } /** * Get the opposite placement of the given one/ * @method * @memberof Popper.Utils * @argument {String} placement * @returns {String} flipped placement */ function getOppositePlacement(placement) { var hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' }; return placement.replace(/left|right|bottom|top/g, function (matched) { return hash[matched]; }); } /** * Get offsets to the popper * @method * @memberof Popper.Utils * @param {Object} position - CSS position the Popper will get applied * @param {HTMLElement} popper - the popper element * @param {Object} referenceOffsets - the reference offsets (the popper will be relative to this) * @param {String} placement - one of the valid placement options * @returns {Object} popperOffsets - An object containing the offsets which will be applied to the popper */ function getPopperOffsets(position, popper, referenceOffsets, placement) { placement = placement.split('-')[0]; // Get popper node sizes var popperRect = getOuterSizes(popper); // Add position, width and height to our offsets object var popperOffsets = { position: position, width: popperRect.width, height: popperRect.height }; // depending by the popper placement we have to compute its offsets slightly differently var isHoriz = ['right', 'left'].indexOf(placement) !== -1; var mainSide = isHoriz ? 'top' : 'left'; var secondarySide = isHoriz ? 'left' : 'top'; var measurement = isHoriz ? 'height' : 'width'; var secondaryMeasurement = !isHoriz ? 'height' : 'width'; popperOffsets[mainSide] = referenceOffsets[mainSide] + referenceOffsets[measurement] / 2 - popperRect[measurement] / 2; if (placement === secondarySide) { popperOffsets[secondarySide] = referenceOffsets[secondarySide] - popperRect[secondaryMeasurement]; } else { popperOffsets[secondarySide] = referenceOffsets[getOppositePlacement(secondarySide)]; } return popperOffsets; } /** * Get offsets to the reference element * @method * @memberof Popper.Utils * @param {Object} state * @param {Element} popper - the popper element * @param {Element} reference - the reference element (the popper will be relative to this) * @returns {Object} An object containing the offsets which will be applied to the popper */ function getReferenceOffsets(state, popper, reference) { var isParentFixed = state.position === 'fixed'; var isParentTransformed = state.isParentTransformed; var offsetParent = getOffsetParent(isParentFixed && isParentTransformed ? reference : popper); return getOffsetRectRelativeToCustomParent(reference, offsetParent, isParentFixed, isParentTransformed); } /** * Get the prefixed supported property name * @method * @memberof Popper.Utils * @argument {String} property (camelCase) * @returns {String} prefixed property (camelCase) */ function getSupportedPropertyName(property) { var prefixes = [false, 'ms', 'webkit', 'moz', 'o']; var upperProp = property.charAt(0).toUpperCase() + property.slice(1); for (var i = 0; i < prefixes.length - 1; i++) { var prefix = prefixes[i]; var toCheck = prefix ? '' + prefix + upperProp : property; if (typeof window.document.body.style[toCheck] !== 'undefined') { return toCheck; } } return null; } /** * Check if the given variable is a function * @method * @memberof Popper.Utils * @argument {*} functionToCheck - variable to check * @returns {Boolean} answer to: is a function? */ function isFunction(functionToCheck) { var getType = {}; return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; } /** * Helper used to know if the given modifier is enabled. * @method * @memberof Popper.Utils * @returns {Boolean} */ function isModifierEnabled(modifiers, modifierName) { return modifiers.some(function (_ref) { var name = _ref.name, enabled = _ref.enabled; return enabled && name === modifierName; }); } /** * Helper used to know if the given modifier depends from another one. * It checks if the needed modifier is listed and enabled. * @method * @memberof Popper.Utils * @param {Array} modifiers - list of modifiers * @param {String} requestingName - name of requesting modifier * @param {String} requestedName - name of requested modifier * @returns {Boolean} */ function isModifierRequired(modifiers, requestingName, requestedName) { var requesting = find(modifiers, function (_ref) { var name = _ref.name; return name === requestingName; }); return !!requesting && modifiers.some(function (modifier) { return modifier.name === requestedName && modifier.enabled && modifier.order < requesting.order; }); } /** * Tells if a given input is a number * @method * @memberof Popper.Utils * @param {*} input to check * @return {Boolean} */ function isNumeric(n) { return n !== '' && !isNaN(parseFloat(n)) && isFinite(n); } /** * Check if the given element has transforms applied to itself or a parent * @method * @memberof Popper.Utils * @param {Element} element * @return {Boolean} answer to "isTransformed?" */ function isTransformed(element) { if (element.nodeName === 'BODY') { return false; } if (getStyleComputedProperty(element, 'transform') !== 'none') { return true; } return getParentNode(element) ? isTransformed(getParentNode(element)) : element; } /** * Remove event listeners used to update the popper position * @method * @memberof Popper.Utils * @private */ function removeEventListeners(reference, state) { // Remove resize event listener on window window.removeEventListener('resize', state.updateBound); // Remove scroll event listener on scroll parents state.scrollParents.forEach(function (target) { target.removeEventListener('scroll', state.updateBound); }); // Reset state state.updateBound = null; state.scrollParents = []; state.scrollElement = null; state.eventsEnabled = false; return state; } /** * Loop trough the list of modifiers and run them in order, each of them will then edit the data object * @method * @memberof Popper.Utils * @param {Object} data * @param {Array} modifiers * @param {Function} ends */ function runModifiers(modifiers, data, ends) { var modifiersToRun = ends === undefined ? modifiers : modifiers.slice(0, findIndex(modifiers, 'name', ends)); modifiersToRun.forEach(function (modifier) { if (modifier.enabled && isFunction(modifier.function)) { data = modifier.function(data, modifier); } }); return data; } /** * Set the attributes to the given popper * @method * @memberof Popper.Utils * @argument {Element} element - Element to apply the attributes to * @argument {Object} styles - Object with a list of properties and values which will be applied to the element */ function setAttributes(element, attributes) { Object.keys(attributes).forEach(function (prop) { var value = attributes[prop]; if (value !== false) { element.setAttribute(prop, attributes[prop]); } else { element.removeAttribute(prop); } }); } /** * Set the style to the given popper * @method * @memberof Popper.Utils * @argument {Element} element - Element to apply the style to * @argument {Object} styles - Object with a list of properties and values which will be applied to the element */ function setStyles(element, styles) { Object.keys(styles).forEach(function (prop) { var unit = ''; // add unit if the value is numeric and is one of the following if (['width', 'height', 'top', 'right', 'bottom', 'left'].indexOf(prop) !== -1 && isNumeric(styles[prop])) { unit = 'px'; } element.style[prop] = styles[prop] + unit; }); } function attachToScrollParents(scrollParent, event, callback, scrollParents) { var isBody = scrollParent.nodeName === 'BODY'; var target = isBody ? window : scrollParent; target.addEventListener(event, callback, { passive: true }); if (!isBody) { attachToScrollParents(getScrollParent(target.parentNode), event, callback, scrollParents); } scrollParents.push(target); } /** * Setup needed event listeners used to update the popper position * @method * @memberof Popper.Utils * @private */ function setupEventListeners(reference, options, state, updateBound) { // Resize event listener on window state.updateBound = updateBound; window.addEventListener('resize', state.updateBound, { passive: true }); // Scroll event listener on scroll parents var scrollElement = getScrollParent(reference); attachToScrollParents(scrollElement, 'scroll', state.updateBound, state.scrollParents); state.scrollElement = scrollElement; state.eventsEnabled = true; return state; } /** @namespace Popper.Utils */ var Utils = { computeAutoPlacement: computeAutoPlacement, debounce: debounce, findIndex: findIndex, getBordersSize: getBordersSize, getBoundaries: getBoundaries, getBoundingClientRect: getBoundingClientRect, getClientRect: getClientRect, getOffsetParent: getOffsetParent, getOffsetRect: getOffsetRect, getOffsetRectRelativeToCustomParent: getOffsetRectRelativeToCustomParent, getOuterSizes: getOuterSizes, getParentNode: getParentNode, getPopperOffsets: getPopperOffsets, getPosition: getPosition, getReferenceOffsets: getReferenceOffsets, getScroll: getScroll, getScrollParent: getScrollParent, getStyleComputedProperty: getStyleComputedProperty, getSupportedPropertyName: getSupportedPropertyName, getTotalScroll: getTotalScroll, getWindowSizes: getWindowSizes, includeScroll: includeScroll, isFixed: isFixed, isFunction: isFunction, isModifierEnabled: isModifierEnabled, isModifierRequired: isModifierRequired, isNative: isNative, isNumeric: isNumeric, isTransformed: isTransformed, removeEventListeners: removeEventListeners, runModifiers: runModifiers, setAttributes: setAttributes, setStyles: setStyles, setupEventListeners: setupEventListeners }; /** * Apply the computed styles to the popper element * @method * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} data.styles - List of style properties - values to apply to popper element * @argument {Object} data.attributes - List of attribute properties - values to apply to popper element * @argument {Object} options - Modifiers configuration and options * @returns {Object} The same data object */ function applyStyle(data, options) { // apply the final offsets to the popper // NOTE: 1 DOM access here var styles = { position: data.offsets.popper.position }; var attributes = { 'x-placement': data.placement }; // round top and left to avoid blurry text var left = Math.round(data.offsets.popper.left); var top = Math.round(data.offsets.popper.top); // if gpuAcceleration is set to true and transform is supported, // we use `translate3d` to apply the position to the popper we // automatically use the supported prefixed version if needed var prefixedProperty = getSupportedPropertyName('transform'); if (options.gpuAcceleration && prefixedProperty) { styles[prefixedProperty] = 'translate3d(' + left + 'px, ' + top + 'px, 0)'; styles.top = 0; styles.left = 0; styles.willChange = 'transform'; } // othwerise, we use the standard `left` and `top` properties else { styles.left = left; styles.top = top; styles.willChange = 'top, left'; } // any property present in `data.styles` will be applied to the popper, // in this way we can make the 3rd party modifiers add custom styles to it // Be aware, modifiers could override the properties defined in the previous // lines of this modifier! setStyles(data.instance.popper, _extends({}, styles, data.styles)); // any property present in `data.attributes` will be applied to the popper, // they will be set as HTML attributes of the element setAttributes(data.instance.popper, _extends({}, attributes, data.attributes)); // if the arrow style has been computed, apply the arrow style if (data.offsets.arrow) { setStyles(data.arrowElement, data.offsets.arrow); } return data; } /** * Set the x-placement attribute before everything else because it could be used to add margins to the popper * margins needs to be calculated to get the correct popper offsets * @method * @memberof Popper.modifiers * @param {HTMLElement} reference - The reference element used to position the popper * @param {HTMLElement} popper - The HTML element used as popper. * @param {Object} options - Popper.js options */ function applyStyleOnLoad(reference, popper, options, modifierOptions, state) { // compute reference element offsets var referenceOffsets = getReferenceOffsets(state, popper, reference); // compute auto placement, store placement inside the data object, // modifiers will be able to edit `placement` if needed // and refer to originalPlacement to know the original value options.placement = computeAutoPlacement(options.placement, referenceOffsets, popper); popper.setAttribute('x-placement', options.placement); return options; } /** * Modifier used to move the arrowElements on the edge of the popper to make sure them are always between the popper and the reference element * It will use the CSS outer size of the arrowElement element to know how many pixels of conjuction are needed * @method * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function arrow(data, options) { // arrow depends on keepTogether in order to work if (!isModifierRequired(data.instance.modifiers, 'arrow', 'keepTogether')) { console.warn('WARNING: `keepTogether` modifier is required by arrow modifier in order to work, be sure to include it before `arrow`!'); return data; } var arrowElement = options.element; // if arrowElement is a string, suppose it's a CSS selector if (typeof arrowElement === 'string') { arrowElement = data.instance.popper.querySelector(arrowElement); // if arrowElement is not found, don't run the modifier if (!arrowElement) { return data; } } else { // if the arrowElement isn't a query selector we must check that the // provided DOM node is child of its popper node if (!data.instance.popper.contains(arrowElement)) { console.warn('WARNING: `arrow.element` must be child of its popper element!'); return data; } } var placement = data.placement.split('-')[0]; var popper = getClientRect(data.offsets.popper); var reference = data.offsets.reference; var isVertical = ['left', 'right'].indexOf(placement) !== -1; var len = isVertical ? 'height' : 'width'; var side = isVertical ? 'top' : 'left'; var altSide = isVertical ? 'left' : 'top'; var opSide = isVertical ? 'bottom' : 'right'; var arrowElementSize = getOuterSizes(arrowElement)[len]; // // extends keepTogether behavior making sure the popper and its reference have enough pixels in conjuction // // top/left side if (reference[opSide] - arrowElementSize < popper[side]) { data.offsets.popper[side] -= popper[side] - (reference[opSide] - arrowElementSize); } // bottom/right side if (reference[side] + arrowElementSize > popper[opSide]) { data.offsets.popper[side] += reference[side] + arrowElementSize - popper[opSide]; } // compute center of the popper var center = reference[side] + reference[len] / 2 - arrowElementSize / 2; // Compute the sideValue using the updated popper offsets var sideValue = center - getClientRect(data.offsets.popper)[side]; // prevent arrowElement from being placed not contiguously to its popper sideValue = Math.max(Math.min(popper[len] - arrowElementSize, sideValue), 0); data.arrowElement = arrowElement; data.offsets.arrow = {}; data.offsets.arrow[side] = sideValue; data.offsets.arrow[altSide] = ''; // make sure to unset any eventual altSide value from the DOM node return data; } /** * Get the opposite placement variation of the given one/ * @method * @memberof Popper.Utils * @argument {String} placement variation * @returns {String} flipped placement variation */ function getOppositeVariation(variation) { if (variation === 'end') { return 'start'; } else if (variation === 'start') { return 'end'; } return variation; } /** * Modifier used to flip the placement of the popper when the latter is starting overlapping its reference element. * Requires the `preventOverflow` modifier before it in order to work. * **NOTE:** data.instance modifier will run all its previous modifiers everytime it tries to flip the popper! * @method * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function flip(data, options) { // if `inner` modifier is enabled, we can't use the `flip` modifier if (isModifierEnabled(data.instance.modifiers, 'inner')) { return data; } if (data.flipped && data.placement === data.originalPlacement) { // seems like flip is trying to loop, probably there's not enough space on any of the flippable sides return data; } var boundaries = getBoundaries(data.instance.popper, options.padding, options.boundariesElement); var placement = data.placement.split('-')[0]; var placementOpposite = getOppositePlacement(placement); var variation = data.placement.split('-')[1] || ''; var flipOrder = []; if (options.behavior === 'flip') { flipOrder = [placement, placementOpposite]; } else { flipOrder = options.behavior; } flipOrder.forEach(function (step, index) { if (placement !== step || flipOrder.length === index + 1) { return data; } placement = data.placement.split('-')[0]; placementOpposite = getOppositePlacement(placement); var popperOffsets = getClientRect(data.offsets.popper); var refOffsets = data.offsets.reference; // using floor because the reference offsets may contain decimals we are not going to consider here var floor = Math.floor; var overlapsRef = placement === 'left' && floor(popperOffsets.right) > floor(refOffsets.left) || placement === 'right' && floor(popperOffsets.left) < floor(refOffsets.right) || placement === 'top' && floor(popperOffsets.bottom) > floor(refOffsets.top) || placement === 'bottom' && floor(popperOffsets.top) < floor(refOffsets.bottom); var overflowsLeft = floor(popperOffsets.left) < floor(boundaries.left); var overflowsRight = floor(popperOffsets.right) > floor(boundaries.right); var overflowsTop = floor(popperOffsets.top) < floor(boundaries.top); var overflowsBottom = floor(popperOffsets.bottom) > floor(boundaries.bottom); var overflowsBoundaries = placement === 'left' && overflowsLeft || placement === 'right' && overflowsRight || placement === 'top' && overflowsTop || placement === 'bottom' && overflowsBottom; // flip the variation if required var isVertical = ['top', 'bottom'].indexOf(placement) !== -1; var flippedVariation = !!options.flipVariations && (isVertical && variation === 'start' && overflowsLeft || isVertical && variation === 'end' && overflowsRight || !isVertical && variation === 'start' && overflowsTop || !isVertical && variation === 'end' && overflowsBottom); if (overlapsRef || overflowsBoundaries || flippedVariation) { // this boolean to detect any flip loop data.flipped = true; if (overlapsRef || overflowsBoundaries) { placement = flipOrder[index + 1]; } if (flippedVariation) { variation = getOppositeVariation(variation); } data.placement = placement + (variation ? '-' + variation : ''); data.offsets.popper = getPopperOffsets(data.instance.state.position, data.instance.popper, data.offsets.reference, data.placement); data = runModifiers(data.instance.modifiers, data, 'flip'); } }); return data; } /** * Modifier used to make sure the popper is always near its reference element * It cares only about the first axis, you can still have poppers with margin * between the popper and its reference element. * @method * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function keepTogether(data) { var popper = getClientRect(data.offsets.popper); var reference = data.offsets.reference; var placement = data.placement.split('-')[0]; var floor = Math.floor; var isVertical = ['top', 'bottom'].indexOf(placement) !== -1; var side = isVertical ? 'right' : 'bottom'; var opSide = isVertical ? 'left' : 'top'; var measurement = isVertical ? 'width' : 'height'; if (popper[side] < floor(reference[opSide])) { data.offsets.popper[opSide] = floor(reference[opSide]) - popper[measurement]; } if (popper[opSide] > floor(reference[side])) { data.offsets.popper[opSide] = floor(reference[side]); } return data; } /** * Modifier used to add an offset to the popper, useful if you more granularity positioning your popper. * The offsets will shift the popper on the side of its reference element. * @method * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @argument {Number|String} options.offset=0 * Basic usage allows a number used to nudge the popper by the given amount of pixels. * You can pass a percentage value as string (eg. `20%`) to nudge by the given percentage (relative to reference element size) * Other supported units are `vh` and `vw` (relative to viewport) * Additionally, you can pass a pair of values (eg. `10 20` or `2vh 20%`) to nudge the popper * on both axis. * A note about percentage values, if you want to refer a percentage to the popper size instead of the reference element size, * use `%p` instead of `%` (eg: `20%p`). To make it clearer, you can replace `%` with `%r` and use eg.`10%p 25%r`. * > **Heads up!** The order of the axis is relative to the popper placement: `bottom` or `top` are `X,Y`, the other are `Y,X` * @returns {Object} The data object, properly modified */ function offset(data, options) { var placement = data.placement; var popper = data.offsets.popper; var offsets = void 0; if (isNumeric(options.offset)) { offsets = [options.offset, 0]; } else { // split the offset in case we are providing a pair of offsets separated // by a blank space offsets = options.offset.split(' '); // itherate through each offset to compute them in case they are percentages offsets = offsets.map(function (offset, index) { // separate value from unit var split = offset.match(/(\d*\.?\d*)(.*)/); var value = +split[1]; var unit = split[2]; // use height if placement is left or right and index is 0 otherwise use width // in this way the first offset will use an axis and the second one // will use the other one var useHeight = placement.indexOf('right') !== -1 || placement.indexOf('left') !== -1; if (index === 1) { useHeight = !useHeight; } var measurement = useHeight ? 'height' : 'width'; // if is a percentage relative to the popper (%p), we calculate the value of it using // as base the sizes of the popper // if is a percentage (% or %r), we calculate the value of it using as base the // sizes of the reference element if (unit.indexOf('%') === 0) { var element = void 0; switch (unit) { case '%p': element = data.offsets.popper; break; case '%': case '$r': default: element = data.offsets.reference; } var rect = getClientRect(element); var len = rect[measurement]; return len / 100 * value; } // if is a vh or vw, we calculate the size based on the viewport else if (unit === 'vh' || unit === 'vw') { var size = void 0; if (unit === 'vh') { size = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); } else { size = Math.max(document.documentElement.clientWidth, window.innerWidth || 0); } return size / 100 * value; } // if is an explicit pixel unit, we get rid of the unit and keep the value else if (unit === 'px') { return +value; } // if is an implicit unit, it's px, and we return just the value else { return +offset; } }); } if (data.placement.indexOf('left') !== -1) { popper.top += offsets[0]; popper.left -= offsets[1] || 0; } else if (data.placement.indexOf('right') !== -1) { popper.top += offsets[0]; popper.left += offsets[1] || 0; } else if (data.placement.indexOf('top') !== -1) { popper.left += offsets[0]; popper.top -= offsets[1] || 0; } else if (data.placement.indexOf('bottom') !== -1) { popper.left += offsets[0]; popper.top += offsets[1] || 0; } return data; } /** * Modifier used to prevent the popper from being positioned outside the boundary. * * An scenario exists where the reference itself is not within the boundaries. We can * say it has "escaped the boundaries" — or just "escaped". In this case we need to * decide whether the popper should either: * * - detach from the reference and remain "trapped" in the boundaries, or * - if it should be ignore the boundary and "escape with the reference" * * When `escapeWithReference` is `true`, and reference is completely outside the * boundaries, the popper will overflow (or completely leave) the boundaries in order * to remain attached to the edge of the reference. * * @method * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function preventOverflow(data, options) { var boundariesElement = options.boundariesElement || getOffsetParent(data.instance.popper); var boundaries = getBoundaries(data.instance.popper, options.padding, boundariesElement); options.boundaries = boundaries; var order = options.priority; var popper = getClientRect(data.offsets.popper); var check = { primary: function primary(placement) { var value = popper[placement]; if (popper[placement] < boundaries[placement] && !options.escapeWithReference) { value = Math.max(popper[placement], boundaries[placement]); } return defineProperty({}, placement, value); }, secondary: function secondary(placement) { var mainSide = placement === 'right' ? 'left' : 'top'; var value = popper[mainSide]; if (popper[placement] > boundaries[placement] && !options.escapeWithReference) { value = Math.min(popper[mainSide], boundaries[placement] - (placement === 'right' ? popper.width : popper.height)); } return defineProperty({}, mainSide, value); } }; order.forEach(function (placement) { var side = ['left', 'top'].indexOf(placement) !== -1 ? 'primary' : 'secondary'; popper = _extends({}, popper, check[side](placement)); }); data.offsets.popper = popper; return data; } /** * Modifier used to shift the popper on the start or end of its reference element side * @method * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function shift(data) { var placement = data.placement; var basePlacement = placement.split('-')[0]; var shiftvariation = placement.split('-')[1]; // if shift shiftvariation is specified, run the modifier if (shiftvariation) { var reference = data.offsets.reference; var popper = getClientRect(data.offsets.popper); var isVertical = ['bottom', 'top'].indexOf(basePlacement) !== -1; var side = isVertical ? 'left' : 'top'; var measurement = isVertical ? 'width' : 'height'; var shiftOffsets = { start: defineProperty({}, side, reference[side]), end: defineProperty({}, side, reference[side] + reference[measurement] - popper[measurement]) }; data.offsets.popper = _extends({}, popper, shiftOffsets[shiftvariation]); } return data; } /** * Modifier used to hide the popper when its reference element is outside of the * popper boundaries. It will set an x-hidden attribute which can be used to hide * the popper when its reference is out of boundaries. * @method * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function hide(data) { if (!isModifierRequired(data.instance.modifiers, 'hide', 'preventOverflow')) { console.warn('WARNING: preventOverflow modifier is required by hide modifier in order to work, be sure to include it before hide!'); return data; } var refRect = data.offsets.reference; var bound = find(data.instance.modifiers, function (modifier) { return modifier.name === 'preventOverflow'; }).boundaries; if (refRect.bottom < bound.top || refRect.left > bound.right || refRect.top > bound.bottom || refRect.right < bound.left) { // Avoid unnecessary DOM access if visibility hasn't changed if (data.hide === true) { return data; } data.hide = true; data.attributes['x-out-of-boundaries'] = ''; } else { // Avoid unnecessary DOM access if visibility hasn't changed if (data.hide === false) { return data; } data.hide = false; data.attributes['x-out-of-boundaries'] = false; } return data; } /** * Modifier used to make the popper flow toward the inner of the reference element. * By default, when this modifier is disabled, the popper will be placed outside * the reference element. * @method * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function inner(data) { var placement = data.placement; var basePlacement = placement.split('-')[0]; var popper = getClientRect(data.offsets.popper); var reference = getClientRect(data.offsets.reference); var isHoriz = ['left', 'right'].indexOf(basePlacement) !== -1; var subtractLength = ['top', 'left'].indexOf(basePlacement) === -1; popper[isHoriz ? 'left' : 'top'] = reference[placement] - (subtractLength ? popper[isHoriz ? 'width' : 'height'] : 0); data.placement = getOppositePlacement(placement); data.offsets.popper = getClientRect(popper); return data; } /** * Modifiers are plugins used to alter the behavior of your poppers. * Popper.js uses a set of 7 modifiers to provide all the basic functionalities * needed by the library. * * Each modifier is an object containing several properties listed below. * @namespace Modifiers * @param {Object} modifier - Modifier descriptor * @param {Integer} modifier.order * The `order` property defines the execution order of the modifiers. * The built-in modifiers have orders with a gap of 100 units in between, * this allows you to inject additional modifiers between the existing ones * without having to redefine the order of all of them. * The modifiers are executed starting from the one with the lowest order. * @param {Boolean} modifier.enabled - When `true`, the modifier will be used. * @param {Modifiers~modifier} modifier.function - Modifier function. * @param {Modifiers~onLoad} modifier.onLoad - Function executed on popper initalization * @return {Object} data - Each modifier must return the modified `data` object. */ var modifiers = { shift: { order: 100, enabled: true, function: shift }, offset: { order: 200, enabled: true, function: offset, // nudges popper from its origin by the given amount of pixels (can be negative) offset: 0 }, preventOverflow: { order: 300, enabled: true, function: preventOverflow, // popper will try to prevent overflow following these priorities // by default, then, it could overflow on the left and on top of the boundariesElement priority: ['left', 'right', 'top', 'bottom'], // amount of pixel used to define a minimum distance between the boundaries and the popper // this makes sure the popper has always a little padding between the edges of its container padding: 5, boundariesElement: 'scrollParent' }, keepTogether: { order: 400, enabled: true, function: keepTogether }, arrow: { order: 500, enabled: true, function: arrow, // selector or node used as arrow element: '[x-arrow]' }, flip: { order: 600, enabled: true, function: flip, // the behavior used to change the popper's placement behavior: 'flip', // the popper will flip if it hits the edges of the boundariesElement - padding padding: 5, boundariesElement: 'viewport' }, inner: { order: 700, enabled: false, function: inner }, hide: { order: 800, enabled: true, function: hide }, applyStyle: { order: 900, enabled: true, // if true, it uses the CSS 3d transformation to position the popper gpuAcceleration: true, function: applyStyle, onLoad: applyStyleOnLoad } }; /** * Modifiers can edit the `data` object to change the beheavior of the popper. * This object contains all the informations used by Popper.js to compute the * popper position. * The modifier can edit the data as needed, and then `return` it as result. * * @callback Modifiers~modifier * @param {dataObject} data * @return {dataObject} modified data */ /** * The `dataObject` is an object containing all the informations used by Popper.js * this object get passed to modifiers and to the `onCreate` and `onUpdate` callbacks. * @name dataObject * @property {Object} data.instance The Popper.js instance * @property {String} data.placement Placement applied to popper * @property {String} data.originalPlacement Placement originally defined on init * @property {Boolean} data.flipped True if popper has been flipped by flip modifier * @property {Boolean} data.hide True if the reference element is out of boundaries, useful to know when to hide the popper. * @property {HTMLElement} data.arrowElement Node used as arrow by arrow modifier * @property {Object} data.styles Any CSS property defined here will be applied to the popper, it expects the JavaScript nomenclature (eg. `marginBottom`) * @property {Object} data.boundaries Offsets of the popper boundaries * @property {Object} data.offsets The measurements of popper, reference and arrow elements. * @property {Object} data.offsets.popper `top`, `left`, `width`, `height` values * @property {Object} data.offsets.reference `top`, `left`, `width`, `height` values * @property {Object} data.offsets.arro] `top` and `left` offsets, only one of them will be different from 0 */ // Utils // Modifiers // default options var DEFAULTS = { // placement of the popper placement: 'bottom', // whether events (resize, scroll) are initially enabled eventsEnabled: true, /** * Callback called when the popper is created. * By default, is set to no-op. * Access Popper.js instance with `data.instance`. * @callback createCallback * @static * @param {dataObject} data */ onCreate: function onCreate() {}, /** * Callback called when the popper is updated, this callback is not called * on the initialization/creation of the popper, but only on subsequent * updates. * By default, is set to no-op. * Access Popper.js instance with `data.instance`. * @callback updateCallback * @static * @param {dataObject} data */ onUpdate: function onUpdate() {}, // list of functions used to modify the offsets before they are applied to the popper modifiers: modifiers }; /** * Create a new Popper.js instance * @class Popper * @param {HTMLElement} reference - The reference element used to position the popper * @param {HTMLElement} popper - The HTML element used as popper. * @param {Object} options * @param {String} options.placement=bottom * Placement of the popper accepted values: `top(-start, -end), right(-start, -end), bottom(-start, -end), * left(-start, -end)` * * @param {Boolean} options.eventsEnabled=true * Whether events (resize, scroll) are initially enabled * @param {Boolean} options.gpuAcceleration=true * When this property is set to true, the popper position will be applied using CSS3 translate3d, allowing the * browser to use the GPU to accelerate the rendering. * If set to false, the popper will be placed using `top` and `left` properties, not using the GPU. * * @param {Boolean} options.removeOnDestroy=false * Set to true if you want to automatically remove the popper when you call the `destroy` method. * * @param {Object} options.modifiers * List of functions used to modify the data before they are applied to the popper (see source code for default values) * * @param {Object} options.modifiers.arrow - Arrow modifier configuration * @param {String|HTMLElement} options.modifiers.arrow.element='[x-arrow]' * The DOM Node used as arrow for the popper, or a CSS selector used to get the DOM node. It must be child of * its parent Popper. Popper.js will apply to the given element the style required to align the arrow with its * reference element. * By default, it will look for a child node of the popper with the `x-arrow` attribute. * * @param {Object} options.modifiers.offset - Offset modifier configuration * @param {Number} options.modifiers.offset.offset=0 * Amount of pixels the popper will be shifted (can be negative). * * @param {Object} options.modifiers.preventOverflow - PreventOverflow modifier configuration * @param {Array} [options.modifiers.preventOverflow.priority=['left', 'right', 'top', 'bottom']] * Priority used when Popper.js tries to avoid overflows from the boundaries, they will be checked in order, * this means that the last one will never overflow * @param {String|HTMLElement} options.modifiers.preventOverflow.boundariesElement='scrollParent' * Boundaries used by the modifier, can be `scrollParent`, `window`, `viewport` or any DOM element. * @param {Number} options.modifiers.preventOverflow.padding=5 * Amount of pixel used to define a minimum distance between the boundaries and the popper * this makes sure the popper has always a little padding between the edges of its container. * * @param {Object} options.modifiers.flip - Flip modifier configuration * @param {String|Array} options.modifiers.flip.behavior='flip' * The behavior used by the `flip` modifier to change the placement of the popper when the latter is trying to * overlap its reference element. Defining `flip` as value, the placement will be flipped on * its axis (`right - left`, `top - bottom`). * You can even pass an array of placements (eg: `['right', 'left', 'top']` ) to manually specify * how alter the placement when a flip is needed. (eg. in the above example, it would first flip from right to left, * then, if even in its new placement, the popper is overlapping its reference element, it will be moved to top) * @param {String|HTMLElement} options.modifiers.flip.boundariesElement='viewport' * The element which will define the boundaries of the popper position, the popper will never be placed outside * of the defined boundaries (except if `keepTogether` is enabled) * * @param {Object} options.modifiers.inner - Inner modifier configuration * @param {Number} options.modifiers.inner.enabled=false * Set to `true` to make the popper flow toward the inner of the reference element. * * @param {Number} options.modifiers.flip.padding=5 * Amount of pixel used to define a minimum distance between the boundaries and the popper * this makes sure the popper has always a little padding between the edges of its container. * * @param {createCallback} options.onCreate - onCreate callback * Function called after the Popper has been instantiated. * * @param {updateCallback} options.onUpdate - onUpdate callback * Function called on subsequent updates of Popper. * * @return {Object} instance - The generated Popper.js instance */ var Popper = function () { function Popper(reference, popper) { var _this = this; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; classCallCheck(this, Popper); this.scheduleUpdate = function () { return requestAnimationFrame(_this.update); }; // make update() debounced, so that it only runs at most once-per-tick this.update = debounce(this.update.bind(this)); // with {} we create a new object with the options inside it this.options = _extends({}, Popper.Defaults, options); // init state this.state = { isDestroyed: false, isCreated: false, scrollParents: [] }; // get reference and popper elements (allow jQuery wrappers) this.reference = reference.jquery ? reference[0] : reference; this.popper = popper.jquery ? popper[0] : popper; // refactoring modifiers' list (Object => Array) this.modifiers = Object.keys(Popper.Defaults.modifiers).map(function (name) { return _extends({ name: name }, Popper.Defaults.modifiers[name]); }); // assign default values to modifiers, making sure to override them with // the ones defined by user this.modifiers = this.modifiers.map(function (defaultConfig) { var userConfig = options.modifiers && options.modifiers[defaultConfig.name] || {}; return _extends({}, defaultConfig, userConfig); }); // add custom modifiers to the modifiers list if (options.modifiers) { this.options.modifiers = _extends({}, Popper.Defaults.modifiers, options.modifiers); Object.keys(options.modifiers).forEach(function (name) { // take in account only custom modifiers if (Popper.Defaults.modifiers[name] === undefined) { var modifier = options.modifiers[name]; modifier.name = name; _this.modifiers.push(modifier); } }); } // get the popper position type this.state.position = getPosition(this.reference); // sort the modifiers by order this.modifiers = this.modifiers.sort(function (a, b) { return a.order - b.order; }); // modifiers have the ability to execute arbitrary code when Popper.js get inited // such code is executed in the same order of its modifier // they could add new properties to their options configuration // BE AWARE: don't add options to `options.modifiers.name` but to `modifierOptions`! this.modifiers.forEach(function (modifierOptions) { if (modifierOptions.enabled && isFunction(modifierOptions.onLoad)) { modifierOptions.onLoad(_this.reference, _this.popper, _this.options, modifierOptions, _this.state); } }); // determine how we should set the origin of offsets this.state.isParentTransformed = isTransformed(this.popper.parentNode); // fire the first update to position the popper in the right place this.update(); var eventsEnabled = this.options.eventsEnabled; if (eventsEnabled) { // setup event listeners, they will take care of update the position in specific situations this.enableEventListeners(); } this.state.eventsEnabled = eventsEnabled; } // // Methods // /** * Updates the position of the popper, computing the new offsets and applying the new style * Prefer `scheduleUpdate` over `update` because of performance reasons * @method * @memberof Popper */ createClass(Popper, [{ key: 'update', value: function update() { // if popper is destroyed, don't perform any further update if (this.state.isDestroyed) { return; } var data = { instance: this, styles: {}, attributes: {}, flipped: false, offsets: {} }; // make sure to apply the popper position before any computation this.state.position = getPosition(this.reference); setStyles(this.popper, { position: this.state.position }); // compute reference element offsets data.offsets.reference = getReferenceOffsets(this.state, this.popper, this.reference); // compute auto placement, store placement inside the data object, // modifiers will be able to edit `placement` if needed // and refer to originalPlacement to know the original value data.placement = computeAutoPlacement(this.options.placement, data.offsets.reference, this.popper); // store the computed placement inside `originalPlacement` data.originalPlacement = this.options.placement; // compute the popper offsets data.offsets.popper = getPopperOffsets(this.state, this.popper, data.offsets.reference, data.placement); // run the modifiers data = runModifiers(this.modifiers, data); // the first `update` will call `onCreate` callback // the other ones will call `onUpdate` callback if (!this.state.isCreated) { this.state.isCreated = true; this.options.onCreate(data); } else { this.options.onUpdate(data); } } /** * Schedule an update, it will run on the next UI update available * @method scheduleUpdate * @memberof Popper */ }, { key: 'destroy', /** * Destroy the popper * @method * @memberof Popper */ value: function destroy() { this.state.isDestroyed = true; // touch DOM only if `applyStyle` modifier is enabled if (isModifierEnabled(this.modifiers, 'applyStyle')) { this.popper.removeAttribute('x-placement'); this.popper.style.left = ''; this.popper.style.position = ''; this.popper.style.top = ''; this.popper.style[getSupportedPropertyName('transform')] = ''; } this.disableEventListeners(); // remove the popper if user explicity asked for the deletion on destroy // do not use `remove` because IE11 doesn't support it if (this.options.removeOnDestroy) { this.popper.parentNode.removeChild(this.popper); } return this; } /** * it will add resize/scroll events and start recalculating * position of the popper element when they are triggered * @method * @memberof Popper */ }, { key: 'enableEventListeners', value: function enableEventListeners() { if (!this.state.eventsEnabled) { this.state = setupEventListeners(this.reference, this.options, this.state, this.scheduleUpdate); } } /** * it will remove resize/scroll events and won't recalculate * popper position when they are triggered. It also won't trigger onUpdate callback anymore, * unless you call 'update' method manually. * @method * @memberof Popper */ }, { key: 'disableEventListeners', value: function disableEventListeners() { if (this.state.eventsEnabled) { window.cancelAnimationFrame(this.scheduleUpdate); this.state = removeEventListeners(this.reference, this.state); } } /** * Collection of utilities useful when writing custom modifiers * @memberof Popper */ /** * List of accepted placements to use as values of the `placement` option * @memberof Popper */ /** * Default Popper.js options * @memberof Popper */ }]); return Popper; }(); Popper.Utils = Utils; Popper.placements = ['auto', 'auto-start', 'auto-end', 'top', 'top-start', 'top-end', 'right', 'right-start', 'right-end', 'bottom', 'bottom-start', 'bottom-end', 'left', 'left-start', 'left-end']; Popper.Defaults = DEFAULTS; return Popper; }); //# sourceMappingURL=popper.es5.js.map /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, module) {'use strict'; 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; }; /** * Lodash (Custom Build) <https://lodash.com/> * Build: `lodash modularize exports="npm" -o ./` * Copyright JS Foundation and other contributors <https://js.foundation/> * Released under MIT license <https://lodash.com/license> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', asyncTag = '[object AsyncFunction]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', nullTag = '[object Null]', objectTag = '[object Object]', promiseTag = '[object Promise]', proxyTag = '[object Proxy]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', undefinedTag = '[object Undefined]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Detect free variable `global` from Node.js. */ var freeGlobal = (typeof global === 'undefined' ? 'undefined' : _typeof(global)) == 'object' && global && global.Object === Object && global; /** Detect free variable `self`. */ var freeSelf = (typeof self === 'undefined' ? 'undefined' : _typeof(self)) == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Detect free variable `exports`. */ var freeExports = ( false ? 'undefined' : _typeof(exports)) == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && ( false ? 'undefined' : _typeof(module)) == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = function () { try { return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }(); /* Node.js helper references. */ var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function (value) { return func(value); }; } /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function (value, key) { result[++index] = [key, value]; }); return result; } /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function (arg) { return func(transform(arg)); }; } /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function (value) { result[++index] = value; }); return result; } /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = root['__core-js_shared__']; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to detect methods masquerading as native. */ var maskSrcKey = function () { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? 'Symbol(src)_1.' + uid : ''; }(); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'); /** Built-in value references. */ var Buffer = moduleExports ? root.Buffer : undefined, _Symbol = root.Symbol, Uint8Array = root.Uint8Array, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, symToStringTag = _Symbol ? _Symbol.toStringTag : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, nativeKeys = overArg(Object.keys, Object); /* Built-in method references that are verified to be native. */ var DataView = getNative(root, 'DataView'), Map = getNative(root, 'Map'), Promise = getNative(root, 'Promise'), Set = getNative(root, 'Set'), WeakMap = getNative(root, 'WeakMap'), nativeCreate = getNative(Object, 'create'); /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** Used to convert symbols to primitives and strings. */ var symbolProto = _Symbol ? _Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = nativeCreate && value === undefined ? HASH_UNDEFINED : value; return this; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new Hash(), 'map': new (Map || ListCache)(), 'string': new Hash() }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new MapCache(); while (++index < length) { this.add(values[index]); } } /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache(); this.size = 0; } /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || pairs.length < LARGE_ARRAY_SIZE - 1) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. isBuff && (key == 'offset' || key == 'parent') || // PhantomJS 2 has enumerable non-index properties on typed arrays. isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset') || // Skip index properties. isIndex(key, length)))) { result.push(key); } } return result; } /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value); } /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || !isObjectLike(value) && !isObjectLike(other)) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack()); return objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack()); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack()); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache() : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function (othValue, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == other + ''; case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && 'constructor' in object && 'constructor' in other && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray : function (object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function (symbol) { return propertyIsEnumerable.call(object, symbol); }); }; /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if (DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag || Map && getTag(new Map()) != mapTag || Promise && getTag(Promise.resolve()) != promiseTag || Set && getTag(new Set()) != setTag || WeakMap && getTag(new WeakMap()) != weakMapTag) { getTag = function getTag(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length; } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value === 'undefined' ? 'undefined' : _typeof(value); return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null; } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && maskSrcKey in func; } /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = typeof Ctor == 'function' && Ctor.prototype || objectProto; return value === proto; } /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return func + ''; } catch (e) {} } return ''; } /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || value !== value && other !== other; } /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = baseIsArguments(function () { return arguments; }()) ? baseIsArguments : function (value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return baseIsEqual(value, other); } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value === 'undefined' ? 'undefined' : _typeof(value); return value != null && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) == 'object'; } /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } module.exports = isEqual; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(16)(module))) /***/ }, /* 16 */ /***/ function(module, exports) { "use strict"; module.exports = function (module) { if (!module.webpackPolyfill) { module.deprecate = function () {}; module.paths = []; // module.parent = undefined by default module.children = []; module.webpackPolyfill = 1; } return module; }; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); 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 _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(3); var _propTypes2 = _interopRequireDefault(_propTypes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var Arrow = function Arrow(props, context) { var _props$tag = props.tag, tag = _props$tag === undefined ? 'span' : _props$tag, innerRef = props.innerRef, style = props.style, children = props.children, restProps = _objectWithoutProperties(props, ['tag', 'innerRef', 'style', 'children']); var popper = context.popper; var arrowRef = function arrowRef(node) { return popper.setArrowNode(node); }; var arrowStyle = _extends({}, popper.getArrowStyle(), style); if (typeof children === 'function') { return children({ arrowRef: arrowRef, arrowStyle: arrowStyle }); } return (0, _react.createElement)(tag, _extends({ ref: function ref(node) { arrowRef(node); if (typeof innerRef === 'function') { innerRef(node); } }, style: arrowStyle }, restProps), children); }; Arrow.contextTypes = { popper: _propTypes2.default.object.isRequired }; Arrow.propTypes = { tag: _propTypes2.default.string, innerRef: _propTypes2.default.func, children: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func]) }; exports.default = Arrow; /***/ } /******/ ]) }); ;
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import * as React from 'react'; import PropTypes from 'prop-types'; import { chainPropTypes } from '@material-ui/utils'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; import InputBase from '../InputBase'; import MenuItem from '../MenuItem'; import Select from '../Select'; import TableCell from '../TableCell'; import Toolbar from '../Toolbar'; import Typography from '../Typography'; import TablePaginationActions from './TablePaginationActions'; import useId from '../utils/useId'; export const styles = theme => ({ /* Styles applied to the root element. */ root: { color: theme.palette.text.primary, fontSize: theme.typography.pxToRem(14), overflow: 'auto', // Increase the specificity to override TableCell. '&:last-child': { padding: 0 } }, /* Styles applied to the Toolbar component. */ toolbar: { minHeight: 52, paddingRight: 2 }, /* Styles applied to the spacer element. */ spacer: { flex: '1 1 100%' }, /* Styles applied to the caption Typography components if `variant="caption"`. */ caption: { flexShrink: 0 }, // TODO v5: `.selectRoot` should be merged with `.input` /* Styles applied to the Select component root element. */ selectRoot: { marginRight: 32, marginLeft: 8 }, /* Styles applied to the Select component `select` class. */ select: { paddingLeft: 8, paddingRight: 24, textAlign: 'right', textAlignLast: 'right' // Align <select> on Chrome. }, // TODO v5: remove /* Styles applied to the Select component `icon` class. */ selectIcon: {}, /* Styles applied to the `InputBase` component. */ input: { color: 'inherit', fontSize: 'inherit', flexShrink: 0 }, /* Styles applied to the MenuItem component. */ menuItem: {}, /* Styles applied to the internal `TablePaginationActions` component. */ actions: { flexShrink: 0, marginLeft: 20 } }); function defaultLabelDisplayedRows({ from, to, count }) { return `${from}-${to} of ${count !== -1 ? count : `more than ${to}`}`; } function defaultGetAriaLabel(type) { return `Go to ${type} page`; } /** * A `TableCell` based component for placing inside `TableFooter` for pagination. */ const TablePagination = /*#__PURE__*/React.forwardRef(function TablePagination(props, ref) { const { ActionsComponent = TablePaginationActions, backIconButtonProps, classes, className, colSpan: colSpanProp, component: Component = TableCell, count, getItemAriaLabel = defaultGetAriaLabel, labelDisplayedRows = defaultLabelDisplayedRows, labelRowsPerPage = 'Rows per page:', nextIconButtonProps, onPageChange, onRowsPerPageChange, page, rowsPerPage, rowsPerPageOptions = [10, 25, 50, 100], SelectProps = {}, showFirstButton = false, showLastButton = false } = props, other = _objectWithoutPropertiesLoose(props, ["ActionsComponent", "backIconButtonProps", "classes", "className", "colSpan", "component", "count", "getItemAriaLabel", "labelDisplayedRows", "labelRowsPerPage", "nextIconButtonProps", "onPageChange", "onRowsPerPageChange", "page", "rowsPerPage", "rowsPerPageOptions", "SelectProps", "showFirstButton", "showLastButton"]); let colSpan; if (Component === TableCell || Component === 'td') { colSpan = colSpanProp || 1000; // col-span over everything } const selectId = useId(SelectProps.id); const labelId = useId(SelectProps.labelId); const MenuItemComponent = SelectProps.native ? 'option' : MenuItem; const getLabelDisplayedRowsTo = () => { if (count === -1) return (page + 1) * rowsPerPage; return rowsPerPage === -1 ? count : Math.min(count, (page + 1) * rowsPerPage); }; return /*#__PURE__*/React.createElement(Component, _extends({ className: clsx(classes.root, className), colSpan: colSpan, ref: ref }, other), /*#__PURE__*/React.createElement(Toolbar, { className: classes.toolbar }, /*#__PURE__*/React.createElement("div", { className: classes.spacer }), rowsPerPageOptions.length > 1 && /*#__PURE__*/React.createElement(Typography, { color: "inherit", variant: "body2", className: classes.caption, id: labelId }, labelRowsPerPage), rowsPerPageOptions.length > 1 && /*#__PURE__*/React.createElement(Select, _extends({ classes: { select: classes.select, icon: classes.selectIcon }, input: /*#__PURE__*/React.createElement(InputBase, { className: clsx(classes.input, classes.selectRoot) }), value: rowsPerPage, onChange: onRowsPerPageChange, id: selectId, labelId: labelId }, SelectProps), rowsPerPageOptions.map(rowsPerPageOption => /*#__PURE__*/React.createElement(MenuItemComponent, { className: classes.menuItem, key: rowsPerPageOption.value ? rowsPerPageOption.value : rowsPerPageOption, value: rowsPerPageOption.value ? rowsPerPageOption.value : rowsPerPageOption }, rowsPerPageOption.label ? rowsPerPageOption.label : rowsPerPageOption))), /*#__PURE__*/React.createElement(Typography, { color: "inherit", variant: "body2", className: classes.caption }, labelDisplayedRows({ from: count === 0 ? 0 : page * rowsPerPage + 1, to: getLabelDisplayedRowsTo(), count: count === -1 ? -1 : count, page })), /*#__PURE__*/React.createElement(ActionsComponent, { className: classes.actions, backIconButtonProps: backIconButtonProps, count: count, nextIconButtonProps: nextIconButtonProps, onPageChange: onPageChange, page: page, rowsPerPage: rowsPerPage, showFirstButton: showFirstButton, showLastButton: showLastButton, getItemAriaLabel: getItemAriaLabel }))); }); process.env.NODE_ENV !== "production" ? TablePagination.propTypes = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * The component used for displaying the actions. * Either a string to use a HTML element or a component. * @default TablePaginationActions */ ActionsComponent: PropTypes.elementType, /** * Props applied to the back arrow [`IconButton`](/api/icon-button/) component. */ backIconButtonProps: PropTypes.object, /** * Override or extend the styles applied to the component. */ classes: PropTypes.object, /** * @ignore */ className: PropTypes.string, /** * @ignore */ colSpan: PropTypes.number, /** * The component used for the root node. * Either a string to use a HTML element or a component. */ component: PropTypes.elementType, /** * The total number of rows. * * To enable server side pagination for an unknown number of items, provide -1. */ count: PropTypes.number.isRequired, /** * Accepts a function which returns a string value that provides a user-friendly name for the current page. * * For localization purposes, you can use the provided [translations](/guides/localization/). * * @param {string} type The link or button type to format ('first' | 'last' | 'next' | 'previous'). * @returns {string} * @default function defaultGetAriaLabel(type) { * return `Go to ${type} page`; * } */ getItemAriaLabel: PropTypes.func, /** * Customize the displayed rows label. Invoked with a `{ from, to, count, page }` * object. * * For localization purposes, you can use the provided [translations](/guides/localization/). * @default function defaultLabelDisplayedRows({ from, to, count }) { * return `${from}-${to} of ${count !== -1 ? count : `more than ${to}`}`; * } */ labelDisplayedRows: PropTypes.func, /** * Customize the rows per page label. * * For localization purposes, you can use the provided [translations](/guides/localization/). * @default 'Rows per page:' */ labelRowsPerPage: PropTypes.node, /** * Props applied to the next arrow [`IconButton`](/api/icon-button/) element. */ nextIconButtonProps: PropTypes.object, /** * Callback fired when the page is changed. * * @param {object} event The event source of the callback. * @param {number} page The page selected. */ onPageChange: PropTypes.func.isRequired, /** * Callback fired when the number of rows per page is changed. * * @param {object} event The event source of the callback. */ onRowsPerPageChange: PropTypes.func, /** * The zero-based index of the current page. */ page: chainPropTypes(PropTypes.number.isRequired, props => { const { count, page, rowsPerPage } = props; if (count === -1) { return null; } const newLastPage = Math.max(0, Math.ceil(count / rowsPerPage) - 1); if (page < 0 || page > newLastPage) { return new Error('Material-UI: The page prop of a TablePagination is out of range ' + `(0 to ${newLastPage}, but page is ${page}).`); } return null; }), /** * The number of rows per page. * * Set -1 to display all the rows. */ rowsPerPage: PropTypes.number.isRequired, /** * Customizes the options of the rows per page select field. If less than two options are * available, no select field will be displayed. * @default [10, 25, 50, 100] */ rowsPerPageOptions: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.number, PropTypes.shape({ label: PropTypes.string.isRequired, value: PropTypes.number.isRequired })]).isRequired), /** * Props applied to the rows per page [`Select`](/api/select/) element. * @default {} */ SelectProps: PropTypes.object, /** * If `true`, show the first-page button. * @default false */ showFirstButton: PropTypes.bool, /** * If `true`, show the last-page button. * @default false */ showLastButton: PropTypes.bool } : void 0; export default withStyles(styles, { name: 'MuiTablePagination' })(TablePagination);
var assert = require('assert'); var math = require('../../../index'); var Matrix = math.type.Matrix; var DenseMatrix = math.type.DenseMatrix; var ImmutableDenseMatrix = math.type.ImmutableDenseMatrix; var SparseMatrix = math.type.SparseMatrix; var Complex = math.type.Complex; var Range = math.type.Range; var index = math.index; describe('ImmutableDenseMatrix', function() { describe('constructor', function() { it('should create empty matrix if called with no argument', function() { var m = new ImmutableDenseMatrix(); assert.deepEqual(m._size, [0]); assert.deepEqual(m._data, []); }); it('should create a ImmutableDenseMatrix from an array', function () { var m = new ImmutableDenseMatrix( [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ]); assert.deepEqual(m._size, [4, 3]); assert.deepEqual( m._data, [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ]); }); it('should create a ImmutableDenseMatrix from another ImmutableDenseMatrix', function () { var m1 = new ImmutableDenseMatrix( [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ]); var m2 = new ImmutableDenseMatrix(m1); assert.deepEqual(m1._size, m2._size); assert.deepEqual(m1._data, m2._data); }); it('should create a ImmutableDenseMatrix from a DenseMatrix', function () { var m1 = new DenseMatrix( [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ]); var m2 = new ImmutableDenseMatrix(m1); assert.deepEqual(m1._size, m2._size); assert.deepEqual(m1._data, m2._data); }); it('should create a ImmutableDenseMatrix from a SparseMatrix', function () { var m1 = new SparseMatrix( [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ]); var m2 = new ImmutableDenseMatrix(m1); assert.deepEqual(m1.size(), m2.size()); assert.deepEqual(m1.toArray(), m2.toArray()); }); it('should have a property isMatrix', function () { var a = new ImmutableDenseMatrix(); assert.strictEqual(a.isMatrix, true); }); it('should have a property isDenseMatrix', function () { var a = new ImmutableDenseMatrix(); assert.strictEqual(a.isDenseMatrix, true); }); it('should have a property isImmutableDenseMatrix', function () { var a = new ImmutableDenseMatrix(); assert.strictEqual(a.isImmutableDenseMatrix, true); }); it('should have a property type', function () { var a = new ImmutableDenseMatrix(); assert.strictEqual(a.type, 'ImmutableDenseMatrix'); }); it('should throw an error when called without new keyword', function () { assert.throws(function () { ImmutableDenseMatrix(); }, /Constructor must be called with the new operator/); }); it('should throw an error when called with invalid datatype', function () { assert.throws(function () { new ImmutableDenseMatrix([], 1); }); }); }); describe('size', function() { it('should return the expected size', function() { assert.deepEqual(new ImmutableDenseMatrix().size(), [0]); assert.deepEqual(new ImmutableDenseMatrix([[23]]).size(), [1,1]); assert.deepEqual(new ImmutableDenseMatrix([[1,2,3],[4,5,6]]).size(), [2,3]); assert.deepEqual(new ImmutableDenseMatrix([1,2,3]).size(), [3]); assert.deepEqual(new ImmutableDenseMatrix([[1],[2],[3]]).size(), [3,1]); assert.deepEqual(new ImmutableDenseMatrix([[[1],[2],[3]]]).size(), [1,3,1]); assert.deepEqual(new ImmutableDenseMatrix([[[3]]]).size(), [1,1,1]); assert.deepEqual(new ImmutableDenseMatrix([[]]).size(), [1,0]); }); }); describe('toString', function() { it('should return string representation of matrix', function() { assert.equal(new ImmutableDenseMatrix([[1,2],[3,4]]).toString(), '[[1, 2], [3, 4]]'); assert.equal(new ImmutableDenseMatrix([[1,2],[3,1/3]]).toString(), '[[1, 2], [3, 0.3333333333333333]]'); }); }); describe('toJSON', function () { it('should serialize Matrix', function() { assert.deepEqual( new ImmutableDenseMatrix([[1,2],[3,4]]).toJSON(), { mathjs: 'ImmutableDenseMatrix', data: [[1, 2], [3, 4]], size: [2, 2], datatype: undefined }); }); it('should serialize Matrix, number datatype', function() { assert.deepEqual( new ImmutableDenseMatrix([[1,2],[3,4]], 'number').toJSON(), { mathjs: 'ImmutableDenseMatrix', data: [[1, 2], [3, 4]], size: [2, 2], datatype: 'number' }); }); }); describe('fromJSON', function () { it('should deserialize Matrix', function() { var json = { mathjs: 'ImmutableDenseMatrix', data: [[1, 2], [3, 4]], size: [2, 2] }; var m = ImmutableDenseMatrix.fromJSON(json); assert.ok(m instanceof Matrix); assert.deepEqual(m._size, [2, 2]); assert.strictEqual(m._data[0][0], 1); assert.strictEqual(m._data[0][1], 2); assert.strictEqual(m._data[1][0], 3); assert.strictEqual(m._data[1][1], 4); }); it('should deserialize Matrix, number datatype', function() { var json = { mathjs: 'ImmutableDenseMatrix', data: [[1, 2], [3, 4]], size: [2, 2], datatype: 'number' }; var m = ImmutableDenseMatrix.fromJSON(json); assert.ok(m instanceof Matrix); assert.deepEqual(m._size, [2, 2]); assert.strictEqual(m._data[0][0], 1); assert.strictEqual(m._data[0][1], 2); assert.strictEqual(m._data[1][0], 3); assert.strictEqual(m._data[1][1], 4); assert.strictEqual(m._datatype, 'number'); }); }); describe('format', function () { it('should format matrix', function() { assert.equal(new ImmutableDenseMatrix([[1,2],[3,1/3]]).format(), '[[1, 2], [3, 0.3333333333333333]]'); assert.equal(new ImmutableDenseMatrix([[1,2],[3,1/3]]).format(3), '[[1, 2], [3, 0.333]]'); assert.equal(new ImmutableDenseMatrix([[1,2],[3,1/3]]).format(4), '[[1, 2], [3, 0.3333]]'); }); }); describe('resize', function() { it('should throw an exception on resize', function() { var m = new ImmutableDenseMatrix([[1,2,3],[4,5,6]]); assert.throws(function () { m.resize([2,4]); }, /Cannot invoke resize on an Immutable Matrix instance/); }); }); describe('reshape', function() { it('should throw an exception on reshape', function() { var m = new ImmutableDenseMatrix([[1,2,3],[4,5,6]]); assert.throws(function () { m.reshape([6,1]); }, /Cannot invoke reshape on an Immutable Matrix instance/); }); }); describe('get', function () { var m = new ImmutableDenseMatrix([[0, 1], [2, 3]]); it('should get a value from the matrix', function() { assert.equal(m.get([1,0]), 2); assert.equal(m.get([0,1]), 1); }); it('should throw an error when getting a value out of range', function() { assert.throws(function () { m.get([3,0]); }); assert.throws(function () { m.get([1,5]); }); assert.throws(function () { m.get([1]); }); assert.throws(function () { m.get([]); }); }); it('should throw an error in case of dimension mismatch', function() { assert.throws(function () { m.get([0,2,0,2,0,2]); }, /Dimension mismatch/); }); it('should throw an error when getting a value given a invalid index', function() { assert.throws(function () { m.get([1.2, 2]); }); assert.throws(function () { m.get([1,-2]); }); assert.throws(function () { m.get(1,1); }); assert.throws(function () { m.get(math.index(1,1)); }); assert.throws(function () { m.get([[1,1]]); }); }); }); describe('set', function () { it('should throw an exception on set', function() { var m = new ImmutableDenseMatrix([[0, 0], [0, 0]]); assert.throws(function () { m.set([1,0], 5); }, /Cannot invoke set on an Immutable Matrix instance/); }); }); describe('get subset', function() { it('should get the right subset of the matrix', function() { var m; // get 1-dimensional m = new ImmutableDenseMatrix(math.range(0,10)); assert.deepEqual(m.size(), [10]); assert.deepEqual(m.subset(index(new Range(2, 5))).valueOf(), [2,3,4]); // get 2-dimensional m = new ImmutableDenseMatrix([[1,2,3],[4,5,6],[7,8,9]]); assert.deepEqual(m.size(), [3,3]); assert.deepEqual(m.subset(index(1,1)), 5); assert.deepEqual(m.subset(index(new Range(0,2),new Range(0,2))).valueOf(), [[1,2],[4,5]]); assert.deepEqual(m.subset(index(1, new Range(1,3))).valueOf(), [[5,6]]); assert.deepEqual(m.subset(index(0, new Range(1,3))).valueOf(), [[2,3]]); assert.deepEqual(m.subset(index(new Range(1,3), 1)).valueOf(), [[5],[8]]); assert.deepEqual(m.subset(index(new Range(1,3), 2)).valueOf(), [[6],[9]]); // get n-dimensional m = new ImmutableDenseMatrix([[[1,2],[3,4]], [[5,6],[7,8]]]); assert.deepEqual(m.size(), [2,2,2]); assert.deepEqual(m.subset(index(new Range(0,2),new Range(0,2),new Range(0,2))).valueOf(), m.valueOf()); assert.deepEqual(m.subset(index(0,0,0)), 1); assert.deepEqual(m.subset(index(1,1,1)).valueOf(), 8); assert.deepEqual(m.subset(index(1,1,new Range(0,2))).valueOf(), [[[7,8]]]); assert.deepEqual(m.subset(index(1,new Range(0,2),1)).valueOf(), [[[6],[8]]]); assert.deepEqual(m.subset(index(new Range(0,2),1,1)).valueOf(), [[[4]],[[8]]]); }); it('should squeeze the output when index contains a scalar', function() { var m = new ImmutableDenseMatrix(math.range(0,10)); assert.deepEqual(m.subset(index(1)), 1); assert.deepEqual(m.subset(index(new Range(1,2))), new ImmutableDenseMatrix([1])); m = new ImmutableDenseMatrix([[1,2], [3,4]]); assert.deepEqual(m.subset(index(1,1)), 4); assert.deepEqual(m.subset(index(new Range(1,2), 1)), new ImmutableDenseMatrix([[4]])); assert.deepEqual(m.subset(index(1, new Range(1,2))), new ImmutableDenseMatrix([[4]])); assert.deepEqual(m.subset(index(new Range(1,2), new Range(1,2))), new ImmutableDenseMatrix([[4]])); }); it('should throw an error if the given subset is invalid', function() { var m = new ImmutableDenseMatrix(); assert.throws(function () { m.subset([-1]); }); m = new ImmutableDenseMatrix([[1,2,3],[4,5,6]]); assert.throws(function () { m.subset([1,2,3]); }); assert.throws(function () { m.subset([3,0]); }); assert.throws(function () { m.subset([1]); }); }); it('should throw an error in case of wrong number of arguments', function() { var m = new ImmutableDenseMatrix(); assert.throws(function () { m.subset();}, /Wrong number of arguments/); assert.throws(function () { m.subset(1,2,3,4); }, /Wrong number of arguments/); }); it('should throw an error in case of dimension mismatch', function() { var m = new ImmutableDenseMatrix([[1,2,3],[4,5,6]]); assert.throws(function () { m.subset(index(new Range(0,2))); }, /Dimension mismatch/); }); }); describe('set subset', function() { it('should throw an exception on set subset', function() { var m = new ImmutableDenseMatrix([[0,0],[0,0]]); assert.throws(function () { m.subset(index(0, new Range(0,2)), [1,1]); }, /Cannot invoke set subset on an Immutable Matrix instance/); }); }); describe('map', function() { it('should apply the given function to all elements in the matrix', function() { var m = new ImmutableDenseMatrix([ [[1,2],[3,4]], [[5,6],[7,8]], [[9,10],[11,12]], [[13,14],[15,16]] ]); var m2 = m.map(function (value) { return value * 2; }); assert.deepEqual( m2.valueOf(), [ [[2,4],[6,8]], [[10,12],[14,16]], [[18,20],[22,24]], [[26,28],[30,32]] ]); m = new ImmutableDenseMatrix([1]); m2 = m.map(function (value) { return value * 2; }); assert.deepEqual(m2.valueOf(), [2]); m = new ImmutableDenseMatrix([1,2,3]); m2 = m.map(function (value) { return value * 2; }); assert.deepEqual(m2.valueOf(), [2,4,6]); }); it('should work on empty matrices', function() { var m = new ImmutableDenseMatrix([]); var m2 = m.map(function (value) { return value * 2; }); assert.deepEqual(m2.toArray(), []); }); it('should invoke callback with parameters value, index, obj', function() { var m = new ImmutableDenseMatrix([[1,2,3], [4,5,6]]); var m2 = m.map( function (value, index, obj) { return math.clone([value, index, obj === m]); } ); assert.deepEqual( m2.toArray(), [ [ [1, [0, 0], true ], [2, [0, 1], true ], [3, [0, 2], true ] ], [ [4, [1, 0], true ], [5, [1, 1], true ], [6, [1, 2], true ] ] ]); }); }); describe('forEach', function() { it('should run on all elements of the matrix, last dimension first', function() { var m, output; m = new ImmutableDenseMatrix([ [[1,2],[3,4]], [[5,6],[7,8]], [[9,10],[11,12]], [[13,14],[15,16]] ]); output = []; m.forEach(function (value) { output.push(value); }); assert.deepEqual(output, [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]); m = new ImmutableDenseMatrix([1]); output = []; m.forEach(function (value) { output.push(value); }); assert.deepEqual(output, [1]); m = new ImmutableDenseMatrix([1,2,3]); output = []; m.forEach(function (value) { output.push(value); }); assert.deepEqual(output, [1,2,3]); }); it('should work on empty matrices', function() { var m = new ImmutableDenseMatrix([]); var output = []; m.forEach(function (value) { output.push(value); }); assert.deepEqual(output, []); }); it('should invoke callback with parameters value, index, obj', function() { var m = new ImmutableDenseMatrix([[1,2,3], [4,5,6]]); var output = []; m.forEach( function (value, index, obj) { output.push(math.clone([value, index, obj === m])); } ); assert.deepEqual(output, [ [1, [0, 0], true ], [2, [0, 1], true ], [3, [0, 2], true ], [4, [1, 0], true ], [5, [1, 1], true ], [6, [1, 2], true ] ]); }); }); describe('clone', function() { it('should clone the matrix properly', function() { var m1 = new ImmutableDenseMatrix( [ [1,2,3], [4,5,6] ]); var m2 = m1.clone(); assert.deepEqual(m1._data, m2._data); }); }); describe('toArray', function () { it('should return array', function () { var m = new ImmutableDenseMatrix({ data: [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ], size: [4, 3] }); var a = m.toArray(); assert.deepEqual( a, [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ]); }); it('should return array, complex numbers', function () { var m = new ImmutableDenseMatrix({ data: [new Complex(1, 1), new Complex(4, 4), new Complex(5, 5), new Complex(2, 2), new Complex(3, 3), new Complex(6, 6)], size: [1, 6] }); var a = m.toArray(); assert.deepEqual(a, [new Complex(1, 1), new Complex(4, 4), new Complex(5, 5), new Complex(2, 2), new Complex(3, 3), new Complex(6, 6)]); }); }); describe('diagonal', function () { it('should get matrix diagonal (n x n)', function () { var m = new ImmutableDenseMatrix( [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ]); assert.deepEqual(m.diagonal(), new DenseMatrix([1, 1, 1])); }); it('should get matrix diagonal (n x n), k > 0', function () { var m = new ImmutableDenseMatrix( [ [1, 2, 0], [0, 1, 3], [0, 0, 1] ]); assert.deepEqual(m.diagonal(1), new DenseMatrix([2, 3])); }); it('should get matrix diagonal (n x n), k < 0', function () { var m = new ImmutableDenseMatrix( [ [1, 0, 0], [2, 1, 0], [0, 3, 1] ]); assert.deepEqual(m.diagonal(-1), new DenseMatrix([2, 3])); }); it('should get matrix diagonal (m x n), m > n', function () { var m = new ImmutableDenseMatrix( [ [1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 0] ]); assert.deepEqual(m.diagonal(), new DenseMatrix([1, 1, 1])); }); it('should get matrix diagonal (m x n), m > n, k > 0', function () { var m = new ImmutableDenseMatrix( [ [1, 2, 0], [0, 1, 3], [0, 0, 1], [0, 0, 0] ]); assert.deepEqual(m.diagonal(1), new DenseMatrix([2, 3])); }); it('should get matrix diagonal (m x n), m > n, k < 0', function () { var m = new ImmutableDenseMatrix( [ [1, 0, 0], [2, 1, 0], [0, 3, 1], [0, 0, 4] ]); assert.deepEqual(m.diagonal(-1), new DenseMatrix([2, 3, 4])); }); it('should get matrix diagonal (m x n), m < n', function () { var m = new ImmutableDenseMatrix( [ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0] ]); assert.deepEqual(m.diagonal(), new DenseMatrix([1, 1, 1])); }); it('should get matrix diagonal (m x n), m < n, k > 0', function () { var m = new ImmutableDenseMatrix( [ [1, 2, 0, 0], [0, 1, 3, 0], [0, 0, 1, 4] ]); assert.deepEqual(m.diagonal(1), new DenseMatrix([2, 3, 4])); }); it('should get matrix diagonal (m x n), m < n, k < 0', function () { var m = new ImmutableDenseMatrix( [ [1, 0, 0, 0], [2, 1, 0, 0], [4, 3, 1, 0] ]); assert.deepEqual(m.diagonal(-1), new DenseMatrix([2, 3])); assert.deepEqual(m.diagonal(-2), new DenseMatrix([4])); }); }); describe('swapRows', function () { it('should throw an exception on set subset', function() { var m = new ImmutableDenseMatrix( [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ]); assert.throws(function () { m.swapRows(1, 2); }, /Cannot invoke swapRows on an Immutable Matrix instance/); }); }); });
Template.replacementInsert.events = { 'click #btnSave': function(e, t) { e.preventDefault(); Router.current()._post = true; Router.current().insert(t); Router.current()._post = false; }, };
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v12.0.1 * @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); }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; Object.defineProperty(exports, "__esModule", { value: true }); var eventService_1 = require("./eventService"); var constants_1 = require("./constants"); var componentUtil_1 = require("./components/componentUtil"); var gridApi_1 = require("./gridApi"); var context_1 = require("./context/context"); var columnController_1 = require("./columnController/columnController"); var utils_1 = require("./utils"); var DEFAULT_ROW_HEIGHT = 25; var DEFAULT_VIEWPORT_ROW_MODEL_PAGE_SIZE = 5; var DEFAULT_VIEWPORT_ROW_MODEL_BUFFER_SIZE = 5; function isTrue(value) { return value === true || value === 'true'; } function zeroOrGreater(value, defaultValue) { if (value >= 0) { return value; } else { // zero gets returned if number is missing or the wrong type return defaultValue; } } function oneOrGreater(value, defaultValue) { if (value > 0) { return value; } else { // zero gets returned if number is missing or the wrong type return defaultValue; } } var GridOptionsWrapper = (function () { function GridOptionsWrapper() { this.propertyEventService = new eventService_1.EventService(); this.domDataKey = '__AG_' + Math.random().toString(); } GridOptionsWrapper_1 = GridOptionsWrapper; GridOptionsWrapper.prototype.agWire = function (gridApi, columnApi) { this.gridOptions.api = gridApi; this.gridOptions.columnApi = columnApi; this.checkForDeprecated(); }; GridOptionsWrapper.prototype.destroy = function () { // need to remove these, as we don't own the lifecycle of the gridOptions, we need to // remove the references in case the user keeps the grid options, we want the rest // of the grid to be picked up by the garbage collector this.gridOptions.api = null; this.gridOptions.columnApi = null; }; GridOptionsWrapper.prototype.init = function () { var async = this.useAsyncEvents(); this.eventService.addGlobalListener(this.globalEventHandler.bind(this), async); this.setupFrameworkComponents(); if (this.isGroupSelectsChildren() && this.isSuppressParentsInRowNodes()) { console.warn('ag-Grid: groupSelectsChildren does not work wth suppressParentsInRowNodes, this selection method needs the part in rowNode to work'); } if (this.isGroupSelectsChildren()) { if (!this.isRowSelectionMulti()) { console.warn('ag-Grid: rowSelectionMulti must be true for groupSelectsChildren to make sense'); } if (this.isRowModelEnterprise()) { console.warn('ag-Grid: group selects children is NOT support for Enterprise Row Model. ' + 'This is because the rows are lazy loaded, so selecting a group is not possible as' + 'the grid has no way of knowing what the children are.'); } } if (this.isGroupRemoveSingleChildren() && this.isGroupHideOpenParents()) { console.warn('ag-Grid: groupRemoveSingleChildren and groupHideOpenParents do not work with each other, you need to pick one. And don\'t ask us how to us these together on our support forum either you will get the same answer!'); } }; GridOptionsWrapper.prototype.setupFrameworkComponents = function () { this.fullWidthCellRenderer = this.frameworkFactory.gridOptionsFullWidthCellRenderer(this.gridOptions); this.groupRowRenderer = this.frameworkFactory.gridOptionsGroupRowRenderer(this.gridOptions); this.groupRowInnerRenderer = this.frameworkFactory.gridOptionsGroupRowInnerRenderer(this.gridOptions); }; // returns the dom data, or undefined if not found GridOptionsWrapper.prototype.getDomData = function (element, key) { var domData = element[this.domDataKey]; if (domData) { return domData[key]; } else { return undefined; } }; GridOptionsWrapper.prototype.setDomData = function (element, key, value) { var domData = element[this.domDataKey]; if (utils_1.Utils.missing(domData)) { domData = {}; element[this.domDataKey] = domData; } domData[key] = value; }; // the cellRenderers come from the instances for this class, not from gridOptions, which allows // the baseFrameworkFactory to replace with framework specific ones GridOptionsWrapper.prototype.getFullWidthCellRenderer = function () { return this.fullWidthCellRenderer; }; GridOptionsWrapper.prototype.getGroupRowRenderer = function () { return this.groupRowRenderer; }; GridOptionsWrapper.prototype.getGroupRowInnerRenderer = function () { return this.groupRowInnerRenderer; }; GridOptionsWrapper.prototype.isEnterprise = function () { return this.enterprise; }; GridOptionsWrapper.prototype.isRowSelection = function () { return this.gridOptions.rowSelection === "single" || this.gridOptions.rowSelection === "multiple"; }; GridOptionsWrapper.prototype.isRowDeselection = function () { return isTrue(this.gridOptions.rowDeselection); }; GridOptionsWrapper.prototype.isRowSelectionMulti = function () { return this.gridOptions.rowSelection === 'multiple'; }; GridOptionsWrapper.prototype.getContext = function () { return this.gridOptions.context; }; GridOptionsWrapper.prototype.isPivotMode = function () { return isTrue(this.gridOptions.pivotMode); }; GridOptionsWrapper.prototype.isPivotTotals = function () { return isTrue(this.gridOptions.pivotTotals); }; GridOptionsWrapper.prototype.isRowModelInfinite = function () { return this.gridOptions.rowModelType === constants_1.Constants.ROW_MODEL_TYPE_INFINITE; }; GridOptionsWrapper.prototype.isRowModelViewport = function () { return this.gridOptions.rowModelType === constants_1.Constants.ROW_MODEL_TYPE_VIEWPORT; }; GridOptionsWrapper.prototype.isRowModelEnterprise = function () { return this.gridOptions.rowModelType === constants_1.Constants.ROW_MODEL_TYPE_ENTERPRISE; }; GridOptionsWrapper.prototype.isRowModelDefault = function () { return utils_1.Utils.missing(this.gridOptions.rowModelType) || this.gridOptions.rowModelType === constants_1.Constants.ROW_MODEL_TYPE_IN_MEMORY || this.gridOptions.rowModelType === constants_1.Constants.DEPRECATED_ROW_MODEL_TYPE_NORMAL; }; GridOptionsWrapper.prototype.isFullRowEdit = function () { return this.gridOptions.editType === 'fullRow'; }; GridOptionsWrapper.prototype.isSuppressFocusAfterRefresh = function () { return isTrue(this.gridOptions.suppressFocusAfterRefresh); }; GridOptionsWrapper.prototype.isShowToolPanel = function () { return isTrue(this.gridOptions.showToolPanel); }; GridOptionsWrapper.prototype.isToolPanelSuppressRowGroups = function () { return isTrue(this.gridOptions.toolPanelSuppressRowGroups); }; GridOptionsWrapper.prototype.isToolPanelSuppressValues = function () { return isTrue(this.gridOptions.toolPanelSuppressValues); }; GridOptionsWrapper.prototype.isToolPanelSuppressPivots = function () { // never allow pivot mode when using enterprise model if (this.isRowModelEnterprise()) { return true; } // otherwise, let user decide return isTrue(this.gridOptions.toolPanelSuppressPivots); }; GridOptionsWrapper.prototype.isToolPanelSuppressPivotMode = function () { // never allow pivot mode when using enterprise model if (this.isRowModelEnterprise()) { return true; } // otherwise, let user decide return isTrue(this.gridOptions.toolPanelSuppressPivotMode); }; GridOptionsWrapper.prototype.isSuppressTouch = function () { return isTrue(this.gridOptions.suppressTouch); }; GridOptionsWrapper.prototype.useAsyncEvents = function () { return !isTrue(this.gridOptions.suppressAsyncEvents); }; GridOptionsWrapper.prototype.isEnableCellChangeFlash = function () { return isTrue(this.gridOptions.enableCellChangeFlash); }; GridOptionsWrapper.prototype.isGroupSelectsChildren = function () { return isTrue(this.gridOptions.groupSelectsChildren); }; GridOptionsWrapper.prototype.isGroupSelectsFiltered = function () { return isTrue(this.gridOptions.groupSelectsFiltered); }; GridOptionsWrapper.prototype.isGroupHideOpenParents = function () { return isTrue(this.gridOptions.groupHideOpenParents); }; // if we are doing hideOpenParents, then we always have groupMultiAutoColumn, otherwise hideOpenParents would not work GridOptionsWrapper.prototype.isGroupMultiAutoColumn = function () { return isTrue(this.gridOptions.groupMultiAutoColumn) || isTrue(this.gridOptions.groupHideOpenParents); }; GridOptionsWrapper.prototype.isGroupRemoveSingleChildren = function () { return isTrue(this.gridOptions.groupRemoveSingleChildren); }; GridOptionsWrapper.prototype.isGroupIncludeFooter = function () { return isTrue(this.gridOptions.groupIncludeFooter); }; GridOptionsWrapper.prototype.isGroupSuppressBlankHeader = function () { return isTrue(this.gridOptions.groupSuppressBlankHeader); }; GridOptionsWrapper.prototype.isSuppressRowClickSelection = function () { return isTrue(this.gridOptions.suppressRowClickSelection); }; GridOptionsWrapper.prototype.isSuppressCellSelection = function () { return isTrue(this.gridOptions.suppressCellSelection); }; GridOptionsWrapper.prototype.isSuppressMultiSort = function () { return isTrue(this.gridOptions.suppressMultiSort); }; GridOptionsWrapper.prototype.isGroupSuppressAutoColumn = function () { return isTrue(this.gridOptions.groupSuppressAutoColumn); }; GridOptionsWrapper.prototype.isSuppressDragLeaveHidesColumns = function () { return isTrue(this.gridOptions.suppressDragLeaveHidesColumns); }; GridOptionsWrapper.prototype.isSuppressScrollOnNewData = function () { return isTrue(this.gridOptions.suppressScrollOnNewData); }; GridOptionsWrapper.prototype.isForPrint = function () { return this.gridOptions.domLayout === 'forPrint'; }; GridOptionsWrapper.prototype.isAutoHeight = function () { return this.gridOptions.domLayout === 'autoHeight'; }; GridOptionsWrapper.prototype.isSuppressHorizontalScroll = function () { return isTrue(this.gridOptions.suppressHorizontalScroll); }; GridOptionsWrapper.prototype.isSuppressLoadingOverlay = function () { return isTrue(this.gridOptions.suppressLoadingOverlay); }; GridOptionsWrapper.prototype.isSuppressNoRowsOverlay = function () { return isTrue(this.gridOptions.suppressNoRowsOverlay); }; GridOptionsWrapper.prototype.isSuppressFieldDotNotation = function () { return isTrue(this.gridOptions.suppressFieldDotNotation); }; GridOptionsWrapper.prototype.getPinnedTopRowData = function () { return this.gridOptions.pinnedTopRowData; }; GridOptionsWrapper.prototype.getPinnedBottomRowData = function () { return this.gridOptions.pinnedBottomRowData; }; GridOptionsWrapper.prototype.isFunctionsPassive = function () { return isTrue(this.gridOptions.functionsPassive); }; GridOptionsWrapper.prototype.isSuppressRowHoverClass = function () { return isTrue(this.gridOptions.suppressRowHoverClass); }; GridOptionsWrapper.prototype.isSuppressTabbing = function () { return isTrue(this.gridOptions.suppressTabbing); }; GridOptionsWrapper.prototype.isSuppressChangeDetection = function () { return isTrue(this.gridOptions.suppressChangeDetection); }; GridOptionsWrapper.prototype.getQuickFilterText = function () { return this.gridOptions.quickFilterText; }; GridOptionsWrapper.prototype.isCacheQuickFilter = function () { return isTrue(this.gridOptions.cacheQuickFilter); }; GridOptionsWrapper.prototype.isUnSortIcon = function () { return isTrue(this.gridOptions.unSortIcon); }; GridOptionsWrapper.prototype.isSuppressMenuHide = function () { return isTrue(this.gridOptions.suppressMenuHide); }; GridOptionsWrapper.prototype.getRowStyle = function () { return this.gridOptions.rowStyle; }; GridOptionsWrapper.prototype.getRowClass = function () { return this.gridOptions.rowClass; }; GridOptionsWrapper.prototype.getRowStyleFunc = function () { return this.gridOptions.getRowStyle; }; GridOptionsWrapper.prototype.getRowClassFunc = function () { return this.gridOptions.getRowClass; }; GridOptionsWrapper.prototype.getPostProcessPopupFunc = function () { return this.gridOptions.postProcessPopup; }; GridOptionsWrapper.prototype.getDoesDataFlowerFunc = function () { return this.gridOptions.doesDataFlower; }; GridOptionsWrapper.prototype.getIsFullWidthCellFunc = function () { return this.gridOptions.isFullWidthCell; }; GridOptionsWrapper.prototype.getFullWidthCellRendererParams = function () { return this.gridOptions.fullWidthCellRendererParams; }; GridOptionsWrapper.prototype.isEmbedFullWidthRows = function () { // if autoHeight, we always embed fullWidth rows, otherwise we let the user decide return this.isAutoHeight() || isTrue(this.gridOptions.embedFullWidthRows); }; GridOptionsWrapper.prototype.getBusinessKeyForNodeFunc = function () { return this.gridOptions.getBusinessKeyForNode; }; GridOptionsWrapper.prototype.getHeaderCellRenderer = function () { return this.gridOptions.headerCellRenderer; }; GridOptionsWrapper.prototype.getApi = function () { return this.gridOptions.api; }; GridOptionsWrapper.prototype.getColumnApi = function () { return this.gridOptions.columnApi; }; GridOptionsWrapper.prototype.isDeltaRowDataMode = function () { return isTrue(this.gridOptions.deltaRowDataMode); }; GridOptionsWrapper.prototype.isEnsureDomOrder = function () { return isTrue(this.gridOptions.ensureDomOrder); }; GridOptionsWrapper.prototype.isEnableColResize = function () { return isTrue(this.gridOptions.enableColResize); }; GridOptionsWrapper.prototype.isSingleClickEdit = function () { return isTrue(this.gridOptions.singleClickEdit); }; GridOptionsWrapper.prototype.isSuppressClickEdit = function () { return isTrue(this.gridOptions.suppressClickEdit); }; GridOptionsWrapper.prototype.isStopEditingWhenGridLosesFocus = function () { return isTrue(this.gridOptions.stopEditingWhenGridLosesFocus); }; GridOptionsWrapper.prototype.getGroupDefaultExpanded = function () { return this.gridOptions.groupDefaultExpanded; }; GridOptionsWrapper.prototype.getAutoSizePadding = function () { return this.gridOptions.autoSizePadding; }; GridOptionsWrapper.prototype.getMaxConcurrentDatasourceRequests = function () { return this.gridOptions.maxConcurrentDatasourceRequests; }; GridOptionsWrapper.prototype.getMaxBlocksInCache = function () { return this.gridOptions.maxBlocksInCache; }; GridOptionsWrapper.prototype.getCacheOverflowSize = function () { return this.gridOptions.cacheOverflowSize; }; GridOptionsWrapper.prototype.getPaginationPageSize = function () { return this.gridOptions.paginationPageSize; }; GridOptionsWrapper.prototype.getCacheBlockSize = function () { return this.gridOptions.cacheBlockSize; }; GridOptionsWrapper.prototype.getInfiniteInitialRowCount = function () { return this.gridOptions.infiniteInitialRowCount; }; GridOptionsWrapper.prototype.isPurgeClosedRowNodes = function () { return isTrue(this.gridOptions.purgeClosedRowNodes); }; GridOptionsWrapper.prototype.isSuppressPaginationPanel = function () { return isTrue(this.gridOptions.suppressPaginationPanel); }; GridOptionsWrapper.prototype.getRowData = function () { return this.gridOptions.rowData; }; GridOptionsWrapper.prototype.isGroupUseEntireRow = function () { return isTrue(this.gridOptions.groupUseEntireRow); }; GridOptionsWrapper.prototype.isEnableRtl = function () { return isTrue(this.gridOptions.enableRtl); }; GridOptionsWrapper.prototype.getAutoGroupColumnDef = function () { return this.gridOptions.autoGroupColumnDef; }; GridOptionsWrapper.prototype.isGroupSuppressRow = function () { return isTrue(this.gridOptions.groupSuppressRow); }; GridOptionsWrapper.prototype.getRowGroupPanelShow = function () { return this.gridOptions.rowGroupPanelShow; }; GridOptionsWrapper.prototype.getPivotPanelShow = function () { return this.gridOptions.pivotPanelShow; }; GridOptionsWrapper.prototype.isAngularCompileRows = function () { return isTrue(this.gridOptions.angularCompileRows); }; GridOptionsWrapper.prototype.isAngularCompileFilters = function () { return isTrue(this.gridOptions.angularCompileFilters); }; GridOptionsWrapper.prototype.isAngularCompileHeaders = function () { return isTrue(this.gridOptions.angularCompileHeaders); }; GridOptionsWrapper.prototype.isDebug = function () { return isTrue(this.gridOptions.debug); }; GridOptionsWrapper.prototype.getColumnDefs = function () { return this.gridOptions.columnDefs; }; GridOptionsWrapper.prototype.getColumnTypes = function () { return this.gridOptions.columnTypes; }; GridOptionsWrapper.prototype.getDatasource = function () { return this.gridOptions.datasource; }; GridOptionsWrapper.prototype.getViewportDatasource = function () { return this.gridOptions.viewportDatasource; }; GridOptionsWrapper.prototype.getEnterpriseDatasource = function () { return this.gridOptions.enterpriseDatasource; }; GridOptionsWrapper.prototype.isEnableSorting = function () { return isTrue(this.gridOptions.enableSorting) || isTrue(this.gridOptions.enableServerSideSorting); }; GridOptionsWrapper.prototype.isAccentedSort = function () { return isTrue(this.gridOptions.accentedSort); }; GridOptionsWrapper.prototype.isEnableCellExpressions = function () { return isTrue(this.gridOptions.enableCellExpressions); }; GridOptionsWrapper.prototype.isEnableGroupEdit = function () { return isTrue(this.gridOptions.enableGroupEdit); }; GridOptionsWrapper.prototype.isSuppressMiddleClickScrolls = function () { return isTrue(this.gridOptions.suppressMiddleClickScrolls); }; GridOptionsWrapper.prototype.isSuppressPreventDefaultOnMouseWheel = function () { return isTrue(this.gridOptions.suppressPreventDefaultOnMouseWheel); }; GridOptionsWrapper.prototype.isSuppressColumnVirtualisation = function () { return isTrue(this.gridOptions.suppressColumnVirtualisation); }; GridOptionsWrapper.prototype.isSuppressContextMenu = function () { return isTrue(this.gridOptions.suppressContextMenu); }; GridOptionsWrapper.prototype.isAllowContextMenuWithControlKey = function () { return isTrue(this.gridOptions.allowContextMenuWithControlKey); }; GridOptionsWrapper.prototype.isSuppressCopyRowsToClipboard = function () { return isTrue(this.gridOptions.suppressCopyRowsToClipboard); }; GridOptionsWrapper.prototype.isEnableFilter = function () { return isTrue(this.gridOptions.enableFilter) || isTrue(this.gridOptions.enableServerSideFilter); }; GridOptionsWrapper.prototype.isPagination = function () { return isTrue(this.gridOptions.pagination); }; // these are deprecated, should remove them when we take out server side pagination GridOptionsWrapper.prototype.isEnableServerSideFilter = function () { return this.gridOptions.enableServerSideFilter; }; GridOptionsWrapper.prototype.isEnableServerSideSorting = function () { return isTrue(this.gridOptions.enableServerSideSorting); }; GridOptionsWrapper.prototype.isSuppressScrollLag = function () { return isTrue(this.gridOptions.suppressScrollLag); }; GridOptionsWrapper.prototype.isSuppressMovableColumns = function () { return isTrue(this.gridOptions.suppressMovableColumns); }; GridOptionsWrapper.prototype.isAnimateRows = function () { // never allow animating if enforcing the row order if (this.isEnsureDomOrder()) { return false; } return isTrue(this.gridOptions.animateRows); }; GridOptionsWrapper.prototype.isSuppressColumnMoveAnimation = function () { return isTrue(this.gridOptions.suppressColumnMoveAnimation); }; GridOptionsWrapper.prototype.isSuppressAggFuncInHeader = function () { return isTrue(this.gridOptions.suppressAggFuncInHeader); }; GridOptionsWrapper.prototype.isSuppressAggAtRootLevel = function () { return isTrue(this.gridOptions.suppressAggAtRootLevel); }; GridOptionsWrapper.prototype.isEnableRangeSelection = function () { return isTrue(this.gridOptions.enableRangeSelection); }; GridOptionsWrapper.prototype.isPaginationAutoPageSize = function () { return isTrue(this.gridOptions.paginationAutoPageSize); }; GridOptionsWrapper.prototype.isRememberGroupStateWhenNewData = function () { return isTrue(this.gridOptions.rememberGroupStateWhenNewData); }; GridOptionsWrapper.prototype.getIcons = function () { return this.gridOptions.icons; }; GridOptionsWrapper.prototype.getAggFuncs = function () { return this.gridOptions.aggFuncs; }; GridOptionsWrapper.prototype.getIsScrollLag = function () { return this.gridOptions.isScrollLag; }; GridOptionsWrapper.prototype.getSortingOrder = function () { return this.gridOptions.sortingOrder; }; GridOptionsWrapper.prototype.getAlignedGrids = function () { return this.gridOptions.alignedGrids; }; GridOptionsWrapper.prototype.getGroupRowRendererParams = function () { return this.gridOptions.groupRowRendererParams; }; GridOptionsWrapper.prototype.getOverlayLoadingTemplate = function () { return this.gridOptions.overlayLoadingTemplate; }; GridOptionsWrapper.prototype.getOverlayNoRowsTemplate = function () { return this.gridOptions.overlayNoRowsTemplate; }; GridOptionsWrapper.prototype.isSuppressAutoSize = function () { return isTrue(this.gridOptions.suppressAutoSize); }; GridOptionsWrapper.prototype.isSuppressParentsInRowNodes = function () { return isTrue(this.gridOptions.suppressParentsInRowNodes); }; GridOptionsWrapper.prototype.isEnableStatusBar = function () { return isTrue(this.gridOptions.enableStatusBar); }; GridOptionsWrapper.prototype.isAlwaysShowStatusBar = function () { return isTrue(this.gridOptions.alwaysShowStatusBar); }; GridOptionsWrapper.prototype.isFunctionsReadOnly = function () { return isTrue(this.gridOptions.functionsReadOnly); }; GridOptionsWrapper.prototype.isFloatingFilter = function () { return this.gridOptions.floatingFilter; }; // public isFloatingFilter(): boolean { return true; } GridOptionsWrapper.prototype.getDefaultColDef = function () { return this.gridOptions.defaultColDef; }; GridOptionsWrapper.prototype.getDefaultColGroupDef = function () { return this.gridOptions.defaultColGroupDef; }; GridOptionsWrapper.prototype.getDefaultExportParams = function () { return this.gridOptions.defaultExportParams; }; GridOptionsWrapper.prototype.getHeaderCellTemplate = function () { return this.gridOptions.headerCellTemplate; }; GridOptionsWrapper.prototype.getHeaderCellTemplateFunc = function () { return this.gridOptions.getHeaderCellTemplate; }; GridOptionsWrapper.prototype.getNodeChildDetailsFunc = function () { return this.gridOptions.getNodeChildDetails; }; GridOptionsWrapper.prototype.getGroupRowAggNodesFunc = function () { return this.gridOptions.groupRowAggNodes; }; GridOptionsWrapper.prototype.getContextMenuItemsFunc = function () { return this.gridOptions.getContextMenuItems; }; GridOptionsWrapper.prototype.getMainMenuItemsFunc = function () { return this.gridOptions.getMainMenuItems; }; GridOptionsWrapper.prototype.getRowNodeIdFunc = function () { return this.gridOptions.getRowNodeId; }; GridOptionsWrapper.prototype.getNavigateToNextCellFunc = function () { return this.gridOptions.navigateToNextCell; }; GridOptionsWrapper.prototype.getTabToNextCellFunc = function () { return this.gridOptions.tabToNextCell; }; GridOptionsWrapper.prototype.isValueCache = function () { return isTrue(this.gridOptions.valueCache); }; GridOptionsWrapper.prototype.isValueCacheNeverExpires = function () { return isTrue(this.gridOptions.valueCacheNeverExpires); }; GridOptionsWrapper.prototype.isAggregateOnlyChangedColumns = function () { return isTrue(this.gridOptions.aggregateOnlyChangedColumns); }; GridOptionsWrapper.prototype.getProcessSecondaryColDefFunc = function () { return this.gridOptions.processSecondaryColDef; }; GridOptionsWrapper.prototype.getProcessSecondaryColGroupDefFunc = function () { return this.gridOptions.processSecondaryColGroupDef; }; GridOptionsWrapper.prototype.getSendToClipboardFunc = function () { return this.gridOptions.sendToClipboard; }; GridOptionsWrapper.prototype.getProcessCellForClipboardFunc = function () { return this.gridOptions.processCellForClipboard; }; GridOptionsWrapper.prototype.getProcessCellFromClipboardFunc = function () { return this.gridOptions.processCellFromClipboard; }; GridOptionsWrapper.prototype.getViewportRowModelPageSize = function () { return oneOrGreater(this.gridOptions.viewportRowModelPageSize, DEFAULT_VIEWPORT_ROW_MODEL_PAGE_SIZE); }; GridOptionsWrapper.prototype.getViewportRowModelBufferSize = function () { return zeroOrGreater(this.gridOptions.viewportRowModelBufferSize, DEFAULT_VIEWPORT_ROW_MODEL_BUFFER_SIZE); }; // public getCellRenderers(): {[key: string]: {new(): ICellRenderer} | ICellRendererFunc} { return this.gridOptions.cellRenderers; } // public getCellEditors(): {[key: string]: {new(): ICellEditor}} { return this.gridOptions.cellEditors; } GridOptionsWrapper.prototype.getClipboardDeliminator = function () { return utils_1.Utils.exists(this.gridOptions.clipboardDeliminator) ? this.gridOptions.clipboardDeliminator : '\t'; }; GridOptionsWrapper.prototype.setProperty = function (key, value) { var gridOptionsNoType = this.gridOptions; var previousValue = gridOptionsNoType[key]; if (previousValue !== value) { gridOptionsNoType[key] = value; this.propertyEventService.dispatchEvent(key, { currentValue: value, previousValue: previousValue }); } }; GridOptionsWrapper.prototype.addEventListener = function (key, listener) { this.propertyEventService.addEventListener(key, listener); }; GridOptionsWrapper.prototype.removeEventListener = function (key, listener) { this.propertyEventService.removeEventListener(key, listener); }; GridOptionsWrapper.prototype.executeProcessRowPostCreateFunc = function (params) { if (this.gridOptions.processRowPostCreate) { this.gridOptions.processRowPostCreate(params); } }; // properties GridOptionsWrapper.prototype.getHeaderHeight = function () { if (typeof this.gridOptions.headerHeight === 'number') { return this.gridOptions.headerHeight; } else { return 25; } }; GridOptionsWrapper.prototype.getFloatingFiltersHeight = function () { if (typeof this.gridOptions.floatingFiltersHeight === 'number') { return this.gridOptions.floatingFiltersHeight; } else { return 20; } }; GridOptionsWrapper.prototype.getGroupHeaderHeight = function () { if (typeof this.gridOptions.groupHeaderHeight === 'number') { return this.gridOptions.groupHeaderHeight; } else { return this.getHeaderHeight(); } }; GridOptionsWrapper.prototype.getPivotHeaderHeight = function () { if (typeof this.gridOptions.pivotHeaderHeight === 'number') { return this.gridOptions.pivotHeaderHeight; } else { return this.getHeaderHeight(); } }; GridOptionsWrapper.prototype.getPivotGroupHeaderHeight = function () { if (typeof this.gridOptions.pivotGroupHeaderHeight === 'number') { return this.gridOptions.pivotGroupHeaderHeight; } else { return this.getGroupHeaderHeight(); } }; GridOptionsWrapper.prototype.isExternalFilterPresent = function () { if (typeof this.gridOptions.isExternalFilterPresent === 'function') { return this.gridOptions.isExternalFilterPresent(); } else { return false; } }; GridOptionsWrapper.prototype.doesExternalFilterPass = function (node) { if (typeof this.gridOptions.doesExternalFilterPass === 'function') { return this.gridOptions.doesExternalFilterPass(node); } else { return false; } }; GridOptionsWrapper.prototype.getDocument = function () { // if user is providing document, we use the users one, // otherwise we use the document on the global namespace. var result; if (utils_1.Utils.exists(this.gridOptions.getDocument)) { result = this.gridOptions.getDocument(); } if (utils_1.Utils.exists(result)) { return result; } else { return document; } }; GridOptionsWrapper.prototype.getLayoutInterval = function () { if (typeof this.gridOptions.layoutInterval === 'number') { return this.gridOptions.layoutInterval; } else { return constants_1.Constants.LAYOUT_INTERVAL; } }; GridOptionsWrapper.prototype.getMinColWidth = function () { if (this.gridOptions.minColWidth > GridOptionsWrapper_1.MIN_COL_WIDTH) { return this.gridOptions.minColWidth; } else { return GridOptionsWrapper_1.MIN_COL_WIDTH; } }; GridOptionsWrapper.prototype.getMaxColWidth = function () { if (this.gridOptions.maxColWidth > GridOptionsWrapper_1.MIN_COL_WIDTH) { return this.gridOptions.maxColWidth; } else { return null; } }; GridOptionsWrapper.prototype.getColWidth = function () { if (typeof this.gridOptions.colWidth !== 'number' || this.gridOptions.colWidth < GridOptionsWrapper_1.MIN_COL_WIDTH) { return 200; } else { return this.gridOptions.colWidth; } }; GridOptionsWrapper.prototype.getRowBuffer = function () { if (typeof this.gridOptions.rowBuffer === 'number') { if (this.gridOptions.rowBuffer < 0) { console.warn('ag-Grid: rowBuffer should not be negative'); } return this.gridOptions.rowBuffer; } else { return constants_1.Constants.ROW_BUFFER_SIZE; } }; // the user might be using some non-standard scrollbar, eg a scrollbar that has zero // width and overlays (like the Safari scrollbar, but presented in Chrome). so we // allow the user to provide the scroll width before we work it out. GridOptionsWrapper.prototype.getScrollbarWidth = function () { var scrollbarWidth = this.gridOptions.scrollbarWidth; if (typeof scrollbarWidth !== 'number' || scrollbarWidth < 0) { scrollbarWidth = utils_1.Utils.getScrollbarWidth(); } return scrollbarWidth; }; GridOptionsWrapper.prototype.checkForDeprecated = function () { // casting to generic object, so typescript compiles even though // we are looking for attributes that don't exist var options = this.gridOptions; if (options.suppressUnSort) { console.warn('ag-grid: as of v1.12.4 suppressUnSort is not used. Please use sortOrder instead.'); } if (options.suppressDescSort) { console.warn('ag-grid: as of v1.12.4 suppressDescSort is not used. Please use sortOrder instead.'); } if (options.groupAggFields) { console.warn('ag-grid: as of v3 groupAggFields is not used. Please add appropriate agg fields to your columns.'); } if (options.groupHidePivotColumns) { console.warn('ag-grid: as of v3 groupHidePivotColumns is not used as pivot columns are now called rowGroup columns. Please refer to the documentation'); } if (options.groupKeys) { console.warn('ag-grid: as of v3 groupKeys is not used. You need to set rowGroupIndex on the columns to group. Please refer to the documentation'); } if (typeof options.groupDefaultExpanded === 'boolean') { console.warn('ag-grid: groupDefaultExpanded can no longer be boolean. for groupDefaultExpanded=true, use groupDefaultExpanded=9999 instead, to expand all the groups'); } if (options.onRowDeselected || options.rowDeselected) { console.warn('ag-grid: since version 3.4 event rowDeselected no longer exists, please check the docs'); } if (options.rowsAlreadyGrouped) { console.warn('ag-grid: since version 3.4 rowsAlreadyGrouped no longer exists, please use getNodeChildDetails() instead'); } if (options.groupAggFunction) { console.warn('ag-grid: since version 4.3.x groupAggFunction is now called groupRowAggNodes'); } if (options.checkboxSelection) { console.warn('ag-grid: since version 8.0.x checkboxSelection is not supported as a grid option. ' + 'If you want this on all columns, use defaultColDef instead and set it there'); } if (options.paginationInitialRowCount) { console.warn('ag-grid: since version 9.0.x paginationInitialRowCount is now called infiniteInitialRowCount'); } if (options.infinitePageSize) { console.warn('ag-grid: since version 9.0.x infinitePageSize is now called cacheBlockSize'); } if (options.infiniteBlockSize) { console.warn('ag-grid: since version 10.0.x infiniteBlockSize is now called cacheBlockSize'); } if (options.maxPagesInCache) { console.warn('ag-grid: since version 10.0.x maxPagesInCache is now called maxBlocksInCache'); } if (options.paginationOverflowSize) { console.warn('ag-grid: since version 10.0.x paginationOverflowSize is now called cacheOverflowSize'); } if (options.forPrint) { console.warn('ag-grid: since version 10.1.x, use property domLayout="forPrint" instead of forPrint=true'); } if (options.suppressMenuFilterPanel) { console.warn("ag-grid: since version 11.0.x, use property colDef.menuTabs=['filterMenuTab'] instead of suppressMenuFilterPanel=true"); } if (options.suppressMenuMainPanel) { console.warn("ag-grid: since version 11.0.x, use property colDef.menuTabs=['generalMenuTab'] instead of suppressMenuMainPanel=true"); } if (options.suppressMenuColumnPanel) { console.warn("ag-grid: since version 11.0.x, use property colDef.menuTabs=['columnsMenuTab'] instead of suppressMenuColumnPanel=true"); } if (options.suppressUseColIdForGroups) { console.warn("ag-grid: since version 11.0.x, this is not in use anymore. You should be able to remove it from your definition"); } if (options.groupColumnDef) { console.warn("ag-grid: since version 11.0.x, groupColumnDef has been renamed, this property is now called autoGroupColumnDef. Please change your configuration accordingly"); } if (options.slaveGrids) { console.warn("ag-grid: since version 12.x, slaveGrids has been renamed, this property is now called alignedGrids. Please change your configuration accordingly"); } if (options.floatingTopRowData) { console.warn("ag-grid: since version 12.x, floatingTopRowData is now called pinnedTopRowData"); } if (options.floatingBottomRowData) { console.warn("ag-grid: since version 12.x, floatingBottomRowData is now called pinnedBottomRowData"); } if (options.paginationStartPage) { console.warn("ag-grid: since version 12.x, paginationStartPage is gone, please call api.paginationGoToPage(" + options.paginationStartPage + ") instead."); } }; GridOptionsWrapper.prototype.getLocaleTextFunc = function () { if (this.gridOptions.localeTextFunc) { return this.gridOptions.localeTextFunc; } var that = this; return function (key, defaultValue) { var localeText = that.gridOptions.localeText; if (localeText && localeText[key]) { return localeText[key]; } else { return defaultValue; } }; }; // responsible for calling the onXXX functions on gridOptions GridOptionsWrapper.prototype.globalEventHandler = function (eventName, event) { var callbackMethodName = componentUtil_1.ComponentUtil.getCallbackForEvent(eventName); if (typeof this.gridOptions[callbackMethodName] === 'function') { this.gridOptions[callbackMethodName](event); } }; // we don't allow dynamic row height for virtual paging GridOptionsWrapper.prototype.getRowHeightAsNumber = function () { var rowHeight = this.gridOptions.rowHeight; if (utils_1.Utils.missing(rowHeight)) { return DEFAULT_ROW_HEIGHT; } else if (this.isNumeric(this.gridOptions.rowHeight)) { return this.gridOptions.rowHeight; } else { console.warn('ag-Grid row height must be a number if not using standard row model'); return DEFAULT_ROW_HEIGHT; } }; GridOptionsWrapper.prototype.getRowHeightForNode = function (rowNode) { // check the function first, in case use set both function and // number, when using virtual pagination then function can be // used for pinned rows and the number for the body rows. if (typeof this.gridOptions.getRowHeight === 'function') { var params = { node: rowNode, data: rowNode.data, api: this.gridOptions.api, context: this.gridOptions.context }; return this.gridOptions.getRowHeight(params); } else if (this.isNumeric(this.gridOptions.rowHeight)) { return this.gridOptions.rowHeight; } else { return DEFAULT_ROW_HEIGHT; } }; GridOptionsWrapper.prototype.isDynamicRowHeight = function () { return typeof this.gridOptions.getRowHeight === 'function'; }; GridOptionsWrapper.prototype.isNumeric = function (value) { return !isNaN(value) && typeof value === 'number'; }; GridOptionsWrapper.MIN_COL_WIDTH = 10; GridOptionsWrapper.PROP_HEADER_HEIGHT = 'headerHeight'; GridOptionsWrapper.PROP_GROUP_REMOVE_SINGLE_CHILDREN = 'groupRemoveSingleChildren'; GridOptionsWrapper.PROP_PIVOT_HEADER_HEIGHT = 'pivotHeaderHeight'; GridOptionsWrapper.PROP_GROUP_HEADER_HEIGHT = 'groupHeaderHeight'; GridOptionsWrapper.PROP_PIVOT_GROUP_HEADER_HEIGHT = 'pivotGroupHeaderHeight'; GridOptionsWrapper.PROP_FLOATING_FILTERS_HEIGHT = 'floatingFiltersHeight'; __decorate([ context_1.Autowired('gridOptions'), __metadata("design:type", Object) ], GridOptionsWrapper.prototype, "gridOptions", void 0); __decorate([ context_1.Autowired('columnController'), __metadata("design:type", columnController_1.ColumnController) ], GridOptionsWrapper.prototype, "columnController", void 0); __decorate([ context_1.Autowired('eventService'), __metadata("design:type", eventService_1.EventService) ], GridOptionsWrapper.prototype, "eventService", void 0); __decorate([ context_1.Autowired('enterprise'), __metadata("design:type", Boolean) ], GridOptionsWrapper.prototype, "enterprise", void 0); __decorate([ context_1.Autowired('frameworkFactory'), __metadata("design:type", Object) ], GridOptionsWrapper.prototype, "frameworkFactory", void 0); __decorate([ __param(0, context_1.Qualifier('gridApi')), __param(1, context_1.Qualifier('columnApi')), __metadata("design:type", Function), __metadata("design:paramtypes", [gridApi_1.GridApi, columnController_1.ColumnApi]), __metadata("design:returntype", void 0) ], GridOptionsWrapper.prototype, "agWire", null); __decorate([ context_1.PreDestroy, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], GridOptionsWrapper.prototype, "destroy", null); __decorate([ context_1.PostConstruct, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], GridOptionsWrapper.prototype, "init", null); GridOptionsWrapper = GridOptionsWrapper_1 = __decorate([ context_1.Bean('gridOptionsWrapper') ], GridOptionsWrapper); return GridOptionsWrapper; var GridOptionsWrapper_1; }()); exports.GridOptionsWrapper = GridOptionsWrapper;
/*! * inferno-redux v1.3.0-rc.0 * (c) 2017 Dominic Gannaway' * Released under the MIT License. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('inferno-component'), require('redux'), require('hoist-non-inferno-statics'), require('inferno-create-element')) : typeof define === 'function' && define.amd ? define(['exports', 'inferno-component', 'redux', 'hoist-non-inferno-statics', 'inferno-create-element'], factory) : (factory((global['inferno-redux'] = global['inferno-redux'] || {}),global.Inferno.Component,global.redux,global.hoistStatics,global.Inferno.createElement)); }(this, (function (exports,Component,redux,hoistStatics,createElement) { 'use strict'; Component = 'default' in Component ? Component['default'] : Component; hoistStatics = 'default' in hoistStatics ? hoistStatics['default'] : hoistStatics; createElement = 'default' in createElement ? createElement['default'] : createElement; var ERROR_MSG = 'a runtime error occured! Use Inferno in development environment to find the error.'; function toArray(children) { return isArray(children) ? children : (children ? [children] : children); } // this is MUCH faster than .constructor === Array and instanceof Array // in Node 7 and the later versions of V8, slower in older versions though var isArray = Array.isArray; function isNullOrUndef(obj) { return isUndefined(obj) || isNull(obj); } function isFunction(obj) { return typeof obj === 'function'; } function isNull(obj) { return obj === null; } function isUndefined(obj) { return obj === undefined; } function throwError(message) { if (!message) { message = ERROR_MSG; } throw new Error(("Inferno Error: " + message)); } var EMPTY_OBJ = {}; { Object.freeze(EMPTY_OBJ); } /** * Prints a warning in the console if it exists. * * @param {String} message The warning message. * @returns {void} */ function warning$1(message) { /* eslint-disable no-console */ if (typeof console !== 'undefined' && typeof console.error === 'function') { console.error(message); } /* eslint-enable no-console */ try { // This error was thrown as a convenience so that if you enable // "break on all exceptions" in your console, // it would pause the execution at this line. throw new Error(message); } catch (e) { } /* eslint-enable no-empty */ } function shallowEqual(objA, objB) { if (objA === objB) { return true; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. var hasOwn = Object.prototype.hasOwnProperty; for (var i = 0, len = keysA.length; i < len; i++) { var key = keysA[i]; if (!hasOwn.call(objB, key) || objA[key] !== objB[key]) { return false; } } return true; } function wrapActionCreators(actionCreators) { return function (dispatch) { return redux.bindActionCreators(actionCreators, dispatch); }; } var didWarnAboutReceivingStore = false; function warnAboutReceivingStore() { if (didWarnAboutReceivingStore) { return; } didWarnAboutReceivingStore = true; warning$1('<Provider> does not support changing `store` on the fly.'); } var Provider = (function (Component$$1) { function Provider(props, context) { Component$$1.call(this, props, context); this.store = props.store; } if ( Component$$1 ) Provider.__proto__ = Component$$1; Provider.prototype = Object.create( Component$$1 && Component$$1.prototype ); Provider.prototype.constructor = Provider; Provider.prototype.getChildContext = function getChildContext () { return { store: this.store }; }; Provider.prototype.render = function render () { if (isNullOrUndef(this.props.children) || toArray(this.props.children).length !== 1) { throw Error('Inferno Error: Only one child is allowed within the `Provider` component'); } return this.props.children; }; return Provider; }(Component)); { Provider.prototype.componentWillReceiveProps = function (nextProps) { var ref = this; var store = ref.store; var nextStore = nextProps.store; if (store !== nextStore) { warnAboutReceivingStore(); } }; } // From https://github.com/lodash/lodash/blob/es function overArg(func, transform) { return function (arg) { return func(transform(arg)); }; } var getPrototype = overArg(Object.getPrototypeOf, Object); function isObjectLike(value) { return value != null && typeof value === 'object'; } var objectTag = '[object Object]'; var funcProto = Function.prototype; var objectProto = Object.prototype; var funcToString = funcProto.toString; var hasOwnProperty = objectProto.hasOwnProperty; var objectCtorString = funcToString.call(Object); var objectToString = objectProto.toString; function isPlainObject(value) { if (!isObjectLike(value) || objectToString.call(value) !== objectTag) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return (typeof Ctor === 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) === objectCtorString); } var errorObject = { value: null }; var defaultMapStateToProps = function (state) { return ({}); }; // eslint-disable-line no-unused-vars var defaultMapDispatchToProps = function (dispatch) { return ({ dispatch: dispatch }); }; var defaultMergeProps = function (stateProps, dispatchProps, parentProps) { return Object.assign({}, parentProps, stateProps, dispatchProps); }; function tryCatch(fn, ctx) { try { return fn.apply(ctx); } catch (e) { errorObject.value = e; return errorObject; } } function getDisplayName(WrappedComponent) { return WrappedComponent.displayName || WrappedComponent.name || 'Component'; } // Helps track hot reloading. var nextVersion = 0; function connect(mapStateToProps, mapDispatchToProps, mergeProps, options) { if ( options === void 0 ) options = {}; var shouldSubscribe = Boolean(mapStateToProps); var mapState = mapStateToProps || defaultMapStateToProps; var mapDispatch; if (isFunction(mapDispatchToProps)) { mapDispatch = mapDispatchToProps; } else if (!mapDispatchToProps) { mapDispatch = defaultMapDispatchToProps; } else { mapDispatch = wrapActionCreators(mapDispatchToProps); } var finalMergeProps = mergeProps || defaultMergeProps; var pure = options.pure; if ( pure === void 0 ) pure = true; var withRef = options.withRef; if ( withRef === void 0 ) withRef = false; var checkMergedEquals = pure && finalMergeProps !== defaultMergeProps; // Helps track hot reloading. var version = nextVersion++; return function wrapWithConnect(WrappedComponent) { var connectDisplayName = "Connect(" + (getDisplayName(WrappedComponent)) + ")"; function checkStateShape(props, methodName) { if (!isPlainObject(props)) { warning$1(methodName + "() in " + connectDisplayName + " must return a plain object. " + "Instead received " + props + "."); } } function computeMergedProps(stateProps, dispatchProps, parentProps) { var mergedProps = finalMergeProps(stateProps, dispatchProps, parentProps); { checkStateShape(mergedProps, 'mergeProps'); } return mergedProps; } var Connect = (function (Component$$1) { function Connect(props, context) { var this$1 = this; Component$$1.call(this, props, context); this.version = version; this.wrappedInstance = null; this.store = (props && props.store) || (context && context.store); this.componentDidMount = function () { this$1.trySubscribe(); }; if (!this.store) { throwError('Could not find "store" in either the context or ' + "props of \"" + connectDisplayName + "\". " + 'Either wrap the root component in a <Provider>, ' + "or explicitly pass \"store\" as a prop to \"" + connectDisplayName + "\"."); } var storeState = this.store.getState(); this.state = { storeState: storeState }; this.clearCache(); } if ( Component$$1 ) Connect.__proto__ = Component$$1; Connect.prototype = Object.create( Component$$1 && Component$$1.prototype ); Connect.prototype.constructor = Connect; Connect.prototype.shouldComponentUpdate = function shouldComponentUpdate () { return !pure || this.haveOwnPropsChanged || this.hasStoreStateChanged; }; Connect.prototype.computeStateProps = function computeStateProps (store, props) { if (!this.finalMapStateToProps) { return this.configureFinalMapState(store, props); } var state = store.getState(); var stateProps = this.doStatePropsDependOnOwnProps ? this.finalMapStateToProps(state, props) : this.finalMapStateToProps(state); return stateProps; }; Connect.prototype.configureFinalMapState = function configureFinalMapState (store, props) { var mappedState = mapState(store.getState(), props); var isFactory = isFunction(mappedState); this.finalMapStateToProps = isFactory ? mappedState : mapState; this.doStatePropsDependOnOwnProps = this.finalMapStateToProps.length !== 1; if (isFactory) { return this.computeStateProps(store, props); } return mappedState; }; Connect.prototype.computeDispatchProps = function computeDispatchProps (store, props) { if (!this.finalMapDispatchToProps) { return this.configureFinalMapDispatch(store, props); } var dispatch = store.dispatch; var dispatchProps = this.doDispatchPropsDependOnOwnProps ? this.finalMapDispatchToProps(dispatch, props) : this.finalMapDispatchToProps(dispatch); return dispatchProps; }; Connect.prototype.configureFinalMapDispatch = function configureFinalMapDispatch (store, props) { var mappedDispatch = mapDispatch(store.dispatch, props); var isFactory = isFunction(mappedDispatch); this.finalMapDispatchToProps = isFactory ? mappedDispatch : mapDispatch; this.doDispatchPropsDependOnOwnProps = this.finalMapDispatchToProps.length !== 1; if (isFactory) { return this.computeDispatchProps(store, props); } return mappedDispatch; }; Connect.prototype.updateStatePropsIfNeeded = function updateStatePropsIfNeeded () { var nextStateProps = this.computeStateProps(this.store, this.props); if (this.stateProps && shallowEqual(nextStateProps, this.stateProps)) { return false; } this.stateProps = nextStateProps; return true; }; Connect.prototype.updateDispatchPropsIfNeeded = function updateDispatchPropsIfNeeded () { var nextDispatchProps = this.computeDispatchProps(this.store, this.props); if (this.dispatchProps && shallowEqual(nextDispatchProps, this.dispatchProps)) { return false; } this.dispatchProps = nextDispatchProps; return true; }; Connect.prototype.updateMergedPropsIfNeeded = function updateMergedPropsIfNeeded () { var nextMergedProps = computeMergedProps(this.stateProps, this.dispatchProps, this.props); if (this.mergedProps && checkMergedEquals && shallowEqual(nextMergedProps, this.mergedProps)) { return false; } this.mergedProps = nextMergedProps; return true; }; Connect.prototype.isSubscribed = function isSubscribed () { return isFunction(this.unsubscribe); }; Connect.prototype.trySubscribe = function trySubscribe () { if (shouldSubscribe && !this.unsubscribe) { this.unsubscribe = this.store.subscribe(this.handleChange.bind(this)); this.handleChange(); } }; Connect.prototype.tryUnsubscribe = function tryUnsubscribe () { if (this.unsubscribe) { this.unsubscribe(); this.unsubscribe = null; } }; Connect.prototype.componentWillReceiveProps = function componentWillReceiveProps (nextProps) { if (!pure || !shallowEqual(nextProps, this.props)) { this.haveOwnPropsChanged = true; } }; Connect.prototype.componentWillUnmount = function componentWillUnmount () { this.tryUnsubscribe(); this.clearCache(); }; Connect.prototype.clearCache = function clearCache () { this.dispatchProps = null; this.stateProps = null; this.mergedProps = null; this.haveOwnPropsChanged = true; this.hasStoreStateChanged = true; this.haveStatePropsBeenPrecalculated = false; this.statePropsPrecalculationError = null; this.renderedElement = null; this.finalMapDispatchToProps = null; this.finalMapStateToProps = null; }; Connect.prototype.handleChange = function handleChange () { if (!this.unsubscribe) { return; } var storeState = this.store.getState(); var prevStoreState = this.state.storeState; if (pure && prevStoreState === storeState) { return; } if (pure && !this.doStatePropsDependOnOwnProps) { var haveStatePropsChanged = tryCatch(this.updateStatePropsIfNeeded, this); if (!haveStatePropsChanged) { return; } if (haveStatePropsChanged === errorObject) { this.statePropsPrecalculationError = errorObject.value; } this.haveStatePropsBeenPrecalculated = true; } this.hasStoreStateChanged = true; this.setState({ storeState: storeState }); }; Connect.prototype.getWrappedInstance = function getWrappedInstance () { return this.wrappedInstance; }; Connect.prototype.render = function render () { var this$1 = this; var ref = this; var haveOwnPropsChanged = ref.haveOwnPropsChanged; var hasStoreStateChanged = ref.hasStoreStateChanged; var haveStatePropsBeenPrecalculated = ref.haveStatePropsBeenPrecalculated; var statePropsPrecalculationError = ref.statePropsPrecalculationError; var renderedElement = ref.renderedElement; this.haveOwnPropsChanged = false; this.hasStoreStateChanged = false; this.haveStatePropsBeenPrecalculated = false; this.statePropsPrecalculationError = null; if (statePropsPrecalculationError) { throw statePropsPrecalculationError; } var shouldUpdateStateProps = true; var shouldUpdateDispatchProps = true; if (pure && renderedElement) { shouldUpdateStateProps = hasStoreStateChanged || (haveOwnPropsChanged && this.doStatePropsDependOnOwnProps); shouldUpdateDispatchProps = haveOwnPropsChanged && this.doDispatchPropsDependOnOwnProps; } var haveStatePropsChanged = false; var haveDispatchPropsChanged = false; if (haveStatePropsBeenPrecalculated) { haveStatePropsChanged = true; } else if (shouldUpdateStateProps) { haveStatePropsChanged = this.updateStatePropsIfNeeded(); } if (shouldUpdateDispatchProps) { haveDispatchPropsChanged = this.updateDispatchPropsIfNeeded(); } var haveMergedPropsChanged = true; if (haveStatePropsChanged || haveDispatchPropsChanged || haveOwnPropsChanged) { haveMergedPropsChanged = this.updateMergedPropsIfNeeded(); } else { haveMergedPropsChanged = false; } if (!haveMergedPropsChanged && renderedElement) { return renderedElement; } if (withRef) { this.renderedElement = createElement(WrappedComponent, Object.assign({}, this.mergedProps, { ref: function (instance) { return this$1.wrappedInstance = instance; } })); } else { this.renderedElement = createElement(WrappedComponent, this.mergedProps); } return this.renderedElement; }; return Connect; }(Component)); Connect.displayName = connectDisplayName; Connect.WrappedComponent = WrappedComponent; { Connect.prototype.componentWillUpdate = function componentWillUpdate() { if (this.version === version) { return; } // We are hot reloading! this.version = version; this.trySubscribe(); this.clearCache(); }; } return hoistStatics(Connect, WrappedComponent); }; } var index = { Provider: Provider, connect: connect }; exports['default'] = index; exports.Provider = Provider; exports.connect = connect; Object.defineProperty(exports, '__esModule', { value: true }); })));
import Result from '../lib/result'; import parse from '../lib/parse'; import { expect } from 'chai'; import path from 'path'; import fs from 'fs'; describe('Root', () => { describe('toString()', () => { fs.readdirSync(path.join(__dirname, 'cases')).forEach( name => { if ( !name.match(/\.css$/) ) return; it('stringify ' + name, () => { let file = path.join(__dirname, 'cases', name); let css = fs.readFileSync(file).toString(); expect(parse(css, { from: file }).toString()).to.eql(css); }); }); }); describe('prepend()', () => { it('fixes spaces on insert before first', () => { let css = parse('a {} b {}'); css.prepend({ selector: 'em' }); expect(css.toString()).to.eql('em {} a {} b {}'); }); it('uses default spaces on only first', () => { let css = parse('a {}'); css.prepend({ selector: 'em' }); expect(css.toString()).to.eql('em {}\na {}'); }); }); describe('append()', () => { it('sets new line between rules in multiline files', () => { let a = parse('a {}\n\na {}\n'); let b = parse('b {}\n'); expect(a.append(b).toString()).to.eql('a {}\n\na {}\n\nb {}\n'); }); it('sets new line between rules on last newline', () => { let a = parse('a {}\n'); let b = parse('b {}\n'); expect(a.append(b).toString()).to.eql('a {}\nb {}\n'); }); it('saves compressed style', () => { let a = parse('a{}a{}'); let b = parse('b {\n}\n'); expect(a.append(b).toString()).to.eql('a{}a{}b{}'); }); }); describe('insertAfter()', () => { it('does not use before of first rule', () => { let css = parse('a{} b{}'); css.insertAfter(0, { selector: '.a' }); css.insertAfter(2, { selector: '.b' }); expect(css.nodes[1].before).to.not.exist; expect(css.nodes[3].before).to.eql(' '); expect(css.toString()).to.eql('a{} .a{} b{} .b{}'); }); }); describe('remove()', () => { it('fixes spaces on removing first rule', () => { let css = parse('a{}\nb{}\n'); css.first.removeSelf(); expect(css.toString()).to.eql('b{}\n'); }); }); describe('toResult()', () => { it('generates result with map', () => { let root = parse('a {}'); let result = root.toResult({ map: true }); expect(result).to.be.a.instanceOf(Result); expect(result.css).to.match(/a \{\}\n\/\*# sourceMappingURL=/); }); }); });
/* Copyright 2014 Google Inc. All rights reserved. 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(window) { if (!!window.cookieChoices) { return window.cookieChoices; } var document = window.document; // IE8 does not support textContent, so we should fallback to innerText. var supportsTextContent = 'textContent' in document.body; var cookieChoices = (function() { var cookieName = 'displayCookieConsent'; var cookieConsentId = 'cookieChoiceInfo'; var dismissLinkId = 'cookieChoiceDismiss'; function _createHeaderElement(cookieText, dismissText, linkText, linkHref) { var butterBarStyles = 'position:fixed;width:100%;background-color:#eee;' + 'margin:0; left:0; top:0;padding:4px;z-index:1000;text-align:center;'; var cookieConsentElement = document.createElement('div'); cookieConsentElement.id = cookieConsentId; cookieConsentElement.style.cssText = butterBarStyles; cookieConsentElement.appendChild(_createConsentText(cookieText)); if (!!linkText && !!linkHref) { cookieConsentElement.appendChild(_createInformationLink(linkText, linkHref)); } cookieConsentElement.appendChild(_createDismissLink(dismissText)); return cookieConsentElement; } function _createDialogElement(cookieText, dismissText, linkText, linkHref) { var glassStyle = 'position:fixed;width:100%;height:100%;z-index:999;' + 'top:0;left:0;opacity:0.5;filter:alpha(opacity=50);' + 'background-color:#ccc;'; var dialogStyle = 'z-index:1000;position:fixed;left:50%;top:50%'; var contentStyle = 'position:relative;left:-50%;margin-top:-25%;' + 'background-color:#fff;padding:20px;box-shadow:4px 4px 25px #888;'; var cookieConsentElement = document.createElement('div'); cookieConsentElement.id = cookieConsentId; var glassPanel = document.createElement('div'); glassPanel.style.cssText = glassStyle; var content = document.createElement('div'); content.style.cssText = contentStyle; var dialog = document.createElement('div'); dialog.style.cssText = dialogStyle; var dismissLink = _createDismissLink(dismissText); dismissLink.style.display = 'block'; dismissLink.style.textAlign = 'right'; dismissLink.style.marginTop = '8px'; content.appendChild(_createConsentText(cookieText)); if (!!linkText && !!linkHref) { content.appendChild(_createInformationLink(linkText, linkHref)); } content.appendChild(dismissLink); dialog.appendChild(content); cookieConsentElement.appendChild(glassPanel); cookieConsentElement.appendChild(dialog); return cookieConsentElement; } function _setElementText(element, text) { if (supportsTextContent) { element.textContent = text; } else { element.innerText = text; } } function _createConsentText(cookieText) { var consentText = document.createElement('span'); _setElementText(consentText, cookieText); return consentText; } function _createDismissLink(dismissText) { var dismissLink = document.createElement('a'); _setElementText(dismissLink, dismissText); dismissLink.id = dismissLinkId; dismissLink.href = '#'; dismissLink.style.marginLeft = '24px'; return dismissLink; } function _createInformationLink(linkText, linkHref) { var infoLink = document.createElement('a'); _setElementText(infoLink, linkText); infoLink.href = linkHref; infoLink.target = '_blank'; infoLink.style.marginLeft = '8px'; return infoLink; } function _dismissLinkClick() { _saveUserPreference(); _removeCookieConsent(); return false; } function _showCookieConsent(cookieText, dismissText, linkText, linkHref, isDialog) { if (_shouldDisplayConsent()) { _removeCookieConsent(); var consentElement = (isDialog) ? _createDialogElement(cookieText, dismissText, linkText, linkHref) : _createHeaderElement(cookieText, dismissText, linkText, linkHref); var fragment = document.createDocumentFragment(); fragment.appendChild(consentElement); document.body.appendChild(fragment.cloneNode(true)); document.getElementById(dismissLinkId).onclick = _dismissLinkClick; } } function showCookieConsentBar(cookieText, dismissText, linkText, linkHref) { _showCookieConsent(cookieText, dismissText, linkText, linkHref, false); } function showCookieConsentDialog(cookieText, dismissText, linkText, linkHref) { _showCookieConsent(cookieText, dismissText, linkText, linkHref, true); } function _removeCookieConsent() { var cookieChoiceElement = document.getElementById(cookieConsentId); if (cookieChoiceElement != null) { cookieChoiceElement.parentNode.removeChild(cookieChoiceElement); } } function _saveUserPreference() { // Set the cookie expiry to one year after today. var expiryDate = new Date(); expiryDate.setFullYear(expiryDate.getFullYear() + 1); document.cookie = cookieName + '=y; expires=' + expiryDate.toGMTString(); } function _shouldDisplayConsent() { // Display the header only if the cookie has not been set. return !document.cookie.match(new RegExp(cookieName + '=([^;]+)')); } var exports = {}; exports.showCookieConsentBar = showCookieConsentBar; exports.showCookieConsentDialog = showCookieConsentDialog; return exports; })(); window.cookieChoices = cookieChoices; return cookieChoices; })(this);
var Symbol = require('./_Symbol'); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } module.exports = getRawTag;
/*--------------------------------------------------------------------------------------------- @author Constantin Saguin - @brutaldesign @link http://csag.co @github http://github.com/brutaldesign/swipebox @version 1.2.1 @license MIT License ----------------------------------------------------------------------------------------------*/ ;(function (window, document, $, undefined) { $.swipebox = function(elem, options) { var defaults = { useCSS : true, initialIndexOnArray : 0, hideBarsDelay : 3000, videoMaxWidth : 1140, vimeoColor : 'CCCCCC', beforeOpen: null, afterClose: null }, plugin = this, elements = [], // slides array [{href:'...', title:'...'}, ...], elem = elem, selector = elem.selector, $selector = $(selector), isTouch = document.createTouch !== undefined || ('ontouchstart' in window) || ('onmsgesturechange' in window) || navigator.msMaxTouchPoints, supportSVG = !!(window.SVGSVGElement), winWidth = window.innerWidth ? window.innerWidth : $(window).width(), winHeight = window.innerHeight ? window.innerHeight : $(window).height(), html = '<div id="swipebox-overlay">\ <div id="swipebox-slider"></div>\ <div id="swipebox-caption"></div>\ <div id="swipebox-action">\ <a id="swipebox-close"></a>\ <a id="swipebox-prev"></a>\ <a id="swipebox-next"></a>\ </div>\ </div>'; plugin.settings = {} plugin.init = function(){ plugin.settings = $.extend({}, defaults, options); if ($.isArray(elem)) { elements = elem; ui.target = $(window); ui.init(plugin.settings.initialIndexOnArray); }else{ $selector.click(function(e){ elements = []; var index , relType, relVal; if (!relVal) { relType = 'rel'; relVal = $(this).attr(relType); } if (relVal && relVal !== '' && relVal !== 'nofollow') { $elem = $selector.filter('[' + relType + '="' + relVal + '"]'); }else{ $elem = $(selector); } $elem.each(function(){ var title = null, href = null; if( $(this).attr('title') ) title = $(this).attr('title'); if( $(this).attr('href') ) href = $(this).attr('href'); elements.push({ href: href, title: title }); }); index = $elem.index($(this)); e.preventDefault(); e.stopPropagation(); ui.target = $(e.target); ui.init(index); }); } } plugin.refresh = function() { if (!$.isArray(elem)) { ui.destroy(); $elem = $(selector); ui.actions(); } } var ui = { init : function(index){ if (plugin.settings.beforeOpen) plugin.settings.beforeOpen(); this.target.trigger('swipebox-start'); $.swipebox.isOpen = true; this.build(); this.openSlide(index); this.openMedia(index); this.preloadMedia(index+1); this.preloadMedia(index-1); }, build : function(){ var $this = this; $('body').append(html); if($this.doCssTrans()){ $('#swipebox-slider').css({ '-webkit-transition' : 'left 0.4s ease', '-moz-transition' : 'left 0.4s ease', '-o-transition' : 'left 0.4s ease', '-khtml-transition' : 'left 0.4s ease', 'transition' : 'left 0.4s ease' }); $('#swipebox-overlay').css({ '-webkit-transition' : 'opacity 1s ease', '-moz-transition' : 'opacity 1s ease', '-o-transition' : 'opacity 1s ease', '-khtml-transition' : 'opacity 1s ease', 'transition' : 'opacity 1s ease' }); $('#swipebox-action, #swipebox-caption').css({ '-webkit-transition' : '0.5s', '-moz-transition' : '0.5s', '-o-transition' : '0.5s', '-khtml-transition' : '0.5s', 'transition' : '0.5s' }); } /* if(supportSVG){ var bg = $('#swipebox-action #swipebox-close').css('background-image'); bg = bg.replace('png', 'svg'); $('#swipebox-action #swipebox-prev,#swipebox-action #swipebox-next,#swipebox-action #swipebox-close').css({ 'background-image' : bg }); }*/ $.each( elements, function(){ $('#swipebox-slider').append('<div class="slide"></div>'); }); $this.setDim(); $this.actions(); $this.keyboard(); $this.gesture(); $this.animBars(); $this.resize(); }, setDim : function(){ var width, height, sliderCss = {}; if( "onorientationchange" in window ){ window.addEventListener("orientationchange", function() { if( window.orientation == 0 ){ width = winWidth; height = winHeight; }else if( window.orientation == 90 || window.orientation == -90 ){ width = winHeight; height = winWidth; } }, false); }else{ width = window.innerWidth ? window.innerWidth : $(window).width(); height = window.innerHeight ? window.innerHeight : $(window).height(); } sliderCss = { width : width, height : height } $('#swipebox-overlay').css(sliderCss); }, resize : function (){ var $this = this; $(window).resize(function() { $this.setDim(); }).resize(); }, supportTransition : function() { var prefixes = 'transition WebkitTransition MozTransition OTransition msTransition KhtmlTransition'.split(' '); for(var i = 0; i < prefixes.length; i++) { if(document.createElement('div').style[prefixes[i]] !== undefined) { return prefixes[i]; } } return false; }, doCssTrans : function(){ if(plugin.settings.useCSS && this.supportTransition() ){ return true; } }, gesture : function(){ if ( isTouch ){ var $this = this, distance = null, swipMinDistance = 10, startCoords = {}, endCoords = {}; var bars = $('#swipebox-caption, #swipebox-action'); bars.addClass('visible-bars'); $this.setTimeout(); $('body').bind('touchstart', function(e){ $(this).addClass('touching'); endCoords = e.originalEvent.targetTouches[0]; startCoords.pageX = e.originalEvent.targetTouches[0].pageX; $('.touching').bind('touchmove',function(e){ e.preventDefault(); e.stopPropagation(); endCoords = e.originalEvent.targetTouches[0]; }); return false; }).bind('touchend',function(e){ e.preventDefault(); e.stopPropagation(); distance = endCoords.pageX - startCoords.pageX; if( distance >= swipMinDistance ){ // swipeLeft $this.getPrev(); }else if( distance <= - swipMinDistance ){ // swipeRight $this.getNext(); }else{ // tap if(!bars.hasClass('visible-bars')){ $this.showBars(); $this.setTimeout(); }else{ $this.clearTimeout(); $this.hideBars(); } } $('.touching').off('touchmove').removeClass('touching'); }); } }, setTimeout: function(){ if(plugin.settings.hideBarsDelay > 0){ var $this = this; $this.clearTimeout(); $this.timeout = window.setTimeout( function(){ $this.hideBars() }, plugin.settings.hideBarsDelay ); } }, clearTimeout: function(){ window.clearTimeout(this.timeout); this.timeout = null; }, showBars : function(){ var bars = $('#swipebox-caption, #swipebox-action'); if(this.doCssTrans()){ bars.addClass('visible-bars'); }else{ $('#swipebox-caption').animate({ top : 0 }, 500); $('#swipebox-action').animate({ bottom : 0 }, 500); setTimeout(function(){ bars.addClass('visible-bars'); }, 1000); } }, hideBars : function(){ var bars = $('#swipebox-caption, #swipebox-action'); if(this.doCssTrans()){ bars.removeClass('visible-bars'); }else{ $('#swipebox-caption').animate({ top : '-50px' }, 500); $('#swipebox-action').animate({ bottom : '-50px' }, 500); setTimeout(function(){ bars.removeClass('visible-bars'); }, 1000); } }, animBars : function(){ var $this = this; var bars = $('#swipebox-caption, #swipebox-action'); bars.addClass('visible-bars'); $this.setTimeout(); $('#swipebox-slider').click(function(e){ if(!bars.hasClass('visible-bars')){ $this.showBars(); $this.setTimeout(); } }); $('#swipebox-action').hover(function() { $this.showBars(); bars.addClass('force-visible-bars'); $this.clearTimeout(); },function() { bars.removeClass('force-visible-bars'); $this.setTimeout(); }); }, keyboard : function(){ var $this = this; $(window).bind('keyup', function(e){ e.preventDefault(); e.stopPropagation(); if (e.keyCode == 37){ $this.getPrev(); } else if (e.keyCode==39){ $this.getNext(); } else if (e.keyCode == 27) { $this.closeSlide(); } }); }, actions : function(){ var $this = this; if( elements.length < 2 ){ $('#swipebox-prev, #swipebox-next').hide(); }else{ $('#swipebox-prev').bind('click touchend', function(e){ e.preventDefault(); e.stopPropagation(); $this.getPrev(); $this.setTimeout(); }); $('#swipebox-next').bind('click touchend', function(e){ e.preventDefault(); e.stopPropagation(); $this.getNext(); $this.setTimeout(); }); } $('#swipebox-close').bind('click touchend', function(e){ $this.closeSlide(); }); }, setSlide : function (index, isFirst){ isFirst = isFirst || false; var slider = $('#swipebox-slider'); if(this.doCssTrans()){ slider.css({ left : (-index*100)+'%' }); }else{ slider.animate({ left : (-index*100)+'%' }); } $('#swipebox-slider .slide').removeClass('current'); $('#swipebox-slider .slide').eq(index).addClass('current'); this.setTitle(index); if( isFirst ){ slider.fadeIn(); } $('#swipebox-prev, #swipebox-next').removeClass('disabled'); if(index == 0){ $('#swipebox-prev').addClass('disabled'); }else if( index == elements.length - 1 ){ $('#swipebox-next').addClass('disabled'); } }, openSlide : function (index){ $('html').addClass('swipebox'); $(window).trigger('resize'); // fix scroll bar visibility on desktop this.setSlide(index, true); }, preloadMedia : function (index){ var $this = this, src = null; if( elements[index] !== undefined ) src = elements[index].href; if( !$this.isVideo(src) ){ setTimeout(function(){ $this.openMedia(index); }, 1000); }else{ $this.openMedia(index); } }, openMedia : function (index){ var $this = this, src = null; if( elements[index] !== undefined ) src = elements[index].href; if(index < 0 || index >= elements.length){ return false; } if( !$this.isVideo(src) ){ $this.loadMedia(src, function(){ $('#swipebox-slider .slide').eq(index).html(this); }); }else{ $('#swipebox-slider .slide').eq(index).html($this.getVideo(src)); } }, setTitle : function (index, isFirst){ var title = null; $('#swipebox-caption').empty(); if( elements[index] !== undefined ) title = elements[index].title; if(title){ $('#swipebox-caption').append(title); } }, isVideo : function (src){ if( src ){ if( src.match(/youtube\.com\/watch\?v=([a-zA-Z0-9\-_]+)/) || src.match(/vimeo\.com\/([0-9]*)/) ){ return true; } } }, getVideo : function(url){ var iframe = ''; var output = ''; var youtubeUrl = url.match(/watch\?v=([a-zA-Z0-9\-_]+)/); var vimeoUrl = url.match(/vimeo\.com\/([0-9]*)/); if( youtubeUrl ){ iframe = '<iframe width="560" height="315" src="//www.youtube.com/embed/'+youtubeUrl[1]+'" frameborder="0" allowfullscreen></iframe>'; }else if(vimeoUrl){ iframe = '<iframe width="560" height="315" src="http://player.vimeo.com/video/'+vimeoUrl[1]+'?byline=0&amp;portrait=0&amp;color='+plugin.settings.vimeoColor+'" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>'; } return '<div class="swipebox-video-container" style="max-width:'+plugin.settings.videomaxWidth+'px"><div class="swipebox-video">'+iframe+'</div></div>'; }, loadMedia : function (src, callback){ if( !this.isVideo(src) ){ var img = $('<img>').on('load', function(){ callback.call(img); }); img.attr('src',src); } }, getNext : function (){ var $this = this; index = $('#swipebox-slider .slide').index($('#swipebox-slider .slide.current')); if(index+1 < elements.length){ index++; $this.setSlide(index); $this.preloadMedia(index+1); } else{ $('#swipebox-slider').addClass('rightSpring'); setTimeout(function(){ $('#swipebox-slider').removeClass('rightSpring'); },500); } }, getPrev : function (){ index = $('#swipebox-slider .slide').index($('#swipebox-slider .slide.current')); if(index > 0){ index--; this.setSlide(index); this.preloadMedia(index-1); } else{ $('#swipebox-slider').addClass('leftSpring'); setTimeout(function(){ $('#swipebox-slider').removeClass('leftSpring'); },500); } }, closeSlide : function (){ $('html').removeClass('swipebox'); $(window).trigger('resize'); this.destroy(); }, destroy : function(){ $(window).unbind('keyup'); $('body').unbind('touchstart'); $('body').unbind('touchmove'); $('body').unbind('touchend'); $('#swipebox-slider').unbind(); $('#swipebox-overlay').remove(); if (!$.isArray(elem)) elem.removeData('_swipebox'); if ( this.target ) this.target.trigger('swipebox-destroy'); $.swipebox.isOpen = false; if (plugin.settings.afterClose) plugin.settings.afterClose(); } }; plugin.init(); }; $.fn.swipebox = function(options){ if (!$.data(this, "_swipebox")) { var swipebox = new $.swipebox(this, options); this.data('_swipebox', swipebox); } return this.data('_swipebox'); } }(window, document, jQuery));
import PopoverMixin from 'ghost/mixins/popover-mixin'; var GhostPopover = Ember.Component.extend(PopoverMixin, { classNames: 'ghost-popover fade-in', name: null, closeOnClick: false, //Helps track the user re-opening the menu while it's fading out. closing: false, open: function () { this.set('closing', false); this.set('isOpen', true); this.set('button.isOpen', true); }, close: function () { var self = this; this.set('closing', true); if (this.get('button')) { this.set('button.isOpen', false); } this.$().fadeOut(200, function () { //Make sure this wasn't an aborted fadeout by //checking `closing`. if (self.get('closing')) { self.set('isOpen', false); self.set('closing', false); } }); }, //Called by the popover service when any popover button is clicked. toggle: function (options) { var isClosing = this.get('closing'), isOpen = this.get('isOpen'), name = this.get('name'), button = this.get('button'), targetPopoverName = options.target; if (name === targetPopoverName && (!isOpen || isClosing)) { if (!button) { button = options.button; this.set('button', button); } this.open(); } else if (isOpen) { this.close(); } }, click: function (event) { this._super(event); if (this.get('closeOnClick')) { return this.close(); } }, didInsertElement: function () { this._super(); var popoverService = this.get('popover'); popoverService.on('close', this, this.close); popoverService.on('toggle', this, this.toggle); }, willDestroyElement: function () { this._super(); var popoverService = this.get('popover'); popoverService.off('close', this, this.close); popoverService.off('toggle', this, this.toggle); } }); export default GhostPopover;
"use strict"; exports.__esModule = true; exports.default = void 0; var _deepDiffer = _interopRequireDefault(require("../deepDiffer")); var React = _interopRequireWildcard(require("react")); var _StyleSheet = _interopRequireDefault(require("../../../exports/StyleSheet")); var _View = _interopRequireDefault(require("../../../exports/View")); var _ScrollView = _interopRequireDefault(require("../../../exports/ScrollView")); var _VirtualizedList = _interopRequireDefault(require("../VirtualizedList")); var _invariant = _interopRequireDefault(require("fbjs/lib/invariant")); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _extends() { _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; }; return _extends.apply(this, arguments); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(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 defaultProps = _objectSpread(_objectSpread({}, _VirtualizedList.default.defaultProps), {}, { numColumns: 1 }); /** * A performant interface for rendering simple, flat lists, supporting the most handy features: * * - Fully cross-platform. * - Optional horizontal mode. * - Configurable viewability callbacks. * - Header support. * - Footer support. * - Separator support. * - Pull to Refresh. * - Scroll loading. * - ScrollToIndex support. * * If you need section support, use [`<SectionList>`](docs/sectionlist.html). * * Minimal Example: * * <FlatList * data={[{key: 'a'}, {key: 'b'}]} * renderItem={({item}) => <Text>{item.key}</Text>} * /> * * More complex, multi-select example demonstrating `PureComponent` usage for perf optimization and avoiding bugs. * * - By binding the `onPressItem` handler, the props will remain `===` and `PureComponent` will * prevent wasteful re-renders unless the actual `id`, `selected`, or `title` props change, even * if the components rendered in `MyListItem` did not have such optimizations. * - By passing `extraData={this.state}` to `FlatList` we make sure `FlatList` itself will re-render * when the `state.selected` changes. Without setting this prop, `FlatList` would not know it * needs to re-render any items because it is also a `PureComponent` and the prop comparison will * not show any changes. * - `keyExtractor` tells the list to use the `id`s for the react keys instead of the default `key` property. * * * class MyListItem extends React.PureComponent { * _onPress = () => { * this.props.onPressItem(this.props.id); * }; * * render() { * const textColor = this.props.selected ? "red" : "black"; * return ( * <TouchableOpacity onPress={this._onPress}> * <View> * <Text style={{ color: textColor }}> * {this.props.title} * </Text> * </View> * </TouchableOpacity> * ); * } * } * * class MultiSelectList extends React.PureComponent { * state = {selected: (new Map(): Map<string, boolean>)}; * * _keyExtractor = (item, index) => item.id; * * _onPressItem = (id: string) => { * // updater functions are preferred for transactional updates * this.setState((state) => { * // copy the map rather than modifying state. * const selected = new Map(state.selected); * selected.set(id, !selected.get(id)); // toggle * return {selected}; * }); * }; * * _renderItem = ({item}) => ( * <MyListItem * id={item.id} * onPressItem={this._onPressItem} * selected={!!this.state.selected.get(item.id)} * title={item.title} * /> * ); * * render() { * return ( * <FlatList * data={this.props.data} * extraData={this.state} * keyExtractor={this._keyExtractor} * renderItem={this._renderItem} * /> * ); * } * } * * This is a convenience wrapper around [`<VirtualizedList>`](docs/virtualizedlist.html), * and thus inherits its props (as well as those of `ScrollView`) that aren't explicitly listed * here, along with the following caveats: * * - Internal state is not preserved when content scrolls out of the render window. Make sure all * your data is captured in the item data or external stores like Flux, Redux, or Relay. * - This is a `PureComponent` which means that it will not re-render if `props` remain shallow- * equal. Make sure that everything your `renderItem` function depends on is passed as a prop * (e.g. `extraData`) that is not `===` after updates, otherwise your UI may not update on * changes. This includes the `data` prop and parent component state. * - In order to constrain memory and enable smooth scrolling, content is rendered asynchronously * offscreen. This means it's possible to scroll faster than the fill rate ands momentarily see * blank content. This is a tradeoff that can be adjusted to suit the needs of each application, * and we are working on improving it behind the scenes. * - By default, the list looks for a `key` prop on each item and uses that for the React key. * Alternatively, you can provide a custom `keyExtractor` prop. * * Also inherits [ScrollView Props](docs/scrollview.html#props), unless it is nested in another FlatList of same orientation. */ var FlatList = /*#__PURE__*/function (_React$PureComponent) { _inheritsLoose(FlatList, _React$PureComponent); var _proto = FlatList.prototype; /** * Scrolls to the end of the content. May be janky without `getItemLayout` prop. */ _proto.scrollToEnd = function scrollToEnd(params) { if (this._listRef) { this._listRef.scrollToEnd(params); } } /** * Scrolls to the item at the specified index such that it is positioned in the viewable area * such that `viewPosition` 0 places it at the top, 1 at the bottom, and 0.5 centered in the * middle. `viewOffset` is a fixed number of pixels to offset the final target position. * * Note: cannot scroll to locations outside the render window without specifying the * `getItemLayout` prop. */ ; _proto.scrollToIndex = function scrollToIndex(params) { if (this._listRef) { this._listRef.scrollToIndex(params); } } /** * Requires linear scan through data - use `scrollToIndex` instead if possible. * * Note: cannot scroll to locations outside the render window without specifying the * `getItemLayout` prop. */ ; _proto.scrollToItem = function scrollToItem(params) { if (this._listRef) { this._listRef.scrollToItem(params); } } /** * Scroll to a specific content pixel offset in the list. * * Check out [scrollToOffset](docs/virtualizedlist.html#scrolltooffset) of VirtualizedList */ ; _proto.scrollToOffset = function scrollToOffset(params) { if (this._listRef) { this._listRef.scrollToOffset(params); } } /** * Tells the list an interaction has occurred, which should trigger viewability calculations, e.g. * if `waitForInteractions` is true and the user has not scrolled. This is typically called by * taps on items or by navigation actions. */ ; _proto.recordInteraction = function recordInteraction() { if (this._listRef) { this._listRef.recordInteraction(); } } /** * Displays the scroll indicators momentarily. * * @platform ios */ ; _proto.flashScrollIndicators = function flashScrollIndicators() { if (this._listRef) { this._listRef.flashScrollIndicators(); } } /** * Provides a handle to the underlying scroll responder. */ ; _proto.getScrollResponder = function getScrollResponder() { if (this._listRef) { return this._listRef.getScrollResponder(); } } /** * Provides a reference to the underlying host component */ ; _proto.getNativeScrollRef = function getNativeScrollRef() { if (this._listRef) { /* $FlowFixMe[incompatible-return] Suppresses errors found when fixing * TextInput typing */ return this._listRef.getScrollRef(); } }; _proto.getScrollableNode = function getScrollableNode() { if (this._listRef) { return this._listRef.getScrollableNode(); } }; _proto.setNativeProps = function setNativeProps(props) { if (this._listRef) { this._listRef.setNativeProps(props); } }; function FlatList(_props) { var _this; _this = _React$PureComponent.call(this, _props) || this; _this._virtualizedListPairs = []; _this._captureRef = function (ref) { _this._listRef = ref; }; _this._getItem = function (data, index) { var numColumns = _this.props.numColumns; if (numColumns > 1) { var ret = []; for (var kk = 0; kk < numColumns; kk++) { var _item = data[index * numColumns + kk]; if (_item != null) { ret.push(_item); } } return ret; } else { return data[index]; } }; _this._getItemCount = function (data) { if (data) { var numColumns = _this.props.numColumns; return numColumns > 1 ? Math.ceil(data.length / numColumns) : data.length; } else { return 0; } }; _this._keyExtractor = function (items, index) { var _this$props = _this.props, keyExtractor = _this$props.keyExtractor, numColumns = _this$props.numColumns; if (numColumns > 1) { (0, _invariant.default)(Array.isArray(items), 'FlatList: Encountered internal consistency error, expected each item to consist of an ' + 'array with 1-%s columns; instead, received a single item.', numColumns); return items // $FlowFixMe[incompatible-call] .map(function (it, kk) { return keyExtractor(it, index * numColumns + kk); }).join(':'); } else { // $FlowFixMe Can't call keyExtractor with an array return keyExtractor(items, index); } }; _this._renderer = function () { var _ref; var _this$props2 = _this.props, ListItemComponent = _this$props2.ListItemComponent, renderItem = _this$props2.renderItem, numColumns = _this$props2.numColumns, columnWrapperStyle = _this$props2.columnWrapperStyle; var virtualizedListRenderKey = ListItemComponent ? 'ListItemComponent' : 'renderItem'; var renderer = function renderer(props) { if (ListItemComponent) { // $FlowFixMe Component isn't valid return /*#__PURE__*/React.createElement(ListItemComponent, props); } else if (renderItem) { // $FlowFixMe[incompatible-call] return renderItem(props); } else { return null; } }; return _ref = {}, _ref[virtualizedListRenderKey] = function (info) { if (numColumns > 1) { var _item2 = info.item, _index = info.index; (0, _invariant.default)(Array.isArray(_item2), 'Expected array of items with numColumns > 1'); return /*#__PURE__*/React.createElement(_View.default, { style: _StyleSheet.default.compose(styles.row, columnWrapperStyle) }, _item2.map(function (it, kk) { var element = renderer({ item: it, index: _index * numColumns + kk, separators: info.separators }); return element != null ? /*#__PURE__*/React.createElement(React.Fragment, { key: kk }, element) : null; })); } else { return renderer(info); } }, _ref; }; _this._checkProps(_this.props); if (_this.props.viewabilityConfigCallbackPairs) { _this._virtualizedListPairs = _this.props.viewabilityConfigCallbackPairs.map(function (pair) { return { viewabilityConfig: pair.viewabilityConfig, onViewableItemsChanged: _this._createOnViewableItemsChanged(pair.onViewableItemsChanged) }; }); } else if (_this.props.onViewableItemsChanged) { _this._virtualizedListPairs.push({ /* $FlowFixMe(>=0.63.0 site=react_native_fb) This comment suppresses an * error found when Flow v0.63 was deployed. To see the error delete * this comment and run Flow. */ viewabilityConfig: _this.props.viewabilityConfig, onViewableItemsChanged: _this._createOnViewableItemsChanged(_this.props.onViewableItemsChanged) }); } return _this; } _proto.componentDidUpdate = function componentDidUpdate(prevProps) { (0, _invariant.default)(prevProps.numColumns === this.props.numColumns, 'Changing numColumns on the fly is not supported. Change the key prop on FlatList when ' + 'changing the number of columns to force a fresh render of the component.'); (0, _invariant.default)(prevProps.onViewableItemsChanged === this.props.onViewableItemsChanged, 'Changing onViewableItemsChanged on the fly is not supported'); (0, _invariant.default)(!(0, _deepDiffer.default)(prevProps.viewabilityConfig, this.props.viewabilityConfig), 'Changing viewabilityConfig on the fly is not supported'); (0, _invariant.default)(prevProps.viewabilityConfigCallbackPairs === this.props.viewabilityConfigCallbackPairs, 'Changing viewabilityConfigCallbackPairs on the fly is not supported'); this._checkProps(this.props); }; _proto._checkProps = function _checkProps(props) { var getItem = props.getItem, getItemCount = props.getItemCount, horizontal = props.horizontal, numColumns = props.numColumns, columnWrapperStyle = props.columnWrapperStyle, onViewableItemsChanged = props.onViewableItemsChanged, viewabilityConfigCallbackPairs = props.viewabilityConfigCallbackPairs; (0, _invariant.default)(!getItem && !getItemCount, 'FlatList does not support custom data formats.'); if (numColumns > 1) { (0, _invariant.default)(!horizontal, 'numColumns does not support horizontal.'); } else { (0, _invariant.default)(!columnWrapperStyle, 'columnWrapperStyle not supported for single column lists'); } (0, _invariant.default)(!(onViewableItemsChanged && viewabilityConfigCallbackPairs), 'FlatList does not support setting both onViewableItemsChanged and ' + 'viewabilityConfigCallbackPairs.'); }; _proto._pushMultiColumnViewable = function _pushMultiColumnViewable(arr, v) { var _this$props3 = this.props, numColumns = _this$props3.numColumns, keyExtractor = _this$props3.keyExtractor; v.item.forEach(function (item, ii) { (0, _invariant.default)(v.index != null, 'Missing index!'); var index = v.index * numColumns + ii; arr.push(_objectSpread(_objectSpread({}, v), {}, { item: item, key: keyExtractor(item, index), index: index })); }); }; _proto._createOnViewableItemsChanged = function _createOnViewableItemsChanged(onViewableItemsChanged) { var _this2 = this; return function (info) { var numColumns = _this2.props.numColumns; if (onViewableItemsChanged) { if (numColumns > 1) { var changed = []; var viewableItems = []; info.viewableItems.forEach(function (v) { return _this2._pushMultiColumnViewable(viewableItems, v); }); info.changed.forEach(function (v) { return _this2._pushMultiColumnViewable(changed, v); }); onViewableItemsChanged({ viewableItems: viewableItems, changed: changed }); } else { onViewableItemsChanged(info); } } }; }; _proto.render = function render() { var _this$props4 = this.props, numColumns = _this$props4.numColumns, columnWrapperStyle = _this$props4.columnWrapperStyle, restProps = _objectWithoutPropertiesLoose(_this$props4, ["numColumns", "columnWrapperStyle"]); return /*#__PURE__*/React.createElement(_VirtualizedList.default, _extends({}, restProps, { getItem: this._getItem, getItemCount: this._getItemCount, keyExtractor: this._keyExtractor, ref: this._captureRef, viewabilityConfigCallbackPairs: this._virtualizedListPairs }, this._renderer())); }; return FlatList; }(React.PureComponent); FlatList.defaultProps = defaultProps; var styles = _StyleSheet.default.create({ row: { flexDirection: 'row' } }); var _default = FlatList; exports.default = _default; module.exports = exports.default;
/*global angular,inject,describe,it,expect,beforeEach*/ describe('directive: choice-field', function () { 'use strict'; var directive = require('../../../../ng-admin/Crud/field/maChoiceField'); var ChoiceField = require('admin-config/lib/Field/ChoiceField'); angular.module('testapp_ChoiceField', ['ui.select']).directive('maChoiceField', directive); var $compile, scope, directiveUsage = '<ma-choice-field entry="entry" field="field" value="value"></ma-choice-field>'; beforeEach(angular.mock.module('testapp_ChoiceField')); beforeEach(inject(function (_$compile_, _$rootScope_) { $compile = _$compile_; scope = _$rootScope_; })); it("should contain a ui-select tag", function () { scope.field = new ChoiceField(); var element = $compile(directiveUsage)(scope); scope.$digest(); var uiSelect = element.children()[0]; expect(uiSelect.classList.contains('ui-select-container')).toBeTruthy(); }); it("should add any supplied attribute", function () { scope.field = new ChoiceField().attributes({ disabled: true }); var element = $compile(directiveUsage)(scope); scope.$digest(); expect(element.children()[0].getAttribute('disabled')).toBeTruthy(); }); it('should allow to remove selected option only if not required', function() { function test(isRequired, expectedAllowClearValue) { scope.field = new ChoiceField().validation({ required: isRequired }); var element = $compile(directiveUsage)(scope); scope.$digest(); expect(element[0].querySelector('.ui-select-match').getAttribute('allow-clear')).toEqual(expectedAllowClearValue.toString()); } test(true, false); test(false, true); }); it("should contain the choices as options", function () { scope.field = new ChoiceField().choices([ {label: 'foo', value: 'bar'}, {label: 'baz', value: 'bazValue'} ]); var element = $compile(directiveUsage)(scope); scope.$digest(); var uiSelect = angular.element(element.children()[0]).controller('uiSelect'); expect(angular.toJson(uiSelect.items)).toEqual(JSON.stringify([ {label: 'foo', value: 'bar'}, {label: 'baz', value: 'bazValue'} ])); }); it("should contain the choices from choicesFunc as options", function () { var choices = [ {label: 'foo', value: 'bar'}, {label: 'baz', value: 'bazValue'} ]; scope.field = new ChoiceField().choices(function(entry){ return choices; }); var element = $compile(directiveUsage)(scope); scope.$digest(); var uiSelect = angular.element(element.children()[0]).controller('uiSelect'); expect(angular.toJson(uiSelect.items)).toEqual(JSON.stringify([ {label: 'foo', value: 'bar'}, {label: 'baz', value: 'bazValue'} ])); }); it("should pass entry to choicesFunc", function () { var choices = []; var choicesFuncWasCalled = false; scope.entry = {moo: 'boo'}; scope.field = new ChoiceField().choices(function(entry){ expect(entry.moo).toEqual('boo'); choicesFuncWasCalled = true; return choices; }); $compile(directiveUsage)(scope); scope.$digest(); expect(choicesFuncWasCalled).toBeTruthy(); }); it("should have the option with the bounded value selected", function () { scope.field = new ChoiceField().choices([ {label: 'foo', value: 'bar'}, {label: 'baz', value: 'bazValue'} ]); scope.value = 'bazValue'; var element = $compile(directiveUsage)(scope); scope.$digest(); var uiSelect = angular.element(element.children()[0]).controller('uiSelect'); expect(angular.toJson(uiSelect.selected)).toEqual(JSON.stringify({ label: 'baz', value: 'bazValue' })); }); });
module.exports={title:"Tutanota",slug:"tutanota",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Tutanota icon</title><path d="M2.158.934C.978.934.025 1.895.023 3.08.017 9.74.005 16.413 0 23.066c.793-.297 1.67-.56 2.56-.918 6.188-2.485 11.249-4.598 11.253-6.983a1.66 1.66 0 0 0-.016-.23c-.32-2.356-5.916-3.087-5.908-4.166a.37.37 0 0 1 .05-.177c.673-1.184 3.336-1.128 4.316-1.212.982-.085 3.285-.067 3.397-.773a.44.44 0 0 0 .005-.065c.003-.656-1.584-.913-1.584-.913s1.925.29 1.92 1.042a.445.445 0 0 1-.015.114c-.207.81-1.901.962-3.021 1.017-1.06.054-2.673.175-2.679.695 0 .03.005.062.015.095.253.76 6.167 1.127 9.95 3.102 2.178 1.136 3.26 3.004 3.757 4.974V3.08A2.14 2.14 0 0 0 21.866.934H2.158Z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://github.com/tutao/tutanota/blob/8ff5f0e7d78834ac8fcb0f2357c394b757ea4793/resources/images/logo-solo-red.svg",hex:"840010"};
Date.Specification = new Specification({ 'Overview': { setup: function() { }, 'Today': { run: function() { this.date = Date.parse('Today'); }, assert: function() { return Date.today().equals( this.date ) } }, 'Yesterday': { run: function() { this.date = Date.parse('Yesterday') }, assert: function() { return Date.today().addDays(-1).equals( this.date ) } }, 'Tomorrow': { run: function() { this.date = Date.parse('Tomorrow') }, assert: function() { return Date.today().addDays(1).equals( this.date ) } }, 't = "Today"': { run: function() { }, assert: function() { return Date.today().equals(Date.parse('t')) } }, 'tod = "Today"': { run: function() { }, assert: function() { return Date.today().equals(Date.parse('tod')) } }, 'yes = "Yesterday"': { run: function() { }, assert: function() { return Date.today().add(-1).days().equals(Date.parse('yes')) } }, 'tom = "Tomorrow"': { run: function() { }, assert: function() { return Date.today().add(1).day().equals(Date.parse('tom')) } } }, 'Relative Days': { setup: function() { }, 'last monday': { run: function() { }, assert: function() { return Date.today().last().monday().equals(Date.parse('last monday')) } }, 'last mon': { run: function() { }, assert: function() { return Date.today().last().monday().equals(Date.parse('last mon')) } }, 'last mo': { run: function() { }, assert: function() { return Date.today().last().monday().equals(Date.parse('last mo')) } }, 'last tuesday': { run: function() { }, assert: function() { return Date.today().last().tuesday().equals(Date.parse('last tuesday')) } }, 'last tues': { run: function() { }, assert: function() { return Date.today().last().tuesday().equals(Date.parse('last tues')) } }, 'last tue': { run: function() { }, assert: function() { return Date.today().last().tuesday().equals(Date.parse('last tue')) } }, 'last tu': { run: function() { }, assert: function() { return Date.today().last().tuesday().equals(Date.parse('last tu')) } }, 'last wednesday': { run: function() { }, assert: function() { return Date.today().last().wednesday().equals(Date.parse('last wednesday')) } }, 'last wed': { run: function() { }, assert: function() { return Date.today().last().wednesday().equals(Date.parse('last wed')) } }, 'last we': { run: function() { }, assert: function() { return Date.today().last().wednesday().equals(Date.parse('last we')) } }, 'last thursday': { run: function() { }, assert: function() { return Date.today().last().thursday().equals(Date.parse('last thursday')) } }, 'last thurs': { run: function() { }, assert: function() { return Date.today().last().thursday().equals(Date.parse('last thurs')) } }, 'last thur': { run: function() { }, assert: function() { return Date.today().last().thursday().equals(Date.parse('last thur')) } }, 'last thu': { run: function() { }, assert: function() { return Date.today().last().thursday().equals(Date.parse('last thu')) } }, // 'last th': { // run: function() { }, // assert: function() { return Date.today().last().thursday().equals(Date.parse('last th')) } // }, 'last friday': { run: function() { }, assert: function() { return Date.today().last().friday().equals(Date.parse('last friday')) } }, 'last fri': { run: function() { }, assert: function() { return Date.today().last().friday().equals(Date.parse('last fri')) } }, 'last fr': { run: function() { }, assert: function() { return Date.today().last().friday().equals(Date.parse('last fr')) } }, 'last saturday': { run: function() { }, assert: function() { return Date.today().last().saturday().equals(Date.parse('last saturday')) } }, 'last sat': { run: function() { }, assert: function() { return Date.today().last().saturday().equals(Date.parse('last sat')) } }, 'last sa': { run: function() { }, assert: function() { return Date.today().last().saturday().equals(Date.parse('last sa')) } }, 'last sunday': { run: function() { }, assert: function() { return Date.today().last().sunday().equals(Date.parse('last sunday')) } }, 'last sun': { run: function() { }, assert: function() { return Date.today().last().sunday().equals(Date.parse('last sun')) } }, 'last su': { run: function() { }, assert: function() { return Date.today().last().sunday().equals(Date.parse('last su')) } }, 'prev monday': { run: function() { }, assert: function() { return Date.today().prev().monday().equals(Date.parse('prev monday')) } }, 'prev mon': { run: function() { }, assert: function() { return Date.today().prev().monday().equals(Date.parse('prev mon')) } }, 'prev mo': { run: function() { }, assert: function() { return Date.today().prev().monday().equals(Date.parse('prev mo')) } }, 'prev tuesday': { run: function() { }, assert: function() { return Date.today().prev().tuesday().equals(Date.parse('prev tuesday')) } }, 'prev tues': { run: function() { }, assert: function() { return Date.today().prev().tuesday().equals(Date.parse('prev tues')) } }, 'prev tue': { run: function() { }, assert: function() { return Date.today().prev().tuesday().equals(Date.parse('prev tue')) } }, 'prev tu': { run: function() { }, assert: function() { return Date.today().prev().tuesday().equals(Date.parse('prev tu')) } }, 'prev wednesday': { run: function() { }, assert: function() { return Date.today().prev().wednesday().equals(Date.parse('prev wednesday')) } }, 'prev wed': { run: function() { }, assert: function() { return Date.today().prev().wednesday().equals(Date.parse('prev wed')) } }, 'prev we': { run: function() { }, assert: function() { return Date.today().prev().wednesday().equals(Date.parse('prev we')) } }, 'prev thursday': { run: function() { }, assert: function() { return Date.today().prev().thursday().equals(Date.parse('prev thursday')) } }, 'prev thurs': { run: function() { }, assert: function() { return Date.today().prev().thursday().equals(Date.parse('prev thurs')) } }, 'prev thur': { run: function() { }, assert: function() { return Date.today().prev().thursday().equals(Date.parse('prev thur')) } }, 'prev thu': { run: function() { }, assert: function() { return Date.today().prev().thursday().equals(Date.parse('prev thu')) } }, // 'prev th': { // run: function() { }, // assert: function() { return Date.today().prev().thursday().equals(Date.parse('prev th')) } // }, 'prev friday': { run: function() { }, assert: function() { return Date.today().prev().friday().equals(Date.parse('prev friday')) } }, 'prev fri': { run: function() { }, assert: function() { return Date.today().prev().friday().equals(Date.parse('prev fri')) } }, 'prev fr': { run: function() { }, assert: function() { return Date.today().prev().friday().equals(Date.parse('prev fr')) } }, 'prev saturday': { run: function() { }, assert: function() { return Date.today().prev().saturday().equals(Date.parse('prev saturday')) } }, 'prev sat': { run: function() { }, assert: function() { return Date.today().prev().saturday().equals(Date.parse('prev sat')) } }, 'prev sa': { run: function() { }, assert: function() { return Date.today().prev().saturday().equals(Date.parse('prev sa')) } }, 'prev sunday': { run: function() { }, assert: function() { return Date.today().prev().sunday().equals(Date.parse('prev sunday')) } }, 'prev sun': { run: function() { }, assert: function() { return Date.today().prev().sunday().equals(Date.parse('prev sun')) } }, 'prev su': { run: function() { }, assert: function() { return Date.today().prev().sunday().equals(Date.parse('prev su')) } }, 'previous monday': { run: function() { }, assert: function() { return Date.today().previous().monday().equals(Date.parse('previous monday')) } }, 'previous mon': { run: function() { }, assert: function() { return Date.today().previous().monday().equals(Date.parse('previous mon')) } }, 'previous mo': { run: function() { }, assert: function() { return Date.today().previous().monday().equals(Date.parse('previous mo')) } }, 'previous tuesday': { run: function() { }, assert: function() { return Date.today().previous().tuesday().equals(Date.parse('previous tuesday')) } }, 'previous tues': { run: function() { }, assert: function() { return Date.today().previous().tuesday().equals(Date.parse('previous tues')) } }, 'previous tue': { run: function() { }, assert: function() { return Date.today().previous().tuesday().equals(Date.parse('previous tue')) } }, 'previous tu': { run: function() { }, assert: function() { return Date.today().previous().tuesday().equals(Date.parse('previous tu')) } }, 'previous wednesday': { run: function() { }, assert: function() { return Date.today().previous().wednesday().equals(Date.parse('previous wednesday')) } }, 'previous wed': { run: function() { }, assert: function() { return Date.today().previous().wednesday().equals(Date.parse('previous wed')) } }, 'previous we': { run: function() { }, assert: function() { return Date.today().previous().wednesday().equals(Date.parse('previous we')) } }, 'previous thursday': { run: function() { }, assert: function() { return Date.today().previous().thursday().equals(Date.parse('previous thursday')) } }, 'previous thurs': { run: function() { }, assert: function() { return Date.today().previous().thursday().equals(Date.parse('previous thurs')) } }, 'previous thur': { run: function() { }, assert: function() { return Date.today().previous().thursday().equals(Date.parse('previous thur')) } }, 'previous thu': { run: function() { }, assert: function() { return Date.today().previous().thursday().equals(Date.parse('previous thu')) } }, // 'previous th': { // run: function() { }, // assert: function() { return Date.today().previous().thursday().equals(Date.parse('previous th')) } // }, 'previous friday': { run: function() { }, assert: function() { return Date.today().previous().friday().equals(Date.parse('previous friday')) } }, 'previous fri': { run: function() { }, assert: function() { return Date.today().previous().friday().equals(Date.parse('previous fri')) } }, 'previous fr': { run: function() { }, assert: function() { return Date.today().previous().friday().equals(Date.parse('previous fr')) } }, 'previous saturday': { run: function() { }, assert: function() { return Date.today().previous().saturday().equals(Date.parse('previous saturday')) } }, 'previous sat': { run: function() { }, assert: function() { return Date.today().previous().saturday().equals(Date.parse('previous sat')) } }, 'previous sa': { run: function() { }, assert: function() { return Date.today().previous().saturday().equals(Date.parse('previous sa')) } }, 'previous sunday': { run: function() { }, assert: function() { return Date.today().previous().sunday().equals(Date.parse('previous sunday')) } }, 'previous sun': { run: function() { }, assert: function() { return Date.today().previous().sunday().equals(Date.parse('previous sun')) } }, 'previous su': { run: function() { }, assert: function() { return Date.today().previous().sunday().equals(Date.parse('previous su')) } }, 'next monday': { run: function() { }, assert: function() { return Date.today().next().monday().equals(Date.parse('next monday')) } }, 'next mon': { run: function() { }, assert: function() { return Date.today().next().monday().equals(Date.parse('next mon')) } }, 'next mo': { run: function() { }, assert: function() { return Date.today().next().monday().equals(Date.parse('next mo')) } }, 'next tuesday': { run: function() { }, assert: function() { return Date.today().next().tuesday().equals(Date.parse('next tuesday')) } }, 'next tues': { run: function() { }, assert: function() { return Date.today().next().tuesday().equals(Date.parse('next tues')) } }, 'next tue': { run: function() { }, assert: function() { return Date.today().next().tuesday().equals(Date.parse('next tue')) } }, 'next tu': { run: function() { }, assert: function() { return Date.today().next().tuesday().equals(Date.parse('next tu')) } }, 'next wednesday': { run: function() { }, assert: function() { return Date.today().next().wednesday().equals(Date.parse('next wednesday')) } }, 'next wed': { run: function() { }, assert: function() { return Date.today().next().wednesday().equals(Date.parse('next wed')) } }, 'next we': { run: function() { }, assert: function() { return Date.today().next().wednesday().equals(Date.parse('next we')) } }, 'next thursday': { run: function() { }, assert: function() { return Date.today().next().thursday().equals(Date.parse('next thursday')) } }, 'next thurs': { run: function() { }, assert: function() { return Date.today().next().thursday().equals(Date.parse('next thurs')) } }, 'next thur': { run: function() { }, assert: function() { return Date.today().next().thursday().equals(Date.parse('next thur')) } }, 'next thu': { run: function() { }, assert: function() { return Date.today().next().thursday().equals(Date.parse('next thu')) } }, // 'next th': { // run: function() { }, // assert: function() { return Date.today().next().thursday().equals(Date.parse('next th')) } // }, 'next friday': { run: function() { }, assert: function() { return Date.today().next().friday().equals(Date.parse('next friday')) } }, 'next fri': { run: function() { }, assert: function() { return Date.today().next().friday().equals(Date.parse('next fri')) } }, 'next fr': { run: function() { }, assert: function() { return Date.today().next().friday().equals(Date.parse('next fr')) } }, 'next saturday': { run: function() { }, assert: function() { return Date.today().next().saturday().equals(Date.parse('next saturday')) } }, 'next sat': { run: function() { }, assert: function() { return Date.today().next().saturday().equals(Date.parse('next sat')) } }, 'next sa': { run: function() { }, assert: function() { return Date.today().next().saturday().equals(Date.parse('next sa')) } }, 'next sunday': { run: function() { }, assert: function() { return Date.today().next().sunday().equals(Date.parse('next sunday')) } }, 'next sun': { run: function() { }, assert: function() { return Date.today().next().sunday().equals(Date.parse('next sun')) } }, 'next su': { run: function() { }, assert: function() { return Date.today().next().sunday().equals(Date.parse('next su')) } } }, 'Relative Months': { setup: function() { }, 'last january': { run: function() { }, assert: function() { return Date.today().last().january().equals(Date.parse('last january')) } }, 'last jan': { run: function() { }, assert: function() { return Date.today().last().january().equals(Date.parse('last jan')) } }, 'last february': { run: function() { }, assert: function() { return Date.today().last().february().equals(Date.parse('last february')) } }, 'last feb': { run: function() { }, assert: function() { return Date.today().last().february().equals(Date.parse('last feb')) } }, 'last march': { run: function() { }, assert: function() { return Date.today().last().march().equals(Date.parse('last march')) } }, 'last mar': { run: function() { }, assert: function() { return Date.today().last().march().equals(Date.parse('last mar')) } }, 'last april': { run: function() { }, assert: function() { return Date.today().last().april().equals(Date.parse('last april')) } }, 'last apr': { run: function() { }, assert: function() { return Date.today().last().apr().equals(Date.parse('last apr')) } }, 'last may': { run: function() { }, assert: function() { return Date.today().last().may().equals(Date.parse('last may')) } }, 'last june': { run: function() { }, assert: function() { return Date.today().last().june().equals(Date.parse('last june')) } }, 'last jun': { run: function() { }, assert: function() { return Date.today().last().june().equals(Date.parse('last jun')) } }, 'last july': { run: function() { }, assert: function() { return Date.today().last().july().equals(Date.parse('last july')) } }, 'last jul': { run: function() { }, assert: function() { return Date.today().last().july().equals(Date.parse('last july')) } }, 'last august': { run: function() { }, assert: function() { return Date.today().last().august().equals(Date.parse('last august')) } }, 'last aug': { run: function() { }, assert: function() { return Date.today().last().august().equals(Date.parse('last aug')) } }, 'last september': { run: function() { }, assert: function() { return Date.today().last().september().equals(Date.parse('last september')) } }, 'last sept': { run: function() { }, assert: function() { return Date.today().last().september().equals(Date.parse('last sept')) } }, 'last sep': { run: function() { }, assert: function() { return Date.today().last().sep().equals(Date.parse('last sep')) } }, 'last october': { run: function() { }, assert: function() { return Date.today().last().october().equals(Date.parse('last october')) } }, 'last oct': { run: function() { }, assert: function() { return Date.today().last().october().equals(Date.parse('last oct')) } }, 'last november': { run: function() { }, assert: function() { return Date.today().last().november().equals(Date.parse('last november')) } }, 'last nov': { run: function() { }, assert: function() { return Date.today().last().november().equals(Date.parse('last nov')) } }, 'last december': { run: function() { }, assert: function() { return Date.today().last().december().equals(Date.parse('last december')) } }, 'last dec': { run: function() { }, assert: function() { return Date.today().last().december().equals(Date.parse('last dec')) } }, 'prev january': { run: function() { }, assert: function() { return Date.today().prev().january().equals(Date.parse('prev january')) } }, 'prev jan': { run: function() { }, assert: function() { return Date.today().prev().january().equals(Date.parse('prev jan')) } }, 'prev february': { run: function() { }, assert: function() { return Date.today().prev().february().equals(Date.parse('prev february')) } }, 'prev feb': { run: function() { }, assert: function() { return Date.today().prev().february().equals(Date.parse('prev feb')) } }, 'prev march': { run: function() { }, assert: function() { return Date.today().prev().march().equals(Date.parse('prev march')) } }, 'prev mar': { run: function() { }, assert: function() { return Date.today().prev().march().equals(Date.parse('prev mar')) } }, 'prev april': { run: function() { }, assert: function() { return Date.today().prev().april().equals(Date.parse('prev april')) } }, 'prev apr': { run: function() { }, assert: function() { return Date.today().prev().apr().equals(Date.parse('prev apr')) } }, 'prev may': { run: function() { }, assert: function() { return Date.today().prev().may().equals(Date.parse('prev may')) } }, 'prev june': { run: function() { }, assert: function() { return Date.today().prev().june().equals(Date.parse('prev june')) } }, 'prev jun': { run: function() { }, assert: function() { return Date.today().prev().june().equals(Date.parse('prev jun')) } }, 'prev july': { run: function() { }, assert: function() { return Date.today().prev().july().equals(Date.parse('prev july')) } }, 'prev jul': { run: function() { }, assert: function() { return Date.today().prev().july().equals(Date.parse('prev july')) } }, 'prev august': { run: function() { }, assert: function() { return Date.today().prev().august().equals(Date.parse('prev august')) } }, 'prev aug': { run: function() { }, assert: function() { return Date.today().prev().august().equals(Date.parse('prev aug')) } }, 'prev september': { run: function() { }, assert: function() { return Date.today().prev().september().equals(Date.parse('prev september')) } }, 'prev sept': { run: function() { }, assert: function() { return Date.today().prev().september().equals(Date.parse('prev sept')) } }, 'prev sep': { run: function() { }, assert: function() { return Date.today().prev().sep().equals(Date.parse('prev sep')) } }, 'prev october': { run: function() { }, assert: function() { return Date.today().prev().october().equals(Date.parse('prev october')) } }, 'prev oct': { run: function() { }, assert: function() { return Date.today().prev().october().equals(Date.parse('prev oct')) } }, 'prev november': { run: function() { }, assert: function() { return Date.today().prev().november().equals(Date.parse('prev november')) } }, 'prev nov': { run: function() { }, assert: function() { return Date.today().prev().november().equals(Date.parse('prev nov')) } }, 'prev december': { run: function() { }, assert: function() { return Date.today().prev().december().equals(Date.parse('prev december')) } }, 'prev dec': { run: function() { }, assert: function() { return Date.today().prev().december().equals(Date.parse('prev dec')) } }, 'previous january': { run: function() { }, assert: function() { return Date.today().previous().january().equals(Date.parse('previous january')) } }, 'previous jan': { run: function() { }, assert: function() { return Date.today().previous().january().equals(Date.parse('previous jan')) } }, 'previous february': { run: function() { }, assert: function() { return Date.today().previous().february().equals(Date.parse('previous february')) } }, 'previous feb': { run: function() { }, assert: function() { return Date.today().previous().february().equals(Date.parse('previous feb')) } }, 'previous march': { run: function() { }, assert: function() { return Date.today().previous().march().equals(Date.parse('previous march')) } }, 'previous mar': { run: function() { }, assert: function() { return Date.today().previous().march().equals(Date.parse('previous mar')) } }, 'previous april': { run: function() { }, assert: function() { return Date.today().previous().april().equals(Date.parse('previous april')) } }, 'previous apr': { run: function() { }, assert: function() { return Date.today().previous().apr().equals(Date.parse('previous apr')) } }, 'previous may': { run: function() { }, assert: function() { return Date.today().previous().may().equals(Date.parse('previous may')) } }, 'previous june': { run: function() { }, assert: function() { return Date.today().previous().june().equals(Date.parse('previous june')) } }, 'previous jun': { run: function() { }, assert: function() { return Date.today().previous().june().equals(Date.parse('previous jun')) } }, 'previous july': { run: function() { }, assert: function() { return Date.today().previous().july().equals(Date.parse('previous july')) } }, 'previous jul': { run: function() { }, assert: function() { return Date.today().previous().july().equals(Date.parse('previous july')) } }, 'previous august': { run: function() { }, assert: function() { return Date.today().previous().august().equals(Date.parse('previous august')) } }, 'previous aug': { run: function() { }, assert: function() { return Date.today().previous().august().equals(Date.parse('previous aug')) } }, 'previous september': { run: function() { }, assert: function() { return Date.today().previous().september().equals(Date.parse('previous september')) } }, 'previous sept': { run: function() { }, assert: function() { return Date.today().previous().september().equals(Date.parse('previous sept')) } }, 'previous sep': { run: function() { }, assert: function() { return Date.today().previous().sep().equals(Date.parse('previous sep')) } }, 'previous october': { run: function() { }, assert: function() { return Date.today().previous().october().equals(Date.parse('previous october')) } }, 'previous oct': { run: function() { }, assert: function() { return Date.today().previous().october().equals(Date.parse('previous oct')) } }, 'previous november': { run: function() { }, assert: function() { return Date.today().previous().november().equals(Date.parse('previous november')) } }, 'previous nov': { run: function() { }, assert: function() { return Date.today().previous().november().equals(Date.parse('previous nov')) } }, 'previous december': { run: function() { }, assert: function() { return Date.today().previous().december().equals(Date.parse('previous december')) } }, 'previous dec': { run: function() { }, assert: function() { return Date.today().previous().december().equals(Date.parse('previous dec')) } }, 'next january': { run: function() { }, assert: function() { return Date.today().next().january().equals(Date.parse('next january')) } }, 'next jan': { run: function() { }, assert: function() { return Date.today().next().january().equals(Date.parse('next jan')) } }, 'next february': { run: function() { }, assert: function() { return Date.today().next().february().equals(Date.parse('next february')) } }, 'next feb': { run: function() { }, assert: function() { return Date.today().next().february().equals(Date.parse('next feb')) } }, 'next march': { run: function() { }, assert: function() { return Date.today().next().march().equals(Date.parse('next march')) } }, 'next mar': { run: function() { }, assert: function() { return Date.today().next().march().equals(Date.parse('next mar')) } }, 'next april': { run: function() { }, assert: function() { return Date.today().next().april().equals(Date.parse('next april')) } }, 'next apr': { run: function() { }, assert: function() { return Date.today().next().apr().equals(Date.parse('next apr')) } }, 'next may': { run: function() { }, assert: function() { return Date.today().next().may().equals(Date.parse('next may')) } }, 'next june': { run: function() { }, assert: function() { return Date.today().next().june().equals(Date.parse('next june')) } }, 'next jun': { run: function() { }, assert: function() { return Date.today().next().june().equals(Date.parse('next jun')) } }, 'next july': { run: function() { }, assert: function() { return Date.today().next().july().equals(Date.parse('next july')) } }, 'next jul': { run: function() { }, assert: function() { return Date.today().next().july().equals(Date.parse('next july')) } }, 'next august': { run: function() { }, assert: function() { return Date.today().next().august().equals(Date.parse('next august')) } }, 'next aug': { run: function() { }, assert: function() { return Date.today().next().august().equals(Date.parse('next aug')) } }, 'next september': { run: function() { }, assert: function() { return Date.today().next().september().equals(Date.parse('next september')) } }, 'next sept': { run: function() { }, assert: function() { return Date.today().next().september().equals(Date.parse('next sept')) } }, 'next sep': { run: function() { }, assert: function() { return Date.today().next().sep().equals(Date.parse('next sep')) } }, 'next october': { run: function() { }, assert: function() { return Date.today().next().october().equals(Date.parse('next october')) } }, 'next oct': { run: function() { }, assert: function() { return Date.today().next().october().equals(Date.parse('next oct')) } }, 'next november': { run: function() { }, assert: function() { return Date.today().next().november().equals(Date.parse('next november')) } }, 'next nov': { run: function() { }, assert: function() { return Date.today().next().november().equals(Date.parse('next nov')) } }, 'next december': { run: function() { }, assert: function() { return Date.today().next().december().equals(Date.parse('next december')) } }, 'next dec': { run: function() { }, assert: function() { return Date.today().next().december().equals(Date.parse('next dec')) } } }, 'Relative Date Element Parts': { setup: function() { }, 'last seconds': { run: function() { }, assert: function() { return new Date().last().second().set({millisecond: 0}).equals(Date.parse('last seconds').set({millisecond: 0})) } }, 'last second': { run: function() { }, assert: function() { return new Date().last().second().set({millisecond: 0}).equals(Date.parse('last second').set({millisecond: 0})) } }, 'last sec': { run: function() { }, assert: function() { return new Date().last().second().set({millisecond: 0}).equals(Date.parse('last sec').set({millisecond: 0})) } }, 'last minutes': { run: function() { }, assert: function() { return new Date().last().minute().set({millisecond: 0}).equals(Date.parse('last minutes').set({millisecond: 0})) } }, 'last minute': { run: function() { }, assert: function() { return new Date().last().minute().set({millisecond: 0}).equals(Date.parse('last minute').set({millisecond: 0})) } }, 'last min': { run: function() { }, assert: function() { return new Date().last().minute().set({millisecond: 0}).equals(Date.parse('last min').set({millisecond: 0})) } }, 'last mn': { run: function() { }, assert: function() { return new Date().last().minute().set({millisecond: 0}).equals(Date.parse('last mn').set({millisecond: 0})) } }, 'last hours': { run: function() { }, assert: function() { return new Date().last().hour().set({millisecond: 0}).equals(Date.parse('last hours').set({millisecond: 0})) } }, 'last hour': { run: function() { }, assert: function() { return new Date().last().hour().set({millisecond: 0}).equals(Date.parse('last hour').set({millisecond: 0})) } }, 'last days': { run: function() { }, assert: function() { return Date.today().last().day().equals(Date.parse('last days')) } }, 'last day': { run: function() { }, assert: function() { return Date.today().last().day().equals(Date.parse('last day')) } }, 'last weeks': { run: function() { }, assert: function() { return Date.today().last().week().equals(Date.parse('last weeks')) } }, 'last week': { run: function() { }, assert: function() { return Date.today().last().week().equals(Date.parse('last week')) } }, 'last months': { run: function() { }, assert: function() { return Date.today().last().month().equals(Date.parse('last months')) } }, 'last month': { run: function() { }, assert: function() { return Date.today().last().month().equals(Date.parse('last month')) } }, 'last years': { run: function() { }, assert: function() { return Date.today().last().year().equals(Date.parse('last years')) } }, 'last year': { run: function() { }, assert: function() { return Date.today().last().year().equals(Date.parse('last year')) } }, 'prev seconds': { run: function() { }, assert: function() { return new Date().prev().second().set({millisecond: 0}).equals(Date.parse('prev seconds').set({millisecond: 0})) } }, 'prev second': { run: function() { }, assert: function() { return new Date().prev().second().set({millisecond: 0}).equals(Date.parse('prev second').set({millisecond: 0})) } }, 'prev sec': { run: function() { }, assert: function() { return new Date().prev().second().set({millisecond: 0}).equals(Date.parse('prev sec').set({millisecond: 0})) } }, 'prev minutes': { run: function() { }, assert: function() { return new Date().prev().minute().set({millisecond: 0}).equals(Date.parse('prev minutes').set({millisecond: 0})) } }, 'prev minute': { run: function() { }, assert: function() { return new Date().prev().minute().set({millisecond: 0}).equals(Date.parse('prev minute').set({millisecond: 0})) } }, 'prev min': { run: function() { }, assert: function() { return new Date().prev().minute().set({millisecond: 0}).equals(Date.parse('prev min').set({millisecond: 0})) } }, 'prev mn': { run: function() { }, assert: function() { return new Date().prev().minute().set({millisecond: 0}).equals(Date.parse('prev mn').set({millisecond: 0})) } }, 'prev hours': { run: function() { }, assert: function() { return new Date().prev().hour().set({millisecond: 0}).equals(Date.parse('prev hours').set({millisecond: 0})) } }, 'prev hour': { run: function() { }, assert: function() { return new Date().prev().hour().set({millisecond: 0}).equals(Date.parse('prev hour').set({millisecond: 0})) } }, 'prev days': { run: function() { }, assert: function() { return Date.today().prev().day().equals(Date.parse('prev days')) } }, 'prev day': { run: function() { }, assert: function() { return Date.today().prev().day().equals(Date.parse('prev day')) } }, 'prev weeks': { run: function() { }, assert: function() { return Date.today().prev().week().equals(Date.parse('prev weeks')) } }, 'prev week': { run: function() { }, assert: function() { return Date.today().prev().week().equals(Date.parse('prev week')) } }, 'prev months': { run: function() { }, assert: function() { return Date.today().prev().month().equals(Date.parse('prev months')) } }, 'prev month': { run: function() { }, assert: function() { return Date.today().prev().month().equals(Date.parse('prev month')) } }, 'prev years': { run: function() { }, assert: function() { return Date.today().prev().year().equals(Date.parse('prev years')) } }, 'prev year': { run: function() { }, assert: function() { return Date.today().prev().year().equals(Date.parse('prev year')) } }, 'previous seconds': { run: function() { }, assert: function() { return new Date().previous().second().set({millisecond: 0}).equals(Date.parse('previous seconds').set({millisecond: 0})) } }, 'previous second': { run: function() { }, assert: function() { return new Date().previous().second().set({millisecond: 0}).equals(Date.parse('previous second').set({millisecond: 0})) } }, 'previous sec': { run: function() { }, assert: function() { return new Date().previous().second().set({millisecond: 0}).equals(Date.parse('previous sec').set({millisecond: 0})) } }, 'previous minutes': { run: function() { }, assert: function() { return new Date().previous().minute().set({millisecond: 0}).equals(Date.parse('previous minutes').set({millisecond: 0})) } }, 'previous minute': { run: function() { }, assert: function() { return new Date().previous().minute().set({millisecond: 0}).equals(Date.parse('previous minute').set({millisecond: 0})) } }, 'previous min': { run: function() { }, assert: function() { return new Date().previous().minute().set({millisecond: 0}).equals(Date.parse('previous min').set({millisecond: 0})) } }, 'previous mn': { run: function() { }, assert: function() { return new Date().previous().minute().set({millisecond: 0}).equals(Date.parse('previous mn').set({millisecond: 0})) } }, 'previous hours': { run: function() { }, assert: function() { return new Date().previous().hour().set({millisecond: 0}).equals(Date.parse('previous hours').set({millisecond: 0})) } }, 'previous hour': { run: function() { }, assert: function() { return new Date().previous().hour().set({millisecond: 0}).equals(Date.parse('previous hour').set({millisecond: 0})) } }, 'previous days': { run: function() { }, assert: function() { return Date.today().previous().day().equals(Date.parse('previous days')) } }, 'previous day': { run: function() { }, assert: function() { return Date.today().previous().day().equals(Date.parse('previous day')) } }, 'previous weeks': { run: function() { }, assert: function() { return Date.today().previous().week().equals(Date.parse('previous weeks')) } }, 'previous week': { run: function() { }, assert: function() { return Date.today().previous().week().equals(Date.parse('previous week')) } }, 'previous months': { run: function() { }, assert: function() { return Date.today().previous().month().equals(Date.parse('previous months')) } }, 'previous month': { run: function() { }, assert: function() { return Date.today().previous().month().equals(Date.parse('previous month')) } }, 'previous years': { run: function() { }, assert: function() { return Date.today().previous().year().equals(Date.parse('previous years')) } }, 'previous year': { run: function() { }, assert: function() { return Date.today().previous().year().equals(Date.parse('previous year')) } }, 'next seconds': { run: function() { }, assert: function() { return new Date().next().second().set({millisecond: 0}).equals(Date.parse('next seconds').set({millisecond: 0})) } }, 'next second': { run: function() { }, assert: function() { return new Date().next().second().set({millisecond: 0}).equals(Date.parse('next second').set({millisecond: 0})) } }, 'next sec': { run: function() { }, assert: function() { return new Date().next().second().set({millisecond: 0}).equals(Date.parse('next sec').set({millisecond: 0})) } }, 'next minutes': { run: function() { }, assert: function() { return new Date().next().minute().set({millisecond: 0}).equals(Date.parse('next minutes').set({millisecond: 0})) } }, 'next minute': { run: function() { }, assert: function() { return new Date().next().minute().set({millisecond: 0}).equals(Date.parse('next minute').set({millisecond: 0})) } }, 'next min': { run: function() { }, assert: function() { return new Date().next().minute().set({millisecond: 0}).equals(Date.parse('next min').set({millisecond: 0})) } }, 'next mn': { run: function() { }, assert: function() { return new Date().next().minute().set({millisecond: 0}).equals(Date.parse('next mn').set({millisecond: 0})) } }, 'next hours': { run: function() { }, assert: function() { return new Date().next().hour().set({millisecond: 0}).equals(Date.parse('next hours').set({millisecond: 0})) } }, 'next hour': { run: function() { }, assert: function() { return new Date().next().hour().set({millisecond: 0}).equals(Date.parse('next hour').set({millisecond: 0})) } }, 'next days': { run: function() { }, assert: function() { return Date.today().next().day().equals(Date.parse('next days')) } }, 'next day': { run: function() { }, assert: function() { return Date.today().next().day().equals(Date.parse('next day')) } }, 'next weeks': { run: function() { }, assert: function() { return Date.today().next().week().equals(Date.parse('next weeks')) } }, 'next week': { run: function() { }, assert: function() { return Date.today().next().week().equals(Date.parse('next week')) } }, 'next months': { run: function() { }, assert: function() { return Date.today().next().month().equals(Date.parse('next months')) } }, 'next month': { run: function() { }, assert: function() { return Date.today().next().month().equals(Date.parse('next month')) } }, 'next years': { run: function() { }, assert: function() { return Date.today().next().year().equals(Date.parse('next years')) } }, 'next year': { run: function() { }, assert: function() { return Date.today().next().year().equals(Date.parse('next year')) } } } }); $(document).ready( function() { Date.Specification.validate().show() } );
var Waterline = require('../../../lib/waterline'), assert = require('assert'); describe('Collection Query', function() { describe('.create()', function() { describe('with transformed values', function() { var Model; before(function() { Model = Waterline.Collection.extend({ identity: 'user', connection: 'foo', attributes: { name: { type: 'string', columnName: 'login' } } }); }); it('should transform values before sending to adapter', function(done) { var waterline = new Waterline(); waterline.loadCollection(Model); // Fixture Adapter Def var adapterDef = { create: function(con, col, values, cb) { assert(values.login); return cb(null, values); } }; var connections = { 'foo': { adapter: 'foobar' } }; waterline.initialize({ adapters: { foobar: adapterDef }, connections: connections }, function(err, colls) { if(err) return done(err); colls.collections.user.create({ name: 'foo' }, done); }); }); it('should transform values after receiving from adapter', function(done) { var waterline = new Waterline(); waterline.loadCollection(Model); // Fixture Adapter Def var adapterDef = { create: function(con, col, values, cb) { assert(values.login); return cb(null, values); } }; var connections = { 'foo': { adapter: 'foobar' } }; waterline.initialize({ adapters: { foobar: adapterDef }, connections: connections }, function(err, colls) { if(err) return done(err); colls.collections.user.create({ name: 'foo' }, function(err, values) { assert(values.name); assert(!values.login); done(); }); }); }); }); }); });
import { Curve } from '../core/Curve'; import { Vector2 } from '../../math/Vector2'; function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { this.aX = aX; this.aY = aY; this.xRadius = xRadius; this.yRadius = yRadius; this.aStartAngle = aStartAngle; this.aEndAngle = aEndAngle; this.aClockwise = aClockwise; this.aRotation = aRotation || 0; } EllipseCurve.prototype = Object.create( Curve.prototype ); EllipseCurve.prototype.constructor = EllipseCurve; EllipseCurve.prototype.isEllipseCurve = true; EllipseCurve.prototype.getPoint = function ( t ) { var twoPi = Math.PI * 2; var deltaAngle = this.aEndAngle - this.aStartAngle; var samePoints = Math.abs( deltaAngle ) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI while ( deltaAngle < 0 ) deltaAngle += twoPi; while ( deltaAngle > twoPi ) deltaAngle -= twoPi; if ( deltaAngle < Number.EPSILON ) { if ( samePoints ) { deltaAngle = 0; } else { deltaAngle = twoPi; } } if ( this.aClockwise === true && ! samePoints ) { if ( deltaAngle === twoPi ) { deltaAngle = - twoPi; } else { deltaAngle = deltaAngle - twoPi; } } var angle = this.aStartAngle + t * deltaAngle; var x = this.aX + this.xRadius * Math.cos( angle ); var y = this.aY + this.yRadius * Math.sin( angle ); if ( this.aRotation !== 0 ) { var cos = Math.cos( this.aRotation ); var sin = Math.sin( this.aRotation ); var tx = x - this.aX; var ty = y - this.aY; // Rotate the point about the center of the ellipse. x = tx * cos - ty * sin + this.aX; y = tx * sin + ty * cos + this.aY; } return new Vector2( x, y ); }; export { EllipseCurve };
/* http://keith-wood.name/svg.html SVG for jQuery v1.4.5. Written by Keith Wood (kbwood{at}iinet.com.au) August 2007. Dual licensed under the GPL (http://dev.jquery.com/browser/trunk/jquery/GPL-LICENSE.txt) and MIT (http://dev.jquery.com/browser/trunk/jquery/MIT-LICENSE.txt) licenses. Please attribute the author if you use it. */ (function($) { // Hide scope, no $ conflict /* SVG manager. Use the singleton instance of this class, $.svg, to interact with the SVG functionality. */ function SVGManager() { this._settings = []; // Settings to be remembered per SVG object this._extensions = []; // List of SVG extensions added to SVGWrapper // for each entry [0] is extension name, [1] is extension class (function) // the function takes one parameter - the SVGWrapper instance this.regional = []; // Localisations, indexed by language, '' for default (English) this.regional[''] = {errorLoadingText: 'Error loading', notSupportedText: 'This browser does not support SVG'}; this.local = this.regional['']; // Current localisation this._uuid = new Date().getTime(); this._renesis = detectActiveX('RenesisX.RenesisCtrl'); } /* Determine whether a given ActiveX control is available. @param classId (string) the ID for the ActiveX control @return (boolean) true if found, false if not */ function detectActiveX(classId) { try { return !!(window.ActiveXObject && new ActiveXObject(classId)); } catch (e) { return false; } } var PROP_NAME = 'svgwrapper'; $.extend(SVGManager.prototype, { /* Class name added to elements to indicate already configured with SVG. */ markerClassName: 'hasSVG', /* SVG namespace. */ svgNS: 'http://www.w3.org/2000/svg', /* XLink namespace. */ xlinkNS: 'http://www.w3.org/1999/xlink', /* SVG wrapper class. */ _wrapperClass: SVGWrapper, /* Camel-case versions of attribute names containing dashes or are reserved words. */ _attrNames: {class_: 'class', in_: 'in', alignmentBaseline: 'alignment-baseline', baselineShift: 'baseline-shift', clipPath: 'clip-path', clipRule: 'clip-rule', colorInterpolation: 'color-interpolation', colorInterpolationFilters: 'color-interpolation-filters', colorRendering: 'color-rendering', dominantBaseline: 'dominant-baseline', enableBackground: 'enable-background', fillOpacity: 'fill-opacity', fillRule: 'fill-rule', floodColor: 'flood-color', floodOpacity: 'flood-opacity', fontFamily: 'font-family', fontSize: 'font-size', fontSizeAdjust: 'font-size-adjust', fontStretch: 'font-stretch', fontStyle: 'font-style', fontVariant: 'font-variant', fontWeight: 'font-weight', glyphOrientationHorizontal: 'glyph-orientation-horizontal', glyphOrientationVertical: 'glyph-orientation-vertical', horizAdvX: 'horiz-adv-x', horizOriginX: 'horiz-origin-x', imageRendering: 'image-rendering', letterSpacing: 'letter-spacing', lightingColor: 'lighting-color', markerEnd: 'marker-end', markerMid: 'marker-mid', markerStart: 'marker-start', stopColor: 'stop-color', stopOpacity: 'stop-opacity', strikethroughPosition: 'strikethrough-position', strikethroughThickness: 'strikethrough-thickness', strokeDashArray: 'stroke-dasharray', strokeDashOffset: 'stroke-dashoffset', strokeLineCap: 'stroke-linecap', strokeLineJoin: 'stroke-linejoin', strokeMiterLimit: 'stroke-miterlimit', strokeOpacity: 'stroke-opacity', strokeWidth: 'stroke-width', textAnchor: 'text-anchor', textDecoration: 'text-decoration', textRendering: 'text-rendering', underlinePosition: 'underline-position', underlineThickness: 'underline-thickness', vertAdvY: 'vert-adv-y', vertOriginY: 'vert-origin-y', wordSpacing: 'word-spacing', writingMode: 'writing-mode'}, /* Add the SVG object to its container. */ _attachSVG: function(container, settings) { var svg = (container.namespaceURI == this.svgNS ? container : null); var container = (svg ? null : container); if ($(container || svg).hasClass(this.markerClassName)) { return; } if (typeof settings == 'string') { settings = {loadURL: settings}; } else if (typeof settings == 'function') { settings = {onLoad: settings}; } $(container || svg).addClass(this.markerClassName); try { if (!svg) { svg = document.createElementNS(this.svgNS, 'svg'); svg.setAttribute('version', '1.1'); if (container.clientWidth > 0) { svg.setAttribute('width', container.clientWidth); } if (container.clientHeight > 0) { svg.setAttribute('height', container.clientHeight); } container.appendChild(svg); } this._afterLoad(container, svg, settings || {}); } catch (e) { if ($.browser.msie) { if (!container.id) { container.id = 'svg' + (this._uuid++); } this._settings[container.id] = settings; container.innerHTML = '<embed type="image/svg+xml" width="100%" ' + 'height="100%" src="' + (settings.initPath || '') + 'blank.svg" ' + 'pluginspage="http://www.adobe.com/svg/viewer/install/main.html"/>'; } else { container.innerHTML = '<p class="svg_error">' + this.local.notSupportedText + '</p>'; } } }, /* SVG callback after loading - register SVG root. */ _registerSVG: function() { for (var i = 0; i < document.embeds.length; i++) { // Check all var container = document.embeds[i].parentNode; if (!$(container).hasClass($.svg.markerClassName) || // Not SVG $.data(container, PROP_NAME)) { // Already done continue; } var svg = null; try { svg = document.embeds[i].getSVGDocument(); } catch(e) { setTimeout($.svg._registerSVG, 250); // Renesis takes longer to load return; } svg = (svg ? svg.documentElement : null); if (svg) { $.svg._afterLoad(container, svg); } } }, /* Post-processing once loaded. */ _afterLoad: function(container, svg, settings) { var settings = settings || this._settings[container.id]; this._settings[container ? container.id : ''] = null; var wrapper = new this._wrapperClass(svg, container); $.data(container || svg, PROP_NAME, wrapper); try { if (settings.loadURL) { // Load URL wrapper.load(settings.loadURL, settings); } if (settings.settings) { // Additional settings wrapper.configure(settings.settings); } if (settings.onLoad && !settings.loadURL) { // Onload callback settings.onLoad.apply(container || svg, [wrapper]); } } catch (e) { alert(e); } }, /* Return the SVG wrapper created for a given container. @param container (string) selector for the container or (element) the container for the SVG object or jQuery collection - first entry is the container @return (SVGWrapper) the corresponding SVG wrapper element, or null if not attached */ _getSVG: function(container) { container = (typeof container == 'string' ? $(container)[0] : (container.jquery ? container[0] : container)); return $.data(container, PROP_NAME); }, /* Remove the SVG functionality from a div. @param container (element) the container for the SVG object */ _destroySVG: function(container) { var $container = $(container); if (!$container.hasClass(this.markerClassName)) { return; } $container.removeClass(this.markerClassName); if (container.namespaceURI != this.svgNS) { $container.empty(); } $.removeData(container, PROP_NAME); }, /* Extend the SVGWrapper object with an embedded class. The constructor function must take a single parameter that is a reference to the owning SVG root object. This allows the extension to access the basic SVG functionality. @param name (string) the name of the SVGWrapper attribute to access the new class @param extClass (function) the extension class constructor */ addExtension: function(name, extClass) { this._extensions.push([name, extClass]); }, /* Does this node belong to SVG? @param node (element) the node to be tested @return (boolean) true if an SVG node, false if not */ isSVGElem: function(node) { return (node.nodeType == 1 && node.namespaceURI == $.svg.svgNS); } }); /* The main SVG interface, which encapsulates the SVG element. Obtain a reference from $().svg('get') */ function SVGWrapper(svg, container) { this._svg = svg; // The SVG root node this._container = container; // The containing div for (var i = 0; i < $.svg._extensions.length; i++) { var extension = $.svg._extensions[i]; this[extension[0]] = new extension[1](this); } } $.extend(SVGWrapper.prototype, { /* Retrieve the width of the SVG object. */ _width: function() { return (this._container ? this._container.clientWidth : this._svg.width); }, /* Retrieve the height of the SVG object. */ _height: function() { return (this._container ? this._container.clientHeight : this._svg.height); }, /* Retrieve the root SVG element. @return the top-level SVG element */ root: function() { return this._svg; }, /* Configure a SVG node. @param node (element, optional) the node to configure @param settings (object) additional settings for the root @param clear (boolean) true to remove existing attributes first, false to add to what is already there (optional) @return (SVGWrapper) this root */ configure: function(node, settings, clear) { if (!node.nodeName) { clear = settings; settings = node; node = this._svg; } if (clear) { for (var i = node.attributes.length - 1; i >= 0; i--) { var attr = node.attributes.item(i); if (!(attr.nodeName == 'onload' || attr.nodeName == 'version' || attr.nodeName.substring(0, 5) == 'xmlns')) { node.attributes.removeNamedItem(attr.nodeName); } } } for (var attrName in settings) { node.setAttribute($.svg._attrNames[attrName] || attrName, settings[attrName]); } return this; }, /* Locate a specific element in the SVG document. @param id (string) the element's identifier @return (element) the element reference, or null if not found */ getElementById: function(id) { return this._svg.ownerDocument.getElementById(id); }, /* Change the attributes for a SVG node. @param element (SVG element) the node to change @param settings (object) the new settings @return (SVGWrapper) this root */ change: function(element, settings) { if (element) { for (var name in settings) { if (settings[name] == null) { element.removeAttribute($.svg._attrNames[name] || name); } else { element.setAttribute($.svg._attrNames[name] || name, settings[name]); } } } return this; }, /* Check for parent being absent and adjust arguments accordingly. */ _args: function(values, names, optSettings) { names.splice(0, 0, 'parent'); names.splice(names.length, 0, 'settings'); var args = {}; var offset = 0; if (values[0] != null && values[0].jquery) { values[0] = values[0][0]; } if (values[0] != null && !(typeof values[0] == 'object' && values[0].nodeName)) { args['parent'] = null; offset = 1; } for (var i = 0; i < values.length; i++) { args[names[i + offset]] = values[i]; } if (optSettings) { $.each(optSettings, function(i, value) { if (typeof args[value] == 'object') { args.settings = args[value]; args[value] = null; } }); } return args; }, /* Add a title. @param parent (element or jQuery) the parent node for the new title (optional) @param text (string) the text of the title @param settings (object) additional settings for the title (optional) @return (element) the new title node */ title: function(parent, text, settings) { var args = this._args(arguments, ['text']); var node = this._makeNode(args.parent, 'title', args.settings || {}); node.appendChild(this._svg.ownerDocument.createTextNode(args.text)); return node; }, /* Add a description. @param parent (element or jQuery) the parent node for the new description (optional) @param text (string) the text of the description @param settings (object) additional settings for the description (optional) @return (element) the new description node */ describe: function(parent, text, settings) { var args = this._args(arguments, ['text']); var node = this._makeNode(args.parent, 'desc', args.settings || {}); node.appendChild(this._svg.ownerDocument.createTextNode(args.text)); return node; }, /* Add a definitions node. @param parent (element or jQuery) the parent node for the new definitions (optional) @param id (string) the ID of this definitions (optional) @param settings (object) additional settings for the definitions (optional) @return (element) the new definitions node */ defs: function(parent, id, settings) { var args = this._args(arguments, ['id'], ['id']); return this._makeNode(args.parent, 'defs', $.extend( (args.id ? {id: args.id} : {}), args.settings || {})); }, /* Add a symbol definition. @param parent (element or jQuery) the parent node for the new symbol (optional) @param id (string) the ID of this symbol @param x1 (number) the left coordinate for this symbol @param y1 (number) the top coordinate for this symbol @param width (number) the width of this symbol @param height (number) the height of this symbol @param settings (object) additional settings for the symbol (optional) @return (element) the new symbol node */ symbol: function(parent, id, x1, y1, width, height, settings) { var args = this._args(arguments, ['id', 'x1', 'y1', 'width', 'height']); return this._makeNode(args.parent, 'symbol', $.extend({id: args.id, viewBox: args.x1 + ' ' + args.y1 + ' ' + args.width + ' ' + args.height}, args.settings || {})); }, /* Add a marker definition. @param parent (element or jQuery) the parent node for the new marker (optional) @param id (string) the ID of this marker @param refX (number) the x-coordinate for the reference point @param refY (number) the y-coordinate for the reference point @param mWidth (number) the marker viewport width @param mHeight (number) the marker viewport height @param orient (string or int) 'auto' or angle (degrees) (optional) @param settings (object) additional settings for the marker (optional) @return (element) the new marker node */ marker: function(parent, id, refX, refY, mWidth, mHeight, orient, settings) { var args = this._args(arguments, ['id', 'refX', 'refY', 'mWidth', 'mHeight', 'orient'], ['orient']); return this._makeNode(args.parent, 'marker', $.extend( {id: args.id, refX: args.refX, refY: args.refY, markerWidth: args.mWidth, markerHeight: args.mHeight, orient: args.orient || 'auto'}, args.settings || {})); }, /* Add a style node. @param parent (element or jQuery) the parent node for the new node (optional) @param styles (string) the CSS styles @param settings (object) additional settings for the node (optional) @return (element) the new style node */ style: function(parent, styles, settings) { var args = this._args(arguments, ['styles']); var node = this._makeNode(args.parent, 'style', $.extend( {type: 'text/css'}, args.settings || {})); node.appendChild(this._svg.ownerDocument.createTextNode(args.styles)); if ($.browser.opera) { $('head').append('<style type="text/css">' + args.styles + '</style>'); } return node; }, /* Add a script node. @param parent (element or jQuery) the parent node for the new node (optional) @param script (string) the JavaScript code @param type (string) the MIME type for the code (optional, default 'text/javascript') @param settings (object) additional settings for the node (optional) @return (element) the new script node */ script: function(parent, script, type, settings) { var args = this._args(arguments, ['script', 'type'], ['type']); var node = this._makeNode(args.parent, 'script', $.extend( {type: args.type || 'text/javascript'}, args.settings || {})); node.appendChild(this._svg.ownerDocument.createTextNode(args.script)); if (!$.browser.mozilla) { $.globalEval(args.script); } return node; }, /* Add a linear gradient definition. Specify all of x1, y1, x2, y2 or none of them. @param parent (element or jQuery) the parent node for the new gradient (optional) @param id (string) the ID for this gradient @param stops (string[][]) the gradient stops, each entry is [0] is offset (0.0-1.0 or 0%-100%), [1] is colour, [2] is opacity (optional) @param x1 (number) the x-coordinate of the gradient start (optional) @param y1 (number) the y-coordinate of the gradient start (optional) @param x2 (number) the x-coordinate of the gradient end (optional) @param y2 (number) the y-coordinate of the gradient end (optional) @param settings (object) additional settings for the gradient (optional) @return (element) the new gradient node */ linearGradient: function(parent, id, stops, x1, y1, x2, y2, settings) { var args = this._args(arguments, ['id', 'stops', 'x1', 'y1', 'x2', 'y2'], ['x1']); var sets = $.extend({id: args.id}, (args.x1 != null ? {x1: args.x1, y1: args.y1, x2: args.x2, y2: args.y2} : {})); return this._gradient(args.parent, 'linearGradient', $.extend(sets, args.settings || {}), args.stops); }, /* Add a radial gradient definition. Specify all of cx, cy, r, fx, fy or none of them. @param parent (element or jQuery) the parent node for the new gradient (optional) @param id (string) the ID for this gradient @param stops (string[][]) the gradient stops, each entry [0] is offset, [1] is colour, [2] is opacity (optional) @param cx (number) the x-coordinate of the largest circle centre (optional) @param cy (number) the y-coordinate of the largest circle centre (optional) @param r (number) the radius of the largest circle (optional) @param fx (number) the x-coordinate of the gradient focus (optional) @param fy (number) the y-coordinate of the gradient focus (optional) @param settings (object) additional settings for the gradient (optional) @return (element) the new gradient node */ radialGradient: function(parent, id, stops, cx, cy, r, fx, fy, settings) { var args = this._args(arguments, ['id', 'stops', 'cx', 'cy', 'r', 'fx', 'fy'], ['cx']); var sets = $.extend({id: args.id}, (args.cx != null ? {cx: args.cx, cy: args.cy, r: args.r, fx: args.fx, fy: args.fy} : {})); return this._gradient(args.parent, 'radialGradient', $.extend(sets, args.settings || {}), args.stops); }, /* Add a gradient node. */ _gradient: function(parent, name, settings, stops) { var node = this._makeNode(parent, name, settings); for (var i = 0; i < stops.length; i++) { var stop = stops[i]; this._makeNode(node, 'stop', $.extend( {offset: stop[0], stopColor: stop[1]}, (stop[2] != null ? {stopOpacity: stop[2]} : {}))); } return node; }, /* Add a pattern definition. Specify all of vx, vy, xwidth, vheight or none of them. @param parent (element or jQuery) the parent node for the new pattern (optional) @param id (string) the ID for this pattern @param x (number) the x-coordinate for the left edge of the pattern @param y (number) the y-coordinate for the top edge of the pattern @param width (number) the width of the pattern @param height (number) the height of the pattern @param vx (number) the minimum x-coordinate for view box (optional) @param vy (number) the minimum y-coordinate for the view box (optional) @param vwidth (number) the width of the view box (optional) @param vheight (number) the height of the view box (optional) @param settings (object) additional settings for the pattern (optional) @return (element) the new pattern node */ pattern: function(parent, id, x, y, width, height, vx, vy, vwidth, vheight, settings) { var args = this._args(arguments, ['id', 'x', 'y', 'width', 'height', 'vx', 'vy', 'vwidth', 'vheight'], ['vx']); var sets = $.extend({id: args.id, x: args.x, y: args.y, width: args.width, height: args.height}, (args.vx != null ? {viewBox: args.vx + ' ' + args.vy + ' ' + args.vwidth + ' ' + args.vheight} : {})); return this._makeNode(args.parent, 'pattern', $.extend(sets, args.settings || {})); }, /* Add a clip path definition. @param parent (element) the parent node for the new element (optional) @param id (string) the ID for this path @param units (string) either 'userSpaceOnUse' (default) or 'objectBoundingBox' (optional) @return (element) the new clipPath node */ clipPath: function(parent, id, units, settings) { var args = this._args(arguments, ['id', 'units']); args.units = args.units || 'userSpaceOnUse'; return this._makeNode(args.parent, 'clipPath', $.extend( {id: args.id, clipPathUnits: args.units}, args.settings || {})); }, /* Add a mask definition. @param parent (element or jQuery) the parent node for the new mask (optional) @param id (string) the ID for this mask @param x (number) the x-coordinate for the left edge of the mask @param y (number) the y-coordinate for the top edge of the mask @param width (number) the width of the mask @param height (number) the height of the mask @param settings (object) additional settings for the mask (optional) @return (element) the new mask node */ mask: function(parent, id, x, y, width, height, settings) { var args = this._args(arguments, ['id', 'x', 'y', 'width', 'height']); return this._makeNode(args.parent, 'mask', $.extend( {id: args.id, x: args.x, y: args.y, width: args.width, height: args.height}, args.settings || {})); }, /* Create a new path object. @return (SVGPath) a new path object */ createPath: function() { return new SVGPath(); }, /* Create a new text object. @return (SVGText) a new text object */ createText: function() { return new SVGText(); }, /* Add an embedded SVG element. Specify all of vx, vy, vwidth, vheight or none of them. @param parent (element or jQuery) the parent node for the new node (optional) @param x (number) the x-coordinate for the left edge of the node @param y (number) the y-coordinate for the top edge of the node @param width (number) the width of the node @param height (number) the height of the node @param vx (number) the minimum x-coordinate for view box (optional) @param vy (number) the minimum y-coordinate for the view box (optional) @param vwidth (number) the width of the view box (optional) @param vheight (number) the height of the view box (optional) @param settings (object) additional settings for the node (optional) @return (element) the new node */ svg: function(parent, x, y, width, height, vx, vy, vwidth, vheight, settings) { var args = this._args(arguments, ['x', 'y', 'width', 'height', 'vx', 'vy', 'vwidth', 'vheight'], ['vx']); var sets = $.extend({x: args.x, y: args.y, width: args.width, height: args.height}, (args.vx != null ? {viewBox: args.vx + ' ' + args.vy + ' ' + args.vwidth + ' ' + args.vheight} : {})); return this._makeNode(args.parent, 'svg', $.extend(sets, args.settings || {})); }, /* Create a group. @param parent (element or jQuery) the parent node for the new group (optional) @param id (string) the ID of this group (optional) @param settings (object) additional settings for the group (optional) @return (element) the new group node */ group: function(parent, id, settings) { var args = this._args(arguments, ['id'], ['id']); return this._makeNode(args.parent, 'g', $.extend({id: args.id}, args.settings || {})); }, /* Add a usage reference. Specify all of x, y, width, height or none of them. @param parent (element or jQuery) the parent node for the new node (optional) @param x (number) the x-coordinate for the left edge of the node (optional) @param y (number) the y-coordinate for the top edge of the node (optional) @param width (number) the width of the node (optional) @param height (number) the height of the node (optional) @param ref (string) the ID of the definition node @param settings (object) additional settings for the node (optional) @return (element) the new node */ use: function(parent, x, y, width, height, ref, settings) { var args = this._args(arguments, ['x', 'y', 'width', 'height', 'ref']); if (typeof args.x == 'string') { args.ref = args.x; args.settings = args.y; args.x = args.y = args.width = args.height = null; } var node = this._makeNode(args.parent, 'use', $.extend( {x: args.x, y: args.y, width: args.width, height: args.height}, args.settings || {})); node.setAttributeNS($.svg.xlinkNS, 'href', args.ref); return node; }, /* Add a link, which applies to all child elements. @param parent (element or jQuery) the parent node for the new link (optional) @param ref (string) the target URL @param settings (object) additional settings for the link (optional) @return (element) the new link node */ link: function(parent, ref, settings) { var args = this._args(arguments, ['ref']); var node = this._makeNode(args.parent, 'a', args.settings); node.setAttributeNS($.svg.xlinkNS, 'href', args.ref); return node; }, /* Add an image. @param parent (element or jQuery) the parent node for the new image (optional) @param x (number) the x-coordinate for the left edge of the image @param y (number) the y-coordinate for the top edge of the image @param width (number) the width of the image @param height (number) the height of the image @param ref (string) the path to the image @param settings (object) additional settings for the image (optional) @return (element) the new image node */ image: function(parent, x, y, width, height, ref, settings) { var args = this._args(arguments, ['x', 'y', 'width', 'height', 'ref']); var node = this._makeNode(args.parent, 'image', $.extend( {x: args.x, y: args.y, width: args.width, height: args.height}, args.settings || {})); node.setAttributeNS($.svg.xlinkNS, 'href', args.ref); return node; }, /* Draw a path. @param parent (element or jQuery) the parent node for the new shape (optional) @param path (string or SVGPath) the path to draw @param settings (object) additional settings for the shape (optional) @return (element) the new shape node */ path: function(parent, path, settings) { var args = this._args(arguments, ['path']); return this._makeNode(args.parent, 'path', $.extend( {d: (args.path.path ? args.path.path() : args.path)}, args.settings || {})); }, /* Draw a rectangle. Specify both of rx and ry or neither. @param parent (element or jQuery) the parent node for the new shape (optional) @param x (number) the x-coordinate for the left edge of the rectangle @param y (number) the y-coordinate for the top edge of the rectangle @param width (number) the width of the rectangle @param height (number) the height of the rectangle @param rx (number) the x-radius of the ellipse for the rounded corners (optional) @param ry (number) the y-radius of the ellipse for the rounded corners (optional) @param settings (object) additional settings for the shape (optional) @return (element) the new shape node */ rect: function(parent, x, y, width, height, rx, ry, settings) { var args = this._args(arguments, ['x', 'y', 'width', 'height', 'rx', 'ry'], ['rx']); return this._makeNode(args.parent, 'rect', $.extend( {x: args.x, y: args.y, width: args.width, height: args.height}, (args.rx ? {rx: args.rx, ry: args.ry} : {}), args.settings || {})); }, /* Draw a circle. @param parent (element or jQuery) the parent node for the new shape (optional) @param cx (number) the x-coordinate for the centre of the circle @param cy (number) the y-coordinate for the centre of the circle @param r (number) the radius of the circle @param settings (object) additional settings for the shape (optional) @return (element) the new shape node */ circle: function(parent, cx, cy, r, settings) { var args = this._args(arguments, ['cx', 'cy', 'r']); return this._makeNode(args.parent, 'circle', $.extend( {cx: args.cx, cy: args.cy, r: args.r}, args.settings || {})); }, /* Draw an ellipse. @param parent (element or jQuery) the parent node for the new shape (optional) @param cx (number) the x-coordinate for the centre of the ellipse @param cy (number) the y-coordinate for the centre of the ellipse @param rx (number) the x-radius of the ellipse @param ry (number) the y-radius of the ellipse @param settings (object) additional settings for the shape (optional) @return (element) the new shape node */ ellipse: function(parent, cx, cy, rx, ry, settings) { var args = this._args(arguments, ['cx', 'cy', 'rx', 'ry']); return this._makeNode(args.parent, 'ellipse', $.extend( {cx: args.cx, cy: args.cy, rx: args.rx, ry: args.ry}, args.settings || {})); }, /* Draw a line. @param parent (element or jQuery) the parent node for the new shape (optional) @param x1 (number) the x-coordinate for the start of the line @param y1 (number) the y-coordinate for the start of the line @param x2 (number) the x-coordinate for the end of the line @param y2 (number) the y-coordinate for the end of the line @param settings (object) additional settings for the shape (optional) @return (element) the new shape node */ line: function(parent, x1, y1, x2, y2, settings) { var args = this._args(arguments, ['x1', 'y1', 'x2', 'y2']); return this._makeNode(args.parent, 'line', $.extend( {x1: args.x1, y1: args.y1, x2: args.x2, y2: args.y2}, args.settings || {})); }, /* Draw a polygonal line. @param parent (element or jQuery) the parent node for the new shape (optional) @param points (number[][]) the x-/y-coordinates for the points on the line @param settings (object) additional settings for the shape (optional) @return (element) the new shape node */ polyline: function(parent, points, settings) { var args = this._args(arguments, ['points']); return this._poly(args.parent, 'polyline', args.points, args.settings); }, /* Draw a polygonal shape. @param parent (element or jQuery) the parent node for the new shape (optional) @param points (number[][]) the x-/y-coordinates for the points on the shape @param settings (object) additional settings for the shape (optional) @return (element) the new shape node */ polygon: function(parent, points, settings) { var args = this._args(arguments, ['points']); return this._poly(args.parent, 'polygon', args.points, args.settings); }, /* Draw a polygonal line or shape. */ _poly: function(parent, name, points, settings) { var ps = ''; for (var i = 0; i < points.length; i++) { ps += points[i].join() + ' '; } return this._makeNode(parent, name, $.extend( {points: $.trim(ps)}, settings || {})); }, /* Draw text. Specify both of x and y or neither of them. @param parent (element or jQuery) the parent node for the text (optional) @param x (number or number[]) the x-coordinate(s) for the text (optional) @param y (number or number[]) the y-coordinate(s) for the text (optional) @param value (string) the text content or (SVGText) text with spans and references @param settings (object) additional settings for the text (optional) @return (element) the new text node */ text: function(parent, x, y, value, settings) { var args = this._args(arguments, ['x', 'y', 'value']); if (typeof args.x == 'string' && arguments.length < 4) { args.value = args.x; args.settings = args.y; args.x = args.y = null; } return this._text(args.parent, 'text', args.value, $.extend( {x: (args.x && isArray(args.x) ? args.x.join(' ') : args.x), y: (args.y && isArray(args.y) ? args.y.join(' ') : args.y)}, args.settings || {})); }, /* Draw text along a path. @param parent (element or jQuery) the parent node for the text (optional) @param path (string) the ID of the path @param value (string) the text content or (SVGText) text with spans and references @param settings (object) additional settings for the text (optional) @return (element) the new text node */ textpath: function(parent, path, value, settings) { var args = this._args(arguments, ['path', 'value']); var node = this._text(args.parent, 'textPath', args.value, args.settings || {}); node.setAttributeNS($.svg.xlinkNS, 'href', args.path); return node; }, /* Draw text. */ _text: function(parent, name, value, settings) { var node = this._makeNode(parent, name, settings); if (typeof value == 'string') { node.appendChild(node.ownerDocument.createTextNode(value)); } else { for (var i = 0; i < value._parts.length; i++) { var part = value._parts[i]; if (part[0] == 'tspan') { var child = this._makeNode(node, part[0], part[2]); child.appendChild(node.ownerDocument.createTextNode(part[1])); node.appendChild(child); } else if (part[0] == 'tref') { var child = this._makeNode(node, part[0], part[2]); child.setAttributeNS($.svg.xlinkNS, 'href', part[1]); node.appendChild(child); } else if (part[0] == 'textpath') { var set = $.extend({}, part[2]); set.href = null; var child = this._makeNode(node, part[0], set); child.setAttributeNS($.svg.xlinkNS, 'href', part[2].href); child.appendChild(node.ownerDocument.createTextNode(part[1])); node.appendChild(child); } else { // straight text node.appendChild(node.ownerDocument.createTextNode(part[1])); } } } return node; }, /* Add a custom SVG element. @param parent (element or jQuery) the parent node for the new element (optional) @param name (string) the name of the element @param settings (object) additional settings for the element (optional) @return (element) the new custom node */ other: function(parent, name, settings) { var args = this._args(arguments, ['name']); return this._makeNode(args.parent, args.name, args.settings || {}); }, /* Create a shape node with the given settings. */ _makeNode: function(parent, name, settings) { parent = parent || this._svg; var node = this._svg.ownerDocument.createElementNS($.svg.svgNS, name); for (var name in settings) { var value = settings[name]; if (value != null && value != null && (typeof value != 'string' || value != '')) { node.setAttribute($.svg._attrNames[name] || name, value); } } parent.appendChild(node); return node; }, /* Add an existing SVG node to the diagram. @param parent (element or jQuery) the parent node for the new node (optional) @param node (element) the new node to add or (string) the jQuery selector for the node or (jQuery collection) set of nodes to add @return (SVGWrapper) this wrapper */ add: function(parent, node) { var args = this._args((arguments.length == 1 ? [null, parent] : arguments), ['node']); var svg = this; args.parent = args.parent || this._svg; args.node = (args.node.jquery ? args.node : $(args.node)); try { if ($.svg._renesis) { throw 'Force traversal'; } args.parent.appendChild(args.node.cloneNode(true)); } catch (e) { args.node.each(function() { var child = svg._cloneAsSVG(this); if (child) { args.parent.appendChild(child); } }); } return this; }, /* Clone an existing SVG node and add it to the diagram. @param parent (element or jQuery) the parent node for the new node (optional) @param node (element) the new node to add or (string) the jQuery selector for the node or (jQuery collection) set of nodes to add @return (element[]) collection of new nodes */ clone: function(parent, node) { var svg = this; var args = this._args((arguments.length == 1 ? [null, parent] : arguments), ['node']); args.parent = args.parent || this._svg; args.node = (args.node.jquery ? args.node : $(args.node)); var newNodes = []; args.node.each(function() { var child = svg._cloneAsSVG(this); if (child) { child.id = ''; args.parent.appendChild(child); newNodes.push(child); } }); return newNodes; }, /* SVG nodes must belong to the SVG namespace, so clone and ensure this is so. @param node (element) the SVG node to clone @return (element) the cloned node */ _cloneAsSVG: function(node) { var newNode = null; if (node.nodeType == 1) { // element newNode = this._svg.ownerDocument.createElementNS( $.svg.svgNS, this._checkName(node.nodeName)); for (var i = 0; i < node.attributes.length; i++) { var attr = node.attributes.item(i); if (attr.nodeName != 'xmlns' && attr.nodeValue) { if (attr.prefix == 'xlink') { newNode.setAttributeNS($.svg.xlinkNS, attr.localName || attr.baseName, attr.nodeValue); } else { newNode.setAttribute(this._checkName(attr.nodeName), attr.nodeValue); } } } for (var i = 0; i < node.childNodes.length; i++) { var child = this._cloneAsSVG(node.childNodes[i]); if (child) { newNode.appendChild(child); } } } else if (node.nodeType == 3) { // text if ($.trim(node.nodeValue)) { newNode = this._svg.ownerDocument.createTextNode(node.nodeValue); } } else if (node.nodeType == 4) { // CDATA if ($.trim(node.nodeValue)) { try { newNode = this._svg.ownerDocument.createCDATASection(node.nodeValue); } catch (e) { newNode = this._svg.ownerDocument.createTextNode( node.nodeValue.replace(/&/g, '&amp;'). replace(/</g, '&lt;').replace(/>/g, '&gt;')); } } } return newNode; }, /* Node names must be lower case and without SVG namespace prefix. */ _checkName: function(name) { name = (name.substring(0, 1) >= 'A' && name.substring(0, 1) <= 'Z' ? name.toLowerCase() : name); return (name.substring(0, 4) == 'svg:' ? name.substring(4) : name); }, /* Load an external SVG document. @param url (string) the location of the SVG document or the actual SVG content @param settings (boolean) see addTo below or (function) see onLoad below or (object) additional settings for the load with attributes below: addTo (boolean) true to add to what's already there, or false to clear the canvas first changeSize (boolean) true to allow the canvas size to change, or false to retain the original onLoad (function) callback after the document has loaded, 'this' is the container, receives SVG object and optional error message as a parameter parent (string or element or jQuery) the parent to load into, defaults to top-level svg element @return (SVGWrapper) this root */ load: function(url, settings) { settings = (typeof settings == 'boolean' ? {addTo: settings} : (typeof settings == 'function' ? {onLoad: settings} : (typeof settings == 'string' ? {parent: settings} : (typeof settings == 'object' && settings.nodeName ? {parent: settings} : (typeof settings == 'object' && settings.jquery ? {parent: settings} : settings || {}))))); if (!settings.parent && !settings.addTo) { this.clear(false); } var size = [this._svg.getAttribute('width'), this._svg.getAttribute('height')]; var wrapper = this; // Report a problem with the load var reportError = function(message) { message = $.svg.local.errorLoadingText + ': ' + message; if (settings.onLoad) { settings.onLoad.apply(wrapper._container || wrapper._svg, [wrapper, message]); } else { wrapper.text(null, 10, 20, message); } }; // Create a DOM from SVG content var loadXML4IE = function(data) { var xml = new ActiveXObject('Microsoft.XMLDOM'); xml.validateOnParse = false; xml.resolveExternals = false; xml.async = false; xml.loadXML(data); if (xml.parseError.errorCode != 0) { reportError(xml.parseError.reason); return null; } return xml; }; // Load the SVG DOM var loadSVG = function(data) { if (!data) { return; } if (data.documentElement.nodeName != 'svg') { var errors = data.getElementsByTagName('parsererror'); var messages = (errors.length ? errors[0].getElementsByTagName('div') : []); // Safari reportError(!errors.length ? '???' : (messages.length ? messages[0] : errors[0]).firstChild.nodeValue); return; } var parent = (settings.parent ? $(settings.parent)[0] : wrapper._svg); var attrs = {}; for (var i = 0; i < data.documentElement.attributes.length; i++) { var attr = data.documentElement.attributes.item(i); if (!(attr.nodeName == 'version' || attr.nodeName.substring(0, 5) == 'xmlns')) { attrs[attr.nodeName] = attr.nodeValue; } } wrapper.configure(parent, attrs, !settings.parent); var nodes = data.documentElement.childNodes; for (var i = 0; i < nodes.length; i++) { try { if ($.svg._renesis) { throw 'Force traversal'; } parent.appendChild(wrapper._svg.ownerDocument.importNode(nodes[i], true)); if (nodes[i].nodeName == 'script') { $.globalEval(nodes[i].textContent); } } catch (e) { wrapper.add(parent, nodes[i]); } } if (!settings.changeSize) { wrapper.configure(parent, {width: size[0], height: size[1]}); } if (settings.onLoad) { settings.onLoad.apply(wrapper._container || wrapper._svg, [wrapper]); } }; if (url.match('<svg')) { // Inline SVG loadSVG($.browser.msie ? loadXML4IE(url) : new DOMParser().parseFromString(url, 'text/xml')); } else { // Remote SVG $.ajax({url: url, dataType: ($.browser.msie ? 'text' : 'xml'), success: function(xml) { loadSVG($.browser.msie ? loadXML4IE(xml) : xml); }, error: function(http, message, exc) { reportError(message + (exc ? ' ' + exc.message : '')); }}); } return this; }, /* Delete a specified node. @param node (element or jQuery) the drawing node to remove @return (SVGWrapper) this root */ remove: function(node) { node = (node.jquery ? node[0] : node); node.parentNode.removeChild(node); return this; }, /* Delete everything in the current document. @param attrsToo (boolean) true to clear any root attributes as well, false to leave them (optional) @return (SVGWrapper) this root */ clear: function(attrsToo) { if (attrsToo) { this.configure({}, true); } while (this._svg.firstChild) { this._svg.removeChild(this._svg.firstChild); } return this; }, /* Serialise the current diagram into an SVG text document. @param node (SVG element) the starting node (optional) @return (string) the SVG as text */ toSVG: function(node) { node = node || this._svg; return (typeof XMLSerializer == 'undefined' ? this._toSVG(node) : new XMLSerializer().serializeToString(node)); }, /* Serialise one node in the SVG hierarchy. */ _toSVG: function(node) { var svgDoc = ''; if (!node) { return svgDoc; } if (node.nodeType == 3) { // Text svgDoc = node.nodeValue; } else if (node.nodeType == 4) { // CDATA svgDoc = '<![CDATA[' + node.nodeValue + ']]>'; } else { // Element svgDoc = '<' + node.nodeName; if (node.attributes) { for (var i = 0; i < node.attributes.length; i++) { var attr = node.attributes.item(i); if (!($.trim(attr.nodeValue) == '' || attr.nodeValue.match(/^\[object/) || attr.nodeValue.match(/^function/))) { svgDoc += ' ' + (attr.namespaceURI == $.svg.xlinkNS ? 'xlink:' : '') + attr.nodeName + '="' + attr.nodeValue + '"'; } } } if (node.firstChild) { svgDoc += '>'; var child = node.firstChild; while (child) { svgDoc += this._toSVG(child); child = child.nextSibling; } svgDoc += '</' + node.nodeName + '>'; } else { svgDoc += '/>'; } } return svgDoc; } }); /* Helper to generate an SVG path. Obtain an instance from the SVGWrapper object. String calls together to generate the path and use its value: var path = root.createPath(); root.path(null, path.move(100, 100).line(300, 100).line(200, 300).close(), {fill: 'red'}); or root.path(null, path.move(100, 100).line([[300, 100], [200, 300]]).close(), {fill: 'red'}); */ function SVGPath() { this._path = ''; } $.extend(SVGPath.prototype, { /* Prepare to create a new path. @return (SVGPath) this path */ reset: function() { this._path = ''; return this; }, /* Move the pointer to a position. @param x (number) x-coordinate to move to or (number[][]) x-/y-coordinates to move to @param y (number) y-coordinate to move to (omitted if x is array) @param relative (boolean) true for coordinates relative to the current point, false for coordinates being absolute @return (SVGPath) this path */ move: function(x, y, relative) { relative = (isArray(x) ? y : relative); return this._coords((relative ? 'm' : 'M'), x, y); }, /* Draw a line to a position. @param x (number) x-coordinate to move to or (number[][]) x-/y-coordinates to move to @param y (number) y-coordinate to move to (omitted if x is array) @param relative (boolean) true for coordinates relative to the current point, false for coordinates being absolute @return (SVGPath) this path */ line: function(x, y, relative) { relative = (isArray(x) ? y : relative); return this._coords((relative ? 'l' : 'L'), x, y); }, /* Draw a horizontal line to a position. @param x (number) x-coordinate to draw to or (number[]) x-coordinates to draw to @param relative (boolean) true for coordinates relative to the current point, false for coordinates being absolute @return (SVGPath) this path */ horiz: function(x, relative) { this._path += (relative ? 'h' : 'H') + (isArray(x) ? x.join(' ') : x); return this; }, /* Draw a vertical line to a position. @param y (number) y-coordinate to draw to or (number[]) y-coordinates to draw to @param relative (boolean) true for coordinates relative to the current point, false for coordinates being absolute @return (SVGPath) this path */ vert: function(y, relative) { this._path += (relative ? 'v' : 'V') + (isArray(y) ? y.join(' ') : y); return this; }, /* Draw a cubic Bézier curve. @param x1 (number) x-coordinate of beginning control point or (number[][]) x-/y-coordinates of control and end points to draw to @param y1 (number) y-coordinate of beginning control point (omitted if x1 is array) @param x2 (number) x-coordinate of ending control point (omitted if x1 is array) @param y2 (number) y-coordinate of ending control point (omitted if x1 is array) @param x (number) x-coordinate of curve end (omitted if x1 is array) @param y (number) y-coordinate of curve end (omitted if x1 is array) @param relative (boolean) true for coordinates relative to the current point, false for coordinates being absolute @return (SVGPath) this path */ curveC: function(x1, y1, x2, y2, x, y, relative) { relative = (isArray(x1) ? y1 : relative); return this._coords((relative ? 'c' : 'C'), x1, y1, x2, y2, x, y); }, /* Continue a cubic Bézier curve. Starting control point is the reflection of the previous end control point. @param x2 (number) x-coordinate of ending control point or (number[][]) x-/y-coordinates of control and end points to draw to @param y2 (number) y-coordinate of ending control point (omitted if x2 is array) @param x (number) x-coordinate of curve end (omitted if x2 is array) @param y (number) y-coordinate of curve end (omitted if x2 is array) @param relative (boolean) true for coordinates relative to the current point, false for coordinates being absolute @return (SVGPath) this path */ smoothC: function(x2, y2, x, y, relative) { relative = (isArray(x2) ? y2 : relative); return this._coords((relative ? 's' : 'S'), x2, y2, x, y); }, /* Draw a quadratic Bézier curve. @param x1 (number) x-coordinate of control point or (number[][]) x-/y-coordinates of control and end points to draw to @param y1 (number) y-coordinate of control point (omitted if x1 is array) @param x (number) x-coordinate of curve end (omitted if x1 is array) @param y (number) y-coordinate of curve end (omitted if x1 is array) @param relative (boolean) true for coordinates relative to the current point, false for coordinates being absolute @return (SVGPath) this path */ curveQ: function(x1, y1, x, y, relative) { relative = (isArray(x1) ? y1 : relative); return this._coords((relative ? 'q' : 'Q'), x1, y1, x, y); }, /* Continue a quadratic Bézier curve. Control point is the reflection of the previous control point. @param x (number) x-coordinate of curve end or (number[][]) x-/y-coordinates of points to draw to @param y (number) y-coordinate of curve end (omitted if x is array) @param relative (boolean) true for coordinates relative to the current point, false for coordinates being absolute @return (SVGPath) this path */ smoothQ: function(x, y, relative) { relative = (isArray(x) ? y : relative); return this._coords((relative ? 't' : 'T'), x, y); }, /* Generate a path command with (a list of) coordinates. */ _coords: function(cmd, x1, y1, x2, y2, x3, y3) { if (isArray(x1)) { for (var i = 0; i < x1.length; i++) { var cs = x1[i]; this._path += (i == 0 ? cmd : ' ') + cs[0] + ',' + cs[1] + (cs.length < 4 ? '' : ' ' + cs[2] + ',' + cs[3] + (cs.length < 6 ? '': ' ' + cs[4] + ',' + cs[5])); } } else { this._path += cmd + x1 + ',' + y1 + (x2 == null ? '' : ' ' + x2 + ',' + y2 + (x3 == null ? '' : ' ' + x3 + ',' + y3)); } return this; }, /* Draw an arc to a position. @param rx (number) x-radius of arc or (number/boolean[][]) x-/y-coordinates and flags for points to draw to @param ry (number) y-radius of arc (omitted if rx is array) @param xRotate (number) x-axis rotation (degrees, clockwise) (omitted if rx is array) @param large (boolean) true to draw the large part of the arc, false to draw the small part (omitted if rx is array) @param clockwise (boolean) true to draw the clockwise arc, false to draw the anti-clockwise arc (omitted if rx is array) @param x (number) x-coordinate of arc end (omitted if rx is array) @param y (number) y-coordinate of arc end (omitted if rx is array) @param relative (boolean) true for coordinates relative to the current point, false for coordinates being absolute @return (SVGPath) this path */ arc: function(rx, ry, xRotate, large, clockwise, x, y, relative) { relative = (isArray(rx) ? ry : relative); this._path += (relative ? 'a' : 'A'); if (isArray(rx)) { for (var i = 0; i < rx.length; i++) { var cs = rx[i]; this._path += (i == 0 ? '' : ' ') + cs[0] + ',' + cs[1] + ' ' + cs[2] + ' ' + (cs[3] ? '1' : '0') + ',' + (cs[4] ? '1' : '0') + ' ' + cs[5] + ',' + cs[6]; } } else { this._path += rx + ',' + ry + ' ' + xRotate + ' ' + (large ? '1' : '0') + ',' + (clockwise ? '1' : '0') + ' ' + x + ',' + y; } return this; }, /* Close the current path. @return (SVGPath) this path */ close: function() { this._path += 'z'; return this; }, /* Return the string rendering of the specified path. @return (string) stringified path */ path: function() { return this._path; } }); SVGPath.prototype.moveTo = SVGPath.prototype.move; SVGPath.prototype.lineTo = SVGPath.prototype.line; SVGPath.prototype.horizTo = SVGPath.prototype.horiz; SVGPath.prototype.vertTo = SVGPath.prototype.vert; SVGPath.prototype.curveCTo = SVGPath.prototype.curveC; SVGPath.prototype.smoothCTo = SVGPath.prototype.smoothC; SVGPath.prototype.curveQTo = SVGPath.prototype.curveQ; SVGPath.prototype.smoothQTo = SVGPath.prototype.smoothQ; SVGPath.prototype.arcTo = SVGPath.prototype.arc; /* Helper to generate an SVG text object. Obtain an instance from the SVGWrapper object. String calls together to generate the text and use its value: var text = root.createText(); root.text(null, x, y, text.string('This is '). span('red', {fill: 'red'}).string('!'), {fill: 'blue'}); */ function SVGText() { this._parts = []; // The components of the text object } $.extend(SVGText.prototype, { /* Prepare to create a new text object. @return (SVGText) this text */ reset: function() { this._parts = []; return this; }, /* Add a straight string value. @param value (string) the actual text @return (SVGText) this text object */ string: function(value) { this._parts[this._parts.length] = ['text', value]; return this; }, /* Add a separate text span that has its own settings. @param value (string) the actual text @param settings (object) the settings for this text @return (SVGText) this text object */ span: function(value, settings) { this._parts[this._parts.length] = ['tspan', value, settings]; return this; }, /* Add a reference to a previously defined text string. @param id (string) the ID of the actual text @param settings (object) the settings for this text @return (SVGText) this text object */ ref: function(id, settings) { this._parts[this._parts.length] = ['tref', id, settings]; return this; }, /* Add text drawn along a path. @param id (string) the ID of the path @param value (string) the actual text @param settings (object) the settings for this text @return (SVGText) this text object */ path: function(id, value, settings) { this._parts[this._parts.length] = ['textpath', value, $.extend({href: id}, settings || {})]; return this; } }); /* Attach the SVG functionality to a jQuery selection. @param command (string) the command to run (optional, default 'attach') @param options (object) the new settings to use for these SVG instances @return jQuery (object) for chaining further calls */ $.fn.svg = function(options) { var otherArgs = Array.prototype.slice.call(arguments, 1); if (typeof options == 'string' && options == 'get') { return $.svg['_' + options + 'SVG'].apply($.svg, [this[0]].concat(otherArgs)); } return this.each(function() { if (typeof options == 'string') { $.svg['_' + options + 'SVG'].apply($.svg, [this].concat(otherArgs)); } else { $.svg._attachSVG(this, options || {}); } }); }; /* Determine whether an object is an array. */ function isArray(a) { return (a && a.constructor == Array); } // Singleton primary SVG interface $.svg = new SVGManager(); })(jQuery);
/* AngularJS v1.2.0-rc.3 (c) 2010-2012 Google, Inc. http://angularjs.org License: MIT */ (function(u,c,A){'use strict';function w(c,s,g,b,d){return{restrict:"ECA",terminal:!0,priority:400,transclude:"element",compile:function(l,m,y){return function(p,l,m){function k(){h&&(h.$destroy(),h=null);q&&(d.leave(q),q=null)}function x(){var a=c.current&&c.current.locals,e=a&&a.$template;if(e){var r=p.$new();y(r,function(v){k();v.html(e);d.enter(v,null,l);var f=g(v.contents()),n=c.current;h=n.scope=r;q=v;if(n.controller){a.$scope=h;var p=b(n.controller,a);n.controllerAs&&(h[n.controllerAs]=p); v.data("$ngControllerController",p);v.children().data("$ngControllerController",p)}f(h);h.$emit("$viewContentLoaded");h.$eval(t);s()})}else k()}var h,q,t=m.onload||"";p.$on("$routeChangeSuccess",x);x()}}}}u=c.module("ngRoute",["ng"]).provider("$route",function(){function u(b,d){return c.extend(new (c.extend(function(){},{prototype:b})),d)}function s(b,c){var l=c.caseInsensitiveMatch,m={originalPath:b,regexp:b},g=m.keys=[];b=b.replace(/([().])/g,"\\$1").replace(/(\/)?:(\w+)([\?|\*])?/g,function(b, c,d,k){b="?"===k?k:null;k="*"===k?k:null;g.push({name:d,optional:!!b});c=c||"";return""+(b?"":c)+"(?:"+(b?c:"")+(k&&"(.+?)"||"([^/]+)")+(b||"")+")"+(b||"")}).replace(/([\/$\*])/g,"\\$1");m.regexp=RegExp("^"+b+"$",l?"i":"");return m}var g={};this.when=function(b,d){g[b]=c.extend({reloadOnSearch:!0},d,b&&s(b,d));if(b){var l="/"==b[b.length-1]?b.substr(0,b.length-1):b+"/";g[l]=c.extend({redirectTo:b},s(l,d))}return this};this.otherwise=function(b){this.when(null,b);return this};this.$get=["$rootScope", "$location","$routeParams","$q","$injector","$http","$templateCache","$sce",function(b,d,l,m,s,p,w,z){function k(){var a=x(),e=t.current;if(a&&e&&a.$$route===e.$$route&&c.equals(a.pathParams,e.pathParams)&&!a.reloadOnSearch&&!q)e.params=a.params,c.copy(e.params,l),b.$broadcast("$routeUpdate",e);else if(a||e)q=!1,b.$broadcast("$routeChangeStart",a,e),(t.current=a)&&a.redirectTo&&(c.isString(a.redirectTo)?d.path(h(a.redirectTo,a.params)).search(a.params).replace():d.url(a.redirectTo(a.pathParams,d.path(), d.search())).replace()),m.when(a).then(function(){if(a){var b=c.extend({},a.resolve),e,f;c.forEach(b,function(a,e){b[e]=c.isString(a)?s.get(a):s.invoke(a)});c.isDefined(e=a.template)?c.isFunction(e)&&(e=e(a.params)):c.isDefined(f=a.templateUrl)&&(c.isFunction(f)&&(f=f(a.params)),f=z.getTrustedResourceUrl(f),c.isDefined(f)&&(a.loadedTemplateUrl=f,e=p.get(f,{cache:w}).then(function(a){return a.data})));c.isDefined(e)&&(b.$template=e);return m.all(b)}}).then(function(d){a==t.current&&(a&&(a.locals=d, c.copy(a.params,l)),b.$broadcast("$routeChangeSuccess",a,e))},function(c){a==t.current&&b.$broadcast("$routeChangeError",a,e,c)})}function x(){var a,b;c.forEach(g,function(r,k){var f;if(f=!b){var n=d.path();f=r.keys;var h={};if(r.regexp)if(n=r.regexp.exec(n)){for(var g=1,l=n.length;g<l;++g){var m=f[g-1],p="string"==typeof n[g]?decodeURIComponent(n[g]):n[g];m&&p&&(h[m.name]=p)}f=h}else f=null;else f=null;f=a=f}f&&(b=u(r,{params:c.extend({},d.search(),a),pathParams:a}),b.$$route=r)});return b||g[null]&& u(g[null],{params:{},pathParams:{}})}function h(a,b){var d=[];c.forEach((a||"").split(":"),function(a,c){if(0===c)d.push(a);else{var g=a.match(/(\w+)(.*)/),h=g[1];d.push(b[h]);d.push(g[2]||"");delete b[h]}});return d.join("")}var q=!1,t={routes:g,reload:function(){q=!0;b.$evalAsync(k)}};b.$on("$locationChangeSuccess",k);return t}]});u.provider("$routeParams",function(){this.$get=function(){return{}}});u.directive("ngView",w);w.$inject=["$route","$anchorScroll","$compile","$controller","$animate"]})(window, window.angular); //# sourceMappingURL=angular-route.min.js.map
require("../packages/meteor/flush-buffers-on-exit-in-windows.js");
export loadInfo from './loadInfo'; export loadAuth from './loadAuth'; export login from './login'; export logout from './logout'; export * as widget from './widget/index'; export * as survey from './survey/index';
/*! videojs-contrib-dash - v2.6.0 - 2016-12-12 * Copyright (c) 2016 Brightcove */ (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){ (function (global){ '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 _window = require('global/window'); var _window2 = _interopRequireDefault(_window); var _video = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null); var _video2 = _interopRequireDefault(_video); var _dashjs = (typeof window !== "undefined" ? window['dashjs'] : typeof global !== "undefined" ? global['dashjs'] : null); var _dashjs2 = _interopRequireDefault(_dashjs); 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 isArray = function isArray(a) { return Object.prototype.toString.call(a) === '[object Array]'; }; /** * videojs-contrib-dash * * Use Dash.js to playback DASH content inside of Video.js via a SourceHandler */ var Html5DashJS = function () { function Html5DashJS(source, tech, options) { var _this = this; _classCallCheck(this, Html5DashJS); // Get options from tech if not provided for backwards compatibility options = options || tech.options_; this.player = (0, _video2.default)(options.playerId); this.player.dash = this.player.dash || {}; this.tech_ = tech; this.el_ = tech.el(); this.elParent_ = this.el_.parentNode; // Do nothing if the src is falsey if (!source.src) { return; } // While the manifest is loading and Dash.js has not finished initializing // we must defer events and functions calls with isReady_ and then `triggerReady` // again later once everything is setup tech.isReady_ = false; if (Html5DashJS.updateSourceData) { _video2.default.log.warn('updateSourceData has been deprecated.' + ' Please switch to using hook("updatesource", callback).'); source = Html5DashJS.updateSourceData(source); } // call updatesource hooks Html5DashJS.hooks('updatesource').forEach(function (hook) { source = hook(source); }); var manifestSource = source.src; this.keySystemOptions_ = Html5DashJS.buildDashJSProtData(source.keySystemOptions); this.player.dash.mediaPlayer = _dashjs2.default.MediaPlayer().create(); this.mediaPlayer_ = this.player.dash.mediaPlayer; // Log MedaPlayer messages through video.js if (Html5DashJS.useVideoJSDebug) { _video2.default.log.warn('useVideoJSDebug has been deprecated.' + ' Please switch to using hook("beforeinitialize", callback).'); Html5DashJS.useVideoJSDebug(this.mediaPlayer_); } if (Html5DashJS.beforeInitialize) { _video2.default.log.warn('beforeInitialize has been deprecated.' + ' Please switch to using hook("beforeinitialize", callback).'); Html5DashJS.beforeInitialize(this.player, this.mediaPlayer_); } Html5DashJS.hooks('beforeinitialize').forEach(function (hook) { hook(_this.player, _this.mediaPlayer_); }); // Must run controller before these two lines or else there is no // element to bind to. this.mediaPlayer_.initialize(); // Apply any options that are set if (options.dash && options.dash.limitBitrateByPortal) { this.mediaPlayer_.setLimitBitrateByPortal(true); } else { this.mediaPlayer_.setLimitBitrateByPortal(false); } this.mediaPlayer_.attachView(this.el_); // Dash.js autoplays by default, video.js will handle autoplay this.mediaPlayer_.setAutoPlay(false); // Attach the source with any protection data this.mediaPlayer_.setProtectionData(this.keySystemOptions_); this.mediaPlayer_.attachSource(manifestSource); this.tech_.triggerReady(); } /* * Iterate over the `keySystemOptions` array and convert each object into * the type of object Dash.js expects in the `protData` argument. * * Also rename 'licenseUrl' property in the options to an 'serverURL' property */ _createClass(Html5DashJS, [{ key: 'dispose', value: function dispose() { if (this.mediaPlayer_) { this.mediaPlayer_.reset(); } if (this.player.dash) { delete this.player.dash; } } /** * Get a list of hooks for a specific lifecycle * * @param {string} type the lifecycle to get hooks from * @param {Function=|Function[]=} hook Optionally add a hook tothe lifecycle * @return {Array} an array of hooks or epty if none * @method hooks */ }], [{ key: 'buildDashJSProtData', value: function buildDashJSProtData(keySystemOptions) { var output = {}; if (!keySystemOptions || !isArray(keySystemOptions)) { return null; } for (var i = 0; i < keySystemOptions.length; i++) { var keySystem = keySystemOptions[i]; var options = _video2.default.mergeOptions({}, keySystem.options); if (options.licenseUrl) { options.serverURL = options.licenseUrl; delete options.licenseUrl; } output[keySystem.name] = options; } return output; } }, { key: 'hooks', value: function hooks(type, hook) { Html5DashJS.hooks_[type] = Html5DashJS.hooks_[type] || []; if (hook) { Html5DashJS.hooks_[type] = Html5DashJS.hooks_[type].concat(hook); } return Html5DashJS.hooks_[type]; } /** * Add a function hook to a specific dash lifecycle * * @param {string} type the lifecycle to hook the function to * @param {Function|Function[]} hook the function or array of functions to attach * @method hook */ }, { key: 'hook', value: function hook(type, _hook) { Html5DashJS.hooks(type, _hook); } /** * Remove a hook from a specific dash lifecycle. * * @param {string} type the lifecycle that the function hooked to * @param {Function} hook The hooked function to remove * @return {boolean} True if the function was removed, false if not found * @method removeHook */ }, { key: 'removeHook', value: function removeHook(type, hook) { var index = Html5DashJS.hooks(type).indexOf(hook); if (index === -1) { return false; } Html5DashJS.hooks_[type] = Html5DashJS.hooks_[type].slice(); Html5DashJS.hooks_[type].splice(index, 1); return true; } }]); return Html5DashJS; }(); Html5DashJS.hooks_ = {}; var canHandleKeySystems = function canHandleKeySystems(source) { if (Html5DashJS.updateSourceData) { source = Html5DashJS.updateSourceData(source); } var videoEl = document.createElement('video'); if (source.keySystemOptions && !(navigator.requestMediaKeySystemAccess || // IE11 Win 8.1 videoEl.msSetMediaKeys)) { return false; } return true; }; _video2.default.DashSourceHandler = function () { return { canHandleSource: function canHandleSource(source) { var dashExtRE = /\.mpd/i; if (!canHandleKeySystems(source)) { return ''; } if (_video2.default.DashSourceHandler.canPlayType(source.type)) { return 'probably'; } else if (dashExtRE.test(source.src)) { return 'maybe'; } else { return ''; } }, handleSource: function handleSource(source, tech, options) { return new Html5DashJS(source, tech, options); }, canPlayType: function canPlayType(type) { return _video2.default.DashSourceHandler.canPlayType(type); } }; }; _video2.default.DashSourceHandler.canPlayType = function (type) { var dashTypeRE = /^application\/dash\+xml/i; if (dashTypeRE.test(type)) { return 'probably'; } return ''; }; // Only add the SourceHandler if the browser supports MediaSourceExtensions if (!!_window2.default.MediaSource) { _video2.default.getComponent('Html5').registerSourceHandler(_video2.default.DashSourceHandler(), 0); } _video2.default.Html5DashJS = Html5DashJS; exports.default = Html5DashJS; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"global/window":2}],2:[function(require,module,exports){ (function (global){ if (typeof window !== "undefined") { module.exports = window; } else if (typeof global !== "undefined") { module.exports = global; } else if (typeof self !== "undefined"){ module.exports = self; } else { module.exports = {}; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}]},{},[1]);
/** * @fileoverview Comma spacing - validates spacing before and after comma * @author Vignesh Anand aka vegetableman. * @copyright 2014 Vignesh Anand. All rights reserved. */ "use strict"; var astUtils = require("../ast-utils"); //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = function(context) { var sourceCode = context.getSourceCode(); var tokensAndComments = sourceCode.tokensAndComments; var options = { before: context.options[0] ? !!context.options[0].before : false, after: context.options[0] ? !!context.options[0].after : true }; //-------------------------------------------------------------------------- // Helpers //-------------------------------------------------------------------------- // list of comma tokens to ignore for the check of leading whitespace var commaTokensToIgnore = []; /** * Determines if a given token is a comma operator. * @param {ASTNode} token The token to check. * @returns {boolean} True if the token is a comma, false if not. * @private */ function isComma(token) { return !!token && (token.type === "Punctuator") && (token.value === ","); } /** * Reports a spacing error with an appropriate message. * @param {ASTNode} node The binary expression node to report. * @param {string} dir Is the error "before" or "after" the comma? * @param {ASTNode} otherNode The node at the left or right of `node` * @returns {void} * @private */ function report(node, dir, otherNode) { context.report({ node: node, fix: function(fixer) { if (options[dir]) { if (dir === "before") { return fixer.insertTextBefore(node, " "); } else { return fixer.insertTextAfter(node, " "); } } else { var start, end; var newText = ""; if (dir === "before") { start = otherNode.range[1]; end = node.range[0]; } else { start = node.range[1]; end = otherNode.range[0]; } return fixer.replaceTextRange([start, end], newText); } }, message: options[dir] ? "A space is required " + dir + " ','." : "There should be no space " + dir + " ','." }); } /** * Validates the spacing around a comma token. * @param {Object} tokens - The tokens to be validated. * @param {Token} tokens.comma The token representing the comma. * @param {Token} [tokens.left] The last token before the comma. * @param {Token} [tokens.right] The first token after the comma. * @param {Token|ASTNode} reportItem The item to use when reporting an error. * @returns {void} * @private */ function validateCommaItemSpacing(tokens, reportItem) { if (tokens.left && astUtils.isTokenOnSameLine(tokens.left, tokens.comma) && (options.before !== sourceCode.isSpaceBetweenTokens(tokens.left, tokens.comma)) ) { report(reportItem, "before", tokens.left); } if (tokens.right && !options.after && tokens.right.type === "Line") { return; } if (tokens.right && astUtils.isTokenOnSameLine(tokens.comma, tokens.right) && (options.after !== sourceCode.isSpaceBetweenTokens(tokens.comma, tokens.right)) ) { report(reportItem, "after", tokens.right); } } /** * Adds null elements of the given ArrayExpression or ArrayPattern node to the ignore list. * @param {ASTNode} node An ArrayExpression or ArrayPattern node. * @returns {void} */ function addNullElementsToIgnoreList(node) { var previousToken = context.getFirstToken(node); node.elements.forEach(function(element) { var token; if (element === null) { token = context.getTokenAfter(previousToken); if (isComma(token)) { commaTokensToIgnore.push(token); } } else { token = context.getTokenAfter(element); } previousToken = token; }); } //-------------------------------------------------------------------------- // Public //-------------------------------------------------------------------------- return { "Program:exit": function() { var previousToken, nextToken; tokensAndComments.forEach(function(token, i) { if (!isComma(token)) { return; } if (token && token.type === "JSXText") { return; } previousToken = tokensAndComments[i - 1]; nextToken = tokensAndComments[i + 1]; validateCommaItemSpacing({ comma: token, left: isComma(previousToken) || commaTokensToIgnore.indexOf(token) > -1 ? null : previousToken, right: isComma(nextToken) ? null : nextToken }, token); }); }, "ArrayExpression": addNullElementsToIgnoreList, "ArrayPattern": addNullElementsToIgnoreList }; }; module.exports.schema = [ { "type": "object", "properties": { "before": { "type": "boolean" }, "after": { "type": "boolean" } }, "additionalProperties": false } ];
var cookies = function (data, opt) { function defaults (obj, defs) { obj = obj || {}; for (var key in defs) { if (obj[key] === undefined) { obj[key] = defs[key]; } } return obj; } defaults(cookies, { expires: 365 * 24 * 3600, path: '/', secure: window.location.protocol === 'https:', // Advanced nulltoremove: true, autojson: true, autoencode: true, encode: function (val) { return encodeURIComponent(val); }, decode: function (val) { return decodeURIComponent(val); }, error: function (error, data, opt) { throw new Error(error); }, fallback: false }); opt = defaults(opt, cookies); function expires (time) { var expires = time; if (!(expires instanceof Date)) { expires = new Date(); expires.setTime(expires.getTime() + (time * 1000)); } return expires.toUTCString(); } if (typeof data === 'string') { var value = document.cookie.split(/;\s*/) .map(opt.autoencode ? opt.decode : function (d) { return d; }) .map(function (part) { return part.split('='); }) .reduce(function (parts, part) { parts[part[0]] = part.splice(1).join('='); console.log(parts); return parts; }, {})[data]; if (!opt.autojson) return value; var real; try { real = JSON.parse(value); } catch (e) { real = value; } if (typeof real === 'undefined' && opt.fallback) real = opt.fallback(data, opt); return real; } // Set each of the cookies for (var key in data) { var val = data[key]; var expired = typeof val === 'undefined' || (opt.nulltoremove && val === null); var str = opt.autojson ? JSON.stringify(val) : val; var encoded = opt.autoencode ? opt.encode(str) : str; if (expired) encoded = ''; var res = opt.encode(key) + '=' + encoded + (opt.expires ? (';expires=' + expires(expired ? -10000 : opt.expires)) : '') + ';path=' + opt.path + (opt.domain ? (';domain=' + opt.domain) : '') + (opt.secure ? ';secure' : ''); if (opt.test) opt.test(res); document.cookie = res; var read = (cookies(opt.encode(key)) || ''); if (val && !expired && opt.expires > 0 && JSON.stringify(read) !== JSON.stringify(val)) { if (navigator.cookieEnabled) { if (opt.fallback) { opt.fallback(data, opt); } else { opt.error('Cookie too large at ' + val.length + ' characters'); } } else { opt.error('Cookies not enabled'); } } } return cookies; }; (function webpackUniversalModuleDefinition (root) { if (typeof exports === 'object' && typeof module === 'object') { module.exports = cookies; } else if (typeof define === 'function' && define.amd) { define('cookies', [], cookies); } else if (typeof exports === 'object') { exports['cookies'] = cookies; } else { root['cookies'] = cookies; } })(this);
import createChainableTypeChecker from 'react-prop-types/lib/utils/createChainableTypeChecker'; import ValidComponentChildren from './ValidComponentChildren'; export function requiredRoles() { for (var _len = arguments.length, roles = Array(_len), _key = 0; _key < _len; _key++) { roles[_key] = arguments[_key]; } return createChainableTypeChecker(function (props, propName, component) { var missing = void 0; roles.every(function (role) { if (!ValidComponentChildren.some(props.children, function (child) { return child.props.bsRole === role; })) { missing = role; return false; } return true; }); if (missing) { return new Error('(children) ' + component + ' - Missing a required child with bsRole: ' + (missing + '. ' + component + ' must have at least one child of each of ') + ('the following bsRoles: ' + roles.join(', '))); } return null; }); } export function exclusiveRoles() { for (var _len2 = arguments.length, roles = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { roles[_key2] = arguments[_key2]; } return createChainableTypeChecker(function (props, propName, component) { var duplicate = void 0; roles.every(function (role) { var childrenWithRole = ValidComponentChildren.filter(props.children, function (child) { return child.props.bsRole === role; }); if (childrenWithRole.length > 1) { duplicate = role; return false; } return true; }); if (duplicate) { return new Error('(children) ' + component + ' - Duplicate children detected of bsRole: ' + (duplicate + '. Only one child each allowed with the following ') + ('bsRoles: ' + roles.join(', '))); } return null; }); }
/* * jQuery MiniColors: A tiny color picker built on jQuery * * Copyright Cory LaViska for A Beautiful Site, LLC. (http://www.abeautifulsite.net/) * * Dual-licensed under the MIT and GPL Version 2 licenses * */ if(jQuery) (function($) { // Yay, MiniColors! $.minicolors = { // Default settings defaultSettings: { animationSpeed: 100, animationEasing: 'swing', classes: '', control: 'hue', defaultValue: '', hideSpeed: 100, inline: false, letterCase: 'lowercase', opacity: false, position: 'default', showSpeed: 100, styles: '', swatchPosition: 'left', textfield: true, change: null, hide: null, show: null } }; // Public methods $.extend($.fn, { minicolors: function(method, data) { switch(method) { // Destroy the control case 'destroy': $(this).each( function() { destroy($(this)); }); return $(this); // Get/set opacity case 'opacity': if( data === undefined ) { // Getter return $(this).attr('data-opacity'); } else { // Setter $(this).each( function() { refresh($(this).attr('data-opacity', data)); }); return $(this); } // Get an RGB(A) object based on the current color/opacity case 'rgbObject': return rgbObject($(this), method === 'rgbaObject'); // Get an RGB(A) string based on the current color/opacity case 'rgbString': case 'rgbaString': return rgbString($(this), method === 'rgbaString') // Get/set settings on the fly case 'settings': if( data === undefined ) { return $(this).data('minicolors-settings'); } else { // Setter $(this).each( function() { var settings = $(this).data('minicolors-settings') || {}; destroy($(this)); $(this).minicolors($.extend(true, settings, data)); }); return $(this); } // Get/set the hex color value case 'value': if( data === undefined ) { // Getter return $(this).val(); } else { // Setter $(this).each( function() { refresh($(this).val(data)); }); return $(this); } // Initializes the control case 'create': default: if( method !== 'create' ) data = method; $(this).each( function() { init($(this), data); }); return $(this); } } }); // Initialize input elements function init(input, settings) { var minicolors = $('<span class="minicolors" />'), defaultSettings = $.minicolors.defaultSettings; // Do nothing if already initialized if( input.data('minicolors-initialized') ) return; // Handle settings settings = $.extend(true, {}, defaultSettings, settings); // The wrapper minicolors .attr('class', minicolors.attr('class') + ' ' + settings.classes) .attr('style', settings.styles) .toggleClass('minicolors-swatch-left', settings.swatchPosition === 'left') .toggleClass('minicolors-with-opacity', settings.opacity); // Custom positioning if( settings.position !== undefined ) { $.each(settings.position.split(' '), function() { minicolors.addClass('minicolors-position-' + this); }); } // The input input .addClass('minicolors-input') .data('minicolors-initialized', true) .data('minicolors-settings', settings) .prop('size', 7) .prop('maxlength', 7) .wrap(minicolors) .after( '<span class="minicolors-panel minicolors-slider-' + settings.control + '">' + '<span class="minicolors-slider">' + '<span class="minicolors-picker"></span>' + '</span>' + '<span class="minicolors-opacity-slider">' + '<span class="minicolors-picker"></span>' + '</span>' + '<span class="minicolors-grid">' + '<span class="minicolors-grid-inner"></span>' + '<span class="minicolors-picker"><span></span></span>' + '</span>' + '</span>' ); // Prevent text selection in IE input.parent().find('.minicolors-panel').on('selectstart', function() { return false; }).end(); // Detect swatch position if( settings.swatchPosition === 'left' ) { // Left input.before('<span class="minicolors-swatch"><span></span></span>'); } else { // Right input.after('<span class="minicolors-swatch"><span></span></span>'); } // Disable textfield if( !settings.textfield ) input.addClass('minicolors-hidden'); // Inline controls if( settings.inline ) input.parent().addClass('minicolors-inline'); updateFromInput(input); } // Returns the input back to its original state function destroy(input) { var minicolors = input.parent(); // Revert the input element input .removeData('minicolors-initialized') .removeData('minicolors-settings') .removeProp('size') .removeProp('maxlength') .removeClass('minicolors-input'); // Remove the wrap and destroy whatever remains minicolors.before(input).remove(); } // Refresh the specified control function refresh(input) { updateFromInput(input); } // Shows the specified dropdown panel function show(input) { var minicolors = input.parent(), panel = minicolors.find('.minicolors-panel'), settings = input.data('minicolors-settings'); // Do nothing if uninitialized, disabled, or already open if( !input.data('minicolors-initialized') || input.prop('disabled') || minicolors.hasClass('minicolors-focus') ) return; hide(); minicolors.addClass('minicolors-focus'); panel .stop(true, true) .fadeIn(settings.showSpeed, function() { if( settings.show ) settings.show.call(input); }); } // Hides all dropdown panels function hide() { $('.minicolors-input').each( function() { var input = $(this), settings = input.data('minicolors-settings'), minicolors = input.parent(); // Don't hide inline controls if( settings.inline ) return; minicolors.find('.minicolors-panel').fadeOut(settings.hideSpeed, function() { if(minicolors.hasClass('minicolors-focus')) { if( settings.hide ) settings.hide.call(input); } minicolors.removeClass('minicolors-focus'); }); }); } // Moves the selected picker function move(target, event, animate) { var input = target.parents('.minicolors').find('INPUT'), settings = input.data('minicolors-settings'), picker = target.find('[class$=-picker]'), offsetX = target.offset().left, offsetY = target.offset().top, x = Math.round(event.pageX - offsetX), y = Math.round(event.pageY - offsetY), duration = animate ? settings.animationSpeed : 0, wx, wy, r, phi; // Touch support if( event.originalEvent.changedTouches ) { x = event.originalEvent.changedTouches[0].pageX - offsetX; y = event.originalEvent.changedTouches[0].pageY - offsetY; } // Constrain picker to its container if( x < 0 ) x = 0; if( y < 0 ) y = 0; if( x > target.width() ) x = target.width(); if( y > target.height() ) y = target.height(); // Constrain color wheel values to the wheel if( target.parent().is('.minicolors-slider-wheel') && picker.parent().is('.minicolors-grid') ) { wx = 75 - x; wy = 75 - y; r = Math.sqrt(wx * wx + wy * wy); phi = Math.atan2(wy, wx); if( phi < 0 ) phi += Math.PI * 2; if( r > 75 ) { r = 75; x = 75 - (75 * Math.cos(phi)); y = 75 - (75 * Math.sin(phi)); } x = Math.round(x); y = Math.round(y); } // Move the picker if( target.is('.minicolors-grid') ) { picker .stop(true) .animate({ top: y + 'px', left: x + 'px' }, duration, settings.animationEasing, function() { updateFromControl(input); }); } else { picker .stop(true) .animate({ top: y + 'px' }, duration, settings.animationEasing, function() { updateFromControl(input); }); } } // Sets the input based on the color picker values function updateFromControl(input) { function getCoords(picker, container) { var left, top; if( !picker.length || !container ) return null; left = picker.offset().left; top = picker.offset().top; return { x: left - container.offset().left + (picker.outerWidth() / 2), y: top - container.offset().top + (picker.outerHeight() / 2) }; } var hue, saturation, brightness, opacity, rgb, hex, x, y, r, phi, // Helpful references minicolors = input.parent(), settings = input.data('minicolors-settings'), panel = minicolors.find('.minicolors-panel'), swatch = minicolors.find('.minicolors-swatch'), // Panel objects grid = minicolors.find('.minicolors-grid'), slider = minicolors.find('.minicolors-slider'), opacitySlider = minicolors.find('.minicolors-opacity-slider'), // Picker objects gridPicker = grid.find('[class$=-picker]'), sliderPicker = slider.find('[class$=-picker]'), opacityPicker = opacitySlider.find('[class$=-picker]'), // Picker positions gridPos = getCoords(gridPicker, grid), sliderPos = getCoords(sliderPicker, slider), opacityPos = getCoords(opacityPicker, opacitySlider); // Determine HSB values switch(settings.control) { case 'wheel': // Calculate hue, saturation, and brightness x = (grid.width() / 2) - gridPos.x; y = (grid.height() / 2) - gridPos.y; r = Math.sqrt(x * x + y * y); phi = Math.atan2(y, x); if( phi < 0 ) phi += Math.PI * 2; if( r > 75 ) { r = 75; gridPos.x = 69 - (75 * Math.cos(phi)); gridPos.y = 69 - (75 * Math.sin(phi)); } saturation = keepWithin(r / 0.75, 0, 100); hue = keepWithin(phi * 180 / Math.PI, 0, 360); brightness = keepWithin(100 - Math.floor(sliderPos.y * (100 / slider.height())), 0, 100); hex = hsb2hex({ h: hue, s: saturation, b: brightness }); // Update UI slider.css('backgroundColor', hsb2hex({ h: hue, s: saturation, b: 100 })); break; case 'saturation': // Calculate hue, saturation, and brightness hue = keepWithin(parseInt(gridPos.x * (360 / grid.width())), 0, 360); saturation = keepWithin(100 - Math.floor(sliderPos.y * (100 / slider.height())), 0, 100); brightness = keepWithin(100 - Math.floor(gridPos.y * (100 / grid.height())), 0, 100); hex = hsb2hex({ h: hue, s: saturation, b: brightness }); // Update UI slider.css('backgroundColor', hsb2hex({ h: hue, s: 100, b: brightness })); minicolors.find('.minicolors-grid-inner').css('opacity', saturation / 100); break; case 'brightness': // Calculate hue, saturation, and brightness hue = keepWithin(parseInt(gridPos.x * (360 / grid.width())), 0, 360); saturation = keepWithin(100 - Math.floor(gridPos.y * (100 / grid.height())), 0, 100); brightness = keepWithin(100 - Math.floor(sliderPos.y * (100 / slider.height())), 0, 100); hex = hsb2hex({ h: hue, s: saturation, b: brightness }); // Update UI slider.css('backgroundColor', hsb2hex({ h: hue, s: saturation, b: 100 })); minicolors.find('.minicolors-grid-inner').css('opacity', 1 - (brightness / 100)); break; default: // Calculate hue, saturation, and brightness hue = keepWithin(360 - parseInt(sliderPos.y * (360 / slider.height())), 0, 360); saturation = keepWithin(Math.floor(gridPos.x * (100 / grid.width())), 0, 100); brightness = keepWithin(100 - Math.floor(gridPos.y * (100 / grid.height())), 0, 100); hex = hsb2hex({ h: hue, s: saturation, b: brightness }); // Update UI grid.css('backgroundColor', hsb2hex({ h: hue, s: 100, b: 100 })); break; } // Determine opacity if( settings.opacity ) { opacity = parseFloat(1 - (opacityPos.y / opacitySlider.height())).toFixed(2); } else { opacity = 1; } // Update input control input.val(hex); if( settings.opacity ) input.attr('data-opacity', opacity); // Set swatch color swatch.find('SPAN').css({ backgroundColor: hex, opacity: opacity }); // Fire change event if( hex + opacity !== input.data('minicolors-lastChange') ) { input.data('minicolors-lastChange', hex + opacity); if( settings.change ) settings.change.call(input, hex, opacity); } } // Sets the color picker values from the input function updateFromInput(input, preserveInputValue) { var hex, hsb, opacity, x, y, r, phi, // Helpful references minicolors = input.parent(), settings = input.data('minicolors-settings'), swatch = minicolors.find('.minicolors-swatch'), // Panel objects grid = minicolors.find('.minicolors-grid'), slider = minicolors.find('.minicolors-slider'), opacitySlider = minicolors.find('.minicolors-opacity-slider'), // Picker objects gridPicker = grid.find('[class$=-picker]'), sliderPicker = slider.find('[class$=-picker]'), opacityPicker = opacitySlider.find('[class$=-picker]'); // Determine hex/HSB values hex = convertCase(parseHex(input.val(), true)); if( !hex ) hex = convertCase(parseHex(settings.defaultValue, true)); hsb = hex2hsb(hex); // Update input value if( !preserveInputValue ) input.val(hex); // Determine opacity value if( settings.opacity ) { opacity = input.attr('data-opacity') === '' ? 1 : keepWithin(parseFloat(input.attr('data-opacity')).toFixed(2), 0, 1); input.attr('data-opacity', opacity); swatch.find('SPAN').css('opacity', opacity); // Set opacity picker position y = keepWithin(opacitySlider.height() - (opacitySlider.height() * opacity), 0, opacitySlider.height()); opacityPicker.css('top', y + 'px'); } // Update swatch swatch.find('SPAN').css('backgroundColor', hex); // Determine picker locations switch(settings.control) { case 'wheel': // Set grid position r = keepWithin(Math.ceil(hsb.s * 0.75), 0, grid.height() / 2); phi = hsb.h * Math.PI / 180; x = keepWithin(75 - Math.cos(phi) * r, 0, grid.width()); y = keepWithin(75 - Math.sin(phi) * r, 0, grid.height()); gridPicker.css({ top: y + 'px', left: x + 'px' }); // Set slider position y = 150 - (hsb.b / (100 / grid.height())); if( hex === '' ) y = 0; sliderPicker.css('top', y + 'px'); // Update panel color slider.css('backgroundColor', hsb2hex({ h: hsb.h, s: hsb.s, b: 100 })); break; case 'saturation': // Set grid position x = keepWithin((5 * hsb.h) / 12, 0, 150); y = keepWithin(grid.height() - Math.ceil(hsb.b / (100 / grid.height())), 0, grid.height()); gridPicker.css({ top: y + 'px', left: x + 'px' }); // Set slider position y = keepWithin(slider.height() - (hsb.s * (slider.height() / 100)), 0, slider.height()); sliderPicker.css('top', y + 'px'); // Update UI slider.css('backgroundColor', hsb2hex({ h: hsb.h, s: 100, b: hsb.b })); minicolors.find('.minicolors-grid-inner').css('opacity', hsb.s / 100); break; case 'brightness': // Set grid position x = keepWithin((5 * hsb.h) / 12, 0, 150); y = keepWithin(grid.height() - Math.ceil(hsb.s / (100 / grid.height())), 0, grid.height()); gridPicker.css({ top: y + 'px', left: x + 'px' }); // Set slider position y = keepWithin(slider.height() - (hsb.b * (slider.height() / 100)), 0, slider.height()); sliderPicker.css('top', y + 'px'); // Update UI slider.css('backgroundColor', hsb2hex({ h: hsb.h, s: hsb.s, b: 100 })); minicolors.find('.minicolors-grid-inner').css('opacity', 1 - (hsb.b / 100)); break; default: // Set grid position x = keepWithin(Math.ceil(hsb.s / (100 / grid.width())), 0, grid.width()); y = keepWithin(grid.height() - Math.ceil(hsb.b / (100 / grid.height())), 0, grid.height()); gridPicker.css({ top: y + 'px', left: x + 'px' }); // Set slider position y = keepWithin(slider.height() - (hsb.h / (360 / slider.height())), 0, slider.height()); sliderPicker.css('top', y + 'px'); // Update panel color grid.css('backgroundColor', hsb2hex({ h: hsb.h, s: 100, b: 100 })); break; } } // Generates an RGB(A) object based on the input's value function rgbObject(input) { var hex = parseHex($(input).val(), true), rgb = hex2rgb(hex), opacity = $(input).attr('data-opacity'); if( !rgb ) return null; if( opacity !== undefined ) $.extend(rgb, { a: parseFloat(opacity) }); return rgb; } // Genearates an RGB(A) string based on the input's value function rgbString(input, alpha) { var hex = parseHex($(input).val(), true), rgb = hex2rgb(hex), opacity = $(input).attr('data-opacity'); if( !rgb ) return null; if( opacity === undefined ) opacity = 1; if( alpha ) { return 'rgba(' + rgb.r + ', ' + rgb.g + ', ' + rgb.b + ', ' + parseFloat(opacity) + ')'; } else { return 'rgb(' + rgb.r + ', ' + rgb.g + ', ' + rgb.b + ')'; } } // Converts to the letter case specified in settings function convertCase(string, letterCase) { return letterCase === 'uppercase' ? string.toUpperCase() : string.toLowerCase(); } // Parses a string and returns a valid hex string when possible function parseHex(string, expand) { string = string.replace(/[^A-F0-9]/ig, ''); if( string.length !== 3 && string.length !== 6 ) return ''; if( string.length === 3 && expand ) { string = string[0] + string[0] + string[1] + string[1] + string[2] + string[2]; } return '#' + string; } // Keeps value within min and max function keepWithin(value, min, max) { if( value < min ) value = min; if( value > max ) value = max; return value; } // Converts an HSB object to an RGB object function hsb2rgb(hsb) { var rgb = {}; var h = Math.round(hsb.h); var s = Math.round(hsb.s * 255 / 100); var v = Math.round(hsb.b * 255 / 100); if(s === 0) { rgb.r = rgb.g = rgb.b = v; } else { var t1 = v; var t2 = (255 - s) * v / 255; var t3 = (t1 - t2) * (h % 60) / 60; if( h === 360 ) h = 0; if( h < 60 ) { rgb.r = t1; rgb.b = t2; rgb.g = t2 + t3; } else if( h < 120 ) {rgb.g = t1; rgb.b = t2; rgb.r = t1 - t3; } else if( h < 180 ) {rgb.g = t1; rgb.r = t2; rgb.b = t2 + t3; } else if( h < 240 ) {rgb.b = t1; rgb.r = t2; rgb.g = t1 - t3; } else if( h < 300 ) {rgb.b = t1; rgb.g = t2; rgb.r = t2 + t3; } else if( h < 360 ) {rgb.r = t1; rgb.g = t2; rgb.b = t1 - t3; } else { rgb.r = 0; rgb.g = 0; rgb.b = 0; } } return { r: Math.round(rgb.r), g: Math.round(rgb.g), b: Math.round(rgb.b) }; } // Converts an RGB object to a hex string function rgb2hex(rgb) { var hex = [ rgb.r.toString(16), rgb.g.toString(16), rgb.b.toString(16) ]; $.each(hex, function(nr, val) { if (val.length === 1) hex[nr] = '0' + val; }); return '#' + hex.join(''); } // Converts an HSB object to a hex string function hsb2hex(hsb) { return rgb2hex(hsb2rgb(hsb)); } // Converts a hex string to an HSB object function hex2hsb(hex) { var hsb = rgb2hsb(hex2rgb(hex)); if( hsb.s === 0 ) hsb.h = 360; return hsb; } // Converts an RGB object to an HSB object function rgb2hsb(rgb) { var hsb = { h: 0, s: 0, b: 0 }; var min = Math.min(rgb.r, rgb.g, rgb.b); var max = Math.max(rgb.r, rgb.g, rgb.b); var delta = max - min; hsb.b = max; hsb.s = max !== 0 ? 255 * delta / max : 0; if( hsb.s !== 0 ) { if( rgb.r === max ) { hsb.h = (rgb.g - rgb.b) / delta; } else if( rgb.g === max ) { hsb.h = 2 + (rgb.b - rgb.r) / delta; } else { hsb.h = 4 + (rgb.r - rgb.g) / delta; } } else { hsb.h = -1; } hsb.h *= 60; if( hsb.h < 0 ) { hsb.h += 360; } hsb.s *= 100/255; hsb.b *= 100/255; return hsb; } // Converts a hex string to an RGB object function hex2rgb(hex) { hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16); return { r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF) }; } // Handle events $(document) // Hide on clicks outside of the control .on('mousedown.minicolors touchstart.minicolors', function(event) { if( !$(event.target).parents().add(event.target).hasClass('minicolors') ) { hide(); } }) // Start moving .on('mousedown.minicolors touchstart.minicolors', '.minicolors-grid, .minicolors-slider, .minicolors-opacity-slider', function(event) { var target = $(this); event.preventDefault(); $(document).data('minicolors-target', target); move(target, event, true); }) // Move pickers .on('mousemove.minicolors touchmove.minicolors', function(event) { var target = $(document).data('minicolors-target'); if( target ) move(target, event); }) // Stop moving .on('mouseup.minicolors touchend.minicolors', function() { $(this).removeData('minicolors-target'); }) // Toggle panel when swatch is clicked .on('mousedown.minicolors touchstart.minicolors', '.minicolors-swatch', function(event) { var input = $(this).parent().find('INPUT'), minicolors = input.parent(); if( minicolors.hasClass('minicolors-focus') ) { hide(input); } else { show(input); } }) // Show on focus .on('focus.minicolors', '.minicolors-input', function(event) { var input = $(this); if( !input.data('minicolors-initialized') ) return; show(input); }) // Fix hex and hide on blur .on('blur.minicolors', '.minicolors-input', function(event) { var input = $(this), settings = input.data('minicolors-settings'); if( !input.data('minicolors-initialized') ) return; // Parse Hex input.val(parseHex(input.val(), true)); // Is it blank? if( input.val() === '' ) input.val(parseHex(settings.defaultValue, true)); // Adjust case input.val( convertCase(input.val(), settings.letterCase) ); hide(input); }) // Handle keypresses .on('keydown.minicolors', '.minicolors-input', function(event) { var input = $(this); if( !input.data('minicolors-initialized') ) return; switch(event.keyCode) { case 9: // tab hide(); break; case 27: // esc hide(); input.blur(); break; } }) // Update on keyup .on('keyup.minicolors', '.minicolors-input', function(event) { var input = $(this); if( !input.data('minicolors-initialized') ) return; updateFromInput(input, true); }) // Update on paste .on('paste.minicolors', '.minicolors-input', function(event) { var input = $(this); if( !input.data('minicolors-initialized') ) return; setTimeout( function() { updateFromInput(input, true); }, 1); }); })(jQuery);
"use strict"; var numeric = (typeof exports === "undefined")?(function numeric() {}):(exports); if(typeof global !== "undefined") { global.numeric = numeric; } numeric.version = "1.2.4"; // 1. Utility functions numeric.bench = function bench (f,interval) { var t1,t2,n,i; if(typeof interval === "undefined") { interval = 15; } n = 0.5; t1 = new Date(); while(1) { n*=2; for(i=n;i>3;i-=4) { f(); f(); f(); f(); } while(i>0) { f(); i--; } t2 = new Date(); if(t2-t1 > interval) break; } for(i=n;i>3;i-=4) { f(); f(); f(); f(); } while(i>0) { f(); i--; } t2 = new Date(); return 1000*(3*n-1)/(t2-t1); } numeric.Function = Function; numeric.precision = 4; numeric.largeArray = 50; numeric.prettyPrint = function prettyPrint(x) { function fmtnum(x) { if(x === 0) { return '0'; } if(isNaN(x)) { return 'NaN'; } if(x<0) { return '-'+fmtnum(-x); } if(isFinite(x)) { var scale = Math.floor(Math.log(x) / Math.log(10)); var normalized = x / Math.pow(10,scale); var basic = normalized.toPrecision(numeric.precision); if(parseFloat(basic) === 10) { scale++; normalized = 1; basic = normalized.toPrecision(numeric.precision); } return parseFloat(basic).toString()+'e'+scale.toString(); } return 'Infinity'; } var ret = []; function foo(x) { var k; if(typeof x === "undefined") { ret.push(Array(numeric.precision+8).join(' ')); return false; } if(typeof x === "string") { ret.push('"'+x+'"'); return false; } if(typeof x === "boolean") { ret.push(x.toString()); return false; } if(typeof x === "number") { var a = fmtnum(x); var b = x.toPrecision(numeric.precision); var c = parseFloat(x.toString()).toString(); var d = [a,b,c,parseFloat(b).toString(),parseFloat(c).toString()]; for(k=1;k<d.length;k++) { if(d[k].length < a.length) a = d[k]; } ret.push(Array(numeric.precision+8-a.length).join(' ')+a); return false; } if(x === null) { ret.push("null"); return false; } if(typeof x === "function") { ret.push(x.toString()); var flag = false; for(k in x) { if(x.hasOwnProperty(k)) { if(flag) ret.push(',\n'); else ret.push('\n{'); flag = true; ret.push(k); ret.push(': \n'); foo(x[k]); } } if(flag) ret.push('}\n'); return true; } if(x instanceof Array) { if(x.length > numeric.largeArray) { ret.push('...Large Array...'); return true; } var flag = false; ret.push('['); for(k=0;k<x.length;k++) { if(k>0) { ret.push(','); if(flag) ret.push('\n '); } flag = foo(x[k]); } ret.push(']'); return true; } ret.push('{'); var flag = false; for(k in x) { if(x.hasOwnProperty(k)) { if(flag) ret.push(',\n'); flag = true; ret.push(k); ret.push(': \n'); foo(x[k]); } } ret.push('}'); return true; } foo(x); return ret.join(''); } numeric.parseDate = function parseDate(d) { function foo(d) { if(typeof d === 'string') { return Date.parse(d.replace(/-/g,'/')); } if(!(d instanceof Array)) { throw new Error("parseDate: parameter must be arrays of strings"); } var ret = [],k; for(k=0;k<d.length;k++) { ret[k] = foo(d[k]); } return ret; } return foo(d); } numeric.parseFloat = function parseFloat_(d) { function foo(d) { if(typeof d === 'string') { return parseFloat(d); } if(!(d instanceof Array)) { throw new Error("parseFloat: parameter must be arrays of strings"); } var ret = [],k; for(k=0;k<d.length;k++) { ret[k] = foo(d[k]); } return ret; } return foo(d); } numeric.parseCSV = function parseCSV(t) { var foo = t.split('\n'); var j,k; var ret = []; var pat = /(([^'",]*)|('[^']*')|("[^"]*")),/g; var patnum = /^\s*(([+-]?[0-9]+(\.[0-9]*)?(e[+-]?[0-9]+)?)|([+-]?[0-9]*(\.[0-9]+)?(e[+-]?[0-9]+)?))\s*$/; var stripper = function(n) { return n.substr(0,n.length-1); } var count = 0; for(k=0;k<foo.length;k++) { var bar = (foo[k]+",").match(pat),baz; if(bar.length>0) { ret[count] = []; for(j=0;j<bar.length;j++) { baz = stripper(bar[j]); if(patnum.test(baz)) { ret[count][j] = parseFloat(baz); } else ret[count][j] = baz; } count++; } } return ret; } numeric.toCSV = function toCSV(A) { var s = numeric.dim(A); var i,j,m,n,row,ret; m = s[0]; n = s[1]; ret = []; for(i=0;i<m;i++) { row = []; for(j=0;j<m;j++) { row[j] = A[i][j].toString(); } ret[i] = row.join(', '); } return ret.join('\n')+'\n'; } numeric.getURL = function getURL(url) { var client = new XMLHttpRequest(); client.open("GET",url,false); client.send(); return client; } numeric.imageURL = function imageURL(img) { function base64(A) { var n = A.length, i,x,y,z,p,q,r,s; var key = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var ret = ""; for(i=0;i<n;i+=3) { x = A[i]; y = A[i+1]; z = A[i+2]; p = x >> 2; q = ((x & 3) << 4) + (y >> 4); r = ((y & 15) << 2) + (z >> 6); s = z & 63; if(i+1>=n) { r = s = 64; } else if(i+2>=n) { s = 64; } ret += key.charAt(p) + key.charAt(q) + key.charAt(r) + key.charAt(s); } return ret; } function crc32Array (a,from,to) { if(typeof from === "undefined") { from = 0; } if(typeof to === "undefined") { to = a.length; } var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; var crc = -1, y = 0, n = a.length,i; for (i = from; i < to; i++) { y = (crc ^ a[i]) & 0xFF; crc = (crc >>> 8) ^ table[y]; } return crc ^ (-1); } var h = img[0].length, w = img[0][0].length, s1, s2, next,k,length,a,b,i,j,adler32,crc32; var stream = [ 137, 80, 78, 71, 13, 10, 26, 10, // 0: PNG signature 0,0,0,13, // 8: IHDR Chunk length 73, 72, 68, 82, // 12: "IHDR" (w >> 24) & 255, (w >> 16) & 255, (w >> 8) & 255, w&255, // 16: Width (h >> 24) & 255, (h >> 16) & 255, (h >> 8) & 255, h&255, // 20: Height 8, // 24: bit depth 2, // 25: RGB 0, // 26: deflate 0, // 27: no filter 0, // 28: no interlace -1,-2,-3,-4, // 29: CRC -5,-6,-7,-8, // 33: IDAT Chunk length 73, 68, 65, 84, // 37: "IDAT" // RFC 1950 header starts here 8, // 41: RFC1950 CMF 29 // 42: RFC1950 FLG ]; crc32 = crc32Array(stream,12,29); stream[29] = (crc32>>24)&255; stream[30] = (crc32>>16)&255; stream[31] = (crc32>>8)&255; stream[32] = (crc32)&255; s1 = 1; s2 = 0; for(i=0;i<h;i++) { if(i<h-1) { stream.push(0); } else { stream.push(1); } a = (3*w+1+(i===0))&255; b = ((3*w+1+(i===0))>>8)&255; stream.push(a); stream.push(b); stream.push((~a)&255); stream.push((~b)&255); if(i===0) stream.push(0); for(j=0;j<w;j++) { for(k=0;k<3;k++) { a = img[k][i][j]; if(a>255) a = 255; else if(a<0) a=0; else a = Math.round(a); s1 = (s1 + a )%65521; s2 = (s2 + s1)%65521; stream.push(a); } } stream.push(0); } adler32 = (s2<<16)+s1; stream.push((adler32>>24)&255); stream.push((adler32>>16)&255); stream.push((adler32>>8)&255); stream.push((adler32)&255); length = stream.length - 41; stream[33] = (length>>24)&255; stream[34] = (length>>16)&255; stream[35] = (length>>8)&255; stream[36] = (length)&255; crc32 = crc32Array(stream,37); stream.push((crc32>>24)&255); stream.push((crc32>>16)&255); stream.push((crc32>>8)&255); stream.push((crc32)&255); stream.push(0); stream.push(0); stream.push(0); stream.push(0); // a = stream.length; stream.push(73); // I stream.push(69); // E stream.push(78); // N stream.push(68); // D stream.push(174); // CRC1 stream.push(66); // CRC2 stream.push(96); // CRC3 stream.push(130); // CRC4 return 'data:image/png;base64,'+base64(stream); } // 2. Linear algebra with Arrays. numeric._dim = function _dim(x) { var ret = []; while(typeof x === "object") { ret.push(x.length); x = x[0]; } return ret; } numeric.dim = function dim(x) { var y,z; if(typeof x === "object") { y = x[0]; if(typeof y === "object") { z = y[0]; if(typeof z === "object") { return numeric._dim(x); } return [x.length,y.length]; } return [x.length]; } return []; } numeric.mapreduce = function mapreduce(body,init) { return Function('x','accum','_s','_k', 'if(typeof accum === "undefined") accum = '+init+';\n'+ 'if(typeof x === "number") { var xi = x; '+body+'; return accum; }\n'+ 'if(typeof _s === "undefined") _s = numeric.dim(x);\n'+ 'if(typeof _k === "undefined") _k = 0;\n'+ 'var _n = _s[_k];\n'+ 'var i,xi;\n'+ 'if(_k < _s.length-1) {\n'+ ' for(i=_n-1;i>=0;i--) {\n'+ ' accum = arguments.callee(x[i],accum,_s,_k+1);\n'+ ' }'+ ' return accum;\n'+ '}\n'+ 'for(i=_n-1;i>=1;i-=2) { \n'+ ' xi = x[i];\n'+ ' '+body+';\n'+ ' xi = x[i-1];\n'+ ' '+body+';\n'+ '}\n'+ 'if(i === 0) {\n'+ ' xi = x[i];\n'+ ' '+body+'\n'+ '}\n'+ 'return accum;' ); } numeric.same = function same(x,y) { var i,n; if(!(x instanceof Array) || !(y instanceof Array)) { return false; } n = x.length; if(n !== y.length) { return false; } for(i=0;i<n;i++) { if(x[i] === y[i]) { continue; } if(typeof x[i] === "object") { if(!same(x[i],y[i])) return false; } else { return false; } } return true; } numeric.rep = function rep(s,v,k) { if(typeof k === "undefined") { k=0; } var n = s[k], ret = Array(n), i; if(k === s.length-1) { for(i=n-2;i>=0;i-=2) { ret[i+1] = v; ret[i] = v; } if(i===-1) { ret[0] = v; } return ret; } for(i=n-1;i>=0;i--) { ret[i] = numeric.rep(s,v,k+1); } return ret; } numeric.dotMMsmall = function dotMMsmall(x,y) { var i,j,k,p,q,r,ret,foo,bar,woo,i0,k0,p0,r0; p = x.length; q = y.length; r = y[0].length; ret = Array(p); for(i=p-1;i>=0;i--) { foo = Array(r); bar = x[i]; for(k=r-1;k>=0;k--) { woo = bar[q-1]*y[q-1][k]; for(j=q-2;j>=1;j-=2) { i0 = j-1; woo += bar[j]*y[j][k] + bar[i0]*y[i0][k]; } if(j===0) { woo += bar[0]*y[0][k]; } foo[k] = woo; } ret[i] = foo; } return ret; } numeric._getCol = function _getCol(A,j,x) { var n = A.length, i; for(i=n-1;i>0;--i) { x[i] = A[i][j]; --i; x[i] = A[i][j]; } if(i===0) x[0] = A[0][j]; } numeric.dotMMbig = function dotMMbig(x,y){ var gc = numeric._getCol, p = y.length, v = Array(p); var m = x.length, n = y[0].length, A = new Array(m), xj; var i,j,k,z; --p; --m; for(i=m;i!==-1;--i) A[i] = Array(n); --n; for(i=n;i!==-1;--i) { gc(y,i,v); for(j=m;j!==-1;--j) { z=0; xj = x[j]; for(k=p;k>0;--k) { z += xj[k] * v[k]; --k; z += xj[k] * v[k]; } if(k===0) z+= xj[0] * v[0]; A[j][i] = z; } } return A; } numeric.dotMV = function dotMV(x,y) { var p = x.length, q = y.length,i; var ret = Array(p), dotVV = numeric.dotVV; for(i=p-1;i>=0;i--) { ret[i] = dotVV(x[i],y); } return ret; } numeric.dotVM = function dotVM(x,y) { var i,j,k,p,q,r,ret,foo,bar,woo,i0,k0,p0,r0,s1,s2,s3,baz,accum; p = x.length; q = y[0].length; ret = Array(q); for(k=q-1;k>=0;k--) { woo = x[p-1]*y[p-1][k]; for(j=p-2;j>=1;j-=2) { i0 = j-1; woo += x[j]*y[j][k] + x[i0]*y[i0][k]; } if(j===0) { woo += x[0]*y[0][k]; } ret[k] = woo; } return ret; } numeric.dotVV = function dotVV(x,y) { var i,n=x.length,i1,ret = x[n-1]*y[n-1]; for(i=n-2;i>=1;i-=2) { i1 = i-1; ret += x[i]*y[i] + x[i1]*y[i1]; } if(i===0) { ret += x[0]*y[0]; } return ret; } numeric.dot = function dot(x,y) { var d = numeric.dim; switch(d(x).length*1000+d(y).length) { case 2002: if(y.length < 10) return numeric.dotMMsmall(x,y); else return numeric.dotMMbig(x,y); case 2001: return numeric.dotMV(x,y); case 1002: return numeric.dotVM(x,y); case 1001: return numeric.dotVV(x,y); case 1000: return numeric.mulVS(x,y); case 1: return numeric.mulSV(x,y); case 0: return x*y; default: throw new Error('numeric.dot only works on vectors and matrices'); } } numeric.diag = function diag(d) { var i,i1,j,n = d.length, A = Array(n), Ai; for(i=n-1;i>=0;i--) { Ai = Array(n); i1 = i+2; for(j=n-1;j>=i1;j-=2) { Ai[j] = 0; Ai[j-1] = 0; } if(j>i) { Ai[j] = 0; } Ai[i] = d[i]; for(j=i-1;j>=1;j-=2) { Ai[j] = 0; Ai[j-1] = 0; } if(j===0) { Ai[0] = 0; } A[i] = Ai; } return A; } numeric.getDiag = function(A) { var n = Math.min(A.length,A[0].length),i,ret = Array(n); for(i=n-1;i>=1;--i) { ret[i] = A[i][i]; --i; ret[i] = A[i][i]; } if(i===0) { ret[0] = A[0][0]; } return ret; } numeric.identity = function identity(n) { return numeric.diag(numeric.rep([n],1)); } numeric.pointwise = function pointwise(params,body,setup) { if(typeof setup === "undefined") { setup = ""; } var fun = []; var k; var avec = /\[i\]$/,p,thevec = ''; for(k=0;k<params.length;k++) { if(avec.test(params[k])) { p = params[k].substring(0,params[k].length-3); thevec = p; } else { p = params[k]; } fun.push(p); } fun[params.length] = '_s'; fun[params.length+1] = '_k'; fun[params.length+2] = ( 'if(typeof _s === "undefined") _s = numeric.dim('+thevec+');\n'+ 'if(typeof _k === "undefined") _k = 0;\n'+ 'var _n = _s[_k];\n'+ 'var i, ret = Array(_n);\n'+ 'if(_k < _s.length-1) {\n'+ ' for(i=_n-1;i>=0;i--) ret[i] = arguments.callee('+params.join(',')+',_s,_k+1);\n'+ ' return ret;\n'+ '}\n'+ setup+'\n'+ 'for(i=_n-1;i>=3;--i) { \n'+ ' '+body+'\n'+ ' --i;\n'+ ' '+body+'\n'+ ' --i;\n'+ ' '+body+'\n'+ ' --i;\n'+ ' '+body+'\n'+ '}\n'+ 'while(i>=0) {\n'+ ' '+body+'\n'+ ' --i;\n'+ '}\n'+ 'return ret;' ); return Function.apply(null,fun); } numeric._biforeach = (function _biforeach(x,y,s,k,f) { if(k === s.length-1) { f(x,y); return; } var i,n=s[k]; for(i=n-1;i>=0;i--) { _biforeach(x[i],y[i],s,k+1,f); } }); numeric.anyV = numeric.mapreduce('if(xi) return true;','false'); numeric.allV = numeric.mapreduce('if(!xi) return false;','true'); numeric.any = function(x) { if(typeof x.length === "undefined") return x; return numeric.anyV(x); } numeric.all = function(x) { if(typeof x.length === "undefined") return x; return numeric.allV(x); } numeric.ops2 = { add: '+', sub: '-', mul: '*', div: '/', mod: '%', and: '&&', or: '||', eq: '===', neq: '!==', lt: '<', gt: '>', leq: '<=', geq: '>=', band: '&', bor: '|', bxor: '^', lshift: '<<', rshift: '>>', rrshift: '>>>' }; numeric.opseq = { addeq: '+=', subeq: '-=', muleq: '*=', diveq: '/=', modeq: '%=', lshifteq: '<<=', rshifteq: '>>=', rrshifteq: '>>>=', andeq: '&=', oreq: '|=', xoreq: '^=' }; numeric.mathfuns = ['abs','acos','asin','atan','ceil','cos', 'exp','floor','log','round','sin','sqrt','tan']; numeric.ops1 = { neg: '-', not: '!', bnot: '~' }; (function () { var i,o; for(i in numeric.ops2) { if(numeric.ops2.hasOwnProperty(i)) { o = numeric.ops2[i]; numeric[i+'VV'] = numeric.pointwise(['x[i]','y[i]'],'ret[i] = x[i] '+o+' y[i];'); numeric[i+'SV'] = numeric.pointwise(['x','y[i]'],'ret[i] = x '+o+' y[i];'); numeric[i+'VS'] = numeric.pointwise(['x[i]','y'],'ret[i] = x[i] '+o+' y;'); numeric[i] = Function( 'var n = arguments.length, i, x = arguments[0], y;\n'+ 'var VV = numeric.'+i+'VV, VS = numeric.'+i+'VS, SV = numeric.'+i+'SV;\n'+ 'for(i=1;i!==n;++i) { \n'+ ' y = arguments[i];'+ ' if(typeof x === "object") {\n'+ ' if(typeof y === "object") x = VV(x,y);\n'+ ' else x = VS(x,y);\n'+ ' } else if(typeof y === "object") x = SV(x,y);\n'+ ' else x = x '+o+' y;\n'+ '}\nreturn x;\n'); numeric[o] = numeric[i]; } } for(i in numeric.ops1) { if(numeric.ops1.hasOwnProperty(i)) { o = numeric.ops1[i]; numeric[i+'V'] = numeric.pointwise(['x[i]'],'ret[i] = '+o+'x[i];'); numeric[i] = Function('x','if(typeof x === "object") return numeric.'+i+'V(x);\nreturn '+o+'(x);'); } } for(i=0;i<numeric.mathfuns.length;i++) { o = numeric.mathfuns[i]; numeric[o+'V'] = numeric.pointwise(['x[i]'],'ret[i] = fun(x[i]);','var fun = Math.'+o+';'); numeric[o] = Function('x','if(typeof x === "object") return numeric.'+o+'V(x);\nreturn Math.'+o+'(x);'); } numeric.isNaNV = numeric.pointwise(['x[i]'],'ret[i] = isNaN(x[i]);'); numeric.isNaN = function isNaN(x) { if(typeof x === "object") return numeric.isNaNV(x); return isNaN(x); } numeric.isFiniteV = numeric.pointwise(['x[i]'],'ret[i] = isFinite(x[i]);'); numeric.isFinite = function isNaN(x) { if(typeof x === "object") return numeric.isFiniteV(x); return isFinite(x); } for(i in numeric.opseq) { if(numeric.opseq.hasOwnProperty(i)) { numeric[i+'S'] = Function('x','y', 'var n = x.length, i;\n'+ 'for(i=n-1;i>=0;i--) x[i] '+numeric.opseq[i]+' y;'); numeric[i+'V'] = Function('x','y', 'var n = x.length, i;\n'+ 'for(i=n-1;i>=0;i--) x[i] '+numeric.opseq[i]+' y[i];'); numeric[i] = Function('x','y', 'var s = numeric.dim(x);\n'+ 'if(typeof y === "number") { numeric._biforeach(x,y,s,0,numeric.'+i+'S); return x; }\n'+ 'numeric._biforeach(x,y,s,0,numeric.'+i+'V);\n'+ 'return x;'); numeric[numeric.opseq[i]] = numeric[i]; } } }()); numeric._f2 = ['atan2','pow','max','min']; ((function() { var i,j; for(j=0;j<numeric._f2.length;++j) { i = numeric._f2[j]; numeric[i+'VV'] = numeric.pointwise(['x[i]','y[i]'],'ret[i] = zz(x[i],y[i]);','var zz = Math.'+i+';'); numeric[i+'VS'] = numeric.pointwise(['x[i]','y'],'ret[i] = zz(x[i],y);','var zz = Math.'+i+';'); numeric[i+'SV'] = numeric.pointwise(['x','y[i]'],'ret[i] = zz(x,y[i]);','var zz = Math.'+i+';'); numeric[i] = Function('x','y', 'if(typeof x === "object") {\n'+ ' if(typeof y === "object") return numeric.'+i+'VV(x,y);\n'+ ' return numeric.'+i+'VS(x,y);\n'+ '}\n'+ 'if (typeof y === "object") return numeric.'+i+'SV(x,y);\n'+ 'return Math.'+i+'(x,y);\n'); } })()); numeric.atan2VV = numeric.pointwise(['x[i]','y[i]'],'ret[i] = atan2(x[i],y[i]);','var atan2 = Math.atan2;'); numeric.atan2VS = numeric.pointwise(['x[i]','y'],'ret[i] = atan2(x[i],y);','var atan2 = Math.atan2;'); numeric.atan2SV = numeric.pointwise(['x','y[i]'],'ret[i] = atan2(x,y[i]);','var atan2 = Math.atan2;'); numeric.atan2 = function atan2(x,y) { if(typeof x === "object") { if(typeof y === "object") return numeric.atan2VV(x,y); return numeric.atan2VS(x,y); } if (typeof y === "object") return numeric.atan2SV(x,y); return Math.atan2(x,y); } numeric.truncVV = numeric.pointwise(['x[i]','y[i]'],'ret[i] = round(x[i]/y[i])*y[i];','var round = Math.round;'); numeric.truncVS = numeric.pointwise(['x[i]','y'],'ret[i] = round(x[i]/y)*y;','var round = Math.round;'); numeric.truncSV = numeric.pointwise(['x','y[i]'],'ret[i] = round(x/y[i])*y[i];','var round = Math.round;'); numeric.trunc = function trunc(x,y) { if(typeof x === "object") { if(typeof y === "object") return numeric.truncVV(x,y); return numeric.truncVS(x,y); } if (typeof y === "object") return numeric.truncSV(x,y); return Math.round(x/y)*y; } numeric.powVV = numeric.pointwise(['x[i]','y[i]'],'ret[i] = pow(x[i],y[i]);','var pow = Math.pow;'); numeric.powVS = numeric.pointwise(['x[i]','y'],'ret[i] = pow(x[i],y);','var pow = Math.pow;'); numeric.powSV = numeric.pointwise(['x','y[i]'],'ret[i] = pow(x,y[i]);','var pow = Math.pow;'); numeric.pow = function pow(x,y) { if(typeof x === "object") { if(typeof y === "object") return numeric.powVV(x,y); return numeric.powVS(x,y); } if (typeof y === "object") return numeric.powSV(x,y); return Math.pow(x,y); } numeric.clone = numeric.pointwise(['x[i]'],'ret[i] = x[i];'); numeric.inv = function inv(x) { var s = numeric.dim(x), abs = Math.abs, m = s[0], n = s[1]; var A = numeric.clone(x), Ai, Aj; var I = numeric.identity(m), Ii, Ij; var i,j,k,x; for(j=0;j<n;++j) { var i0 = -1; var v0 = -1; for(i=j;i!==m;++i) { k = abs(A[i][j]); if(k>v0) { i0 = i; v0 = k; } } Aj = A[i0]; A[i0] = A[j]; A[j] = Aj; Ij = I[i0]; I[i0] = I[j]; I[j] = Ij; x = Aj[j]; for(k=j;k!==n;++k) Aj[k] /= x; for(k=n-1;k!==-1;--k) Ij[k] /= x; for(i=m-1;i!==-1;--i) { if(i!==j) { Ai = A[i]; Ii = I[i]; x = Ai[j]; for(k=j+1;k!==n;++k) Ai[k] -= Aj[k]*x; for(k=n-1;k>0;--k) { Ii[k] -= Ij[k]*x; --k; Ii[k] -= Ij[k]*x; } if(k===0) Ii[0] -= Ij[0]*x; } } } return I; } numeric.det = function det(x) { var s = numeric.dim(x); if(s.length !== 2 || s[0] !== s[1]) { throw new Error('numeric: det() only works on square matrices'); } var n = s[0], ret = 1,i,j,k,A = numeric.clone(x),Aj,Ai,alpha,temp,k1,k2,k3; for(j=0;j<n-1;j++) { k=j; for(i=j+1;i<n;i++) { if(Math.abs(A[i][j]) > Math.abs(A[k][j])) { k = i; } } if(k !== j) { temp = A[k]; A[k] = A[j]; A[j] = temp; ret *= -1; } Aj = A[j]; for(i=j+1;i<n;i++) { Ai = A[i]; alpha = Ai[j]/Aj[j]; for(k=j+1;k<n-1;k+=2) { k1 = k+1; Ai[k] -= Aj[k]*alpha; Ai[k1] -= Aj[k1]*alpha; } if(k!==n) { Ai[k] -= Aj[k]*alpha; } } if(Aj[j] === 0) { return 0; } ret *= Aj[j]; } return ret*A[j][j]; } numeric.transpose = function transpose(x) { var i,j,m = x.length,n = x[0].length, ret=Array(n),A0,A1,Bj; for(j=0;j<n;j++) ret[j] = Array(m); for(i=m-1;i>=1;i-=2) { A1 = x[i]; A0 = x[i-1]; for(j=n-1;j>=1;--j) { Bj = ret[j]; Bj[i] = A1[j]; Bj[i-1] = A0[j]; --j; Bj = ret[j]; Bj[i] = A1[j]; Bj[i-1] = A0[j]; } if(j===0) { Bj = ret[0]; Bj[i] = A1[0]; Bj[i-1] = A0[0]; } } if(i===0) { A0 = x[0]; for(j=n-1;j>=1;--j) { ret[j][0] = A0[j]; --j; ret[j][0] = A0[j]; } if(j===0) { ret[0][0] = A0[0]; } } return ret; } numeric.negtranspose = function negtranspose(x) { var i,j,m = x.length,n = x[0].length, ret=Array(n),A0,A1,Bj; for(j=0;j<n;j++) ret[j] = Array(m); for(i=m-1;i>=1;i-=2) { A1 = x[i]; A0 = x[i-1]; for(j=n-1;j>=1;--j) { Bj = ret[j]; Bj[i] = -A1[j]; Bj[i-1] = -A0[j]; --j; Bj = ret[j]; Bj[i] = -A1[j]; Bj[i-1] = -A0[j]; } if(j===0) { Bj = ret[0]; Bj[i] = -A1[0]; Bj[i-1] = -A0[0]; } } if(i===0) { A0 = x[0]; for(j=n-1;j>=1;--j) { ret[j][0] = -A0[j]; --j; ret[j][0] = -A0[j]; } if(j===0) { ret[0][0] = -A0[0]; } } return ret; } numeric._random = function _random(s,k) { var i,n=s[k],ret=Array(n), rnd; if(k === s.length-1) { rnd = Math.random; for(i=n-1;i>=1;i-=2) { ret[i] = rnd(); ret[i-1] = rnd(); } if(i===0) { ret[0] = rnd(); } return ret; } for(i=n-1;i>=0;i--) ret[i] = _random(s,k+1); return ret; } numeric.random = function random(s) { return numeric._random(s,0); } numeric.norm2Squared = function norm2Squared(x) {} numeric.norm2Squared = numeric.mapreduce('accum += xi*xi;','0'); numeric.norm2 = function norm2(x) { return Math.sqrt(numeric.norm2Squared(x)); } numeric.norminf = numeric.mapreduce('accum = max(abs(xi),accum);','0; var max = Math.max, abs = Math.abs;'); numeric.sum = numeric.mapreduce('accum += xi;','0'); numeric.sup = numeric.mapreduce('accum = max(xi,accum);','-Infinity; var max = Math.max;'); numeric.inf = numeric.mapreduce('accum = min(xi,accum);','Infinity; var min = Math.min;'); numeric.linspace = function linspace(a,b,n) { if(typeof n === "undefined") n = Math.max(Math.round(b-a)+1,1); if(n<2) { return n===1?[a]:[]; } var i,ret = Array(n); n--; for(i=n;i>=0;i--) { ret[i] = (i*b+(n-i)*a)/n; } return ret; } numeric.getBlock = function getBlock(x,from,to) { var s = numeric.dim(x); function foo(x,k) { var i,a = from[k], n = to[k]-a, ret = Array(n); if(k === s.length-1) { for(i=n;i>=0;i--) { ret[i] = x[i+a]; } return ret; } for(i=n;i>=0;i--) { ret[i] = foo(x[i+a],k+1); } return ret; } return foo(x,0); } numeric.setBlock = function setBlock(x,from,to,B) { var s = numeric.dim(x); function foo(x,y,k) { var i,a = from[k], n = to[k]-a; if(k === s.length-1) { for(i=n;i>=0;i--) { x[i+a] = y[i]; } } for(i=n;i>=0;i--) { foo(x[i+a],y[i],k+1); } } foo(x,B,0); return x; } numeric.getRange = function getRange(A,I,J) { var m = I.length, n = J.length; var i,j; var B = Array(m), Bi, AI; for(i=m-1;i!==-1;--i) { B[i] = Array(n); Bi = B[i]; AI = A[I[i]]; for(j=n-1;j!==-1;--j) Bi[j] = AI[J[j]]; } return B; } numeric.blockMatrix = function blockMatrix(X) { var s = numeric.dim(X); if(s.length<4) return numeric.blockMatrix([X]); var m=s[0],n=s[1],M,N,i,j,Xij; M = 0; N = 0; for(i=0;i<m;++i) M+=X[i][0].length; for(j=0;j<n;++j) N+=X[0][j][0].length; var Z = Array(M); for(i=0;i<M;++i) Z[i] = Array(N); var I=0,J,ZI,k,l,Xijk; for(i=0;i<m;++i) { J=N; for(j=n-1;j!==-1;--j) { Xij = X[i][j]; J -= Xij[0].length; for(k=Xij.length-1;k!==-1;--k) { Xijk = Xij[k]; ZI = Z[I+k]; for(l = Xijk.length-1;l!==-1;--l) ZI[J+l] = Xijk[l]; } } I += X[i][0].length; } return Z; } numeric.tensor = function tensor(x,y) { if(typeof x === "number" || typeof y === "number") return numeric.mul(x,y); var s1 = numeric.dim(x), s2 = numeric.dim(y); if(s1.length !== 1 || s2.length !== 1) { throw new Error('numeric: tensor product is only defined for vectors'); } var m = s1[0], n = s2[0], A = Array(m), Ai, i,j,xi; for(i=m-1;i>=0;i--) { Ai = Array(n); xi = x[i]; for(j=n-1;j>=3;--j) { Ai[j] = xi * y[j]; --j; Ai[j] = xi * y[j]; --j; Ai[j] = xi * y[j]; --j; Ai[j] = xi * y[j]; } while(j>=0) { Ai[j] = xi * y[j]; --j; } A[i] = Ai; } return A; } // 3. The Tensor type T numeric.T = function T(x,y) { this.x = x; this.y = y; } numeric.t = function t(x,y) { return new numeric.T(x,y); } numeric.Tbinop = function Tbinop(rr,rc,cr,cc,setup) { var io = numeric.indexOf; if(typeof setup !== "string") { var k; setup = ''; for(k in numeric) { if(numeric.hasOwnProperty(k) && (rr.indexOf(k)>=0 || rc.indexOf(k)>=0 || cr.indexOf(k)>=0 || cc.indexOf(k)>=0) && k.length>1) { setup += 'var '+k+' = numeric.'+k+';\n'; } } } return Function(['y'], 'var x = this;\n'+ 'if(!(y instanceof numeric.T)) { y = new numeric.T(y); }\n'+ setup+'\n'+ 'if(x.y) {'+ ' if(y.y) {'+ ' return new numeric.T('+cc+');\n'+ ' }\n'+ ' return new numeric.T('+cr+');\n'+ '}\n'+ 'if(y.y) {\n'+ ' return new numeric.T('+rc+');\n'+ '}\n'+ 'return new numeric.T('+rr+');\n' ); } numeric.T.prototype.add = numeric.Tbinop( 'add(x.x,y.x)', 'add(x.x,y.x),y.y', 'add(x.x,y.x),x.y', 'add(x.x,y.x),add(x.y,y.y)'); numeric.T.prototype.sub = numeric.Tbinop( 'sub(x.x,y.x)', 'sub(x.x,y.x),neg(y.y)', 'sub(x.x,y.x),x.y', 'sub(x.x,y.x),sub(x.y,y.y)'); numeric.T.prototype.mul = numeric.Tbinop( 'mul(x.x,y.x)', 'mul(x.x,y.x),mul(x.x,y.y)', 'mul(x.x,y.x),mul(x.y,y.x)', 'sub(mul(x.x,y.x),mul(x.y,y.y)),add(mul(x.x,y.y),mul(x.y,y.x))'); numeric.T.prototype.reciprocal = function reciprocal() { var mul = numeric.mul, div = numeric.div; if(this.y) { var d = numeric.add(mul(this.x,this.x),mul(this.y,this.y)); return new numeric.T(div(this.x,d),div(numeric.neg(this.y),d)); } return new T(div(1,this.x)); } numeric.T.prototype.div = function div(y) { if(!(y instanceof numeric.T)) y = new numeric.T(y); if(y.y) { return this.mul(y.reciprocal()); } var div = numeric.div; if(this.y) { return new numeric.T(div(this.x,y.x),div(this.y,y.x)); } return new numeric.T(div(this.x,y.x)); } numeric.T.prototype.dot = numeric.Tbinop( 'dot(x.x,y.x)', 'dot(x.x,y.x),dot(x.x,y.y)', 'dot(x.x,y.x),dot(x.y,y.x)', 'sub(dot(x.x,y.x),dot(x.y,y.y)),add(dot(x.x,y.y),dot(x.y,y.x))' ); numeric.T.prototype.transpose = function transpose() { var t = numeric.transpose, x = this.x, y = this.y; if(y) { return new numeric.T(t(x),t(y)); } return new numeric.T(t(x)); } numeric.T.prototype.transjugate = function transjugate() { var t = numeric.transpose, x = this.x, y = this.y; if(y) { return new numeric.T(t(x),numeric.negtranspose(y)); } return new numeric.T(t(x)); } numeric.Tunop = function Tunop(r,c,s) { if(typeof s !== "string") { s = ''; } return Function( 'var x = this;\n'+ s+'\n'+ 'if(x.y) {'+ ' '+c+';\n'+ '}\n'+ r+';\n' ); } numeric.T.prototype.exp = numeric.Tunop( 'return new numeric.T(ex)', 'return new numeric.T(mul(cos(x.y),ex),mul(sin(x.y),ex))', 'var ex = numeric.exp(x.x), cos = numeric.cos, sin = numeric.sin, mul = numeric.mul;'); numeric.T.prototype.conj = numeric.Tunop( 'return new numeric.T(x.x);', 'return new numeric.T(x.x,numeric.neg(x.y));'); numeric.T.prototype.neg = numeric.Tunop( 'return new numeric.T(neg(x.x));', 'return new numeric.T(neg(x.x),neg(x.y));', 'var neg = numeric.neg;'); numeric.T.prototype.sin = numeric.Tunop( 'return new numeric.T(numeric.sin(x.x))', 'return x.exp().sub(x.neg().exp()).div(new numeric.T(0,2));'); numeric.T.prototype.cos = numeric.Tunop( 'return new numeric.T(numeric.cos(x.x))', 'return x.exp().add(x.neg().exp()).div(2);'); numeric.T.prototype.abs = numeric.Tunop( 'return new numeric.T(numeric.abs(x.x));', 'return new numeric.T(numeric.sqrt(numeric.add(mul(x.x,x.x),mul(x.y,x.y))));', 'var mul = numeric.mul;'); numeric.T.prototype.log = numeric.Tunop( 'return new numeric.T(numeric.log(x.x));', 'var theta = new numeric.T(numeric.atan2(x.y,x.x)), r = x.abs();\n'+ 'return new numeric.T(numeric.log(r.x),theta.x);'); numeric.T.prototype.norm2 = numeric.Tunop( 'return numeric.norm2(x.x);', 'var f = numeric.norm2Squared;\n'+ 'return Math.sqrt(f(x.x)+f(x.y));'); numeric.T.prototype.inv = function inv() { var A = this; if(typeof A.y === "undefined") { return new numeric.T(numeric.inv(A.x)); } var n = A.x.length, i, j, k; var Rx = numeric.identity(n),Ry = numeric.rep([n,n],0); var Ax = numeric.clone(A.x), Ay = numeric.clone(A.y); var Aix, Aiy, Ajx, Ajy, Rix, Riy, Rjx, Rjy; var i,j,k,d,d1,ax,ay,bx,by,temp; for(i=0;i<n;i++) { ax = Ax[i][i]; ay = Ay[i][i]; d = ax*ax+ay*ay; k = i; for(j=i+1;j<n;j++) { ax = Ax[j][i]; ay = Ay[j][i]; d1 = ax*ax+ay*ay; if(d1 > d) { k=j; d = d1; } } if(k!==i) { temp = Ax[i]; Ax[i] = Ax[k]; Ax[k] = temp; temp = Ay[i]; Ay[i] = Ay[k]; Ay[k] = temp; temp = Rx[i]; Rx[i] = Rx[k]; Rx[k] = temp; temp = Ry[i]; Ry[i] = Ry[k]; Ry[k] = temp; } Aix = Ax[i]; Aiy = Ay[i]; Rix = Rx[i]; Riy = Ry[i]; ax = Aix[i]; ay = Aiy[i]; for(j=i+1;j<n;j++) { bx = Aix[j]; by = Aiy[j]; Aix[j] = (bx*ax+by*ay)/d; Aiy[j] = (by*ax-bx*ay)/d; } for(j=0;j<n;j++) { bx = Rix[j]; by = Riy[j]; Rix[j] = (bx*ax+by*ay)/d; Riy[j] = (by*ax-bx*ay)/d; } for(j=i+1;j<n;j++) { Ajx = Ax[j]; Ajy = Ay[j]; Rjx = Rx[j]; Rjy = Ry[j]; ax = Ajx[i]; ay = Ajy[i]; for(k=i+1;k<n;k++) { bx = Aix[k]; by = Aiy[k]; Ajx[k] -= bx*ax-by*ay; Ajy[k] -= by*ax+bx*ay; } for(k=0;k<n;k++) { bx = Rix[k]; by = Riy[k]; Rjx[k] -= bx*ax-by*ay; Rjy[k] -= by*ax+bx*ay; } } } for(i=n-1;i>0;i--) { Rix = Rx[i]; Riy = Ry[i]; for(j=i-1;j>=0;j--) { Rjx = Rx[j]; Rjy = Ry[j]; ax = Ax[j][i]; ay = Ay[j][i]; for(k=n-1;k>=0;k--) { bx = Rix[k]; by = Riy[k]; Rjx[k] -= ax*bx - ay*by; Rjy[k] -= ax*by + ay*bx; } } } return new numeric.T(Rx,Ry); } numeric.T.prototype.get = function get(i) { var x = this.x, y = this.y, k = 0, ik, n = i.length; if(y) { while(k<n) { ik = i[k]; x = x[ik]; y = y[ik]; k++; } return new numeric.T(x,y); } while(k<n) { ik = i[k]; x = x[ik]; k++; } return new numeric.T(x); } numeric.T.prototype.set = function set(i,v) { var x = this.x, y = this.y, k = 0, ik, n = i.length, vx = v.x, vy = v.y; if(n===0) { if(vy) { this.y = vy; } else if(y) { this.y = undefined; } this.x = x; return this; } if(vy) { if(y) { /* ok */ } else { y = numeric.rep(numeric.dim(x),0); this.y = y; } while(k<n-1) { ik = i[k]; x = x[ik]; y = y[ik]; k++; } ik = i[k]; x[ik] = vx; y[ik] = vy; return this; } if(y) { while(k<n-1) { ik = i[k]; x = x[ik]; y = y[ik]; k++; } ik = i[k]; x[ik] = vx; if(vx instanceof Array) y[ik] = numeric.rep(numeric.dim(vx),0); else y[ik] = 0; return this; } while(k<n-1) { ik = i[k]; x = x[ik]; k++; } ik = i[k]; x[ik] = vx; return this; } numeric.T.prototype.getRows = function getRows(i0,i1) { var n = i1-i0+1, j; var rx = Array(n), ry, x = this.x, y = this.y; for(j=i0;j<=i1;j++) { rx[j-i0] = x[j]; } if(y) { ry = Array(n); for(j=i0;j<=i1;j++) { ry[j-i0] = y[j]; } return new numeric.T(rx,ry); } return new numeric.T(rx); } numeric.T.prototype.setRows = function setRows(i0,i1,A) { var j; var rx = this.x, ry = this.y, x = A.x, y = A.y; for(j=i0;j<=i1;j++) { rx[j] = x[j-i0]; } if(y) { if(!ry) { ry = numeric.rep(numeric.dim(rx),0); this.y = ry; } for(j=i0;j<=i1;j++) { ry[j] = y[j-i0]; } } else if(ry) { for(j=i0;j<=i1;j++) { ry[j] = numeric.rep([x[j-i0].length],0); } } return this; } numeric.T.prototype.getRow = function getRow(k) { var x = this.x, y = this.y; if(y) { return new numeric.T(x[k],y[k]); } return new numeric.T(x[k]); } numeric.T.prototype.setRow = function setRow(i,v) { var rx = this.x, ry = this.y, x = v.x, y = v.y; rx[i] = x; if(y) { if(!ry) { ry = numeric.rep(numeric.dim(rx),0); this.y = ry; } ry[i] = y; } else if(ry) { ry = numeric.rep([x.length],0); } return this; } numeric.T.prototype.getBlock = function getBlock(from,to) { var x = this.x, y = this.y, b = numeric.getBlock; if(y) { return new numeric.T(b(x,from,to),b(y,from,to)); } return new numeric.T(b(x,from,to)); } numeric.T.prototype.setBlock = function setBlock(from,to,A) { if(!(A instanceof numeric.T)) A = new numeric.T(A); var x = this.x, y = this.y, b = numeric.setBlock, Ax = A.x, Ay = A.y; if(Ay) { if(!y) { this.y = numeric.rep(numeric.dim(this),0); y = this.y; } b(x,from,to,Ax); b(y,from,to,Ay); return this; } b(x,from,to,Ax); if(y) b(y,from,to,numeric.rep(numeric.dim(Ax),0)); } numeric.T.rep = function rep(s,v) { var T = numeric.T; if(!(v instanceof T)) v = new T(v); var x = v.x, y = v.y, r = numeric.rep; if(y) return new T(r(s,x),r(s,y)); return new T(r(s,x)); } numeric.T.diag = function diag(d) { if(!(d instanceof numeric.T)) d = new numeric.T(d); var x = d.x, y = d.y, diag = numeric.diag; if(y) return new numeric.T(diag(x),diag(y)); return new numeric.T(diag(x)); } numeric.T.eig = function eig() { if(this.y) { throw new Error('eig: not implemented for complex matrices.'); } return numeric.eig(this.x); } numeric.T.identity = function identity(n) { return new numeric.T(numeric.identity(n)); } numeric.T.prototype.getDiag = function getDiag() { var n = numeric; var x = this.x, y = this.y; if(y) { return new n.T(n.getDiag(x),n.getDiag(y)); } return new n.T(n.getDiag(x)); } // 4. Eigenvalues of real matrices numeric.house = function house(x) { var v = numeric.clone(x); var s = x[0] >= 0 ? 1 : -1; var alpha = s*numeric.norm2(x); v[0] += alpha; var foo = numeric.norm2(v); if(foo === 0) { /* this should not happen */ throw new Error('eig: internal error'); } return numeric.div(v,foo); } numeric.toUpperHessenberg = function toUpperHessenberg(me) { var s = numeric.dim(me); if(s.length !== 2 || s[0] !== s[1]) { throw new Error('numeric: toUpperHessenberg() only works on square matrices'); } var m = s[0], i,j,k,x,v,A = numeric.clone(me),B,C,Ai,Ci,Q = numeric.identity(m),Qi; for(j=0;j<m-2;j++) { x = Array(m-j-1); for(i=j+1;i<m;i++) { x[i-j-1] = A[i][j]; } if(numeric.norm2(x)>0) { v = numeric.house(x); B = numeric.getBlock(A,[j+1,j],[m-1,m-1]); C = numeric.tensor(v,numeric.dot(v,B)); for(i=j+1;i<m;i++) { Ai = A[i]; Ci = C[i-j-1]; for(k=j;k<m;k++) Ai[k] -= 2*Ci[k-j]; } B = numeric.getBlock(A,[0,j+1],[m-1,m-1]); C = numeric.tensor(numeric.dot(B,v),v); for(i=0;i<m;i++) { Ai = A[i]; Ci = C[i]; for(k=j+1;k<m;k++) Ai[k] -= 2*Ci[k-j-1]; } B = Array(m-j-1); for(i=j+1;i<m;i++) B[i-j-1] = Q[i]; C = numeric.tensor(v,numeric.dot(v,B)); for(i=j+1;i<m;i++) { Qi = Q[i]; Ci = C[i-j-1]; for(k=0;k<m;k++) Qi[k] -= 2*Ci[k]; } } } return {H:A, Q:Q}; } numeric.epsilon = 2.220446049250313e-16; numeric.QRFrancis = function(H,maxiter) { if(typeof maxiter === "undefined") { maxiter = 10000; } H = numeric.clone(H); var H0 = numeric.clone(H); var s = numeric.dim(H),m=s[0],x,v,a,b,c,d,det,tr, Hloc, Q = numeric.identity(m), Qi, Hi, B, C, Ci,i,j,k,iter; if(m<3) { return {Q:Q, B:[ [0,m-1] ]}; } var epsilon = numeric.epsilon; for(iter=0;iter<maxiter;iter++) { for(j=0;j<m-1;j++) { if(Math.abs(H[j+1][j]) < epsilon*(Math.abs(H[j][j])+Math.abs(H[j+1][j+1]))) { var QH1 = numeric.QRFrancis(numeric.getBlock(H,[0,0],[j,j]),maxiter); var QH2 = numeric.QRFrancis(numeric.getBlock(H,[j+1,j+1],[m-1,m-1]),maxiter); B = Array(j+1); for(i=0;i<=j;i++) { B[i] = Q[i]; } C = numeric.dot(QH1.Q,B); for(i=0;i<=j;i++) { Q[i] = C[i]; } B = Array(m-j-1); for(i=j+1;i<m;i++) { B[i-j-1] = Q[i]; } C = numeric.dot(QH2.Q,B); for(i=j+1;i<m;i++) { Q[i] = C[i-j-1]; } return {Q:Q,B:QH1.B.concat(numeric.add(QH2.B,j+1))}; } } a = H[m-2][m-2]; b = H[m-2][m-1]; c = H[m-1][m-2]; d = H[m-1][m-1]; tr = a+d; det = (a*d-b*c); Hloc = numeric.getBlock(H, [0,0], [2,2]); if(tr*tr>=4*det) { var s1,s2; s1 = 0.5*(tr+Math.sqrt(tr*tr-4*det)); s2 = 0.5*(tr-Math.sqrt(tr*tr-4*det)); Hloc = numeric.add(numeric.sub(numeric.dot(Hloc,Hloc), numeric.mul(Hloc,s1+s2)), numeric.diag(numeric.rep([3],s1*s2))); } else { Hloc = numeric.add(numeric.sub(numeric.dot(Hloc,Hloc), numeric.mul(Hloc,tr)), numeric.diag(numeric.rep([3],det))); } x = [Hloc[0][0],Hloc[1][0],Hloc[2][0]]; v = numeric.house(x); B = [H[0],H[1],H[2]]; C = numeric.tensor(v,numeric.dot(v,B)); for(i=0;i<3;i++) { Hi = H[i]; Ci = C[i]; for(k=0;k<m;k++) Hi[k] -= 2*Ci[k]; } B = numeric.getBlock(H, [0,0],[m-1,2]); C = numeric.tensor(numeric.dot(B,v),v); for(i=0;i<m;i++) { Hi = H[i]; Ci = C[i]; for(k=0;k<3;k++) Hi[k] -= 2*Ci[k]; } B = [Q[0],Q[1],Q[2]]; C = numeric.tensor(v,numeric.dot(v,B)); for(i=0;i<3;i++) { Qi = Q[i]; Ci = C[i]; for(k=0;k<m;k++) Qi[k] -= 2*Ci[k]; } var J; for(j=0;j<m-2;j++) { for(k=j;k<=j+1;k++) { if(Math.abs(H[k+1][k]) < epsilon*(Math.abs(H[k][k])+Math.abs(H[k+1][k+1]))) { var QH1 = numeric.QRFrancis(numeric.getBlock(H,[0,0],[k,k]),maxiter); var QH2 = numeric.QRFrancis(numeric.getBlock(H,[k+1,k+1],[m-1,m-1]),maxiter); B = Array(k+1); for(i=0;i<=k;i++) { B[i] = Q[i]; } C = numeric.dot(QH1.Q,B); for(i=0;i<=k;i++) { Q[i] = C[i]; } B = Array(m-k-1); for(i=k+1;i<m;i++) { B[i-k-1] = Q[i]; } C = numeric.dot(QH2.Q,B); for(i=k+1;i<m;i++) { Q[i] = C[i-k-1]; } return {Q:Q,B:QH1.B.concat(numeric.add(QH2.B,k+1))}; } } J = Math.min(m-1,j+3); x = Array(J-j); for(i=j+1;i<=J;i++) { x[i-j-1] = H[i][j]; } v = numeric.house(x); B = numeric.getBlock(H, [j+1,j],[J,m-1]); C = numeric.tensor(v,numeric.dot(v,B)); for(i=j+1;i<=J;i++) { Hi = H[i]; Ci = C[i-j-1]; for(k=j;k<m;k++) Hi[k] -= 2*Ci[k-j]; } B = numeric.getBlock(H, [0,j+1],[m-1,J]); C = numeric.tensor(numeric.dot(B,v),v); for(i=0;i<m;i++) { Hi = H[i]; Ci = C[i]; for(k=j+1;k<=J;k++) Hi[k] -= 2*Ci[k-j-1]; } B = Array(J-j); for(i=j+1;i<=J;i++) B[i-j-1] = Q[i]; C = numeric.tensor(v,numeric.dot(v,B)); for(i=j+1;i<=J;i++) { Qi = Q[i]; Ci = C[i-j-1]; for(k=0;k<m;k++) Qi[k] -= 2*Ci[k]; } } } throw new Error('numeric: eigenvalue iteration does not converge -- increase maxiter?'); } numeric.eig = function eig(A,maxiter) { var QH = numeric.toUpperHessenberg(A); var QB = numeric.QRFrancis(QH.H,maxiter); var T = numeric.T; var n = A.length,i,k,flag = false,B = QB.B,H = numeric.dot(QB.Q,numeric.dot(QH.H,numeric.transpose(QB.Q))); var Q = new T(numeric.dot(QB.Q,QH.Q)),Q0; var m = B.length,j; var a,b,c,d,p1,p2,disc,x,y,p,q,n1,n2; var sqrt = Math.sqrt; for(k=0;k<m;k++) { i = B[k][0]; if(i === B[k][1]) { // nothing } else { j = i+1; a = H[i][i]; b = H[i][j]; c = H[j][i]; d = H[j][j]; if(b === 0 && c === 0) continue; p1 = -a-d; p2 = a*d-b*c; disc = p1*p1-4*p2; if(disc>=0) { if(p1<0) x = -0.5*(p1-sqrt(disc)); else x = -0.5*(p1+sqrt(disc)); n1 = (a-x)*(a-x)+b*b; n2 = c*c+(d-x)*(d-x); if(n1>n2) { n1 = sqrt(n1); p = (a-x)/n1; q = b/n1; } else { n2 = sqrt(n2); p = c/n2; q = (d-x)/n2; } Q0 = new T([[q,-p],[p,q]]); Q.setRows(i,j,Q0.dot(Q.getRows(i,j))); } else { x = -0.5*p1; y = 0.5*sqrt(-disc); n1 = (a-x)*(a-x)+b*b; n2 = c*c+(d-x)*(d-x); if(n1>n2) { n1 = sqrt(n1+y*y); p = (a-x)/n1; q = b/n1; x = 0; y /= n1; } else { n2 = sqrt(n2+y*y); p = c/n2; q = (d-x)/n2; x = y/n2; y = 0; } Q0 = new T([[q,-p],[p,q]],[[x,y],[y,-x]]); Q.setRows(i,j,Q0.dot(Q.getRows(i,j))); } } } var R = Q.dot(A).dot(Q.transjugate()), n = A.length, E = numeric.T.identity(n); for(j=0;j<n;j++) { if(j>0) { for(k=j-1;k>=0;k--) { var Rk = R.get([k,k]), Rj = R.get([j,j]); if(numeric.neq(Rk.x,Rj.x) || numeric.neq(Rk.y,Rj.y)) { x = R.getRow(k).getBlock([k],[j-1]); y = E.getRow(j).getBlock([k],[j-1]); E.set([j,k],(R.get([k,j]).neg().sub(x.dot(y))).div(Rk.sub(Rj))); } else { E.setRow(j,E.getRow(k)); continue; } } } } for(j=0;j<n;j++) { x = E.getRow(j); E.setRow(j,x.div(x.norm2())); } E = E.transpose(); E = Q.transjugate().dot(E); return { lambda:R.getDiag(), E:E }; }; // 5. Compressed Column Storage matrices numeric.ccsSparse = function ccsSparse(A) { var m = A.length,n,foo, i,j, counts = []; for(i=m-1;i!==-1;--i) { foo = A[i]; for(j in foo) { j = parseInt(j); while(j>=counts.length) counts[counts.length] = 0; if(foo[j]!==0) counts[j]++; } } var n = counts.length; var Ai = Array(n+1); Ai[0] = 0; for(i=0;i<n;++i) Ai[i+1] = Ai[i] + counts[i]; var Aj = Array(Ai[n]), Av = Array(Ai[n]); for(i=m-1;i!==-1;--i) { foo = A[i]; for(j in foo) { if(foo[j]!==0) { counts[j]--; Aj[Ai[j]+counts[j]] = i; Av[Ai[j]+counts[j]] = foo[j]; } } } return [Ai,Aj,Av]; } numeric.ccsFull = function ccsFull(A) { var Ai = A[0], Aj = A[1], Av = A[2], s = numeric.ccsDim(A), m = s[0], n = s[1], i,j,j0,j1,k; var B = numeric.rep([m,n],0); for(i=0;i<n;i++) { j0 = Ai[i]; j1 = Ai[i+1]; for(j=j0;j<j1;++j) { B[Aj[j]][i] = Av[j]; } } return B; } numeric.ccsTSolve = function ccsTSolve(A,b,x,bj,xj) { var Ai = A[0], Aj = A[1], Av = A[2],m = Ai.length-1, max = Math.max,n=0; if(typeof bj === "undefined") x = numeric.rep([m],0); if(typeof bj === "undefined") bj = numeric.linspace(0,x.length-1); if(typeof xj === "undefined") xj = []; function dfs(j) { var k; if(x[j] !== 0) return; x[j] = 1; for(k=Ai[j];k<Ai[j+1];++k) dfs(Aj[k]); xj[n] = j; ++n; } var i,j,j0,j1,k,l,l0,l1,a; for(i=bj.length-1;i!==-1;--i) { dfs(bj[i]); } xj.length = n; for(i=xj.length-1;i!==-1;--i) { x[xj[i]] = 0; } for(i=bj.length-1;i!==-1;--i) { j = bj[i]; x[j] = b[j]; } for(i=xj.length-1;i!==-1;--i) { j = xj[i]; j0 = Ai[j]; j1 = max(Ai[j+1],j0); for(k=j0;k!==j1;++k) { if(Aj[k] === j) { x[j] /= Av[k]; break; } } a = x[j]; for(k=j0;k!==j1;++k) { l = Aj[k]; if(l !== j) x[l] -= a*Av[k]; } } return x; } numeric.ccsDFS = function ccsDFS(n) { this.k = Array(n); this.k1 = Array(n); this.j = Array(n); } numeric.ccsDFS.prototype.dfs = function dfs(J,Ai,Aj,x,xj,Pinv) { var m = 0,foo,n=xj.length; var k = this.k, k1 = this.k1, j = this.j,km,k11; if(x[J]!==0) return; x[J] = 1; j[0] = J; k[0] = km = Ai[J]; k1[0] = k11 = Ai[J+1]; while(1) { if(km >= k11) { xj[n] = j[m]; if(m===0) return; ++n; --m; km = k[m]; k11 = k1[m]; } else { foo = Pinv[Aj[km]]; if(x[foo] === 0) { x[foo] = 1; k[m] = km; ++m; j[m] = foo; km = Ai[foo]; k1[m] = k11 = Ai[foo+1]; } else ++km; } } } numeric.ccsLPSolve = function ccsLPSolve(A,B,x,xj,I,Pinv,dfs) { var Ai = A[0], Aj = A[1], Av = A[2],m = Ai.length-1, n=0; var Bi = B[0], Bj = B[1], Bv = B[2]; var i,i0,i1,j,J,j0,j1,k,l,l0,l1,a; i0 = Bi[I]; i1 = Bi[I+1]; xj.length = 0; for(i=i0;i<i1;++i) { dfs.dfs(Pinv[Bj[i]],Ai,Aj,x,xj,Pinv); } for(i=xj.length-1;i!==-1;--i) { x[xj[i]] = 0; } for(i=i0;i!==i1;++i) { j = Pinv[Bj[i]]; x[j] = Bv[i]; } for(i=xj.length-1;i!==-1;--i) { j = xj[i]; j0 = Ai[j]; j1 = Ai[j+1]; for(k=j0;k<j1;++k) { if(Pinv[Aj[k]] === j) { x[j] /= Av[k]; break; } } a = x[j]; for(k=j0;k<j1;++k) { l = Pinv[Aj[k]]; if(l !== j) x[l] -= a*Av[k]; } } return x; } numeric.ccsLUP1 = function ccsLUP1(A,threshold) { var m = A[0].length-1; var L = [numeric.rep([m+1],0),[],[]], U = [numeric.rep([m+1], 0),[],[]]; var Li = L[0], Lj = L[1], Lv = L[2], Ui = U[0], Uj = U[1], Uv = U[2]; var x = numeric.rep([m],0), xj = numeric.rep([m],0); var i,j,k,j0,j1,a,e,c,d,K; var sol = numeric.ccsLPSolve, max = Math.max, abs = Math.abs; var P = numeric.linspace(0,m-1),Pinv = numeric.linspace(0,m-1); var dfs = new numeric.ccsDFS(m); if(typeof threshold === "undefined") { threshold = 1; } for(i=0;i<m;++i) { sol(L,A,x,xj,i,Pinv,dfs); a = -1; e = -1; for(j=xj.length-1;j!==-1;--j) { k = xj[j]; if(k <= i) continue; c = abs(x[k]); if(c > a) { e = k; a = c; } } if(abs(x[i])<threshold*a) { j = P[i]; a = P[e]; P[i] = a; Pinv[a] = i; P[e] = j; Pinv[j] = e; a = x[i]; x[i] = x[e]; x[e] = a; } a = Li[i]; e = Ui[i]; d = x[i]; Lj[a] = P[i]; Lv[a] = 1; ++a; for(j=xj.length-1;j!==-1;--j) { k = xj[j]; c = x[k]; xj[j] = 0; x[k] = 0; if(k<=i) { Uj[e] = k; Uv[e] = c; ++e; } else { Lj[a] = P[k]; Lv[a] = c/d; ++a; } } Li[i+1] = a; Ui[i+1] = e; } for(j=Lj.length-1;j!==-1;--j) { Lj[j] = Pinv[Lj[j]]; } return {L:L, U:U, P:P, Pinv:Pinv}; } numeric.ccsDFS0 = function ccsDFS0(n) { this.k = Array(n); this.k1 = Array(n); this.j = Array(n); } numeric.ccsDFS0.prototype.dfs = function dfs(J,Ai,Aj,x,xj,Pinv,P) { var m = 0,foo,n=xj.length; var k = this.k, k1 = this.k1, j = this.j,km,k11; if(x[J]!==0) return; x[J] = 1; j[0] = J; k[0] = km = Ai[Pinv[J]]; k1[0] = k11 = Ai[Pinv[J]+1]; while(1) { if(isNaN(km)) throw new Error("Ow!"); if(km >= k11) { xj[n] = Pinv[j[m]]; if(m===0) return; ++n; --m; km = k[m]; k11 = k1[m]; } else { foo = Aj[km]; if(x[foo] === 0) { x[foo] = 1; k[m] = km; ++m; j[m] = foo; foo = Pinv[foo]; km = Ai[foo]; k1[m] = k11 = Ai[foo+1]; } else ++km; } } } numeric.ccsLPSolve0 = function ccsLPSolve0(A,B,y,xj,I,Pinv,P,dfs) { var Ai = A[0], Aj = A[1], Av = A[2],m = Ai.length-1, n=0; var Bi = B[0], Bj = B[1], Bv = B[2]; var i,i0,i1,j,J,j0,j1,k,l,l0,l1,a; i0 = Bi[I]; i1 = Bi[I+1]; xj.length = 0; for(i=i0;i<i1;++i) { dfs.dfs(Bj[i],Ai,Aj,y,xj,Pinv,P); } for(i=xj.length-1;i!==-1;--i) { j = xj[i]; y[P[j]] = 0; } for(i=i0;i!==i1;++i) { j = Bj[i]; y[j] = Bv[i]; } for(i=xj.length-1;i!==-1;--i) { j = xj[i]; l = P[j]; j0 = Ai[j]; j1 = Ai[j+1]; for(k=j0;k<j1;++k) { if(Aj[k] === l) { y[l] /= Av[k]; break; } } a = y[l]; for(k=j0;k<j1;++k) y[Aj[k]] -= a*Av[k]; y[l] = a; } } numeric.ccsLUP0 = function ccsLUP0(A,threshold) { var m = A[0].length-1; var L = [numeric.rep([m+1],0),[],[]], U = [numeric.rep([m+1], 0),[],[]]; var Li = L[0], Lj = L[1], Lv = L[2], Ui = U[0], Uj = U[1], Uv = U[2]; var y = numeric.rep([m],0), xj = numeric.rep([m],0); var i,j,k,j0,j1,a,e,c,d,K; var sol = numeric.ccsLPSolve0, max = Math.max, abs = Math.abs; var P = numeric.linspace(0,m-1),Pinv = numeric.linspace(0,m-1); var dfs = new numeric.ccsDFS0(m); if(typeof threshold === "undefined") { threshold = 1; } for(i=0;i<m;++i) { sol(L,A,y,xj,i,Pinv,P,dfs); a = -1; e = -1; for(j=xj.length-1;j!==-1;--j) { k = xj[j]; if(k <= i) continue; c = abs(y[P[k]]); if(c > a) { e = k; a = c; } } if(abs(y[P[i]])<threshold*a) { j = P[i]; a = P[e]; P[i] = a; Pinv[a] = i; P[e] = j; Pinv[j] = e; } a = Li[i]; e = Ui[i]; d = y[P[i]]; Lj[a] = P[i]; Lv[a] = 1; ++a; for(j=xj.length-1;j!==-1;--j) { k = xj[j]; c = y[P[k]]; xj[j] = 0; y[P[k]] = 0; if(k<=i) { Uj[e] = k; Uv[e] = c; ++e; } else { Lj[a] = P[k]; Lv[a] = c/d; ++a; } } Li[i+1] = a; Ui[i+1] = e; } for(j=Lj.length-1;j!==-1;--j) { Lj[j] = Pinv[Lj[j]]; } return {L:L, U:U, P:P, Pinv:Pinv}; } numeric.ccsLUP = numeric.ccsLUP0; numeric.ccsDim = function ccsDim(A) { return [numeric.sup(A[1])+1,A[0].length-1]; } numeric.ccsGetBlock = function ccsGetBlock(A,i,j) { var s = numeric.ccsDim(A),m=s[0],n=s[1]; if(typeof i === "undefined") { i = numeric.linspace(0,m-1); } else if(typeof i === "number") { i = [i]; } if(typeof j === "undefined") { j = numeric.linspace(0,n-1); } else if(typeof j === "number") { j = [j]; } var p,p0,p1,P = i.length,q,Q = j.length,r,jq,ip; var Bi = numeric.rep([n],0), Bj=[], Bv=[], B = [Bi,Bj,Bv]; var Ai = A[0], Aj = A[1], Av = A[2]; var x = numeric.rep([m],0),count=0,flags = numeric.rep([m],0); for(q=0;q<Q;++q) { jq = j[q]; var q0 = Ai[jq]; var q1 = Ai[jq+1]; for(p=q0;p<q1;++p) { r = Aj[p]; flags[r] = 1; x[r] = Av[p]; } for(p=0;p<P;++p) { ip = i[p]; if(flags[ip]) { Bj[count] = p; Bv[count] = x[i[p]]; ++count; } } for(p=q0;p<q1;++p) { r = Aj[p]; flags[r] = 0; } Bi[q+1] = count; } return B; } numeric.ccsDot = function ccsDot(A,B) { var Ai = A[0], Aj = A[1], Av = A[2]; var Bi = B[0], Bj = B[1], Bv = B[2]; var sA = numeric.ccsDim(A), sB = numeric.ccsDim(B); var m = sA[0], n = sA[1], o = sB[1]; var x = numeric.rep([m],0), flags = numeric.rep([m],0), xj = Array(m); var Ci = numeric.rep([o],0), Cj = [], Cv = [], C = [Ci,Cj,Cv]; var i,j,k,j0,j1,i0,i1,l,p,a,b; for(k=0;k!==o;++k) { j0 = Bi[k]; j1 = Bi[k+1]; p = 0; for(j=j0;j<j1;++j) { a = Bj[j]; b = Bv[j]; i0 = Ai[a]; i1 = Ai[a+1]; for(i=i0;i<i1;++i) { l = Aj[i]; if(flags[l]===0) { xj[p] = l; flags[l] = 1; p = p+1; } x[l] = x[l] + Av[i]*b; } } j0 = Ci[k]; j1 = j0+p; Ci[k+1] = j1; for(j=p-1;j!==-1;--j) { b = j0+j; i = xj[j]; Cj[b] = i; Cv[b] = x[i]; flags[i] = 0; x[i] = 0; } Ci[k+1] = Ci[k]+p; } return C; } numeric.ccsLUPSolve = function ccsLUPSolve(LUP,B) { var L = LUP.L, U = LUP.U, P = LUP.P; var Bi = B[0]; var flag = false; if(typeof Bi !== "object") { B = [[0,B.length],numeric.linspace(0,B.length-1),B]; Bi = B[0]; flag = true; } var Bj = B[1], Bv = B[2]; var n = L[0].length-1, m = Bi.length-1; var x = numeric.rep([n],0), xj = Array(n); var b = numeric.rep([n],0), bj = Array(n); var Xi = numeric.rep([m+1],0), Xj = [], Xv = []; var sol = numeric.ccsTSolve; var i,j,j0,j1,k,J,N=0; for(i=0;i<m;++i) { k = 0; j0 = Bi[i]; j1 = Bi[i+1]; for(j=j0;j<j1;++j) { J = LUP.Pinv[Bj[j]]; bj[k] = J; b[J] = Bv[j]; ++k; } bj.length = k; sol(L,b,x,bj,xj); for(j=bj.length-1;j!==-1;--j) b[bj[j]] = 0; sol(U,x,b,xj,bj); if(flag) return b; for(j=xj.length-1;j!==-1;--j) x[xj[j]] = 0; for(j=bj.length-1;j!==-1;--j) { J = bj[j]; Xj[N] = J; Xv[N] = b[J]; b[J] = 0; ++N; } Xi[i+1] = N; } return [Xi,Xj,Xv]; } numeric.ccsbinop = function ccsbinop(body,setup) { if(typeof setup === "undefined") setup=''; return Function('X','Y', 'var Xi = X[0], Xj = X[1], Xv = X[2];\n'+ 'var Yi = Y[0], Yj = Y[1], Yv = Y[2];\n'+ 'var n = Xi.length-1,m = Math.max(numeric.sup(Xj),numeric.sup(Yj))+1;\n'+ 'var Zi = numeric.rep([n+1],0), Zj = [], Zv = [];\n'+ 'var x = numeric.rep([m],0),y = numeric.rep([m],0);\n'+ 'var xk,yk,zk;\n'+ 'var i,j,j0,j1,k,p=0;\n'+ setup+ 'for(i=0;i<n;++i) {\n'+ ' j0 = Xi[i]; j1 = Xi[i+1];\n'+ ' for(j=j0;j!==j1;++j) {\n'+ ' k = Xj[j];\n'+ ' x[k] = 1;\n'+ ' Zj[p] = k;\n'+ ' ++p;\n'+ ' }\n'+ ' j0 = Yi[i]; j1 = Yi[i+1];\n'+ ' for(j=j0;j!==j1;++j) {\n'+ ' k = Yj[j];\n'+ ' y[k] = Yv[j];\n'+ ' if(x[k] === 0) {\n'+ ' Zj[p] = k;\n'+ ' ++p;\n'+ ' }\n'+ ' }\n'+ ' Zi[i+1] = p;\n'+ ' j0 = Xi[i]; j1 = Xi[i+1];\n'+ ' for(j=j0;j!==j1;++j) x[Xj[j]] = Xv[j];\n'+ ' j0 = Zi[i]; j1 = Zi[i+1];\n'+ ' for(j=j0;j!==j1;++j) {\n'+ ' k = Zj[j];\n'+ ' xk = x[k];\n'+ ' yk = y[k];\n'+ body+'\n'+ ' Zv[j] = zk;\n'+ ' }\n'+ ' j0 = Xi[i]; j1 = Xi[i+1];\n'+ ' for(j=j0;j!==j1;++j) x[Xj[j]] = 0;\n'+ ' j0 = Yi[i]; j1 = Yi[i+1];\n'+ ' for(j=j0;j!==j1;++j) y[Yj[j]] = 0;\n'+ '}\n'+ 'return [Zi,Zj,Zv];' ); }; (function() { var k,A,B,C; for(k in numeric.ops2) { if(isFinite(eval('1'+numeric.ops2[k]+'0'))) A = '[Y[0],Y[1],numeric.'+k+'(X,Y[2])]'; else A = 'NaN'; if(isFinite(eval('0'+numeric.ops2[k]+'1'))) B = '[X[0],X[1],numeric.'+k+'(X[2],Y)]'; else B = 'NaN'; if(isFinite(eval('1'+numeric.ops2[k]+'0')) && isFinite(eval('0'+numeric.ops2[k]+'1'))) C = 'numeric.ccs'+k+'MM(X,Y)'; else C = 'NaN'; numeric['ccs'+k+'MM'] = numeric.ccsbinop('zk = xk '+numeric.ops2[k]+'yk;'); numeric['ccs'+k] = Function('X','Y', 'if(typeof X === "number") return '+A+';\n'+ 'if(typeof Y === "number") return '+B+';\n'+ 'return '+C+';\n' ); } }()); numeric.ccsScatter = function ccsScatter(A) { var Ai = A[0], Aj = A[1], Av = A[2]; var n = numeric.sup(Aj)+1,m=Ai.length; var Ri = numeric.rep([n],0),Rj=Array(m), Rv = Array(m); var counts = numeric.rep([n],0),i; for(i=0;i<m;++i) counts[Aj[i]]++; for(i=0;i<n;++i) Ri[i+1] = Ri[i] + counts[i]; var ptr = Ri.slice(0),k,Aii; for(i=0;i<m;++i) { Aii = Aj[i]; k = ptr[Aii]; Rj[k] = Ai[i]; Rv[k] = Av[i]; ptr[Aii]=ptr[Aii]+1; } return [Ri,Rj,Rv]; } numeric.ccsGather = function ccsGather(A) { var Ai = A[0], Aj = A[1], Av = A[2]; var n = Ai.length-1,m = Aj.length; var Ri = Array(m), Rj = Array(m), Rv = Array(m); var i,j,j0,j1,p; p=0; for(i=0;i<n;++i) { j0 = Ai[i]; j1 = Ai[i+1]; for(j=j0;j!==j1;++j) { Rj[p] = i; Ri[p] = Aj[j]; Rv[p] = Av[j]; ++p; } } return [Ri,Rj,Rv]; } // The following sparse linear algebra routines are deprecated. numeric.sdim = function dim(A,ret,k) { if(typeof ret === "undefined") { ret = []; } if(typeof A !== "object") return ret; if(typeof k === "undefined") { k=0; } if(!(k in ret)) { ret[k] = 0; } if(A.length > ret[k]) ret[k] = A.length; var i; for(i in A) { if(A.hasOwnProperty(i)) dim(A[i],ret,k+1); } return ret; }; numeric.sclone = function clone(A,k,n) { if(typeof k === "undefined") { k=0; } if(typeof n === "undefined") { n = numeric.sdim(A).length; } var i,ret = Array(A.length); if(k === n-1) { for(i in A) { if(A.hasOwnProperty(i)) ret[i] = A[i]; } return ret; } for(i in A) { if(A.hasOwnProperty(i)) ret[i] = clone(A[i],k+1,n); } return ret; } numeric.sdiag = function diag(d) { var n = d.length,i,ret = Array(n),i1,i2,i3; for(i=n-1;i>=1;i-=2) { i1 = i-1; ret[i] = []; ret[i][i] = d[i]; ret[i1] = []; ret[i1][i1] = d[i1]; } if(i===0) { ret[0] = []; ret[0][0] = d[i]; } return ret; } numeric.sidentity = function identity(n) { return numeric.sdiag(numeric.rep([n],1)); } numeric.stranspose = function transpose(A) { var ret = [], n = A.length, i,j,Ai; for(i in A) { if(!(A.hasOwnProperty(i))) continue; Ai = A[i]; for(j in Ai) { if(!(Ai.hasOwnProperty(j))) continue; if(typeof ret[j] !== "object") { ret[j] = []; } ret[j][i] = Ai[j]; } } return ret; } numeric.sLUP = function LUP(A,tol) { throw new Error("The function numeric.sLUP had a bug in it and has been removed. Please use the new numeric.ccsLUP function instead."); }; numeric.sdotMM = function dotMM(A,B) { var p = A.length, q = B.length, BT = numeric.stranspose(B), r = BT.length, Ai, BTk; var i,j,k,accum; var ret = Array(p),reti; for(i=p-1;i>=0;i--) { reti = []; Ai = A[i]; for(k=r-1;k>=0;k--) { accum = 0; BTk = BT[k]; for(j in Ai) { if(!(Ai.hasOwnProperty(j))) continue; if(j in BTk) { accum += Ai[j]*BTk[j]; } } if(accum) reti[k] = accum; } ret[i] = reti; } return ret; } numeric.sdotMV = function dotMV(A,x) { var p = A.length, Ai, i,j; var ret = Array(p), accum; for(i=p-1;i>=0;i--) { Ai = A[i]; accum = 0; for(j in Ai) { if(!(Ai.hasOwnProperty(j))) continue; if(x[j]) accum += Ai[j]*x[j]; } if(accum) ret[i] = accum; } return ret; } numeric.sdotVM = function dotMV(x,A) { var i,j,Ai,alpha; var ret = [], accum; for(i in x) { if(!x.hasOwnProperty(i)) continue; Ai = A[i]; alpha = x[i]; for(j in Ai) { if(!Ai.hasOwnProperty(j)) continue; if(!ret[j]) { ret[j] = 0; } ret[j] += alpha*Ai[j]; } } return ret; } numeric.sdotVV = function dotVV(x,y) { var i,ret=0; for(i in x) { if(x[i] && y[i]) ret+= x[i]*y[i]; } return ret; } numeric.sdot = function dot(A,B) { var m = numeric.sdim(A).length, n = numeric.sdim(B).length; var k = m*1000+n; switch(k) { case 0: return A*B; case 1001: return numeric.sdotVV(A,B); case 2001: return numeric.sdotMV(A,B); case 1002: return numeric.sdotVM(A,B); case 2002: return numeric.sdotMM(A,B); default: throw new Error('numeric.sdot not implemented for tensors of order '+m+' and '+n); } } numeric.sscatter = function scatter(V) { var n = V[0].length, Vij, i, j, m = V.length, A = [], Aj; for(i=n-1;i>=0;--i) { if(!V[m-1][i]) continue; Aj = A; for(j=0;j<m-2;j++) { Vij = V[j][i]; if(!Aj[Vij]) Aj[Vij] = []; Aj = Aj[Vij]; } Aj[V[j][i]] = V[j+1][i]; } return A; } numeric.sgather = function gather(A,ret,k) { if(typeof ret === "undefined") ret = []; if(typeof k === "undefined") k = []; var n,i,Ai; n = k.length; for(i in A) { if(A.hasOwnProperty(i)) { k[n] = parseInt(i); Ai = A[i]; if(typeof Ai === "number") { if(Ai) { if(ret.length === 0) { for(i=n+1;i>=0;--i) ret[i] = []; } for(i=n;i>=0;--i) ret[i].push(k[i]); ret[n+1].push(Ai); } } else gather(Ai,ret,k); } } if(k.length>n) k.pop(); return ret; } // 6. Coordinate matrices numeric.cLU = function LU(A) { var I = A[0], J = A[1], V = A[2]; var p = I.length, m=0, i,j,k,a,b,c; for(i=0;i<p;i++) if(I[i]>m) m=I[i]; m++; var L = Array(m), U = Array(m), left = numeric.rep([m],Infinity), right = numeric.rep([m],-Infinity); var Ui, Uj,alpha; for(k=0;k<p;k++) { i = I[k]; j = J[k]; if(j<left[i]) left[i] = j; if(j>right[i]) right[i] = j; } for(i=0;i<m-1;i++) { if(right[i] > right[i+1]) right[i+1] = right[i]; } for(i=m-1;i>=1;i--) { if(left[i]<left[i-1]) left[i-1] = left[i]; } var countL = 0, countU = 0; for(i=0;i<m;i++) { U[i] = numeric.rep([right[i]-left[i]+1],0); L[i] = numeric.rep([i-left[i]],0); countL += i-left[i]+1; countU += right[i]-i+1; } for(k=0;k<p;k++) { i = I[k]; U[i][J[k]-left[i]] = V[k]; } for(i=0;i<m-1;i++) { a = i-left[i]; Ui = U[i]; for(j=i+1;left[j]<=i && j<m;j++) { b = i-left[j]; c = right[i]-i; Uj = U[j]; alpha = Uj[b]/Ui[a]; if(alpha) { for(k=1;k<=c;k++) { Uj[k+b] -= alpha*Ui[k+a]; } L[j][i-left[j]] = alpha; } } } var Ui = [], Uj = [], Uv = [], Li = [], Lj = [], Lv = []; var p,q,foo; p=0; q=0; for(i=0;i<m;i++) { a = left[i]; b = right[i]; foo = U[i]; for(j=i;j<=b;j++) { if(foo[j-a]) { Ui[p] = i; Uj[p] = j; Uv[p] = foo[j-a]; p++; } } foo = L[i]; for(j=a;j<i;j++) { if(foo[j-a]) { Li[q] = i; Lj[q] = j; Lv[q] = foo[j-a]; q++; } } Li[q] = i; Lj[q] = i; Lv[q] = 1; q++; } return {U:[Ui,Uj,Uv], L:[Li,Lj,Lv]}; }; numeric.cLUsolve = function LUsolve(lu,b) { var L = lu.L, U = lu.U, ret = numeric.clone(b); var Li = L[0], Lj = L[1], Lv = L[2]; var Ui = U[0], Uj = U[1], Uv = U[2]; var p = Ui.length, q = Li.length; var m = ret.length,i,j,k; k = 0; for(i=0;i<m;i++) { while(Lj[k] < i) { ret[i] -= Lv[k]*ret[Lj[k]]; k++; } k++; } k = p-1; for(i=m-1;i>=0;i--) { while(Uj[k] > i) { ret[i] -= Uv[k]*ret[Uj[k]]; k--; } ret[i] /= Uv[k]; k--; } return ret; }; numeric.cgrid = function grid(n,shape) { if(typeof n === "number") n = [n,n]; var ret = numeric.rep(n,-1); var i,j,count; if(typeof shape !== "function") { switch(shape) { case 'L': shape = function(i,j) { return (i>=n[0]/2 || j<n[1]/2); } break; default: shape = function(i,j) { return true; }; break; } } count=0; for(i=1;i<n[0]-1;i++) for(j=1;j<n[1]-1;j++) if(shape(i,j)) { ret[i][j] = count; count++; } return ret; } numeric.cdelsq = function delsq(g) { var dir = [[-1,0],[0,-1],[0,1],[1,0]]; var s = numeric.dim(g), m = s[0], n = s[1], i,j,k,p,q; var Li = [], Lj = [], Lv = []; for(i=1;i<m-1;i++) for(j=1;j<n-1;j++) { if(g[i][j]<0) continue; for(k=0;k<4;k++) { p = i+dir[k][0]; q = j+dir[k][1]; if(g[p][q]<0) continue; Li.push(g[i][j]); Lj.push(g[p][q]); Lv.push(-1); } Li.push(g[i][j]); Lj.push(g[i][j]); Lv.push(4); } return [Li,Lj,Lv]; } numeric.cdotMV = function dotMV(A,x) { var ret, Ai = A[0], Aj = A[1], Av = A[2],k,p=Ai.length,N; N=0; for(k=0;k<p;k++) { if(Ai[k]>N) N = Ai[k]; } N++; ret = numeric.rep([N],0); for(k=0;k<p;k++) { ret[Ai[k]]+=Av[k]*x[Aj[k]]; } return ret; } // 7. Splines numeric.Spline = function Spline(x,yl,yr,kl,kr) { this.x = x; this.yl = yl; this.yr = yr; this.kl = kl; this.kr = kr; } numeric.Spline.prototype._at = function _at(x1,p) { var x = this.x; var yl = this.yl; var yr = this.yr; var kl = this.kl; var kr = this.kr; var x1,a,b,t; var add = numeric.add, sub = numeric.sub, mul = numeric.mul; a = sub(mul(kl[p],x[p+1]-x[p]),sub(yr[p+1],yl[p])); b = add(mul(kr[p+1],x[p]-x[p+1]),sub(yr[p+1],yl[p])); t = (x1-x[p])/(x[p+1]-x[p]); var s = t*(1-t); return add(add(add(mul(1-t,yl[p]),mul(t,yr[p+1])),mul(a,s*(1-t))),mul(b,s*t)); } numeric.Spline.prototype.at = function at(x0) { if(typeof x0 === "number") { var x = this.x; var n = x.length; var p,q,mid,floor = Math.floor,a,b,t; p = 0; q = n-1; while(q-p>1) { mid = floor((p+q)/2); if(x[mid] <= x0) p = mid; else q = mid; } return this._at(x0,p); } var n = x0.length, i, ret = Array(n); for(i=n-1;i!==-1;--i) ret[i] = this.at(x0[i]); return ret; } numeric.Spline.prototype.diff = function diff() { var x = this.x; var yl = this.yl; var yr = this.yr; var kl = this.kl; var kr = this.kr; var n = yl.length; var i,dx,dy; var zl = kl, zr = kr, pl = Array(n), pr = Array(n); var add = numeric.add, mul = numeric.mul, div = numeric.div, sub = numeric.sub; for(i=n-1;i!==-1;--i) { dx = x[i+1]-x[i]; dy = sub(yr[i+1],yl[i]); pl[i] = div(add(mul(dy, 6),mul(kl[i],-4*dx),mul(kr[i+1],-2*dx)),dx*dx); pr[i+1] = div(add(mul(dy,-6),mul(kl[i], 2*dx),mul(kr[i+1], 4*dx)),dx*dx); } return new numeric.Spline(x,zl,zr,pl,pr); } numeric.Spline.prototype.roots = function roots() { function sqr(x) { return x*x; } function heval(y0,y1,k0,k1,x) { var A = k0*2-(y1-y0); var B = -k1*2+(y1-y0); var t = (x+1)*0.5; var s = t*(1-t); return (1-t)*y0+t*y1+A*s*(1-t)+B*s*t; } var ret = []; var x = this.x, yl = this.yl, yr = this.yr, kl = this.kl, kr = this.kr; if(typeof yl[0] === "number") { yl = [yl]; yr = [yr]; kl = [kl]; kr = [kr]; } var m = yl.length,n=x.length-1,i,j,k,y,s,t; var ai,bi,ci,di, ret = Array(m),ri,k0,k1,y0,y1,A,B,D,dx,cx,stops,z0,z1,zm,t0,t1,tm; var sqrt = Math.sqrt; for(i=0;i!==m;++i) { ai = yl[i]; bi = yr[i]; ci = kl[i]; di = kr[i]; ri = []; for(j=0;j!==n;j++) { if(j>0 && bi[j]*ai[j]<0) ri.push(x[j]); dx = (x[j+1]-x[j]); cx = x[j]; y0 = ai[j]; y1 = bi[j+1]; k0 = ci[j]/dx; k1 = di[j+1]/dx; D = sqr(k0-k1+3*(y0-y1)) + 12*k1*y0; A = k1+3*y0+2*k0-3*y1; B = 3*(k1+k0+2*(y0-y1)); if(D<=0) { z0 = A/B; if(z0>x[j] && z0<x[j+1]) stops = [x[j],z0,x[j+1]]; else stops = [x[j],x[j+1]]; } else { z0 = (A-sqrt(D))/B; z1 = (A+sqrt(D))/B; stops = [x[j]]; if(z0>x[j] && z0<x[j+1]) stops.push(z0); if(z1>x[j] && z1<x[j+1]) stops.push(z1); stops.push(x[j+1]); } t0 = stops[0]; z0 = this._at(t0,j); for(k=0;k<stops.length-1;k++) { t1 = stops[k+1]; z1 = this._at(t1,j); if(z0 === 0) { ri.push(t0); t0 = t1; z0 = z1; continue; } if(z1 === 0 || z0*z1>0) { t0 = t1; z0 = z1; continue; } var side = 0; while(1) { tm = (z0*t1-z1*t0)/(z0-z1); if(tm <= t0 || tm >= t1) { break; } zm = this._at(tm,j); if(zm*z1>0) { t1 = tm; z1 = zm; if(side === -1) z0*=0.5; side = -1; } else if(zm*z0>0) { t0 = tm; z0 = zm; if(side === 1) z1*=0.5; side = 1; } else break; } ri.push(tm); t0 = stops[k+1]; z0 = this._at(t0, j); } if(z1 === 0) ri.push(t1); } ret[i] = ri; } if(typeof this.yl[0] === "number") return ret[0]; return ret; } numeric.spline = function spline(x,y,k1,kn) { var n = x.length, b = [], dx = [], dy = []; var i; var sub = numeric.sub,mul = numeric.mul,add = numeric.add; for(i=n-2;i>=0;i--) { dx[i] = x[i+1]-x[i]; dy[i] = sub(y[i+1],y[i]); } if(typeof k1 === "string" || typeof kn === "string") { k1 = kn = "periodic"; } // Build sparse tridiagonal system var T = [[],[],[]]; switch(typeof k1) { case "undefined": b[0] = mul(3/(dx[0]*dx[0]),dy[0]); T[0].push(0,0); T[1].push(0,1); T[2].push(2/dx[0],1/dx[0]); break; case "string": b[0] = add(mul(3/(dx[n-2]*dx[n-2]),dy[n-2]),mul(3/(dx[0]*dx[0]),dy[0])); T[0].push(0,0,0); T[1].push(n-2,0,1); T[2].push(1/dx[n-2],2/dx[n-2]+2/dx[0],1/dx[0]); break; default: b[0] = k1; T[0].push(0); T[1].push(0); T[2].push(1); break; } for(i=1;i<n-1;i++) { b[i] = add(mul(3/(dx[i-1]*dx[i-1]),dy[i-1]),mul(3/(dx[i]*dx[i]),dy[i])); T[0].push(i,i,i); T[1].push(i-1,i,i+1); T[2].push(1/dx[i-1],2/dx[i-1]+2/dx[i],1/dx[i]); } switch(typeof kn) { case "undefined": b[n-1] = mul(3/(dx[n-2]*dx[n-2]),dy[n-2]); T[0].push(n-1,n-1); T[1].push(n-2,n-1); T[2].push(1/dx[n-2],2/dx[n-2]); break; case "string": T[1][T[1].length-1] = 0; break; default: b[n-1] = kn; T[0].push(n-1); T[1].push(n-1); T[2].push(1); break; } if(typeof b[0] !== "number") b = numeric.transpose(b); else b = [b]; var k = Array(b.length); if(typeof k1 === "string") { for(i=k.length-1;i!==-1;--i) { k[i] = numeric.ccsLUPSolve(numeric.ccsLUP(numeric.ccsScatter(T)),b[i]); k[i][n-1] = k[i][0]; } } else { for(i=k.length-1;i!==-1;--i) { k[i] = numeric.cLUsolve(numeric.cLU(T),b[i]); } } if(typeof y[0] === "number") k = k[0]; else k = numeric.transpose(k); return new numeric.Spline(x,y,y,k,k); } // 8. FFT numeric.fftpow2 = function fftpow2(x,y) { var n = x.length; if(n === 1) return; var cos = Math.cos, sin = Math.sin, i,j; var xe = Array(n/2), ye = Array(n/2), xo = Array(n/2), yo = Array(n/2); j = n/2; for(i=n-1;i!==-1;--i) { --j; xo[j] = x[i]; yo[j] = y[i]; --i; xe[j] = x[i]; ye[j] = y[i]; } fftpow2(xe,ye); fftpow2(xo,yo); j = n/2; var t,k = (-6.2831853071795864769252867665590057683943387987502116419/n),ci,si; for(i=n-1;i!==-1;--i) { --j; if(j === -1) j = n/2-1; t = k*i; ci = cos(t); si = sin(t); x[i] = xe[j] + ci*xo[j] - si*yo[j]; y[i] = ye[j] + ci*yo[j] + si*xo[j]; } } numeric._ifftpow2 = function _ifftpow2(x,y) { var n = x.length; if(n === 1) return; var cos = Math.cos, sin = Math.sin, i,j; var xe = Array(n/2), ye = Array(n/2), xo = Array(n/2), yo = Array(n/2); j = n/2; for(i=n-1;i!==-1;--i) { --j; xo[j] = x[i]; yo[j] = y[i]; --i; xe[j] = x[i]; ye[j] = y[i]; } _ifftpow2(xe,ye); _ifftpow2(xo,yo); j = n/2; var t,k = (6.2831853071795864769252867665590057683943387987502116419/n),ci,si; for(i=n-1;i!==-1;--i) { --j; if(j === -1) j = n/2-1; t = k*i; ci = cos(t); si = sin(t); x[i] = xe[j] + ci*xo[j] - si*yo[j]; y[i] = ye[j] + ci*yo[j] + si*xo[j]; } } numeric.ifftpow2 = function ifftpow2(x,y) { numeric._ifftpow2(x,y); numeric.diveq(x,x.length); numeric.diveq(y,y.length); } numeric.convpow2 = function convpow2(ax,ay,bx,by) { numeric.fftpow2(ax,ay); numeric.fftpow2(bx,by); var i,n = ax.length,axi,bxi,ayi,byi; for(i=n-1;i!==-1;--i) { axi = ax[i]; ayi = ay[i]; bxi = bx[i]; byi = by[i]; ax[i] = axi*bxi-ayi*byi; ay[i] = axi*byi+ayi*bxi; } numeric.ifftpow2(ax,ay); } numeric.T.prototype.fft = function fft() { var x = this.x, y = this.y; var n = x.length, log = Math.log, log2 = log(2), p = Math.ceil(log(2*n-1)/log2), m = Math.pow(2,p); var cx = numeric.rep([m],0), cy = numeric.rep([m],0), cos = Math.cos, sin = Math.sin; var k, c = (-3.141592653589793238462643383279502884197169399375105820/n),t; var a = numeric.rep([m],0), b = numeric.rep([m],0),nhalf = Math.floor(n/2); for(k=0;k<n;k++) a[k] = x[k]; if(typeof y !== "undefined") for(k=0;k<n;k++) b[k] = y[k]; cx[0] = 1; for(k=1;k<=m/2;k++) { t = c*k*k; cx[k] = cos(t); cy[k] = sin(t); cx[m-k] = cos(t); cy[m-k] = sin(t) } var X = new numeric.T(a,b), Y = new numeric.T(cx,cy); X = X.mul(Y); numeric.convpow2(X.x,X.y,numeric.clone(Y.x),numeric.neg(Y.y)); X = X.mul(Y); X.x.length = n; X.y.length = n; return X; } numeric.T.prototype.ifft = function ifft() { var x = this.x, y = this.y; var n = x.length, log = Math.log, log2 = log(2), p = Math.ceil(log(2*n-1)/log2), m = Math.pow(2,p); var cx = numeric.rep([m],0), cy = numeric.rep([m],0), cos = Math.cos, sin = Math.sin; var k, c = (3.141592653589793238462643383279502884197169399375105820/n),t; var a = numeric.rep([m],0), b = numeric.rep([m],0),nhalf = Math.floor(n/2); for(k=0;k<n;k++) a[k] = x[k]; if(typeof y !== "undefined") for(k=0;k<n;k++) b[k] = y[k]; cx[0] = 1; for(k=1;k<=m/2;k++) { t = c*k*k; cx[k] = cos(t); cy[k] = sin(t); cx[m-k] = cos(t); cy[m-k] = sin(t) } var X = new numeric.T(a,b), Y = new numeric.T(cx,cy); X = X.mul(Y); numeric.convpow2(X.x,X.y,numeric.clone(Y.x),numeric.neg(Y.y)); X = X.mul(Y); X.x.length = n; X.y.length = n; return X.div(n); } //9. Unconstrained optimization numeric.gradient = function gradient(f,x) { var n = x.length; var f0 = f(x); if(isNaN(f0)) throw new Error('gradient: f(x) is a NaN!'); var max = Math.max; var i,x0 = numeric.clone(x),f1,f2, J = Array(n); var div = numeric.div, sub = numeric.sub,errest,roundoff,max = Math.max,eps = 1e-3,abs = Math.abs, min = Math.min; var t0,t1,t2,it=0,d1,d2,N; for(i=0;i<n;i++) { var h = max(1e-6*f0,1e-8); while(1) { ++it; if(it>20) { throw new Error("Numerical gradient fails"); } x0[i] = x[i]+h; f1 = f(x0); x0[i] = x[i]-h; f2 = f(x0); x0[i] = x[i]; if(isNaN(f1) || isNaN(f2)) { h/=16; continue; } J[i] = (f1-f2)/(2*h); t0 = x[i]-h; t1 = x[i]; t2 = x[i]+h; d1 = (f1-f0)/h; d2 = (f0-f2)/h; N = max(abs(J[i]),abs(f0),abs(f1),abs(f2),abs(t0),abs(t1),abs(t2),1e-8); errest = min(max(abs(d1-J[i]),abs(d2-J[i]),abs(d1-d2))/N,h/N); if(errest>eps) { h/=16; } else break; } } return J; } numeric.uncmin = function uncmin(f,x0,tol,gradient,maxit,callback,options) { var grad = numeric.gradient; if(typeof options === "undefined") { options = {}; } if(typeof tol === "undefined") { tol = 1e-8; } if(typeof gradient === "undefined") { gradient = function(x) { return grad(f,x); }; } if(typeof maxit === "undefined") maxit = 1000; x0 = numeric.clone(x0); var n = x0.length; var f0 = f(x0),f1,df0; if(isNaN(f0)) throw new Error('uncmin: f(x0) is a NaN!'); var max = Math.max, norm2 = numeric.norm2; tol = max(tol,numeric.epsilon); var step,g0,g1,H1 = options.Hinv || numeric.identity(n); var dot = numeric.dot, inv = numeric.inv, sub = numeric.sub, add = numeric.add, ten = numeric.tensor, div = numeric.div, mul = numeric.mul; var all = numeric.all, isfinite = numeric.isFinite, neg = numeric.neg; var it=0,i,s,x1,y,Hy,Hs,ys,i0,t,nstep,t1,t2; var msg = ""; g0 = gradient(x0); while(it<maxit) { if(typeof callback === "function") { if(callback(it,x0,f0,g0,H1)) { msg = "Callback returned true"; break; } } if(!all(isfinite(g0))) { msg = "Gradient has Infinity or NaN"; break; } step = neg(dot(H1,g0)); if(!all(isfinite(step))) { msg = "Search direction has Infinity or NaN"; break; } nstep = norm2(step); if(nstep < tol) { msg="Newton step smaller than tol"; break; } t = 1; df0 = dot(g0,step); // line search x1 = x0; while(it < maxit) { if(t*nstep < tol) { break; } s = mul(step,t); x1 = add(x0,s); f1 = f(x1); if(f1-f0 >= 0.1*t*df0 || isNaN(f1)) { t *= 0.5; ++it; continue; } break; } if(t*nstep < tol) { msg = "Line search step size smaller than tol"; break; } if(it === maxit) { msg = "maxit reached during line search"; break; } g1 = gradient(x1); y = sub(g1,g0); ys = dot(y,s); Hy = dot(H1,y); H1 = sub(add(H1, mul( (ys+dot(y,Hy))/(ys*ys), ten(s,s) )), div(add(ten(Hy,s),ten(s,Hy)),ys)); x0 = x1; f0 = f1; g0 = g1; ++it; } return {solution: x0, f: f0, gradient: g0, invHessian: H1, iterations:it, message: msg}; } // 10. Ode solver (Dormand-Prince) numeric.Dopri = function Dopri(x,y,f,ymid,iterations,msg,events) { this.x = x; this.y = y; this.f = f; this.ymid = ymid; this.iterations = iterations; this.events = events; this.message = msg; } numeric.Dopri.prototype._at = function _at(xi,j) { function sqr(x) { return x*x; } var sol = this; var xs = sol.x; var ys = sol.y; var k1 = sol.f; var ymid = sol.ymid; var n = xs.length; var x0,x1,xh,y0,y1,yh,xi; var floor = Math.floor,h; var c = 0.5; var add = numeric.add, mul = numeric.mul,sub = numeric.sub, p,q,w; x0 = xs[j]; x1 = xs[j+1]; y0 = ys[j]; y1 = ys[j+1]; h = x1-x0; xh = x0+c*h; yh = ymid[j]; p = sub(k1[j ],mul(y0,1/(x0-xh)+2/(x0-x1))); q = sub(k1[j+1],mul(y1,1/(x1-xh)+2/(x1-x0))); w = [sqr(xi - x1) * (xi - xh) / sqr(x0 - x1) / (x0 - xh), sqr(xi - x0) * sqr(xi - x1) / sqr(x0 - xh) / sqr(x1 - xh), sqr(xi - x0) * (xi - xh) / sqr(x1 - x0) / (x1 - xh), (xi - x0) * sqr(xi - x1) * (xi - xh) / sqr(x0-x1) / (x0 - xh), (xi - x1) * sqr(xi - x0) * (xi - xh) / sqr(x0-x1) / (x1 - xh)]; return add(add(add(add(mul(y0,w[0]), mul(yh,w[1])), mul(y1,w[2])), mul( p,w[3])), mul( q,w[4])); } numeric.Dopri.prototype.at = function at(x) { var i,j,k,floor = Math.floor; if(typeof x !== "number") { var n = x.length, ret = Array(n); for(i=n-1;i!==-1;--i) { ret[i] = this.at(x[i]); } return ret; } var x0 = this.x; i = 0; j = x0.length-1; while(j-i>1) { k = floor(0.5*(i+j)); if(x0[k] <= x) i = k; else j = k; } return this._at(x,i); } numeric.dopri = function dopri(x0,x1,y0,f,tol,maxit,event) { if(typeof tol === "undefined") { tol = 1e-6; } if(typeof maxit === "undefined") { maxit = 1000; } var xs = [x0], ys = [y0], k1 = [f(x0,y0)], k2,k3,k4,k5,k6,k7, ymid = []; var A2 = 1/5; var A3 = [3/40,9/40]; var A4 = [44/45,-56/15,32/9]; var A5 = [19372/6561,-25360/2187,64448/6561,-212/729]; var A6 = [9017/3168,-355/33,46732/5247,49/176,-5103/18656]; var b = [35/384,0,500/1113,125/192,-2187/6784,11/84]; var bm = [0.5*6025192743/30085553152, 0, 0.5*51252292925/65400821598, 0.5*-2691868925/45128329728, 0.5*187940372067/1594534317056, 0.5*-1776094331/19743644256, 0.5*11237099/235043384]; var c = [1/5,3/10,4/5,8/9,1,1]; var e = [-71/57600,0,71/16695,-71/1920,17253/339200,-22/525,1/40]; var i = 0,er,j; var h = (x1-x0)/10; var it = 0; var add = numeric.add, mul = numeric.mul, y1,erinf; var max = Math.max, min = Math.min, abs = Math.abs, norminf = numeric.norminf,pow = Math.pow; var any = numeric.any, lt = numeric.lt, and = numeric.and, sub = numeric.sub; var e0, e1, ev; var ret = new numeric.Dopri(xs,ys,k1,ymid,-1,""); if(typeof event === "function") e0 = event(x0,y0); while(x0<x1 && it<maxit) { ++it; if(x0+h>x1) h = x1-x0; k2 = f(x0+c[0]*h, add(y0,mul( A2*h,k1[i]))); k3 = f(x0+c[1]*h, add(add(y0,mul(A3[0]*h,k1[i])),mul(A3[1]*h,k2))); k4 = f(x0+c[2]*h, add(add(add(y0,mul(A4[0]*h,k1[i])),mul(A4[1]*h,k2)),mul(A4[2]*h,k3))); k5 = f(x0+c[3]*h, add(add(add(add(y0,mul(A5[0]*h,k1[i])),mul(A5[1]*h,k2)),mul(A5[2]*h,k3)),mul(A5[3]*h,k4))); k6 = f(x0+c[4]*h,add(add(add(add(add(y0,mul(A6[0]*h,k1[i])),mul(A6[1]*h,k2)),mul(A6[2]*h,k3)),mul(A6[3]*h,k4)),mul(A6[4]*h,k5))); y1 = add(add(add(add(add(y0,mul(k1[i],h*b[0])),mul(k3,h*b[2])),mul(k4,h*b[3])),mul(k5,h*b[4])),mul(k6,h*b[5])); k7 = f(x0+h,y1); er = add(add(add(add(add(mul(k1[i],h*e[0]),mul(k3,h*e[2])),mul(k4,h*e[3])),mul(k5,h*e[4])),mul(k6,h*e[5])),mul(k7,h*e[6])); if(typeof er === "number") erinf = abs(er); else erinf = norminf(er); if(erinf > tol) { // reject h = 0.2*h*pow(tol/erinf,0.25); if(x0+h === x0) { ret.msg = "Step size became too small"; break; } continue; } ymid[i] = add(add(add(add(add(add(y0, mul(k1[i],h*bm[0])), mul(k3 ,h*bm[2])), mul(k4 ,h*bm[3])), mul(k5 ,h*bm[4])), mul(k6 ,h*bm[5])), mul(k7 ,h*bm[6])); ++i; xs[i] = x0+h; ys[i] = y1; k1[i] = k7; if(typeof event === "function") { var yi,xl = x0,xr = x0+0.5*h,xi; e1 = event(xr,ymid[i-1]); ev = and(lt(e0,0),lt(0,e1)); if(!any(ev)) { xl = xr; xr = x0+h; e0 = e1; e1 = event(xr,y1); ev = and(lt(e0,0),lt(0,e1)); } if(any(ev)) { var xc, yc, en,ei; var side=0, sl = 1.0, sr = 1.0; while(1) { if(typeof e0 === "number") xi = (sr*e1*xl-sl*e0*xr)/(sr*e1-sl*e0); else { xi = xr; for(j=e0.length-1;j!==-1;--j) { if(e0[j]<0 && e1[j]>0) xi = min(xi,(sr*e1[j]*xl-sl*e0[j]*xr)/(sr*e1[j]-sl*e0[j])); } } if(xi <= xl || xi >= xr) break; yi = ret._at(xi, i-1); ei = event(xi,yi); en = and(lt(e0,0),lt(0,ei)); if(any(en)) { xr = xi; e1 = ei; ev = en; sr = 1.0; if(side === -1) sl *= 0.5; else sl = 1.0; side = -1; } else { xl = xi; e0 = ei; sl = 1.0; if(side === 1) sr *= 0.5; else sr = 1.0; side = 1; } } y1 = ret._at(0.5*(x0+xi),i-1); ret.f[i] = f(xi,yi); ret.x[i] = xi; ret.y[i] = yi; ret.ymid[i-1] = y1; ret.events = ev; ret.iterations = it; return ret; } } x0 += h; y0 = y1; e0 = e1; h = min(0.8*h*pow(tol/erinf,0.25),4*h); } ret.iterations = it; return ret; } // 11. Ax = b numeric.LU = function(A, fast) { fast = fast || false; var abs = Math.abs; var i, j, k, absAjk, Akk, Ak, Pk, Ai; var max; var n = A.length, n1 = n-1; var P = new Array(n); if(!fast) A = numeric.clone(A); for (k = 0; k < n; ++k) { Pk = k; Ak = A[k]; max = abs(Ak[k]); for (j = k + 1; j < n; ++j) { absAjk = abs(A[j][k]); if (max < absAjk) { max = absAjk; Pk = j; } } P[k] = Pk; if (Pk != k) { A[k] = A[Pk]; A[Pk] = Ak; Ak = A[k]; } Akk = Ak[k]; for (i = k + 1; i < n; ++i) { A[i][k] /= Akk; } for (i = k + 1; i < n; ++i) { Ai = A[i]; for (j = k + 1; j < n1; ++j) { Ai[j] -= Ai[k] * Ak[j]; ++j; Ai[j] -= Ai[k] * Ak[j]; } if(j===n1) Ai[j] -= Ai[k] * Ak[j]; } } return { LU: A, P: P }; } numeric.LUsolve = function LUsolve(LUP, b) { var i, j; var LU = LUP.LU; var n = LU.length; var x = numeric.clone(b); var P = LUP.P; var Pi, LUi, LUii, tmp; for (i=n-1;i!==-1;--i) x[i] = b[i]; for (i = 0; i < n; ++i) { Pi = P[i]; if (P[i] !== i) { tmp = x[i]; x[i] = x[Pi]; x[Pi] = tmp; } LUi = LU[i]; for (j = 0; j < i; ++j) { x[i] -= x[j] * LUi[j]; } } for (i = n - 1; i >= 0; --i) { LUi = LU[i]; for (j = i + 1; j < n; ++j) { x[i] -= x[j] * LUi[j]; } x[i] /= LUi[i]; } return x; } numeric.solve = function solve(A,b,fast) { return numeric.LUsolve(numeric.LU(A,fast), b); } // 12. Linear programming numeric.echelonize = function echelonize(A) { var s = numeric.dim(A), m = s[0], n = s[1]; var I = numeric.identity(m); var P = Array(m); var i,j,k,l,Ai,Ii,Z,a; var abs = Math.abs; var diveq = numeric.diveq; A = numeric.clone(A); for(i=0;i<m;++i) { k = 0; Ai = A[i]; Ii = I[i]; for(j=1;j<n;++j) if(abs(Ai[k])<abs(Ai[j])) k=j; P[i] = k; diveq(Ii,Ai[k]); diveq(Ai,Ai[k]); for(j=0;j<m;++j) if(j!==i) { Z = A[j]; a = Z[k]; for(l=n-1;l!==-1;--l) Z[l] -= Ai[l]*a; Z = I[j]; for(l=m-1;l!==-1;--l) Z[l] -= Ii[l]*a; } } return {I:I, A:A, P:P}; } numeric.__solveLP = function __solveLP(c,A,b,tol,maxit,x,flag) { var sum = numeric.sum, log = numeric.log, mul = numeric.mul, sub = numeric.sub, dot = numeric.dot, div = numeric.div, add = numeric.add; var m = c.length, n = b.length,y; var unbounded = false, cb,i0=0; var alpha = 1.0; var f0,df0,AT = numeric.transpose(A), svd = numeric.svd,transpose = numeric.transpose,leq = numeric.leq, sqrt = Math.sqrt, abs = Math.abs; var muleq = numeric.muleq; var norm = numeric.norminf, any = numeric.any,min = Math.min; var all = numeric.all, gt = numeric.gt; var p = Array(m), A0 = Array(n),e=numeric.rep([n],1), H; var solve = numeric.solve, z = sub(b,dot(A,x)),count; var dotcc = dot(c,c); var g; for(count=i0;count<maxit;++count) { var i,j,d; for(i=n-1;i!==-1;--i) A0[i] = div(A[i],z[i]); var A1 = transpose(A0); for(i=m-1;i!==-1;--i) p[i] = (/*x[i]+*/sum(A1[i])); alpha = 0.25*abs(dotcc/dot(c,p)); var a1 = 100*sqrt(dotcc/dot(p,p)); if(!isFinite(alpha) || alpha>a1) alpha = a1; g = add(c,mul(alpha,p)); H = dot(A1,A0); for(i=m-1;i!==-1;--i) H[i][i] += 1; d = solve(H,div(g,alpha),true); var t0 = div(z,dot(A,d)); var t = 1.0; for(i=n-1;i!==-1;--i) if(t0[i]<0) t = min(t,-0.999*t0[i]); y = sub(x,mul(d,t)); z = sub(b,dot(A,y)); if(!all(gt(z,0))) return { solution: x, message: "", iterations: count }; x = y; if(alpha<tol) return { solution: y, message: "", iterations: count }; if(flag) { var s = dot(c,g), Ag = dot(A,g); unbounded = true; for(i=n-1;i!==-1;--i) if(s*Ag[i]<0) { unbounded = false; break; } } else { if(x[m-1]>=0) unbounded = false; else unbounded = true; } if(unbounded) return { solution: y, message: "Unbounded", iterations: count }; } return { solution: x, message: "maximum iteration count exceeded", iterations:count }; } numeric._solveLP = function _solveLP(c,A,b,tol,maxit) { var m = c.length, n = b.length,y; var sum = numeric.sum, log = numeric.log, mul = numeric.mul, sub = numeric.sub, dot = numeric.dot, div = numeric.div, add = numeric.add; var c0 = numeric.rep([m],0).concat([1]); var J = numeric.rep([n,1],-1); var A0 = numeric.blockMatrix([[A , J ]]); var b0 = b; var y = numeric.rep([m],0).concat(Math.max(0,numeric.sup(numeric.neg(b)))+1); var x0 = numeric.__solveLP(c0,A0,b0,tol,maxit,y,false); var x = numeric.clone(x0.solution); x.length = m; var foo = numeric.inf(sub(b,dot(A,x))); if(foo<0) { return { solution: NaN, message: "Infeasible", iterations: x0.iterations }; } var ret = numeric.__solveLP(c, A, b, tol, maxit-x0.iterations, x, true); ret.iterations += x0.iterations; return ret; }; numeric.solveLP = function solveLP(c,A,b,Aeq,beq,tol,maxit) { if(typeof maxit === "undefined") maxit = 1000; if(typeof tol === "undefined") tol = numeric.epsilon; if(typeof Aeq === "undefined") return numeric._solveLP(c,A,b,tol,maxit); var m = Aeq.length, n = Aeq[0].length, o = A.length; var B = numeric.echelonize(Aeq); var flags = numeric.rep([n],0); var P = B.P; var Q = []; var i; for(i=P.length-1;i!==-1;--i) flags[P[i]] = 1; for(i=n-1;i!==-1;--i) if(flags[i]===0) Q.push(i); var g = numeric.getRange; var I = numeric.linspace(0,m-1), J = numeric.linspace(0,o-1); var Aeq2 = g(Aeq,I,Q), A1 = g(A,J,P), A2 = g(A,J,Q), dot = numeric.dot, sub = numeric.sub; console.log('hi'); var A3 = dot(A1,B.I); var A4 = sub(A2,dot(A3,Aeq2)), b4 = sub(b,dot(A3,beq)); var c1 = Array(P.length), c2 = Array(Q.length); for(i=P.length-1;i!==-1;--i) c1[i] = c[P[i]]; for(i=Q.length-1;i!==-1;--i) c2[i] = c[Q[i]]; var c4 = sub(c2,dot(c1,dot(B.I,Aeq2))); var S = numeric._solveLP(c4,A4,b4,tol,maxit); var x2 = S.solution; var x1 = dot(B.I,sub(beq,dot(Aeq2,x2))); var x = Array(c.length); for(i=P.length-1;i!==-1;--i) x[P[i]] = x1[i]; for(i=Q.length-1;i!==-1;--i) x[Q[i]] = x2[i]; return { solution: x, message:S.message, iterations: S.iterations }; } numeric.MPStoLP = function MPStoLP(MPS) { if(MPS instanceof String) { MPS.split('\n'); } var state = 0; var states = ['Initial state','NAME','ROWS','COLUMNS','RHS','BOUNDS','ENDATA']; var n = MPS.length; var i,j,z,N=0,rows = {}, sign = [], rl = 0, vars = {}, nv = 0; var name; var c = [], A = [], b = []; function err(e) { throw new Error('MPStoLP: '+e+'\nLine '+i+': '+MPS[i]+'\nCurrent state: '+states[state]+'\n'); } for(i=0;i<n;++i) { z = MPS[i]; var w0 = z.match(/\S*/g); var w = []; for(j=0;j<w0.length;++j) if(w0[j]!=="") w.push(w0[j]); if(w.length === 0) continue; for(j=0;j<states.length;++j) if(z.substr(0,states[j].length) === states[j]) break; if(j<states.length) { state = j; if(j===1) { name = w[1]; } if(j===6) return { name:name, c:c, A:numeric.transpose(A), b:b, rows:rows, vars:vars }; continue; } switch(state) { case 0: case 1: err('Unexpected line'); case 2: switch(w[0]) { case 'N': if(N===0) N = w[1]; else err('Two or more N rows'); break; case 'L': rows[w[1]] = rl; sign[rl] = 1; b[rl] = 0; ++rl; break; case 'G': rows[w[1]] = rl; sign[rl] = -1;b[rl] = 0; ++rl; break; case 'E': rows[w[1]] = rl; sign[rl] = 0;b[rl] = 0; ++rl; break; default: err('Parse error '+numeric.prettyPrint(w)); } break; case 3: if(!vars.hasOwnProperty(w[0])) { vars[w[0]] = nv; c[nv] = 0; A[nv] = numeric.rep([rl],0); ++nv; } var p = vars[w[0]]; for(j=1;j<w.length;j+=2) { if(w[j] === N) { c[p] = parseFloat(w[j+1]); continue; } var q = rows[w[j]]; A[p][q] = (sign[q]<0?-1:1)*parseFloat(w[j+1]); } break; case 4: for(j=1;j<w.length;j+=2) b[rows[w[j]]] = (sign[rows[w[j]]]<0?-1:1)*parseFloat(w[j+1]); break; case 5: /*FIXME*/ break; case 6: err('Internal error'); } } err('Reached end of file without ENDATA'); } // seedrandom.js version 2.0. // Author: David Bau 4/2/2011 // // Defines a method Math.seedrandom() that, when called, substitutes // an explicitly seeded RC4-based algorithm for Math.random(). Also // supports automatic seeding from local or network sources of entropy. // // Usage: // // <script src=http://davidbau.com/encode/seedrandom-min.js></script> // // Math.seedrandom('yipee'); Sets Math.random to a function that is // initialized using the given explicit seed. // // Math.seedrandom(); Sets Math.random to a function that is // seeded using the current time, dom state, // and other accumulated local entropy. // The generated seed string is returned. // // Math.seedrandom('yowza', true); // Seeds using the given explicit seed mixed // together with accumulated entropy. // // <script src="http://bit.ly/srandom-512"></script> // Seeds using physical random bits downloaded // from random.org. // // <script src="https://jsonlib.appspot.com/urandom?callback=Math.seedrandom"> // </script> Seeds using urandom bits from call.jsonlib.com, // which is faster than random.org. // // Examples: // // Math.seedrandom("hello"); // Use "hello" as the seed. // document.write(Math.random()); // Always 0.5463663768140734 // document.write(Math.random()); // Always 0.43973793770592234 // var rng1 = Math.random; // Remember the current prng. // // var autoseed = Math.seedrandom(); // New prng with an automatic seed. // document.write(Math.random()); // Pretty much unpredictable. // // Math.random = rng1; // Continue "hello" prng sequence. // document.write(Math.random()); // Always 0.554769432473455 // // Math.seedrandom(autoseed); // Restart at the previous seed. // document.write(Math.random()); // Repeat the 'unpredictable' value. // // Notes: // // Each time seedrandom('arg') is called, entropy from the passed seed // is accumulated in a pool to help generate future seeds for the // zero-argument form of Math.seedrandom, so entropy can be injected over // time by calling seedrandom with explicit data repeatedly. // // On speed - This javascript implementation of Math.random() is about // 3-10x slower than the built-in Math.random() because it is not native // code, but this is typically fast enough anyway. Seeding is more expensive, // especially if you use auto-seeding. Some details (timings on Chrome 4): // // Our Math.random() - avg less than 0.002 milliseconds per call // seedrandom('explicit') - avg less than 0.5 milliseconds per call // seedrandom('explicit', true) - avg less than 2 milliseconds per call // seedrandom() - avg about 38 milliseconds per call // // LICENSE (BSD): // // Copyright 2010 David Bau, all rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. 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. // // 3. Neither the name of this module 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 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. // /** * All code is in an anonymous closure to keep the global namespace clean. * * @param {number=} overflow * @param {number=} startdenom */ // Patched by Seb so that seedrandom.js does not pollute the Math object. // My tests suggest that doing Math.trouble = 1 makes Math lookups about 5% // slower. numeric.seedrandom = { pow:Math.pow, random:Math.random }; (function (pool, math, width, chunks, significance, overflow, startdenom) { // // seedrandom() // This is the seedrandom function described above. // math['seedrandom'] = function seedrandom(seed, use_entropy) { var key = []; var arc4; // Flatten the seed string or build one from local entropy if needed. seed = mixkey(flatten( use_entropy ? [seed, pool] : arguments.length ? seed : [new Date().getTime(), pool, window], 3), key); // Use the seed to initialize an ARC4 generator. arc4 = new ARC4(key); // Mix the randomness into accumulated entropy. mixkey(arc4.S, pool); // Override Math.random // This function returns a random double in [0, 1) that contains // randomness in every bit of the mantissa of the IEEE 754 value. math['random'] = function random() { // Closure to return a random double: var n = arc4.g(chunks); // Start with a numerator n < 2 ^ 48 var d = startdenom; // and denominator d = 2 ^ 48. var x = 0; // and no 'extra last byte'. while (n < significance) { // Fill up all significant digits by n = (n + x) * width; // shifting numerator and d *= width; // denominator and generating a x = arc4.g(1); // new least-significant-byte. } while (n >= overflow) { // To avoid rounding up, before adding n /= 2; // last byte, shift everything d /= 2; // right using integer math until x >>>= 1; // we have exactly the desired bits. } return (n + x) / d; // Form the number within [0, 1). }; // Return the seed that was used return seed; }; // // ARC4 // // An ARC4 implementation. The constructor takes a key in the form of // an array of at most (width) integers that should be 0 <= x < (width). // // The g(count) method returns a pseudorandom integer that concatenates // the next (count) outputs from ARC4. Its return value is a number x // that is in the range 0 <= x < (width ^ count). // /** @constructor */ function ARC4(key) { var t, u, me = this, keylen = key.length; var i = 0, j = me.i = me.j = me.m = 0; me.S = []; me.c = []; // The empty key [] is treated as [0]. if (!keylen) { key = [keylen++]; } // Set up S using the standard key scheduling algorithm. while (i < width) { me.S[i] = i++; } for (i = 0; i < width; i++) { t = me.S[i]; j = lowbits(j + t + key[i % keylen]); u = me.S[j]; me.S[i] = u; me.S[j] = t; } // The "g" method returns the next (count) outputs as one number. me.g = function getnext(count) { var s = me.S; var i = lowbits(me.i + 1); var t = s[i]; var j = lowbits(me.j + t); var u = s[j]; s[i] = u; s[j] = t; var r = s[lowbits(t + u)]; while (--count) { i = lowbits(i + 1); t = s[i]; j = lowbits(j + t); u = s[j]; s[i] = u; s[j] = t; r = r * width + s[lowbits(t + u)]; } me.i = i; me.j = j; return r; }; // For robust unpredictability discard an initial batch of values. // See http://www.rsa.com/rsalabs/node.asp?id=2009 me.g(width); } // // flatten() // Converts an object tree to nested arrays of strings. // /** @param {Object=} result * @param {string=} prop * @param {string=} typ */ function flatten(obj, depth, result, prop, typ) { result = []; typ = typeof(obj); if (depth && typ == 'object') { for (prop in obj) { if (prop.indexOf('S') < 5) { // Avoid FF3 bug (local/sessionStorage) try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {} } } } return (result.length ? result : obj + (typ != 'string' ? '\0' : '')); } // // mixkey() // Mixes a string seed into a key that is an array of integers, and // returns a shortened string seed that is equivalent to the result key. // /** @param {number=} smear * @param {number=} j */ function mixkey(seed, key, smear, j) { seed += ''; // Ensure the seed is a string smear = 0; for (j = 0; j < seed.length; j++) { key[lowbits(j)] = lowbits((smear ^= key[lowbits(j)] * 19) + seed.charCodeAt(j)); } seed = ''; for (j in key) { seed += String.fromCharCode(key[j]); } return seed; } // // lowbits() // A quick "n mod width" for width a power of 2. // function lowbits(n) { return n & (width - 1); } // // The following constants are related to IEEE 754 limits. // startdenom = math.pow(width, chunks); significance = math.pow(2, significance); overflow = significance * 2; // // When seedrandom.js is loaded, we immediately mix a few bits // from the built-in RNG into the entropy pool. Because we do // not want to intefere with determinstic PRNG state later, // seedrandom will not call math.random on its own again after // initialization. // mixkey(math.random(), pool); // End anonymous scope, and pass initial values. }( [], // pool: entropy pool starts empty numeric.seedrandom, // math: package containing random, pow, and seedrandom 256, // width: each RC4 output is 0 <= x < 256 6, // chunks: at least six RC4 outputs for each double 52 // significance: there are 52 significant digits in a double )); /* This file is a slightly modified version of quadprog.js from Alberto Santini. * It has been slightly modified by Sébastien Loisel to make sure that it handles * 0-based Arrays instead of 1-based Arrays. * License is in resources/LICENSE.quadprog */ (function(exports) { function base0to1(A) { if(typeof A !== "object") { return A; } var ret = [], i,n=A.length; for(i=0;i<n;i++) ret[i+1] = base0to1(A[i]); return ret; } function base1to0(A) { if(typeof A !== "object") { return A; } var ret = [], i,n=A.length; for(i=1;i<n;i++) ret[i-1] = base1to0(A[i]); return ret; } function dpori(a, lda, n) { var i, j, k, kp1, t; for (k = 1; k <= n; k = k + 1) { a[k][k] = 1 / a[k][k]; t = -a[k][k]; //~ dscal(k - 1, t, a[1][k], 1); for (i = 1; i < k; i = i + 1) { a[i][k] = t * a[i][k]; } kp1 = k + 1; if (n < kp1) { break; } for (j = kp1; j <= n; j = j + 1) { t = a[k][j]; a[k][j] = 0; //~ daxpy(k, t, a[1][k], 1, a[1][j], 1); for (i = 1; i <= k; i = i + 1) { a[i][j] = a[i][j] + (t * a[i][k]); } } } } function dposl(a, lda, n, b) { var i, k, kb, t; for (k = 1; k <= n; k = k + 1) { //~ t = ddot(k - 1, a[1][k], 1, b[1], 1); t = 0; for (i = 1; i < k; i = i + 1) { t = t + (a[i][k] * b[i]); } b[k] = (b[k] - t) / a[k][k]; } for (kb = 1; kb <= n; kb = kb + 1) { k = n + 1 - kb; b[k] = b[k] / a[k][k]; t = -b[k]; //~ daxpy(k - 1, t, a[1][k], 1, b[1], 1); for (i = 1; i < k; i = i + 1) { b[i] = b[i] + (t * a[i][k]); } } } function dpofa(a, lda, n, info) { var i, j, jm1, k, t, s; for (j = 1; j <= n; j = j + 1) { info[1] = j; s = 0; jm1 = j - 1; if (jm1 < 1) { s = a[j][j] - s; if (s <= 0) { break; } a[j][j] = Math.sqrt(s); } else { for (k = 1; k <= jm1; k = k + 1) { //~ t = a[k][j] - ddot(k - 1, a[1][k], 1, a[1][j], 1); t = a[k][j]; for (i = 1; i < k; i = i + 1) { t = t - (a[i][j] * a[i][k]); } t = t / a[k][k]; a[k][j] = t; s = s + t * t; } s = a[j][j] - s; if (s <= 0) { break; } a[j][j] = Math.sqrt(s); } info[1] = 0; } } function qpgen2(dmat, dvec, fddmat, n, sol, crval, amat, bvec, fdamat, q, meq, iact, nact, iter, work, ierr) { var i, j, l, l1, info, it1, iwzv, iwrv, iwrm, iwsv, iwuv, nvl, r, iwnbv, temp, sum, t1, tt, gc, gs, nu, t1inf, t2min, vsmall, tmpa, tmpb, go; r = Math.min(n, q); l = 2 * n + (r * (r + 5)) / 2 + 2 * q + 1; vsmall = 1.0e-60; do { vsmall = vsmall + vsmall; tmpa = 1 + 0.1 * vsmall; tmpb = 1 + 0.2 * vsmall; } while (tmpa <= 1 || tmpb <= 1); for (i = 1; i <= n; i = i + 1) { work[i] = dvec[i]; } for (i = n + 1; i <= l; i = i + 1) { work[i] = 0; } for (i = 1; i <= q; i = i + 1) { iact[i] = 0; } info = []; if (ierr[1] === 0) { dpofa(dmat, fddmat, n, info); if (info[1] !== 0) { ierr[1] = 2; return; } dposl(dmat, fddmat, n, dvec); dpori(dmat, fddmat, n); } else { for (j = 1; j <= n; j = j + 1) { sol[j] = 0; for (i = 1; i <= j; i = i + 1) { sol[j] = sol[j] + dmat[i][j] * dvec[i]; } } for (j = 1; j <= n; j = j + 1) { dvec[j] = 0; for (i = j; i <= n; i = i + 1) { dvec[j] = dvec[j] + dmat[j][i] * sol[i]; } } } crval[1] = 0; for (j = 1; j <= n; j = j + 1) { sol[j] = dvec[j]; crval[1] = crval[1] + work[j] * sol[j]; work[j] = 0; for (i = j + 1; i <= n; i = i + 1) { dmat[i][j] = 0; } } crval[1] = -crval[1] / 2; ierr[1] = 0; iwzv = n; iwrv = iwzv + n; iwuv = iwrv + r; iwrm = iwuv + r + 1; iwsv = iwrm + (r * (r + 1)) / 2; iwnbv = iwsv + q; for (i = 1; i <= q; i = i + 1) { sum = 0; for (j = 1; j <= n; j = j + 1) { sum = sum + amat[j][i] * amat[j][i]; } work[iwnbv + i] = Math.sqrt(sum); } nact = 0; iter[1] = 0; iter[2] = 0; function fn_goto_50() { iter[1] = iter[1] + 1; l = iwsv; for (i = 1; i <= q; i = i + 1) { l = l + 1; sum = -bvec[i]; for (j = 1; j <= n; j = j + 1) { sum = sum + amat[j][i] * sol[j]; } if (Math.abs(sum) < vsmall) { sum = 0; } if (i > meq) { work[l] = sum; } else { work[l] = -Math.abs(sum); if (sum > 0) { for (j = 1; j <= n; j = j + 1) { amat[j][i] = -amat[j][i]; } bvec[i] = -bvec[i]; } } } for (i = 1; i <= nact; i = i + 1) { work[iwsv + iact[i]] = 0; } nvl = 0; temp = 0; for (i = 1; i <= q; i = i + 1) { if (work[iwsv + i] < temp * work[iwnbv + i]) { nvl = i; temp = work[iwsv + i] / work[iwnbv + i]; } } if (nvl === 0) { return 999; } return 0; } function fn_goto_55() { for (i = 1; i <= n; i = i + 1) { sum = 0; for (j = 1; j <= n; j = j + 1) { sum = sum + dmat[j][i] * amat[j][nvl]; } work[i] = sum; } l1 = iwzv; for (i = 1; i <= n; i = i + 1) { work[l1 + i] = 0; } for (j = nact + 1; j <= n; j = j + 1) { for (i = 1; i <= n; i = i + 1) { work[l1 + i] = work[l1 + i] + dmat[i][j] * work[j]; } } t1inf = true; for (i = nact; i >= 1; i = i - 1) { sum = work[i]; l = iwrm + (i * (i + 3)) / 2; l1 = l - i; for (j = i + 1; j <= nact; j = j + 1) { sum = sum - work[l] * work[iwrv + j]; l = l + j; } sum = sum / work[l1]; work[iwrv + i] = sum; if (iact[i] < meq) { // continue; break; } if (sum < 0) { // continue; break; } t1inf = false; it1 = i; } if (!t1inf) { t1 = work[iwuv + it1] / work[iwrv + it1]; for (i = 1; i <= nact; i = i + 1) { if (iact[i] < meq) { // continue; break; } if (work[iwrv + i] < 0) { // continue; break; } temp = work[iwuv + i] / work[iwrv + i]; if (temp < t1) { t1 = temp; it1 = i; } } } sum = 0; for (i = iwzv + 1; i <= iwzv + n; i = i + 1) { sum = sum + work[i] * work[i]; } if (Math.abs(sum) <= vsmall) { if (t1inf) { ierr[1] = 1; // GOTO 999 return 999; } else { for (i = 1; i <= nact; i = i + 1) { work[iwuv + i] = work[iwuv + i] - t1 * work[iwrv + i]; } work[iwuv + nact + 1] = work[iwuv + nact + 1] + t1; // GOTO 700 return 700; } } else { sum = 0; for (i = 1; i <= n; i = i + 1) { sum = sum + work[iwzv + i] * amat[i][nvl]; } tt = -work[iwsv + nvl] / sum; t2min = true; if (!t1inf) { if (t1 < tt) { tt = t1; t2min = false; } } for (i = 1; i <= n; i = i + 1) { sol[i] = sol[i] + tt * work[iwzv + i]; if (Math.abs(sol[i]) < vsmall) { sol[i] = 0; } } crval[1] = crval[1] + tt * sum * (tt / 2 + work[iwuv + nact + 1]); for (i = 1; i <= nact; i = i + 1) { work[iwuv + i] = work[iwuv + i] - tt * work[iwrv + i]; } work[iwuv + nact + 1] = work[iwuv + nact + 1] + tt; if (t2min) { nact = nact + 1; iact[nact] = nvl; l = iwrm + ((nact - 1) * nact) / 2 + 1; for (i = 1; i <= nact - 1; i = i + 1) { work[l] = work[i]; l = l + 1; } if (nact === n) { work[l] = work[n]; } else { for (i = n; i >= nact + 1; i = i - 1) { if (work[i] === 0) { // continue; break; } gc = Math.max(Math.abs(work[i - 1]), Math.abs(work[i])); gs = Math.min(Math.abs(work[i - 1]), Math.abs(work[i])); if (work[i - 1] >= 0) { temp = Math.abs(gc * Math.sqrt(1 + gs * gs / (gc * gc))); } else { temp = -Math.abs(gc * Math.sqrt(1 + gs * gs / (gc * gc))); } gc = work[i - 1] / temp; gs = work[i] / temp; if (gc === 1) { // continue; break; } if (gc === 0) { work[i - 1] = gs * temp; for (j = 1; j <= n; j = j + 1) { temp = dmat[j][i - 1]; dmat[j][i - 1] = dmat[j][i]; dmat[j][i] = temp; } } else { work[i - 1] = temp; nu = gs / (1 + gc); for (j = 1; j <= n; j = j + 1) { temp = gc * dmat[j][i - 1] + gs * dmat[j][i]; dmat[j][i] = nu * (dmat[j][i - 1] + temp) - dmat[j][i]; dmat[j][i - 1] = temp; } } } work[l] = work[nact]; } } else { sum = -bvec[nvl]; for (j = 1; j <= n; j = j + 1) { sum = sum + sol[j] * amat[j][nvl]; } if (nvl > meq) { work[iwsv + nvl] = sum; } else { work[iwsv + nvl] = -Math.abs(sum); if (sum > 0) { for (j = 1; j <= n; j = j + 1) { amat[j][nvl] = -amat[j][nvl]; } bvec[nvl] = -bvec[nvl]; } } // GOTO 700 return 700; } } return 0; } function fn_goto_797() { l = iwrm + (it1 * (it1 + 1)) / 2 + 1; l1 = l + it1; if (work[l1] === 0) { // GOTO 798 return 798; } gc = Math.max(Math.abs(work[l1 - 1]), Math.abs(work[l1])); gs = Math.min(Math.abs(work[l1 - 1]), Math.abs(work[l1])); if (work[l1 - 1] >= 0) { temp = Math.abs(gc * Math.sqrt(1 + gs * gs / (gc * gc))); } else { temp = -Math.abs(gc * Math.sqrt(1 + gs * gs / (gc * gc))); } gc = work[l1 - 1] / temp; gs = work[l1] / temp; if (gc === 1) { // GOTO 798 return 798; } if (gc === 0) { for (i = it1 + 1; i <= nact; i = i + 1) { temp = work[l1 - 1]; work[l1 - 1] = work[l1]; work[l1] = temp; l1 = l1 + i; } for (i = 1; i <= n; i = i + 1) { temp = dmat[i][it1]; dmat[i][it1] = dmat[i][it1 + 1]; dmat[i][it1 + 1] = temp; } } else { nu = gs / (1 + gc); for (i = it1 + 1; i <= nact; i = i + 1) { temp = gc * work[l1 - 1] + gs * work[l1]; work[l1] = nu * (work[l1 - 1] + temp) - work[l1]; work[l1 - 1] = temp; l1 = l1 + i; } for (i = 1; i <= n; i = i + 1) { temp = gc * dmat[i][it1] + gs * dmat[i][it1 + 1]; dmat[i][it1 + 1] = nu * (dmat[i][it1] + temp) - dmat[i][it1 + 1]; dmat[i][it1] = temp; } } return 0; } function fn_goto_798() { l1 = l - it1; for (i = 1; i <= it1; i = i + 1) { work[l1] = work[l]; l = l + 1; l1 = l1 + 1; } work[iwuv + it1] = work[iwuv + it1 + 1]; iact[it1] = iact[it1 + 1]; it1 = it1 + 1; if (it1 < nact) { // GOTO 797 return 797; } return 0; } function fn_goto_799() { work[iwuv + nact] = work[iwuv + nact + 1]; work[iwuv + nact + 1] = 0; iact[nact] = 0; nact = nact - 1; iter[2] = iter[2] + 1; return 0; } go = 0; while (true) { go = fn_goto_50(); if (go === 999) { return; } while (true) { go = fn_goto_55(); if (go === 0) { break; } if (go === 999) { return; } if (go === 700) { if (it1 === nact) { fn_goto_799(); } else { while (true) { fn_goto_797(); go = fn_goto_798(); if (go !== 797) { break; } } fn_goto_799(); } } } } } function solveQP(Dmat, dvec, Amat, bvec, meq, factorized) { Dmat = base0to1(Dmat); dvec = base0to1(dvec); Amat = base0to1(Amat); var i, n, q, nact, r, crval = [], iact = [], sol = [], work = [], iter = [], message; meq = meq || 0; factorized = factorized ? base0to1(factorized) : [undefined, 0]; bvec = bvec ? base0to1(bvec) : []; // In Fortran the array index starts from 1 n = Dmat.length - 1; q = Amat[1].length - 1; if (!bvec) { for (i = 1; i <= q; i = i + 1) { bvec[i] = 0; } } for (i = 1; i <= q; i = i + 1) { iact[i] = 0; } nact = 0; r = Math.min(n, q); for (i = 1; i <= n; i = i + 1) { sol[i] = 0; } crval[1] = 0; for (i = 1; i <= (2 * n + (r * (r + 5)) / 2 + 2 * q + 1); i = i + 1) { work[i] = 0; } for (i = 1; i <= 2; i = i + 1) { iter[i] = 0; } qpgen2(Dmat, dvec, n, n, sol, crval, Amat, bvec, n, q, meq, iact, nact, iter, work, factorized); message = ""; if (factorized[1] === 1) { message = "constraints are inconsistent, no solution!"; } if (factorized[1] === 2) { message = "matrix D in quadratic function is not positive definite!"; } return { solution: base1to0(sol), value: base1to0(crval), unconstrained_solution: base1to0(dvec), iterations: base1to0(iter), iact: base1to0(iact), message: message }; } exports.solveQP = solveQP; }(numeric)); /* Shanti Rao sent me this routine by private email. I had to modify it slightly to work on Arrays instead of using a Matrix object. It is apparently translated from http://stitchpanorama.sourceforge.net/Python/svd.py */ numeric.svd= function svd(A) { var temp; //Compute the thin SVD from G. H. Golub and C. Reinsch, Numer. Math. 14, 403-420 (1970) var prec= numeric.epsilon; //Math.pow(2,-52) // assumes double prec var tolerance= 1.e-64/prec; var itmax= 50; var c=0; var i=0; var j=0; var k=0; var l=0; var u= numeric.clone(A); var m= u.length; var n= u[0].length; if (m < n) throw "Need more rows than columns" var e = new Array(n); var q = new Array(n); for (i=0; i<n; i++) e[i] = q[i] = 0.0; var v = numeric.rep([n,n],0); // v.zero(); function pythag(a,b) { a = Math.abs(a) b = Math.abs(b) if (a > b) return a*Math.sqrt(1.0+(b*b/a/a)) else if (b == 0.0) return a return b*Math.sqrt(1.0+(a*a/b/b)) } //Householder's reduction to bidiagonal form var f= 0.0; var g= 0.0; var h= 0.0; var x= 0.0; var y= 0.0; var z= 0.0; var s= 0.0; for (i=0; i < n; i++) { e[i]= g; s= 0.0; l= i+1; for (j=i; j < m; j++) s += (u[j][i]*u[j][i]); if (s <= tolerance) g= 0.0; else { f= u[i][i]; g= Math.sqrt(s); if (f >= 0.0) g= -g; h= f*g-s u[i][i]=f-g; for (j=l; j < n; j++) { s= 0.0 for (k=i; k < m; k++) s += u[k][i]*u[k][j] f= s/h for (k=i; k < m; k++) u[k][j]+=f*u[k][i] } } q[i]= g s= 0.0 for (j=l; j < n; j++) s= s + u[i][j]*u[i][j] if (s <= tolerance) g= 0.0 else { f= u[i][i+1] g= Math.sqrt(s) if (f >= 0.0) g= -g h= f*g - s u[i][i+1] = f-g; for (j=l; j < n; j++) e[j]= u[i][j]/h for (j=l; j < m; j++) { s=0.0 for (k=l; k < n; k++) s += (u[j][k]*u[i][k]) for (k=l; k < n; k++) u[j][k]+=s*e[k] } } y= Math.abs(q[i])+Math.abs(e[i]) if (y>x) x=y } // accumulation of right hand gtransformations for (i=n-1; i != -1; i+= -1) { if (g != 0.0) { h= g*u[i][i+1] for (j=l; j < n; j++) v[j][i]=u[i][j]/h for (j=l; j < n; j++) { s=0.0 for (k=l; k < n; k++) s += u[i][k]*v[k][j] for (k=l; k < n; k++) v[k][j]+=(s*v[k][i]) } } for (j=l; j < n; j++) { v[i][j] = 0; v[j][i] = 0; } v[i][i] = 1; g= e[i] l= i } // accumulation of left hand transformations for (i=n-1; i != -1; i+= -1) { l= i+1 g= q[i] for (j=l; j < n; j++) u[i][j] = 0; if (g != 0.0) { h= u[i][i]*g for (j=l; j < n; j++) { s=0.0 for (k=l; k < m; k++) s += u[k][i]*u[k][j]; f= s/h for (k=i; k < m; k++) u[k][j]+=f*u[k][i]; } for (j=i; j < m; j++) u[j][i] = u[j][i]/g; } else for (j=i; j < m; j++) u[j][i] = 0; u[i][i] += 1; } // diagonalization of the bidiagonal form prec= prec*x for (k=n-1; k != -1; k+= -1) { for (var iteration=0; iteration < itmax; iteration++) { // test f splitting var test_convergence = false for (l=k; l != -1; l+= -1) { if (Math.abs(e[l]) <= prec) { test_convergence= true break } if (Math.abs(q[l-1]) <= prec) break } if (!test_convergence) { // cancellation of e[l] if l>0 c= 0.0 s= 1.0 var l1= l-1 for (i =l; i<k+1; i++) { f= s*e[i] e[i]= c*e[i] if (Math.abs(f) <= prec) break g= q[i] h= pythag(f,g) q[i]= h c= g/h s= -f/h for (j=0; j < m; j++) { y= u[j][l1] z= u[j][i] u[j][l1] = y*c+(z*s) u[j][i] = -y*s+(z*c) } } } // test f convergence z= q[k] if (l== k) { //convergence if (z<0.0) { //q[k] is made non-negative q[k]= -z for (j=0; j < n; j++) v[j][k] = -v[j][k] } break //break out of iteration loop and move on to next k value } if (iteration >= itmax-1) throw 'Error: no convergence.' // shift from bottom 2x2 minor x= q[l] y= q[k-1] g= e[k-1] h= e[k] f= ((y-z)*(y+z)+(g-h)*(g+h))/(2.0*h*y) g= pythag(f,1.0) if (f < 0.0) f= ((x-z)*(x+z)+h*(y/(f-g)-h))/x else f= ((x-z)*(x+z)+h*(y/(f+g)-h))/x // next QR transformation c= 1.0 s= 1.0 for (i=l+1; i< k+1; i++) { g= e[i] y= q[i] h= s*g g= c*g z= pythag(f,h) e[i-1]= z c= f/z s= h/z f= x*c+g*s g= -x*s+g*c h= y*s y= y*c for (j=0; j < n; j++) { x= v[j][i-1] z= v[j][i] v[j][i-1] = x*c+z*s v[j][i] = -x*s+z*c } z= pythag(f,h) q[i-1]= z c= f/z s= h/z f= c*g+s*y x= -s*g+c*y for (j=0; j < m; j++) { y= u[j][i-1] z= u[j][i] u[j][i-1] = y*c+z*s u[j][i] = -y*s+z*c } } e[l]= 0.0 e[k]= f q[k]= x } } //vt= transpose(v) //return (u,q,vt) for (i=0;i<q.length; i++) if (q[i] < prec) q[i] = 0 //sort eigenvalues for (i=0; i< n; i++) { //writeln(q) for (j=i-1; j >= 0; j--) { if (q[j] < q[i]) { // writeln(i,'-',j) c = q[j] q[j] = q[i] q[i] = c for(k=0;k<u.length;k++) { temp = u[k][i]; u[k][i] = u[k][j]; u[k][j] = temp; } for(k=0;k<v.length;k++) { temp = v[k][i]; v[k][i] = v[k][j]; v[k][j] = temp; } // u.swapCols(i,j) // v.swapCols(i,j) i = j } } } return {U:u,S:q,V:v} };
var fs = require('fs') var path = require('path') var ncp = require('ncp').ncp var mkdir = require('./mkdir') var create = require('./create') var BUF_LENGTH = 64 * 1024 var _buff = new Buffer(BUF_LENGTH) var copyFileSync = function(srcFile, destFile) { var fdr = fs.openSync(srcFile, 'r') var stat = fs.fstatSync(fdr) var fdw = fs.openSync(destFile, 'w', stat.mode) var bytesRead = 1 var pos = 0 while (bytesRead > 0) { bytesRead = fs.readSync(fdr, _buff, 0, BUF_LENGTH, pos) fs.writeSync(fdw, _buff, 0, bytesRead) pos += bytesRead } fs.closeSync(fdr) fs.closeSync(fdw) } function copy(src, dest, options, callback) { if( typeof options == "function" && !callback) { callback = options options = {} } else if (typeof options == "function" || options instanceof RegExp) { options = {filter: options} } callback = callback || function(){} fs.lstat(src, function(err, stats) { if (err) return callback(err) var dir = null if (stats.isDirectory()) { var parts = dest.split(path.sep) parts.pop() dir = parts.join(path.sep) } else { dir = path.dirname(dest) } fs.exists(dir, function(dirExists) { if (dirExists) return ncp(src, dest, options, callback) mkdir.mkdirs(dir, function(err) { if (err) return callback(err) ncp(src, dest, options, callback) }) }) }) } function copySync(src, dest, options) { if (typeof options == "function" || options instanceof RegExp) { options = {filter: options} } options = options || {} options.recursive = !!options.recursive options.filter = options.filter || function() { return true } var stats = options.recursive ? fs.lstatSync(src) : fs.statSync(src) var destFolder = path.dirname(dest) var destFolderExists = fs.existsSync(destFolder) var performCopy = false if (stats.isFile()) { if (options.filter instanceof RegExp) performCopy = options.filter.test(src) else if (typeof options.filter == "function") performCopy = options.filter(src) if (performCopy) { if (!destFolderExists) mkdir.mkdirsSync(destFolder) copyFileSync(src, dest) } } else if (stats.isDirectory()) { if (!fs.existsSync(dest)) mkdir.mkdirsSync(dest) var contents = fs.readdirSync(src) contents.forEach(function(content) { copySync(path.join(src, content), path.join(dest, content), {filter: options.filter, recursive: true}) }) } else if (options.recursive && stats.isSymbolicLink()) { var srcPath = fs.readlinkSync(src) fs.symlinkSync(srcPath, dest) } } module.exports = { copy: copy, copySync: copySync }
/** * Sample React Native App * https://github.com/facebook/react-native */ 'use strict'; var React = require('react-native'); var { AppRegistry, BackAndroid, Text, View, Navigator, StyleSheet, ToolbarAndroid, ToastAndroid, } = React; var ToolbarAndroid = require('ToolbarAndroid'); var TimerMixin = require('react-timer-mixin'); var WelcomeScreen = require('./WelcomeScreen'); var ListScreen = require('./ListScreen'); var StoryScreen = require('./StoryScreen'); var _navigator; BackAndroid.addEventListener('hardwareBackPress', function() { if (_navigator && _navigator.getCurrentRoutes().length > 1) { _navigator.pop(); return true; } return false; }); var backHandler = { handler: null, } var RCTZhiHuDaily = React.createClass({ // mixins: [TimerMixin], // componentDidMount: function() { // this.setTimeout( // () => { // this.setState({splashed: true}); // }, // 50 // ); // }, RouteMapper: function(route, navigationOperations, onComponentRef) { _navigator = navigationOperations; if (route.name === 'home') { return ( <View style={styles.container}> <ListScreen navigator={navigationOperations}/> </View> ); } else if (route.name === 'story') { return ( <View style={styles.container}> <StoryScreen style={{flex: 1}} navigator={navigationOperations} story={route.story} /> </View> ); } }, getInitialState: function() { return { splashed: false, }; }, onActionSelected: function(position) { }, render: function() { var initialRoute = {name: 'home'}; return ( <Navigator style={styles.container} initialRoute={initialRoute} configureScene={() => Navigator.SceneConfigs.FadeAndroid} renderScene={this.RouteMapper} /> ); // if (!this.state.splashed) { // return ( // <WelcomeScreen /> // ); // } else { // return ( // <View style={styles.container}> // <ToolbarAndroid // navIcon={require('image!ic_menu_white')} // title="知乎日报" // titleColor="white" // style={styles.toolbar} // actions={toolbarActions} // onActionSelected={this.onActionSelected} /> // <ListScreen /> // </View> // // ); // } } }); var styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('RCTZhiHuDaily', () => RCTZhiHuDaily);
/* Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang("uicolor","da",{title:"Brugerflade på farvevælger",options:"Color Options",highlight:"Highlight",selected:"Selected Color",predefined:"Prædefinerede farveskemaer",config:"Indsæt denne streng i din config.js fil"});
(function($) { /* ======== A Handy Little QUnit Reference ======== http://api.qunitjs.com/ Test methods: module(name, {[setup][ ,teardown]}) test(name, callback) expect(numberOfAssertions) stop(increment) start(decrement) Test assertions: ok(value, [message]) equal(actual, expected, [message]) notEqual(actual, expected, [message]) deepEqual(actual, expected, [message]) notDeepEqual(actual, expected, [message]) strictEqual(actual, expected, [message]) notStrictEqual(actual, expected, [message]) throws(block, [expected], [message]) */ module('jQuery#awesome', { // This will run before each test in this module. setup: function() { this.elems = $('#qunit-fixture').children(); } }); test('is chainable', function() { expect(1); // Not a bad test to run on collection methods. strictEqual(this.elems.awesome(), this.elems, 'should be chainable'); }); test('is awesome', function() { expect(1); strictEqual(this.elems.awesome().text(), 'awesome0awesome1awesome2', 'should be awesome'); }); module('jQuery.awesome'); test('is awesome', function() { expect(2); strictEqual($.awesome(), 'awesome.', 'should be awesome'); strictEqual($.awesome({punctuation: '!'}), 'awesome!', 'should be thoroughly awesome'); }); module(':awesome selector', { // This will run before each test in this module. setup: function() { this.elems = $('#qunit-fixture').children(); } }); test('is awesome', function() { expect(1); // Use deepEqual & .get() when comparing jQuery objects. deepEqual(this.elems.filter(':awesome').get(), this.elems.last().get(), 'knows awesome when it sees it'); }); }(jQuery));
import length from "./length"; var coordinates = [null, null], object = {type: "LineString", coordinates: coordinates}; export default function(a, b) { coordinates[0] = a; coordinates[1] = b; return length(object); }
module.exports = function (html) { if (typeof document !== 'undefined') { return; } var jsdom = require('jsdom').jsdom; global.document = jsdom(html || ''); global.window = global.document.parentWindow; global.navigator = { userAgent: 'JSDOM' }; };
/** * interact.js v1.0.14 * * Copyright (c) 2012, 2013, 2014 Taye Adeyemi <dev@taye.me> * Open source under the MIT License. * https://raw.github.com/taye/interact.js/master/LICENSE */ (function (window) { 'use strict'; var document = window.document, console = window.console, SVGElement = window.SVGElement || blank, SVGSVGElement = window.SVGSVGElement || blank, SVGElementInstance = window.SVGElementInstance || blank, HTMLElement = window.HTMLElement || window.Element, PointerEvent = window.PointerEvent || window.MSPointerEvent, GestureEvent = window.GestureEvent || window.MSGestureEvent, Gesture = window.Gesture || window.MSGesture, hypot = Math.hypot || function (x, y) { return Math.sqrt(x * x + y * y); }, // Previous native pointer move event coordinates prevCoords = { pageX: 0, pageY: 0, clientX: 0, clientY: 0, timeStamp: 0 }, // current native pointer move event coordinates curCoords = { pageX: 0, pageY: 0, clientX: 0, clientY: 0, timeStamp: 0 }, // Starting InteractEvent pointer coordinates startCoords = { pageX: 0, pageY: 0, clientX: 0, clientY: 0, timeStamp: 0 }, // Change in coordinates and time of the pointer pointerDelta = { pageX: 0, pageY: 0, clientX: 0, clientY: 0, timeStamp: 0, pageSpeed: 0, clientSpeed: 0 }, // keep track of added PointerEvents if browser supports them pointerIds = PointerEvent? []: null, pointerMoves = PointerEvent? []: null, downTime = 0, // the timeStamp of the starting event downEvent = null, // gesturestart/mousedown/touchstart event prevEvent = null, // previous action event tapTime = 0, // time of the most recent tap event prevTap = null, tmpXY = {}, // reduce object creation in getXY() inertiaStatus = { active : false, target : null, targetElement: null, startEvent: null, pointerUp : {}, xe : 0, ye : 0, duration: 0, t0 : 0, vx0: 0, vys: 0, lambda_v0: 0, one_ve_v0: 0, i : null }, gesture = { start: { x: 0, y: 0 }, startDistance: 0, // distance between two touches of touchStart prevDistance : 0, distance : 0, scale: 1, // gesture.distance / gesture.startDistance startAngle: 0, // angle of line joining two touches prevAngle : 0 // angle of the previous gesture event }, interactables = [], // all set interactables dropzones = [], // all dropzone element interactables elements = [], // all elements that have been made interactable selectors = {}, // all css selector interactables selectorDZs = [], // all dropzone selector interactables matches = [], // all selectors that are matched by target element delegatedEvents = {}, // { type: { selector: [[listener, useCapture]} } selectorGesture = null, // MSGesture object for selector PointerEvents target = null, // current interactable being interacted with dropTarget = null, // the dropzone a drag target might be dropped into dropElement = null, // the element at the time of checking prevDropTarget = null, // the dropzone that was recently dragged away from prevDropElement = null, // the element at the time of checking defaultOptions = { draggable : false, dropzone : false, accept : null, resizable : false, squareResize: false, gesturable : false, styleCursor : true, // aww snap snap: { mode : 'grid', endOnly : false, actions : ['drag'], range : Infinity, grid : { x: 100, y: 100 }, gridOffset : { x: 0, y: 0 }, anchors : [], paths : [], arrayTypes : /^anchors$|^paths$|^actions$/, objectTypes : /^grid$|^gridOffset$/, stringTypes : /^mode$/, numberTypes : /^range$/, boolTypes : /^endOnly$/ }, snapEnabled : false, restrict: { drag: null, resize: null, gesture: null, endOnly: false }, restrictEnabled: true, autoScroll: { container : window, // the item that is scrolled (Window or HTMLElement) margin : 60, speed : 300, // the scroll speed in pixels per second numberTypes : /^margin$|^speed$/ }, autoScrollEnabled: false, inertia: { resistance : 10, // the lambda in exponential decay minSpeed : 100, // target speed must be above this for inertia to start endSpeed : 10, // the speed at which inertia is slow enough to stop actions : ['drag', 'resize'], zeroResumeDelta: false, numberTypes: /^resistance$|^minSpeed$|^endSpeed$/, arrayTypes : /^actions$/, boolTypes: /^zeroResumeDelta$/ }, inertiaEnabled: false, origin : { x: 0, y: 0 }, deltaSource : 'page' }, snapStatus = { locked : false, x : 0, y : 0, dx : 0, dy : 0, realX : 0, realY : 0, anchors: [], paths : [] }, restrictStatus = { dx: 0, dy: 0, snap: snapStatus, restricted: false }, // Things related to autoScroll autoScroll = { target: null, i: null, // the handle returned by window.setInterval x: 0, // Direction each pulse is to scroll in y: 0, // scroll the window by the values in scroll.x/y scroll: function () { var options = autoScroll.target.options.autoScroll, container = options.container, now = new Date().getTime(), // change in time in seconds dt = (now - autoScroll.prevTime) / 1000, // displacement s = options.speed * dt; if (s >= 1) { if (container instanceof window.Window) { container.scrollBy(autoScroll.x * s, autoScroll.y * s); } else if (container) { container.scrollLeft += autoScroll.x * s; container.scrollTop += autoScroll.y * s; } autoScroll.prevTime = now; } if (autoScroll.isScrolling) { cancelFrame(autoScroll.i); autoScroll.i = reqFrame(autoScroll.scroll); } }, edgeMove: function (event) { if (target && target.options.autoScrollEnabled && (dragging || resizing)) { var top, right, bottom, left, options = target.options.autoScroll; if (options.container instanceof window.Window) { left = event.clientX < autoScroll.margin; top = event.clientY < autoScroll.margin; right = event.clientX > options.container.innerWidth - autoScroll.margin; bottom = event.clientY > options.container.innerHeight - autoScroll.margin; } else { var rect = getElementRect(options.container); left = event.clientX < rect.left + autoScroll.margin; top = event.clientY < rect.top + autoScroll.margin; right = event.clientX > rect.right - autoScroll.margin; bottom = event.clientY > rect.bottom - autoScroll.margin; } autoScroll.x = (right ? 1: left? -1: 0); autoScroll.y = (bottom? 1: top? -1: 0); if (!autoScroll.isScrolling) { // set the autoScroll properties to those of the target autoScroll.margin = options.margin; autoScroll.speed = options.speed; autoScroll.start(target); } } }, isScrolling: false, prevTime: 0, start: function (target) { autoScroll.isScrolling = true; cancelFrame(autoScroll.i); autoScroll.target = target; autoScroll.prevTime = new Date().getTime(); autoScroll.i = reqFrame(autoScroll.scroll); }, stop: function () { autoScroll.isScrolling = false; cancelFrame(autoScroll.i); } }, // Does the browser support touch input? supportsTouch = 'createTouch' in document, // Less Precision with touch input margin = supportsTouch? 20: 10, pointerIsDown = false, pointerWasMoved = false, gesturing = false, dragging = false, dynamicDrop = false, resizing = false, resizeAxes = 'xy', // What to do depending on action returned by getAction() of interactable // Dictates what styles should be used and what pointerMove event Listner // is to be added after pointerDown actions = { drag: { cursor : 'move', moveListener: dragMove }, resizex: { cursor : 'e-resize', moveListener: resizeMove }, resizey: { cursor : 's-resize', moveListener: resizeMove }, resizexy: { cursor : 'se-resize', moveListener: resizeMove }, gesture: { cursor : '', moveListener: gestureMove } }, actionIsEnabled = { drag : true, resize : true, gesture: true }, // Action that's ready to be fired on next move event prepared = null, // because Webkit and Opera still use 'mousewheel' event type wheelEvent = 'onmousewheel' in document? 'mousewheel': 'wheel', eventTypes = [ 'dragstart', 'dragmove', 'draginertiastart', 'dragend', 'dragenter', 'dragleave', 'drop', 'resizestart', 'resizemove', 'resizeinertiastart', 'resizeend', 'gesturestart', 'gesturemove', 'gestureinertiastart', 'gestureend', 'tap', 'doubletap' ], globalEvents = {}, fireStates = { directBind: 0, onevent : 1, globalBind: 2 }, // Opera Mobile must be handled differently isOperaMobile = navigator.appName == 'Opera' && supportsTouch && navigator.userAgent.match('Presto'), // prefix matchesSelector matchesSelector = 'matchesSelector' in Element.prototype? 'matchesSelector': 'webkitMatchesSelector' in Element.prototype? 'webkitMatchesSelector': 'mozMatchesSelector' in Element.prototype? 'mozMatchesSelector': 'oMatchesSelector' in Element.prototype? 'oMatchesSelector': 'msMatchesSelector', // will be polyfill function if browser is IE8 IE8MatchesSelector, // native requestAnimationFrame or polyfill reqFrame = window.requestAnimationFrame, cancelFrame = window.cancelAnimationFrame, // used for adding event listeners to window and document windowTarget = { _element: window, events : {} }, docTarget = { _element: document, events : {} }, parentWindowTarget = { _element: window.parent, events : {} }, parentDocTarget = { _element: null, events : {} }, // Events wrapper events = (function () { var Event = window.Event, useAttachEvent = 'attachEvent' in window && !('addEventListener' in window), addEvent = !useAttachEvent? 'addEventListener': 'attachEvent', removeEvent = !useAttachEvent? 'removeEventListener': 'detachEvent', on = useAttachEvent? 'on': '', elements = [], targets = [], attachedListeners = []; if (!('indexOf' in Array.prototype)) { Array.prototype.indexOf = function(elt /*, from*/) { var len = this.length >>> 0; var from = Number(arguments[1]) || 0; from = (from < 0)? Math.ceil(from): Math.floor(from); if (from < 0) { from += len; } for (; from < len; from++) { if (from in this && this[from] === elt) { return from; } } return -1; }; } if (!('stopPropagation' in Event.prototype)) { Event.prototype.stopPropagation = function () { this.cancelBubble = true; }; Event.prototype.stopImmediatePropagation = function () { this.cancelBubble = true; this.immediatePropagationStopped = true; }; } if (!('preventDefault' in Event.prototype)) { Event.prototype.preventDefault = function () { this.returnValue = false; }; } if (!('hasOwnProperty' in Event.prototype)) { /* jshint -W001 */ // ignore warning about setting IE8 Event#hasOwnProperty Event.prototype.hasOwnProperty = Object.prototype.hasOwnProperty; } function add (element, type, listener, useCapture) { var elementIndex = elements.indexOf(element), target = targets[elementIndex]; if (!target) { target = { events: {}, typeCount: 0 }; elementIndex = elements.push(element) - 1; targets.push(target); attachedListeners.push((useAttachEvent ? { supplied: [], wrapped: [], useCount: [] } : null)); } if (!target.events[type]) { target.events[type] = []; target.typeCount++; } if (target.events[type].indexOf(listener) === -1) { var ret; if (useAttachEvent) { var listeners = attachedListeners[elementIndex], listenerIndex = listeners.supplied.indexOf(listener); var wrapped = listeners.wrapped[listenerIndex] || function (event) { if (!event.immediatePropagationStopped) { event.target = event.srcElement; event.currentTarget = element; if (/mouse|click/.test(event.type)) { event.pageX = event.clientX + document.documentElement.scrollLeft; event.pageY = event.clientY + document.documentElement.scrollTop; } listener(event); } }; ret = element[addEvent](on + type, wrapped, Boolean(useCapture)); if (listenerIndex === -1) { listeners.supplied.push(listener); listeners.wrapped.push(wrapped); listeners.useCount.push(1); } else { listeners.useCount[listenerIndex]++; } } else { ret = element[addEvent](type, listener, useCapture || false); } target.events[type].push(listener); return ret; } } function remove (element, type, listener, useCapture) { var i, elementIndex = elements.indexOf(element), target = targets[elementIndex], listeners, listenerIndex, wrapped = listener; if (!target || !target.events) { return; } if (useAttachEvent) { listeners = attachedListeners[elementIndex]; listenerIndex = listeners.supplied.indexOf(listener); wrapped = listeners.wrapped[listenerIndex]; } if (type === 'all') { for (type in target.events) { if (target.events.hasOwnProperty(type)) { remove(element, type, 'all'); } } return; } if (target.events[type]) { var len = target.events[type].length; if (listener === 'all') { for (i = 0; i < len; i++) { remove(element, type, target.events[type][i], Boolean(useCapture)); } } else { for (i = 0; i < len; i++) { if (target.events[type][i] === listener) { element[removeEvent](on + type, wrapped, useCapture || false); target.events[type].splice(i, 1); if (useAttachEvent && listeners) { listeners.useCount[listenerIndex]--; if (listeners.useCount[listenerIndex] === 0) { listeners.supplied.splice(listenerIndex, 1); listeners.wrapped.splice(listenerIndex, 1); listeners.useCount.splice(listenerIndex, 1); } } break; } } } if (target.events[type] && target.events[type].length === 0) { target.events[type] = null; target.typeCount--; } } if (!target.typeCount) { targets.splice(elementIndex); elements.splice(elementIndex); attachedListeners.splice(elementIndex); } } return { add: function (target, type, listener, useCapture) { add(target._element, type, listener, useCapture); }, remove: function (target, type, listener, useCapture) { remove(target._element, type, listener, useCapture); }, addToElement: add, removeFromElement: remove, useAttachEvent: useAttachEvent }; }()); function blank () {} function isElement (o) { return !!o && ( typeof Element === "object" ? o instanceof Element : //DOM2 o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName==="string" ); } function setEventXY (targetObj, source) { getPageXY(source, tmpXY); targetObj.pageX = tmpXY.x; targetObj.pageY = tmpXY.y; getClientXY(source, tmpXY); targetObj.clientX = tmpXY.x; targetObj.clientY = tmpXY.y; targetObj.timeStamp = new Date().getTime(); } function setEventDeltas (targetObj, prev, cur) { targetObj.pageX = cur.pageX - prev.pageX; targetObj.pageY = cur.pageY - prev.pageY; targetObj.clientX = cur.clientX - prev.clientX; targetObj.clientY = cur.clientY - prev.clientY; targetObj.timeStamp = new Date().getTime() - prev.timeStamp; // set pointer velocity var dt = Math.max(targetObj.timeStamp / 1000, 0.001); targetObj.pageSpeed = hypot(targetObj.pageX, targetObj.pageY) / dt; targetObj.pageVX = targetObj.pageX / dt; targetObj.pageVY = targetObj.pageY / dt; targetObj.clientSpeed = hypot(targetObj.clientX, targetObj.pageY) / dt; targetObj.clientVX = targetObj.clientX / dt; targetObj.clientVY = targetObj.clientY / dt; } // Get specified X/Y coords for mouse or event.touches[0] function getXY (type, event, xy) { var touch, x, y; xy = xy || {}; type = type || 'page'; if (/touch/.test(event.type) && event.touches) { touch = (event.touches.length)? event.touches[0]: event.changedTouches[0]; x = touch[type + 'X']; y = touch[type + 'Y']; } else { x = event[type + 'X']; y = event[type + 'Y']; } xy.x = x; xy.y = y; return xy; } function getPageXY (event, page) { page = page || {}; if (event instanceof InteractEvent) { if (/inertiastart/.test(event.type)) { getPageXY(inertiaStatus.pointerUp, page); page.x += inertiaStatus.sx; page.y += inertiaStatus.sy; } else { page.x = event.pageX; page.y = event.pageY; } } // Opera Mobile handles the viewport and scrolling oddly else if (isOperaMobile) { getXY('screen', event, page); page.x += window.scrollX; page.y += window.scrollY; } // MSGesture events don't have pageX/Y else if (/gesture|inertia/i.test(event.type)) { getXY('client', event, page); page.x += document.documentElement.scrollLeft; page.y += document.documentElement.scrollTop; } else { getXY('page', event, page); } return page; } function getClientXY (event, client) { client = client || {}; if (event instanceof InteractEvent) { if (/inertiastart/.test(event.type)) { getClientXY(inertiaStatus.pointerUp, client); client.x += inertiaStatus.sx; client.y += inertiaStatus.sy; } else { client.x = event.clientX; client.y = event.clientY; } } else { // Opera Mobile handles the viewport and scrolling oddly getXY(isOperaMobile? 'screen': 'client', event, client); } return client; } function getScrollXY () { return { x: window.scrollX || document.documentElement.scrollLeft, y: window.scrollY || document.documentElement.scrollTop }; } function getElementRect (element) { var scroll = /ipad|iphone|ipod/i.test(navigator.userAgent) ? { x: 0, y: 0 } : getScrollXY(), clientRect = (element instanceof SVGElement)? element.getBoundingClientRect(): element.getClientRects()[0]; return clientRect && { left : clientRect.left + scroll.x, right : clientRect.right + scroll.x, top : clientRect.top + scroll.y, bottom: clientRect.bottom + scroll.y, width : clientRect.width || clientRect.right - clientRect.left, height: clientRect.heigh || clientRect.bottom - clientRect.top }; } function getTouchPair (event) { var touches = []; if (event instanceof Array) { touches[0] = event[0]; touches[1] = event[1]; } else if (PointerEvent) { touches[0] = pointerMoves[0]; touches[1] = pointerMoves[1]; } else { touches[0] = event.touches[0]; if (event.type === 'touchend' && event.touches.length === 1) { touches[1] = event.changedTouches[0]; } else { touches[1] = event.touches[1]; } } return touches; } function touchAverage (event) { var touches = getTouchPair(event); return { pageX: (touches[0].pageX + touches[1].pageX) / 2, pageY: (touches[0].pageY + touches[1].pageY) / 2, clientX: (touches[0].clientX + touches[1].clientX) / 2, clientY: (touches[0].clientY + touches[1].clientY) / 2, }; } function touchBBox (event) { if (!(event.touches && event.touches.length) && !(PointerEvent && pointerMoves.length)) { return; } var touches = getTouchPair(event), minX = Math.min(touches[0].pageX, touches[1].pageX), minY = Math.min(touches[0].pageY, touches[1].pageY), maxX = Math.max(touches[0].pageX, touches[1].pageX), maxY = Math.max(touches[0].pageY, touches[1].pageY); return { x: minX, y: minY, left: minX, top: minY, width: maxX - minX, height: maxY - minY }; } function touchDistance (event) { var deltaSource = (target && target.options || defaultOptions).deltaSource, sourceX = deltaSource + 'X', sourceY = deltaSource + 'Y', touches = getTouchPair(event); var dx = touches[0][sourceX] - touches[1][sourceX], dy = touches[0][sourceY] - touches[1][sourceY]; return hypot(dx, dy); } function touchAngle (event, prevAngle) { var deltaSource = (target && target.options || defaultOptions).deltaSource, sourceX = deltaSource + 'X', sourceY = deltaSource + 'Y', touches = getTouchPair(event), dx = touches[0][sourceX] - touches[1][sourceX], dy = touches[0][sourceY] - touches[1][sourceY], angle = 180 * Math.atan(dy / dx) / Math.PI; if (typeof prevAngle === 'number') { var dr = angle - prevAngle, drClamped = dr % 360; if (drClamped > 315) { angle -= 360 + (angle / 360)|0 * 360; } else if (drClamped > 135) { angle -= 180 + (angle / 360)|0 * 360; } else if (drClamped < -315) { angle += 360 + (angle / 360)|0 * 360; } else if (drClamped < -135) { angle += 180 + (angle / 360)|0 * 360; } } return angle; } function getOriginXY (interactable, element) { interactable = interactable || target; var origin = interactable ? interactable.options.origin : defaultOptions.origin; element = element || interactable._element; if (origin === 'parent') { origin = element.parentNode; } else if (origin === 'self') { origin = element; } if (isElement(origin)) { origin = getElementRect(origin); origin.x = origin.left; origin.y = origin.top; } else if (typeof origin === 'function') { origin = origin(interactable && element); } return origin; } function calcRects (interactableList) { for (var i = 0, len = interactableList.length; i < len; i++) { interactableList[i].rect = interactableList[i].getRect(); } } function inertiaFrame () { var options = inertiaStatus.target.options.inertia, lambda = options.resistance, t = new Date().getTime() / 1000 - inertiaStatus.t0; if (t < inertiaStatus.te) { var progress = 1 - (Math.exp(-lambda * t) - inertiaStatus.lambda_v0) / inertiaStatus.one_ve_v0; if (inertiaStatus.modifiedXe === inertiaStatus.xe && inertiaStatus.modifiedYe === inertiaStatus.ye) { inertiaStatus.sx = inertiaStatus.xe * progress; inertiaStatus.sy = inertiaStatus.ye * progress; } else { var quadPoint = getQuadraticCurvePoint( 0, 0, inertiaStatus.xe, inertiaStatus.ye, inertiaStatus.modifiedXe, inertiaStatus.modifiedYe, progress); inertiaStatus.sx = quadPoint.x; inertiaStatus.sy = quadPoint.y; } pointerMove(inertiaStatus.startEvent); inertiaStatus.i = reqFrame(inertiaFrame); } else { inertiaStatus.sx = inertiaStatus.modifiedXe; inertiaStatus.sy = inertiaStatus.modifiedYe; inertiaStatus.active = false; pointerMove(inertiaStatus.startEvent); pointerUp(inertiaStatus.startEvent); } } function _getQBezierValue(t, p1, p2, p3) { var iT = 1 - t; return iT * iT * p1 + 2 * iT * t * p2 + t * t * p3; } function getQuadraticCurvePoint(startX, startY, cpX, cpY, endX, endY, position) { return { x: _getQBezierValue(position, startX, cpX, endX), y: _getQBezierValue(position, startY, cpY, endY) }; } // Test for the element that's "above" all other qualifiers function resolveDrops (elements) { if (elements.length) { var dropzone, deepestZone = elements[0], parent, deepestZoneParents = [], dropzoneParents = [], child, i, n; for (i = 1; i < elements.length; i++) { dropzone = elements[i]; if (!deepestZoneParents.length) { parent = deepestZone; while (parent.parentNode !== document) { deepestZoneParents.unshift(parent); parent = parent.parentNode; } } // if this element is an svg element and the current deepest is // an HTMLElement if (deepestZone instanceof HTMLElement && dropzone instanceof SVGElement && !(dropzone instanceof SVGSVGElement)) { if (dropzone === deepestZone.parentNode) { continue; } parent = dropzone.ownerSVGElement; } else { parent = dropzone; } dropzoneParents = []; while (parent.parentNode !== document) { dropzoneParents.unshift(parent); parent = parent.parentNode; } // get (position of last common ancestor) + 1 n = 0; while(dropzoneParents[n] && dropzoneParents[n] === deepestZoneParents[n]) { n++; } var parents = [ dropzoneParents[n - 1], dropzoneParents[n], deepestZoneParents[n] ]; child = parents[0].lastChild; while (child) { if (child === parents[1]) { deepestZone = dropzone; deepestZoneParents = []; break; } else if (child === parents[2]) { break; } child = child.previousSibling; } } return { element: deepestZone, index: elements.indexOf(deepestZone) }; } } function getDrop (event, element) { if (dropzones.length || selectorDZs.length) { var i, drops = [], elements = [], selectorDrops = [], selectorElements = [], drop, dropzone; element = element || target._element; // collect all element dropzones that qualify for a drop for (i = 0; i < dropzones.length; i++) { var current = dropzones[i]; // if the dropzone has an accept option, test against it if (isElement(current.options.accept)) { if (current.options.accept !== element) { continue; } } else if (typeof current.options.accept === 'string') { if (!element[matchesSelector](current.options.accept)) { continue; } } if (element !== current._element && current.dropCheck(event, target, element)) { drops.push(current); elements.push(current._element); } } // get the most apprpriate dropzone based on DOM depth and order drop = resolveDrops(elements); dropzone = drop? drops[drop.index]: null; if (selectorDZs.length) { for (i = 0; i < selectorDZs.length; i++) { var selector = selectorDZs[i], nodeList = document.querySelectorAll(selector.selector); for (var j = 0, len = nodeList.length; j < len; j++) { selector._element = nodeList[j]; selector.rect = selector.getRect(); // if the dropzone has an accept option, test against it if (isElement(selector.options.accept)) { if (selector.options.accept !== element) { continue; } } else if (typeof selector.options.accept === 'string') { if (!element[matchesSelector](selector.options.accept)) { continue; } } if (selector._element !== element && elements.indexOf(selector._element) === -1 && selectorElements.indexOf(selector._element === -1) && selector.dropCheck(event, target)) { selectorDrops.push(selector); selectorElements.push(selector._element); } } } if (selectorElements.length) { if (dropzone) { selectorDrops.push(dropzone); selectorElements.push(dropzone._element); } drop = resolveDrops(selectorElements); if (drop) { dropzone = selectorDrops[drop.index]; if (dropzone.selector) { dropzone._element = selectorElements[drop.index]; } } } } return dropzone? { dropzone: dropzone, element: dropzone._element }: null; } } function InteractEvent (event, action, phase, element, related) { var client, page, deltaSource = (target && target.options || defaultOptions).deltaSource, sourceX = deltaSource + 'X', sourceY = deltaSource + 'Y', options = target? target.options: defaultOptions, origin = getOriginXY(target, element); element = element || target._element; if (action === 'gesture' && !PointerEvent) { var average = touchAverage(event); page = { x: (average.pageX - origin.x), y: (average.pageY - origin.y) }; client = { x: (average.clientX - origin.x), y: (average.clientY - origin.y) }; } else { page = getPageXY(event); client = getClientXY(event); page.x -= origin.x; page.y -= origin.y; client.x -= origin.x; client.y -= origin.y; if (options.snapEnabled && options.snap.actions.indexOf(action) !== -1) { this.snap = { range : snapStatus.range, locked : snapStatus.locked, x : snapStatus.x, y : snapStatus.y, realX : snapStatus.realX, realY : snapStatus.realY, dx : snapStatus.dx, dy : snapStatus.dy }; if (snapStatus.locked) { page.x += snapStatus.dx; page.y += snapStatus.dy; client.x += snapStatus.dx; client.y += snapStatus.dy; } } } if (target.options.restrict[action] && restrictStatus.restricted) { page.x += restrictStatus.dx; page.y += restrictStatus.dy; client.x += restrictStatus.dx; client.y += restrictStatus.dy; this.restrict = { dx: restrictStatus.dx, dy: restrictStatus.dy }; } this.pageX = page.x; this.pageY = page.y; this.clientX = client.x; this.clientY = client.y; if (phase === 'start' && !(event instanceof InteractEvent)) { setEventXY(startCoords, this); } this.x0 = startCoords.pageX; this.y0 = startCoords.pageY; this.clientX0 = startCoords.clientX; this.clientY0 = startCoords.clientY; this.ctrlKey = event.ctrlKey; this.altKey = event.altKey; this.shiftKey = event.shiftKey; this.metaKey = event.metaKey; this.button = event.button; this.target = element; this.t0 = downTime; this.type = action + (phase || ''); if (inertiaStatus.active) { this.detail = 'inertia'; } if (related) { this.relatedTarget = related; } if (prevEvent && prevEvent.detail === 'inertia' && !inertiaStatus.active && options.inertia.zeroResumeDelta) { this.dx = this.dy = 0; } // end event dx, dy is difference between start and end points else if (phase === 'end' || action === 'drop') { if (deltaSource === 'client') { this.dx = client.x - startCoords.clientX; this.dy = client.y - startCoords.clientY; } else { this.dx = page.x - startCoords.pageX; this.dy = page.y - startCoords.pageY; } } // copy properties from previousmove if starting inertia else if (phase === 'inertiastart') { this.dx = prevEvent.dx; this.dy = prevEvent.dy; } else { if (deltaSource === 'client') { this.dx = client.x - prevEvent.clientX; this.dy = client.y - prevEvent.clientY; } else { this.dx = page.x - prevEvent.pageX; this.dy = page.y - prevEvent.pageY; } } if (action === 'resize') { if (options.squareResize || event.shiftKey) { if (resizeAxes === 'y') { this.dx = this.dy; } else { this.dy = this.dx; } this.axes = 'xy'; } else { this.axes = resizeAxes; if (resizeAxes === 'x') { this.dy = 0; } else if (resizeAxes === 'y') { this.dx = 0; } } } else if (action === 'gesture') { this.touches = (PointerEvent ? [pointerMoves[0], pointerMoves[1]] : event.touches); if (phase === 'start') { this.distance = touchDistance(event); this.box = touchBBox(event); this.scale = 1; this.ds = 0; this.angle = touchAngle(event); this.da = 0; } else if (phase === 'end' || event instanceof InteractEvent) { this.distance = prevEvent.distance; this.box = prevEvent.box; this.scale = prevEvent.scale; this.ds = this.scale - 1; this.angle = prevEvent.angle; this.da = this.angle - gesture.startAngle; } else { this.distance = touchDistance(event); this.box = touchBBox(event); this.scale = this.distance / gesture.startDistance; this.angle = touchAngle(event, gesture.prevAngle); this.ds = this.scale - gesture.prevScale; this.da = this.angle - gesture.prevAngle; } } if (phase === 'start') { this.timeStamp = downTime; this.dt = 0; this.duration = 0; this.speed = 0; this.velocityX = 0; this.velocityY = 0; } else if (phase === 'inertiastart') { this.timeStamp = new Date().getTime(); this.dt = prevEvent.dt; this.duration = prevEvent.duration; this.speed = prevEvent.speed; this.velocityX = prevEvent.velocityX; this.velocityY = prevEvent.velocityY; } else { this.timeStamp = new Date().getTime(); this.dt = this.timeStamp - prevEvent.timeStamp; this.duration = this.timeStamp - downTime; var dx, dy, dt; // Use natural event coordinates (without snapping/restricions) // subtract modifications from previous event if event given is // not a native event if (phase === 'end' || event instanceof InteractEvent) { // change in time in seconds // use event sequence duration for end events // => average speed of the event sequence // (minimum dt of 1ms) dt = Math.max((phase === 'end'? this.duration: this.dt) / 1000, 0.001); dx = this[sourceX] - prevEvent[sourceX]; dy = this[sourceY] - prevEvent[sourceY]; if (this.snap && this.snap.locked) { dx -= this.snap.dx; dy -= this.snap.dy; } if (this.restrict) { dx -= this.restrict.dx; dy -= this.restrict.dy; } if (prevEvent.snap && prevEvent.snap.locked) { dx -= (prevEvent[sourceX] - prevEvent.snap.dx); dy -= (prevEvent[sourceY] - prevEvent.snap.dy); } if (prevEvent.restrict) { dx += prevEvent.restrict.dx; dy += prevEvent.restrict.dy; } // speed and velocity in pixels per second this.speed = hypot(dx, dy) / dt; this.velocityX = dx / dt; this.velocityY = dy / dt; } // if normal move event, use previous user event coords else { this.speed = pointerDelta[deltaSource + 'Speed']; this.velocityX = pointerDelta[deltaSource + 'VX']; this.velocityY = pointerDelta[deltaSource + 'VY']; } } } InteractEvent.prototype = { preventDefault: blank, stopImmediatePropagation: function () { this.immediatePropagationStopped = this.propagationStopped = true; }, stopPropagation: function () { this.propagationStopped = true; } }; function preventOriginalDefault () { this.originalEvent.preventDefault(); } function fireTaps (event, targets, elements) { var tap = {}, prop, i; for (prop in event) { if (event.hasOwnProperty(prop)) { tap[prop] = event[prop]; } } tap.preventDefault = preventOriginalDefault; tap.stopPropagation = InteractEvent.prototype.stopPropagation; tap.stopImmediatePropagation = InteractEvent.prototype.stopImmediatePropagation; tap.timeStamp = new Date().getTime(); tap.originalEvent = event; tap.dt = tap.timeStamp - downTime; tap.type = 'tap'; var interval = tap.timeStamp - tapTime, dbl = (prevTap && prevTap.type !== 'dubletap' && prevTap.target === tap.target && interval < 500); tapTime = tap.timeStamp; for (i = 0; i < targets.length; i++) { var origin = getOriginXY(targets[i], elements[i]); tap.pageX -= origin.x; tap.pageY -= origin.y; tap.clientX -= origin.x; tap.clientY -= origin.y; tap.currentTarget = elements[i]; targets[i].fire(tap); if (tap.immediatePropagationStopped ||(tap.propagationStopped && targets[i + 1] !== tap.currentTarget)) { break; } } if (dbl) { var doubleTap = {}; for (prop in tap) { doubleTap[prop] = tap[prop]; } doubleTap.dt = interval; doubleTap.type = 'doubletap'; for (i = 0; i < targets.length; i++) { doubleTap.currentTarget = elements[i]; targets[i].fire(doubleTap); if (doubleTap.immediatePropagationStopped ||(doubleTap.propagationStopped && targets[i + 1] !== doubleTap.currentTarget)) { break; } } prevTap = doubleTap; } else { prevTap = tap; } } function collectTaps (event) { if(downEvent) { if (pointerWasMoved || !(event instanceof downEvent.constructor) || downEvent.target !== event.target) { return; } } var tapTargets = [], tapElements = []; var element = event.target; while (element) { if (interact.isSet(element)) { tapTargets.push(interact(element)); tapElements.push(element); } for (var selector in selectors) { var elements = Element.prototype[matchesSelector] === IE8MatchesSelector ? document.querySelectorAll(selector) : undefined; if (element !== document && element[matchesSelector](selector, elements)) { tapTargets.push(selectors[selector]); tapElements.push(element); } } element = element.parentNode; } if (tapTargets.length) { fireTaps(event, tapTargets, tapElements); } } // Check if action is enabled globally and the current target supports it // If so, return the validated action. Otherwise, return null function validateAction (action, interactable) { if (typeof action !== 'string') { return null; } interactable = interactable || target; var actionType = action.indexOf('resize') !== -1? 'resize': action, options = (interactable || target).options; if (( (actionType === 'resize' && options.resizable ) || (action === 'drag' && options.draggable ) || (action === 'gesture' && options.gesturable)) && actionIsEnabled[actionType]) { if (action === 'resize' || action === 'resizeyx') { action = 'resizexy'; } return action; } return null; } function selectorDown (event) { if (prepared && downEvent && event.type !== downEvent.type) { if (!(/^input$|^textarea$/i.test(target._element.nodeName))) { event.preventDefault(); } return; } // try to ignore browser simulated mouse after touch if (downEvent && event.type === 'mousedown' && downEvent.type === 'touchstart' && event.timeStamp - downEvent.timeStamp < 300) { return; } var element = (event.target instanceof SVGElementInstance ? event.target.correspondingUseElement : event.target), action; if (PointerEvent) { addPointer(event); } // Check if the down event hits the current inertia target if (inertiaStatus.active && target.selector) { // climb up the DOM tree from the event target while (element && element !== document) { // if this element is the current inertia target element if (element === inertiaStatus.targetElement // and the prospective action is the same as the ongoing one && validateAction(target.getAction(event)) === prepared) { // stop inertia so that the next move will be a normal one cancelFrame(inertiaStatus.i); inertiaStatus.active = false; if (PointerEvent) { // add the pointer to the gesture object addPointer(event, selectorGesture); } return; } element = element.parentNode; } } // do nothing if interacting if (dragging || resizing || gesturing) { return; } if (matches.length && /mousedown|pointerdown/i.test(event.type)) { action = validateSelector(event, matches); } else { var selector, elements; while (element && element !== document && !action) { matches = []; for (selector in selectors) { elements = Element.prototype[matchesSelector] === IE8MatchesSelector? document.querySelectorAll(selector): undefined; if (element[matchesSelector](selector, elements)) { selectors[selector]._element = element; matches.push(selectors[selector]); } } action = validateSelector(event, matches); element = element.parentNode; } } if (action) { pointerIsDown = true; prepared = action; return pointerDown(event, action); } else { // do these now since pointerDown isn't being called from here downTime = new Date().getTime(); downEvent = event; setEventXY(prevCoords, event); pointerWasMoved = false; } } // Determine action to be performed on next pointerMove and add appropriate // style and event Liseners function pointerDown (event, forceAction) { if (!forceAction && pointerIsDown && downEvent && event.type !== downEvent.type) { if (!(/^input$|^textarea$/i.test(target._element.nodeName))) { event.preventDefault(); } return; } pointerIsDown = true; if (PointerEvent) { addPointer(event); } // If it is the second touch of a multi-touch gesture, keep the target // the same if a target was set by the first touch // Otherwise, set the target if there is no action prepared if ((((event.touches && event.touches.length < 2) || (pointerIds && pointerIds.length < 2)) && !target) || !prepared) { target = interactables.get(event.currentTarget); } var options = target && target.options; if (target && !(dragging || resizing || gesturing)) { var action = validateAction(forceAction || target.getAction(event)); setEventXY(startCoords, event); if (PointerEvent && event instanceof PointerEvent) { // Dom modification seems to reset the gesture target if (!target._gesture.target) { target._gesture.target = target._element; } addPointer(event, target._gesture); } if (!action) { return event; } pointerWasMoved = false; if (options.styleCursor) { document.documentElement.style.cursor = actions[action].cursor; } resizeAxes = action === 'resizexy'? 'xy': action === 'resizex'? 'x': action === 'resizey'? 'y': ''; if (action === 'gesture' && ((event.touches && event.touches.length < 2) || PointerEvent && pointerIds.length < 2)) { action = null; } prepared = action; snapStatus.x = null; snapStatus.y = null; downTime = new Date().getTime(); downEvent = event; setEventXY(prevCoords, event); pointerWasMoved = false; if (!(/^input$|^textarea$/i.test(target._element.nodeName))) { event.preventDefault(); } } // if inertia is active try to resume action else if (inertiaStatus.active && event.currentTarget === inertiaStatus.targetElement && target === inertiaStatus.target && validateAction(target.getAction(event)) === prepared) { cancelFrame(inertiaStatus.i); inertiaStatus.active = false; if (PointerEvent) { if (!target._gesture.target) { target._gesture.target = target._element; } // add the pointer to the gesture object addPointer(event, target._gesture); } } } function setSnapping (event, status) { var snap = target.options.snap, anchors = snap.anchors, page, closest, range, inRange, snapChanged, dx, dy, distance, i, len; status = status || snapStatus; if (status.useStatusXY) { page = { x: status.x, y: status.y }; } else { var origin = getOriginXY(target); page = getPageXY(event); page.x -= origin.x; page.y -= origin.y; } status.realX = page.x; status.realY = page.y; // change to infinite range when range is negative if (snap.range < 0) { snap.range = Infinity; } // create an anchor representative for each path's returned point if (snap.mode === 'path') { anchors = []; for (i = 0, len = snap.paths.length; i < len; i++) { var path = snap.paths[i]; if (typeof path === 'function') { path = path(page.x, page.y); } anchors.push({ x: typeof path.x === 'number' ? path.x : page.x, y: typeof path.y === 'number' ? path.y : page.y, range: typeof path.range === 'number'? path.range: snap.range }); } } if ((snap.mode === 'anchor' || snap.mode === 'path') && anchors.length) { closest = { anchor: null, distance: 0, range: 0, dx: 0, dy: 0 }; for (i = 0, len = anchors.length; i < len; i++) { var anchor = anchors[i]; range = typeof anchor.range === 'number'? anchor.range: snap.range; dx = anchor.x - page.x; dy = anchor.y - page.y; distance = hypot(dx, dy); inRange = distance < range; // Infinite anchors count as being out of range // compared to non infinite ones that are in range if (range === Infinity && closest.inRange && closest.range !== Infinity) { inRange = false; } if (!closest.anchor || (inRange? // is the closest anchor in range? (closest.inRange && range !== Infinity)? // the pointer is relatively deeper in this anchor distance / range < closest.distance / closest.range: //the pointer is closer to this anchor distance < closest.distance: // The other is not in range and the pointer is closer to this anchor (!closest.inRange && distance < closest.distance))) { if (range === Infinity) { inRange = true; } closest.anchor = anchor; closest.distance = distance; closest.range = range; closest.inRange = inRange; closest.dx = dx; closest.dy = dy; status.range = range; } } inRange = closest.inRange; snapChanged = (closest.anchor.x !== status.x || closest.anchor.y !== status.y); status.x = closest.anchor.x; status.y = closest.anchor.y; status.dx = closest.dx; status.dy = closest.dy; } else if (snap.mode === 'grid') { var gridx = Math.round((page.x - snap.gridOffset.x) / snap.grid.x), gridy = Math.round((page.y - snap.gridOffset.y) / snap.grid.y), newX = gridx * snap.grid.x + snap.gridOffset.x, newY = gridy * snap.grid.y + snap.gridOffset.y; dx = newX - page.x; dy = newY - page.y; distance = hypot(dx, dy); inRange = distance < snap.range; snapChanged = (newX !== status.x || newY !== status.y); status.x = newX; status.y = newY; status.dx = dx; status.dy = dy; status.range = snap.range; } status.changed = (snapChanged || (inRange && !status.locked)); status.locked = inRange; return status; } function setRestriction (event, status) { var action = interact.currentAction() || prepared, restriction = target && target.options.restrict[action], page; status = status || restrictStatus; page = status.useStatusXY ? page = { x: status.x, y: status.y } : page = getPageXY(event); if (status.snap && status.snap.locked) { page.x += status.snap.dx || 0; page.y += status.snap.dy || 0; } status.dx = 0; status.dy = 0; status.restricted = false; if (!action || !restriction) { return status; } var rect; if (restriction === 'parent') { restriction = target._element.parentNode; } else if (restriction === 'self') { restriction = target._element; } if (isElement(restriction)) { rect = getElementRect(restriction); } else { if (typeof restriction === 'function') { restriction = restriction(page.x, page.y, target._element); } rect = restriction; // object is assumed to have // x, y, width, height or // left, top, right, bottom if ('x' in restriction && 'y' in restriction) { rect = { left : restriction.x, top : restriction.y, right : restriction.x + restriction.width, bottom: restriction.y + restriction.height }; } } status.dx = Math.max(Math.min(rect.right , page.x), rect.left) - page.x; status.dy = Math.max(Math.min(rect.bottom, page.y), rect.top ) - page.y; status.restricted = true; return status; } function pointerMove (event, preEnd) { if (!pointerIsDown) { return; } if (!(event instanceof InteractEvent)) { setEventXY(curCoords, event); } // register movement of more than 1 pixel if (!pointerWasMoved) { var dx = curCoords.clientX - prevCoords.clientX, dy = curCoords.clientY - prevCoords.clientY; pointerWasMoved = hypot(dx, dy) > 1; } // return if there is no prepared action if (!prepared // or this is a mousemove event but the down event was a touch || (event.type === 'mousemove' && downEvent.type === 'touchstart')) { return; } if (pointerWasMoved // ignore movement while inertia is active && (!inertiaStatus.active || (event instanceof InteractEvent && /inertiastart/.test(event.type)))) { // if just starting an action, calculate the pointer speed now if (!(dragging || resizing || gesturing)) { setEventDeltas(pointerDelta, prevCoords, curCoords); } if (prepared && target) { var shouldRestrict = target.options.restrictEnabled && (!target.options.restrict.endOnly || preEnd), starting = !(dragging || resizing || gesturing), snapEvent = starting? downEvent: event; if (starting) { prevEvent = downEvent; } if (!shouldRestrict) { restrictStatus.restricted = false; } // check for snap if (target.options.snapEnabled && target.options.snap.actions.indexOf(prepared) !== -1 && (!target.options.snap.endOnly || preEnd)) { setSnapping(snapEvent); // move if snapping doesn't prevent it or a restriction is in place if ((snapStatus.changed || !snapStatus.locked) || shouldRestrict) { if (shouldRestrict) { setRestriction(event); } actions[prepared].moveListener(event); } } // if no snap, always move else { if (shouldRestrict) { setRestriction(event); } actions[prepared].moveListener(event); } } } if (!(event instanceof InteractEvent)) { // set pointer coordinate, time changes and speeds setEventDeltas(pointerDelta, prevCoords, curCoords); setEventXY(prevCoords, event); } if (dragging || resizing) { autoScroll.edgeMove(event); } } function addPointer (event, gesture) { // dont add the event if it's not the same pointer type as the previous event if (pointerMoves.length && pointerMoves[0].pointerType !== event.pointerType) { return; } if (gesture) { gesture.addPointer(event.pointerId); } var index = pointerIds.indexOf(event.pointerId); if (index === -1) { pointerIds.push(event.pointerId); pointerMoves.push(event); } else { pointerMoves[index] = event; } } function removePointer (event) { var index = pointerIds.indexOf(event.pointerId); if (index === -1) { return; } pointerIds.splice(index, 1); pointerMoves.splice(index, 1); } function recordPointers (event) { var index = pointerIds.indexOf(event.pointerId); if (index === -1) { return; } if (/move/i.test(event.type)) { pointerMoves[index] = event; } else if (/up|cancel/i.test(event.type)) { removePointer(event); // End the gesture InteractEvent if there are // fewer than 2 active pointers if (gesturing && pointerIds.length < 2) { target._gesture.stop(); } } } function dragMove (event) { event.preventDefault(); var dragEvent, dragEnterEvent, dragLeaveEvent, dropTarget, leaveDropTarget; if (!dragging) { dragEvent = new InteractEvent(downEvent, 'drag', 'start'); dragging = true; target.fire(dragEvent); if (!dynamicDrop) { calcRects(dropzones); for (var i = 0; i < selectorDZs.length; i++) { selectorDZs[i]._elements = document.querySelectorAll(selectorDZs[i].selector); } } prevEvent = dragEvent; // set snapping for the next move event if (target.options.snapEnabled && !target.options.snap.endOnly) { setSnapping(event); } } dragEvent = new InteractEvent(event, 'drag', 'move'); var draggableElement = target._element, drop = getDrop(dragEvent, draggableElement); if (drop) { dropTarget = drop.dropzone; dropElement = drop.element; } else { dropTarget = dropElement = null; } // Make sure that the target selector draggable's element is // restored after dropChecks target._element = draggableElement; if (dropElement !== prevDropElement) { // if there was a prevDropTarget, create a dragleave event if (prevDropTarget) { dragLeaveEvent = new InteractEvent(event, 'drag', 'leave', prevDropElement, draggableElement); dragEvent.dragLeave = prevDropElement; leaveDropTarget = prevDropTarget; prevDropTarget = prevDropElement = null; } // if the dropTarget is not null, create a dragenter event if (dropTarget) { dragEnterEvent = new InteractEvent(event, 'drag', 'enter', dropElement, draggableElement); dragEvent.dragEnter = dropTarget._element; prevDropTarget = dropTarget; prevDropElement = prevDropTarget._element; } } target.fire(dragEvent); if (dragLeaveEvent) { leaveDropTarget.fire(dragLeaveEvent); } if (dragEnterEvent) { dropTarget.fire(dragEnterEvent); } prevEvent = dragEvent; } function resizeMove (event) { event.preventDefault(); var resizeEvent; if (!resizing) { resizeEvent = new InteractEvent(downEvent, 'resize', 'start'); target.fire(resizeEvent); target.fire(resizeEvent); resizing = true; prevEvent = resizeEvent; // set snapping for the next move event if (target.options.snapEnabled && !target.options.snap.endOnly) { setSnapping(event); } } resizeEvent = new InteractEvent(event, 'resize', 'move'); target.fire(resizeEvent); prevEvent = resizeEvent; } function gestureMove (event) { if ((!event.touches || event.touches.length < 2) && !PointerEvent) { return; } event.preventDefault(); var gestureEvent; if (!gesturing) { gestureEvent = new InteractEvent(downEvent, 'gesture', 'start'); gestureEvent.ds = 0; gesture.startDistance = gesture.prevDistance = gestureEvent.distance; gesture.startAngle = gesture.prevAngle = gestureEvent.angle; gesture.scale = 1; gesturing = true; target.fire(gestureEvent); prevEvent = gestureEvent; // set snapping for the next move event if (target.options.snapEnabled && !target.options.snap.endOnly) { setSnapping(event); } } gestureEvent = new InteractEvent(event, 'gesture', 'move'); gestureEvent.ds = gestureEvent.scale - gesture.scale; target.fire(gestureEvent); prevEvent = gestureEvent; gesture.prevAngle = gestureEvent.angle; gesture.prevDistance = gestureEvent.distance; if (gestureEvent.scale !== Infinity && gestureEvent.scale !== null && gestureEvent.scale !== undefined && !isNaN(gestureEvent.scale)) { gesture.scale = gestureEvent.scale; } } function validateSelector (event, matches) { for (var i = 0, len = matches.length; i < len; i++) { var match = matches[i], action = validateAction(match.getAction(event, match), match); if (action) { target = match; return action; } } } function pointerOver (event) { if (pointerIsDown || dragging || resizing || gesturing) { return; } var curMatches = [], prevTargetElement = target && target._element, eventTarget = (event.target instanceof SVGElementInstance ? event.target.correspondingUseElement : event.target); for (var selector in selectors) { if (selectors.hasOwnProperty(selector) && selectors[selector] && eventTarget[matchesSelector](selector)) { selectors[selector]._element = eventTarget; curMatches.push(selectors[selector]); } } var elementInteractable = interactables.get(eventTarget), elementAction = elementInteractable && validateAction( elementInteractable.getAction(event), elementInteractable); if (elementAction) { target = elementInteractable; matches = []; } else { if (validateSelector(event, curMatches)) { matches = curMatches; pointerHover(event, matches); events.addToElement(eventTarget, 'mousemove', pointerHover); } else if (target) { var prevTargetChildren = prevTargetElement.querySelectorAll('*'); if (Array.prototype.indexOf.call(prevTargetChildren, eventTarget) !== -1) { // reset the elements of the matches to the old target for (var i = 0; i < matches.length; i++) { matches[i]._element = prevTargetElement; } pointerHover(event, matches); events.addToElement(target._element, 'mousemove', pointerHover); } else { target = null; matches = []; } } } } function pointerOut (event) { if (pointerIsDown || dragging || resizing || gesturing) { return; } // Remove temporary event listeners for selector Interactables var eventTarget = (event.target instanceof SVGElementInstance ? event.target.correspondingUseElement : event.target); if (!interactables.get(eventTarget)) { events.removeFromElement(eventTarget, pointerHover); } if (target && target.options.styleCursor && !(dragging || resizing || gesturing)) { document.documentElement.style.cursor = ''; } } // Check what action would be performed on pointerMove target if a mouse // button were pressed and change the cursor accordingly function pointerHover (event, matches) { if (!(pointerIsDown || dragging || resizing || gesturing)) { var action; if (matches) { action = validateSelector(event, matches); } else if (target) { action = validateAction(target.getAction(event)); } if (target && target.options.styleCursor) { if (action) { document.documentElement.style.cursor = actions[action].cursor; } else { document.documentElement.style.cursor = ''; } } } else if (prepared) { event.preventDefault(); } } // End interact move events and stop auto-scroll unless inertia is enabled function pointerUp (event) { // don't return if the event is an InteractEvent (in the case of inertia end) // or if the browser uses PointerEvents (event would always be a gestureend) if (!(event instanceof InteractEvent || PointerEvent) && pointerIsDown && downEvent && !(event instanceof downEvent.constructor)) { return; } if (event.touches && event.touches.length >= 2) { return; } // Stop native GestureEvent inertia if (GestureEvent && (event instanceof GestureEvent) && /inertiastart/i.test(event.type)) { event.gestureObject.stop(); return; } var endEvent, inertiaOptions = target && target.options.inertia, prop; if (dragging || resizing || gesturing) { if (inertiaStatus.active) { return; } var deltaSource =target.options.deltaSource, pointerSpeed = pointerDelta[deltaSource + 'Speed']; // check if inertia should be started if (target.options.inertiaEnabled && prepared !== 'gesture' && inertiaOptions.actions.indexOf(prepared) !== -1 && event !== inertiaStatus.startEvent && (new Date().getTime() - curCoords.timeStamp) < 50 && pointerSpeed > inertiaOptions.minSpeed && pointerSpeed > inertiaOptions.endSpeed) { var lambda = inertiaOptions.resistance, inertiaDur = -Math.log(inertiaOptions.endSpeed / pointerSpeed) / lambda, startEvent; inertiaStatus.active = true; inertiaStatus.target = target; inertiaStatus.targetElement = target._element; if (events.useAttachEvent) { // make a copy of the pointerdown event because IE8 // http://stackoverflow.com/a/3533725/2280888 for (prop in event) { if (event.hasOwnProperty(prop)) { inertiaStatus.pointerUp[prop] = event[prop]; } } } else { inertiaStatus.pointerUp = event; } inertiaStatus.startEvent = startEvent = new InteractEvent(event, 'drag', 'inertiastart'); inertiaStatus.vx0 = pointerDelta[deltaSource + 'VX']; inertiaStatus.vy0 = pointerDelta[deltaSource + 'VY']; inertiaStatus.v0 = pointerSpeed; inertiaStatus.x0 = prevEvent.pageX; inertiaStatus.y0 = prevEvent.pageY; inertiaStatus.t0 = inertiaStatus.startEvent.timeStamp / 1000; inertiaStatus.sx = inertiaStatus.sy = 0; inertiaStatus.modifiedXe = inertiaStatus.xe = (inertiaStatus.vx0 - inertiaDur) / lambda; inertiaStatus.modifiedYe = inertiaStatus.ye = (inertiaStatus.vy0 - inertiaDur) / lambda; inertiaStatus.te = inertiaDur; inertiaStatus.lambda_v0 = lambda / inertiaStatus.v0; inertiaStatus.one_ve_v0 = 1 - inertiaOptions.endSpeed / inertiaStatus.v0; var startX = startEvent.pageX, startY = startEvent.pageY, statusObject; if (startEvent.snap && startEvent.snap.locked) { startX -= startEvent.snap.dx; startY -= startEvent.snap.dy; } if (startEvent.restrict) { startX -= startEvent.restrict.dx; startY -= startEvent.restrict.dy; } statusObject = { useStatusXY: true, x: startX + inertiaStatus.xe, y: startY + inertiaStatus.ye, dx: 0, dy: 0, snap: null }; statusObject.snap = statusObject; if (target.options.snapEnabled && target.options.snap.endOnly) { var snap = setSnapping(event, statusObject); if (snap.locked) { inertiaStatus.modifiedXe += snap.dx; inertiaStatus.modifiedYe += snap.dy; } } if (target.options.restrictEnabled && target.options.restrict.endOnly) { var restrict = setRestriction(event, statusObject); inertiaStatus.modifiedXe += restrict.dx; inertiaStatus.modifiedYe += restrict.dy; } cancelFrame(inertiaStatus.i); inertiaStatus.i = reqFrame(inertiaFrame); target.fire(inertiaStatus.startEvent); return; } if ((target.options.snapEnabled && target.options.snap.endOnly) || (target.options.restrictEnabled && target.options.restrict.endOnly)) { // fire a move event at the snapped coordinates pointerMove(event, true); } } if (dragging) { endEvent = new InteractEvent(event, 'drag', 'end'); var dropEvent, draggableElement = target._element, drop = getDrop(endEvent, draggableElement); if (drop) { dropTarget = drop.dropzone; dropElement = drop.element; } else { dropTarget = null; dropElement = null; } // getDrop changes target._element target._element = draggableElement; // get the most apprpriate dropzone based on DOM depth and order if (dropTarget) { dropEvent = new InteractEvent(event, 'drop', null, dropElement, draggableElement); endEvent.dropzone = dropElement; } // if there was a prevDropTarget (perhaps if for some reason this // dragend happens without the mouse moving of the previous drop // target) else if (prevDropTarget) { var dragLeaveEvent = new InteractEvent(event, 'drag', 'leave', dropElement, draggableElement); prevDropTarget.fire(dragLeaveEvent, draggableElement); endEvent.dragLeave = prevDropElement; } target.fire(endEvent); if (dropEvent) { dropTarget.fire(dropEvent); } } else if (resizing) { endEvent = new InteractEvent(event, 'resize', 'end'); target.fire(endEvent); } else if (gesturing) { endEvent = new InteractEvent(event, 'gesture', 'end'); target.fire(endEvent); } interact.stop(); } // bound to document when a listener is added to a selector interactable function delegateListener (event, useCapture) { var fakeEvent = {}, selectors = delegatedEvents[event.type], selector, element = event.target, i; useCapture = useCapture? true: false; // duplicate the event so that currentTarget can be changed for (var prop in event) { fakeEvent[prop] = event[prop]; } fakeEvent.preventDefault = function () { event.preventDefault(); }; // climb up document tree looking for selector matches while (element && element !== document) { for (selector in selectors) { if (element[matchesSelector](selector)) { var listeners = selectors[selector]; fakeEvent.currentTarget = element; for (i = 0; i < listeners.length; i++) { if (listeners[i][1] !== useCapture) { continue; } try { listeners[i][0](fakeEvent); } catch (error) { console.error('Error thrown from delegated listener: ' + '"' + selector + '" ' + event.type + ' ' + (listeners[i][0].name? listeners[i][0].name: '')); console.log(error); } } } } element = element.parentNode; } } function delegateUseCapture (event) { return delegateListener.call(this, event, true); } interactables.indexOfElement = dropzones.indexOfElement = function indexOfElement (element) { for (var i = 0; i < this.length; i++) { var interactable = this[i]; if (interactable.selector === element || (!interactable.selector && interactable._element === element)) { return i; } } return -1; }; interactables.get = function interactableGet (element) { if (typeof element === 'string') { return selectors[element]; } return this[this.indexOfElement(element)]; }; dropzones.get = function dropzoneGet (element) { return this[this.indexOfElement(element)]; }; function clearTargets () { if (target && !target.selector) { target = null; } dropTarget = dropElement = prevDropTarget = prevDropElement = null; } /*\ * interact [ method ] * * The methods of this variable can be used to set elements as * interactables and also to change various default settings. * * Calling it as a function and passing an element or a valid CSS selector * string returns an Interactable object which has various methods to * configure it. * - element (Element | string) The HTML or SVG Element to interact with or CSS selector = (object) An @Interactable * > Usage | interact(document.getElementById('draggable')).draggable(true); | | var rectables = interact('rect'); | rectables | .gesturable(true) | .on('gesturemove', function (event) { | // something cool... | }) | .autoScroll(true); \*/ function interact (element) { return interactables.get(element) || new Interactable(element); } // A class for easy inheritance and setting of an Interactable's options function IOptions (options) { for (var option in defaultOptions) { if (options.hasOwnProperty(option) && typeof options[option] === typeof defaultOptions[option]) { this[option] = options[option]; } } } IOptions.prototype = defaultOptions; /*\ * Interactable [ property ] ** * Object type returned by @interact \*/ function Interactable (element, options) { this._element = element; this._iEvents = this._iEvents || {}; if (typeof element === 'string') { // if the selector is invalid, // an exception will be raised document.querySelector(element); selectors[element] = this; this.selector = element; this._gesture = selectorGesture; } else { if(isElement(element)) { if (PointerEvent) { events.add(this, 'pointerdown', pointerDown ); events.add(this, 'pointermove', pointerHover); this._gesture = new Gesture(); this._gesture.target = element; } else { events.add(this, 'mousedown' , pointerDown ); events.add(this, 'mousemove' , pointerHover); events.add(this, 'touchstart', pointerDown ); events.add(this, 'touchmove' , pointerHover); } } elements.push(this); } interactables.push(this); this.set(options); } Interactable.prototype = { setOnEvents: function (action, phases) { if (action === 'drop') { var drop = phases.ondrop || phases.onDrop || phases.drop, dragenter = phases.ondragenter || phases.onDropEnter || phases.dragenter, dragleave = phases.ondragleave || phases.onDropLeave || phases.dragleave; if (typeof drop === 'function') { this.ondrop = drop ; } if (typeof dragenter === 'function') { this.ondragenter = dragenter; } if (typeof dragleave === 'function') { this.ondragleave = dragleave; } } else { var start = phases.onstart || phases.onStart || phases.start, move = phases.onmove || phases.onMove || phases.move, end = phases.onend || phases.onEnd || phases.end; var inertiastart = phases.oninertiastart || phases.onInertiaStart || phases.inertiastart; action = 'on' + action; if (typeof start === 'function') { this[action + 'start'] = start; } if (typeof move === 'function') { this[action + 'move' ] = move ; } if (typeof end === 'function') { this[action + 'end' ] = end ; } if (typeof inertiastart === 'function') { this[action + 'inertiastart' ] = inertiastart ; } } return this; }, /*\ * Interactable.draggable [ method ] * * Gets or sets whether drag actions can be performed on the * Interactable * = (boolean) Indicates if this can be the target of drag events | var isDraggable = interact('ul li').draggable(); * or - options (boolean | object) #optional true/false or An object with event listeners to be fired on drag events (object makes the Interactable draggable) = (object) This Interactable | interact(element).draggable({ | onstart: function (event) {}, | onmove : function (event) {}, | onend : function (event) {} | }); \*/ draggable: function (options) { if (options instanceof Object) { this.options.draggable = true; this.setOnEvents('drag', options); return this; } if (typeof options === 'boolean') { this.options.draggable = options; return this; } if (options === null) { delete this.options.draggable; return this; } return this.options.draggable; }, /*\ * Interactable.dropzone [ method ] * * Returns or sets whether elements can be dropped onto this * Interactable to trigger drop events * - options (boolean | object | null) #optional The new value to be set. = (boolean | object) The current setting or this Interactable \*/ dropzone: function (options) { if (options instanceof Object) { this.options.dropzone = true; this.setOnEvents('drop', options); this.accept(options.accept); (this.selector? selectorDZs: dropzones).push(this); if (!dynamicDrop && !this.selector) { this.rect = this.getRect(); } return this; } if (typeof options === 'boolean') { if (options) { (this.selector? selectorDZs: dropzones).push(this); if (!dynamicDrop && !this.selector) { this.rect = this.getRect(); } } else { var array = this.selector? selectorDZs: dropzones, index = array.indexOf(this); if (index !== -1) { array.splice(index, 1); } } this.options.dropzone = options; return this; } if (options === null) { delete this.options.dropzone; return this; } return this.options.dropzone; }, /*\ * Interactable.dropCheck [ method ] * * The default function to determine if a dragend event occured over * this Interactable's element. Can be overridden using * @Interactable.dropChecker. * - event (MouseEvent | TouchEvent) The event that ends a drag = (boolean) whether the pointer was over this Interactable \*/ dropCheck: function (event, draggable, element) { var page = getPageXY(event), origin = getOriginXY(draggable, element), horizontal, vertical; page.x += origin.x; page.y += origin.y; if (dynamicDrop) { this.rect = this.getRect(); } if (!this.rect) { return false; } horizontal = (page.x > this.rect.left) && (page.x < this.rect.right); vertical = (page.y > this.rect.top ) && (page.y < this.rect.bottom); return horizontal && vertical; }, /*\ * Interactable.dropChecker [ method ] * * Gets or sets the function used to check if a dragged element is * over this Interactable. See @Interactable.dropCheck. * - checker (function) #optional * The checker is a function which takes a mouseUp/touchEnd event as a * parameter and returns true or false to indicate if the the current * draggable can be dropped into this Interactable * = (Function | Interactable) The checker function or this Interactable \*/ dropChecker: function (newValue) { if (typeof newValue === 'function') { this.dropCheck = newValue; return this; } return this.dropCheck; }, /*\ * Interactable.accept [ method ] * * Gets or sets the Element or CSS selector match that this * Interactable accepts if it is a dropzone. * - newValue (Element | string | null) #optional * If it is an Element, then only that element can be dropped into this dropzone. * If it is a string, the element being dragged must match it as a selector. * If it is null, the accept options is cleared - it accepts any element. * = (string | Element | null | Interactable) The current accept option if given `undefined` or this Interactable \*/ accept: function (newValue) { if (isElement(newValue)) { this.options.accept = newValue; return this; } if (typeof newValue === 'string') { // test if it is a valid CSS selector document.querySelector(newValue); this.options.accept = newValue; return this; } if (newValue === null) { delete this.options.accept; return this; } return this.options.accept; }, /*\ * Interactable.resizable [ method ] * * Gets or sets whether resize actions can be performed on the * Interactable * = (boolean) Indicates if this can be the target of resize elements | var isResizeable = interact('input[type=text]').resizable(); * or - options (boolean | object) #optional true/false or An object with event listeners to be fired on resize events (object makes the Interactable resizable) = (object) This Interactable | interact(element).resizable({ | onstart: function (event) {}, | onmove : function (event) {}, | onend : function (event) {} | }); \*/ resizable: function (options) { if (options instanceof Object) { this.options.resizable = true; this.setOnEvents('resize', options); return this; } if (typeof options === 'boolean') { this.options.resizable = options; return this; } return this.options.resizable; }, // misspelled alias resizeable: blank, /*\ * Interactable.squareResize [ method ] * * Gets or sets whether resizing is forced 1:1 aspect * = (boolean) Current setting * * or * - newValue (boolean) #optional = (object) this Interactable \*/ squareResize: function (newValue) { if (typeof newValue === 'boolean') { this.options.squareResize = newValue; return this; } if (newValue === null) { delete this.options.squareResize; return this; } return this.options.squareResize; }, /*\ * Interactable.gesturable [ method ] * * Gets or sets whether multitouch gestures can be performed on the * Interactable's element * = (boolean) Indicates if this can be the target of gesture events | var isGestureable = interact(element).gesturable(); * or - options (boolean | object) #optional true/false or An object with event listeners to be fired on gesture events (makes the Interactable gesturable) = (object) this Interactable | interact(element).gesturable({ | onmove: function (event) {} | }); \*/ gesturable: function (options) { if (options instanceof Object) { this.options.gesturable = true; this.setOnEvents('gesture', options); return this; } if (typeof options === 'boolean') { this.options.gesturable = options; return this; } if (options === null) { delete this.options.gesturable; return this; } return this.options.gesturable; }, // misspelled alias gestureable: blank, /*\ * Interactable.autoScroll [ method ] * * Returns or sets whether or not any actions near the edges of the * window/container trigger autoScroll for this Interactable * = (boolean | object) * `false` if autoScroll is disabled; object with autoScroll properties * if autoScroll is enabled * * or * - options (object | boolean | null) #optional * options can be: * - an object with margin, distance and interval properties, * - true or false to enable or disable autoScroll or * - null to use default settings = (Interactable) this Interactable \*/ autoScroll: function (options) { var defaults = defaultOptions.autoScroll; if (options instanceof Object) { var autoScroll = this.options.autoScroll; if (autoScroll === defaults) { autoScroll = this.options.autoScroll = { margin : defaults.margin, distance : defaults.distance, interval : defaults.interval, container: defaults.container }; } autoScroll.margin = this.validateSetting('autoScroll', 'margin', options.margin); autoScroll.speed = this.validateSetting('autoScroll', 'speed' , options.speed); autoScroll.container = (isElement(options.container) || options.container instanceof window.Window ? options.container : defaults.container); this.options.autoScrollEnabled = true; this.options.autoScroll = autoScroll; return this; } if (typeof options === 'boolean') { this.options.autoScrollEnabled = options; return this; } if (options === null) { delete this.options.autoScrollEnabled; delete this.options.autoScroll; return this; } return (this.options.autoScrollEnabled ? this.options.autoScroll : false); }, /*\ * Interactable.snap [ method ] ** * Returns or sets if and how action coordinates are snapped ** = (boolean | object) `false` if snap is disabled; object with snap properties if snap is enabled ** * or ** - options (object | boolean | null) #optional = (Interactable) this Interactable > Usage | interact('.handle').snap({ | mode : 'grid', // event coords should snap to the corners of a grid | range : Infinity, // the effective distance of snap ponts | grid : { x: 100, y: 100 }, // the x and y spacing of the grid points | gridOffset : { x: 0, y: 0 }, // the offset of the grid points | }); | | interact('.handle').snap({ | mode : 'anchor', // snap to specified points | anchors : [ | { x: 100, y: 100, range: 25 }, // a point with x, y and a specific range | { x: 200, y: 200 } // a point with x and y. it uses the default range | ] | }); | | interact(document.querySelector('#thing')).snap({ | mode : 'path', | paths: [ | { // snap to points on these x and y axes | x: 100, | y: 100, | range: 25 | }, | // give this function the x and y page coords and snap to the object returned | function (x, y) { | return { | x: x, | y: (75 + 50 * Math.sin(x * 0.04)), | range: 40 | }; | }] | }) | | interact(element).snap({ | // do not snap during normal movement. | // Instead, trigger only one snapped move event | // immediately before the end event. | endOnly: true | }); \*/ snap: function (options) { var defaults = defaultOptions.snap; if (options instanceof Object) { var snap = this.options.snap; if (snap === defaults) { snap = {}; } snap.mode = this.validateSetting('snap', 'mode' , options.mode); snap.endOnly = this.validateSetting('snap', 'endOnly' , options.endOnly); snap.actions = this.validateSetting('snap', 'actions' , options.actions); snap.range = this.validateSetting('snap', 'range' , options.range); snap.paths = this.validateSetting('snap', 'paths' , options.paths); snap.grid = this.validateSetting('snap', 'grid' , options.grid); snap.gridOffset = this.validateSetting('snap', 'gridOffset', options.gridOffset); snap.anchors = this.validateSetting('snap', 'anchors' , options.anchors); this.options.snapEnabled = true; this.options.snap = snap; return this; } if (typeof options === 'boolean') { this.options.snapEnabled = options; return this; } if (options === null) { delete this.options.snapEnabled; delete this.options.snap; return this; } return (this.options.snapEnabled ? this.options.snap : false); }, /*\ * Interactable.inertia [ method ] ** * Returns or sets if and how events continue to run after the pointer is released ** = (boolean | object) `false` if inertia is disabled; `object` with inertia properties if inertia is enabled ** * or ** - options (object | boolean | null) #optional = (Interactable) this Interactable > Usage | // enable and use default settings | interact(element).inertia(true); | | // enable and use custom settings | interact(element).inertia({ | // value greater than 0 | // high values slow the object down more quickly | resistance : 16, | | // the minimum launch speed (pixels per second) that results in inertiastart | minSpeed : 200, | | // inertia will stop when the object slows down to this speed | endSpeed : 20, | | // an array of action types that can have inertia (no gesture) | actions : ['drag', 'resize'], | | // boolean; should the jump when resuming from inertia be ignored in event.dx/dy | zeroResumeDelta: false | }); | | // reset custom settings and use all defaults | interact(element).inertia(null); \*/ inertia: function (options) { var defaults = defaultOptions.inertia; if (options instanceof Object) { var inertia = this.options.inertia; if (inertia === defaults) { inertia = this.options.inertia = { resistance : defaults.resistance, minSpeed : defaults.minSpeed, endSpeed : defaults.endSpeed, actions : defaults.actions, zeroResumeDelta: defaults.zeroResumeDelta }; } inertia.resistance = this.validateSetting('inertia', 'resistance' , options.resistance); inertia.minSpeed = this.validateSetting('inertia', 'minSpeed' , options.minSpeed); inertia.endSpeed = this.validateSetting('inertia', 'endSpeed' , options.endSpeed); inertia.actions = this.validateSetting('inertia', 'actions' , options.actions); inertia.zeroResumeDelta = this.validateSetting('inertia', 'zeroResumeDelta', options.zeroResumeDelta); this.options.inertiaEnabled = true; this.options.inertia = inertia; return this; } if (typeof options === 'boolean') { this.options.inertiaEnabled = options; return this; } if (options === null) { delete this.options.inertiaEnabled; delete this.options.inertia; return this; } return (this.options.inertiaEnabled ? this.options.inertia : false); }, /*\ * Interactable.getAction [ method ] * * The default function to get the action resulting from a pointer * event. overridden using @Interactable.actionChecker * - event (object) The mouse/touch event * = (string | null) The action (drag/resize[axes]/gesture) or null if none can be performed \*/ getAction: function actionCheck (event) { var rect = this.getRect(), right, bottom, action, page = getPageXY(event), options = this.options; if (actionIsEnabled.resize && options.resizable) { right = page.x > (rect.right - margin); bottom = page.y > (rect.bottom - margin); } resizeAxes = (right?'x': '') + (bottom?'y': ''); action = (resizeAxes)? 'resize' + resizeAxes: actionIsEnabled.drag && options.draggable? 'drag': null; if (actionIsEnabled.gesture && ((event.touches && event.touches.length >= 2) || (PointerEvent && pointerIds.length >=2)) && !(dragging || resizing)) { action = 'gesture'; } return action; }, /*\ * Interactable.actionChecker [ method ] * * Gets or sets the function used to check action to be performed on * pointerDown * - checker (function) #optional A function which takes a mouse or touch event event as a parameter and returns 'drag' 'resize' or 'gesture' or null = (Function | Interactable) The checker function or this Interactable \*/ actionChecker: function (newValue) { if (typeof newValue === 'function') { this.getAction = newValue; return this; } if (newValue === null) { delete this.options.getAction; return this; } return this.getAction; }, /*\ * Interactable.getRect [ method ] * * The default function to get an Interactables bounding rect. Can be * overridden using @Interactable.rectChecker. * = (object) The object's bounding rectangle. The properties are numbers with no units. o { o top: -, o left: -, o bottom: -, o right: -, o width: -, o height: - o } \*/ getRect: function rectCheck () { if (this.selector && !(isElement(this._element))) { this._element = document.querySelector(this.selector); } return getElementRect(this._element); }, /*\ * Interactable.rectChecker [ method ] * * Returns or sets the function used to calculate the interactable's * element's rectangle * - checker (function) #optional A function which returns this Interactable's bounding rectangle. See @Interactable.getRect = (function | object) The checker function or this Interactable \*/ rectChecker: function (newValue) { if (typeof newValue === 'function') { this.getRect = newValue; return this; } if (newValue === null) { delete this.options.getRect; return this; } return this.getRect; }, /*\ * Interactable.styleCursor [ method ] * * Returns or sets whether the action that would be performed when the * mouse on the element are checked on `mousemove` so that the cursor * may be styled appropriately * - newValue (function) #optional = (Function | Interactable) The current setting or this Interactable \*/ styleCursor: function (newValue) { if (typeof newValue === 'boolean') { this.options.styleCursor = newValue; return this; } if (newValue === null) { delete this.options.styleCursor; return this; } return this.options.styleCursor; }, /*\ * Interactable.origin [ method ] * * Gets or sets the origin of the Interactable's element. The x and y * of the origin will be subtracted from action event coordinates. * - origin (object) #optional An object with x and y properties which are numbers * OR - origin (Element) #optional An HTML or SVG Element whose rect will be used ** = (object) The current origin or this Interactable \*/ origin: function (newValue) { if (newValue instanceof Object || /^parent$|^self$/.test(newValue)) { this.options.origin = newValue; return this; } if (newValue === null) { delete this.options.origin; return this; } return this.options.origin; }, /*\ * Interactable.deltaSource [ method ] * * Returns or sets the mouse coordinate types used to calculate the * movement of the pointer. * - source (string) #optional Use 'client' if you will be scrolling while interacting; Use 'page' if you want autoScroll to work = (string | object) The current deltaSource or this Interactable \*/ deltaSource: function (newValue) { if (newValue === 'page' || newValue === 'client') { this.options.deltaSource = newValue; return this; } if (newValue === null) { delete this.options.deltaSource; return this; } return this.options.deltaSource; }, /*\ * Interactable.restrict [ method ] * * Returns or sets the rectangles within which actions on this * interactable (after snap calculations) are restricted. * - newValue (object) #optional an object with keys drag, resize, and/or gesture and rects or Elements as values = (object) The current restrictions object or this Interactable ** | interact(element).restrict({ | // the rect will be `interact.getElementRect(element.parentNode)` | drag: element.parentNode, | | // x and y are relative to the the interactable's origin | resize: { x: 100, y: 100, width: 200, height: 200 } | }) | | interact('.draggable').restrict({ | // the rect will be the selected element's parent | drag: 'parent', | | // do not restrict during normal movement. | // Instead, trigger only one restricted move event | // immediately before the end event. | endOnly: true | }); \*/ restrict: function (newValue) { if (newValue === undefined) { return this.options.restrict; } if (newValue instanceof Object) { var newRestrictions = {}; if (newValue.drag instanceof Object || /^parent$|^self$/.test(newValue.drag)) { newRestrictions.drag = newValue.drag; } if (newValue.resize instanceof Object || /^parent$|^self$/.test(newValue.resize)) { newRestrictions.resize = newValue.resize; } if (newValue.gesture instanceof Object || /^parent$|^self$/.test(newValue.gesture)) { newRestrictions.gesture = newValue.gesture; } if (typeof newValue.endOnly === 'boolean') { newRestrictions.endOnly = newValue.endOnly; } this.options.restrictEnabled = true; this.options.restrict = newRestrictions; } else if (newValue === null) { delete this.options.restrict; delete this.options.restrictEnabled; } return this; }, /*\ * Interactable.validateSetting [ method ] * - context (string) eg. 'snap', 'autoScroll' - option (string) The name of the value being set - value (any type) The value being validated * = (typeof value) A valid value for the give context-option pair * - null if defaultOptions[context][value] is undefined * - value if it is the same type as defaultOptions[context][value], * - this.options[context][value] if it is the same type as defaultOptions[context][value], * - or defaultOptions[context][value] \*/ validateSetting: function (context, option, value) { var defaults = defaultOptions[context], current = this.options[context]; if (defaults !== undefined && defaults[option] !== undefined) { if ('objectTypes' in defaults && defaults.objectTypes.test(option)) { if (value instanceof Object) { return value; } else { return (option in current && current[option] instanceof Object ? current [option] : defaults[option]); } } if ('arrayTypes' in defaults && defaults.arrayTypes.test(option)) { if (value instanceof Array) { return value; } else { return (option in current && current[option] instanceof Array ? current[option] : defaults[option]); } } if ('stringTypes' in defaults && defaults.stringTypes.test(option)) { if (typeof value === 'string') { return value; } else { return (option in current && typeof current[option] === 'string' ? current[option] : defaults[option]); } } if ('numberTypes' in defaults && defaults.numberTypes.test(option)) { if (typeof value === 'number') { return value; } else { return (option in current && typeof current[option] === 'number' ? current[option] : defaults[option]); } } if ('boolTypes' in defaults && defaults.boolTypes.test(option)) { if (typeof value === 'boolean') { return value; } else { return (option in current && typeof current[option] === 'boolean' ? current[option] : defaults[option]); } } if ('elementTypes' in defaults && defaults.elementTypes.test(option)) { if (isElement(value)) { return value; } else { return (option in current && isElement(current[option]) ? current[option] : defaults[option]); } } } return null; }, /*\ * Interactable.element [ method ] * * If this is not a selector Interactable, it returns the element this * interactable represents * = (Element) HTML / SVG Element \*/ element: function () { return this._element; }, /*\ * Interactable.fire [ method ] * * Calls listeners for the given InteractEvent type bound globablly * and directly to this Interactable * - iEvent (InteractEvent) The InteractEvent object to be fired on this Interactable = (Interactable) this Interactable \*/ fire: function (iEvent) { if (!(iEvent && iEvent.type) || eventTypes.indexOf(iEvent.type) === -1) { return this; } var listeners, fireState = 0, i = 0, len, onEvent = 'on' + iEvent.type; // Try-catch and loop so an exception thrown from a listener // doesn't ruin everything for everyone while (fireState < 3) { try { switch (fireState) { // Interactable#on() listeners case fireStates.directBind: if (iEvent.type in this._iEvents) { listeners = this._iEvents[iEvent.type]; for (len = listeners.length; i < len && !iEvent.immediatePropagationStopped; i++) { listeners[i](iEvent); } break; } break; // interactable.onevent listener case fireStates.onevent: if (typeof this[onEvent] === 'function') { this[onEvent](iEvent); } break; // interact.on() listeners case fireStates.globalBind: if (iEvent.type in globalEvents && (listeners = globalEvents[iEvent.type])) { for (len = listeners.length; i < len && !iEvent.immediatePropagationStopped; i++) { listeners[i](iEvent); } } } if (iEvent.propagationStopped) { break; } i = 0; fireState++; } catch (error) { console.error('Error thrown from ' + iEvent.type + ' listener'); console.error(error); i++; if (fireState === fireStates.onevent) { fireState++; } } } return this; }, /*\ * Interactable.on [ method ] * * Binds a listener for an InteractEvent or DOM event. * - eventType (string) The type of event to listen for - listener (function) The function to be called on that event - useCapture (boolean) #optional useCapture flag for addEventListener = (object) This Interactable \*/ on: function (eventType, listener, useCapture) { if (eventType === 'wheel') { eventType = wheelEvent; } if (eventTypes.indexOf(eventType) !== -1) { // if this type of event was never bound to this Interactable if (!(eventType in this._iEvents)) { this._iEvents[eventType] = [listener]; } // if the event listener is not already bound for this type else if (this._iEvents[eventType].indexOf(listener) === -1) { this._iEvents[eventType].push(listener); } } // delegated event for selector else if (this.selector) { if (!delegatedEvents[eventType]) { delegatedEvents[eventType] = {}; } var delegated = delegatedEvents[eventType]; if (!delegated[this.selector]) { delegated[this.selector] = []; } // keep listener and useCapture flag delegated[this.selector].push([listener, useCapture? true: false]); // add appropriate delegate listener events.add(docTarget, eventType, useCapture? delegateUseCapture: delegateListener, useCapture); } else { events.add(this, eventType, listener, useCapture); } return this; }, /*\ * Interactable.off [ method ] * * Removes an InteractEvent or DOM event listener * - eventType (string) The type of event that was listened for - listener (function) The listener function to be removed - useCapture (boolean) #optional useCapture flag for removeEventListener = (object) This Interactable \*/ off: function (eventType, listener, useCapture) { var eventList, index = -1; // convert to boolean useCapture = useCapture? true: false; if (eventType === 'wheel') { eventType = wheelEvent; } // if it is an action event type if (eventTypes.indexOf(eventType) !== -1) { eventList = this._iEvents[eventType]; if (eventList && (index = eventList.indexOf(listener)) !== -1) { this._iEvents[eventType].splice(index, 1); } } // delegated event else if (this.selector) { var delegated = delegatedEvents[eventType]; if (delegated && (eventList = delegated[this.selector])) { // look for listener with matching useCapture flag for (index = 0; index < eventList.length; index++) { if (eventList[index][1] === useCapture) { break; } } // remove found listener from delegated list if (index < eventList.length) { eventList.splice(index, 1); } } } // remove listener from this Interatable's element else { events.remove(this._element, listener, useCapture); } return this; }, /*\ * Interactable.set [ method ] * * Reset the options of this Interactable - options (object) The new settings to apply = (object) This Interactablw \*/ set: function (options) { if (!options || typeof options !== 'object') { options = {}; } this.options = new IOptions(options); this.draggable ('draggable' in options? options.draggable : this.options.draggable ); this.dropzone ('dropzone' in options? options.dropzone : this.options.dropzone ); this.resizable ('resizable' in options? options.resizable : this.options.resizable ); this.gesturable('gesturable' in options? options.gesturable: this.options.gesturable); if ('autoScroll' in options) { this.autoScroll (options.autoScroll ); } return this; }, /*\ * Interactable.unset [ method ] * * Remove this interactable from the list of interactables and remove * it's drag, drop, resize and gesture capabilities * = (object) @interact \*/ unset: function () { events.remove(this, 'all'); if (typeof this.selector === 'string') { delete selectors[this.selector]; } else { events.remove(this, 'all'); if (this.options.styleCursor) { this._element.style.cursor = ''; } if (this._gesture) { this._gesture.target = null; } elements.splice(elements.indexOf(this.element())); } this.dropzone(false); interactables.splice(interactables.indexOf(this), 1); return interact; } }; Interactable.prototype.gestureable = Interactable.prototype.gesturable; Interactable.prototype.resizeable = Interactable.prototype.resizable; /*\ * interact.isSet [ method ] * * Check if an element has been set - element (Element) The Element being searched for = (boolean) Indicates if the element or CSS selector was previously passed to interact \*/ interact.isSet = function(element) { return interactables.indexOfElement(element) !== -1; }; /*\ * interact.on [ method ] * * Adds a global listener for an InteractEvent or adds a DOM event to * `document` * - type (string) The type of event to listen for - listener (function) The function to be called on that event - useCapture (boolean) #optional useCapture flag for addEventListener = (object) interact \*/ interact.on = function (type, listener, useCapture) { // if it is an InteractEvent type, add listener to globalEvents if (eventTypes.indexOf(type) !== -1) { // if this type of event was never bound if (!globalEvents[type]) { globalEvents[type] = [listener]; } // if the event listener is not already bound for this type else if (globalEvents[type].indexOf(listener) === -1) { globalEvents[type].push(listener); } } // If non InteratEvent type, addEventListener to document else { events.add(docTarget, type, listener, useCapture); } return interact; }; /*\ * interact.off [ method ] * * Removes a global InteractEvent listener or DOM event from `document` * - type (string) The type of event that was listened for - listener (function) The listener function to be removed - useCapture (boolean) #optional useCapture flag for removeEventListener = (object) interact \*/ interact.off = function (type, listener, useCapture) { if (eventTypes.indexOf(type) === -1) { events.remove(docTarget, type, listener, useCapture); } else { var index; if (type in globalEvents && (index = globalEvents[type].indexOf(listener)) !== -1) { globalEvents[type].splice(index, 1); } } return interact; }; /*\ * interact.simulate [ method ] * * Simulate pointer down to begin to interact with an interactable element - action (string) The action to be performed - drag, resize, etc. - element (Element) The DOM Element to resize/drag - pointerEvent (object) #optional Pointer event whose pageX/Y coordinates will be the starting point of the interact drag/resize = (object) interact \*/ interact.simulate = function (action, element, pointerEvent) { var event = {}, prop, clientRect; if (action === 'resize') { action = 'resizexy'; } // return if the action is not recognised if (!(action in actions)) { return interact; } if (pointerEvent) { for (prop in pointerEvent) { if (pointerEvent.hasOwnProperty(prop)) { event[prop] = pointerEvent[prop]; } } } else { clientRect = (target._element instanceof SVGElement)? element.getBoundingClientRect(): clientRect = element.getClientRects()[0]; if (action === 'drag') { event.pageX = clientRect.left + clientRect.width / 2; event.pageY = clientRect.top + clientRect.height / 2; } else { event.pageX = clientRect.right; event.pageY = clientRect.bottom; } } event.target = event.currentTarget = element; event.preventDefault = event.stopPropagation = blank; pointerDown(event, action); return interact; }; /*\ * interact.enableDragging [ method ] * * Returns or sets whether dragging is enabled for any Interactables * - newValue (boolean) #optional `true` to allow the action; `false` to disable action for all Interactables = (boolean | object) The current setting or interact \*/ interact.enableDragging = function (newValue) { if (newValue !== null && newValue !== undefined) { actionIsEnabled.drag = newValue; return interact; } return actionIsEnabled.drag; }; /*\ * interact.enableResizing [ method ] * * Returns or sets whether resizing is enabled for any Interactables * - newValue (boolean) #optional `true` to allow the action; `false` to disable action for all Interactables = (boolean | object) The current setting or interact \*/ interact.enableResizing = function (newValue) { if (newValue !== null && newValue !== undefined) { actionIsEnabled.resize = newValue; return interact; } return actionIsEnabled.resize; }; /*\ * interact.enableGesturing [ method ] * * Returns or sets whether gesturing is enabled for any Interactables * - newValue (boolean) #optional `true` to allow the action; `false` to disable action for all Interactables = (boolean | object) The current setting or interact \*/ interact.enableGesturing = function (newValue) { if (newValue !== null && newValue !== undefined) { actionIsEnabled.gesture = newValue; return interact; } return actionIsEnabled.gesture; }; interact.eventTypes = eventTypes; /*\ * interact.debug [ method ] * * Returns debugging data = (object) An object with properties that outline the current state and expose internal functions and variables \*/ interact.debug = function () { return { target : target, dragging : dragging, resizing : resizing, gesturing : gesturing, prepared : prepared, prevCoords : prevCoords, downCoords : startCoords, pointerIds : pointerIds, pointerMoves : pointerMoves, addPointer : addPointer, removePointer : removePointer, recordPointers : recordPointers, inertia : inertiaStatus, downTime : downTime, downEvent : downEvent, prevEvent : prevEvent, Interactable : Interactable, IOptions : IOptions, interactables : interactables, dropzones : dropzones, pointerIsDown : pointerIsDown, defaultOptions : defaultOptions, actions : actions, dragMove : dragMove, resizeMove : resizeMove, gestureMove : gestureMove, pointerUp : pointerUp, pointerDown : pointerDown, pointerMove : pointerMove, pointerHover : pointerHover, events : events, globalEvents : globalEvents, delegatedEvents : delegatedEvents }; }; // expose the functions used to caluclate multi-touch properties interact.getTouchAverage = touchAverage; interact.getTouchBBox = touchBBox; interact.getTouchDistance = touchDistance; interact.getTouchAngle = touchAngle; interact.getElementRect = getElementRect; /*\ * interact.margin [ method ] * * Returns or sets the margin for autocheck resizing used in * @Interactable.getAction. That is the distance from the bottom and right * edges of an element clicking in which will start resizing * - newValue (number) #optional = (number | interact) The current margin value or interact \*/ interact.margin = function (newvalue) { if (typeof newvalue === 'number') { margin = newvalue; return interact; } return margin; }; /*\ * interact.styleCursor [ styleCursor ] * * Returns or sets whether the cursor style of the document is changed * depending on what action is being performed * - newValue (boolean) #optional = (boolean | interact) The current setting of interact \*/ interact.styleCursor = function (newValue) { if (typeof newValue === 'boolean') { defaultOptions.styleCursor = newValue; return interact; } return defaultOptions.styleCursor; }; /*\ * interact.autoScroll [ method ] * * Returns or sets whether or not actions near the edges of the window or * specified container element trigger autoScroll by default * - options (boolean | object) true or false to simply enable or disable or an object with margin, distance, container and interval properties = (object) interact * or = (boolean | object) `false` if autoscroll is disabled and the default autoScroll settings if it is enabled \*/ interact.autoScroll = function (options) { var defaults = defaultOptions.autoScroll; if (options instanceof Object) { defaultOptions.autoScrollEnabled = true; if (typeof (options.margin) === 'number') { defaults.margin = options.margin;} if (typeof (options.speed) === 'number') { defaults.speed = options.speed ;} defaults.container = (isElement(options.container) || options.container instanceof window.Window ? options.container : defaults.container); return interact; } if (typeof options === 'boolean') { defaultOptions.autoScrollEnabled = options; return interact; } // return the autoScroll settings if autoScroll is enabled // otherwise, return false return defaultOptions.autoScrollEnabled? defaults: false; }; /*\ * interact.snap [ method ] * * Returns or sets whether actions are constrained to a grid or a * collection of coordinates * - options (boolean | object) #optional New settings * `true` or `false` to simply enable or disable * or an object with some of the following properties o { o mode : 'grid', 'anchor' or 'path', o range : the distance within which snapping to a point occurs, o grid : { o x: the distance between x-axis snap points, o y: the distance between y-axis snap points o }, o gridOffset: { o x, y: the x/y-axis values of the grid origin o }, o anchors: [ o { o x: x coordinate to snap to, o y: y coordinate to snap to, o range: optional range for this anchor o } o { o another anchor o } o ] o } * = (object | interact) The default snap settings object or interact \*/ interact.snap = function (options) { var snap = defaultOptions.snap; if (options instanceof Object) { defaultOptions.snapEnabled = true; if (typeof options.mode === 'string' ) { snap.mode = options.mode; } if (typeof options.endOnly === 'boolean') { snap.endOnly = options.endOnly; } if (typeof options.range === 'number' ) { snap.range = options.range; } if (options.actions instanceof Array ) { snap.actions = options.actions; } if (options.anchors instanceof Array ) { snap.anchors = options.anchors; } if (options.grid instanceof Object) { snap.grid = options.grid; } if (options.gridOffset instanceof Object) { snap.gridOffset = options.gridOffset; } return interact; } if (typeof options === 'boolean') { defaultOptions.snapEnabled = options; return interact; } return { enabled : defaultOptions.snapEnabled, mode : snap.mode, actions : snap.actions, grid : snap.grid, gridOffset: snap.gridOffset, anchors : snap.anchors, paths : snap.paths, range : snap.range, locked : snapStatus.locked, x : snapStatus.x, y : snapStatus.y, realX : snapStatus.realX, realY : snapStatus.realY, dx : snapStatus.dx, dy : snapStatus.dy }; }; /*\ * interact.inertia [ method ] * * Returns or sets inertia settings. * * See @Interactable.inertia * - options (boolean | object) #optional New settings * `true` or `false` to simply enable or disable * or an object of inertia options = (object | interact) The default inertia settings object or interact \*/ interact.inertia = function (options) { var inertia = defaultOptions.inertia; if (options instanceof Object) { defaultOptions.inertiaEnabled = true; if (typeof options.resistance === 'number') { inertia.resistance = options.resistance;} if (typeof options.minSpeed === 'number') { inertia.minSpeed = options.minSpeed ;} if (typeof options.endSpeed === 'number') { inertia.endSpeed = options.endSpeed ;} if (typeof options.zeroResumeDelta === 'boolean') { inertia.zeroResumeDelta = options.zeroResumeDelta ;} if (options.actions instanceof Array) { inertia.actions = options.actions; } return interact; } if (typeof options === 'boolean') { defaultOptions.inertiaEnabled = options; return interact; } return { enabled: defaultOptions.inertiaEnabled, resistance: inertia.resistance, minSpeed: inertia.minSpeed, endSpeed: inertia.endSpeed, actions: inertia.actions, zeroResumeDelta: inertia.zeroResumeDelta }; }; /*\ * interact.supportsTouch [ method ] * = (boolean) Whether or not the browser supports touch input \*/ interact.supportsTouch = function () { return supportsTouch; }; /*\ * interact.currentAction [ method ] * = (string) What action is currently being performed \*/ interact.currentAction = function () { return (dragging && 'drag') || (resizing && 'resize') || (gesturing && 'gesture') || null; }; /*\ * interact.stop [ method ] * * Ends the current interaction * - event (Event) An event on which to call preventDefault() = (object) interact \*/ interact.stop = function (event) { if (dragging || resizing || gesturing) { autoScroll.stop(); matches = []; if (target.options.styleCursor) { document.documentElement.style.cursor = ''; } if (target._gesture) { target._gesture.stop(); } clearTargets(); for (var i = 0; i < selectorDZs.length; i++) { selectorDZs._elements = []; } // prevent Default only if were previously interacting if (event && typeof event.preventDefault === 'function') { event.preventDefault(); } } if (pointerIds && pointerIds.length) { pointerIds.splice(0); pointerMoves.splice(0); } pointerIsDown = snapStatus.locked = dragging = resizing = gesturing = false; prepared = prevEvent = null; // do not clear the downEvent so that it can be used to // test for browser-simulated mouse events after touch return interact; }; /*\ * interact.dynamicDrop [ method ] * * Returns or sets whether the dimensions of dropzone elements are * calculated on every dragmove or only on dragstart for the default * dropChecker * - newValue (boolean) #optional True to check on each move. False to check only before start = (boolean | interact) The current setting or interact \*/ interact.dynamicDrop = function (newValue) { if (typeof newValue === 'boolean') { if (dragging && dynamicDrop !== newValue && !newValue) { calcRects(dropzones); } dynamicDrop = newValue; return interact; } return dynamicDrop; }; /*\ * interact.deltaSource [ method ] * Returns or sets weather pageX/Y or clientX/Y is used to calculate dx/dy. * * See @Interactable.deltaSource * - newValue (string) #optional 'page' or 'client' = (string | Interactable) The current setting or interact \*/ interact.deltaSource = function (newValue) { if (newValue === 'page' || newValue === 'client') { defaultOptions.deltaSource = newValue; return this; } return defaultOptions.deltaSource; }; /*\ * interact.restrict [ method ] * * Returns or sets the default rectangles within which actions (after snap * calculations) are restricted. * * See @Interactable.restrict * - newValue (object) #optional an object with keys drag, resize, and/or gesture and rects or Elements as values = (object) The current restrictions object or interact \*/ interact.restrict = function (newValue) { var defaults = defaultOptions.restrict; if (newValue === undefined) { return defaultOptions.restrict; } if (newValue instanceof Object) { if (newValue.drag instanceof Object || /^parent$|^self$/.test(newValue.drag)) { defaults.drag = newValue.drag; } if (newValue.resize instanceof Object || /^parent$|^self$/.test(newValue.resize)) { defaults.resize = newValue.resize; } if (newValue.gesture instanceof Object || /^parent$|^self$/.test(newValue.gesture)) { defaults.gesture = newValue.gesture; } if (typeof newValue.endOnly === 'boolean') { defaults.endOnly = newValue.endOnly; } } else if (newValue === null) { defaults.drag = defaults.resize = defaults.gesture = null; defaults.endOnly = false; } return this; }; if (PointerEvent) { events.add(docTarget, 'pointerup', collectTaps); events.add(docTarget, 'pointerdown' , selectorDown); events.add(docTarget, 'MSGestureChange', pointerMove ); events.add(docTarget, 'MSGestureEnd' , pointerUp ); events.add(docTarget, 'MSInertiaStart' , pointerUp ); events.add(docTarget, 'pointerover' , pointerOver ); events.add(docTarget, 'pointerout' , pointerOut ); events.add(docTarget, 'pointermove' , recordPointers); events.add(docTarget, 'pointerup' , recordPointers); events.add(docTarget, 'pointercancel', recordPointers); // fix problems of wrong targets in IE events.add(docTarget, 'pointerup', function () { if (!(dragging || resizing || gesturing)) { pointerIsDown = false; } }); selectorGesture = new Gesture(); selectorGesture.target = document.documentElement; } else { events.add(docTarget, 'mouseup' , collectTaps); events.add(docTarget, 'touchend', collectTaps); events.add(docTarget, 'mousedown', selectorDown); events.add(docTarget, 'mousemove', pointerMove ); events.add(docTarget, 'mouseup' , pointerUp ); events.add(docTarget, 'mouseover', pointerOver ); events.add(docTarget, 'mouseout' , pointerOut ); events.add(docTarget, 'touchstart' , selectorDown); events.add(docTarget, 'touchmove' , pointerMove ); events.add(docTarget, 'touchend' , pointerUp ); events.add(docTarget, 'touchcancel', pointerUp ); } events.add(windowTarget, 'blur', pointerUp); try { if (window.frameElement) { parentDocTarget._element = window.frameElement.ownerDocument; events.add(parentDocTarget , 'mouseup' , pointerUp); events.add(parentDocTarget , 'touchend' , pointerUp); events.add(parentDocTarget , 'touchcancel' , pointerUp); events.add(parentDocTarget , 'pointerup' , pointerUp); events.add(parentWindowTarget, 'blur' , pointerUp); } } catch (error) { interact.windowParentError = error; } // For IE's lack of Event#preventDefault events.add(docTarget, 'selectstart', function (e) { if (dragging || resizing || gesturing) { e.preventDefault(); } }); // For IE8's lack of an Element#matchesSelector if (!(matchesSelector in Element.prototype) || typeof (Element.prototype[matchesSelector]) !== 'function') { Element.prototype[matchesSelector] = IE8MatchesSelector = function (selector, elems) { // http://tanalin.com/en/blog/2012/12/matches-selector-ie8/ // modified for better performance elems = elems || this.parentNode.querySelectorAll(selector); var count = elems.length; for (var i = 0; i < count; i++) { if (elems[i] === this) { return true; } } return false; }; } // requestAnimationFrame polyfill (function() { var lastTime = 0, vendors = ['ms', 'moz', 'webkit', 'o']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { reqFrame = window[vendors[x]+'RequestAnimationFrame']; cancelFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; } if (!reqFrame) { reqFrame = function(callback) { var currTime = new Date().getTime(), timeToCall = Math.max(0, 16 - (currTime - lastTime)), id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; } if (!cancelFrame) { cancelFrame = function(id) { clearTimeout(id); }; } }()); // http://documentcloud.github.io/underscore/docs/underscore.html#section-11 /* global exports: true, module */ if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = interact; } exports.interact = interact; } else { window.interact = interact; } } (this));
/** * @fileoverview Tests for use-isnan rule. * @author James Allardice, Michael Paulukonis */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var rule = require("../../../lib/rules/use-isnan"), RuleTester = require("../../../lib/testers/rule-tester"); //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ var ruleTester = new RuleTester(); ruleTester.run("use-isnan", rule, { valid: [ "var x = NaN;", "isNaN(NaN) === true;", "isNaN(123) !== true;", "Number.isNaN(NaN) === true;", "Number.isNaN(123) !== true;", "foo(NaN + 1);", "foo(1 + NaN);", "foo(NaN - 1)", "foo(1 - NaN)", "foo(NaN * 2)", "foo(2 * NaN)", "foo(NaN / 2)", "foo(2 / NaN)", "var x; if (x = NaN) { }" ], invalid: [ { code: "123 == NaN;", errors: [{ message: "Use the isNaN function to compare with NaN.", type: "BinaryExpression"}] }, { code: "123 === NaN;", errors: [{ message: "Use the isNaN function to compare with NaN.", type: "BinaryExpression"}] }, { code: "NaN === \"abc\";", errors: [{ message: "Use the isNaN function to compare with NaN.", type: "BinaryExpression"}] }, { code: "NaN == \"abc\";", errors: [{ message: "Use the isNaN function to compare with NaN.", type: "BinaryExpression"}] }, { code: "123 != NaN;", errors: [{ message: "Use the isNaN function to compare with NaN.", type: "BinaryExpression"}] }, { code: "123 !== NaN;", errors: [{ message: "Use the isNaN function to compare with NaN.", type: "BinaryExpression"}] }, { code: "NaN !== \"abc\";", errors: [{ message: "Use the isNaN function to compare with NaN.", type: "BinaryExpression"}] }, { code: "NaN != \"abc\";", errors: [{ message: "Use the isNaN function to compare with NaN.", type: "BinaryExpression"}] }, { code: "NaN < \"abc\";", errors: [{ message: "Use the isNaN function to compare with NaN.", type: "BinaryExpression"}] }, { code: "\"abc\" < NaN;", errors: [{ message: "Use the isNaN function to compare with NaN.", type: "BinaryExpression"}] }, { code: "NaN > \"abc\";", errors: [{ message: "Use the isNaN function to compare with NaN.", type: "BinaryExpression"}] }, { code: "\"abc\" > NaN;", errors: [{ message: "Use the isNaN function to compare with NaN.", type: "BinaryExpression"}] }, { code: "NaN <= \"abc\";", errors: [{ message: "Use the isNaN function to compare with NaN.", type: "BinaryExpression"}] }, { code: "\"abc\" <= NaN;", errors: [{ message: "Use the isNaN function to compare with NaN.", type: "BinaryExpression"}] }, { code: "NaN >= \"abc\";", errors: [{ message: "Use the isNaN function to compare with NaN.", type: "BinaryExpression"}] }, { code: "\"abc\" >= NaN;", errors: [{ message: "Use the isNaN function to compare with NaN.", type: "BinaryExpression"}] } ] });
var commands = require('./commands'); var pkg = require('../package.json'); var abbreviations = require('./abbreviations')(commands); function clearRuntimeCache() { // Note that in edge cases, some architecture components instance's // in-memory cache might be skipped. // If that's a problem, you should create and fresh instances instead. var PackageRepository = require('./core/PackageRepository'); PackageRepository.clearRuntimeCache(); } module.exports = { version: pkg.version, commands: commands, config: require('./config')(), abbreviations: abbreviations, reset: clearRuntimeCache };
CKEDITOR.plugins.setLang("image2","fr-ca",{alt:"Texte alternatif",btnUpload:"Envoyer sur le serveur",captioned:"Captioned image",captionPlaceholder:"Caption",infoTab:"Informations sur l'image2",lockRatio:"Verrouiller les proportions",menu:"Propriétés de l'image2",pathName:"image",pathNameCaption:"caption",resetSize:"Taille originale",resizer:"Click and drag to resize",title:"Propriétés de l'image2",uploadTab:"Téléverser",urlMissing:"L'URL de la source de l'image est manquant."});
var moment = require('../../moment'); /************************************************** Norwegian nynorsk *************************************************/ exports['locale:nn'] = { setUp : function (cb) { moment.locale('nn'); moment.createFromInputFallback = function () { throw new Error('input not handled by moment'); }; cb(); }, tearDown : function (cb) { moment.locale('en'); cb(); }, 'parse' : function (test) { var tests = 'januar jan_februar feb_mars mar_april apr_mai mai_juni jun_juli jul_august aug_september sep_oktober okt_november nov_desember des'.split('_'), i; function equalTest(input, mmm, i) { test.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } test.done(); }, 'format' : function (test) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'sundag, februar 14. 2010, 3:25:50 pm'], ['ddd, hA', 'sun, 3PM'], ['M Mo MM MMMM MMM', '2 2. 02 februar feb'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. sundag sun su'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '6 6. 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45. day of the year'], ['L', '14.02.2010'], ['LL', '14 februar 2010'], ['LLL', '14 februar 2010 15:25'], ['LLLL', 'sundag 14 februar 2010 15:25'], ['l', '14.2.2010'], ['ll', '14 feb 2010'], ['lll', '14 feb 2010 15:25'], ['llll', 'sun 14 feb 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { test.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } test.done(); }, 'format ordinal' : function (test) { test.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); test.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); test.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); test.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); test.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); test.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); test.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); test.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); test.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); test.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); test.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); test.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); test.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); test.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); test.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); test.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); test.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); test.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); test.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); test.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); test.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); test.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); test.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); test.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); test.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); test.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); test.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); test.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); test.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); test.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); test.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); test.done(); }, 'format month' : function (test) { var expected = 'januar jan_februar feb_mars mar_april apr_mai mai_juni jun_juli jul_august aug_september sep_oktober okt_november nov_desember des'.split('_'), i; for (i = 0; i < expected.length; i++) { test.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } test.done(); }, 'format week' : function (test) { var expected = 'sundag sun su_måndag mån må_tysdag tys ty_onsdag ons on_torsdag tor to_fredag fre fr_laurdag lau lø'.split('_'), i; for (i = 0; i < expected.length; i++) { test.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } test.done(); }, 'from' : function (test) { var start = moment([2007, 1, 28]); test.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'nokre sekund', '44 sekunder = a few seconds'); test.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'eit minutt', '45 seconds = a minute'); test.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'eit minutt', '89 seconds = a minute'); test.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minutt', '90 seconds = 2 minutes'); test.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minutt', '44 minutes = 44 minutes'); test.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'ein time', '45 minutes = an hour'); test.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'ein time', '89 minutes = an hour'); test.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 timar', '90 minutes = 2 hours'); test.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 timar', '5 hours = 5 hours'); test.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 timar', '21 hours = 21 hours'); test.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'ein dag', '22 hours = a day'); test.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'ein dag', '35 hours = a day'); test.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 dagar', '36 hours = 2 days'); test.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'ein dag', '1 day = a day'); test.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dagar', '5 days = 5 days'); test.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 dagar', '25 days = 25 days'); test.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'ein månad', '26 days = a month'); test.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'ein månad', '30 days = a month'); test.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'ein månad', '43 days = a month'); test.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 månader', '46 days = 2 months'); test.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 månader', '75 days = 2 months'); test.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 månader', '76 days = 3 months'); test.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'ein månad', '1 month = a month'); test.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 månader', '5 months = 5 months'); test.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'eit år', '345 days = a year'); test.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 år', '548 days = 2 years'); test.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'eit år', '1 year = a year'); test.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 år', '5 years = 5 years'); test.done(); }, 'suffix' : function (test) { test.equal(moment(30000).from(0), 'om nokre sekund', 'prefix'); test.equal(moment(0).from(30000), 'for nokre sekund sidan', 'suffix'); test.done(); }, 'now from now' : function (test) { test.equal(moment().fromNow(), 'for nokre sekund sidan', 'now from now should display as in the past'); test.done(); }, 'fromNow' : function (test) { test.equal(moment().add({s: 30}).fromNow(), 'om nokre sekund', 'in a few seconds'); test.equal(moment().add({d: 5}).fromNow(), 'om 5 dagar', 'in 5 days'); test.done(); }, 'calendar day' : function (test) { var a = moment().hours(2).minutes(0).seconds(0); test.equal(moment(a).calendar(), 'I dag klokka 02:00', 'today at the same time'); test.equal(moment(a).add({m: 25}).calendar(), 'I dag klokka 02:25', 'Now plus 25 min'); test.equal(moment(a).add({h: 1}).calendar(), 'I dag klokka 03:00', 'Now plus 1 hour'); test.equal(moment(a).add({d: 1}).calendar(), 'I morgon klokka 02:00', 'tomorrow at the same time'); test.equal(moment(a).subtract({h: 1}).calendar(), 'I dag klokka 01:00', 'Now minus 1 hour'); test.equal(moment(a).subtract({d: 1}).calendar(), 'I går klokka 02:00', 'yesterday at the same time'); test.done(); }, 'calendar next week' : function (test) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); test.equal(m.calendar(), m.format('dddd [klokka] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); test.equal(m.calendar(), m.format('dddd [klokka] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); test.equal(m.calendar(), m.format('dddd [klokka] LT'), 'Today + ' + i + ' days end of day'); } test.done(); }, 'calendar last week' : function (test) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); test.equal(m.calendar(), m.format('[Føregåande] dddd [klokka] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); test.equal(m.calendar(), m.format('[Føregåande] dddd [klokka] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); test.equal(m.calendar(), m.format('[Føregåande] dddd [klokka] LT'), 'Today - ' + i + ' days end of day'); } test.done(); }, 'calendar all else' : function (test) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); test.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); test.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); test.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); test.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); test.done(); }, // Monday is the first day of the week. // The week that contains Jan 4th is the first week of the year. 'weeks year starting sunday' : function (test) { test.equal(moment([2012, 0, 1]).week(), 52, 'Jan 1 2012 should be week 52'); test.equal(moment([2012, 0, 2]).week(), 1, 'Jan 2 2012 should be week 1'); test.equal(moment([2012, 0, 8]).week(), 1, 'Jan 8 2012 should be week 1'); test.equal(moment([2012, 0, 9]).week(), 2, 'Jan 9 2012 should be week 2'); test.equal(moment([2012, 0, 15]).week(), 2, 'Jan 15 2012 should be week 2'); test.done(); }, 'weeks year starting monday' : function (test) { test.equal(moment([2007, 0, 1]).week(), 1, 'Jan 1 2007 should be week 1'); test.equal(moment([2007, 0, 7]).week(), 1, 'Jan 7 2007 should be week 1'); test.equal(moment([2007, 0, 8]).week(), 2, 'Jan 8 2007 should be week 2'); test.equal(moment([2007, 0, 14]).week(), 2, 'Jan 14 2007 should be week 2'); test.equal(moment([2007, 0, 15]).week(), 3, 'Jan 15 2007 should be week 3'); test.done(); }, 'weeks year starting tuesday' : function (test) { test.equal(moment([2007, 11, 31]).week(), 1, 'Dec 31 2007 should be week 1'); test.equal(moment([2008, 0, 1]).week(), 1, 'Jan 1 2008 should be week 1'); test.equal(moment([2008, 0, 6]).week(), 1, 'Jan 6 2008 should be week 1'); test.equal(moment([2008, 0, 7]).week(), 2, 'Jan 7 2008 should be week 2'); test.equal(moment([2008, 0, 13]).week(), 2, 'Jan 13 2008 should be week 2'); test.equal(moment([2008, 0, 14]).week(), 3, 'Jan 14 2008 should be week 3'); test.done(); }, 'weeks year starting wednesday' : function (test) { test.equal(moment([2002, 11, 30]).week(), 1, 'Dec 30 2002 should be week 1'); test.equal(moment([2003, 0, 1]).week(), 1, 'Jan 1 2003 should be week 1'); test.equal(moment([2003, 0, 5]).week(), 1, 'Jan 5 2003 should be week 1'); test.equal(moment([2003, 0, 6]).week(), 2, 'Jan 6 2003 should be week 2'); test.equal(moment([2003, 0, 12]).week(), 2, 'Jan 12 2003 should be week 2'); test.equal(moment([2003, 0, 13]).week(), 3, 'Jan 13 2003 should be week 3'); test.done(); }, 'weeks year starting thursday' : function (test) { test.equal(moment([2008, 11, 29]).week(), 1, 'Dec 29 2008 should be week 1'); test.equal(moment([2009, 0, 1]).week(), 1, 'Jan 1 2009 should be week 1'); test.equal(moment([2009, 0, 4]).week(), 1, 'Jan 4 2009 should be week 1'); test.equal(moment([2009, 0, 5]).week(), 2, 'Jan 5 2009 should be week 2'); test.equal(moment([2009, 0, 11]).week(), 2, 'Jan 11 2009 should be week 2'); test.equal(moment([2009, 0, 13]).week(), 3, 'Jan 12 2009 should be week 3'); test.done(); }, 'weeks year starting friday' : function (test) { test.equal(moment([2009, 11, 28]).week(), 53, 'Dec 28 2009 should be week 53'); test.equal(moment([2010, 0, 1]).week(), 53, 'Jan 1 2010 should be week 53'); test.equal(moment([2010, 0, 3]).week(), 53, 'Jan 3 2010 should be week 53'); test.equal(moment([2010, 0, 4]).week(), 1, 'Jan 4 2010 should be week 1'); test.equal(moment([2010, 0, 10]).week(), 1, 'Jan 10 2010 should be week 1'); test.equal(moment([2010, 0, 11]).week(), 2, 'Jan 11 2010 should be week 2'); test.done(); }, 'weeks year starting saturday' : function (test) { test.equal(moment([2010, 11, 27]).week(), 52, 'Dec 27 2010 should be week 52'); test.equal(moment([2011, 0, 1]).week(), 52, 'Jan 1 2011 should be week 52'); test.equal(moment([2011, 0, 2]).week(), 52, 'Jan 2 2011 should be week 52'); test.equal(moment([2011, 0, 3]).week(), 1, 'Jan 3 2011 should be week 1'); test.equal(moment([2011, 0, 9]).week(), 1, 'Jan 9 2011 should be week 1'); test.equal(moment([2011, 0, 10]).week(), 2, 'Jan 10 2011 should be week 2'); test.done(); }, 'weeks year starting sunday formatted' : function (test) { test.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52.', 'Jan 1 2012 should be week 52'); test.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1.', 'Jan 2 2012 should be week 1'); test.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1.', 'Jan 8 2012 should be week 1'); test.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2.', 'Jan 9 2012 should be week 2'); test.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); test.done(); } };
module.exports = distTag var log = require('npmlog') var npa = require('npm-package-arg') var semver = require('semver') var npm = require('./npm.js') var mapToRegistry = require('./utils/map-to-registry.js') var readLocalPkg = require('./utils/read-local-package.js') var usage = require('./utils/usage') var output = require('./utils/output.js') distTag.usage = usage( 'dist-tag', 'npm dist-tag add <pkg>@<version> [<tag>]' + '\nnpm dist-tag rm <pkg> <tag>' + '\nnpm dist-tag ls [<pkg>]' ) distTag.completion = function (opts, cb) { var argv = opts.conf.argv.remain if (argv.length === 2) { return cb(null, ['add', 'rm', 'ls']) } switch (argv[2]) { default: return cb() } } function distTag (args, cb) { var cmd = args.shift() switch (cmd) { case 'add': case 'a': case 'set': case 's': return add(args[0], args[1], cb) case 'rm': case 'r': case 'del': case 'd': case 'remove': return remove(args[1], args[0], cb) case 'ls': case 'l': case 'sl': case 'list': return list(args[0], cb) default: return cb('Usage:\n' + distTag.usage) } } function add (spec, tag, cb) { var thing = npa(spec || '') var pkg = thing.name var version = thing.rawSpec var t = (tag || npm.config.get('tag')).trim() log.verbose('dist-tag add', t, 'to', pkg + '@' + version) if (!pkg || !version || !t) return cb('Usage:\n' + distTag.usage) if (semver.validRange(t)) { var er = new Error('Tag name must not be a valid SemVer range: ' + t) return cb(er) } fetchTags(pkg, function (er, tags) { if (er) return cb(er) if (tags[t] === version) { log.warn('dist-tag add', t, 'is already set to version', version) return cb() } tags[t] = version mapToRegistry(pkg, npm.config, function (er, uri, auth, base) { var params = { 'package': pkg, distTag: t, version: version, auth: auth } npm.registry.distTags.add(base, params, function (er) { if (er) return cb(er) output('+' + t + ': ' + pkg + '@' + version) cb() }) }) }) } function remove (tag, pkg, cb) { log.verbose('dist-tag del', tag, 'from', pkg) fetchTags(pkg, function (er, tags) { if (er) return cb(er) if (!tags[tag]) { log.info('dist-tag del', tag, 'is not a dist-tag on', pkg) return cb(new Error(tag + ' is not a dist-tag on ' + pkg)) } var version = tags[tag] delete tags[tag] mapToRegistry(pkg, npm.config, function (er, uri, auth, base) { var params = { 'package': pkg, distTag: tag, auth: auth } npm.registry.distTags.rm(base, params, function (er) { if (er) return cb(er) output('-' + tag + ': ' + pkg + '@' + version) cb() }) }) }) } function list (pkg, cb) { if (!pkg) { return readLocalPkg(function (er, pkg) { if (er) return cb(er) if (!pkg) return cb(distTag.usage) list(pkg, cb) }) } fetchTags(pkg, function (er, tags) { if (er) { log.error('dist-tag ls', "Couldn't get dist-tag data for", pkg) return cb(er) } var msg = Object.keys(tags).map(function (k) { return k + ': ' + tags[k] }).sort().join('\n') output(msg) cb(er, tags) }) } function fetchTags (pkg, cb) { mapToRegistry(pkg, npm.config, function (er, uri, auth, base) { if (er) return cb(er) var params = { 'package': pkg, auth: auth } npm.registry.distTags.fetch(base, params, function (er, tags) { if (er) return cb(er) if (!tags || !Object.keys(tags).length) { return cb(new Error('No dist-tags found for ' + pkg)) } cb(null, tags) }) }) }
(function (global, factory) { if (typeof define === "function" && define.amd) { define(["exports", "foo"], factory); } else if (typeof exports !== "undefined") { factory(exports, require("foo")); } else { var mod = { exports: {} }; factory(mod.exports, global.foo); global.actual = mod.exports; } })(this, function (exports, _foo) { "use strict"; var _foo2 = babelHelpers.interopRequireDefault(_foo); var _foo22 = babelHelpers.interopRequireDefault(_foo); _foo2["default"]; _foo22["default"]; });
/* Highcharts JS v5.0.9 (2017-03-08) Exporting module (c) 2010-2016 Torstein Honsi License: www.highcharts.com/license */ (function(h){"object"===typeof module&&module.exports?module.exports=h:h(Highcharts)})(function(h){(function(f){var h=f.defaultOptions,n=f.doc,A=f.Chart,u=f.addEvent,F=f.removeEvent,D=f.fireEvent,q=f.createElement,B=f.discardElement,v=f.css,p=f.merge,C=f.pick,k=f.each,r=f.extend,G=f.isTouchDevice,E=f.win,H=f.Renderer.prototype.symbols;r(h.lang,{printChart:"Print chart",downloadPNG:"Download PNG image",downloadJPEG:"Download JPEG image",downloadPDF:"Download PDF document",downloadSVG:"Download SVG vector image", contextButtonTitle:"Chart context menu"});h.navigation={buttonOptions:{theme:{},symbolSize:14,symbolX:12.5,symbolY:10.5,align:"right",buttonSpacing:3,height:22,verticalAlign:"top",width:24}};p(!0,h.navigation,{menuStyle:{border:"1px solid #999999",background:"#ffffff",padding:"5px 0"},menuItemStyle:{padding:"0.5em 1em",background:"none",color:"#333333",fontSize:G?"14px":"11px",transition:"background 250ms, color 250ms"},menuItemHoverStyle:{background:"#335cad",color:"#ffffff"},buttonOptions:{symbolFill:"#666666", symbolStroke:"#666666",symbolStrokeWidth:3,theme:{fill:"#ffffff",stroke:"none",padding:5}}});h.exporting={type:"image/png",url:"https://export.highcharts.com/",printMaxWidth:780,scale:2,buttons:{contextButton:{className:"highcharts-contextbutton",menuClassName:"highcharts-contextmenu",symbol:"menu",_titleKey:"contextButtonTitle",menuItems:[{textKey:"printChart",onclick:function(){this.print()}},{separator:!0},{textKey:"downloadPNG",onclick:function(){this.exportChart()}},{textKey:"downloadJPEG",onclick:function(){this.exportChart({type:"image/jpeg"})}}, {textKey:"downloadPDF",onclick:function(){this.exportChart({type:"application/pdf"})}},{textKey:"downloadSVG",onclick:function(){this.exportChart({type:"image/svg+xml"})}}]}}};f.post=function(a,c,e){var b;a=q("form",p({method:"post",action:a,enctype:"multipart/form-data"},e),{display:"none"},n.body);for(b in c)q("input",{type:"hidden",name:b,value:c[b]},null,a);a.submit();B(a)};r(A.prototype,{sanitizeSVG:function(a,c){if(c&&c.exporting&&c.exporting.allowHTML){var e=a.match(/<\/svg>(.*?$)/);e&&(e= '\x3cforeignObject x\x3d"0" y\x3d"0" width\x3d"'+c.chart.width+'" height\x3d"'+c.chart.height+'"\x3e\x3cbody xmlns\x3d"http://www.w3.org/1999/xhtml"\x3e'+e[1]+"\x3c/body\x3e\x3c/foreignObject\x3e",a=a.replace("\x3c/svg\x3e",e+"\x3c/svg\x3e"))}a=a.replace(/zIndex="[^"]+"/g,"").replace(/isShadow="[^"]+"/g,"").replace(/symbolName="[^"]+"/g,"").replace(/jQuery[0-9]+="[^"]+"/g,"").replace(/url\(("|&quot;)(\S+)("|&quot;)\)/g,"url($2)").replace(/url\([^#]+#/g,"url(#").replace(/<svg /,'\x3csvg xmlns:xlink\x3d"http://www.w3.org/1999/xlink" ').replace(/ (NS[0-9]+\:)?href=/g, " xlink:href\x3d").replace(/\n/," ").replace(/<\/svg>.*?$/,"\x3c/svg\x3e").replace(/(fill|stroke)="rgba\(([ 0-9]+,[ 0-9]+,[ 0-9]+),([ 0-9\.]+)\)"/g,'$1\x3d"rgb($2)" $1-opacity\x3d"$3"').replace(/&nbsp;/g,"\u00a0").replace(/&shy;/g,"\u00ad");return a=a.replace(/<IMG /g,"\x3cimage ").replace(/<(\/?)TITLE>/g,"\x3c$1title\x3e").replace(/height=([^" ]+)/g,'height\x3d"$1"').replace(/width=([^" ]+)/g,'width\x3d"$1"').replace(/hc-svg-href="([^"]+)">/g,'xlink:href\x3d"$1"/\x3e').replace(/ id=([^" >]+)/g,' id\x3d"$1"').replace(/class=([^" >]+)/g, 'class\x3d"$1"').replace(/ transform /g," ").replace(/:(path|rect)/g,"$1").replace(/style="([^"]+)"/g,function(a){return a.toLowerCase()})},getChartHTML:function(){return this.container.innerHTML},getSVG:function(a){var c,e,b,w,m,g=p(this.options,a);n.createElementNS||(n.createElementNS=function(a,c){return n.createElement(c)});e=q("div",null,{position:"absolute",top:"-9999em",width:this.chartWidth+"px",height:this.chartHeight+"px"},n.body);b=this.renderTo.style.width;m=this.renderTo.style.height; b=g.exporting.sourceWidth||g.chart.width||/px$/.test(b)&&parseInt(b,10)||600;m=g.exporting.sourceHeight||g.chart.height||/px$/.test(m)&&parseInt(m,10)||400;r(g.chart,{animation:!1,renderTo:e,forExport:!0,renderer:"SVGRenderer",width:b,height:m});g.exporting.enabled=!1;delete g.data;g.series=[];k(this.series,function(a){w=p(a.userOptions,{animation:!1,enableMouseTracking:!1,showCheckbox:!1,visible:a.visible});w.isInternal||g.series.push(w)});k(this.axes,function(a){a.userOptions.internalKey=f.uniqueKey()}); c=new f.Chart(g,this.callback);a&&k(["xAxis","yAxis","series"],function(b){var d={};a[b]&&(d[b]=a[b],c.update(d))});k(this.axes,function(a){var b=f.find(c.axes,function(b){return b.options.internalKey===a.userOptions.internalKey}),d=a.getExtremes(),e=d.userMin,d=d.userMax;!b||void 0===e&&void 0===d||b.setExtremes(e,d,!0,!1)});b=c.getChartHTML();b=this.sanitizeSVG(b,g);g=null;c.destroy();B(e);return b},getSVGForExport:function(a,c){var e=this.options.exporting;return this.getSVG(p({chart:{borderRadius:0}}, e.chartOptions,c,{exporting:{sourceWidth:a&&a.sourceWidth||e.sourceWidth,sourceHeight:a&&a.sourceHeight||e.sourceHeight}}))},exportChart:function(a,c){c=this.getSVGForExport(a,c);a=p(this.options.exporting,a);f.post(a.url,{filename:a.filename||"chart",type:a.type,width:a.width||0,scale:a.scale,svg:c},a.formAttributes)},print:function(){var a=this,c=a.container,e=[],b=c.parentNode,f=n.body,m=f.childNodes,g=a.options.exporting.printMaxWidth,d,t;if(!a.isPrinting){a.isPrinting=!0;a.pointer.reset(null, 0);D(a,"beforePrint");if(t=g&&a.chartWidth>g)d=[a.options.chart.width,void 0,!1],a.setSize(g,void 0,!1);k(m,function(a,b){1===a.nodeType&&(e[b]=a.style.display,a.style.display="none")});f.appendChild(c);E.focus();E.print();setTimeout(function(){b.appendChild(c);k(m,function(a,b){1===a.nodeType&&(a.style.display=e[b])});a.isPrinting=!1;t&&a.setSize.apply(a,d);D(a,"afterPrint")},1E3)}},contextMenu:function(a,c,e,b,f,m,g){var d=this,t=d.options.navigation,w=d.chartWidth,h=d.chartHeight,p="cache-"+a, l=d[p],x=Math.max(f,m),y,z;l||(d[p]=l=q("div",{className:a},{position:"absolute",zIndex:1E3,padding:x+"px"},d.container),y=q("div",{className:"highcharts-menu"},null,l),v(y,r({MozBoxShadow:"3px 3px 10px #888",WebkitBoxShadow:"3px 3px 10px #888",boxShadow:"3px 3px 10px #888"},t.menuStyle)),z=function(){v(l,{display:"none"});g&&g.setState(0);d.openMenu=!1},u(l,"mouseleave",function(){l.hideTimer=setTimeout(z,500)}),u(l,"mouseenter",function(){clearTimeout(l.hideTimer)}),p=u(n,"mouseup",function(b){d.pointer.inClass(b.target, a)||z()}),u(d,"destroy",p),k(c,function(a){if(a){var b;a.separator?b=q("hr",null,null,y):(b=q("div",{className:"highcharts-menu-item",onclick:function(b){b&&b.stopPropagation();z();a.onclick&&a.onclick.apply(d,arguments)},innerHTML:a.text||d.options.lang[a.textKey]},null,y),b.onmouseover=function(){v(this,t.menuItemHoverStyle)},b.onmouseout=function(){v(this,t.menuItemStyle)},v(b,r({cursor:"pointer"},t.menuItemStyle)));d.exportDivElements.push(b)}}),d.exportDivElements.push(y,l),d.exportMenuWidth= l.offsetWidth,d.exportMenuHeight=l.offsetHeight);c={display:"block"};e+d.exportMenuWidth>w?c.right=w-e-f-x+"px":c.left=e-x+"px";b+m+d.exportMenuHeight>h&&"top"!==g.alignOptions.verticalAlign?c.bottom=h-b-x+"px":c.top=b+m-x+"px";v(l,c);d.openMenu=!0},addButton:function(a){var c=this,e=c.renderer,b=p(c.options.navigation.buttonOptions,a),f=b.onclick,m=b.menuItems,g,d,h=b.symbolSize||12;c.btnCount||(c.btnCount=0);c.exportDivElements||(c.exportDivElements=[],c.exportSVGElements=[]);if(!1!==b.enabled){var k= b.theme,n=k.states,q=n&&n.hover,n=n&&n.select,l;delete k.states;f?l=function(a){a.stopPropagation();f.call(c,a)}:m&&(l=function(){c.contextMenu(d.menuClassName,m,d.translateX,d.translateY,d.width,d.height,d);d.setState(2)});b.text&&b.symbol?k.paddingLeft=C(k.paddingLeft,25):b.text||r(k,{width:b.width,height:b.height,padding:0});d=e.button(b.text,0,0,l,k,q,n).addClass(a.className).attr({"stroke-linecap":"round",title:c.options.lang[b._titleKey],zIndex:3});d.menuClassName=a.menuClassName||"highcharts-menu-"+ c.btnCount++;b.symbol&&(g=e.symbol(b.symbol,b.symbolX-h/2,b.symbolY-h/2,h,h).addClass("highcharts-button-symbol").attr({zIndex:1}).add(d),g.attr({stroke:b.symbolStroke,fill:b.symbolFill,"stroke-width":b.symbolStrokeWidth||1}));d.add().align(r(b,{width:d.width,x:C(b.x,c.buttonOffset)}),!0,"spacingBox");c.buttonOffset+=(d.width+b.buttonSpacing)*("right"===b.align?-1:1);c.exportSVGElements.push(d,g)}},destroyExport:function(a){var c=a?a.target:this;a=c.exportSVGElements;var e=c.exportDivElements;a&& (k(a,function(a,e){a&&(a.onclick=a.ontouchstart=null,c.exportSVGElements[e]=a.destroy())}),a.length=0);e&&(k(e,function(a,e){clearTimeout(a.hideTimer);F(a,"mouseleave");c.exportDivElements[e]=a.onmouseout=a.onmouseover=a.ontouchstart=a.onclick=null;B(a)}),e.length=0)}});H.menu=function(a,c,e,b){return["M",a,c+2.5,"L",a+e,c+2.5,"M",a,c+b/2+.5,"L",a+e,c+b/2+.5,"M",a,c+b-1.5,"L",a+e,c+b-1.5]};A.prototype.renderExporting=function(){var a,c=this.options.exporting,e=c.buttons,b=this.isDirtyExporting||!this.exportSVGElements; this.buttonOffset=0;this.isDirtyExporting&&this.destroyExport();if(b&&!1!==c.enabled){for(a in e)this.addButton(e[a]);this.isDirtyExporting=!1}u(this,"destroy",this.destroyExport)};A.prototype.callbacks.push(function(a){a.renderExporting();u(a,"redraw",a.renderExporting);k(["exporting","navigation"],function(c){a[c]={update:function(e,b){a.isDirtyExporting=!0;p(!0,a.options[c],e);C(b,!0)&&a.redraw()}}})})})(h)});